<commit_before>'use strict';

angular.module('wlsApp.services', [])
/* SERVICE TO WRAP HTTP REQUESTS */
.factory('apiService' , ['$q', '$http', function($q, $http) {
	//var stockListUrl = 'http://dev1:5000/api/stocks/';
	var stockListUrl = 'http://mean.wlsllc.com:5000/api/stocks/';

	var fetchStocks = function() {
		var deferred = $q.defer();
		$http.get(stockListUrl)
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
		})
		return deferred.promise;
	}

	var fetchCurrentStock = function(_id) {
		var deferred = $q.defer();
		$http.get(stockListUrl + _id)
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
		})
		return deferred.promise;
	}

	//---- TRANSFORMREQUESTASFORMPOST AVOIDS HAVING TO INCLUDE JQUERY FOR SERIALIZATION --
	//---- SEE FIRST ANSWER (as of Jan 27, 2015) IN THIS STACKOVERFLOW ARTICLE -----------
	//---- http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object/1714899#1714899
	var transformRequestAsFormPost = function(obj) {
	        var str = [];
	        for(var p in obj)
	        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
	}
	//-----

	var insertStock = function(stock) {
		var payload = {
			name:stock.name,
			ticker:stock.ticker,
			year1:stock.year1,
			year2:stock.year2,
			year3:stock.year3,
			year4:stock.year4,
			year5:stock.year5
		};
		var deferred = $q.defer();
		$http.post(stockListUrl,
			{
				transformRequest: transformRequestAsFormPost,
				data: payload,
				headers: {'Content-Type':'application/x-www-form-urlencoded'}
		})
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
			console.log('post error', reason);
		})
		return deferred.promise;
	}

	var deleteStock = function(_id) {
		var deferred = $q.defer();
		$http.delete(stockListUrl + _id)
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
			console.log('delete error', reason);
		})
		return deferred.promise;
	}

	var editStock = function(_id, stock) {
		var payload = {
			name:stock.name,
			ticker:stock.ticker,
			year1:stock.year1,
			year2:stock.year2,
			year3:stock.year3,
			year4:stock.year4,
			year5:stock.year5
		};
		var deferred = $q.defer();
		$http.put(stockListUrl + _id,
			{
				transformRequest: transformRequestAsFormPost,
				data: payload,
				headers: {'Content-Type':'application/x-www-form-urlencoded'}
		})
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
			console.log('post error', reason);
		})
		return deferred.promise;
	}

	//--- RETURN THE SERVICE OBJECT WITH METHODS -----
	return {
		fetchStocks: function() {
			return fetchStocks();
		},
		fetchCurrentStock: function(_id) {
			return fetchCurrentStock(_id);
		},
		insertStock: function(stock) {
			return insertStock(stock);
		},
		deleteStock: function(_id) {
			return deleteStock(_id);
		},
		editStock: function(_id, stock) {
			return editStock(_id, stock);
		}
	};
}]);
<commit_msg>Change to local mongo<commit_after>'use strict';

angular.module('wlsApp.services', [])
/* SERVICE TO WRAP HTTP REQUESTS */
.factory('apiService' , ['$q', '$http', function($q, $http) {
	var stockListUrl = 'http://localhost:5000/api/stocks/';
	//var stockListUrl = 'http://mean.wlsllc.com:5000/api/stocks/';

	var fetchStocks = function() {
		var deferred = $q.defer();
		$http.get(stockListUrl)
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
		})
		return deferred.promise;
	}

	var fetchCurrentStock = function(_id) {
		var deferred = $q.defer();
		$http.get(stockListUrl + _id)
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
		})
		return deferred.promise;
	}

	//---- TRANSFORMREQUESTASFORMPOST AVOIDS HAVING TO INCLUDE JQUERY FOR SERIALIZATION --
	//---- SEE FIRST ANSWER (as of Jan 27, 2015) IN THIS STACKOVERFLOW ARTICLE -----------
	//---- http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object/1714899#1714899
	var transformRequestAsFormPost = function(obj) {
	        var str = [];
	        for(var p in obj)
	        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
	}
	//-----

	var insertStock = function(stock) {
		var payload = {
			name:stock.name,
			ticker:stock.ticker,
			year1:stock.year1,
			year2:stock.year2,
			year3:stock.year3,
			year4:stock.year4,
			year5:stock.year5
		};
		var deferred = $q.defer();
		$http.post(stockListUrl,
			{
				transformRequest: transformRequestAsFormPost,
				data: payload,
				headers: {'Content-Type':'application/x-www-form-urlencoded'}
		})
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
			console.log('post error', reason);
		})
		return deferred.promise;
	}

	var deleteStock = function(_id) {
		var deferred = $q.defer();
		$http.delete(stockListUrl + _id)
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
			console.log('delete error', reason);
		})
		return deferred.promise;
	}

	var editStock = function(_id, stock) {
		var payload = {
			name:stock.name,
			ticker:stock.ticker,
			year1:stock.year1,
			year2:stock.year2,
			year3:stock.year3,
			year4:stock.year4,
			year5:stock.year5
		};
		var deferred = $q.defer();
		$http.put(stockListUrl + _id,
			{
				transformRequest: transformRequestAsFormPost,
				data: payload,
				headers: {'Content-Type':'application/x-www-form-urlencoded'}
		})
		.success(function(data) {
			deferred.resolve(data);
		})
		.error(function(reason) {
			deferred.reject(reason);
			console.log('post error', reason);
		})
		return deferred.promise;
	}

	//--- RETURN THE SERVICE OBJECT WITH METHODS -----
	return {
		fetchStocks: function() {
			return fetchStocks();
		},
		fetchCurrentStock: function(_id) {
			return fetchCurrentStock(_id);
		},
		insertStock: function(stock) {
			return insertStock(stock);
		},
		deleteStock: function(_id) {
			return deleteStock(_id);
		},
		editStock: function(_id, stock) {
			return editStock(_id, stock);
		}
	};
}]);
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var Cons = function(head,tail) {
    this.head = head;
    this.tail = tail;
    return this;
};

var head = function(l) {
    return l.head;
};

var tail = function(l) {
    return l.tail;
};

var nth = function(list,n) {
    return n === 0 ? head(list) : nth(list.tail, n-1);
};

var map = function(list,f) {
    if (isNull(list)) return list;

    return new Cons(
	f(head(list)),
	map(tail(list),f)
    );
};

var isNull = function(list) {
    return !list;
};

var makeList = function() {
    if (arguments.length === 0) {
	return undefined;
    }

    var args = Array.prototype.slice.call(arguments);
    var head = args.shift();

    return new Cons(head, args.length === 0 ? undefined : makeList.apply(null,args));
};

describe('prelude', function() {
    describe('lists', function() {
	it('should make an empty list', function() {
	    assert.deepEqual(undefined, makeList());
	});

	it('should make a cons cell', function() {
	    var list = makeList(1);

	    assert.equal(1, list.head);
	    assert.equal(undefined, list.tail);
	});

	it('should handle multiple elements', function() {
	    var list = makeList(1,2,3);

	    assert.equal(1,         list.head);
	    assert.equal(2,         list.tail.head);
	    assert.equal(3,         list.tail.tail.head);
	    assert.equal(undefined, list.tail.tail.tail);
	});

	it('should have head and tail functions', function() {
	    assert.equal(1, head(makeList(1,2,3)));
	    assert.equal(2, head(tail(makeList(1,2,3))));
	});

	it('should be possible get the nth element', function() {
	    assert.equal(2, nth(makeList(1,2,3),1));
	});

	it('can map', function() {
	    var addOne = function(x) { return x + 1; };

	    assert.deepEqual(makeList(2,3,4), map(makeList(1,2,3), addOne));
	});

	it('can filter', function() {
	    var isOdd = function(x) { return x % 2 !== 0; };

	    assert.deepEqual(makeList(1,3,5), filter(makeList(1,2,3,4,5), isOdd));
	});

	it('should support null', function() {
	    assert(isNull(makeList()));
	    assert(!isNull(makeList(1)));
	});
    });
});
<commit_msg>define filter<commit_after>"use strict";

var assert = require('assert');

var Cons = function(head,tail) {
    this.head = head;
    this.tail = tail;
    return this;
};

var head = function(l) {
    return l.head;
};

var tail = function(l) {
    return l.tail;
};

var nth = function(list,n) {
    return n === 0 ? head(list) : nth(list.tail, n-1);
};

var map = function(list,f) {
    if (isNull(list)) return list;

    return new Cons(
	f(head(list)),
	map(tail(list),f)
    );
};

var filter = function(list,p) {
    if (isNull(list)) return list;

    if (p(head(list))) return new Cons(head(list), filter(tail(list),p));

    return filter(tail(list),p);
};

var isNull = function(list) {
    return !list;
};

var makeList = function() {
    if (arguments.length === 0) {
	return undefined;
    }

    var args = Array.prototype.slice.call(arguments);
    var head = args.shift();

    return new Cons(head, args.length === 0 ? undefined : makeList.apply(null,args));
};

describe('prelude', function() {
    describe('lists', function() {
	it('should make an empty list', function() {
	    assert.deepEqual(undefined, makeList());
	});

	it('should make a cons cell', function() {
	    var list = makeList(1);

	    assert.equal(1, list.head);
	    assert.equal(undefined, list.tail);
	});

	it('should handle multiple elements', function() {
	    var list = makeList(1,2,3);

	    assert.equal(1,         list.head);
	    assert.equal(2,         list.tail.head);
	    assert.equal(3,         list.tail.tail.head);
	    assert.equal(undefined, list.tail.tail.tail);
	});

	it('should have head and tail functions', function() {
	    assert.equal(1, head(makeList(1,2,3)));
	    assert.equal(2, head(tail(makeList(1,2,3))));
	});

	it('should be possible get the nth element', function() {
	    assert.equal(2, nth(makeList(1,2,3),1));
	});

	it('can map', function() {
	    var addOne = function(x) { return x + 1; };

	    assert.deepEqual(makeList(2,3,4), map(makeList(1,2,3), addOne));
	});

	it('can filter', function() {
	    var isOdd = function(x) { return x % 2 !== 0; };

	    assert.deepEqual(makeList(1,3,5), filter(makeList(1,2,3,4,5), isOdd));
	});

	it('should support null', function() {
	    assert(isNull(makeList()));
	    assert(!isNull(makeList(1)));
	});
    });
});
<|endoftext|>


<commit_before>/**
 * A function that parses the `tokens.css`-file from `@hashicorp/design-system-tokens`
 * and creates a map out of it that can be used to build up a color configuration
 * in `tailwind.config.js`.
 *
 * @param {string} tokensPath - The path to `tokens.css` from `@hashicorp/design-system-tokens`
 * @returns { { [string]: string } } An object that contains color names as keys and color values as values.
 */
