code:
/*! JsRender v1.0.0-beta: http://github.com/BorisMoore/jsrender and http://jsviews.com/jsviews
informal pre V1.0 commit counter: 47 */
/*
 * Optimized version of jQuery Templates, for rendering to string.
 * Does not require jQuery, or HTML DOM
 * Integrates with JsViews (http://jsviews.com/jsviews)
 *
 * Copyright 2013, Boris Moore
 * Released under the MIT License.
 */

(function(global, jQuery, undefined) {
	// global is the this object, which is window when running in the usual browser environment.
	"use strict";

	if (jQuery && jQuery.views || global.jsviews) { return; } // JsRender is already loaded

	//========================== Top-level vars ==========================

	var versionNumber = "v1.0.0-beta",

		$, jsvStoreName, rTag, rTmplString,// nodeJsModule,

//TODO	tmplFnsCache = {},
		delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", linkChar = "^",

		rPath = /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
		//                                     none   object     helper    view  viewProperty pathTokens      leafToken

		rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*\.|\s*\^|\s*$)|[)\]])([([]?))|(\s+)/g,
		//          lftPrn0        lftPrn        bound            path    operator err                                                eq             path2       prn    comma   lftPrn2   apos quot      rtPrn rtPrnDot                        prn2      space
		// (left paren? followed by (path? followed by operator) or (path followed by left paren?)) or comma or apos or quot or right paren or space

		rNewLine = /[ \t]*(\r\n|\n|\r)/g,
		rUnescapeQuotes = /\\(['"])/g,
		rEscapeQuotes = /['"\\]/g, // Escape quotes and \ character
		rBuildHash = /\x08(~)?([^\x08]+)\x08/g,
		rTestElseIf = /^if\s/,
		rFirstElem = /<(\w+)[>\s]/,
		rAttrEncode = /[\x00`><"'&]/g, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings
		rHtmlEncode = rAttrEncode,
		autoTmplName = 0,
		viewId = 0,
		charEntities = {
			"&": "&",
			"<": "<",
			">": ">",
			"\x00": "�",
			"'": "'",
			'"': """,
			"`": "`"
		},
		tmplAttr = "data-jsv-tmpl",
		$render = {},
		jsvStores = {
			template: {
				compile: compileTmpl
			},
			tag: {
				compile: compileTag
			},
			helper: {},
			converter: {}
		},

		// jsviews object ($.views if jQuery is loaded)
		$views = {
			jsviews: versionNumber,
			render: $render,
			settings: {
				delimiters: $viewsDelimiters,
				debugMode: true,
				tryCatch: true
			},
			sub: {
				// subscription, e.g. JsViews integration
				View: View,
				Error: JsViewsError,
				tmplFn: tmplFn,
				parse: parseParams,
				extend: $extend,
				error: error,
				syntaxError: syntaxError
			},
			_cnvt: convertVal,
			_tag: renderTag,

			_err: function(e) {
				// Place a breakpoint here to intercept template rendering errors
				return $viewsSettings.debugMode ? ("Error: " + (e.message || e)) + ". " : '';
			}
		};

		function JsViewsError(message, object) {
			// Error exception type for JsViews/JsRender
			// Override of $.views.sub.Error is possible
			if (object && object.onError) {
				if (object.onError(message) === false) {
					return;
				}
			}
			this.name = "JsRender Error";
			this.message = message || "JsRender error";
		}

		function $extend(target, source) {
			var name;
			target = target || {};
			for (name in source) {
				target[name] = source[name];
			}
			return target;
		}

		(JsViewsError.prototype = new Error()).constructor = JsViewsError;

	//========================== Top-level functions ==========================

	//===================
	// jsviews.delimiters
	//===================
	function $viewsDelimiters(openChars, closeChars, link) {
		// Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^"
		// openChars, closeChars: opening and closing strings, each with two characters

		if (!$viewsSub.rTag || openChars) {
			delimOpenChar0 = openChars ? openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters
			delimOpenChar1 = openChars ? openChars.charAt(1) : delimOpenChar1;
			delimCloseChar0 = closeChars ? closeChars.charAt(0) : delimCloseChar0;
			delimCloseChar1 = closeChars ? closeChars.charAt(1) : delimCloseChar1;
			linkChar = link || linkChar;
			openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1;  // Default is "{^{"
			closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1;                   // Default is "}}"
			// Build regex with new delimiters
			//          tag    (followed by / space or })   or cvtr+colon or html or code
			rTag = "(?:(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\\*)))"
				+ "\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)";

			// make rTag available to JsViews (or other components) for parsing binding expressions
			$viewsSub.rTag = rTag + ")";

			rTag = new RegExp(openChars + rTag + "(\\/)?|(?:\\/(\\w+)))" + closeChars, "g");

			// Default:    bind           tag       converter colon html     comment            code      params            slash   closeBlock
			//           /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g

			rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars);
			// rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered
			// NOT to be jQuery selectors
		}
		return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar];
	}

	//=========
	// View.get
	//=========

	function getView(inner, type) { //view.get(inner, type)
		if (!type) {
			// view.get(type)
			type = inner;
			inner = undefined;
		}

		var views, i, l, found,
			view = this,
			root = !type || type === "root";
			// If type is undefined, returns root view (view under top view).

		if (inner) {
			// Go through views - this one, and all nested ones, depth-first - and return first one with given type.
			found = view.type === type ? view : undefined;
			if (!found) {
				views = view.views;
				if (view._.useKey) {
					for (i in views) {
						if (found = views[i].get(inner, type)) {
							break;
						}
					}
				} else for (i = 0, l = views.length; !found && i < l; i++) {
					found = views[i].get(inner, type);
				}
			}
		} else if (root) {
			// Find root view. (view whose parent is top view)
			while (view.parent.parent) {
				found = view = view.parent;
			}
		} else while (view && !found) {
			// Go through views - this one, and all parent ones - and return first one with given type.
			found = view.type === type ? view : undefined;
			view = view.parent;
		}
		return found;
	}

	function getNestedIndex() {
		var view = this.get("item");
		return view ? view.index : undefined;
	}

	getNestedIndex.depends = function() {
		return [this.get("item"), "index"];
	};

	function getIndex() {
		return this.index;
	}

	getIndex.depends = function() {
		return ["index"];
	};

	//==========
	// View.hlp
	//==========

	function getHelper(helper) {
		// Helper method called as view.hlp(key) from compiled template, for helper functions or template parameters ~foo
		var wrapped,
			view = this,
			ctx = view.linkCtx,
			res = (view.ctx || {})[helper];

		if (res === undefined && ctx && ctx.ctx) {
			res = ctx.ctx[helper];
		}
		if (res === undefined) {
			res = $helpers[helper];
		}

		if (res) {
			if (typeof res === "function") {
				wrapped = function() {
					// If it is of type function, we will wrap it, so if called with no this pointer it will be called with the view as 'this' context.
					// If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too.
					// Note that helper functions on deeper paths will have specific this pointers, from the preceding path.
					// For example, ~util.foo() will have the ~util object as 'this' pointer
					return res.apply(this || view, arguments);
				};
				$extend(wrapped, res);
			}
		}
		return wrapped || res;
	}

	//==============
	// jsviews._cnvt
	//==============

	function convertVal(converter, view, tagCtx) {
		// self is template object or linkCtx object
		var tmplConverter, tag, value,
			boundTagCtx = +tagCtx === tagCtx && tagCtx, // if tagCtx is an integer, then it is the key for the boundTagCtx (compiled function to return the tagCtx)
			linkCtx = view.linkCtx; // For data-link="{cvt:...}"...

		if (boundTagCtx) {
			// This is a bound tag: {^{xx:yyy}}. Call compiled function which returns the tagCtxs for current data
			tagCtx = (boundTagCtx = view.tmpl.bnds[boundTagCtx-1])(view.data, view, $views);
		}

		value = tagCtx.args[0];

		if (converter || boundTagCtx) {
			tag = linkCtx && linkCtx.tag || {
				_: {
					inline: !linkCtx,
					bnd: boundTagCtx
				},
				tagName: converter + ":",
				flow: true,
				_is: "tag"
			};

			if (linkCtx) {
				linkCtx.tag = tag;
				tag.linkCtx = tag.linkCtx || linkCtx;
				tagCtx.ctx = extendCtx(tagCtx.ctx, linkCtx.view.ctx);
			}
			tag.tagCtx = tagCtx;
			tagCtx.view = view;

			tag.ctx = tagCtx.ctx || {};
			delete tagCtx.ctx;
			// Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
			view._.tag = tag;

			converter = converter !== "true" && converter; // If there is a convertBack but no convert, converter will be "true"

			if (converter && ((tmplConverter = view.getRsc("converters", converter)) || error("Unknown converter: {{"+ converter + ":"))) {
				// A call to {{cnvt: ... }} or {^{cnvt: ... }} or data-link="{cnvt: ... }"
				tag.depends = tmplConverter.depends;
				value = tmplConverter.apply(tag, tagCtx.args);
			}
			// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
			value = boundTagCtx && view._.onRender
				? view._.onRender(value, view, boundTagCtx)
				: value;
			view._.tag = undefined;
		}
		return value;
	}

	//=============
	// jsviews._tag
	//=============

	function getResource(resourceType, itemName) {
		var res, store,
			view = this;
		while ((res === undefined) && view) {
			store = view.tmpl[resourceType];
			res = store && store[itemName];
			view = view.parent;
		}
		return res || $views[resourceType][itemName];
	}

	function renderTag(tagName, parentView, tmpl, tagCtxs, isRefresh) {
		// Called from within compiled template function, to render a template tag
		// Returns the rendered tag

		var render, tag, tags, attr, parentTag, i, l, itemRet, tagCtx, tagCtxCtx, content, boundTagFn, tagDef, callInit,
			ret = "",
			boundTagKey = +tagCtxs === tagCtxs && tagCtxs, // if tagCtxs is an integer, then it is the boundTagKey
			linkCtx = parentView.linkCtx || 0,
			ctx = parentView.ctx,
			parentTmpl = tmpl || parentView.tmpl,
			parentView_ = parentView._;

		if (tagName._is === "tag") {
			tag = tagName;
			tagName = tag.tagName;
		}

		// Provide tagCtx, linkCtx and ctx access from tag
		if (boundTagKey) {
			// if tagCtxs is an integer, we are data binding
			// Call compiled function which returns the tagCtxs for current data
			tagCtxs = (boundTagFn = parentTmpl.bnds[boundTagKey-1])(parentView.data, parentView, $views);
		}

		l = tagCtxs.length;
		tag = tag || linkCtx.tag;
		for (i = 0; i < l; i++) {
			tagCtx = tagCtxs[i];

			// Set the tmpl property to the content of the block tag, unless set as an override property on the tag
			content = tagCtx.tmpl;
			content = tagCtx.content = content && parentTmpl.tmpls[content - 1];
			tmpl = tagCtx.props.tmpl;
			if (!i && (!tmpl || !tag)) {
				tagDef = parentView.getRsc("tags", tagName) || error("Unknown tag: {{"+ tagName + "}}");
			}
			tmpl = tmpl || (tag ? tag : tagDef).template || content;
			tmpl = "" + tmpl === tmpl // if a string
				? parentView.getRsc("templates", tmpl) || $templates(tmpl)
				: tmpl;

			$extend(tagCtx, {
				tmpl: tmpl,
				render: renderContent,
				index: i,
				view: parentView,
				ctx: extendCtx(tagCtx.ctx, ctx) // Extend parentView.ctx
			}); // Extend parentView.ctx

			if (!tag) {
				// This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet
				// Instantiate tag if it does not yet exist
				if (tagDef._ctr) {
					// If the tag has not already been instantiated, we will create a new instance.
					// ~tag will access the tag, even within the rendering of the template content of this tag.
					// From child/descendant tags, can access using ~tag.parent, or ~parentTags.tagName
//	TODO provide error handling owned by the tag - using tag.onError
//				try {
					tag = new tagDef._ctr();
					callInit = !!tag.init;
//				}
//				catch(e) {
//					tagDef.onError(e);
//				}
					// Set attr on linkCtx to ensure outputting to the correct target attribute.
					tag.attr = tag.attr || tagDef.attr || undefined;
					// Setting either linkCtx.attr or this.attr in the init() allows per-instance choice of target attrib.
				} else {
					// This is a simple tag declared as a function, or with init set to false. We won't instantiate a specific tag constructor - just a standard instance object.
					tag = {
						// tag instance object if no init constructor
						render: tagDef.render
					};
				}
				tag._ = {
					inline: !linkCtx
				};
				if (linkCtx) {
					// Set attr on linkCtx to ensure outputting to the correct target attribute.
					linkCtx.attr = tag.attr = linkCtx.attr || tag.attr;
					linkCtx.tag = tag;
					tag.linkCtx = linkCtx;
				}
				if (tag._.bnd = boundTagFn || linkCtx.fn) {
					// Bound if {^{tag...}} or data-link="{tag...}"
					tag._.arrVws = {};
				} else if (tag.dataBoundOnly) {
					error("{^{" + tagName + "}} tag must be data-bound");
				}
				tag.tagName = tagName;
				tag.parent = parentTag = ctx && ctx.tag;
				tag._is = "tag";
				tag._def = tagDef;
				//TODO better perf for childTags() - keep child tag.tags array, (and remove child, when disposed)
				// tag.tags = [];
				// Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
			}
			parentView_.tag = tag;
			tagCtx.tag = tag;
			tag.tagCtxs = tagCtxs;
			if (!tag.flow) {
				tagCtxCtx = tagCtx.ctx = tagCtx.ctx || {};

				// tags hash: tag.ctx.tags, merged with parentView.ctx.tags,
				tags = tag.parents = tagCtxCtx.parentTags = ctx && extendCtx(tagCtxCtx.parentTags, ctx.parentTags) || {};
				if (parentTag) {
					tags[parentTag.tagName] = parentTag;
					//TODO better perf for childTags:  parentTag.tags.push(tag);
				}
				tagCtxCtx.tag = tag;
			}
		}
		tag.rendering = {}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...)
		for (i = 0; i < l; i++) {
			tagCtx = tag.tagCtx = tagCtxs[i];
			tag.ctx = tagCtx.ctx;

			if (!i && callInit) {
				tag.init(tagCtx, linkCtx, tag.ctx);
				callInit = undefined;
			}

			itemRet = undefined;
			if (render = tag.render) {
				itemRet = render.apply(tag, tagCtx.args);
			}
			itemRet = itemRet !== undefined
				? itemRet   // Return result of render function unless it is undefined, in which case return rendered template
				: tagCtx.tmpl && tagCtx.render() || (isRefresh ? undefined : "");
				// No return value from render, and no template/content tagCtx.render(), so return undefined
			ret =  ret ? ret + (itemRet || "") : itemRet; // If no rendered content, this will be undefined
		}

		delete tag.rendering;

		tag.tagCtx = tag.tagCtxs[0];
		tag.ctx= tag.tagCtx.ctx;

		if (tag._.inline && (attr = tag.attr) && attr !== "html") {
			// inline tag with attr set to "text" will insert HTML-encoded content - as if it was element-based innerText
			ret = attr === "text"
				? $converters.html(ret)
				: "";
		}
		return boundTagKey && parentView._.onRender
			// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
			? parentView._.onRender(ret, parentView, boundTagKey)
			: ret;
	}

	//=================
	// View constructor
	//=================

	function View(context, type, parentView, data, template, key, contentTmpl, onRender) {
		// Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded)
		var views, parentView_, tag,
			isArray = type === "array",
			self_ = {
				key: 0,
				useKey: isArray ? 0 : 1,
				id: "" + viewId++,
				onRender: onRender,
				bnds: {}
			},
			self = {
				data: data,
				tmpl: template,
				content: contentTmpl,
				views: isArray ? [] : {},
				parent: parentView,
				type: type,
				// If the data is an array, this is an 'array view' with a views array for each child 'item view'
				// If the data is not an array, this is an 'item view' with a views 'map' object for any child nested views
				// ._.useKey is non zero if is not an 'array view' (owning a data array). Uuse this as next key for adding to child views map
				get: getView,
				getIndex: getIndex,
				getRsc: getResource,
				hlp: getHelper,
				_: self_,
				_is: "view"
		};
		if (parentView) {
			views = parentView.views;
			parentView_ = parentView._;
			if (parentView_.useKey) {
				// Parent is an 'item view'. Add this view to its views object
				// self._key = is the key in the parent view map
				views[self_.key = "_" + parentView_.useKey++] = self;
				self.index = $viewsSettings.debugMode ? noIndex : "";
				self.getIndex = getNestedIndex;
				tag = parentView_.tag;
				self_.bnd = isArray && (!tag || !!tag._.bnd && tag); // For array views that are data bound for collection change events, set the
				// view._.bnd property to true for top-level link() or data-link="{for}", or to the tag instance for a data-bound tag, e.g. {^{for ...}}
			} else {
				// Parent is an 'array view'. Add this view to its views array
				views.splice(
					// self._.key = self.index - the index in the parent view array
					self_.key = self.index = key,
				0, self);
			}
			// If no context was passed in, use parent context
			// If context was passed in, it should have been merged already with parent context
			self.ctx = context || parentView.ctx;
		} else {
			self.ctx = context;
		}
		return self;
	}

	//=============
	// Registration
	//=============

	function compileChildResources(parentTmpl) {
		var storeName, resources, resourceName, settings, compile;
		for (storeName in jsvStores) {
			settings = jsvStores[storeName];
			if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) {
				for (resourceName in resources) {
					// compile child resource declarations (templates, tags, converters or helpers)
					resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl, storeName, settings);
				}
			}
		}
	}

	function compileTag(name, tagDef, parentTmpl) {
		var init, tmpl;
		if (typeof tagDef === "function") {
			// Simple tag declared as function. No presenter instantation.
			tagDef = {
				depends: tagDef.depends,
				render: tagDef
			};
		} else {
			// Tag declared as object, used as the prototype for tag instantiation (control/presenter)
			if (tmpl = tagDef.template) {
				tagDef.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl;
			}
			if (tagDef.init !== false) {
				// Set int: false on tagDef if you want to provide just a render method, or render and template, but no constuctor or prototype.
				// so equivalent to setting tag to render function, except you can also provide a template.
				init = tagDef._ctr = function(tagCtx) {};
				(init.prototype = tagDef).constructor = init;
			}
		}
		if (parentTmpl) {
			tagDef._parentTmpl = parentTmpl;
		}
//TODO	tagDef.onError = function(e) {
//			var error;
//			if (error = this.prototype.onError) {
//				error.call(this, e);
//			} else {
//				throw e;
//			}
//		}
		return tagDef;
	}

	function compileTmpl(name, tmpl, parentTmpl, storeName, storeSettings, options) {
		// tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object

		//==== nested functions ====
		function tmplOrMarkupFromStr(value) {
			// If value is of type string - treat as selector, or name of compiled template
			// Return the template object, if already compiled, or the markup string

			if (("" + value === value) || value.nodeType > 0) {
				try {
					elem = value.nodeType > 0
					? value
					: !rTmplString.test(value)
					// If value is a string and does not contain HTML or tag content, then test as selector
						&& jQuery && jQuery(global.document).find(value)[0];
					// If selector is valid and returns at least one element, get first element
					// If invalid, jQuery will throw. We will stay with the original string.
				} catch (e) {}

				if (elem) {
					// Generally this is a script element.
					// However we allow it to be any element, so you can for example take the content of a div,
					// use it as a template, and replace it by the same content rendered against data.
					// e.g. for linking the content of a div to a container, and using the initial content as template:
					// $.link("#content", model, {tmpl: "#content"});

					value = elem.getAttribute(tmplAttr);
					name = name || value;
					value = $templates[value];
					if (!value) {
						// Not already compiled and cached, so compile and cache the name
						// Create a name for compiled template if none provided
						name = name || "_" + autoTmplName++;
						elem.setAttribute(tmplAttr, name);
						// Use tmpl as options
						value = $templates[name] = compileTmpl(name, elem.innerHTML, parentTmpl, storeName, storeSettings, options);
					}
				}
				return value;
			}
			// If value is not a string, return undefined
		}

		var tmplOrMarkup, elem;

		//==== Compile the template ====
		tmpl = tmpl || "";
		tmplOrMarkup = tmplOrMarkupFromStr(tmpl);

		// If options, then this was already compiled from a (script) element template declaration.
		// If not, then if tmpl is a template object, use it for options
		options = options || (tmpl.markup ? tmpl : {});
		options.tmplName = name;
		if (parentTmpl) {
			options._parentTmpl = parentTmpl;
		}
		// If tmpl is not a markup string or a selector string, then it must be a template object
		// In that case, get it from the markup property of the object
		if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr(tmpl.markup))) {
			if (tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode)) {
				// if the string references a compiled template object, but the debug or allowCode props are different, need to recompile
				tmplOrMarkup = tmplOrMarkup.markup;
			}
		}
		if (tmplOrMarkup !== undefined) {
			if (name && !parentTmpl) {
				$render[name] = function() {
					return tmpl.render.apply(tmpl, arguments);
				};
			}
			if (tmplOrMarkup.fn || tmpl.fn) {
				// tmpl is already compiled, so use it, or if different name is provided, clone it
				if (tmplOrMarkup.fn) {
					if (name && name !== tmplOrMarkup.tmplName) {
						tmpl = extendCtx(options, tmplOrMarkup);
					} else {
						tmpl = tmplOrMarkup;
					}
				}
			} else {
				// tmplOrMarkup is a markup string, not a compiled template
				// Create template object
				tmpl = TmplObject(tmplOrMarkup, options);
				// Compile to AST and then to compiled function
				tmplFn(tmplOrMarkup.replace(rEscapeQuotes, "\\$&"), tmpl);
			}
			compileChildResources(options);
			return tmpl;
		}
	}
	//==== /end of function compile ====

	function TmplObject(markup, options) {
		// Template object constructor
		var htmlTag,
			wrapMap = $viewsSettings.wrapMap || {},
			tmpl = $extend(
				{
					markup: markup,
					tmpls: [],
					links: {}, // Compiled functions for link expressions
					tags: {}, // Compiled functions for bound tag expressions
					bnds: [],
					_is: "template",
					render: renderContent
				},
				options
			);

		if (!options.htmlTag) {
			// Set tmpl.tag to the top-level HTML tag used in the template, if any...
			htmlTag = rFirstElem.exec(markup);
			tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : "";
		}
		htmlTag = wrapMap[tmpl.htmlTag];
		if (htmlTag && htmlTag !== wrapMap.div) {
			// When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content').
			// Currently not trimmed for <li> tag. (Not worth adding perf cost)
			tmpl.markup = $.trim(tmpl.markup);
		}

		return tmpl;
	}

	function registerStore(storeName, storeSettings) {

		function theStore(name, item, parentTmpl) {
			// The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags

			// For store of name 'thing', Call as:
			//    $.views.things(items[, parentTmpl]),
			// or $.views.things(name, item[, parentTmpl])

			var onStore, compile, itemName, thisStore;

			if (name && "" + name !== name && !name.nodeType && !name.markup) {
				// Call to $.views.things(items[, parentTmpl]),

				// Adding items to the store
				// If name is a map, then item is parentTmpl. Iterate over map and call store for key.
				for (itemName in name) {
					theStore(itemName, name[itemName], item);
				}
				return $views;
			}
			// Adding a single unnamed item to the store
			if (item === undefined) {
				item = name;
				name = undefined;
			}
			if (name && "" + name !== name) { // name must be a string
				parentTmpl = item;
				item = name;
				name = undefined;
			}
			thisStore = parentTmpl ? parentTmpl[storeNames] = parentTmpl[storeNames] || {} : theStore;
			compile = storeSettings.compile;
			if (onStore = $viewsSub.onBeforeStoreItem) {
				// e.g. provide an external compiler or preprocess the item.
				compile = onStore(thisStore, name, item, compile) || compile;
			}
			if (!name) {
				item = compile(undefined, item);
			} else if (item === null) {
				// If item is null, delete this entry
				delete thisStore[name];
			} else {
				thisStore[name] = compile ? (item = compile(name, item, parentTmpl, storeName, storeSettings)) : item;
			}
			if (compile && item) {
				item._is = storeName; // Only do this for compiled objects (tags, templates...)
			}
			if (onStore = $viewsSub.onStoreItem) {
				// e.g. JsViews integration
				onStore(thisStore, name, item, compile);
			}
			return item;
		}

		var storeNames = storeName + "s";

		$views[storeNames] = theStore;
		jsvStores[storeName] = storeSettings;
	}

	//==============
	// renderContent
	//==============

	function renderContent(data, context, parentView, key, isLayout, onRender) {
		// Render template against data as a tree of subviews (nested rendered template instances), or as a string (top-level template).
		// If the data is the parent view, treat as layout template, re-render with the same data context.
		var i, l, dataItem, newView, childView, itemResult, swapContent, tagCtx, contentTmpl, tag_, outerOnRender, tmplName, tmpl,
			self = this,
			allowDataLink = !self.attr || self.attr === "html",
			result = "";

		if (key === true) {
			swapContent = true;
			key = 0;
		}
		if (self.tag) {
			// This is a call from renderTag or tagCtx.render()
			tagCtx = self;
			self = self.tag;
			tag_ = self._;
			tmplName = self.tagName;
			tmpl = tagCtx.tmpl;
			context = extendCtx(context, self.ctx);
			contentTmpl = tagCtx.content; // The wrapped content - to be added to views, below
			if (tagCtx.props.link === false) {
				// link=false setting on block tag
				// We will override inherited value of link by the explicit setting link=false taken from props
				// The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect.
				context = context || {};
				context.link = false;
			}
			parentView = parentView || tagCtx.view;
			data = data === undefined ? parentView : data;
		} else {
			tmpl = self.jquery && (self[0] || error('Unknown template: "' + self.selector + '"')) // This is a call from $(selector).render
				|| self;
		}
		if (tmpl) {
			if (!parentView && data && data._is === "view") {
				parentView = data; // When passing in a view to render or link (and not passing in a parent view) use the passed in view as parentView
			}
			if (parentView) {
				contentTmpl = contentTmpl || parentView.content; // The wrapped content - to be added as #content property on views, below
				onRender = onRender || parentView._.onRender;
				if (data === parentView) {
					// Inherit the data from the parent view.
					// This may be the contents of an {{if}} block
					// Set isLayout = true so we don't iterate the if block if the data is an array.
					data = parentView.data;
					isLayout = true;
				}
				context = extendCtx(context, parentView.ctx);
			}
			if (!parentView || parentView.data === undefined) {
				(context = context || {}).root = data; // Provide ~root as shortcut to top-level data.
			}

			// Set additional context on views created here, (as modified context inherited from the parent, and to be inherited by child views)
			// Note: If no jQuery, $extend does not support chained copies - so limit extend() to two parameters

			if (!tmpl.fn) {
				tmpl = $templates[tmpl] || $templates(tmpl);
			}

			if (tmpl) {
				onRender = (context && context.link) !== false && allowDataLink && onRender;
				// If link===false, do not call onRender, so no data-linking marker nodes
				outerOnRender = onRender;
				if (onRender === true) {
					// Used by view.refresh(). Don't create a new wrapper view.
					outerOnRender = undefined;
					onRender = parentView._.onRender;
				}
				context = tmpl.helpers
					? extendCtx(tmpl.helpers, context)
					: context;
				if ($.isArray(data) && !isLayout) {
					// Create a view for the array, whose child views correspond to each data item. (Note: if key and parentView are passed in
					// along with parent view, treat as insert -e.g. from view.addViews - so parentView is already the view item for array)
					newView = swapContent
						? parentView :
						(key !== undefined && parentView) || View(context, "array", parentView, data, tmpl, key, contentTmpl, onRender);
					for (i = 0, l = data.length; i < l; i++) {
						// Create a view for each data item.
						dataItem = data[i];
						childView = View(context, "item", newView, dataItem, tmpl, (key || 0) + i, contentTmpl, onRender);
						itemResult = tmpl.fn(dataItem, childView, $views);
						result += newView._.onRender ? newView._.onRender(itemResult, childView) : itemResult;
					}
				} else {
					// Create a view for singleton data object. The type of the view will be the tag name, e.g. "if" or "myTag" except for
					// "item", "array" and "data" views. A "data" view is from programatic render(object) against a 'singleton'.
					newView = swapContent ? parentView : View(context, tmplName||"data", parentView, data, tmpl, key, contentTmpl, onRender);
					if (tag_ && !self.flow) {
						newView.tag = self;
					}
					result += tmpl.fn(data, newView, $views);
				}
				return outerOnRender ? outerOnRender(result, newView) : result;
			}
		}
		return "";
	}

	//===========================
	// Build and compile template
	//===========================

	// Generate a reusable function that will serve to render a template against data
	// (Compile AST then build template function)

	function error(message) {
		throw new $viewsSub.Error(message);
	}

	function syntaxError(message) {
		error("Syntax error\n" + message);
	}

	function tmplFn(markup, tmpl, isLinkExpr, convertBack) {
		// Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes
		// Used for compiling templates, and also by JsViews to build functions for data link expressions

		//==== nested functions ====
		function pushprecedingContent(shift) {
			shift -= loc;
			if (shift) {
				content.push(markup.substr(loc, shift).replace(rNewLine, "\\n"));
			}
		}

		function blockTagCheck(tagName) {
			tagName && syntaxError('Unmatched or missing tag: "{{/' + tagName + '}}" in template:\n' + markup);
		}

		function parseTag(all, bind, tagName, converter, colon, html, comment, codeTag, params, slash, closeBlock, index) {

			//    bind         tag        converter colon html     comment            code      params            slash   closeBlock
			// /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
			// Build abstract syntax tree (AST): [tagName, converter, params, content, hash, bindings, contentMarkup]
			if (html) {
				colon = ":";
				converter = "html";
			}
			slash = slash || isLinkExpr;
			var noError, current0,
				pathBindings = bind && [],
				code = "",
				hash = "",
				passedCtx = "",
				// Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression
				block = !slash && !colon && !comment;

			//==== nested helper function ====
			tagName = tagName || colon;
			pushprecedingContent(index);
			loc = index + all.length; // location marker - parsed up to here
			if (codeTag) {
				if (allowCode) {
					content.push(["*", "\n" + params.replace(rUnescapeQuotes, "$1") + "\n"]);
				}
			} else if (tagName) {
				if (tagName === "else") {
					if (rTestElseIf.test(params)) {
						syntaxError('for "{{else if expr}}" use "{{else expr}}"');
					}
					pathBindings = current[6];
					current[7] = markup.substring(current[7], index); // contentMarkup for block tag
					current = stack.pop();
					content = current[3];
					block = true;
				}
				if (params) {
					// remove newlines from the params string, to avoid compiled code errors for unterminated strings
					params = params.replace(rNewLine, " ");
					code = parseParams(params, pathBindings, tmpl)
						.replace(rBuildHash, function(all, isCtx, keyValue) {
							if (isCtx) {
								passedCtx += keyValue + ",";
							} else {
								hash += keyValue + ",";
							}
							return "";
						});
				}
				hash = hash.slice(0, -1);
				code = code.slice(0, -1);
				noError = hash && (hash.indexOf("noerror:true") + 1) && hash || "";

				newNode = [
						tagName,
						converter || !!convertBack || "",
						code,
						block && [],
						'params:"' + params + '",props:{' + hash + "}"
							+ (passedCtx ? ",ctx:{" + passedCtx.slice(0, -1) + "}" : ""),
						noError,
						pathBindings || 0
					];
				content.push(newNode);
				if (block) {
					stack.push(current);
					current = newNode;
					current[7] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag
				}
			} else if (closeBlock) {
				current0 = current[0];
				blockTagCheck(closeBlock !== current0 && current0 !== "else" && closeBlock);
				current[7] = markup.substring(current[7], index); // contentMarkup for block tag
				current = stack.pop();
			}
			blockTagCheck(!current && closeBlock);
			content = current[3];
		}
		//==== /end of nested functions ====

		var newNode,
			allowCode = tmpl && tmpl.allowCode,
			astTop = [],
			loc = 0,
			stack = [],
			content = astTop,
			current = [, , , astTop];

//TODO	result = tmplFnsCache[markup]; // Only cache if template is not named and markup length < ...,
//and there are no bindings or subtemplates?? Consider standard optimization for data-link="a.b.c"
//		if (result) {
//			tmpl.fn = result;
//		} else {

//		result = markup;

		blockTagCheck(stack[0] && stack[0][3].pop()[0]);
		// Build the AST (abstract syntax tree) under astTop
		markup.replace(rTag, parseTag);

		pushprecedingContent(markup.length);

		if (loc = astTop[astTop.length - 1]) {
			blockTagCheck("" + loc !== loc && (+loc[7] === loc[7]) && loc[0]);
		}
//			result = tmplFnsCache[markup] = buildCode(astTop, tmpl);
//		}
		return buildCode(astTop, isLinkExpr ? markup : tmpl, isLinkExpr);
	}

	function buildCode(ast, tmpl, isLinkExpr) {
		// Build the template function code from the AST nodes, and set as property on the passed-in template object
		// Used for compiling templates, and also by JsViews to build functions for data link expressions
		var i, node, tagName, converter, params, hash, hasTag, hasEncoder, getsVal, hasCnvt, useCnvt, tmplBindings, pathBindings,
			nestedTmpls, tmplName, nestedTmpl, tagAndElses, content, markup, nextIsElse, oldCode, isElse, isGetVal, prm, tagCtxFn,
			tmplBindingKey = 0,
			code = "",
			noError = "",
			tmplOptions = {},
			l = ast.length;

		if ("" + tmpl === tmpl) {
			tmplName = isLinkExpr ? 'data-link="' + tmpl.replace(rNewLine, " ").slice(1, -1) + '"' : tmpl;
			tmpl = 0;
		} else {
			tmplName = tmpl.tmplName || "unnamed";
			if (tmpl.allowCode) {
				tmplOptions.allowCode = true;
			}
			if (tmpl.debug) {
				tmplOptions.debug = true;
			}
			tmplBindings = tmpl.bnds;
			nestedTmpls = tmpl.tmpls;
		}
		for (i = 0; i < l; i++) {
			// AST nodes: [tagName, converter, params, content, hash, noError, pathBindings, contentMarkup, link]
			node = ast[i];

			// Add newline for each callout to t() c() etc. and each markup string
			if ("" + node === node) {
				// a markup string to be inserted
				code += '\nret+="' + node + '";';
			} else {
				// a compiled tag expression to be inserted
				tagName = node[0];
				if (tagName === "*") {
					// Code tag: {{* }}
					code += "" + node[1];
				} else {
					converter = node[1];
					params = node[2];
					content = node[3];
					hash = node[4];
					noError = node[5];
					markup = node[7];

					if (!(isElse = tagName === "else")) {
						tmplBindingKey = 0;
						if (tmplBindings && (pathBindings = node[6])) { // Array of paths, or false if not data-bound
							tmplBindingKey = tmplBindings.push(pathBindings);
						}
					}
					if (isGetVal = tagName === ":") {
						if (converter) {
							tagName = converter === "html" ? ">" : converter + tagName;
						}
						if (noError) {
							// If the tag includes noerror=true, we will do a try catch around expressions for named or unnamed parameters
							// passed to the tag, and return the empty string for each expression if it throws during evaluation
							//TODO This does not work for general case - supporting noError on multiple expressions, e.g. tag args and properties.
							//Consider replacing with try<a.b.c(p,q) + a.d, xxx> and return the value of the expression a.b.c(p,q) + a.d, or, if it throws, return xxx||'' (rather than always the empty string)
							prm = "prm" + i;
							noError = "try{var " + prm + "=[" + params + "][0];}catch(e){" + prm + '="";}\n';
							params = prm;
						}
					} else {
						if (content) {
							// Create template object for nested template
							nestedTmpl = TmplObject(markup, tmplOptions);
							nestedTmpl.tmplName = tmplName + "/" + tagName;
							// Compile to AST and then to compiled function
							buildCode(content, nestedTmpl);
							nestedTmpls.push(nestedTmpl);
						}

						if (!isElse) {
							// This is not an else tag.
							tagAndElses = tagName;
							// Switch to a new code string for this bound tag (and its elses, if it has any) - for returning the tagCtxs array
							oldCode = code;
							code = "";
						}
						nextIsElse = ast[i + 1];
						nextIsElse = nextIsElse && nextIsElse[0] === "else";
					}

					hash += ",args:[" + params + "]}";

					if (isGetVal && pathBindings || converter && tagName !== ">") {
						// For convertVal we need a compiled function to return the new tagCtx(s)
						tagCtxFn = new Function("data,view,j,u", " // "
									+ tmplName + " " + tmplBindingKey + " " + tagName + "\n" + noError + "return {" + hash + ";");
						tagCtxFn.paths = pathBindings;
						tagCtxFn._ctxs = tagName;
						if (isLinkExpr) {
							return tagCtxFn;
						}
						useCnvt = 1;
					}

					code += (isGetVal
						? "\n" + (pathBindings ? "" : noError) + (isLinkExpr ? "return " : "ret+=") + (useCnvt // Call _cnvt if there is a converter: {{cnvt: ... }} or {^{cnvt: ... }}
							? (useCnvt = 0, hasCnvt = true, 'c("' + converter + '",view,' + (pathBindings
								? ((tmplBindings[tmplBindingKey - 1] = tagCtxFn), tmplBindingKey) // Store the compiled tagCtxFn in tmpl.bnds, and pass the key to convertVal()
								: "{" + hash) + ");")
							: tagName === ">"
								? (hasEncoder = true, "h(" + params + ");")
								: (getsVal = true, "(v=" + params + ")!=" + (isLinkExpr ? "=" : "") + 'u?v:"";') // Strict equality just for data-link="title{:expr}" so expr=null will remove title attribute
						)
						: (hasTag = true, "{view:view,tmpl:" // Add this tagCtx to the compiled code for the tagCtxs to be passed to renderTag()
							+ (content ? nestedTmpls.length: "0") + "," // For block tags, pass in the key (nestedTmpls.length) to the nested content template
							+ hash + ","));

					if (tagAndElses && !nextIsElse) {
						code = "[" + code.slice(0, -1) + "]"; // This is a data-link expression or the last {{else}} of an inline bound tag. We complete the code for returning the tagCtxs array
						if (isLinkExpr || pathBindings) {
							// This is a bound tag (data-link expression or inline bound tag {^{tag ...}}) so we store a compiled tagCtxs function in tmp.bnds
							code = new Function("data,view,j,u", " // " + tmplName + " " + tmplBindingKey + " " + tagAndElses + "\nreturn " + code + ";");
							if (pathBindings) {
								(tmplBindings[tmplBindingKey - 1] = code).paths = pathBindings;
							}
							code._ctxs = tagName;
							if (isLinkExpr) {
								return code; // For a data-link expression we return the compiled tagCtxs function
							}
						}

						// This is the last {{else}} for an inline tag.
						// For a bound tag, pass the tagCtxs fn lookup key to renderTag.
						// For an unbound tag, include the code directly for evaluating tagCtxs array
						code = oldCode + '\nret+=t("' + tagAndElses + '",view,this,' + (tmplBindingKey || code) + ");";
						pathBindings = 0;
						tagAndElses = 0;
					}
				}
			}
		}
		// Include only the var references that are needed in the code
		code = "// " + tmplName
			+ "\nvar j=j||" + (jQuery ? "jQuery." : "js") + "views"
			+ (getsVal ? ",v" : "")                      // gets value
			+ (hasTag ? ",t=j._tag" : "")                // has tag
			+ (hasCnvt ? ",c=j._cnvt" : "")              // converter
			+ (hasEncoder ? ",h=j.converters.html" : "") // html converter
			+ (isLinkExpr ? ";\n" : ',ret="";\n')
			+ ($viewsSettings.tryCatch ? "try{\n" : "")
			+ (tmplOptions.debug ? "debugger;" : "")
			+ code + (isLinkExpr ? "\n" : "\nreturn ret;\n")
			+ ($viewsSettings.tryCatch ? "\n}catch(e){return j._err(e);}" : "");
		try {
			code = new Function("data,view,j,u", code);
		} catch (e) {
			syntaxError("Compiled template code:\n\n" + code, e);
		}
		if (tmpl) {
			tmpl.fn = code;
		}
		return code;
	}

	function parseParams(params, bindings, tmpl) {

		//function pushBindings() { // Consider structured path bindings
		//	if (bindings) {
		//		named ? bindings[named] = bindings.pop(): bindings.push(list = []);
		//	}
		//}

		function parseTokens(all, lftPrn0, lftPrn, bound, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, rtPrnDot, prn2, space, index, full) {
			//rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*\.|\s*\^)|[)\]])([([]?))|(\s+)/g,
			//          lftPrn0        lftPrn        bound            path    operator err                                                eq             path2       prn    comma   lftPrn2   apos quot      rtPrn rtPrnDot                        prn2      space
			// (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space
			var expr;
			operator = operator || "";
			lftPrn = lftPrn || lftPrn0 || lftPrn2;
			path = path || path2;
			prn = prn || prn2 || "";

			function parsePath(allPath, not, object, helper, view, viewProperty, pathTokens, leafToken) {
				// rPath = /^(?:null|true|false|\d[\d.]*|(!*?)([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
				//                                        none   object     helper    view  viewProperty pathTokens      leafToken
				if (object) {
					if (bindings) {
						if (named === "linkTo") {
							bindto = bindings._jsvto = bindings._jsvto || [];
							bindto.push(path);
						}
						if (!named || boundName) {
							bindings.push(path.slice(not.length)); // Add path binding for paths on props and args,
//							list.push(path);
						}
					}
					if (object !== ".") {
						var ret = (helper
								? 'view.hlp("' + helper + '")'
								: view
									? "view"
									: "data")
							+ (leafToken
								? (viewProperty
									? "." + viewProperty
									: helper
										? ""
										: (view ? "" : "." + object)
									) + (pathTokens || "")
								: (leafToken = helper ? "" : view ? viewProperty || "" : object, ""));

						ret = ret + (leafToken ? "." + leafToken : "");

						return not + (ret.slice(0, 9) === "view.data"
							? ret.slice(5) // convert #view.data... to data...
							: ret);
					}
				}
				return allPath;
			}

			if (err) {
				syntaxError(params);
			} else {
				if (bindings && rtPrnDot && !aposed && !quoted) {
					// This is a binding to a path in which an object is returned by a helper/data function/expression, e.g. foo()^x.y or (a?b:c)^x.y
					// We create a compiled function to get the object instance (which will be called when the dependent data of the subexpression changes, to return the new object, and trigger re-binding of the subsequent path)
					if (!named || boundName || bindto) {
						expr = pathStart[parenDepth];
						if (full.length - 1 > index - expr) { // We need to compile a subexpression
							expr = full.slice(expr, index + 1);
							rtPrnDot = delimOpenChar1 + ":" + expr + delimCloseChar0; // The parameter or function subexpression
							//TODO Optimize along the lines of:
							//var paths = [];
							//rtPrnDot = tmplLinks[rtPrnDot] = tmplLinks[rtPrnDot] || tmplFn(delimOpenChar0 + rtPrnDot + delimCloseChar1, tmpl, true, paths); // Compile the expression (or use cached copy already in tmpl.links)
							//rtPrnDot.paths = rtPrnDot.paths || paths;

							rtPrnDot = tmplLinks[rtPrnDot] = tmplLinks[rtPrnDot] || tmplFn(delimOpenChar0 + rtPrnDot + delimCloseChar1, tmpl, true); // Compile the expression (or use cached copy already in tmpl.links)
							if (!rtPrnDot.paths) {
								parseParams(expr, rtPrnDot.paths = [], tmpl);
							}
							(bindto || bindings).push({_jsvOb: rtPrnDot}); // Insert special object for in path bindings, to be used for binding the compiled sub expression ()
							//list.push({_jsvOb: rtPrnDot});
						}
					}
				}
				return (aposed
					// within single-quoted string
					? (aposed = !apos, (aposed ? all : '"'))
					: quoted
					// within double-quoted string
						? (quoted = !quot, (quoted ? all : '"'))
						:
					(
						(lftPrn
								? (parenDepth++, pathStart[parenDepth] = index++, lftPrn)
								: "")
						+ (space
							? (parenDepth
								? ""
								//: (pushBindings(), named
								//	: ",")
								: named
									? (named = boundName = bindto = false, "\b")
									: ","
							)
							: eq
					// named param
					// Insert backspace \b (\x08) as separator for named params, used subsequently by rBuildHash
								? (parenDepth && syntaxError(params), named = path, boundName = bound, /*pushBindings(),*/ '\b' + path + ':')
								: path
					// path
									? (path.split("^").join(".").replace(rPath, parsePath)
										+ (prn
											? (fnCall[++parenDepth] = true, path.charAt(0) !== "." && (pathStart[parenDepth] = index), prn)
											: operator)
									)
									: operator
										? operator
										: rtPrn
					// function
											? ((fnCall[parenDepth--] = false, rtPrn)
												+ (prn
													? (fnCall[++parenDepth] = true, prn)
													: "")
											)
											: comma
												? (fnCall[parenDepth] || syntaxError(params), ",") // We don't allow top-level literal arrays or objects
												: lftPrn0
													? ""
													: (aposed = apos, quoted = quot, '"')
					))
				);
			}
		}

		var named, bindto, boundName, // list,
			tmplLinks = tmpl.links,
			fnCall = {},
			pathStart = {0:-1},
			parenDepth = 0,
			quoted = false, // boolean for string content in double quotes
			aposed = false; // or in single quotes

		//pushBindings();

		return (params + " ")
			.replace(/\)\^/g, ").") // Treat "...foo()^bar..." as equivalent to "...foo().bar..."
								//since preceding computed observables in the path will always be updated if their dependencies change
			.replace(rParams, parseTokens);
	}

	//==========
	// Utilities
	//==========

	// Merge objects, in particular contexts which inherit from parent contexts
	function extendCtx(context, parentContext) {
		// Return copy of parentContext, unless context is defined and is different, in which case return a new merged context
		// If neither context nor parentContext are defined, return undefined
		return context && context !== parentContext
			? (parentContext
				? $extend($extend({}, parentContext), context)
				: context)
			: parentContext && $extend({}, parentContext);
	}

	// Get character entity for HTML and Attribute encoding
	function getCharEntity(ch) {
		return charEntities[ch] || (charEntities[ch] = "&#" + ch.charCodeAt(0) + ";");
	}

	//========================== Initialize ==========================

	for (jsvStoreName in jsvStores) {
		registerStore(jsvStoreName, jsvStores[jsvStoreName]);
	}

	var $templates = $views.templates,
		$converters = $views.converters,
		$helpers = $views.helpers,
		$tags = $views.tags,
		$viewsSub = $views.sub,
		$viewsSettings = $views.settings,
		noIndex = "Error: #index in nested view: use #getIndex()"; // Error string if debugMode, else empty

	if (jQuery) {
		////////////////////////////////////////////////////////////////////////////////////////////////
		// jQuery is loaded, so make $ the jQuery object
		$ = jQuery;
		$.fn.render = renderContent;

	} else {
		////////////////////////////////////////////////////////////////////////////////////////////////
		// jQuery is not loaded.

		$ = global.jsviews = {};

		$.isArray = Array && Array.isArray || function(obj) {
			return Object.prototype.toString.call(obj) === "[object Array]";
		};

	//	//========================== Future Node.js support ==========================
	//	if ((nodeJsModule = global.module) && nodeJsModule.exports) {
	//		nodeJsModule.exports = $;
	//	}
	}

	$.render = $render;
	$.views = $views;
	$.templates = $templates = $views.templates;

	//========================== Register tags ==========================

	$tags({
		"else": function() {}, // Does nothing but ensures {{else}} tags are recognized as valid
		"if": {
			render: function(val) {
				// This function is called once for {{if}} and once for each {{else}}.
				// We will use the tag.rendering object for carrying rendering state across the calls.
				// If not done (a previous block has not been rendered), look at expression for this block and render the block if expression is truthy
				// Otherwise return ""
				var self = this,
					ret = (self.rendering.done || !val && (arguments.length || !self.tagCtx.index))
						? ""
						: (self.rendering.done = true, self.selected = self.tagCtx.index,
							// Test is satisfied, so render content on current context. We call tagCtx.render() rather than return undefined
							// (which would also render the tmpl/content on the current context but would iterate if it is an array)
							self.tagCtx.render());
				return ret;
			},
			onUpdate: function(ev, eventArgs, tagCtxs) {
				var tci, prevArg, different;
				for (tci = 0; (prevArg = this.tagCtxs[tci]) && prevArg.args.length; tci++) {
					prevArg = prevArg.args[0];
					different = !prevArg !== !tagCtxs[tci].args[0];
					if (!!prevArg || different) {
						return different;
						// If newArg and prevArg are both truthy, return false to cancel update. (Even if values on later elses are different, we still don't want to update, since rendered output would be unchanged)
						// If newArg and prevArg are different, return true, to update
						// If newArg and prevArg are both falsey, move to the next {{else ...}}
					}
				}
				// Boolean value of all args are unchanged (falsey), so return false to cancel update
				return false;
			},
			flow: true
		},
		"for": {
			render: renderForBlock,
			//onUpdate: function(ev, eventArgs, tagCtxs) {
				//Consider adding filtering for perf optimization. However the below prevents update on some scenarios which _should_ update - namely when there is another array on which for also depends.
				//var i, l, tci, prevArg;
				//for (tci = 0; (prevArg = this.tagCtxs[tci]) && prevArg.args.length; tci++) {
				//	if (prevArg.args[0] !== tagCtxs[tci].args[0]) {
				//		return true;
				//	}
				//}
				//return false;
			//},
			onArrayChange: function(ev, eventArgs) {
				var arrayView,
					self = this,
					change = eventArgs.change;
				if (this.tagCtxs[1] && ( // There is an {{else}}
							 change === "insert" && ev.target.length === eventArgs.items.length // inserting, and new length is same as inserted length, so going from 0 to n
						|| change === "remove" && !ev.target.length // removing , and new length 0, so going from n to 0
						|| change === "refresh" && !eventArgs.oldItems.length !== !ev.target.length // refreshing, and length is going from 0 to n or from n to 0
					)) {
					this.refresh();
				} else {
					for (arrayView in self._.arrVws) {
						arrayView = self._.arrVws[arrayView];
						if (arrayView.data === ev.target) {
							arrayView._.onArrayChange.apply(arrayView, arguments);
						}
					}
				}
				ev.done = true;
			},
			flow: true
		},
		props: {
			prep: function(object) {
				var key,
					arr = [];
				for (key in object) {
					arr.push({key: key, prop: object[key]});
				}
				return arr;
			},
			render: renderForBlock,
			flow: true
		},
		include: {
			flow: true
		},
		"*": {
			// {{* code... }} - Ignored if template.allowCode is false. Otherwise include code in compiled template
			render: function(value) {
				return value; // Include the code.
			},
			flow: true
		}
	});

	function renderForBlock(val) {
		// This function is called once for {{for}} and once for each {{else}}.
		// We will use the tag.rendering object for carrying rendering state across the calls.
		var self = this,
			tagCtx = self.tagCtx,
			noArg = !arguments.length,
			result = "",
			done = noArg || 0;

		if (!self.rendering.done) {
			if (noArg) {
				result = undefined;
			} else if (val !== undefined) {
				val = self.prep ? self.prep(val) : val;
				result += tagCtx.render(val);
				done += $.isArray(val) ? val.length : 1;
			}
			if (self.rendering.done = done) {
				self.selected = tagCtx.index;
			}
			// If nothing was rendered we will look at the next {{else}}. Otherwise, we are done.
		}
		return result;
	}
	//========================== Register converters ==========================

	$converters({
		html: function(text) {
			// HTML encode: Replace < > & and ' and " by corresponding entities.
			return text != undefined ? String(text).replace(rHtmlEncode, getCharEntity) : ""; // null and undefined return ""
		},
		attr: function(text) {
			// Attribute encode: Replace < > & ' and " by corresponding entities.
			return text != undefined ? String(text).replace(rAttrEncode, getCharEntity) : text === null ? text : ""; // null returns null, e.g. to remove attribute. undefined returns ""
		},
		url: function(text) {
			// URL encoding helper.
			return text != undefined ? encodeURI(String(text)) : text === null ? text : ""; // null returns null, e.g. to remove attribute. undefined returns ""
		}
	});

	//========================== Define default delimiters ==========================
	$viewsDelimiters();

})(this, this.jQuery);

license: mit


code:
// NanoBaseHelpers is where the base template helpers (common to all templates) are stored
NanoBaseHelpers = function ()
{
	var _urlParameters = {}; // This is populated with the base url parameters (used by all links), which is probaby just the "src" parameter

	var init = function ()
	{
		var body = $('body'); // We store data in the body tag, it's as good a place as any

		_urlParameters = body.data('urlParameters');

		initHelpers();
	};

	var initHelpers = function ()
	{
		$.views.helpers({

			// Generate a Byond link
			link: function( text, icon, parameters, status, elementClass, elementId) {

				var iconHtml = '';
				var iconClass = 'noIcon';
				if (typeof icon != 'undefined' && icon)
				{
					iconHtml = '

';
					iconClass = 'hasIcon';
				}

				if (typeof elementClass == 'undefined' || !elementClass)
				{
					elementClass = '';
				}

				var elementIdHtml = '';
				if (typeof elementId != 'undefined' && elementId)
				{
					elementIdHtml = 'id="' + elementId + '"';
				}

				if (typeof status != 'undefined' && status)
				{
					return '
' + iconHtml + text + '
';
				}

				return '
' + iconHtml + text + '
';
			},
			// Round a number to the nearest integer
			round: function(number) {
				return Math.round(number);
			},
			// Round a number down to integer
			floor: function(number) {
				return Math.floor(number);
			},
			// Round a number up to integer
			ceil: function(number) {
				return Math.ceil(number);
			},
			// Format a string (~string("Hello {0}, how are {1}?", 'Martin', 'you') becomes "Hello Martin, how are you?")
			string: function() {
				if (arguments.length == 0)
				{
					return '';
				}
				else if (arguments.length == 1)
				{
					return arguments[0];
				}
				else if (arguments.length > 1)
				{
					stringArgs = [];
					for (var i = 1; i < arguments.length; i++)
					{
						stringArgs.push(arguments[i]);
					}
					return arguments[0].format(stringArgs);
				}
				return '';
			},
			// Display a bar. Used to show health, capacity, etc.
			displayBar: function(value, rangeMin, rangeMax, styleClass, showText) {

				if (rangeMin < rangeMax)
                {
                    if (value < rangeMin)
                    {
                        value = rangeMin;
                    }
                    else if (value > rangeMax)
                    {
                        value = rangeMax;
                    }
                }
                else
                {
                    if (value > rangeMin)
                    {
                        value = rangeMin;
                    }
                    else if (value < rangeMax)
                    {
                        value = rangeMax;
                    }
                }

				if (typeof styleClass == 'undefined' || !styleClass)
				{
					styleClass = '';
				}

				if (typeof showText == 'undefined' || !showText)
				{
					showText = '';
				}

				var percentage = Math.round((value - rangeMin) / (rangeMax - rangeMin) * 100);

				return '

' + showText + '

';
			},
			// Display DNA Blocks (for the DNA Modifier UI)
			displayDNABlocks: function(dnaString, selectedBlock, selectedSubblock, blockSize, paramKey) {
			    if (!dnaString)
				{
					return '
Please place a valid subject into the DNA modifier.
';
				}

				var characters = dnaString.split('');

                var html = '

1
';
                var block = 1;
                var subblock = 1;
                for (index in characters)
                {
					if (!characters.hasOwnProperty(index) || typeof characters[index] === 'object')
					{
						continue;
					}

					var parameters;
					if (paramKey.toUpperCase() == 'UI')
					{
						parameters = { 'selectUIBlock' : block, 'selectUISubblock' : subblock };
					}
					else
					{
						parameters = { 'selectSEBlock' : block, 'selectSESubblock' : subblock };
					}

                    var status = 'linkActive';
                    if (block == selectedBlock && subblock == selectedSubblock)
                    {
                        status = 'selected';
                    }

                    html += '
' + characters[index] + '
'

                    index++;
                    if (index % blockSize == 0 && index < characters.length)
                    {
						block++;
                        subblock = 1;
                        html += '

' + block + '
';
                    }
                    else
                    {
                        subblock++;
                    }
                }

                html += '
';

				return html;
			}
		});
	};

	// generate a Byond href, combines _urlParameters with parameters
	var generateHref = function (parameters)
	{
		var queryString = '?';

		for (var key in _urlParameters)
		{
			if (_urlParameters.hasOwnProperty(key))
			{
				if (queryString !== '?')
				{
					queryString += ';';
				}
				queryString += key + '=' + _urlParameters[key];
			}
		}

		for (var key in parameters)
		{
			if (parameters.hasOwnProperty(key))
			{
				if (queryString !== '?')
				{
					queryString += ';';
				}
				queryString += key + '=' + parameters[key];
			}
		}
		return queryString;
	};

	return {
        init: function ()
		{
            init();
        }
	};
} ();

$(document).ready(function()
{
	NanoBaseHelpers.init();
});


code:
// NanoConfig is the place to store utility functions
var NanoConfig = function ()
{
    return {
        init: function ()
		{
			if (typeof jQuery == 'undefined') {
				alert('ERROR: jQuery failed to load!');
			}
			if (typeof $.views == 'undefined') {
				alert('ERROR: JSRender failed to load!');
			}
        }
    }
} ();

NanoConfig.init();

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(elt /*, from*/)
    {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++)
        {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
};

if (!String.prototype.format)
{
    String.prototype.format = function (args) {
        var str = this;
        return str.replace(String.prototype.format.regex, function(item) {
            var intVal = parseInt(item.substring(1, item.length - 1));
            var replace;
            if (intVal >= 0) {
                replace = args[intVal];
            } else if (intVal === -1) {
                replace = "{";
            } else if (intVal === -2) {
                replace = "}";
            } else {
                replace = "";
            }
            return replace;
        });
    };
    String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
};

Object.size = function(obj) {
    var size = 0, key;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

if(!window.console) {
    window.console = {
        log : function(str) {
            return false;
        }
    };
};

String.prototype.toTitleCase = function () {
    var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;

    return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {
        if (index > 0 && index + p1.length !== title.length &&
            p1.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
            title.charAt(index - 1).search(/[^\s-]/) < 0) {
            return match.toLowerCase();
        }

        if (p1.substr(1).search(/[A-Z]|\../) > -1) {
            return match;
        }

        return match.charAt(0).toUpperCase() + match.substr(1);
    });
};

$.ajaxSetup({
    cache: false
});


code:
// NanoUpdate handles data from the server and uses it to render templates
NanoUpdate = function ()
{
	// _isInitialised is set to true when all of this ui's templates have been processed/rendered
	var _isInitialised = false;

	// the array of template names to use for this ui
	var _templates = null;
	// the data for this ui
	var _data = null;
	// new data which arrives before _isInitialised is true is stored here for processing later
	var _earlyUpdateData = null;

	// this is an array of callbacks which are called when new data arrives, before it is processed
	var _beforeUpdateCallbacks = [];
	// this is an array of callbacks which are called when new data arrives, before it is processed
	var _afterUpdateCallbacks = [];

	// _canClick is used to disable clicks for a short period after each click (to avoid mis-clicks)
	var _canClick = true;

	// the init function is called when the ui has loaded
	// this function sets up the templates and base functionality
	var init = function ()
	{
		$('#uiNoJavaScript').html('Loading...');

		// this callback is triggered after new data is processed
		// it updates the status/visibility icon and adds click event handling to buttons/links
		NanoUpdate.addAfterUpdateCallback(function (updateData) {
			var uiStatusClass;
			if (updateData['ui']['status'] == 2)
			{
				uiStatusClass = 'icon24 uiStatusGood';
				$('.linkActive').removeClass('inactive');
			}
			else if (updateData['ui']['status'] == 1)
			{
				uiStatusClass = 'icon24 uiStatusAverage';
				$('.linkActive').addClass('inactive');
			}
			else
			{
				uiStatusClass = 'icon24 uiStatusBad'
				$('.linkActive').addClass('inactive');
			}
			$('#uiStatusIcon').attr('class', uiStatusClass);

			$('.linkActive').stopTime('linkPending');
			$('.linkActive').removeClass('linkPending');

			$('.linkActive').off('click');
			$('.linkActive').on('click', function (event) {
				event.preventDefault();
				var href = $(this).data('href');
				if (href != null && _canClick)
				{
					_canClick = false;
					$('body').oneTime(300, 'enableClick', function () {
						_canClick = true;
					});
					if (updateData['ui']['status'] == 2)
					{
						$(this).oneTime(300, 'linkPending', function () {
							$(this).addClass('linkPending');
						});
					}
					window.location.href = href;
				}
			});
		});

		// We store initialData and templateData in the body tag, it's as good a place as any
		var body = $('body');
		var templateData = body.data('templateData');
		var initialData = body.data('initialData');

		if (templateData == null || !initialData == null)
		{
			alert('Error: Initial data did not load correctly.');
		}

		// we count the number of templates for this ui so that we know when they've all been rendered
		var templateCount = 0;
		for (var key in templateData)
		{
			if (templateData.hasOwnProperty(key))
			{
				templateCount++;
			}
		}

		if (!templateCount)
		{
			alert('ERROR: No templates listed!');
		}

		// load markup for each template and register it
		for (var key in templateData)
		{
			if (templateData.hasOwnProperty(key))
			{
				$.when($.get(templateData[key]))
					.done(function(templateMarkup) {
						if (_templates == null)
						{
							_templates = {};
						}

						templateMarkup = templateMarkup.replace(/ +\) *\}\}/g, ')}}');

						templateMarkup += '

'

						try
						{
							_templates[key] = $.templates(key, templateMarkup);

							templateCount--;

							if (templateCount <= 0)
							{
								if (_earlyUpdateData !== null) // Newer data has already arrived, so update
								{
									renderTemplates(_earlyUpdateData);
								}
								else
								{
									renderTemplates(initialData);
								}
								_isInitialised = true;
								$('#uiNoJavaScript').hide();
							}

							executeCallbacks(_afterUpdateCallbacks, _data);
						}
						catch(error)
						{
							alert('ERROR: An error occurred while loading the UI: ' + error.message);
							return;
						}
					});
			}
		}
	};

	// Receive update data from the server
	var receiveUpdateData = function (jsonString)
	{
		var updateData;
		try
		{
			// parse the JSON string from the server into a JSON object
			updateData = jQuery.parseJSON(jsonString);
		}
		catch (error)
		{
			alert(error.Message);
			return;
		}

		if (_isInitialised) // all templates have been registered, so render them
		{
			executeCallbacks(_beforeUpdateCallbacks, updateData);

			renderTemplates(updateData);

			executeCallbacks(_afterUpdateCallbacks, updateData);
		}
		else
		{
			_earlyUpdateData = updateData; // all templates have not been registered. We set _earlyUpdateData which will be applied after the template is loaded with the initial data
		}
	};

	// This function renders the template with the latest data
	// It has to be done recursively as each piece of data is observed individually and needs to be updated individually
	var renderTemplates = function (data)
	{
		if (!_templates.hasOwnProperty("main"))
		{
			alert('Error: Main template not found.');
		}

		_data = data;

		try
		{
			$("#mainTemplate").html(_templates["main"].render(_data));
		}
		catch(error)
		{
			alert('ERROR: An error occurred while rendering the UI: ' + error.message);
			return;
		}
	};

	// Execute all callbacks in the callbacks array/object provided, updateData is passed to them for processing
	var executeCallbacks = function (callbacks, updateData)
	{
		for (var index in callbacks)
		{
			callbacks[index].call(this, updateData);
		}

		return updateData;
	};

	return {
        init: function ()
		{
            init();
        },
		isInitialised: function ()
		{
            return _isInitialised;
        },
		receiveUpdateData: function (jsonString)
		{
			receiveUpdateData(jsonString);
        },
		addBeforeUpdateCallback: function (callbackFunction)
		{
			_beforeUpdateCallbacks.push(callbackFunction);
		},
		addAfterUpdateCallback: function (callbackFunction)
		{
			_afterUpdateCallbacks.push(callbackFunction);
		}
	};
} ();

$(document).ready(function()
{
	NanoUpdate.init();
});


code:
--------------------------------
Nano UI Template Guide
--------------------------------

Nano UI uses templates, which are comprised of HTML and a markup syntax. The markup allows you
to easily add conditionals (if statements), loops (for loops) and custom formatting (using helpers).

Templates are stored in the /nano/templates folder and the file extension is .tmpl.

This guide is being replaced with a wiki entry, found here: http://baystation12.net/wiki/index.php?title=NanoUI


code:
	{{if siliconUser}}

			Interface Lock:

			{{:~link('Engaged', 'locked', {'toggleaccess' : 1}, locked ? 'selected' : null)}}{{:~link('Disengaged', 'unlocked', {'toggleaccess' : 1}, (locked ? null : 'selected'))}}

	{{else}}
		{{if locked}}
			Swipe an ID card to unlock this interface.
		{{else}}
			Swipe an ID card to lock this interface.
		{{/if}}
	{{/if}}

Air Status

{{if environment_data}}
	{{for environment_data}}
		{{:name}}
		{{if danger_level == 2}}

		{{else danger_level == 1}}

		{{else}}

		{{/if}}
		{{:~round(value*100)/100}}
		{{:unit}}

	{{/for}}
	Local Status: {{if danger_level == 2}}
			DANGER: Internals Required
		{{else danger_level == 1}}
			Caution
		{{else}}
			Optimal
		{{/if}}

    Area Status: {{if atmos_alarm}}Atmosphere alert in area{{else fire_alarm}}Fire alarm in area{{else}}No alerts{{/if}}
{{else}}
	Warning: Cannot obtain air sample for analysis.
{{/if}}
{{if dangerous}}

NOTICE: Safety measures nonfunctional. Device may exhibit abnormal behavior.
{{/if}}

{{if (!locked || siliconUser)}}
    {{if screen != 1}}

{{:~link('Main Menu', null, { 'screen' : 1})}}

    {{/if}}
    {{if screen == 1}}

            {{if atmos_alarm}}
                {{:~link('Reset - Area Atmospheric Alarm', null, { 'atmos_reset' : 1})}}
            {{else}}
                {{:~link('Activate - Area Atmospheric Alarm', null, { 'atmos_alarm' : 1})}}
            {{/if}}

                {{:~link('Scrubbers Control', null, { 'screen' : 3})}}

                {{:~link('Vents Control', null, { 'screen' : 2})}}

                {{:~link('Set Environmental Mode', null, { 'screen' : 4})}}

                {{:~link('Sensor Settings', null, { 'screen' : 5})}}

            {{if mode==3}}
                {{:~link('PANIC SIPHON ACTIVE - Turn siphoning off', null, { 'mode' : 1}, null, 'redButton')}}
			{{else}}
                {{:~link('ACTIVATE PANIC SIPHON IN AREA', null, { 'mode' : 3}, null, 'yellowButton')}}
            {{/if}}
    {{else screen == 2}}
		{{for vents}}

{{:long_name}}

					Operating:

					{{:~link(power ? 'On' : 'Off', null, { 'id_tag' : id_tag, 'command' : 'power', 'val' : power ? 0 : 1}, null, power ? null : 'redButton')}}

					Mode:

					{{:direction == "siphon" ? 'Siphoning' : 'Pressurizing'}}

					Pressure Checks:

					{{:~link('External', null, { 'id_tag' : id_tag, 'command' : 'excheck', 'val' : checks}, null, excheck ? 'selected' : null)}}
					{{:~link('Internal', null, { 'id_tag' : id_tag, 'command' : 'incheck', 'val' : checks}, null, incheck ? 'selected' : null)}}

					External Pressure Bound:

					{{:~link(~round(external*100)/100, null, { 'id_tag' : id_tag, 'command' : 'set_external_pressure'})}}
					{{:~link('Reset', null, { 'id_tag' : id_tag, 'command' : 'reset_external_pressure'})}}

		{{/for}}
		{{if !vents.length}}
			No vents connected.
		{{/if}}
    {{else screen == 3}}
		{{for scrubbers}}

{{:long_name}}

					Operating:

					{{:~link(power ? 'On' : 'Off', null, { 'id_tag' : id_tag, 'command' : 'power', 'val' : power ? 0 : 1}, null, power ? null : 'redButton')}}

					Mode:

					{{:~link(scrubbing ? 'Scrubbing' : 'Siphoning', null, { 'id_tag' : id_tag, 'command' : 'scrubbing', 'val' : scrubbing ? 0 : 1}, null, scrubbing ? null : 'redButton')}}

					Filters:

					{{:~link("Carbon Dioxide", null, { 'id_tag' : id_tag, 'command' : "co2_scrub", 'val' : filter_co2 ? 0 : 1}, null, filter_co2 ? 'selected' : null)}}

					{{:~link("Plasma", null, { 'id_tag' : id_tag, 'command' : "tox_scrub", 'val' : filter_toxins ? 0 : 1}, null, filter_toxins ? 'selected' : null)}}

					{{:~link("Nitrous Oxide", null, { 'id_tag' : id_tag, 'command' : "n2o_scrub", 'val' : filter_n2o ? 0 : 1}, null, filter_n2o ? 'selected' : null)}}

		{{/for}}
		{{if !scrubbers.length}}
			No scrubbers connected.
		{{/if}}
    {{else screen == 4}}

Environmental Modes

		{{for modes}}

				{{:~link(name, null, { 'mode' : mode }, null, selected ? (danger ? 'redButton' : 'selected') : (danger ? 'bad' : null))}}

		{{/for}}
    {{else screen == 5}}

Alarm Threshold

		Partial pressure for gases.

				min2	min1	max1	max2

		{{for thresholds}}

				{{:name}}
				{{for settings}}

						{{:~link(selected >= 0 ? ~round(selected*100)/100 : "Off", null, { 'command' : 'set_threshold', 'env' : env, 'var' : val })}}

				{{/for}}

		{{/for}}

    {{/if}}
{{/if}}


code:
Status:

	{{if active}}

Injecting

	{{else}}

Standby

	{{/if}}
	 {{:~link("Toggle Status", "gear", {"togglestatus":1},null)}}

{{if !fueljar}}

No fuel jar detected.

{{else}}

Fuel:

{{:fueljar.fuel}}/{{:fueljar.fuel_max}}

			{{:~link("Eject", "eject", {"ejectjar":1},null,'floatRight')}}

Injecting:

				{{:~link(fueljar.injecting+" units", 'carat-2-n-s', {'set_strength': 1})}}

{{/if}}

Stability:

			{{:~displayBar(stability,0,100,"good")}}
			{{:stability}}%

Shielding Count:

{{:linked_shields}}

Cores:

{{:linked_cores}}

		{{:~link("Refresh Parts",null,{"refreshicons" : 1},(active?"disabled":null),'floatRight')}}

Current Efficiency:

{{:efficiency}}

Average Efficiency:

{{:stability}}

Last Produced:

{{:stored_power}}


code:
	{{if siliconUser}}

			Interface Lock:

			{{:~link('Engaged', 'locked', {'toggleaccess' : 1}, locked ? 'selected' : null)}}{{:~link('Disengaged', 'unlocked', {'toggleaccess' : 1}, malfStatus >= 2 ? 'linkOff' : (locked ? null : 'selected'))}}

	{{else}}
		{{if locked}}
			Swipe an ID card to unlock this interface.
		{{else}}
			Swipe an ID card to lock this interface.
		{{/if}}
	{{/if}}

Power Status

			Main Breaker:

			{{if locked && !siliconUser}}
				{{if isOperating}}
					On
				{{else}}
					Off
				{{/if}}
			{{else}}
				{{:~link('On', 'power', {'breaker' : 1}, isOperating ? 'selected' : null)}}{{:~link('Off', 'close', {'breaker' : 1}, isOperating ? null : 'selected')}}
			{{/if}}

			External Power:

			{{if externalPower == 2}}
				Good
			{{else externalPower == 1}}
				Low
			{{else}}
				None
			{{/if}}

			Power Cell:

		{{if powerCellStatus == null}}

				Power cell removed.

		{{else}}

				{{:~round(powerCellStatus*10)/10}}%

			{{:~displayBar(powerCellStatus, 0, 100, powerCellStatus >= 50 ? 'good' : powerCellStatus >= 25 ? 'average' : 'bad')}}
		{{/if}}

	{{if powerCellStatus != null}}

				Charge Mode:

				{{if locked && !siliconUser}}
					{{if chargeMode}}
						Auto
					{{else}}
						Off
					{{/if}}
				{{else}}
					{{:~link('Auto', 'refresh', {'cmode' : 1}, chargeMode ? 'selected' : null)}}{{:~link('Off', 'close', {'cmode' : 1}, chargeMode ? null : 'selected')}}
				{{/if}}

				{{if chargingStatus > 1}}
					[Fully Charged]
				{{else chargingStatus == 1}}
					[Charging]
				{{else}}
					[Not Charging]
				{{/if}}

	{{/if}}

Power Channels

	{{for powerChannels}}

				{{:title}}:

				{{:powerLoad}} W

				{{if status <= 1}}
					Off
				{{else status >= 2}}
					On
				{{/if}}
				{{if status == 1 || status == 3}}
					[Auto]
				{{else}}
					[Manual]
				{{/if}}

			{{if !~root.locked || ~root.siliconUser}}

					{{:~link('Auto', 'refresh', topicParams.auto, (status == 1 || status == 3) ? 'selected' : null)}}
					{{:~link('On', 'power', topicParams.on, (status == 2) ? 'selected' : null)}}
					{{:~link('Off', 'close', topicParams.off, (status == 0) ? 'selected' : null)}}

			{{/if}}

	{{/for}}

			Total Load:

			{{:totalLoad}} W

			Cover Lock:

			{{if locked && !siliconUser}}
				{{if coverLocked}}
					Engaged
				{{else}}
					Disengaged
				{{/if}}
			{{else}}
				{{:~link('Engaged', 'locked', {'lock' : 1}, coverLocked ? 'selected' : null)}}{{:~link('Disengaged', 'unlocked', {'lock' : 1}, coverLocked ? null : 'selected')}}
			{{/if}}

	{{if siliconUser}}

System Overrides

			{{:~link('Overload Lighting Circuit', 'lightbulb', {'overload' : 1})}}
			{{if malfStatus == 1}}
				{{:~link('Override Programming', 'script', {'malfhack' : 1})}}
			{{else malfStatus == 2}}
				{{:~link('Shunt Core Processes', 'arrowreturn-1-s', {'occupyapc' : 1})}}
			{{else malfStatus == 3}}
				{{:~link('Return to Main Core', 'arrowreturn-1-w', {'deoccupyapc' : 1})}}
			{{else malfStatus == 4}}
				{{:~link('Shunt Core Processes', 'arrowreturn-1-s', {'occupyapc' : 1}, 'linkOff')}}
			{{/if}}

	{{/if}}


code:
		Power:

		{{:~link(on? 'On' : 'Off', null, {'power' : 1})}}

		Output pressure:

			{{:~link('MAX', null, {'set_press' : 'max'}, null)}}
			{{:~link('SET', null, {'set_press' : 'set'}, null)}}

 {{:(pressure_set/100)}} kPa

Filter Type

		{{:~link('Plasma', null, {'filterset' :  0}, (filter_type ==  0)? 'selected' : null)}}

		{{:~link('Oxygen', null, {'filterset' :  1}, (filter_type ==  1)? 'selected' : null)}}

		{{:~link('Nitrogen', null, {'filterset' :  2}, (filter_type ==  2)? 'selected' : null)}}

		{{:~link('Carbon Dioxide', null, {'filterset' :  3}, (filter_type ==  3)? 'selected' : null)}}

		{{:~link('Nitrous Oxide', null, {'filterset' :  4}, (filter_type ==  4)? 'selected' : null)}}

		{{:~link('Nothing', null, {'filterset' :  -1}, (filter_type ==  -1)? 'selected' : null)}}


code:
		Power:

		{{:~link(on? 'On' : 'Off', null, {'power' : 1})}}

{{if max_rate}}

		Transfer rate:

			{{:~link('MAX', null, {'set_transfer_rate' : 'max'}, null)}}
			{{:~link('SET', null, {'set_transfer_rate' : 'set'}, null)}}

 {{:(transfer_rate/100)}} L/s

{{else}}

		Output pressure:

			{{:~link('MAX', null, {'set_press' : 'max'}, null)}}
			{{:~link('SET', null, {'set_press' : 'set'}, null)}}

 {{:(pressure_set/100)}} kPa

{{/if}}


code:
Tank Status

		Tank Label:

{{:name}}
 {{:~link('Relabel', 'pencil', {'relabel' : 1}, canLabel ? null : 'disabled')}}

		Tank Pressure:

		{{:tankPressure}} kPa

		Port Status:

		{{:portConnected ? 'Connected' : 'Disconnected'}}

Holding Tank Status

{{if hasHoldingTank}}

			Tank Label:

{{:holdingTank.name}}
 {{:~link('Eject', 'eject', {'remove_tank' : 1})}}

			Tank Pressure:

			{{:holdingTank.tankPressure}} kPa

{{else}}

No holding tank inserted.

{{/if}}

Release Valve Status

		Release Pressure:

		{{:~displayBar(releasePressure, minReleasePressure, maxReleasePressure)}}

			{{:~link('-', null, {'pressure_adj' : -1000}, (releasePressure > minReleasePressure) ? null : 'disabled')}}
			{{:~link('-', null, {'pressure_adj' : -100}, (releasePressure > minReleasePressure) ? null : 'disabled')}}
			{{:~link('-', null, {'pressure_adj' : -10}, (releasePressure > minReleasePressure) ? null : 'disabled')}}
			{{:~link('-', null, {'pressure_adj' : -1}, (releasePressure > minReleasePressure) ? null : 'disabled')}}

 {{:releasePressure}} kPa

			{{:~link('+', null, {'pressure_adj' : 1}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}
			{{:~link('+', null, {'pressure_adj' : 10}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}
			{{:~link('+', null, {'pressure_adj' : 100}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}
			{{:~link('+', null, {'pressure_adj' : 1000}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}

		Release Valve:

		{{:~link('Open', 'unlocked', {'toggle' : 1}, valveOpen ? 'selected' : null)}}{{:~link('Close', 'locked', {'toggle' : 1}, valveOpen ? null : 'selected')}}


code:
		Energy:

		{{:~displayBar(energy, 0, maxEnergy, 'good', energy + ' Units')}}

		Dispense:

		{{:~link('5', 'gear', {'amount' : 5}, (amount == 5) ? 'selected' : null)}}
		{{:~link('10', 'gear', {'amount' : 10}, (amount == 10) ? 'selected' : null)}}
		{{:~link('20', 'gear', {'amount' : 20}, (amount == 20) ? 'selected' : null)}}
		{{:~link('30', 'gear', {'amount' : 30}, (amount == 30) ? 'selected' : null)}}
		{{:~link('50', 'gear', {'amount' : 50}, (amount == 50) ? 'selected' : null)}}

		Chemical Dispenser

		{{for chemicals}}
			{{:~link(title, 'circle-arrow-s', commands, null, 'fixedLeft')}}
		{{/for}}

		Beaker Contents

		{{:~link('Eject Beaker', 'eject', {'ejectBeaker' : 1}, isBeakerLoaded ? null : 'disabled', 'floatRight')}}

			{{if isBeakerLoaded}}
				Volume: {{:beakerCurrentVolume}} / {{:beakerMaxVolume}}

				{{for beakerContents}}
					{{:volume}} units of {{:name}}

				{{else}}
					Beaker is empty
				{{/for}}
			{{else}}
				No beaker loaded
			{{/if}}


code:
		Status:

		{{:~link(isActive ? 'On' : 'Off', 'power', {'toggle_on' : 1}, isBeakerLoaded ? null : 'disabled')}}

		Target:

	        {{:~link(targetTemp + 'K', 'gear', {'adjust_temperature' : 'input'}, null)}}

		Beaker

		{{:~link('Eject', 'eject', {'eject_beaker' : 1}, isBeakerLoaded ? null : 'disabled', 'floatRight')}}

			{{if isBeakerLoaded}}
				Volume: {{:beakerCurrentVolume}} / {{:beakerMaxVolume}}

				Temperature: {{:currentTemp}} Kelvin

				{{for beakerContents}}
					{{:volume}} units of {{:name}}

				{{else}}
					Beaker is empty
				{{/for}}
			{{else}}
				No beaker loaded
			{{/if}}


code:
Cryo Cell Status

	{{if !hasOccupant}}

Cell Unoccupied

	{{else}}

			{{:occupant.name}} =>
			{{if occupant.stat == 0}}
				Conscious
			{{else occupant.stat == 1}}
				Unconscious
			{{else}}
				DEAD
			{{/if}}

		{{if occupant.stat < 2}}

Health:

				{{if occupant.health >= 0}}
					{{:~displayBar(occupant.health, 0, occupant.maxHealth, 'good')}}
				{{else}}
					{{:~displayBar(occupant.health, 0, occupant.minHealth, 'average alignRight')}}
				{{/if}}

{{:~round(occupant.health)}}

=> Brute Damage:

				{{:~displayBar(occupant.bruteLoss, 0, occupant.maxHealth, 'bad')}}

{{:~round(occupant.bruteLoss)}}

=> Resp. Damage:

				{{:~displayBar(occupant.oxyLoss, 0, occupant.maxHealth, 'bad')}}

{{:~round(occupant.oxyLoss)}}

=> Toxin Damage:

				{{:~displayBar(occupant.toxLoss, 0, occupant.maxHealth, 'bad')}}

{{:~round(occupant.toxLoss)}}

=> Burn Severity:

				{{:~displayBar(occupant.fireLoss, 0, occupant.maxHealth, 'bad')}}

{{:~round(occupant.fireLoss)}}

		{{/if}}
	{{/if}}

Cell Temperature:

		{{:~string('{1} K', cellTemperatureStatus, cellTemperature)}}

		{^{:~link('Open', 'unlocked', {'open' : 1}, isOpen ? 'selected' : null)}}{^{:~link('Close', 'locked', {'close' : 1}, isOpen ? null : 'selected')}}

Cryo Cell Operation

		Cryo Cell Status:

		{{:~link('On', 'power', {'switchOn' : 1}, isOperating ? 'selected' : null)}}{{:~link('Off', 'close', {'switchOff' : 1}, isOperating ? null : 'selected')}}

		Beaker:

		{{if isBeakerLoaded}}
			{{for beakerContents}}
				{{:volume}} units of {{:name}}

			{{else}}
				Beaker is empty
			{{/for}}
		{{else}}
			No beaker loaded
		{{/if}}

		{{:~link('Eject Beaker', 'eject', {'ejectBeaker' : 1}, isBeakerLoaded ? null : 'disabled')}}


code:
	Superconducting Magnetic Energy Storage

		Capacity

		{{:~round(capacity)}} W

		Total Charge

		{{:~round(charge)}} W

		{{:~displayBar(capacityPercent, 0, 100, capacityPercent >= 50 ? 'good' : capacityPercent >= 15 ? 'average' : 'bad')}}

		{{:~round(capacityPercent*10)/10}}%

			Input:
			{{:~link('On', 'power', {'input_attempt' : 1}, inputAttempt ? 'selected' : null)}}
			{{:~link('Off', 'close', {'input_attempt' : 0}, inputAttempt == 0 ? 'selected' : null)}}

			{{if capacityPercent >= 99}}
				Fully Charged
			{{else inputting}}
				Charging
			{{else}}
				Not Charging
			{{/if}}

	{{:~link('0', 'seek-start', {'set_input_level' : '0'}, inputLevel == 0 ? 'selected' : null)}}
	{{:~link('', 'triangle-1-w', {'set_input_level' : 'minus'}, inputLevel == 0 ? 'disabled' : null)}}
	{{:~link('Change', 'gear', {'set_input_level' : 'custom'}, null)}}
	{{:~link('', 'triangle-1-e', {'set_input_level' : 'plus'}, inputLevel == inputLevelMax ? 'disabled' : null)}}
	{{:~link('Maximize', 'seek-end', {'set_input_level' : 'max'}, inputLevel == inputLevelMax ? 'selected' : null)}}

			Available

			{{if inputAvailable > inputLevel}}

			{{else}}

			{{/if}}
			{{:~round(inputAvailable)}} W

			Setting

			{{if inputLevel > outputLevel}}

			{{else inputLevel == outputLevel}}

			{{else}}

			{{/if}}
			{{:~round(inputLevel)}} W

			Max

			{{:~round(inputLevelMax)}} W

			Output:
			{{:~link('On', 'power', {'output_attempt' : 1}, outputAttempt ? 'selected' : null)}}
			{{:~link('Off', 'close', {'output_attempt' : 0}, outputAttempt == 0 ? 'selected' : null)}}

			{{if outputting}}
				Sending Ouput
			{{else charge > 0}}
				Not Sending Output
			{{else}}
				No Charge to Output
			{{/if}}

	{{:~link('0', 'seek-start', {'set_output_level' : '0'}, outputLevel == 0 ? 'selected' : null)}}
	{{:~link('', 'triangle-1-w', {'set_output_level' : 'minus'}, outputLevel == 0 ? 'disabled' : null)}}
	{{:~link('Change', 'gear', {'set_output_level' : 'custom'}, null)}}
	{{:~link('', 'triangle-1-e', {'set_output_level' : 'plus'}, outputLevel == outputLevelMax ? 'disabled' : null)}}
	{{:~link('Maximize', 'seek-end', {'set_output_level' : 'max'}, outputLevel == outputLevelMax ? 'selected' : null)}}

			Used

			{{if outputUsed >= outputLevel}}

			{{else}}

			{{/if}}
			{{:~round(outputUsed)}} W

			Setting

			{{if inputLevel > outputLevel}}

			{{else inputLevel == outputLevel}}

			{{else}}

			{{/if}}
			{{:~round(outputLevel)}} W

			Max

			{{:~round(outputLevelMax)}} W


code:
Status :

			Generated power :

			{{:generated)}} W

			Orientation :

		{{:angle)}}&deg ({{:direction}})

		{{:~link('15&deg', 'minus' ,{'rate_control' : '1', 'cdir' : '-15'})}}
		{{:~link('1&deg', 'minus' , { 'rate_control' : '1', 'cdir' : '-1'})}}
		{{:~link('1&deg', 'plus' , { 'rate_control' : '1', 'cdir' : '1'})}}
		{{:~link('15&deg', 'plus' , { 'rate_control' : '1', 'cdir' : '15'})}}

Tracking :

			Tracker status :

		{{:~link('Off', 'close' ,{'track' : '0'}, (tracking_state == 0)?'selected':'')}}
		{{:~link('Timed', 'clock' ,{'track' : '1'}, (tracking_state == 1)?'selected':'')}}
		{{if connected_tracker}}
			{{:~link('Auto', 'signal-diag' ,{'track' : '2'}, (tracking_state == 2)?'selected':'')}}
		{{else}}
			{{:~link('Auto', 'signal-diag' ,null, 'disabled')}}
		{{/if}}

			Tracking rate :

			 {{:tracking_rate)}} deg/h ({{:rotating_way}})

		{{:~link('180&deg', 'minus' ,{'rate_control' : '1', 'tdir' : '-180'})}}
		{{:~link('30&deg', 'minus' ,{'rate_control' : '1', 'tdir' : '-30'})}}
		{{:~link('1&deg', 'minus' , { 'rate_control' : '1', 'tdir' : '-1'})}}
		{{:~link('1&deg', 'plus' , { 'rate_control' : '1', 'tdir' : '1'})}}
		{{:~link('30&deg', 'plus' , { 'rate_control' : '1', 'tdir' : '30'})}}
		{{:~link('180&deg', 'plus' , { 'rate_control' : '1', 'tdir' : '180'})}}

Connected devices :

			Solars panels :

			{{:connected_panels)}} connected

			Solar tracker :

			{{if connected_tracker}}
				Found
			{{else}}
				Not found
			{{/if}}

	{{:~link('Search for devices', 'refresh' ,{'search_connected' : '1'})}}


code:
{{if maskConnected}}

This tank is connected to a mask.

{{else}}

This tank is NOT connected to a mask.

{{/if}}

		Tank Pressure:

		{{:~displayBar(tankPressure, 0, 1013, (tankPressure > 200) ? 'good' : ((tankPressure > 100) ? 'average' : 'bad'))}}

			{{:tankPressure}} kPa

		Mask Release Pressure:

		{{:~displayBar(releasePressure, 0, maxReleasePressure, (releasePressure >= 23) ? null : ((releasePressure >= 17) ? 'average' : 'bad'))}}

			{{:~link('-', null, {'dist_p' : -5}, (releasePressure > 0) ? null : 'disabled')}}
			{{:~link('-', null, {'dist_p' : -1}, (releasePressure > 0) ? null : 'disabled')}}

 {{:releasePressure}} kPa

			{{:~link('+', null, {'dist_p' : 1}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}
			{{:~link('+', null, {'dist_p' : 5}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}
			{{:~link('Max', null, {'dist_p' : 'max'}, (releasePressure < maxReleasePressure) ? null : 'disabled')}}
			{{:~link('Reset', null, {'dist_p' : 'reset'}, (releasePressure != defaultReleasePressure) ? null : 'disabled')}}

		Mask Release Valve:

		{{:~link('Open', 'unlocked', {'stat' : 1}, (!maskConnected) ? 'disabled' : (valveOpen ? 'selected' : null))}}{{:~link('Close', 'locked', {'stat' : 1}, valveOpen ? null : 'selected')}}