<commit_before>/*
Author: Oliver Steele
Copyright: Copyright 2006 Oliver Steele.  All rights reserved.
Homepage: http://osteele.com/sources/openlaszlo/json
License: MIT License.
Version: 1.0

== JSON.stringify
function JSON.stringify(value, [options]);

Usage:
  JSON.stringify(123) // => '123'
  JSON.stringify([1,2,3]) // => '[1,2,3]'
  JSON.stringify({a:1,b:2}) // => '{"a":1,"b":2}'

== JSON.parse
function JSON.parse(string, [options]);

Parses the first JSON expression from +string+.  If
+options.allowSuffix+ is not specified (the default), the expression
must span the string or the parse produces an error.

Errors are signalled by returning undefined, and optionally invoking
+options.errorHandler+ (see below).

Usage:
  JSON.parse('123') // => 123
  JSON.parse('[1,2,3]') // => [1,2,3]
  JSON.parse('{"a":1,"b":2}') // => {a: 1, b: 2}
  JSON.parse('[') // => undefined (parse error)

+options+ can contain these properties:
* allowSuffix: allow text to follow the expression.  This can be
  used to pack multiple JSON expressions into a single string.
+ startIndex: the index into the string to begin parsing.  This is
  useful in conjunction with allowSuffix.
* errorHandler: function (message: string, index: number): void
  If an error occurs, the errorHandler is invoked with two arguments:
  an error string and a character offset.

=== Notes
JSON.parse accepts these strings don't conform to the JSON grammar:
* '1.e1' -- JSON requires digits after the decimal point
* '01' -- JSON doesn't permit leading zeros.
* '"\a"' -- JSON doesn't permit nonescape characters to be encoded

The parser does not accept unquoted object property names such as {a:
1}.  These are valid JavaScript (when the property name is a valid
identifier), but they are not in the JSON grammar.
*/

/*
Implementation notes:
* use for(;;) instead of for(in) where order matters, since Flash
  iterates backwards.
* test with obj[n] instead of obj.n, to avoid debugger warnings
 */

var JSON = {};

JSON.stringify = function (value) {
    var generator = new JSON.generator();
    return generator.generate(value);
};

JSON.parse = function (str, options) {
    var parser = new JSON.parser();
    if (arguments.length > 1)
        parser.setOptions(options);
    return parser.parse(str);
};

JSON.HEXDIGITS = "0123456789abcdef";

JSON.generator = function () {};

JSON.generator.CHARACTER_QUOTES = {
    '\\': '\\\\',
    '\"': '\\\"',
    '\b': '\\b',
    '\f': '\\f',
    '\n': '\\n',
    '\r': '\\r',
    '\t': '\\t'
};

JSON.generator.prototype.primitiveExceptions = {
	'NaN': 'null',
	'Infinity': 'null',
	'-Infinity': 'null'
};

JSON.generator.prototype.generate = function (value, options) {
    this.segments = [];
    this.appendValue(value);
    return this.segments.join('');
};

JSON.generator.prototype.appendValue = function (value) {
    switch (typeof value) {
    case 'string':
        this.appendString(value);
        break;
    case 'object':
        this.findObjectAppender(value).apply(this, [value]);
        break;
    default:
        this.appendPrimitive(value);
    }
};

JSON.generator.prototype.appendPrimitive = function (v) {
    var s = String(v);
    if (this.primitiveExceptions[s])
        s = this.primitiveExceptions[s];
    this.segments.push(s);
};

JSON.generator.prototype.appendString = function (string) {
    var segments = this.segments;
    var escapes = JSON.generator.CHARACTER_QUOTES;
    var start = 0;
    var i = 0;
    segments.push('"');
    while (i < string.length) {
        var c = string.charAt(i++);
        if (escapes[c]) {
            if (i-1 > start)
                segments.push(string.slice(start, i-1));
            segments.push(escapes[c]);
            start = i;
        } else if (c < ' ' || c > '~') {
			var n = c.charCodeAt(0);
			segments.push('\\u');
			for (var shift = 16; (shift -= 4) >= 0; )
				segments.push(JSON.HEXDIGITS.charAt((n >> shift) & 15));
			start = i;
		} // else collect into current segment
    }
    if (i > start)
        segments.push(string.slice(start, i));
    segments.push('"');
};

// This implements an ordered hash --- ordered, so that Object comes
// last
JSON.generator.prototype.objectAppenders = [
    // treat the Object types that correspond to primitives as though
    // they were the corresponding primitives, so that, for example,
    // {true, new Boolean(true)}, {true, new Boolean(true)}, and {'a',
    // new String('a')} are all equivalence classes for stringifying
    [Boolean, JSON.generator.prototype.appendPrimitive],
    [Number, JSON.generator.prototype.appendPrimitive],
    [String, JSON.generator.prototype.appendString],
    [Array, function (ar) {
        var segments = this.segments;
        segments.push("[");
        for (var i = 0; i < ar.length; i++) {
            if (i > 0) segments.push(",");
            this.appendValue(ar[i]);
        }
        segments.push("]");
    }],
    // This must come last, since it's a superclass
    [Object, function (object) {
        var segments = this.segments;
        segments.push("{");
        var count = 0;
        for (var key in object) {
            if (count++) segments.push(",");
            this.appendValue(key);
            segments.push(":");
            this.appendValue(object[key]);
        }
        segments.push("}");
    }]];

JSON.generator.prototype.findObjectAppender = function (object) {
    if (object == null)
        return function (object) {this.segments.push("null")};
    for (var i = 0; i < this.objectAppenders.length; i++) {
        var entry = this.objectAppenders[i];
        if (object instanceof entry[0])
            return entry[1];
    }
    // program error
};

JSON.parser = function () {
    this.errorHandler = null;
};

JSON.parser.WHITESPACE = " \t\n\r\f";

JSON.parser.CHARACTER_UNQUOTES = {
    'b': '\b',
    'f': '\f',
    'n': '\n',
    'r': '\r',
    't': '\t'
};

JSON.parser.prototype.setOptions = function (options) {
	if (options['errorHandler'])
		this.errorHandler = options.errorHandler;
};

JSON.parser.prototype.parse = function (str) {
    this.string = str;
    this.index = 0;
	this.message = null;
    var value = this.readValue();
	if (!this.message && this.next())
		value = this.error("extra characters at the end of the string");
    if (this.message && this.errorHandler)
        this.errorHandler(this.message, this.index);
    return value;
};

JSON.parser.prototype.error = function (message) {
	this.message = message;
	return undefined;
}

JSON.parser.prototype.readValue = function () {
    var c = this.next();
    var fn = c && this.table[c];
    if (fn)
        return fn.apply(this);
    var keywords = {'true': true, 'false': false, 'null': null};
    var s = this.string;
    var i = this.index-1;
    for (var w in keywords) {
        if (s.slice(i, i+w.length) == w) {
            this.index = i+w.length;
            return keywords[w];
        }
    }
    if (c) return this.error("invalid character: '" + c + "'");
	return this.error("empty expression");
}

JSON.parser.prototype.table = {
    '{': function () {
        var o = {};
        var c;
		var count = 0;
        while ((c = this.next()) != '}') {
            if (count) {
				if (c != ',')
					this.error("missing ','");
			} else if (c == ',') {
				return this.error("extra ','");
			} else
				--this.index;
            var k = this.readValue();
            if (typeof k == "undefined") return undefined;
            if (this.next() != ':') return this.error("missing ':'");
            var v = this.readValue();
            if (typeof v == "undefined") return undefined;
            o[k] = v;
			count++;
        }
        return o;
    },
    '[': function () {
        var ar = [];
        var c;
        while ((c = this.next()) != ']') {
            if (!c) return this.error("unmatched '['");
            if (ar.length) {
				if (c != ',')
					this.error("missing ','");
			} else if (c == ',') {
				return this.error("extra ','");
			} else
				--this.index;
            var n = this.readValue();
            if (typeof n == "undefined") return undefined;
            ar.push(n);
        }
        return ar;
    },
    '"': function () {
        var s = this.string;
        var i = this.index;
        var start = i;
        var segments = [];
        var c;
        while ((c = s.charAt(i++)) != '"') {
            //if (i == s.length) return this.error("unmatched '\"'");
			if (!c) return this.error("umatched '\"'");
            if (c == '\\') {
                if (start < i-1)
                    segments.push(s.slice(start, i-1));
                c = s.charAt(i++);
				if (c == 'u') {
					var code = 0;
					start = i;
					while (i < start+4) {
						c = s.charAt(i++);
						var n = JSON.HEXDIGITS.indexOf(c.toLowerCase());
						if (n < 0) return this.error("invalid unicode digit: '"+c+"'");
						code = code * 16 + n;
					}
					segments.push(String.fromCharCode(code));
				} else
					segments.push(JSON.parser.CHARACTER_UNQUOTES[c] || c);
                start = i;
            }
        }
        if (start < i-1)
            segments.push(s.slice(start, i-1));
        this.index = i;
        return segments.length == 1 ? segments[0] : segments.join('');
    },
	// Also any digit.  The statement that follows this table
	// definition fills in the digits.
    '-': function () {
        var s = this.string;
        var i = this.index;
        var start = i-1;
        var state = 'int';
        var permittedSigns = '-';
        var transitions = {
            'int+.': 'frac',
            'int+e': 'exp',
            'frac+e': 'exp'
        };
        do {
            var c = s.charAt(i++);
			if (!c) break;
            if ('0' <= c && c <= '9') continue;
            if (permittedSigns.indexOf(c) >= 0) {
                permittedSigns = '';
                continue;
            }
            state = transitions[state+'+'+c.toLowerCase()];
            if (state == 'exp') permittedSigns = '+-';
        } while (state);
        this.index = --i;
		s = s.slice(start, i)
		if (s == '-') return this.error("invalid number");
        return Number(s);
    }
};
// copy table['_'] to each of table[i] | i <- '0'..'9':
(function (table) {
    for (var i = 0; i <= 9; i++)
        table[String(i)] = table['-'];
})(JSON.parser.prototype.table);