function colorMapFromTokens(tokensPath) {
  const css = require('css');
  const path = require('path');
  const fs = require('fs');

  const hdsTokensPath = path.join(__dirname, tokensPath);

  const tokensFile = fs.readFileSync(hdsTokensPath, {
    encoding: 'utf8',
    flag: 'r',
  });

  const ast = css.parse(tokensFile);
  const rootVars = ast.stylesheet.rules.filter((r) => r.type !== 'comment')[0];

  // filter out all colors and then create a map out of them
  const vars = rootVars.declarations.filter((d) => d.type !== 'comment');
  const colorPropertyNameCleanupRegex = /^--token-color-(palette-)?/;
  const colors = vars.filter((d) => d.property.match(/^--token-color-/));

  return colors.reduce((acc, d) => {
    acc[d.property.replace(colorPropertyNameCleanupRegex, 'hds-')] = d.value;
    return acc;
  }, {});
}

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./app/**/*.{html,js,hbs,mdx}', './docs/**/*.{html,js,hbs,mdx}'],
  theme: {
    colors: colorMapFromTokens(
      '../../node_modules/@hashicorp/design-system-tokens/dist/products/css/tokens.css'
    ),
    extend: {},
  },
  plugins: [],
};
<commit_msg>Configure tailwind-jit for sub-apps as well<commit_after>/**
 * A function that parses the `tokens.css`-file from `@hashicorp/design-system-tokens`
 * and creates a map out of it that can be used to build up a color configuration
 * in `tailwind.config.js`.
 *
 * @param {string} tokensPath - The path to `tokens.css` from `@hashicorp/design-system-tokens`
 * @returns { { [string]: string } } An object that contains color names as keys and color values as values.
 */
function colorMapFromTokens(tokensPath) {
  const css = require('css');
  const path = require('path');
  const fs = require('fs');

  const hdsTokensPath = path.join(__dirname, tokensPath);

  const tokensFile = fs.readFileSync(hdsTokensPath, {
    encoding: 'utf8',
    flag: 'r',
  });

  const ast = css.parse(tokensFile);
  const rootVars = ast.stylesheet.rules.filter((r) => r.type !== 'comment')[0];

  // filter out all colors and then create a map out of them
  const vars = rootVars.declarations.filter((d) => d.type !== 'comment');
  const colorPropertyNameCleanupRegex = /^--token-color-(palette-)?/;
  const colors = vars.filter((d) => d.property.match(/^--token-color-/));

  return colors.reduce((acc, d) => {
    acc[d.property.replace(colorPropertyNameCleanupRegex, 'hds-')] = d.value;
    return acc;
  }, {});
}

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['../**/*.{html.js,hbs,mdx}'],
  theme: {
    colors: colorMapFromTokens(
      '../../node_modules/@hashicorp/design-system-tokens/dist/products/css/tokens.css'
    ),
    extend: {},
  },
  plugins: [],
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2010 Intalio, Inc
 * Antoine Toulme
 *
 * 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.
 **/

params = window.location.search.toQueryParams();

if (params['profile'] === undefined) {
	params['profile'] = 'default';
}

ORYX = {};
ORYX.CONFIG = {};
ORYX.UUID = params['uuid'];
ORYX.PROFILE = params['profile'];

var segments = window.location.pathname.split("/").without("");

ORYX.CONFIG.ROOT_PATH = "/" + segments.first() + "/";
ORYX.PATH = ORYX.CONFIG.ROOT_PATH;

if (ORYX.UUID === undefined) {
	ORYX.UUID = segments.pop();
}

var addScript = function(url, urls, prefix, finalCallback){

    var script = document.createElement("script")
    script.type = "text/javascript";
    if (urls) {
    	// wait for the script to be loaded to add a new script to respect loading order.
    	if (script.readyState){  //IE
    		script.onreadystatechange = function(){
    			if (script.readyState == "loaded" || script.readyState == "complete"){
    				script.onreadystatechange = null;
    				addScriptSequential(urls, prefix, finalCallback);
    			}
    		}.bind(urls, prefix, finalCallback);
    	} else {  //Others
    		script.onload = function(){
    			addScriptSequential(urls, prefix, finalCallback);
    		}.bind(urls, prefix, finalCallback);
    	}
    }
    script.src = url;
    document.head.appendChild(script);

};

var addScriptSequential = function(urls, prefix, finalCallback) {
	if (urls.size() == 0) {
		if (finalCallback) {
			finalCallback();
		}
		return;
	}
	url = urls.shift();
	addScript(prefix + url, urls, prefix, finalCallback);

};

function loadLanguageFiles() {
	addScript(ORYX.PATH + "i18n/translation_en_us.js");
}

function loadProfile(nextStep) {
	// get the profile, ask for its info, load the files.

	new Ajax.Request(ORYX.PATH + "profile?name=" + params['profile'], {
		asynchronous: false,
		method: 'get',
		contentType: 'application/json',
		onSuccess: function(result) {
		profile = result.responseText.evalJSON();
		// set the title:
		document.getElementsByTagName('title').item(0).text = profile.title;

		// set the stencilset to use:
		ORYX.CONFIG.SSET= profile.stencilset;
		// set the stencilset extensions in effect:
		ORYX.CONFIG.SSEXTS= profile.ssexts.map(function(ssext) {
			// for each of the extensions, we get the extension file and return its contents.
			var contents = null;

			new Ajax.Request(ORYX.PATH + "stencilset/" + ssext, {
				asynchronous: false,
				method: 'get',
				contentType: 'application/json',
				onSuccess: function(result) {
				  contents = result.responseText.evalJSON();
			    },
			    onFailure: function(result) {
			    	alert("Could not load Process Designer"); //TODO even better logging ?
			    }
			});
			return contents;
		});
		//get the complete plugin info:
		new Ajax.Request(ORYX.PATH + "plugins", {
			asynchronous: false,
			method: 'get',
			contentType: 'application/json',
			onSuccess: function(result) {
			try {
			console.log(result.responseText)
			console.log(result.responseText.evalJSON())
			var allPlugins = {};
			result.responseText.evalJSON().each(function (p) {
				console.log(p)
				allPlugins[p.name] = p;
			}.bind(allPlugins));
			console.log(allPlugins);
			// install the current plugins
			ORYX.availablePlugins = [];
			profile.plugins.each(function(pluginName) {

				ORYX.availablePlugins.push(allPlugins[pluginName])
			}.bind(allPlugins));

			// now load the files as requested:
			addScriptSequential(profile.plugins.map(function(pluginName) { return pluginName + ".js"; }),
					ORYX.PATH + 'plugin/', nextStep);
			} catch(e) {
				console.log(e)
			}
		},
	    onFailure: function(result) {
	    	alert("Could not load Process Designer"); //TODO even better logging ?
	    }

		});

	},
	onFailure: function(result) {
		alert("Could not load Process Designer"); //TODO even better logging ?
	}
	});

}

//get the core files to load:
new Ajax.Request(ORYX.PATH + "env", {
	asynchronous: false,
	method: 'get',
	contentType: 'application/json',
	onSuccess: function(result) {
	  addScriptSequential(result.responseText.evalJSON().files, ORYX.PATH, function() {
		  loadLanguageFiles();
		  loadProfile(ORYX.load);

	  });
    },
    onFailure: function(result) {
	  alert("Could not load Process Designer"); //TODO even better logging ?
    }
});

<commit_msg>clean up<commit_after>/**
 * Copyright (c) 2010 Intalio, Inc
 * Antoine Toulme
 *
 * 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.
 **/

params = window.location.search.toQueryParams();

if (params['profile'] === undefined) {
	params['profile'] = 'default';
}

ORYX = {};
ORYX.CONFIG = {};
ORYX.UUID = params['uuid'];
ORYX.PROFILE = params['profile'];

var segments = window.location.pathname.split("/").without("");

ORYX.CONFIG.ROOT_PATH = "/" + segments.first() + "/";
ORYX.PATH = ORYX.CONFIG.ROOT_PATH;

if (ORYX.UUID === undefined) {
	ORYX.UUID = segments.pop();
}

var addScript = function(url, urls, prefix, finalCallback){

    var script = document.createElement("script")
    script.type = "text/javascript";
    if (urls) {
    	// wait for the script to be loaded to add a new script to respect loading order.
    	if (script.readyState){  //IE
    		script.onreadystatechange = function(){
    			if (script.readyState == "loaded" || script.readyState == "complete"){
    				script.onreadystatechange = null;
    				addScriptSequential(urls, prefix, finalCallback);
    			}
    		}.bind(urls, prefix, finalCallback);
    	} else {  //Others
    		script.onload = function(){
    			addScriptSequential(urls, prefix, finalCallback);
    		}.bind(urls, prefix, finalCallback);
    	}
    }
    script.src = url;
    document.head.appendChild(script);

};

var addScriptSequential = function(urls, prefix, finalCallback) {
	if (urls.size() == 0) {
		if (finalCallback) {
			finalCallback();
		}
		return;
	}
	url = urls.shift();
	addScript(prefix + url, urls, prefix, finalCallback);

};

function loadLanguageFiles() {
	addScript(ORYX.PATH + "i18n/translation_en_us.js");
}

function loadProfile(nextStep) {
	// get the profile, ask for its info, load the files.

	new Ajax.Request(ORYX.PATH + "profile?name=" + params['profile'], {
		asynchronous: false,
		method: 'get',
		contentType: 'application/json',
		onSuccess: function(result) {
		profile = result.responseText.evalJSON();
		// set the title:
		document.getElementsByTagName('title').item(0).text = profile.title;

		// set the stencilset to use:
		ORYX.CONFIG.SSET= profile.stencilset;
		// set the stencilset extensions in effect:
		ORYX.CONFIG.SSEXTS= profile.ssexts.map(function(ssext) {
			// for each of the extensions, we get the extension file and return its contents.
			var contents = null;

			new Ajax.Request(ORYX.PATH + "stencilset/" + ssext, {
				asynchronous: false,
				method: 'get',
				contentType: 'application/json',
				onSuccess: function(result) {
				  contents = result.responseText.evalJSON();
			    },
			    onFailure: function(result) {
			    	alert("Could not load Process Designer"); //TODO even better logging ?
			    }
			});
			return contents;
		});
		//get the complete plugin info:
		new Ajax.Request(ORYX.PATH + "plugins", {
			asynchronous: false,
			method: 'get',
			contentType: 'application/json',
			onSuccess: function(result) {
			var allPlugins = {};
			result.responseText.evalJSON().each(function (p) {
				allPlugins[p.name] = p;
			}.bind(allPlugins));
			// install the current plugins
			ORYX.availablePlugins = [];
			profile.plugins.each(function(pluginName) {
				ORYX.availablePlugins.push(allPlugins[pluginName]);
			}.bind(allPlugins));

			// now load the files as requested:
			addScriptSequential(profile.plugins.map(function(pluginName) { return pluginName + ".js"; }),
					ORYX.PATH + 'plugin/', nextStep);
		},
	    onFailure: function(result) {
	    	alert("Could not load Process Designer"); //TODO even better logging ?
	    }

		});

	},
	onFailure: function(result) {
		alert("Could not load Process Designer"); //TODO even better logging ?
	}
	});

}

//get the core files to load:
new Ajax.Request(ORYX.PATH + "env", {
	asynchronous: false,
	method: 'get',
	contentType: 'application/json',
	onSuccess: function(result) {
	  addScriptSequential(result.responseText.evalJSON().files, ORYX.PATH, function() {
		  loadLanguageFiles();
		  loadProfile(ORYX.load);

	  });
    },
    onFailure: function(result) {
	  alert("Could not load Process Designer"); //TODO even better logging ?
    }
});