// return the next non-whitespace character, or undefined
JSON.parser.prototype.next = function () {
    var s = this.string;
    var i = this.index;
    do {
        if (i == s.length) return undefined;
        var c = s.charAt(i++);
    } while (JSON.parser.WHITESPACE.indexOf(c) >= 0);
    this.index = i;
    return c;
};
<commit_msg>JSON now encodes NaN, undefined as null<commit_after>/*
Author: Oliver Steele
Copyright: Copyright 2006 Oliver Steele.  All rights reserved.
Homepage: http://osteele.com/sources/openlaszlo/json
License: MIT License.
Version: 1.1

== JSON.stringify
function JSON.stringify(value, [options]);

Usage:
  JSON.stringify(123) // => '123'
  JSON.stringify([1,2,3]) // => '[1,2,3]'
  JSON.stringify({a:1,b:2}) // => '{"a":1,"b":2}'

== JSON.parse
function JSON.parse(string, [options]);

Parses the first JSON expression from +string+.  If
+options.allowSuffix+ is not specified (the default), the expression
must span the string or the parse produces an error.

Errors are signalled by returning undefined, and optionally invoking
+options.errorHandler+ (see below).

Usage:
  JSON.parse('123') // => 123
  JSON.parse('[1,2,3]') // => [1,2,3]
  JSON.parse('{"a":1,"b":2}') // => {a: 1, b: 2}
  JSON.parse('[') // => undefined (parse error)

+options+ can contain these properties:
* allowSuffix: allow text to follow the expression.  This can be
  used to pack multiple JSON expressions into a single string.
+ startIndex: the index into the string to begin parsing.  This is
  useful in conjunction with allowSuffix.
* errorHandler: function (message: string, index: number): void
  If an error occurs, the errorHandler is invoked with two arguments:
  an error string and a character offset.

=== Notes
JSON.parse accepts these strings which don't conform to the JSON grammar:
* '1.e1' -- JSON requires digits after the decimal point
* '01'   -- JSON doesn't permit leading zeros.
* '"\a"' -- JSON doesn't permit nonescape characters to be encoded

The parser does not accept unquoted object property names such as {a:1}.
These are valid JavaScript (when the property name is a valid
identifier), but they are not in the JSON grammar.
*/

/*
Implementation notes:
* use for(;;) instead of for(in) where order matters, since Flash
  iterates backwards.
* test with obj[n] instead of obj.n, to avoid debugger warnings
 */

var JSON = {};

JSON.stringify = function (value) {
    var generator = new JSON.generator();
    return generator.generate(value);
};

JSON.parse = function (str, options) {
    var parser = new JSON.parser();
    if (arguments.length > 1)
        parser.setOptions(options);
    return parser.parse(str);
};

JSON.HEXDIGITS = "0123456789abcdef";

JSON.generator = function () {};

JSON.generator.CHARACTER_QUOTES = {
    '\\': '\\\\',
    '\"': '\\\"',
    '\b': '\\b',
    '\f': '\\f',
    '\n': '\\n',
    '\r': '\\r',
    '\t': '\\t'
};

JSON.generator.prototype.primitiveExceptions = {
    'undefined': 'null',
    'NaN': 'null',
    'Infinity': 'null',
    '-Infinity': 'null'
};

JSON.generator.prototype.generate = function (value, options) {
    this.segments = [];
    this.appendValue(value);
    return this.segments.join('');
};

JSON.generator.prototype.appendValue = function (value) {
    switch (typeof value) {
    case 'string':
        this.appendString(value);
        break;
    case 'null':
        this.segments.push('null');
    case 'object':
        this.findObjectAppender(value).call(this, value);
        break;
    default:
        this.appendPrimitive(value);
    }
};

JSON.generator.prototype.appendPrimitive = function (v) {
    var s = String(v),
        exceptions = this.primitiveExceptions;
    if (exceptions[s])
        s = exceptions[s];
    this.segments.push(s);
};

JSON.generator.prototype.appendString = function (string) {
    var segments = this.segments,
        escapes = JSON.generator.CHARACTER_QUOTES,
        start = 0,
        i = 0,
        len = string.length;
    segments.push('"');
    while (i < len) {
        var c = string.charAt(i++),
            escape = escapes[c];
        if (escape) {
            if (i-1 > start)
                segments.push(string.slice(start, i-1));
            segments.push(escape);
            start = i;
        } else if (c < ' ' || c > '~') {
            var n = c.charCodeAt(0);
            segments.push('\\u');
            for (var shift = 16; (shift -= 4) >= 0; )
                segments.push(JSON.HEXDIGITS.charAt((n >> shift) & 15));
            start = i;
        } // else collect into current segment
    }
    if (i > start)
        segments.push(string.slice(start, i));
    segments.push('"');
};

// This implements an ordered hash --- ordered, so that Object comes
// last
JSON.generator.prototype.objectAppenders = [
    // treat the Object types that correspond to primitives as though
    // they were the corresponding primitives, so that, for example,
    // {true, new Boolean(true)}, {true, new Boolean(true)}, and {'a',
    // new String('a')} are all equivalence classes for stringifying
    [Boolean, JSON.generator.prototype.appendPrimitive],
    [Number, JSON.generator.prototype.appendPrimitive],
    [String, JSON.generator.prototype.appendString],
    [Array, function (ar) {
        var segments = this.segments;
        segments.push("[");
        for (var i = 0, len = ar.length; i < length; i++) {
            if (i > 0) segments.push(",");
            this.appendValue(ar[i]);
        }
        segments.push("]");
    }],
    // This must come last, since it's a superclass of the classes
    // above
    [Object, function (object) {
        var segments = this.segments;
        segments.push("{");
        var count = 0;
        for (var key in object) {
            if (count++) segments.push(",");
            this.appendValue(key);
            segments.push(":");
            this.appendValue(object[key]);
        }
        segments.push("}");
    }]];

JSON.generator.prototype.findObjectAppender = function (object) {
    var appenders = this.objectAppenders,
        len = appenders.length;
    for (var i = 0; i < len; i++) {
        var entry = appenders[i];
        if (object instanceof entry[0])
            return entry[1];
    }
    // program error
};

JSON.parser = function () {
    this.errorHandler = null;
};

JSON.parser.WHITESPACE = " \t\n\r\f";

JSON.parser.CHARACTER_UNQUOTES = {
    'b': '\b',
    'f': '\f',
    'n': '\n',
    'r': '\r',
    't': '\t'
};

JSON.parser.prototype.setOptions = function (options) {
    if (options['errorHandler'])
        this.errorHandler = options.errorHandler;
};

JSON.parser.prototype.parse = function (str) {
    this.string = str;
    this.index = 0;
    this.message = null;
    var value = this.readValue();
    if (!this.message && this.next())
        value = this.error("extra characters at the end of the string");
    if (this.message && this.errorHandler)
        this.errorHandler(this.message, this.index);
    return value;
};

JSON.parser.prototype.error = function (message) {
    this.message = message;
    return undefined;
}

JSON.parser.prototype.readValue = function () {
    var c = this.next();
    var fn = c && this.table[c];
    if (fn)
        return fn.apply(this);
    var keywords = {'true': true, 'false': false, 'null': null};
    var s = this.string;
    var i = this.index-1;
    for (var w in keywords) {
        if (s.slice(i, i+w.length) == w) {
            this.index = i+w.length;
            return keywords[w];
        }
    }
    if (c) return this.error("invalid character: '" + c + "'");
    return this.error("empty expression");
}

JSON.parser.prototype.table = {
    '{': function () {
        var o = {};
        var c;
        var count = 0;
        while ((c = this.next()) != '}') {
            if (count) {
                if (c != ',')
                    this.error("missing ','");
            } else if (c == ',') {
                return this.error("extra ','");
            } else
                --this.index;
            var k = this.readValue();
            if (typeof k == "undefined") return undefined;
            if (this.next() != ':') return this.error("missing ':'");
            var v = this.readValue();
            if (typeof v == "undefined") return undefined;
            o[k] = v;
            count++;
        }
        return o;
    },
    '[': function () {
        var ar = [];
        var c;
        while ((c = this.next()) != ']') {
            if (!c) return this.error("unmatched '['");
            if (ar.length) {
                if (c != ',')
                    this.error("missing ','");
            } else if (c == ',') {
                return this.error("extra ','");
            } else
                --this.index;
            var n = this.readValue();
            if (typeof n == "undefined") return undefined;
            ar.push(n);
        }
        return ar;
    },
    '"': function () {
        var s = this.string;
        var i = this.index;
        var start = i;
        var segments = [];
        var c;
        while ((c = s.charAt(i++)) != '"') {
            //if (i == s.length) return this.error("unmatched '\"'");
            if (!c) return this.error("umatched '\"'");
            if (c == '\\') {
                if (start < i-1)
                    segments.push(s.slice(start, i-1));
                c = s.charAt(i++);
                if (c == 'u') {
                    var code = 0;
                    start = i;
                    while (i < start+4) {
                        c = s.charAt(i++);
                        var n = JSON.HEXDIGITS.indexOf(c.toLowerCase());
                        if (n < 0) return this.error("invalid unicode digit: '"+c+"'");
                        code = code * 16 + n;
                    }
                    segments.push(String.fromCharCode(code));
                } else
                    segments.push(JSON.parser.CHARACTER_UNQUOTES[c] || c);
                start = i;
            }
        }
        if (start < i-1)
            segments.push(s.slice(start, i-1));
        this.index = i;
        return segments.length == 1 ? segments[0] : segments.join('');
    },
    // Also any digit.  The statement that follows this table
    // definition fills in the digits.
    '-': function () {
        var s = this.string;
        var i = this.index;
        var start = i-1;
        var state = 'int';
        var permittedSigns = '-';
        var transitions = {
            'int+.': 'frac',
            'int+e': 'exp',
            'frac+e': 'exp'
        };
        do {
            var c = s.charAt(i++);
            if (!c) break;
            if ('0' <= c && c <= '9') continue;
            if (permittedSigns.indexOf(c) >= 0) {
                permittedSigns = '';
                continue;
            }
            state = transitions[state+'+'+c.toLowerCase()];
            if (state == 'exp') permittedSigns = '+-';
        } while (state);
        this.index = --i;
        s = s.slice(start, i)
        if (s == '-') return this.error("invalid number");
        return Number(s);
    }
};
// copy table['_'] to each of table[i] | i <- '0'..'9':
(function (table) {
    for (var i = 0; i <= 9; i++)
        table[String(i)] = table['-'];
})(JSON.parser.prototype.table);

// return the next non-whitespace character, or undefined
JSON.parser.prototype.next = function () {
    var s = this.string;
    var i = this.index;
    do {
        if (i == s.length) return undefined;
        var c = s.charAt(i++);
    } while (JSON.parser.WHITESPACE.indexOf(c) >= 0);
    this.index = i;
    return c;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

require("proof")(1, function (equal) {
  var exports = {}, modeler = require("../../modeler").createModeler(exports), called = 0;
  modeler.dynamic("watchers", function (broker, callback) { called++ });
  exports._namespace.watchers.callback();
  equal(called, 1, "constructed");
});
<commit_msg>Deleted Modeler.<commit_after><|endoftext|>


<commit_before>/*
	--------------- jSQL ---------------
	a SQL like database using javascript
	website: http://jsql.injs.org
	licence: MIT Licence
	version: 0.1.1 dev

	description: using jSQL to process the data easily.
*/

(function() {
	var push             = Array.prototype.push,
		slice            = Array.prototype.slice,
		unshift          = Array.prototype.unshift,
		toString         = Object.prototype.toString,
		hasOwnProperty   = Object.prototype.hasOwnProperty;

	var nativeForEach      = Array.prototype.forEach,
		nativeMap          = Array.prototype.map,
		nativeReduce       = Array.prototype.reduce,
		nativeReduceRight  = Array.prototype.reduceRight,
		nativeFilter       = Array.prototype.filter,
		nativeEvery        = Array.prototype.every,
		nativeSome         = Array.prototype.some,
		nativeIndexOf      = Array.prototype.indexOf,
		nativeLastIndexOf  = Array.prototype.lastIndexOf,
		nativeIsArray      = Array.isArray,
		nativeKeys         = Object.keys,
		nativeBind         = Function.prototype.bind;

	var _jSQL, jSQL, _DB = {};

	if(typeof(this.jSQL) !== 'undefined') {
		_jSQL = this.jSQL;
	}

	jSQL = function() {
		this.init.apply(this,arguments);
	};

	jSQL.prototype = {
		init: function() {
			this._jSQL = _jSQL;
			this._DB = _DB;
			this._currentDB = null;
			this._buffer = null;
		},

		/**
		* create a new database
		* @param dbname [String]
		* @param db [Object]
		*/

		create: function(dbname, db) {
			if(this._DB.hasOwnProperty(dbname)) {
				throw('DB Already Exist.');
			}

			this._DB[dbname] = db;
			return this;
		},

		/**
		* select an exist database as current
		* @param dbname [String]
		*/

		use: function(dbname) {
			if(!this._DB.hasOwnProperty(dbname)) {
				throw('Database Not Exist.');
			}

			this._currentDB = this._DB[dbname];
			return this;
		},

		/**
		* drop an exist database
		* @param dbname [String]
		*/

		drop: function(dbname) {
			if(this._DB.hasOwnProperty(dbname)) {
				delete this._DB[dbname];
			}
		},

		/**
		* select object from currentDB
		* @param key
			'*':	 return all
			'a':	 return base value which key is 'a'
			'a.b.c': return deep value a->b->c
		*
		*/

		select: function(key) {
			if(!this._currentDB) {
				throw('Please Select Database First.');
			}

			this._buffer = this._currentDB; //reset the _buffer

			if(key==='*') {
				return this;
			}

			this.where(function(data) {
				return typeof(this._deep(data, key)) !== 'undefined';
			});

			return this;
		},

		/**
		* get the count of current result set
		*/

		count: function() {
			return this._objectToArray(this._buffer).length;
		},

		/**
         * calculate the count of spec key
         * @param key
                '*':     return first package key count
			    'a':	 return base value which key is 'a'
			    'a.b.c': return deep value a->b->c
         *
         * @use [jSQL instance].total('a.b.c')
         */
		total: function(key) {
		    var rs = 0, scope = key.split('.');
            if(key === '*')
            this._buffer = this._currentDB;
            for(var key in this._currentDB) {
                if (this._currentDB.hasOwnProperty(key)) {
                    var tmp = this._currentDB[key];
                    for(var i=0,j=0; i<(j=scope.length); i++) {
                        tmp = tmp[scope[i]];
                        if(!!tmp && i == j - 1) rs++;
                    }
                }
            }

            return rs;
		},

		/**
		* sort the current result set
		* @param field [String]
		* @param callback [function]
		* @param order [String <asc | desc>]
		*/

		orderby: function(field, callback, order) {
			var _array = this._objectToArray(this._buffer);
			var _this = this;

			if(typeof(callback) !== 'function') {
				callback = [order, order = callback][0];
			}

			_array.sort(function(a, b) {
				a = _this._deep(a, field);
				b = _this._deep(b, field);
				if(callback) {
					a = callback(a);
					b = callback(b);
				}
				return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
			});

			this._buffer = this._arrayToObject(_array);
			return this;
		},

		where: function(fn) {
			var _tmp = {}, _swap;
			this._buffer = this._buffer || this._currentDB;

			for(var i in this._buffer) {
				if(this._buffer.hasOwnProperty(i)) {
					_swap = fn.call(this, this._buffer[i], i);

					if(_swap) {
						_tmp[i] = this._buffer[i];
					}
				}
			}
			this._buffer = _tmp;
			return this;
		},

		iterate: function(fn) {
			var _swap;
			this._buffer = this._buffer || this._currentDB;

			for(var i in this._buffer) {
				if(this._buffer.hasOwnProperty(i)) {
					_swap = fn.call(this, this._buffer[i]);

					if(_swap) {
						this.update(i, _swap);
					}
				}
			}
		},

		/**
		* return the current result set
		* @return [Object]
		*/

		findAll: function() {
			return this._buffer;
		},

		/**
		* return a specified item of current result set
		* if the key doesn't given, it'll return the first item
		* @return [Object]
		*/

		find: function(key) {
			if(!key) {
				for(var i in this._buffer) {
					if(key) {
						break;
					}

					if(this._buffer.hasOwnProperty(i)) {
						key = i;
					}
				}
			}

			return this._buffer[key];
		},

		/**
		* return the current result set as array list
		* @return [Object]
		*/

		listAll: function() {
			return this._objectToArray(this._buffer);
		},

		/**
		* update the current result set
		* @param key [String]
		* @param data [Object]
		*/

		update: function(key, data) {
			if(!this._currentDB) {
				throw('Please Select Database First.');
			}

			if(this._currentDB.hasOwnProperty(key)) {
				this._currentDB[key] = data;
			}
		},

		/**
		* limie the current result set
		* @param start [Number]
		* @param end [Number]
		*/

		limit: function(start, end) {
			var _tmp = this._objectToArray(this._buffer);

			if(!end) {
				start = [0, end = start][0];
			}

			this._buffer = this._arrayToObject(_tmp);
		},

		/**
		* private methods
		*/

		_deep: function(data, scope) {
			var _tmp = data, scope = scope.split('.');
			for(var i = 0; i < scope.length; i++) {
				_tmp = _tmp[scope[i]];
			}
			return _tmp;
		},

		_isArray: nativeIsArray || function(obj) {
			return toString.call(obj) === '[object Array]';
		},

		_isObject: function(obj) {
			return obj === Object(obj);
		},

		_clone: function(obj) {
			var _tmp = {};

			if (!this._isObject(obj)) return obj;
			if(this._isArray(obj)) return obj.slice();

			for(var i in obj) {
				if(obj.hasOwnProperty(i)) {
					_tmp[i] = obj[i];
				}
			}
			return _tmp;
		},

		_objectToArray: function(object) {
			var array = [], object = this._clone(object);

			for(var i in object) {
				if(object.hasOwnProperty(i)) {
					object[i].__jSQL_Key = i;
					array.push(object[i]);
				}
			}

			return array;
		},

		_arrayToObject: function(array, key) {
			var object = {};

			for(var i = 0; i < array.length; i++) {
				object[array[i][key || '__jSQL_Key']] = array[i];
				delete object[array[i][key || '__jSQL_Key']][key || '__jSQL_Key'];
			};

			return object;
		}
	};

	typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jSQL = jSQL;
})();<commit_msg>recommit<commit_after>/*
	--------------- jSQL ---------------
	a SQL like database using javascript
	website: http://jsql.injs.org
	licence: MIT Licence
	version: 0.1.1 dev

	description: using jSQL to process the data easily.
*/

(function() {
	var push             = Array.prototype.push,
		slice            = Array.prototype.slice,
		unshift          = Array.prototype.unshift,
		toString         = Object.prototype.toString,
		hasOwnProperty   = Object.prototype.hasOwnProperty;

	var nativeForEach      = Array.prototype.forEach,
		nativeMap          = Array.prototype.map,
		nativeReduce       = Array.prototype.reduce,
		nativeReduceRight  = Array.prototype.reduceRight,
		nativeFilter       = Array.prototype.filter,
		nativeEvery        = Array.prototype.every,
		nativeSome         = Array.prototype.some,
		nativeIndexOf      = Array.prototype.indexOf,
		nativeLastIndexOf  = Array.prototype.lastIndexOf,
		nativeIsArray      = Array.isArray,
		nativeKeys         = Object.keys,
		nativeBind         = Function.prototype.bind;

	var _jSQL, jSQL, _DB = {};

	if(typeof(this.jSQL) !== 'undefined') {
		_jSQL = this.jSQL;
	}

	jSQL = function() {
		this.init.apply(this,arguments);
	};

	jSQL.prototype = {
		init: function() {
			this._jSQL = _jSQL;
			this._DB = _DB;
			this._currentDB = null;
			this._buffer = null;
		},

		/**
		* create a new database
		* @param dbname [String]
		* @param db [Object]
		*/

		create: function(dbname, db) {
			if(this._DB.hasOwnProperty(dbname)) {
				throw('DB Already Exist.');
			}

			this._DB[dbname] = db;
			return this;
		},

		/**
		* select an exist database as current
		* @param dbname [String]
		*/

		use: function(dbname) {
			if(!this._DB.hasOwnProperty(dbname)) {
				throw('Database Not Exist.');
			}

			this._currentDB = this._DB[dbname];
			return this;
		},

		/**
		* drop an exist database
		* @param dbname [String]
		*/

		drop: function(dbname) {
			if(this._DB.hasOwnProperty(dbname)) {
				delete this._DB[dbname];
			}
		},

		/**
		* select object from currentDB
		* @param key
			'*':	 return all
			'a':	 return base value which key is 'a'
			'a.b.c': return deep value a->b->c
		*
		*/

		select: function(key) {
			if(!this._currentDB) {
				throw('Please Select Database First.');
			}

			this._buffer = this._currentDB; //reset the _buffer

			if(key==='*') {
				return this;
			}

			this.where(function(data) {
				return typeof(this._deep(data, key)) !== 'undefined';
			});

			return this;
		},

		/**
		* get the count of current result set
		*/

		count: function() {
			return this._objectToArray(this._buffer).length;
		},

		/**
         * calculate the count of spec key
         * @param key
                '*':     return first package key count
			    'a':	 return base value which key is 'a'
			    'a.b.c': return deep value a->b->c
         *
         * @use [jSQL instance].count('a.b.c')
         */
		total: function(key) {
		    var rs = 0, scope = key.split('.');
            if(key === '*')
            this._buffer = this._currentDB;
            for(var key in this._currentDB) {
                if (this._currentDB.hasOwnProperty(key)) {
                    var tmp = this._currentDB[key];
                    for(var i=0,j=0; i<(j=scope.length); i++) {
                        tmp = tmp[scope[i]];
                        if(!!tmp && i == j - 1) rs++;
                    }
                }
            }
            return rs;
		},

		/**
		* sort the current result set
		* @param field [String]
		* @param callback [function]
		* @param order [String <asc | desc>]
		*/

		orderby: function(field, callback, order) {
			var _array = this._objectToArray(this._buffer);
			var _this = this;

			if(typeof(callback) !== 'function') {
				callback = [order, order = callback][0];
			}

			_array.sort(function(a, b) {
				a = _this._deep(a, field);
				b = _this._deep(b, field);
				if(callback) {
					a = callback(a);
					b = callback(b);
				}
				return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
			});

			this._buffer = this._arrayToObject(_array);
			return this;
		},

		where: function(fn) {
			var _tmp = {}, _swap;
			this._buffer = this._buffer || this._currentDB;

			for(var i in this._buffer) {
				if(this._buffer.hasOwnProperty(i)) {
					_swap = fn.call(this, this._buffer[i], i);

					if(_swap) {
						_tmp[i] = this._buffer[i];
					}
				}
			}
			this._buffer = _tmp;
			return this;
		},

		iterate: function(fn) {
			var _swap;
			this._buffer = this._buffer || this._currentDB;

			for(var i in this._buffer) {
				if(this._buffer.hasOwnProperty(i)) {
					_swap = fn.call(this, this._buffer[i]);

					if(_swap) {
						this.update(i, _swap);
					}
				}
			}
		},

		/**
		* return the current result set
		* @return [Object]
		*/

		findAll: function() {
			return this._buffer;
		},

		/**
		* return a specified item of current result set
		* if the key doesn't given, it'll return the first item
		* @return [Object]
		*/

		find: function(key) {
			if(!key) {
				for(var i in this._buffer) {
					if(key) {
						break;
					}

					if(this._buffer.hasOwnProperty(i)) {
						key = i;
					}
				}
			}

			return this._buffer[key];
		},

		/**
		* return the current result set as array list
		* @return [Object]
		*/

		listAll: function() {
			return this._objectToArray(this._buffer);
		},

		/**
		* update the current result set
		* @param key [String]
		* @param data [Object]
		*/

		update: function(key, data) {
			if(!this._currentDB) {
				throw('Please Select Database First.');
			}

			if(this._currentDB.hasOwnProperty(key)) {
				this._currentDB[key] = data;
			}
		},

		/**
		* limie the current result set
		* @param start [Number]
		* @param end [Number]
		*/

		limit: function(start, end) {
			var _tmp = this._objectToArray(this._buffer);

			if(!end) {
				start = [0, end = start][0];
			}

			this._buffer = this._arrayToObject(_tmp);
		},

		/**
		* private methods
		*/

		_deep: function(data, scope) {
			var _tmp = data, scope = scope.split('.');
			for(var i = 0; i < scope.length; i++) {
				_tmp = _tmp[scope[i]];
			}
			return _tmp;
		},

		_isArray: nativeIsArray || function(obj) {
			return toString.call(obj) === '[object Array]';
		},

		_isObject: function(obj) {
			return obj === Object(obj);
		},

		_clone: function(obj) {
			var _tmp = {};

			if (!this._isObject(obj)) return obj;
			if(this._isArray(obj)) return obj.slice();

			for(var i in obj) {
				if(obj.hasOwnProperty(i)) {
					_tmp[i] = obj[i];
				}
			}
			return _tmp;
		},

		_objectToArray: function(object) {
			var array = [], object = this._clone(object);

			for(var i in object) {
				if(object.hasOwnProperty(i)) {
					object[i].__jSQL_Key = i;
					array.push(object[i]);
				}
			}

			return array;
		},

		_arrayToObject: function(array, key) {
			var object = {};

			for(var i = 0; i < array.length; i++) {
				object[array[i][key || '__jSQL_Key']] = array[i];
				delete object[array[i][key || '__jSQL_Key']][key || '__jSQL_Key'];
			};

			return object;
		}
	};

	typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jSQL = jSQL;
})();<|endoftext|>


<commit_before>/**
 * Underhand solution for reading Json on time without worrying about loadings not being on correct time.
 *
 */

function getJson(){
	//Think if sizeMultiplier should be set instead of the zoom as playerPref
	var x=
{
	"sizeMultiplier": 1.5,
	"nations":
	[
		{
			"name": "Venaja",
			"x": " ,Border:Right",
			"y": 600,
			"width": 187,
			"height": 348,
			"rotation": 0,
			"sprite": "Venäjä"

		},
		{
			"name": "Norja",
			"x": "Left:Venäjä,Percent:19",
			"y": "Same:Venäjä,Percent:-45",
			"width": 258,
			"height": 207,
			"rotation": 0,
			"sprite": "Norja"

		},
		{
			"name": "Suomi",
			"x": "Left:Venäjä,Percent:38",
			"y": "Same:Venäjä,Percent:-60",
			"width": 120,
			"height": 159,
			"rotation": 0,
			"sprite": "Suomi"
		},
		{
			"name": "Ruotsi",
			"x": "Same:Suomi,Percent:-57.5",
			"y": "Same:Suomi,Percent:19",
			"width": 129,
			"height": 191,
			"rotation": 0,
			"sprite": "Ruotsi"

		},
		{
			"name": "Viro",
			"x": "Left:Venäjä,Percent:17",
			"y": "Down:Suomi,Percent:-17",
			"width": 66,
			"height": 34,
			"rotation": 0,
			"sprite": "Viro"
		},
		{
			"name": "Latvia",
			"x": "Same:Viro,Percent:-8",
			"y": "Down:Viro,Percent:-37",
			"width": 69,
			"height": 28,
			"rotation": 0,
			"sprite": "Latvia"
		},
		{
			"name": "Valko-Venaja",
			"x": "Same:Latvia,Percent:36",
			"y": "Down:Latvia,Percent:-13",
			"width": 91,
			"height": 50,
			"rotation": 0,
			"sprite": "Valko-Venaja"
		},
		{
			"name": "Liettua",
			"x": "Same:Latvia,Percent:-11",
			"y": "Down:Latvia,Percent:-30",
			"width": 55,
			"height": 29,
			"rotation": 0,
			"sprite": "Liettua"
		},
		{
			"name": "Ukraina",
			"x": "Same:Valko-Venäjä,Percent:15.5",
			"y": "Down:Valko-Venäjä,Percent:-13",
			"width": 176,
			"height": 75,
			"rotation": 0,
			"sprite": "Ukraina"
		},
		{
			"name": "Puola",
			"x": "Left:Valko-Venäjä,Percent:7",
			"y": "Same:Valko-Venäjä,Percent:33",
			"width": 92,
			"height": 58,
			"rotation": 0,
			"sprite": "Puola"
		},
		{
			"name": "Saksa",
			"x": "Left:Puola,Percent:9",
			"y": "Same:Puola,Percent:11",
			"width": 84,
			"height": 72,
			"rotation": 0,
			"sprite": "Saksa"
		},
		{
			"name": "Tanska",
			"x": "Same:Saksa,Percent:15",
			"y": "Up:Saksa,Percent:16",
			"width": 71,
			"height": 39,
			"rotation": 0,
			"sprite": "Tanska"
		},
		{
			"name": "Alankomaat",
			"x": "Left:Saksa,Percent:43",
			"y": "Same:Saksa,Percent:-32",
			"width": 38,
			"height": 25,
			"rotation": 0,
			"sprite": "Alankomaat"
		},
		{
			"name": "Ranska",
			"x": "Left:Saksa,Percent:27",
			"y": "Down:Saksa,Percent:-40",
			"width": 120,
			"height": 82,
			"rotation": 0,
			"sprite": "Ranska"
		},
		{
			"name": "Belgia",
			"x": "Left:Saksa,Percent:10",
			"y": "Same:Saksa,Percent:50",
			"width": 28,
			"height": 18,
			"rotation": 0,
			"sprite": "Belgia"
		},
		{
			"name": "Italia",
			"x": "Same:Saksa,Percent:15",
			"y": "Down:Saksa,Percent:0",
			"width": 102,
			"height": 86,
			"rotation": 0,
			"sprite": "Italia"
		},
		{
			"name": "Romania",
			"x": "Same:Ukraina,Percent:-69",
			"y": "Down:Ukraina,Percent:-86",
			"width": 89,
			"height": 40,
			"rotation": 0,
			"sprite": "Romania"
		},
		{
			"name": "Moldova",
			"x": "Same:Ukraina,Percent:-89",
			"y": "Down:Ukraina,Percent:-135",
			"width": 33,
			"height": 29,
			"rotation": 0,
			"sprite": "Moldova"
		}
	]
};
return x;
}<commit_msg>Sveitsin korjausta<commit_after>/**
 * Underhand solution for reading Json on time without worrying about loadings not being on correct time.
 *
 */

function getJson(){
	//Think if sizeMultiplier should be set instead of the zoom as playerPref
	var x=
{
	"sizeMultiplier": 1.5,
	"nations":
	[
		{
			"name": "Venaja",
			"x": " ,Border:Right",
			"y": 600,
			"width": 187,
			"height": 348,
			"rotation": 0,
			"sprite": "Venäjä"

		},
		{
			"name": "Norja",
			"x": "Left:Venäjä,Percent:19",
			"y": "Same:Venäjä,Percent:-45",
			"width": 258,
			"height": 207,
			"rotation": 0,
			"sprite": "Norja"

		},
		{
			"name": "Suomi",
			"x": "Left:Venäjä,Percent:38",
			"y": "Same:Venäjä,Percent:-60",
			"width": 120,
			"height": 159,
			"rotation": 0,
			"sprite": "Suomi"
		},
		{
			"name": "Ruotsi",
			"x": "Same:Suomi,Percent:-57.5",
			"y": "Same:Suomi,Percent:19",
			"width": 129,
			"height": 191,
			"rotation": 0,
			"sprite": "Ruotsi"

		},
		{
			"name": "Viro",
			"x": "Left:Venäjä,Percent:17",
			"y": "Down:Suomi,Percent:-17",
			"width": 66,
			"height": 34,
			"rotation": 0,
			"sprite": "Viro"
		},
		{
			"name": "Latvia",
			"x": "Same:Viro,Percent:-8",
			"y": "Down:Viro,Percent:-37",
			"width": 69,
			"height": 28,
			"rotation": 0,
			"sprite": "Latvia"
		},
		{
			"name": "Valko-Venaja",
			"x": "Same:Latvia,Percent:36",
			"y": "Down:Latvia,Percent:-13",
			"width": 91,
			"height": 50,
			"rotation": 0,
			"sprite": "Valko-Venaja"
		},
		{
			"name": "Liettua",
			"x": "Same:Latvia,Percent:-11",
			"y": "Down:Latvia,Percent:-30",
			"width": 55,
			"height": 29,
			"rotation": 0,
			"sprite": "Liettua"
		},
		{
			"name": "Ukraina",
			"x": "Same:Valko-Venäjä,Percent:15.5",
			"y": "Down:Valko-Venäjä,Percent:-13",
			"width": 176,
			"height": 75,
			"rotation": 0,
			"sprite": "Ukraina"
		},
		{
			"name": "Puola",
			"x": "Left:Valko-Venäjä,Percent:7",
			"y": "Same:Valko-Venäjä,Percent:33",
			"width": 92,
			"height": 58,
			"rotation": 0,
			"sprite": "Puola"
		},
		{
			"name": "Saksa",
			"x": "Left:Puola,Percent:9",
			"y": "Same:Puola,Percent:11",
			"width": 84,
			"height": 72,
			"rotation": 0,
			"sprite": "Saksa"
		},
		{
			"name": "Tanska",
			"x": "Same:Saksa,Percent:15",
			"y": "Up:Saksa,Percent:16",
			"width": 71,
			"height": 39,
			"rotation": 0,
			"sprite": "Tanska"
		},
		{
			"name": "Alankomaat",
			"x": "Left:Saksa,Percent:43",
			"y": "Same:Saksa,Percent:-32",
			"width": 38,
			"height": 25,
			"rotation": 0,
			"sprite": "Alankomaat"
		},
		{
			"name": "Ranska",
			"x": "Left:Saksa,Percent:27",
			"y": "Down:Saksa,Percent:-40",
			"width": 120,
			"height": 82,
			"rotation": 0,
			"sprite": "Ranska"
		},
		{
			"name": "Belgia",
			"x": "Left:Saksa,Percent:10",
			"y": "Same:Saksa,Percent:50",
			"width": 28,
			"height": 18,
			"rotation": 0,
			"sprite": "Belgia"
		},
		{
			"name": "Italia",
			"x": "Same:Saksa,Percent:15",
			"y": "Down:Saksa,Percent:0",
			"width": 102,
			"height": 86,
			"rotation": 0,
			"sprite": "Italia"
		},
		{
			"name": "Romania",
			"x": "Same:Ukraina,Percent:-69",
			"y": "Down:Ukraina,Percent:-86",
			"width": 89,
			"height": 40,
			"rotation": 0,
			"sprite": "Romania"
		},
		{
			"name": "Moldova",
			"x": "Same:Ukraina,Percent:-89",
			"y": "Down:Ukraina,Percent:-135",
			"width": 33,
			"height": 29,
			"rotation": 0,
			"sprite": "Moldova"
		},
		{
			"name": "Sveitsi",
			"x": 400,
			"y": 400,
			"width": 88,
			"height": 36,
			"rotation": 0,
			"sprite": "Sveitsi"
		}
	]
};
return x;
}<|endoftext|>


<commit_before>define([
    'crafty'
], function(Crafty) {

  'use strict';

  var TILE_WIDTH = 32;
  var ASSETS = {
    'sprites': {
      'images/game/player.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpritePlayer': [0, 0]},
      },
      'images/game/wall.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpriteWall': [0, 0]}
      },
      'images/game/door.png': {
      'tile': TILE_WIDTH,
      'tileh': TILE_WIDTH,
      'map': {'SpriteDoor': [0,0]}
      }
    }
  }

  var _player;
  var _gameModelAdpt;
  var _playerModelAdpt;

  function initCrafty() {
    Crafty.c('Player', {
      init: function() {
        this.requires('2D, Canvas, Fourway, Collision, SpritePlayer, SpriteAnimation');

        this.fourway(_playerModelAdpt.getSpeed());

        this.reel('PlayerMovingRight',600, 0, 0, 1);
        this.reel('PlayerMovingUp',   600, 1, 0, 1);
        this.reel('PlayerMovingLeft', 600, 2, 0, 1);
        this.reel('PlayerMovingDown', 600, 3, 0, 1);

        this.onHit('Solid', this.stopMovement);
        this.onHit('Door', this.useDoor);

        this.bind('NewDirection', function(data) {
          if (data.x > 0) {
            this.animate('PlayerMovingRight', -1);
          } else if (data.x < 0) {
            this.animate('PlayerMovingLeft', -1);
          } else if (data.y > 0) {
            this.animate('PlayerMovingDown', -1);
          } else if (data.y < 0) {
            this.animate('PlayerMovingUp', -1);
          } else {
            this.pauseAnimation();
          }
        });

        this.bind('Moved', function(oldPosition) {
          _playerModelAdpt.setX(this.x);
          _playerModelAdpt.setY(this.y);
        });
      },

      stopMovement: function() {
        if (this._movement) {
          this.x -= this._movement.x;
          this.y -= this._movement.y;
        }
      },

      useDoor: function(doorParts) {
        console.log(doorParts[0].obj.doorID);
        _gameModelAdpt.onDoorVisit(doorParts[0].obj.doorID);
      }

    });

    Crafty.c('Wall', {
      init: function() {
        this.requires('2D, Canvas, Solid, SpriteWall, RoomItem');
      }
    });

    Crafty.c('Door', {
      init: function() {
        this.requires('2D, Canvas, SpriteDoor, RoomItem');
      }
    });

    Crafty.init(_gameModelAdpt.getDimensions().width,
                _gameModelAdpt.getDimensions().height,
                document.getElementById('game-stage'));

    Crafty.load(ASSETS, function() {
    });

  }

  function start() {
  }

  function loadRoom(roomConfig) {
    Crafty('RoomItem').each(function() { this.destroy(); });
    Crafty.background(roomConfig.background);
    setupBarriers(roomConfig.doors);
    _player.attr({x: _playerModelAdpt.getX(), y: _playerModelAdpt.getY()});
  }

  function makePlayerView(playerModelAdpt) {
    _playerModelAdpt = playerModelAdpt;

    _player = Crafty.e('Player');

    return _player;
  }

  function setupBarriers(gateways) {
    var widthInTiles = _gameModelAdpt.getDimensions().width/TILE_WIDTH;
    var heightInTiles = _gameModelAdpt.getDimensions().height/TILE_WIDTH;

    for (var j = 0; j < widthInTiles; j++) {
      if(!('north' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: 0});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: 0, doorID: 'north'});
      }
      if(!('south' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH, doorID: 'south'});
      }
    }

    for (var i = 0; i < heightInTiles; i++) {
      if(!('west' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: 0, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: 0, y: i * TILE_WIDTH, doorID: 'west'});
      }
      if(!('east' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH, doorID: 'east'});
      }
    }

  }

  return function GameView(gameModelAdpt) {
    _gameModelAdpt = gameModelAdpt;

    document.getElementById('btn-join').addEventListener('click', function() {
      _gameModelAdpt.onJoinClick(document.getElementById('ipt-name').value);
    });

    document.getElementById('btn-speed-inc').addEventListener('click', function() {
      _playerModelAdpt.onSpeedIncClick();
    });

    document.getElementById('btn-speed-dec').addEventListener('click', function() {
      _playerModelAdpt.onSpeedDecClick();
    });

    initCrafty();

    this.loadRoom = loadRoom;
    this.start = start;
    this.makePlayerView = makePlayerView;
  }
});
<commit_msg>Fixed a bug that caused multiple door usage events.<commit_after>define([
    'crafty'
], function(Crafty) {

  'use strict';

  var TILE_WIDTH = 32;
  var ASSETS = {
    'sprites': {
      'images/game/player.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpritePlayer': [0, 0]},
      },
      'images/game/wall.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpriteWall': [0, 0]}
      },
      'images/game/door.png': {
      'tile': TILE_WIDTH,
      'tileh': TILE_WIDTH,
      'map': {'SpriteDoor': [0,0]}
      }
    }
  }

  var _player;
  var _gameModelAdpt;
  var _playerModelAdpt;

  function initCrafty() {
    Crafty.c('Player', {
      init: function() {
        this.requires('2D, Canvas, Fourway, Collision, SpritePlayer, SpriteAnimation');

        this.fourway(_playerModelAdpt.getSpeed());

        this.reel('PlayerMovingRight',600, 0, 0, 1);
        this.reel('PlayerMovingUp',   600, 1, 0, 1);
        this.reel('PlayerMovingLeft', 600, 2, 0, 1);
        this.reel('PlayerMovingDown', 600, 3, 0, 1);

        this.onHit('Solid', this.stopMovement);
        this.onHit('Door', this.useDoor);

        this.bind('NewDirection', function(data) {
          if (data.x > 0) {
            this.animate('PlayerMovingRight', -1);
          } else if (data.x < 0) {
            this.animate('PlayerMovingLeft', -1);
          } else if (data.y > 0) {
            this.animate('PlayerMovingDown', -1);
          } else if (data.y < 0) {
            this.animate('PlayerMovingUp', -1);
          } else {
            this.pauseAnimation();
          }
        });

        this.bind('Moved', function(oldPosition) {
          _playerModelAdpt.setX(this.x);
          _playerModelAdpt.setY(this.y);
        });
      },

      stopMovement: function() {
        if (this._movement) {
          this.x -= this._movement.x;
          this.y -= this._movement.y;
        }
      },

      useDoor: function(doorParts) {
        /*
         * If the door lock has been enabled, this will prevent a door from
         * being used twice for the same room.
         */
        if (this.attr('doorLock')) {
          console.log('the lock prevented a double move');
          return;
        }

        _gameModelAdpt.onDoorVisit(doorParts[0].obj.doorID);

        /* Lock the door to prevent double usages. */
        this.attr({'doorLock': true});
      }

    });

    Crafty.c('Wall', {
      init: function() {
        this.requires('2D, Canvas, Solid, SpriteWall, RoomItem');
      }
    });

    Crafty.c('Door', {
      init: function() {
        this.requires('2D, Canvas, SpriteDoor, RoomItem');
      }
    });

    Crafty.init(_gameModelAdpt.getDimensions().width,
                _gameModelAdpt.getDimensions().height,
                document.getElementById('game-stage'));

    Crafty.load(ASSETS, function() {
    });

  }

  function start() {
  }

  function loadRoom(roomConfig) {
    Crafty('RoomItem').each(function() { this.destroy(); });
    Crafty.background(roomConfig.background);
    setupBarriers(roomConfig.doors);

    /* Sets the player location and re-allows door usage. */
    _player.attr({x: _playerModelAdpt.getX(),
                  y: _playerModelAdpt.getY(),
                  doorLock: false});
  }

  function makePlayerView(playerModelAdpt) {
    _playerModelAdpt = playerModelAdpt;

    _player = Crafty.e('Player');

    return _player;
  }

  function setupBarriers(gateways) {
    var widthInTiles = _gameModelAdpt.getDimensions().width/TILE_WIDTH;
    var heightInTiles = _gameModelAdpt.getDimensions().height/TILE_WIDTH;

    for (var j = 0; j < widthInTiles; j++) {
      if(!('north' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: 0});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: 0, doorID: 'north'});
      }
      if(!('south' in gateways && (j == widthInTiles/2 || j == widthInTiles/2-1))) {
        Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: j * TILE_WIDTH, y: (heightInTiles - 1) * TILE_WIDTH, doorID: 'south'});
      }
    }

    for (var i = 0; i < heightInTiles; i++) {
      if(!('west' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: 0, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: 0, y: i * TILE_WIDTH, doorID: 'west'});
      }
      if(!('east' in gateways && (i == heightInTiles/2 || i == heightInTiles/2-1))) {
        Crafty.e('Wall').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH});
      }
      else {
        Crafty.e('Door').attr({x: (widthInTiles - 1) * TILE_WIDTH, y: i * TILE_WIDTH, doorID: 'east'});
      }
    }

  }

  return function GameView(gameModelAdpt) {
    _gameModelAdpt = gameModelAdpt;

    document.getElementById('btn-join').addEventListener('click', function() {
      _gameModelAdpt.onJoinClick(document.getElementById('ipt-name').value);
    });

    document.getElementById('btn-speed-inc').addEventListener('click', function() {
      _playerModelAdpt.onSpeedIncClick();
    });

    document.getElementById('btn-speed-dec').addEventListener('click', function() {
      _playerModelAdpt.onSpeedDecClick();
    });

    initCrafty();

    this.loadRoom = loadRoom;
    this.start = start;
    this.makePlayerView = makePlayerView;
  }
});
<|endoftext|>