<|endoftext|>


<commit_before>var Chat = {
    left : null,
    right: null,
    room: null,
    date: null,
    lastScroll: null,
    lastHeight: null,
    edit: false,

    // Chat state
    state: null,
    since: null,

    sendMessage: function(jid, muc)
    {
        var n = document.querySelector('#chat_textarea');
        var text = n.value;
        n.value = "";
        n.focus();
        MovimUtils.textareaAutoheight(n);

        localStorage.removeItem(n.dataset.jid + '_message');

        if(Chat.edit) {
            Chat.edit = false;
            Chat_ajaxCorrect(jid, encodeURIComponent(text));
        } else {
            Chat_ajaxSendMessage(jid, encodeURIComponent(text), muc);
        }
    },

    focus: function(jid)
    {
        if(jid) {
            document.querySelector('#chat_widget').dataset.jid = jid;
        }

        var textarea = document.querySelector('#chat_textarea');

        setTimeout(function() {
            var textarea = document.querySelector('#chat_textarea');
            textarea.value = localStorage.getItem(textarea.dataset.jid + '_message');
        }, 0); // Fix Me

        textarea.onkeydown = function(event) {
            if(event.keyCode == 38 && this.value == '') {
                Chat_ajaxLast(this.dataset.jid);
            } else if(event.keyCode == 40
            && (this.value == '' || Chat.edit == true)) {
                Chat.clearReplace();
            }
        };

        textarea.onkeypress = function(event) {
            if(event.keyCode == 13) {
                if(event.shiftKey) {
                    return;
                }
                Chat.state = 0;
                Chat.sendMessage(this.dataset.jid, Boolean(this.dataset.muc));

                return false;
            } else if(!Boolean(this.dataset.muc)) {
                if(Chat.state == 0 || Chat.state == 2) {
                    Chat.state = 1;
                    Chat_ajaxSendComposing(this.dataset.jid);
                    Chat.since = new Date().getTime();
                }
            }
        };

        textarea.onkeyup = function(event) {
            localStorage.setItem(this.dataset.jid + '_message', this.value);

            setTimeout(function()
            {
                var textarea = document.querySelector('#chat_textarea');

                if(textarea
                && !Boolean(textarea.dataset.muc)
                && Chat.state == 1
                && Chat.since + 5000 < new Date().getTime()) {
                    Chat.state = 2;
                    Chat_ajaxSendPaused(textarea.dataset.jid);
                }
            },5000);

            Chat.toggleAction(this.value.length);
        };

        textarea.oninput = function() {
            MovimUtils.textareaAutoheight(this);
        };

        if(document.documentElement.clientWidth > 1024) {
            document.querySelector('#chat_textarea').focus();
        }
    },
    setTextarea: function(value)
    {
        Chat.edit = true;
        var textarea = document.querySelector('#chat_textarea');
        textarea.value = value;
        MovimUtils.textareaAutoheight(textarea);

    },
    clearReplace: function()
    {
        Chat.edit = false;
        var textarea = document.querySelector('#chat_textarea');
        textarea.value = '';
        MovimUtils.textareaAutoheight(textarea);
    },
    notify : function(title, body, image)
    {
        if(document_focus == false) {
            movim_title_inc();
            movim_desktop_notification(title, body, image);
        }
    },
    empty : function()
    {
        Chat_ajaxGet();
    },
    setBubbles : function(left, right, room) {
        var div = document.createElement('div');

        div.innerHTML = left;
        Chat.left = div.firstChild.cloneNode(true);
        div.innerHTML = right;
        Chat.right = div.firstChild.cloneNode(true);
        div.innerHTML = room;
        Chat.room = div.firstChild.cloneNode(true);

        Chat.setScrollBehaviour();
    },
    setScrollBehaviour : function() {
        var discussion = document.querySelector('#chat_widget div.contained');
        discussion.onscroll = function() {
            if(discussion.dataset.muc != true) {
                if(this.scrollTop < 1) {
                    var chat = document.querySelector('#chat_widget');
                    Chat_ajaxGetHistory(chat.dataset.jid, Chat.date);
                }
            }
            Chat.lastHeight = this.clientHeight;
        };
    },
    appendMucMessages : function(date, messages) {
        id = MovimUtils.cleanupId(messages[0].jidfrom + '_conversation');
        var conversation = document.getElementById(id);
        datebox = Chat.room.cloneNode(true);
        datebox.innerHTML = date;

        /*if(conversation) {
            conversation.appendChild(datebox);
        }*/

        for(var i = 0, len = messages.length; i < len; ++i){
            bubble = Chat.room.cloneNode(true);

            if(messages[i].body.match(/^\/me/)) {
                bubble.querySelector('.message').className = 'message quote';
                messages[i].body = messages[i].body.substr(4);
            }

            if (messages[i].sticker != null) {
                MovimUtils.addClass(bubble.querySelector('p.message'), 'sticker');
                bubble.querySelector('p.message').appendChild(Chat.getStickerHtml(messages[i].sticker));
            } else {
                bubble.querySelector('p.message').innerHTML = messages[i].body.replace(/\r\n?|\n/g, '
');
            }

            if (messages[i].quoted) {
                bubble.querySelector('p.message').classList.add('quoted');
            }

            bubble.querySelector('span.info').innerHTML = messages[i].publishedPrepared;
            bubble.querySelector('p.user').className = 'user ' + messages[i].color;

            bubble.querySelector('p.user').onclick = function(n) {
                var textarea = document.querySelector('#chat_textarea');
                textarea.value = this.innerHTML + ', ' + textarea.value;
                textarea.focus();
            };

            bubble.querySelector('p.user').innerHTML = messages[i].resource;
            if(conversation) {
                conversation.appendChild(bubble);
            }
        }
    },
    appendMessagesWrapper : function(page, prepend) {
        Chat.date = null;
        if(page) {
            var scrolled = MovimTpl.isPanelScrolled();

            var discussion = document.querySelector('#chat_widget div.contained');

            if(discussion == null) return;

            Chat.lastScroll = discussion.scrollHeight;

            for(date in page) {
                if (page[date].constructor == Array) { //groupchat
                    if(!Chat.date) {
                        Chat.date = page[date][0].published;
                    }
                    Chat.appendMucMessages(date, page[date]);
                } else {
                    for(speakertime in page[date]) {
                        if(!Chat.date)
                            Chat.date = page[date][speakertime].published;
                        Chat.appendSpeaker(speakertime, page[date][speakertime], prepend);
                    }
                }
            }

            // Only scroll down if scroll was at the bottom before the new msg
            // => don't scroll if the user was reading previous messages
            if(scrolled && prepend !== true) {
                setTimeout(function() {
                    MovimTpl.scrollPanel();
                }, 20);
            }

            if(prepend) {
                // And we scroll where we were
                var scrollDiff = discussion.scrollHeight - Chat.lastScroll;
                discussion.scrollTop += scrollDiff;
                Chat.lastScroll = discussion.scrollHeight;
            }
        }
    },
    appendSpeaker : function(idjidtime, data, prepend) {
        var bubble = null,
            mergeMsg = false,
            msgStack,
            refBubble;
        var jidtime = idjidtime.substring(idjidtime.indexOf('<') + 1);

        if(prepend) {
            refBubble = document.querySelector("#chat_widget .contained li:first-child");
            msgStack = document.querySelector("[data-bubble='" + jidtime + "']");
        } else {
            refBubble = document.querySelector("#chat_widget .contained li:last-child");
            var stack = document.querySelectorAll("[data-bubble='" + jidtime + "']");
            msgStack = stack[stack.length-1];
        }

        if(msgStack != null
            && msgStack.parentNode == refBubble
            && data.file === null
            && data.sticker === null
            && !MovimUtils.hasClass(refBubble.querySelector('div.bubble'), "sticker")
            && !MovimUtils.hasClass(refBubble.querySelector('div.bubble'), "file")
        ){
            bubble = msgStack.parentNode;
            mergeMsg = true;
        } else {
            if (data.session == data.jidfrom) {
                bubble = Chat.right.cloneNode(true);
                id = data.jidto + '_conversation';
            } else {
                bubble = Chat.left.cloneNode(true);
                id = data.jidfrom + '_conversation';
            }

            id = MovimUtils.cleanupId(id);

            bubble.querySelector('div.bubble').setAttribute("data-bubble", jidtime);
            bubble.querySelector('div.bubble').setAttribute("data-publishedPrepared", data.publishedPrepared);
        }

        var msg = bubble.querySelector('div.bubble > div');
        var span = msg.getElementsByTagName('span')[0];
        var p = msg.getElementsByTagName('p')[0];

        // If there is already a msg in this bubble, create another div (next msg or replacement)
        if (bubble.querySelector('div.bubble p')
        && bubble.querySelector('div.bubble p').innerHTML != "") {
            msg = document.createElement("div");
            p = document.createElement("p");
            span = document.createElement("span");
            span.className = "info";
        }

        if (data.rtl) {
            bubble.querySelector('div.bubble').setAttribute('dir', 'rtl');
        }

        if (data.body.match(/^\/me\s/)) {
            p.className = 'quote';
            // Remove "/me " from beginning of body
            data.body = data.body.substr(4);
        }

        if (data.id != null) {
            msg.setAttribute("id", data.id);
            if (data.newid != null) {
                msg.setAttribute("id", data.newid);
            }
        }

        if (data.sticker != null) {
            MovimUtils.addClass(bubble.querySelector('div.bubble'), 'sticker');
            p.appendChild(Chat.getStickerHtml(data.sticker));
        } else {
            p.innerHTML = data.body.replace(/\r\n?|\n/g, '
');
        }

        if (data.file != null) {
            MovimUtils.addClass(bubble.querySelector('div.bubble'), 'file');
            p.appendChild(Chat.getFileHtml(data.file, data.sticker));
        }

        if (data.edited) {
            span.appendChild(Chat.getEditedIcoHtml());
        }
        if (data.delivered) {
            span.appendChild(Chat.getDeliveredIcoHtml(data.delivered));
        }

        msg.appendChild(p);
        msg.appendChild(span);

        var elem = document.getElementById(data.id);
        if (elem) {
            elem.parentElement.replaceChild(msg, elem);
            mergeMsg = true;
        } else {
            if(prepend)
                bubble.querySelector('div.bubble').insertBefore( msg, bubble.querySelector('div.bubble').firstChild );
            else
                bubble.querySelector('div.bubble').appendChild(msg);
        }

        if(prepend){
            Chat.date = data.published;

            // We prepend
            if (!mergeMsg)
                MovimTpl.prepend("#" + id, bubble.outerHTML);
        } else {
            if (!mergeMsg) {
                MovimTpl.append("#" + id, bubble.outerHTML);
            }
        }
    },
    getStickerHtml: function(sticker) {
        var img = document.createElement("img");
        if(sticker.url) {
            img.setAttribute("src", sticker.url);
            if(sticker.width)  img.setAttribute("width", sticker.width);
            if(sticker.height)
                img.setAttribute("height", sticker.height);
            else {
                img.setAttribute("height", "150");
            }
        }

        if(sticker.picture) {
            var a = document.createElement("a");
            a.setAttribute("href", sticker.url);
            a.setAttribute("target", "_blank");
            a.appendChild(img);
            return a;
        } else {
            return img;
        }
    },
    getFileHtml: function(file, sticker) {
        var div = document.createElement("div");
        div.setAttribute("class", "file");

        var a = document.createElement("a");
        if(sticker == null) {
            a.innerHTML = file.name;
        }
        a.setAttribute("href", file.uri);
        a.setAttribute("target", "_blank");

        div.appendChild(a);

        var span = document.createElement("span");
        span.innerHTML = file.size;
        span.setAttribute("class", "size");

        a.appendChild(span);

        return div;
    },
    getEditedIcoHtml: function() {
        var i = document.createElement("i");
        i.setAttribute("class", "zmdi zmdi-edit");
        return i;
    },
    getDeliveredIcoHtml: function(delivered) {
        var i = document.createElement("i");
        i.setAttribute("class", "zmdi zmdi-check");
        i.setAttribute("title", delivered);
        return i;
    },
    toggleAction: function(l) {
        var send_button = document.querySelector(".chat_box span[data-jid]");
        var attachment_button = document.querySelector(".chat_box span.control:not([data-jid])");
        if(send_button && attachment_button) {
            if(l > 0){
                MovimUtils.showElement(send_button);
                MovimUtils.hideElement(attachment_button);
            } else {
                MovimUtils.showElement(attachment_button);
                MovimUtils.hideElement(send_button);
            }
        }
    }
};

MovimWebsocket.attach(function() {
    var jid = MovimUtils.urlParts().params[0];
    var room = MovimUtils.urlParts().params[1];
    if(jid) {
        MovimTpl.showPanel();

        if(room) {
            Chat_ajaxGetRoom(jid);
        } else {
            Chat_ajaxGet(jid);
            Notification.current('chat|' + jid);
        }
    }
});

if(typeof Upload != 'undefined') {
    Upload.attach(function(file) {
        var textarea = document.querySelector('#chat_textarea');

        Chat_ajaxSendMessage(textarea.dataset.jid, false, Boolean(textarea.dataset.muc), false, false, file);
    });
}

document.addEventListener('focus', function() {
    var textarea = document.querySelector('#chat_textarea');
    if(textarea) textarea.focus();
});

window.addEventListener('resize', function() {
    var discussion = document.querySelector('#chat_widget div.contained');
    if(discussion) {
        discussion.scrollTop += Chat.lastHeight - discussion.clientHeight;
        Chat.lastHeight = discussion.clientHeight;
    }
});

var state = 0;
<commit_msg>Small cleanup<commit_after>var Chat = {
    left : null,
    right: null,
    room: null,
    date: null,
    lastScroll: null,
    lastHeight: null,
    edit: false,

    // Chat state
    state: null,
    since: null,

    sendMessage: function(jid, muc)
    {
        var n = document.querySelector('#chat_textarea');
        var text = n.value;
        n.value = "";
        n.focus();
        MovimUtils.textareaAutoheight(n);

        localStorage.removeItem(n.dataset.jid + '_message');

        if(Chat.edit) {
            Chat.edit = false;
            Chat_ajaxCorrect(jid, encodeURIComponent(text));
        } else {
            Chat_ajaxSendMessage(jid, encodeURIComponent(text), muc);
        }
    },

    focus: function(jid)
    {
        if(jid) {
            document.querySelector('#chat_widget').dataset.jid = jid;
        }

        var textarea = document.querySelector('#chat_textarea');

        setTimeout(function() {
            var textarea = document.querySelector('#chat_textarea');
            textarea.value = localStorage.getItem(textarea.dataset.jid + '_message');
        }, 0); // Fix Me

        textarea.onkeydown = function(event) {
            if(event.keyCode == 38 && this.value == '') {
                Chat_ajaxLast(this.dataset.jid);
            } else if(event.keyCode == 40
            && (this.value == '' || Chat.edit == true)) {
                Chat.clearReplace();
            }
        };

        textarea.onkeypress = function(event) {
            if(event.keyCode == 13) {
                if(event.shiftKey) {
                    return;
                }
                Chat.state = 0;
                Chat.sendMessage(this.dataset.jid, Boolean(this.dataset.muc));

                return false;
            } else if(!Boolean(this.dataset.muc)) {
                if(Chat.state == 0 || Chat.state == 2) {
                    Chat.state = 1;
                    Chat_ajaxSendComposing(this.dataset.jid);
                    Chat.since = new Date().getTime();
                }
            }
        };

        textarea.onkeyup = function(event) {
            localStorage.setItem(this.dataset.jid + '_message', this.value);

            setTimeout(function()
            {
                var textarea = document.querySelector('#chat_textarea');

                if(textarea
                && !Boolean(textarea.dataset.muc)
                && Chat.state == 1
                && Chat.since + 5000 < new Date().getTime()) {
                    Chat.state = 2;
                    Chat_ajaxSendPaused(textarea.dataset.jid);
                }
            },5000);

            Chat.toggleAction(this.value.length);
        };

        textarea.oninput = function() {
            MovimUtils.textareaAutoheight(this);
        };

        if(document.documentElement.clientWidth > 1024) {
            document.querySelector('#chat_textarea').focus();
        }
    },
    setTextarea: function(value)
    {
        Chat.edit = true;
        var textarea = document.querySelector('#chat_textarea');
        textarea.value = value;
        MovimUtils.textareaAutoheight(textarea);

    },
    clearReplace: function()
    {
        Chat.edit = false;
        var textarea = document.querySelector('#chat_textarea');
        textarea.value = '';
        MovimUtils.textareaAutoheight(textarea);
    },
    notify : function(title, body, image)
    {
        if(document_focus == false) {
            movim_title_inc();
            movim_desktop_notification(title, body, image);
        }
    },
    empty : function()
    {
        Chat_ajaxGet();
    },
    setBubbles : function(left, right, room) {
        var div = document.createElement('div');

        div.innerHTML = left;
        Chat.left = div.firstChild.cloneNode(true);
        div.innerHTML = right;
        Chat.right = div.firstChild.cloneNode(true);
        div.innerHTML = room;
        Chat.room = div.firstChild.cloneNode(true);

        Chat.setScrollBehaviour();
    },
    setScrollBehaviour : function() {
        var discussion = document.querySelector('#chat_widget div.contained');
        discussion.onscroll = function() {
            if(discussion.dataset.muc != true) {
                if(this.scrollTop < 1) {
                    var chat = document.querySelector('#chat_widget');
                    Chat_ajaxGetHistory(chat.dataset.jid, Chat.date);
                }
            }
            Chat.lastHeight = this.clientHeight;
        };
    },
    appendMucMessages : function(date, messages) {
        id = MovimUtils.cleanupId(messages[0].jidfrom + '_conversation');
        var conversation = document.getElementById(id);
        datebox = Chat.room.cloneNode(true);
        datebox.innerHTML = date;

        /*if(conversation) {
            conversation.appendChild(datebox);
        }*/

        for(var i = 0, len = messages.length; i < len; ++i){
            bubble = Chat.room.cloneNode(true);

            if(messages[i].body.match(/^\/me/)) {
                bubble.querySelector('.message').className = 'message quote';
                messages[i].body = messages[i].body.substr(4);
            }

            if (messages[i].sticker != null) {
                MovimUtils.addClass(bubble.querySelector('p.message'), 'sticker');
                bubble.querySelector('p.message').appendChild(Chat.getStickerHtml(messages[i].sticker));
            } else {
                bubble.querySelector('p.message').innerHTML = messages[i].body.replace(/\r\n?|\n/g, '
');
            }

            if (messages[i].quoted) {
                bubble.querySelector('p.message').classList.add('quoted');
            }

            bubble.querySelector('span.info').innerHTML = messages[i].publishedPrepared;
            bubble.querySelector('p.user').className = 'user ' + messages[i].color;

            bubble.querySelector('p.user').onclick = function(n) {
                var textarea = document.querySelector('#chat_textarea');
                textarea.value = this.innerHTML + ', ' + textarea.value;
                textarea.focus();
            };

            bubble.querySelector('p.user').innerHTML = messages[i].resource;
            if(conversation) {
                conversation.appendChild(bubble);
            }
        }
    },
    appendMessagesWrapper : function(page, prepend) {
        Chat.date = null;
        if(page) {
            var scrolled = MovimTpl.isPanelScrolled();

            var discussion = document.querySelector('#chat_widget div.contained');

            if(discussion == null) return;

            Chat.lastScroll = discussion.scrollHeight;

            for(date in page) {
                if (page[date].constructor == Array) { //groupchat
                    if(!Chat.date) {
                        Chat.date = page[date][0].published;
                    }
                    Chat.appendMucMessages(date, page[date]);
                } else {
                    for(speakertime in page[date]) {
                        if(!Chat.date)
                            Chat.date = page[date][speakertime].published;
                        Chat.appendSpeaker(speakertime, page[date][speakertime], prepend);
                    }
                }
            }

            // Only scroll down if scroll was at the bottom before the new msg
            // => don't scroll if the user was reading previous messages
            if(scrolled && prepend !== true) {
                setTimeout(function() {
                    MovimTpl.scrollPanel();
                }, 20);
            }

            if(prepend) {
                // And we scroll where we were
                var scrollDiff = discussion.scrollHeight - Chat.lastScroll;
                discussion.scrollTop += scrollDiff;
                Chat.lastScroll = discussion.scrollHeight;
            }
        }
    },
    appendSpeaker : function(idjidtime, data, prepend) {
        var bubble = null,
            mergeMsg = false,
            msgStack,
            refBubble;
        var jidtime = idjidtime.substring(idjidtime.indexOf('<') + 1);

        if(prepend) {
            refBubble = document.querySelector("#chat_widget .contained li:first-child");
            msgStack = document.querySelector("[data-bubble='" + jidtime + "']");
        } else {
            refBubble = document.querySelector("#chat_widget .contained li:last-child");
            var stack = document.querySelectorAll("[data-bubble='" + jidtime + "']");
            msgStack = stack[stack.length-1];
        }

        if(msgStack != null
            && msgStack.parentNode == refBubble
            && data.file === null
            && data.sticker === null
            && !MovimUtils.hasClass(refBubble.querySelector('div.bubble'), "sticker")
            && !MovimUtils.hasClass(refBubble.querySelector('div.bubble'), "file")
        ){
            bubble = msgStack.parentNode;
            mergeMsg = true;
        } else {
            if (data.session == data.jidfrom) {
                bubble = Chat.right.cloneNode(true);
                id = data.jidto + '_conversation';
            } else {
                bubble = Chat.left.cloneNode(true);
                id = data.jidfrom + '_conversation';
            }

            id = MovimUtils.cleanupId(id);

            bubble.querySelector('div.bubble').dataset.bubble = jidtime;
            bubble.querySelector('div.bubble').dataset.publishedprepared = data.publishedPrepared;
        }

        var msg = bubble.querySelector('div.bubble > div');
        var span = msg.getElementsByTagName('span')[0];
        var p = msg.getElementsByTagName('p')[0];

        // If there is already a msg in this bubble, create another div (next msg or replacement)
        if (bubble.querySelector('div.bubble p')
        && bubble.querySelector('div.bubble p').innerHTML != "") {
            msg = document.createElement("div");
            p = document.createElement("p");
            span = document.createElement("span");
            span.className = "info";
        }

        if (data.rtl) {
            bubble.querySelector('div.bubble').setAttribute('dir', 'rtl');
        }

        if (data.body.match(/^\/me\s/)) {
            p.className = 'quote';
            // Remove "/me " from beginning of body
            data.body = data.body.substr(4);
        }

        if (data.id != null) {
            msg.setAttribute("id", data.id);
            if (data.newid != null) {
                msg.setAttribute("id", data.newid);
            }
        }

        if (data.sticker != null) {
            MovimUtils.addClass(bubble.querySelector('div.bubble'), 'sticker');
            p.appendChild(Chat.getStickerHtml(data.sticker));
        } else {
            p.innerHTML = data.body.replace(/\r\n?|\n/g, '
');
        }

        if (data.file != null) {
            MovimUtils.addClass(bubble.querySelector('div.bubble'), 'file');
            p.appendChild(Chat.getFileHtml(data.file, data.sticker));
        }

        if (data.edited) {
            span.appendChild(Chat.getEditedIcoHtml());
        }
        if (data.delivered) {
            span.appendChild(Chat.getDeliveredIcoHtml(data.delivered));
        }

        msg.appendChild(p);
        msg.appendChild(span);

        var elem = document.getElementById(data.id);
        if (elem) {
            elem.parentElement.replaceChild(msg, elem);
            mergeMsg = true;
        } else {
            if(prepend)
                bubble.querySelector('div.bubble').insertBefore( msg, bubble.querySelector('div.bubble').firstChild );
            else
                bubble.querySelector('div.bubble').appendChild(msg);
        }

        if(prepend){
            Chat.date = data.published;

            // We prepend
            if (!mergeMsg)
                MovimTpl.prepend("#" + id, bubble.outerHTML);
        } else {
            if (!mergeMsg) {
                MovimTpl.append("#" + id, bubble.outerHTML);
            }
        }
    },
    getStickerHtml: function(sticker) {
        var img = document.createElement("img");
        if(sticker.url) {
            img.setAttribute("src", sticker.url);
            if(sticker.width)  img.setAttribute("width", sticker.width);
            if(sticker.height)
                img.setAttribute("height", sticker.height);
            else {
                img.setAttribute("height", "150");
            }
        }

        if(sticker.picture) {
            var a = document.createElement("a");
            a.setAttribute("href", sticker.url);
            a.setAttribute("target", "_blank");
            a.appendChild(img);
            return a;
        } else {
            return img;
        }
    },
    getFileHtml: function(file, sticker) {
        var div = document.createElement("div");
        div.setAttribute("class", "file");

        var a = document.createElement("a");
        if(sticker == null) {
            a.innerHTML = file.name;
        }
        a.setAttribute("href", file.uri);
        a.setAttribute("target", "_blank");

        div.appendChild(a);

        var span = document.createElement("span");
        span.innerHTML = file.size;
        span.setAttribute("class", "size");

        a.appendChild(span);

        return div;
    },
    getEditedIcoHtml: function() {
        var i = document.createElement("i");
        i.setAttribute("class", "zmdi zmdi-edit");
        return i;
    },
    getDeliveredIcoHtml: function(delivered) {
        var i = document.createElement("i");
        i.setAttribute("class", "zmdi zmdi-check");
        i.setAttribute("title", delivered);
        return i;
    },
    toggleAction: function(l) {
        var send_button = document.querySelector(".chat_box span[data-jid]");
        var attachment_button = document.querySelector(".chat_box span.control:not([data-jid])");
        if(send_button && attachment_button) {
            if(l > 0){
                MovimUtils.showElement(send_button);
                MovimUtils.hideElement(attachment_button);
            } else {
                MovimUtils.showElement(attachment_button);
                MovimUtils.hideElement(send_button);
            }
        }
    }
};

MovimWebsocket.attach(function() {
    var jid = MovimUtils.urlParts().params[0];
    var room = MovimUtils.urlParts().params[1];
    if(jid) {
        MovimTpl.showPanel();

        if(room) {
            Chat_ajaxGetRoom(jid);
        } else {
            Chat_ajaxGet(jid);
            Notification.current('chat|' + jid);
        }
    }
});

if(typeof Upload != 'undefined') {
    Upload.attach(function(file) {
        var textarea = document.querySelector('#chat_textarea');

        Chat_ajaxSendMessage(textarea.dataset.jid, false, Boolean(textarea.dataset.muc), false, false, file);
    });
}

document.addEventListener('focus', function() {
    var textarea = document.querySelector('#chat_textarea');
    if(textarea) textarea.focus();
});

window.addEventListener('resize', function() {
    var discussion = document.querySelector('#chat_widget div.contained');
    if(discussion) {
        discussion.scrollTop += Chat.lastHeight - discussion.clientHeight;
        Chat.lastHeight = discussion.clientHeight;
    }
});

var state = 0;
<|endoftext|>


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

/**
 * A component handler interface using the revealing module design pattern.
 * More details on this design pattern here:
 * https://github.com/jasonmayes/mdl-component-design-pattern
 * @author Jason Mayes.
 */
/* exported componentHandler */
var componentHandler = (function() {
  'use strict';

  var registeredComponents_ = [];
  var createdComponents_ = [];
  var downgradeMethod_ = 'mdlDowngrade_';
  var componentConfigProperty_ = 'mdlComponentConfigInternal_';

  /**
   * Searches registered components for a class we are interested in using.
   * Optionally replaces a match with passed object if specified.
   * @param {string} name The name of a class we want to use.
   * @param {Object=} optReplace Optional object to replace match with.
   * @return {Object | boolean}
   * @private
   */
  function findRegisteredClass_(name, optReplace) {
    for (var i = 0; i < registeredComponents_.length; i++) {
      if (registeredComponents_[i].className === name) {
        if (optReplace !== undefined) {
          registeredComponents_[i] = optReplace;
        }
        return registeredComponents_[i];
      }
    }
    return false;
  }

  /**
   * Returns an array of the classNames of the upgraded classes on the element.
   * @param {HTMLElement} element The element to fetch data from.
   * @return {Array<string>}
   * @private
   */
  function getUpgradedListOfElement_(element) {
    var dataUpgraded = element.getAttribute('data-upgraded');
    // Use `['']` as default value to conform the `,name,name...` style.
    return dataUpgraded === null ? [''] : dataUpgraded.split(',');
  }

  /**
   * Returns true if the given element has already been upgraded for the given
   * class.
   * @param {HTMLElement} element The element we want to check.
   * @param {string} jsClass The class to check for.
   * @return boolean
   * @private
   */
  function isElementUpgraded_(element, jsClass) {
    var upgradedList = getUpgradedListOfElement_(element);
    return upgradedList.indexOf(jsClass) !== -1;
  }

  /**
   * Searches existing DOM for elements of our component type and upgrades them
   * if they have not already been upgraded.
   * @param {!string=} optJsClass the programatic name of the element class we
   * need to create a new instance of.
   * @param {!string=} optCssClass the name of the CSS class elements of this
   * type will have.
   */
  function upgradeDomInternal(optJsClass, optCssClass) {
    if (optJsClass === undefined && optCssClass === undefined) {
      for (var i = 0; i < registeredComponents_.length; i++) {
        upgradeDomInternal(registeredComponents_[i].className,
            registeredComponents_[i].cssClass);
      }
    } else {
      var jsClass = /** @type {!string} */ (optJsClass);
      if (optCssClass === undefined) {
        var registeredClass = findRegisteredClass_(jsClass);
        if (registeredClass) {
          optCssClass = registeredClass.cssClass;
        }
      }

      var elements = document.querySelectorAll('.' + optCssClass);
      for (var n = 0; n < elements.length; n++) {
        upgradeElementInternal(elements[n], jsClass);
      }
    }
  }

  /**
   * Upgrades a specific element rather than all in the DOM.
   * @param {HTMLElement} element The element we wish to upgrade.
   * @param {!string=} optJsClass Optional name of the class we want to upgrade
   * the element to.
   */
  function upgradeElementInternal(element, optJsClass) {
    // Verify argument type.
    if (!(typeof element === 'object' && element instanceof Element)) {
      throw new Error('Invalid argument provided to upgrade MDL element.');
    }
    var upgradedList = getUpgradedListOfElement_(element);
    var classesToUpgrade = [];
    // If jsClass is not provided scan the registered components to find the
    // ones matching the element's CSS classList.
    if (!optJsClass) {
      var classList = element.classList;
      registeredComponents_.forEach(function (component) {
        // Match CSS & Not to be upgraded & Not upgraded.
        if (classList.contains(component.cssClass) &&
            classesToUpgrade.indexOf(component) === -1 &&
            !isElementUpgraded_(element, component.className)) {
          classesToUpgrade.push(component);
        }
      });
    } else if (!isElementUpgraded_(element, optJsClass)) {
      classesToUpgrade.push(findRegisteredClass_(optJsClass));
    }

    // Upgrade the element for each classes.
    for (var i = 0, n = classesToUpgrade.length, registeredClass; i < n; i++) {
      registeredClass = classesToUpgrade[i];
      if (registeredClass) {
        // Mark element as upgraded.
        upgradedList.push(registeredClass.className);
        element.setAttribute('data-upgraded', upgradedList.join(','));
        var instance = new registeredClass.classConstructor(element);
        instance[componentConfigProperty_] = registeredClass;
        createdComponents_.push(instance);
        // Call any callbacks the user has registered with this component type.
        for (var j = 0, m = registeredClass.callbacks.length; j < m; j++) {
          registeredClass.callbacks[j](element);
        }

        if (registeredClass.widget) {
          // Assign per element instance for control over API
          element[registeredClass.className] = instance;
        }
      } else {
        throw new Error(
          'Unable to find a registered component for the given class.');
      }

      var ev = document.createEvent('Events');
      ev.initEvent('mdl-componentupgraded', true, true);
      element.dispatchEvent(ev);
    }
  }

  /**
   * Upgrades a specific list of elements rather than all in the DOM.
   * @param {HTMLElement | Array<HTMLElement> | NodeList | HTMLCollection} elements
   * The elements we wish to upgrade.
   */
  function upgradeElementsInternal(elements) {
    if (!Array.isArray(elements)) {
      if (typeof elements.item === 'function') {
        elements = Array.prototype.slice.call(elements);
      } else {
        elements = [elements];
      }
    }
    for (var i = 0, n = elements.length, element; i < n; i++) {
      element = elements[i];
      if (element instanceof HTMLElement) {
        if (element.children.length > 0) {
          upgradeElementsInternal(element.children);
        }
        upgradeElementInternal(element);
      }
    }
  }

  /**
   * Registers a class for future use and attempts to upgrade existing DOM.
   * @param {Object} config An object containing:
   * {constructor: Constructor, classAsString: string, cssClass: string}
   */
  function registerInternal(config) {
    var newConfig = {
      'classConstructor': config.constructor,
      'className': config.classAsString,
      'cssClass': config.cssClass,
      'widget': config.widget === undefined ? true : config.widget,
      'callbacks': []
    };

    registeredComponents_.forEach(function(item) {
      if (item.cssClass === newConfig.cssClass) {
        throw new Error('The provided cssClass has already been registered.');
      }
      if (item.className === newConfig.className) {
        throw new Error('The provided className has already been registered');
      }
    });

    if (config.constructor.prototype
        .hasOwnProperty(componentConfigProperty_)) {
      throw new Error(
        'MDL component classes must not have ' + componentConfigProperty_ +
          ' defined as a property.');
    }

    var found = findRegisteredClass_(config.classAsString, newConfig);

    if (!found) {
      registeredComponents_.push(newConfig);
    }
  }

  /**
   * Allows user to be alerted to any upgrades that are performed for a given
   * component type
   * @param {string} jsClass The class name of the MDL component we wish
   * to hook into for any upgrades performed.
   * @param {!Function} callback The function to call upon an upgrade. This
   * function should expect 1 parameter - the HTMLElement which got upgraded.
   */
  function registerUpgradedCallbackInternal(jsClass, callback) {
    var regClass = findRegisteredClass_(jsClass);
    if (regClass) {
      regClass.callbacks.push(callback);
    }
  }

  /**
   * Upgrades all registered components found in the current DOM. This is
   * automatically called on window load.
   */
  function upgradeAllRegisteredInternal() {
    for (var n = 0; n < registeredComponents_.length; n++) {
      upgradeDomInternal(registeredComponents_[n].className);
    }
  }

  /**
   * Finds a created component by a given DOM node.
   *
   * @param {!Element} node
   * @return {*}
   */
  function findCreatedComponentByNodeInternal(node) {
    for (var n = 0; n < createdComponents_.length; n++) {
      var component = createdComponents_[n];
      if (component.element_ === node) {
        return component;
      }
    }
  }

  /**
   * Check the component for the downgrade method.
   * Execute if found.
   * Remove component from createdComponents list.
   *
   * @param {*} component
   */
  function deconstructComponentInternal(component) {
    if (component &&
        component[componentConfigProperty_]
          .classConstructor.prototype
          .hasOwnProperty(downgradeMethod_)) {
      component[downgradeMethod_]();
      var componentIndex = createdComponents_.indexOf(component);
      createdComponents_.splice(componentIndex, 1);

      var upgrades = component.element_.getAttribute('data-upgraded').split(',');
      var componentPlace = upgrades.indexOf(
          component[componentConfigProperty_].classAsString);
      upgrades.splice(componentPlace, 1);
      component.element_.setAttribute('data-upgraded', upgrades.join(','));

      var ev = document.createEvent('Events');
      ev.initEvent('mdl-componentdowngraded', true, true);
      component.element_.dispatchEvent(ev);
    }
  }

  /**
   * Downgrade either a given node, an array of nodes, or a NodeList.
   *
   * @param {*} nodes
   */
  function downgradeNodesInternal(nodes) {
    var downgradeNode = function(node) {
      deconstructComponentInternal(findCreatedComponentByNodeInternal(node));
    };
    if (nodes instanceof Array || nodes instanceof NodeList) {
      for (var n = 0; n < nodes.length; n++) {
        downgradeNode(nodes[n]);
      }
    } else if (nodes instanceof Node) {
      downgradeNode(nodes);
    } else {
      throw new Error('Invalid argument provided to downgrade MDL nodes.');
    }
  }

  // Now return the functions that should be made public with their publicly
  // facing names...
  return {
    upgradeDom: upgradeDomInternal,
    upgradeElement: upgradeElementInternal,
    upgradeElements: upgradeElementsInternal,
    upgradeAllRegistered: upgradeAllRegisteredInternal,
    registerUpgradedCallback: registerUpgradedCallbackInternal,
    register: registerInternal,
    downgradeElements: downgradeNodesInternal
  };
})();

window.addEventListener('load', function() {
  'use strict';

  /**
   * Performs a "Cutting the mustard" test. If the browser supports the features
   * tested, adds a mdl-js class to the <html> element. It then upgrades all MDL
   * components requiring JavaScript.
   */
  if ('classList' in document.createElement('div') &&
      'querySelector' in document &&
      'addEventListener' in window && Array.prototype.forEach) {
    document.documentElement.classList.add('mdl-js');
    componentHandler.upgradeAllRegistered();
  } else {
    componentHandler.upgradeElement =
        componentHandler.register = function() {};
  }
});
<commit_msg>JSDoc type annotation fixes<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @typedef {{
 *   constructor: !Function,
 *   className: string,
 *   cssClass: string,
 *   widget: string,
 *   callbacks: !Array<function(!HTMLElement)>
 * }}
 */
var ComponentConfig;  // jshint ignore:line

/**
 * @typedef {{
 *   element_: !HTMLElement,
 *   className: string,
 *   classAsString: string,
 *   cssClass: string,
 *   widget: string
 * }}
 */
var Component;  // jshint ignore:line

/**
 * A component handler interface using the revealing module design pattern.
 * More details on this design pattern here:
 * https://github.com/jasonmayes/mdl-component-design-pattern
 * @author Jason Mayes.
 */
/* exported componentHandler */
var componentHandler = (function() {
  'use strict';

  /** @type {!Array<ComponentConfig>} */ var registeredComponents_ = [];
  /** @type {!Array<Component>} */ var createdComponents_ = [];
  var downgradeMethod_ = 'mdlDowngrade_';
  var componentConfigProperty_ = 'mdlComponentConfigInternal_';

  /**
   * Searches registered components for a class we are interested in using.
   * Optionally replaces a match with passed object if specified.
   * @param {string} name The name of a class we want to use.
   * @param {ComponentConfig=} optReplace Optional object to replace match with.
   * @return {(!Object | boolean)}
   * @private
   */
  function findRegisteredClass_(name, optReplace) {
    for (var i = 0; i < registeredComponents_.length; i++) {
      if (registeredComponents_[i].className === name) {
        if (optReplace !== undefined) {
          registeredComponents_[i] = optReplace;
        }
        return registeredComponents_[i];
      }
    }
    return false;
  }

  /**
   * Returns an array of the classNames of the upgraded classes on the element.
   * @param {!HTMLElement} element The element to fetch data from.
   * @return {!Array<string>}
   * @private
   */
  function getUpgradedListOfElement_(element) {
    var dataUpgraded = element.getAttribute('data-upgraded');
    // Use `['']` as default value to conform the `,name,name...` style.
    return dataUpgraded === null ? [''] : dataUpgraded.split(',');
  }

  /**
   * Returns true if the given element has already been upgraded for the given
   * class.
   * @param {!HTMLElement} element The element we want to check.
   * @param {string} jsClass The class to check for.
   * @return boolean
   * @private
   */
  function isElementUpgraded_(element, jsClass) {
    var upgradedList = getUpgradedListOfElement_(element);
    return upgradedList.indexOf(jsClass) !== -1;
  }

  /**
   * Searches existing DOM for elements of our component type and upgrades them
   * if they have not already been upgraded.
   * @param {string=} optJsClass the programatic name of the element class we
   * need to create a new instance of.
   * @param {string=} optCssClass the name of the CSS class elements of this
   * type will have.
   */
  function upgradeDomInternal(optJsClass, optCssClass) {
    if (optJsClass === undefined && optCssClass === undefined) {
      for (var i = 0; i < registeredComponents_.length; i++) {
        upgradeDomInternal(registeredComponents_[i].className,
            registeredComponents_[i].cssClass);
      }
    } else {
      var jsClass = /** @type {string} */ (optJsClass);
      if (optCssClass === undefined) {
        var registeredClass = findRegisteredClass_(jsClass);
        if (registeredClass) {
          optCssClass = registeredClass.cssClass;
        }
      }

      var elements = document.querySelectorAll('.' + optCssClass);
      for (var n = 0; n < elements.length; n++) {
        upgradeElementInternal(elements[n], jsClass);
      }
    }
  }

  /**
   * Upgrades a specific element rather than all in the DOM.
   * @param {!HTMLElement} element The element we wish to upgrade.
   * @param {string=} optJsClass Optional name of the class we want to upgrade
   * the element to.
   */
  function upgradeElementInternal(element, optJsClass) {
    // Verify argument type.
    if (!(typeof element === 'object' && element instanceof Element)) {
      throw new Error('Invalid argument provided to upgrade MDL element.');
    }
    var upgradedList = getUpgradedListOfElement_(element);
    var classesToUpgrade = [];
    // If jsClass is not provided scan the registered components to find the
    // ones matching the element's CSS classList.
    if (!optJsClass) {
      var classList = element.classList;
      registeredComponents_.forEach(function(component) {
        // Match CSS & Not to be upgraded & Not upgraded.
        if (classList.contains(component.cssClass) &&
            classesToUpgrade.indexOf(component) === -1 &&
            !isElementUpgraded_(element, component.className)) {
          classesToUpgrade.push(component);
        }
      });
    } else if (!isElementUpgraded_(element, optJsClass)) {
      classesToUpgrade.push(findRegisteredClass_(optJsClass));
    }

    // Upgrade the element for each classes.
    for (var i = 0, n = classesToUpgrade.length, registeredClass; i < n; i++) {
      registeredClass = classesToUpgrade[i];
      if (registeredClass) {
        // Mark element as upgraded.
        upgradedList.push(registeredClass.className);
        element.setAttribute('data-upgraded', upgradedList.join(','));
        var instance = new registeredClass.classConstructor(element);
        instance[componentConfigProperty_] = registeredClass;
        createdComponents_.push(instance);
        // Call any callbacks the user has registered with this component type.
        for (var j = 0, m = registeredClass.callbacks.length; j < m; j++) {
          registeredClass.callbacks[j](element);
        }

        if (registeredClass.widget) {
          // Assign per element instance for control over API
          element[registeredClass.className] = instance;
        }
      } else {
        throw new Error(
          'Unable to find a registered component for the given class.');
      }

      var ev = document.createEvent('Events');
      ev.initEvent('mdl-componentupgraded', true, true);
      element.dispatchEvent(ev);
    }
  }

  /**
   * Upgrades a specific list of elements rather than all in the DOM.
   * @param {(!HTMLElement | !Array<!HTMLElement> | !NodeList | !HTMLCollection)} elements
   * The elements we wish to upgrade.
   */
  function upgradeElementsInternal(elements) {
    if (!Array.isArray(elements)) {
      if (typeof elements.item === 'function') {
        elements = Array.prototype.slice.call(/** @type {Array} */ (elements));
      } else {
        elements = [elements];
      }
    }
    for (var i = 0, n = elements.length, element; i < n; i++) {
      element = elements[i];
      if (element instanceof HTMLElement) {
        if (element.children.length > 0) {
          upgradeElementsInternal(element.children);
        }
        upgradeElementInternal(element);
      }
    }
  }

  /**
   * Registers a class for future use and attempts to upgrade existing DOM.
   * @param {{constructor: !Function, classAsString: string, cssClass: string, widget: string}} config
   */
  function registerInternal(config) {
    var newConfig = /** @type {ComponentConfig} */ ({
      'classConstructor': config.constructor,
      'className': config.classAsString,
      'cssClass': config.cssClass,
      'widget': config.widget === undefined ? true : config.widget,
      'callbacks': []
    });

    registeredComponents_.forEach(function(item) {
      if (item.cssClass === newConfig.cssClass) {
        throw new Error('The provided cssClass has already been registered.');
      }
      if (item.className === newConfig.className) {
        throw new Error('The provided className has already been registered');
      }
    });

    if (config.constructor.prototype
        .hasOwnProperty(componentConfigProperty_)) {
      throw new Error(
          'MDL component classes must not have ' + componentConfigProperty_ +
          ' defined as a property.');
    }

    var found = findRegisteredClass_(config.classAsString, newConfig);

    if (!found) {
      registeredComponents_.push(newConfig);
    }
  }

  /**
   * Allows user to be alerted to any upgrades that are performed for a given
   * component type
   * @param {string} jsClass The class name of the MDL component we wish
   * to hook into for any upgrades performed.
   * @param {function(!HTMLElement)} callback The function to call upon an
   * upgrade. This function should expect 1 parameter - the HTMLElement which
   * got upgraded.
   */
  function registerUpgradedCallbackInternal(jsClass, callback) {
    var regClass = findRegisteredClass_(jsClass);
    if (regClass) {
      regClass.callbacks.push(callback);
    }
  }

  /**
   * Upgrades all registered components found in the current DOM. This is
   * automatically called on window load.
   */
  function upgradeAllRegisteredInternal() {
    for (var n = 0; n < registeredComponents_.length; n++) {
      upgradeDomInternal(registeredComponents_[n].className);
    }
  }

  /**
   * Finds a created component by a given DOM node.
   *
   * @param {!Node} node
   * @return {*}
   */
  function findCreatedComponentByNodeInternal(node) {
    for (var n = 0; n < createdComponents_.length; n++) {
      var component = createdComponents_[n];
      if (component.element_ === node) {
        return component;
      }
    }
  }

  /**
   * Check the component for the downgrade method.
   * Execute if found.
   * Remove component from createdComponents list.
   *
   * @param {*} component
   */
  function deconstructComponentInternal(component) {
    if (component &&
        component[componentConfigProperty_]
          .classConstructor.prototype
          .hasOwnProperty(downgradeMethod_)) {
      component[downgradeMethod_]();
      var componentIndex = createdComponents_.indexOf(component);
      createdComponents_.splice(componentIndex, 1);

      var upgrades = component.element_.getAttribute('data-upgraded').split(',');
      var componentPlace = upgrades.indexOf(
          component[componentConfigProperty_].classAsString);
      upgrades.splice(componentPlace, 1);
      component.element_.setAttribute('data-upgraded', upgrades.join(','));

      var ev = document.createEvent('Events');
      ev.initEvent('mdl-componentdowngraded', true, true);
      component.element_.dispatchEvent(ev);
    }
  }

  /**
   * Downgrade either a given node, an array of nodes, or a NodeList.
   *
   * @param {(!Node | !Array<!Node> | !NodeList)} nodes
   */
  function downgradeNodesInternal(nodes) {
    var downgradeNode = function(node) {
      deconstructComponentInternal(findCreatedComponentByNodeInternal(node));
    };
    if (nodes instanceof Array || nodes instanceof NodeList) {
      for (var n = 0; n < nodes.length; n++) {
        downgradeNode(nodes[n]);
      }
    } else if (nodes instanceof Node) {
      downgradeNode(nodes);
    } else {
      throw new Error('Invalid argument provided to downgrade MDL nodes.');
    }
  }

  // Now return the functions that should be made public with their publicly
  // facing names...
  return {
    upgradeDom: upgradeDomInternal,
    upgradeElement: upgradeElementInternal,
    upgradeElements: upgradeElementsInternal,
    upgradeAllRegistered: upgradeAllRegisteredInternal,
    registerUpgradedCallback: registerUpgradedCallbackInternal,
    register: registerInternal,
    downgradeElements: downgradeNodesInternal
  };
})();

window.addEventListener('load', function() {
  'use strict';

  /**
   * Performs a "Cutting the mustard" test. If the browser supports the features
   * tested, adds a mdl-js class to the <html> element. It then upgrades all MDL
   * components requiring JavaScript.
   */
  if ('classList' in document.createElement('div') &&
      'querySelector' in document &&
      'addEventListener' in window && Array.prototype.forEach) {
    document.documentElement.classList.add('mdl-js');
    componentHandler.upgradeAllRegistered();
  } else {
    componentHandler.upgradeElement =
        componentHandler.register = function() {};
  }
});
<|endoftext|>


<commit_before>import glslify from 'rollup-plugin-glslify';
import resolve from 'rollup-plugin-node-resolve';
import builtins from 'rollup-plugin-node-builtins';
import scss from 'rollup-plugin-scss';
import commonjs from 'rollup-plugin-commonjs';
import copy from 'rollup-plugin-copy'

export default {
  input: 'src/main.js',
  output: [
    {
      name: 'SampleViewerApp',
      file: 'dist/GltfSVApp.umd.js',
      format: 'umd',
      sourcemap: true,
      external: [ 'gl-matrix', 'axios', 'jpeg-js', 'fast-png']
    }
  ],
  plugins: [
    commonjs({

    }),
    glslify({include: ['../source/Renderer/shaders/*', '../source/shaders/*']}),
    resolve({
        browser: true,
        preferBuiltins: true
    }),
    builtins(),
    scss(),
    copy({
        targets: [
            { src: ["index.html", "styles.css", "ui.css"], dest: "dist/"},
            { src: ["../assets/models/2.0", "!../asset/models/.git"], dest: "dist/assets/models"},
            { src: ["../assets/environments/*.hdr", "!../asset/environments/.git"], dest: "dist/assets/environments"},
            { src: ["../assets/images"], dest: "dist/assets/images"},
            { src: ["../assets/ui"], dest: "dist/assets/ui"},
            { src: ["../source/libs/*", "!../source/libs/hdrpng.js"], dest: "dist/libs"}
        ]
    })
  ]
};
<commit_msg>fix asset copy paths<commit_after>import glslify from 'rollup-plugin-glslify';
import resolve from 'rollup-plugin-node-resolve';
import builtins from 'rollup-plugin-node-builtins';
import scss from 'rollup-plugin-scss';
import commonjs from 'rollup-plugin-commonjs';
import copy from 'rollup-plugin-copy'

export default {
  input: 'src/main.js',
  output: [
    {
      name: 'SampleViewerApp',
      file: 'dist/GltfSVApp.umd.js',
      format: 'umd',
      sourcemap: true,
      external: [ 'gl-matrix', 'axios', 'jpeg-js', 'fast-png']
    }
  ],
  plugins: [
    commonjs({

    }),
    glslify({include: ['../source/Renderer/shaders/*', '../source/shaders/*']}),
    resolve({
        browser: true,
        preferBuiltins: true
    }),
    builtins(),
    scss(),
    copy({
        targets: [
            { src: ["index.html", "styles.css", "ui.css"], dest: "dist/"},
            { src: ["../assets/models/2.0", "!../asset/models/.git"], dest: "dist/assets/models"},
            { src: ["../assets/environments/*.hdr", "!../asset/environments/.git"], dest: "dist/assets/environments"},
            { src: ["../assets/images"], dest: "dist/assets"},
            { src: ["../assets/ui"], dest: "dist/assets"},
            { src: ["../source/libs/*", "!../source/libs/hdrpng.js"], dest: "dist/libs"}
        ]
    })
  ]
};
<|endoftext|>


<commit_before>//Utilities for finding and working with the Titanium SDK
var path = require('path'),
	fs = require('fs'),
	spawn = require('child_process').spawn,
	_ = require("../lib/alloy/underscore"),
	U = require('../utils'),
	logger = require('../common/logger');

// SDK constants for supported platforms
var HOME = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var SDK_PATHS = {
	darwin: {
		path: '/Library/Application Support/Titanium/',
		suffix: 'mobilesdk/osx'
	},
	linux: {
		path: path.join(HOME,'.titanium/'),
		suffix: 'mobilesdk/linux'
	},
	win32: {
		path: path.join(process.env.APPDATA, 'Titanium'),
		suffix: 'mobilesdk\\win32'
	}
};

// Find out to which path the SDK is installed on OSX
if (process.platform === 'darwin') {
	var osxSdkPaths = [
		path.join(HOME, SDK_PATHS.darwin.path),
		SDK_PATHS.darwin.path
	];
	for (var i = 0; i < osxSdkPaths.length; i++) {
		var sdkPath = osxSdkPaths[i];
		if (path.existsSync(path.join(sdkPath, SDK_PATHS.darwin.suffix))) {
			SDK_PATHS.darwin.path = sdkPath;
			break;
		}
	}
	if (!SDK_PATHS.darwin.path) {
		U.die('Unable to find Titanium SDK, looked in: \n' + osxSdkPaths.join('\n'));
	}
}

//The final SDK location, based on current platform
var TITANIUM_HOME = process.env.TITANIUM_HOME || SDK_PATHS[process.platform].path;
exports.home = TITANIUM_HOME;

var SDK = path.join(TITANIUM_HOME,SDK_PATHS[process.platform].suffix);
exports.SDK = SDK;

//enumerate the Titanium Mobile SDK versions that are currently installed
var versions = _.without(fs.readdirSync(SDK).sort(), '.DS_Store').reverse();
exports.versions = versions;

//spawn an evented child process, which is an invocation of an SDK .py script
//returns the spawned process so you can listen for events (if you care)
//pyScript is resolved relative to the SDK root directory
function py(pyScript, args, version /*optional*/, sdkDir /*optional*/) {
	//use the version they specified, or the latest from the list
	version = version || versions[0];

	//trim extra whitespace from titanium.py output
	function filterLog(line) {
		line =U.trim(line);
		if (!line) return;
		var lines = line.split('\n');
		if (lines.length > 1) {
			_.each(lines,function(l) {
				filterLog(l);
			});
			return;
		}
		var idx = line.indexOf(' -- [');
		if (idx > 0) {
			var idx2 = line.indexOf(']', idx+7);
			line = line.substring(idx2+1);
		}
		if (line.charAt(0)=='[') {
			var i = line.indexOf(']');
			var label = line.substring(1,i);
			var rest = U.trim(line.substring(i+1));
			if (!rest) return;
			switch(label) {
				case 'INFO':
					logger.info(rest);
					return;
				case 'TRACE':
				case 'DEBUG':
					logger.debug(rest);
					return;
				case 'WARN':
					logger.warn(rest);
					return;
				case 'ERROR':
					logger.error(rest);
					return;
			}
		}
		logger.debug(line);
	}

	//invoke .py - use the provided SDK dir if present
	var sdkRoot = sdkDir || path.join(SDK, version);
	var script = path.join(sdkRoot,pyScript);
	var runcmd = spawn('python', [script].concat(args||[]), process.env);

	//run stdout/stderr back through console.log
	runcmd.stdout.on('data', function (data) {
		filterLog(data);
	});

	runcmd.stderr.on('data', function (data) {
		filterLog(data);
	});

	return runcmd;
}
exports.py = py;

//run a titanium project with titanium.py - return the spawned titanium.py process
exports.run = function(projectDir, platform /*optional*/, version /*optional*/, sdkDir /*optional*/) {
	// Validate the input path
	if (!path.existsSync(projectDir)) {
		U.die('projectDir "' + projectDir + '" does not exist');
	}

	// Get the target platform
	// TODO: check tiapp.xml for <deployment-targets> - https://jira.appcelerator.org/browse/ALOY-219
	platform = platform || 'iphone';

	//run the project using titanium.py
	var runArgs = [
		'run',
		'--dir=' + path.resolve(projectDir),
		'--platform=' + platform
	];

	return py('titanium.py', runArgs, version, sdkDir);
};

//create a titanium project - create('FooProject', 'com.appc.foo', ['mobileweb','iphone', 'android'], '/etc/android')
//returns evented process
exports.create = function(name,id,topLevelDir,platformsArray,androidDir, version /*optional*/, sdkDir /*optional*/) {
	var runArgs = [name, id, topLevelDir];
	runArgs.concat(platformsArray);
	//look for Android SDK environment variable
	runArgs.push(androidDir||process.env.ANDROID_SDK);

	return py('project.py', runArgs, version, sdkDir);
};
<commit_msg>workaround for ALOY-307<commit_after>//Utilities for finding and working with the Titanium SDK
var path = require('path'),
	fs = require('fs'),
	spawn = require('child_process').spawn,
	_ = require("../lib/alloy/underscore"),
	U = require('../utils'),
	logger = require('../common/logger');

// SDK constants for supported platforms
var HOME = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var SDK_PATHS = {
	darwin: {
		path: '/Library/Application Support/Titanium/',
		suffix: 'mobilesdk/osx'
	},
	linux: {
		path: path.join(HOME,'.titanium/'),
		suffix: 'mobilesdk/linux'
	},
	win32: {
		path: path.join(process.env.APPDATA, 'Titanium'),
		suffix: 'mobilesdk\\win32'
	}
};

// Find out to which path the SDK is installed on OSX
if (process.platform === 'darwin') {
	var osxSdkPaths = [
		path.join(HOME, SDK_PATHS.darwin.path),
		SDK_PATHS.darwin.path
	];
	for (var i = 0; i < osxSdkPaths.length; i++) {
		var sdkPath = osxSdkPaths[i];
		if (path.existsSync(path.join(sdkPath, SDK_PATHS.darwin.suffix))) {
			SDK_PATHS.darwin.path = sdkPath;
			break;
		}
	}
	if (!SDK_PATHS.darwin.path) {
		U.die('Unable to find Titanium SDK, looked in: \n' + osxSdkPaths.join('\n'));
	}
}

//The final SDK location, based on current platform
var TITANIUM_HOME = process.env.TITANIUM_HOME || SDK_PATHS[process.platform].path;
exports.home = TITANIUM_HOME;

var SDK = path.join(TITANIUM_HOME,SDK_PATHS[process.platform].suffix);
exports.SDK = SDK;

//enumerate the Titanium Mobile SDK versions that are currently installed
var versions = _.without(fs.readdirSync(SDK).sort(), '.DS_Store').reverse();
exports.versions = versions;

//spawn an evented child process, which is an invocation of an SDK .py script
//returns the spawned process so you can listen for events (if you care)
//pyScript is resolved relative to the SDK root directory
function py(pyScript, args, version /*optional*/, sdkDir /*optional*/) {
	//use the version they specified, or the latest from the list
	version = version || versions[0];

	//trim extra whitespace from titanium.py output
	function filterLog(line) {
		line =U.trim(line);
		if (!line) return;

		// Hack to give an appropriate message for android alloy run.
		// This will disappear when we integrate with the new CLI.
		// TODO: http://jira.appcelerator.org/browse/ALOY-258
		line = line.replace('required argument \'--android\' missing (you can also set the environment variable ANDROID_SDK)','[ERROR] You need to set the ANDROID_SDK environment variable to point to your Android SDK');

		var lines = line.split('\n');
		if (lines.length > 1) {
			_.each(lines,function(l) {
				filterLog(l);
			});
			return;
		}
		var idx = line.indexOf(' -- [');
		if (idx > 0) {
			var idx2 = line.indexOf(']', idx+7);
			line = line.substring(idx2+1);
		}
		if (line.charAt(0)=='[') {
			var i = line.indexOf(']');
			var label = line.substring(1,i);
			var rest = U.trim(line.substring(i+1));
			if (!rest) return;
			switch(label) {
				case 'INFO':
					logger.info(rest);
					return;
				case 'TRACE':
				case 'DEBUG':
					logger.debug(rest);
					return;
				case 'WARN':
					logger.warn(rest);
					return;
				case 'ERROR':
					logger.error(rest);
					return;
			}
		}
		logger.debug(line);
	}

	//invoke .py - use the provided SDK dir if present
	var sdkRoot = sdkDir || path.join(SDK, version);
	var script = path.join(sdkRoot,pyScript);
	var runcmd = spawn('python', [script].concat(args||[]), process.env);

	//run stdout/stderr back through console.log
	runcmd.stdout.on('data', function (data) {
		filterLog(data);
	});

	runcmd.stderr.on('data', function (data) {
		filterLog(data);
	});

	return runcmd;
}
exports.py = py;

//run a titanium project with titanium.py - return the spawned titanium.py process
exports.run = function(projectDir, platform /*optional*/, version /*optional*/, sdkDir /*optional*/) {
	// Validate the input path
	if (!path.existsSync(projectDir)) {
		U.die('projectDir "' + projectDir + '" does not exist');
	}

	// Get the target platform
	// TODO: check tiapp.xml for <deployment-targets> - https://jira.appcelerator.org/browse/ALOY-219
	platform = platform || 'iphone';

	//run the project using titanium.py
	var runArgs = [
		'run',
		'--dir=' + path.resolve(projectDir),
		'--platform=' + platform
	];

	return py('titanium.py', runArgs, version, sdkDir);
};

//create a titanium project - create('FooProject', 'com.appc.foo', ['mobileweb','iphone', 'android'], '/etc/android')
//returns evented process
exports.create = function(name,id,topLevelDir,platformsArray,androidDir, version /*optional*/, sdkDir /*optional*/) {
	var runArgs = [name, id, topLevelDir];
	runArgs.concat(platformsArray);
	//look for Android SDK environment variable
	runArgs.push(androidDir||process.env.ANDROID_SDK);

	return py('project.py', runArgs, version, sdkDir);
};
<|endoftext|>


<commit_before>// Copyright, 2013-2014, by Tomas Korcak. <korczis@gmail.com>
//
// 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.

(function () {
    'use strict';

    var define = require('amdefine')(module);

    var requirejs = require('requirejs');
    requirejs.config(require('../../require.js'));

    var deps = [
        '../../modules/webapp',
        'deferred',
        'dependable',
        'util'
    ];

    define(deps, function (Webapp, deferred, dependable, util) {
        ///*
        var resolver = dependable.container();

        // Load app module
        var exports = module.exports = function BLUEjsApp(resolver) {
            BLUEjsApp.super_.call(this, resolver);

            var server =  this.get('server');
        };

        util.inherits(exports, Webapp);

        //*/
    });
}());
<commit_msg>Fixed crash<commit_after>// Copyright, 2013-2014, by Tomas Korcak. <korczis@gmail.com>
//
// 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.

(function () {
    'use strict';

    var define = require('amdefine')(module);

    var requirejs = require('requirejs');
    requirejs.config(require('../../require.js'));

    var deps = [
        '../../modules/webapp',
        'deferred',
        'dependable',
        'util'
    ];

    define(deps, function (Webapp, deferred, dependable, util) {
        ///*
        var resolver = dependable.container();

        // Load app module
        var exports = module.exports = function BLUEjsApp(resolver) {
            BLUEjsApp.super_.call(this, resolver);

            var server =  resolver.get('server');
        };

        util.inherits(exports, Webapp);

        //*/
    });
}());
<|endoftext|>


<commit_before>'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ReportSchema = new Schema({
    worker_id: {type: Schema.Types.ObjectId, ref: 'Worker'},
    stack: String
}, {_id: false});

const TaskSchema = exports.TaskSchema = new Schema({
    dt: Date,
    username: String,

    server_id: {type: Schema.Types.ObjectId, ref: 'Server', index: true},
    //workers: [{type: Schema.Types.ObjectId, ref: 'Worker'}],

    target_id: {type: String},

    status: {type: Number, index: true},
    module: {type: String, index: true},
    cmd: {type: String, index: true},
    params: String,

    internal_error: String,

    error: [ReportSchema],
    report: [ReportSchema]
});

const db = require('../../../lib/db');

TaskSchema.pre('save', function (next) {
    if (!this.isModified('dt')) {
        this.dt = new Date();
    }

    if (!this.isModified('status')) {
        this.status = -1;
    }

    let search = null;

    if (this.target_id[0] === 'W') {
        search = db.WorkerModel;
    } else if (this.target_id[0] === 'G') {
        search = db.WorkersGroupModel;
    } else {
        return next(new Error('Unsupported target id'));
    }

    search.findOne({sys_id: this.target_id}, 'server_id', (err, item) => {
        if (err) {
            next(err);
        } else if (!item) {
            next(new Error(`Target "${this.target_id}" not found`));
        } else {
            this.server_id = item.server_id;
            next();
        }
    });
});

mongoose.model('Task', TaskSchema);<commit_msg>add SERVER target_id value handler<commit_after>'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ReportSchema = new Schema({
    worker_id: {type: Schema.Types.ObjectId, ref: 'Worker'},
    stack: String
}, {_id: false});