<commit_before>var cms = {
	debug: true,
	init:	function(){
		$.blockUI.defaults.css.border = '3px solid #aaa';
		$.blockUI.defaults.css.backgroundColor = 'white';
		$.blockUI.defaults.css.width = '35px';
		$.blockUI.defaults.css.left = '48%';
		$.blockUI.defaults.message = '';
		//$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI); /* can be used to block the whole document on every ajax request */
		this.registerNavHandlers();
		this.registerDashboardHandlers();
	},

	/**
	* set which content shall be loaded via ajax by clicking on a menu button
	*/
	registerNavHandlers: function(){
		if (this.debug) console.log('registering nav menu handlers');
		$('#navmenu > ul > li > a').each(function(){
			var el = $(this);
			var urlSuffix = el.attr('ajax');
			el.unbind();
			el.on('click', function(){
				cms.updateNavigationMenu(urlSuffix);

				$('#content').block();
				$.ajax({
					url: 'cms/' + urlSuffix,
					success: function(data){
						$('#content').html(data);
						if (urlSuffix == 'dashboard')
						{
							cms.registerDashboardHandlers();
						}
						if (urlSuffix == 'templates')
						{
							cms.populateTemplatesGrid();
						}
						if (urlSuffix == 'structures')
						{
							cms.populateStructuresGrid();
						}
						$('#content').unblock();
					},
					failure: function(){
						alert('Oops. An ajax error happened.');
						$('#content').unblock();
					}
				});
			});
		});
	},

	/**
	* register clickable buttons for the dashboard
	*/
	registerDashboardHandlers: function() {
		if (this.debug) console.log('registering dashboard handlers');
		$('.dashboard-list > li').each(function(){
			var el = $(this);
			var urlSuffix = el.attr('href');
			el.unbind();
			el.on('mouseenter', function(){
				$(this).removeClass('unhover-dashboard');
				$(this).addClass('hover-dashboard');
			});
			el.on('mouseleave', function(){
				$(this).addClass('unhover-dashboard');
			});
			el.on('click', function(){
				cms.updateNavigationMenu(urlSuffix);

				$('#content').block();
				$.ajax({
					url: 'cms/' + urlSuffix,
					success: function(data){
						$('#content').html(data);
						if (urlSuffix == 'templates')
						{
							cms.populateTemplateGrid();
						}
						$('#content').unblock();
					},
					failure: function(){
						alert('Oops. An ajax error happened.');
						$('#content').unblock();
					}
				});
			});
		});
	},

	/*
	* Change color of the navigation menu on the fly
	*/
	updateNavigationMenu: function(categoryLink) {
		if (this.debug) console.log('resetting navigation menu to: ' + categoryLink);
		$('#navmenu > ul > li > a').removeClass('big bold');
		$('#navmenu > ul > li > span').remove();
		var el = $('#navmenu > ul > li > a[ajax=' + categoryLink + ']');
		el.addClass('big bold');
		el.parent().append('=');
	},

	/**
	* Load template data into the template grid
	*/
	populateTemplatesGrid: function() {
		if (this.debug) console.log('populating template data grid');

		var sharableDataSource = new kendo.data.DataSource({
			//pageSize: 3,
			transport: {
			read: {
				url: "cms/templates/data",
				dataType: "json"
			}
		}
		});

		$('#template-grid').kendoGrid({
			dataSource: sharableDataSource,
			toolbar: [{
				text: 'Import all templates',
				className: 'tplimport',
				imageClass: 'k-add'
			}],
			scrollable: false,
			pageable: false,
			columns: [{
				title: 'Preview',
				width: 150,
				template: ''
					+''
					+'
#=previewimage_description#
'
			},{
				title: 'Description',
				template: ''
				+'
#=name#
'
				+'
#=description#
'
				+'
Layouts
'
				+'
'
				+'#for (var i=0;i<layouts.length;i++){#'
				+'
Ã #=layouts[i].description#
'
				+'#}#'
				+'
'
				+'
Modules
'
				+'
'
				+'#for (var i=0;i<modules.length;i++){#'
				+'
Ã #=modules[i].description#
'
				+'#}#'
				+'
'
			},{
				title: 'Activate',
				width: 70,
				template: ''
				+'
" '
				+'This template is currently active.
'
				+'<button activate="#=id#" isactive="#=active#">Set active =</button>'
			},],
			dataBound: function(e){
				if (this.debug) console.log("data was bound to the grid / registering button handlers");
				cms.updateTemplateGridInfo();
				$('table > tbody > tr > td > button').each(function(){
					$(this).on('click', function(){
						var dataId = $(this).attr('activate');

						$('#content').block();
						$.ajax({
							url: 'cms/templates/settemplate/' + dataId,
							success: function(data){
								cms.updateTemplateGridInfo(dataId);
								$('#content').unblock();
							},
							failure: function(){
								alert('Oops. An ajax error happened.');
								$('#content').unblock();
							}
						});
					});
				});
			}
		});

		//add click handler to the custom toolbar button
		$('.tplimport').click(function(){
			$('#content').block();
			$.ajax({
				url: 'cms/templates/import',
				success: function(data){
					$('#template-grid').data('kendoGrid').dataSource.read();
					$('#content').unblock();
				},
				failure: function(){
					alert('Oops. An ajax error happened.');
					$('#content').unblock();
				}
			});
		});
	},

	/**
	* Show "set active" button in the template grid, only if the
	* template is not active currently
	*/
	updateTemplateGridInfo: function(dataId){
		$('p.hidden').hide();
		$('button').show();
		if (dataId != null)
		{
			$('p.hidden[activeid=' + dataId + ']').show();
			$('button[activate=' + dataId + ']').hide();
		}
		else
		{
			$('button[isactive=1]').hide();
			$('p.hidden[isactive=1]').show();
		}
	},

	/**
	* Fill the structures grid with data
	*/
	populateStructuresGrid: function() {
		if (this.debug) console.log('populating structures data grid');

		var data = new kendo.data.DataSource({
			transport: {
				read: {
					url: 'cms/structures/data',
					dataType: 'json'
				},
				update: {
					url: function(params){
						return 'cms/structures/update/' + params.id;
					},
					type: 'POST'
				},
				destroy: {
					url: function(params){
						console.log('destroy');
						return 'cms/structures/destroy/' + params.id;
					},
					type: 'POST'
				},
				create: {
					url: 'cms/structures/create',
					type: 'POST',
					complete: function(e) {
						// refresh grid after db update
						$("#structures-grid").data("kendoGrid").dataSource.read();
					}
				},
				// map the parameters we give to the backend according to the used
				// operation (e.g. read out the position for new entries)
				parameterMap: function(options, operation) {
					return {
						id: options.id,
						position: (operation == 'create') ? $('.k-grid-content tr').length : options.position,
						active: options.active,
						title: options.title,
						description: options.description,
						format: options.format
					}
				}
			},
			schema: {
				data: 'data',
				model: {
					id: 'id',
					fields: {
						id: {editable:false, nullable:false, defaultValue: -1},
						position: {editable:false, validation: {required:true}},
						active: {type:'boolean'},
						title: {type:'string', validation: {required:true}},  // TODO !!!!! check for [a-zA-Z0-9_]
						description: {type:'string'},
						format: {type:'string', validation: {required:true}}
					}
				}
			}
		});

		$('#structures-grid').kendoGrid({
			dataSource: data,
			toolbar: ['create', 'save', 'cancel'],
			sortable: false,
			filterable: false,
			scrollable: true,
			selectable: true,
			editable: 'inline', // 'inline' with editable: true the delete command is not working!
			columns: [
				{field:'position', title:'#', width:'50'},
				{field:'active', title:'Active?', width:'70',
					template: '<input type="checkbox" # if(active){# checked #}#/>'
				},
				{field:'title', title:'Title'},
				{field:'description', title:'Description'},
				{field:'format', title:'Type'},
				{command:'destroy', title:''}
			]
		});
	}
}

$(document).ready(function(){
	cms.init();
});<commit_msg>* added validation to the site structures title form<commit_after>var cms = {
	debug: true,
	init:	function(){
		$.blockUI.defaults.css.border = '3px solid #aaa';
		$.blockUI.defaults.css.backgroundColor = 'white';
		$.blockUI.defaults.css.width = '35px';
		$.blockUI.defaults.css.left = '48%';
		$.blockUI.defaults.message = '';
		//$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI); /* can be used to block the whole document on every ajax request */
		this.registerNavHandlers();
		this.registerDashboardHandlers();
	},

	/**
	* set which content shall be loaded via ajax by clicking on a menu button
	*/
	registerNavHandlers: function(){
		if (this.debug) console.log('registering nav menu handlers');
		$('#navmenu > ul > li > a').each(function(){
			var el = $(this);
			var urlSuffix = el.attr('ajax');
			el.unbind();
			el.on('click', function(){
				cms.updateNavigationMenu(urlSuffix);

				$('#content').block();
				$.ajax({
					url: 'cms/' + urlSuffix,
					success: function(data){
						$('#content').html(data);
						if (urlSuffix == 'dashboard')
						{
							cms.registerDashboardHandlers();
						}
						if (urlSuffix == 'templates')
						{
							cms.populateTemplatesGrid();
						}
						if (urlSuffix == 'structures')
						{
							cms.populateStructuresGrid();
						}
						$('#content').unblock();
					},
					failure: function(){
						alert('Oops. An ajax error happened.');
						$('#content').unblock();
					}
				});
			});
		});
	},

	/**
	* register clickable buttons for the dashboard
	*/
	registerDashboardHandlers: function() {
		if (this.debug) console.log('registering dashboard handlers');
		$('.dashboard-list > li').each(function(){
			var el = $(this);
			var urlSuffix = el.attr('href');
			el.unbind();
			el.on('mouseenter', function(){
				$(this).removeClass('unhover-dashboard');
				$(this).addClass('hover-dashboard');
			});
			el.on('mouseleave', function(){
				$(this).addClass('unhover-dashboard');
			});
			el.on('click', function(){
				cms.updateNavigationMenu(urlSuffix);

				$('#content').block();
				$.ajax({
					url: 'cms/' + urlSuffix,
					success: function(data){
						$('#content').html(data);
						if (urlSuffix == 'templates')
						{
							cms.populateTemplateGrid();
						}
						$('#content').unblock();
					},
					failure: function(){
						alert('Oops. An ajax error happened.');
						$('#content').unblock();
					}
				});
			});
		});
	},

	/*
	* Change color of the navigation menu on the fly
	*/
	updateNavigationMenu: function(categoryLink) {
		if (this.debug) console.log('resetting navigation menu to: ' + categoryLink);
		$('#navmenu > ul > li > a').removeClass('big bold');
		$('#navmenu > ul > li > span').remove();
		var el = $('#navmenu > ul > li > a[ajax=' + categoryLink + ']');
		el.addClass('big bold');
		el.parent().append('=');
	},

	/**
	* Load template data into the template grid
	*/
	populateTemplatesGrid: function() {
		if (this.debug) console.log('populating template data grid');

		var sharableDataSource = new kendo.data.DataSource({
			//pageSize: 3,
			transport: {
			read: {
				url: "cms/templates/data",
				dataType: "json"
			}
		}
		});

		$('#template-grid').kendoGrid({
			dataSource: sharableDataSource,
			toolbar: [{
				text: 'Import all templates',
				className: 'tplimport',
				imageClass: 'k-add'
			}],
			scrollable: false,
			pageable: false,
			columns: [{
				title: 'Preview',
				width: 150,
				template: ''
					+''
					+'
#=previewimage_description#
'
			},{
				title: 'Description',
				template: ''
				+'
#=name#
'
				+'
#=description#
'
				+'
Layouts
'
				+'
'
				+'#for (var i=0;i<layouts.length;i++){#'
				+'
Ã #=layouts[i].description#
'
				+'#}#'
				+'
'
				+'
Modules
'
				+'
'
				+'#for (var i=0;i<modules.length;i++){#'
				+'
Ã #=modules[i].description#
'
				+'#}#'
				+'
'
			},{
				title: 'Activate',
				width: 70,
				template: ''
				+'
" '
				+'This template is currently active.
'
				+'<button activate="#=id#" isactive="#=active#">Set active =</button>'
			},],
			dataBound: function(e){
				if (this.debug) console.log("data was bound to the grid / registering button handlers");
				cms.updateTemplateGridInfo();
				$('table > tbody > tr > td > button').each(function(){
					$(this).on('click', function(){
						var dataId = $(this).attr('activate');

						$('#content').block();
						$.ajax({
							url: 'cms/templates/settemplate/' + dataId,
							success: function(data){
								cms.updateTemplateGridInfo(dataId);
								$('#content').unblock();
							},
							failure: function(){
								alert('Oops. An ajax error happened.');
								$('#content').unblock();
							}
						});
					});
				});
			}
		});

		//add click handler to the custom toolbar button
		$('.tplimport').click(function(){
			$('#content').block();
			$.ajax({
				url: 'cms/templates/import',
				success: function(data){
					$('#template-grid').data('kendoGrid').dataSource.read();
					$('#content').unblock();
				},
				failure: function(){
					alert('Oops. An ajax error happened.');
					$('#content').unblock();
				}
			});
		});
	},

	/**
	* Show "set active" button in the template grid, only if the
	* template is not active currently
	*/
	updateTemplateGridInfo: function(dataId){
		$('p.hidden').hide();
		$('button').show();
		if (dataId != null)
		{
			$('p.hidden[activeid=' + dataId + ']').show();
			$('button[activate=' + dataId + ']').hide();
		}
		else
		{
			$('button[isactive=1]').hide();
			$('p.hidden[isactive=1]').show();
		}
	},

	/**
	* Fill the structures grid with data
	*/
	populateStructuresGrid: function() {
		if (this.debug) console.log('populating structures data grid');

		var data = new kendo.data.DataSource({
			transport: {
				read: {
					url: 'cms/structures/data',
					dataType: 'json'
				},
				update: {
					url: function(params){
						return 'cms/structures/update/' + params.id;
					},
					type: 'POST'
				},
				destroy: {
					url: function(params){
						console.log('destroy');
						return 'cms/structures/destroy/' + params.id;
					},
					type: 'POST'
				},
				create: {
					url: 'cms/structures/create',
					type: 'POST',
					complete: function(e) {
						// refresh grid after db update
						$("#structures-grid").data("kendoGrid").dataSource.read();
					}
				},
				// map the parameters we give to the backend according to the used
				// operation (e.g. read out the position for new entries)
				parameterMap: function(options, operation) {
					return {
						id: options.id,
						position: (operation == 'create') ? $('.k-grid-content tr').length : options.position,
						active: options.active,
						title: options.title,
						description: options.description,
						format: options.format
					}
				}
			},
			schema: {
				data: 'data',
				model: {
					id: 'id',
					fields: {
						id: {editable:false, nullable:false, defaultValue: -1},
						position: {editable:false, validation: {required:true}},
						active: {type:'boolean'},
						title: {type:'string', validation: {
							required:true,
							custom: function(input) {
								input.attr('data-custom-msg',
									'The title can only contain letters A-Z, a-z, underscore _ or Numbers 0-9.');
								// check for a-zA-Z0-9_
								return (input.val().match(/^[a-zA-Z0-9_]+$/g));
							}
						}},
						description: {type:'string'},
						format: {type:'string', validation: {required:true}}
					}
				}
			}
		});

		var testData = [
			{ 'value': '2col', 'text': 'omnom 2col' },
			{ 'value': '3col', 'text': 'offoff 3col'}
		];

		$('#structures-grid').kendoGrid({
			dataSource: data,
			toolbar: ['create', 'save', 'cancel'],
			sortable: false,
			filterable: false,
			scrollable: true,
			selectable: true,
			editable: true, // 'inline' with editable: true the delete command is not working!
			columns: [
				{field:'position', title:'#', width:'50'},
				{field:'active', title:'Active?', width:'70',
					template: '<input type="checkbox" # if(active){# checked #}#/>'
				},
				{field:'title', title:'Title'},
				{field:'description', title:'Description'},
				{field:'format', title:'Type', values: testData},
				{command:'destroy', title:''}
			]
		});
	}
}