const TaskSchema = exports.TaskSchema = new Schema({
    dt: Date,
    username: String,

    server_id: {type: Schema.Types.ObjectId, ref: 'Server', index: true},
    //workers: [{type: Schema.Types.ObjectId, ref: 'Worker'}],

    target_id: {type: String},

    status: {type: Number, index: true},
    module: {type: String, index: true},
    cmd: {type: String, index: true},
    params: String,

    internal_error: String,

    error: [ReportSchema],
    report: [ReportSchema]
});

const db = require('../../../lib/db');

TaskSchema.pre('save', function (next) {
    if (!this.isModified('dt')) {
        this.dt = new Date();
    }

    if (!this.isModified('status')) {
        this.status = -1;
    }

    let search = null;

    if (this.target_id && this.target_id[0] === 'W') {
        search = db.WorkerModel;
    } else if (this.target_id && this.target_id[0] === 'G') {
        search = db.WorkersGroupModel;
    } else if (this.target_id === 'SERVER') {
        return next();
    } else {
        return next(new Error('Unsupported target id'));
    }

    search.findOne({sys_id: this.target_id}, 'server_id', (err, item) => {
        if (err) {
            next(err);
        } else if (!item) {
            next(new Error(`Target "${this.target_id}" not found`));
        } else {
            this.server_id = item.server_id;
            next();
        }
    });
});

mongoose.model('Task', TaskSchema);<|endoftext|>