$(document).ready(function(){
	cms.init();
});<|endoftext|>


<commit_before>var Youkok = (function (module) {

    /*
     * Private variables
     */
    var data; // Holds the site information

    /*
     * Init different sub modules
     */
    var initSubModules = function() {
        // Independent sub modules (always loaded)
        Youkok.user.init();
        Youkok.message.init();
        Youkok.general.init();
        Youkok.grayboxes.init();
        Youkok.search.init();
        Youkok.debug.init();

        // Archive
        if (Youkok.getData('view') == 'archive') {
            Youkok.archive.init();
            Youkok.createFile.init();
            Youkok.createLink.init();

            // Init submodule for logged in archive
            if (Youkok.getData('online') == true) {
                Youkok.createDirectory.init();
            }
        }

        // Frontpage
        if (Youkok.getData('view') == 'frontpage') {
            Youkok.frontpage.init();
        }

        // Forgotten password
        if (Youkok.getData('view') == 'forgotten-password' || Youkok.getData('view') == 'profile') {
            Youkok.forgottenPassword.init();
        }

        // Register
        if (Youkok.getData('view') == 'register') {
            Youkok.register.init();
        }
    };

    /*
     * Init function
     */
    module.init = function () {
        // Parse data
        data = jQuery.parseJSON(SITE_DATA);

        // Start moment.js
        moment.lang('en', {
            relativeTime : {
                future: "Om %s",
                past:   "%s siden",
                s:  "Noen få sekunder",
                m:  "Ett minutt",
                mm: "%d minutter",
                h:  "En time",
                hh: "%d timer",
                d:  "en dag",
                dd: "%d dager",
                M:  "En måned",
                MM: "%d måneder",
                y:  "Et år",
                yy: "%d år"
            }
        });

        // Underscorejs settings
        _.templateSettings.variable = 'rc';

        // Apply moment.js
        $('.moment-timestamp').each(function () {
            var $that = $(this);
            $that.html(moment($(this).data('ts')).fromNow());
        });

        // Apply tooltips
        $('.list-group-item a, .list-group-item .moment-timestamp').tooltip();

        // Init submodules
        initSubModules();
    };

    /*
     * Get site data
     */
    module.getData = function (key) {
        return data[key];
    };

    /*
     * Return the module
     */
    return module;
})(Youkok || {});<commit_msg>Fix underscorejs deprecated warning<commit_after>var Youkok = (function (module) {

    /*
     * Private variables
     */
    var data; // Holds the site information

    /*
     * Init different sub modules
     */
    var initSubModules = function() {
        // Independent sub modules (always loaded)
        Youkok.user.init();
        Youkok.message.init();
        Youkok.general.init();
        Youkok.grayboxes.init();
        Youkok.search.init();
        Youkok.debug.init();

        // Archive
        if (Youkok.getData('view') == 'archive') {
            Youkok.archive.init();
            Youkok.createFile.init();
            Youkok.createLink.init();

            // Init submodule for logged in archive
            if (Youkok.getData('online') == true) {
                Youkok.createDirectory.init();
            }
        }

        // Frontpage
        if (Youkok.getData('view') == 'frontpage') {
            Youkok.frontpage.init();
        }

        // Forgotten password
        if (Youkok.getData('view') == 'forgotten-password' || Youkok.getData('view') == 'profile') {
            Youkok.forgottenPassword.init();
        }

        // Register
        if (Youkok.getData('view') == 'register') {
            Youkok.register.init();
        }
    };

    /*
     * Init function
     */
    module.init = function () {
        // Parse data
        data = jQuery.parseJSON(SITE_DATA);

        // Start moment.js
        moment.locale('en', {
            relativeTime : {
                future: "Om %s",
                past:   "%s siden",
                s:  "Noen få sekunder",
                m:  "Ett minutt",
                mm: "%d minutter",
                h:  "En time",
                hh: "%d timer",
                d:  "en dag",
                dd: "%d dager",
                M:  "En måned",
                MM: "%d måneder",
                y:  "Et år",
                yy: "%d år"
            }
        });

        // Underscorejs settings
        _.templateSettings.variable = 'rc';

        // Apply moment.js
        $('.moment-timestamp').each(function () {
            var $that = $(this);
            $that.html(moment($(this).data('ts')).fromNow());
        });

        // Apply tooltips
        $('.list-group-item a, .list-group-item .moment-timestamp').tooltip();

        // Init submodules
        initSubModules();
    };

    /*
     * Get site data
     */
    module.getData = function (key) {
        return data[key];
    };

    /*
     * Return the module
     */
    return module;
})(Youkok || {});<|endoftext|>


<commit_before>angular.module('CsvParser', [])

.factory('CsvParser', function() {

    function CsvParser(data, fieldSpliterChar, recordSpliterChar){

        if (!(this instanceof CsvParser)) return new CsvParser(data, spliter);

        this._data = data;
        this._fieldSpliterChar = fieldSpliterChar || ',';
        this._recordSpliterChar = recordSpliterChar || '\n';

        this.parsedData = {
            headers: [],
            values: []
        };

        this.parse();
    };

    var _split = function(splitter, text){
        return text.split(splitter);
    };

    CsvParser.prototype = {
        fieldSplit: function(text) {
            var me = this;
            return _split(me._fieldSpliterChar, text);
        },
        recordSplit: function(text) {
            return _split(this._recordSpliterChar, text);
        },
        parse: function() {
            var me = this;
            var temp = this.recordSplit(this._data).map(function(v){
                return me.fieldSplit(v);
            });

            this.parsedData.headers = temp[0];
            this.parsedData.values = temp.splice(1);
        },
        find: function(name) {
            return this.parsedData.headers.indexOf(name);
        },
        getColumn: function(name) {
            var index = this.find(name);

            return this.parsedData.values.map(function(v){
                return v[index];
            });
        },
        columnOf: function(name, record){
            // TODO: move this out into record prototype
            var index = this.find(name);

            return record[index];
        },
        filterByColumn: function(columnName, comparison){
            var index = this.find(columnName);

            return this.parsedData.values.filter(function(value, i, obj){
                return comparison(value[index], i, obj);
            });
        },
        recordsWith: function(columnName, value){
            return this.filterByColumn(columnName, function(val){
                return val === value;
            });
        },
        recordsWithout: function(columnName, value){
            var comparison = function(val){
                return val != value;
            };

            if (value instanceof Array) {
                comparison = function(val){
                    return value.indexOf(val) === -1;
                };
            }

            return this.filterByColumn(columnName, comparison);
        },
        recordsWithoutByColumns: function(columns){
            // columns should be an object with
            // key : [values]

            var me = this;

            var is_in_array = function(values, val) {
                return values.indexOf(val) > -1;
            };

            var is_without = function(columns){
                return function(record){
                    for (var key in columns){
                        var values = columns[key];
                        var currentIndex = me.find(key);

                        if (values.length < 1){
                            console.log("No values for key, ", key);
                            continue;
                        }

                        if (currentIndex < 0) {
                            console.log("Key, ", key, "not found");
                            continue;
                        }

                        if (is_in_array(values, record[currentIndex])){
                            return false;
                        }
                    }

                    return true;
                };
            }(columns);

            var records = [];

            for (var i = 0; i < this.parsedData.values.length; i++){
                var currentRecord = this.parsedData.values[i];
                if (is_without(currentRecord)){
                    records.push(currentRecord);
                }
            }

            return records;
        }
    };

    return CsvParser;
})
<commit_msg>Fixing missing char passed to new object<commit_after>angular.module("CsvParser", [])

.factory('CsvParser', function() {

    function CsvParser(data, fieldSpliterChar, recordSpliterChar){

        if (!(this instanceof CsvParser)) return new CsvParser(data, fieldSpliterChar, recordSpliterChar);

        this._data = data;
        this._fieldSpliterChar = fieldSpliterChar || ',';
        this._recordSpliterChar = recordSpliterChar || '\n';

        this.parsedData = {
            headers: [],
            values: []
        };

        this.parse();
    };

    var _split = function(splitter, text){
        return text.split(splitter);
    };

    CsvParser.prototype = {
        fieldSplit: function(text) {
            return _split(this._fieldSpliterChar, text);
        },
        recordSplit: function(text) {
            return _split(this._recordSpliterChar, text);
        },
        parse: function() {
            var me = this;
            var temp = this.recordSplit(this._data).map(function(v){
                return me.fieldSplit(v);
            });

            this.parsedData.headers = temp[0];
            this.parsedData.values = temp.splice(1);
        },
        find: function(name) {
            return this.parsedData.headers.indexOf(name);
        },
        getColumn: function(name) {
            var index = this.find(name);

            return this.parsedData.values.map(function(v){
                return v[index];
            });
        },
        columnOf: function(name, record){
            // TODO: move this out into record prototype
            var index = this.find(name);

            return record[index];
        },
        columnOfAll: function(name){
            var me = this;
            return this.parsedData.values.map(function(v) {
                return me.columnOf(name, v);
            });
        },
        filterByColumn: function(columnName, comparison){
            var index = this.find(columnName);

            return this.parsedData.values.filter(function(value, i, obj){
                return comparison(value[index], i, obj);
            });
        },
        recordsWith: function(columnName, value){
            return this.filterByColumn(columnName, function(val){
                return val === value;
            });
        },
        recordsWithout: function(columnName, value){
            var comparison = function(val){
                return val != value;
            };

            if (value instanceof Array) {
                comparison = function(val){
                    return value.indexOf(val) === -1;
                };
            }

            return this.filterByColumn(columnName, comparison);
        },
        recordsWithoutByColumns: function(columns){
            // columns should be an object with
            // key : [values]

            var me = this;

            var is_in_array = function(values, val) {
                return values.indexOf(val) > -1;
            };

            var is_without = function(columns){
                return function(record){
                    for (var key in columns){
                        var values = columns[key];
                        var currentIndex = me.find(key);

                        if (values.length < 1 || currentIndex < 0){
                            continue;
                        }

                        if (is_in_array(values, record[currentIndex])){
                            return false;
                        }
                    }

                    return true;
                };
            }(columns);

            var records = [];

            for (var i = 0; i < this.parsedData.values.length; i++){
                var currentRecord = this.parsedData.values[i];
                if (is_without(currentRecord)){
                    records.push(currentRecord);
                }
            }

            return records;
        }
    };

    return CsvParser;
});
<|endoftext|>