(function(){if(!Object.defineProperty)return;Object.defineProperty(Function.prototype,"initializing",{value:false,writable:true});Object.defineProperty(Function.prototype,"$super",{value:function(){throw new Error("The $super method is not available.");},writable:true});Function.prototype.inherit=function(init,props,reverse){if(arguments[1]===undefined&&typeof init!=="function"){props=arguments[0];init=undefined}props=props||{};var parent=this,prototype;try{this.initializing=true;prototype=new this;
this.initializing=false}catch(exc){throw new Error("Not possible to inherit from this function");}var createChildMethod=function(key,fn){return function(){var tmp=this.$super,_parent=parent.prototype,_super;do{_super=_parent;if(_parent.constructor===Object)break;_parent=Object.getPrototypeOf(_parent)}while(_super[key]===undefined);if(_super[key]!==undefined)this.$super=_super[key];var res=fn.apply(this,Array.prototype.slice.call(arguments));this.$super=tmp;return res}};Object.getOwnPropertyNames(props).forEach(function(key){if(typeof props[key]===
"function")prototype[key]=createChildMethod(key,props[key]);else{var desc=Object.getOwnPropertyDescriptor(prototype,key);if(desc===undefined||desc.configurable)Object.defineProperty(prototype,key,Object.getOwnPropertyDescriptor(props,key))}});var Function=function(){if(!this.constructor.initializing){var args=Array.prototype.slice.call(arguments);if(!reverse&&parent!==window.Function)parent.apply(this,args);if(typeof init==="function")init.apply(this,args);if(reverse&&parent!==window.Function)parent.apply(this,
args)}};var skip=Object.getOwnPropertyNames(function(){}).concat(["__children__"]);Object.getOwnPropertyNames(parent).forEach(function(key){var desc=Object.getOwnPropertyDescriptor(this,key);if((desc===undefined||desc.configurable)&&skip.indexOf(key)===-1)Object.defineProperty(this,key,Object.getOwnPropertyDescriptor(parent,key))},Function);Function.prototype=prototype;prototype.constructor=Function;if(Object.getOwnPropertyDescriptor(this,"__children__")===undefined)Object.defineProperty(this,"__children__",
{value:[]});this.__children__.push(Function);return Function};Function.prototype.getChildFunctions=function(){return this.__children__!==undefined?this.__children__.slice():[]};var CustomEvent=function(type){var e;try{e=document.createEvent("CustomEvent");e.initCustomEvent.apply(e,Array.prototype.slice.call(arguments))}catch(exc){e=document.createEvent("UIEvents");e.initUIEvent.call(e,arguments[0],arguments[1],arguments[2],null,1);Object.defineProperty(e,"detail",{value:arguments[3]})}return e};var MouseEvent=
function(type){var e=document.createEvent("MouseEvent");e.initMouseEvent.apply(e,Array.prototype.slice.call(arguments));return e};MouseEvent.prototype=window.MouseEvent.prototype;Object.defineProperty(Object.prototype,"eventReceiver",{get:function(){var desc=Object.getOwnPropertyDescriptor(this,"_eventReceiver");if(desc===undefined){var rcv=document.createElement("span");try{Object.defineProperty(rcv,"_listeners",{value:{}})}catch(exc){}Object.defineProperty(this,"_eventReceiver",{value:rcv,writable:false})}return this._eventReceiver},
set:function(){}});Object.defineProperty(Object.prototype,"addEventListener",{value:function(type,listener){var obj=this;this.eventReceiver.addEventListener(type,function(e){listener.call(obj,e);e._dispatched=true},false);var listeners=this.eventReceiver._listeners;if(listeners!==void 0)if(listeners[type]===void 0)listeners[type]=[listener];else listeners[type].push(listener);return this}});Object.defineProperty(Object.prototype,"removeEventListener",{value:function(type,listener){this.eventReceiver.removeEventListener(type,
listener,false);listeners=this.eventReceiver._listeners;if(listeners!==void 0){listeners=listeners[type];if(listeners!==void 0&&listeners.length!==0)listeners.forEach(function(l,i){if(listener===void 0||listener===l)delete listeners[i]})}return this}});Object.defineProperty(Object.prototype,"dispatchEvent",{value:function(e){var res=this.eventReceiver.dispatchEvent(e);if(!e._dispatched&&this.eventReceiver._listeners){var listeners=this.eventReceiver._listeners[e.type];if(listeners!==void 0)listeners.forEach(function(listener){listener.call(this,
e)},this)}return res}});Object.defineProperty(Object.prototype,"fire",{value:function(e,detail){if(e instanceof Event){if(detail!==undefined)throw new Error("Invalid usage.");if(["click","mouseover","mouseout","mousedown","mouseup","dblclick"].indexOf(e.type)!==-1)e=new MouseEvent(e.type,true,true,window,detail,e.screenX,e.screenY,e.clientX,e.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null);return this.dispatchEvent(e)}e=new CustomEvent(e,true,true,detail);return this.dispatchEvent(e)},writable:true});
if(Function.prototype.bind===undefined)Function.prototype.bind=function(ctx){var fn=this;var args=Array.prototype.slice.call(arguments,1);return function(){return fn.apply(ctx,args.concat(Array.prototype.slice.call(arguments)))}};var chainify={"Element":["addEventListener","removeEventListener"]};Object.keys(chainify).forEach(function(key){var obj=window[key],__slice=Array.prototype.slice;chainify[key].forEach(function(key){var fn=this[key];if(typeof fn==="function")this[key]=function(){fn.apply(this,
__slice.call(arguments));return this}},obj.prototype)});if(Array.prototype.first===undefined)Array.prototype.first=function(){return this[0]||undefined};if(Array.prototype.last===undefined)Array.prototype.last=function(){return this.length?this[this.length-1]:undefined};if(Array.prototype.compact===undefined)Array.prototype.compact=function(){return this.filter(function(a){return a!==void 0&&a!==null})};var NativeElement=Element;window.Element=function(tagName,attrs){tagName=tagName.toLowerCase();
var el=document.createElement(tagName);if(attrs!==undefined)Object.getOwnPropertyNames(attrs).forEach(function(key){this.setAttribute(key,attrs[key])},el);return el};Element.prototype=NativeElement.prototype;Element.prototype.html=function(html){if(html===undefined)return this.innerHTML;this.innerHTML=html!==null?html:"";return this};Element.prototype.attr=function(key,value){if(value===undefined)return this.getAttribute(key);this.setAttribute(key,value);return this};Element.prototype.data=function(key,
value){return this.attr("data-"+key,value)};Element.prototype.hasClassName=function(className){return(new RegExp("(^|\\s)"+className+"(\\s|$)")).test(this.className)};Element.prototype.addClassName=function(className){if(!this.hasClassName(className)){this.className+=" "+className;this.className=this.className.replace(/(^\s+|\s+$)/g,"")}return this};Element.prototype.removeClassName=function(className){var e=this.className.split(/\s+/),index=e.indexOf(className);if(index>-1){delete e[index];this.className=
e.join(" ")}return this};Element.prototype.show=function(){if(this.style.display==="none")this.style.display="";return this};Element.prototype.hide=function(){if(this.style.display!=="none")this.style.display="none";return this};Element.prototype.insert=function(){var input=arguments[0];switch(typeof input){case "undefined":throw new Error("Missing input");case "string":case "number":this.appendChild(document.createTextNode(input));break;case "object":if(input instanceof Element||input instanceof
DocumentFragment)this.appendChild(input);else Object.getOwnPropertyNames(input).forEach(function(pos){var els=input[pos],parent;els=els instanceof Array?els:[els];switch(pos){case "top":els.forEach(function(el){this.firstChild?this.insertBefore(el,this.firstChild):this.appendChild(el)},this);break;case "bottom":els.forEach(function(el){this.appendChild(el)},this);break;case "before":parent=this.parentNode;if(!parent)throw new Error("No parent node");els.forEach(function(el){parent.insertBefore(el,
this)},this);break;case "after":parent=this.parentNode;if(!parent)throw new Error("No parent node");if(parent.lastChild===this)els.forEach(function(el){parent.appendChild(el)});else{var next=this.nextSibling;els.forEach(function(el){parent.insertBefore(el,next)})}break}},this);break}return this};Element.prototype.appendTo=function(target){target.appendChild(this);return this};Element.prototype.find=function(){var node_list=this.querySelectorAll.apply(this,arguments);return Array.prototype.slice.call(node_list)};
DocumentFragment.prototype.find=Element.prototype.find;Element.prototype.findOne=function(){return this.querySelector.apply(this,arguments)};DocumentFragment.prototype.findOne=Element.prototype.findOne;Element.prototype.remove=function(){var parent=this.parentNode;if(!parent)throw new Error("No parent node");parent.removeChild(this);return this};if((new Element("span")).innerText===undefined)Object.defineProperty(Element.prototype,"innerText",{get:function(){return this.textContent},set:function(value){this.textContent=
value}});NodeList.prototype.forEach=function(){return Array.prototype.forEach.apply(this,arguments)};NodeList.prototype.some=function(){return Array.prototype.some.apply(this,arguments)};NodeList.prototype.every=function(){return Array.prototype.every.apply(this,arguments)};NodeList.prototype.map=function(){return Array.prototype.map.apply(this,arguments)};NodeList.prototype.reduce=function(){return Array.prototype.reduce.apply(this,arguments)};NodeList.prototype.filter=function(){return Array.prototype.filter.apply(this,
arguments)};NodeList.prototype.first=Array.prototype.first;NodeList.prototype.last=Array.prototype.last;if(window.FileList!==void 0)FileList.prototype.forEach=Array.prototype.forEach;if(Range.prototype.reapply===undefined)Range.prototype.reapply=function(){var sel=window.getSelection(),range=document.createRange();range.setStart(this.startContainer,this.startOffset);range.setEnd(this.endContainer,this.endOffset);sel.removeAllRanges();sel.addRange(range);return range};if(String.prototype.escapeHTML===
undefined)String.prototype.escapeHTML=function(){return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}})();(function(doc){var head=doc.documentElement,isHeadReady,isDomReady,domWaiters=[],queue=[],handlers={},scripts={},isAsync=doc.createElement("script").async===true||"MozAppearance"in doc.documentElement.style||window.opera;var head_var=window.head_conf&&head_conf.head||"require",api=window[head_var]=window[head_var]||function(){api.ready.apply(null,arguments)};var PRELOADED=1,PRELOADING=2,LOADING=3,LOADED=4;api.ROOT="";if(isAsync)api.js=function(){var args=arguments,fn=args[args.length-1],els={};if(!isFunc(fn))fn=
null;each(args,function(el,i){if(el!=fn){el=getScript(el);els[el.name]=el;load(el,fn&&i==args.length-2?function(){if(allLoaded(els))one(fn)}:null)}});return api};else api.js=function(){var args=arguments,rest=[].slice.call(args,1),next=rest[0];if(!isHeadReady){queue.push(function(){api.js.apply(null,args)});return api}if(next){each(rest,function(el){if(!isFunc(el))preload(getScript(el))});load(getScript(args[0]),isFunc(next)?next:function(){api.js.apply(null,rest)})}else load(getScript(args[0]));
return api};api.ready=function(key,fn){if(key==doc){if(isDomReady)one(fn);else domWaiters.push(fn);return api}if(isFunc(key)){fn=key;key="ALL"}if(typeof key!="string"||!isFunc(fn))return api;var script=scripts[key];if(script&&script.state==LOADED||key=="ALL"&&allLoaded()&&isDomReady){one(fn);return api}var arr=handlers[key];if(!arr)arr=handlers[key]=[fn];else arr.push(fn);return api};function one(fn){if(fn._done)return;fn();fn._done=1}function toLabel(url){var els=url.split("/"),name=els[els.length-
1],i=name.indexOf("?");return i!=-1?name.substring(0,i):name}function getScript(url){var script;if(typeof url=="object")for(var key in url){if(url[key])script={name:key,url:api.ROOT+url[key]}}else script={name:toLabel(url),url:api.ROOT+url};var existing=scripts[script.name];if(existing&&existing.url===script.url)return existing;scripts[script.name]=script;return script}function each(arr,fn){if(!arr)return;if(typeof arr=="object")arr=[].slice.call(arr);for(var i=0;i<arr.length;i++)fn.call(arr,arr[i],
i)}function isFunc(el){return Object.prototype.toString.call(el)=="[object Function]"}function allLoaded(els){els=els||scripts;var loaded;for(var name in els){if(els.hasOwnProperty(name)&&els[name].state!=LOADED)return false;loaded=true}return loaded}function onPreload(script){script.state=PRELOADED;each(script.onpreload,function(el){el.call()})}function preload(script,callback){if(script.state===undefined){script.state=PRELOADING;script.onpreload=[];scriptTag({src:script.url,type:"cache"},function(){onPreload(script)})}}
function load(script,callback){if(script.state==LOADED)return callback&&callback();if(script.state==LOADING)return api.ready(script.name,callback);if(script.state==PRELOADING)return script.onpreload.push(function(){load(script,callback)});script.state=LOADING;scriptTag(script.url,function(){script.state=LOADED;if(callback)callback();each(handlers[script.name],function(fn){one(fn)});if(allLoaded()&&isDomReady)each(handlers.ALL,function(fn){one(fn)})})}function scriptTag(src,callback){var s=doc.createElement("script");
s.type="text/"+(src.type||"javascript");s.src=src.src||src;s.async=false;s.onreadystatechange=s.onload=function(){var state=s.readyState;if(!callback.done&&(!state||/loaded|complete/.test(state))){callback.done=true;callback()}};(doc.body||head).appendChild(s)}function fireReady(){if(!isDomReady){isDomReady=true;each(domWaiters,function(fn){one(fn)})}}if(window.addEventListener){doc.addEventListener("DOMContentLoaded",fireReady,false);window.addEventListener("load",fireReady,false)}else if(window.attachEvent){doc.attachEvent("onreadystatechange",
function(){if(doc.readyState==="complete")fireReady()});var frameElement=1;try{frameElement=window.frameElement}catch(e){}if(!frameElement&&head.doScroll)(function(){try{head.doScroll("left");fireReady()}catch(e){setTimeout(arguments.callee,1);return}})();window.attachEvent("onload",fireReady)}if(!doc.readyState&&doc.addEventListener){doc.readyState="loading";doc.addEventListener("DOMContentLoaded",handler=function(){doc.removeEventListener("DOMContentLoaded",handler,false);doc.readyState="complete"},
false)}setTimeout(function(){isHeadReady=true;each(queue,function(fn){fn()})},300)})(document);var JSON;if(!JSON)JSON={};
(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=
/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,
mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function")value=value.toJSON(key);if(typeof rep==="function")value=rep.call(holder,key,value);switch(typeof value){case "string":return quote(value);case "number":return isFinite(value)?String(value):"null";case "boolean":case "null":return String(value);case "object":if(!value)return"null";gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=
1)partial[i]=str(i,value)||"null";v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1)if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v)partial.push(quote(k)+(gap?": ":":")+v)}}else for(k in value)if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v)partial.push(quote(k)+(gap?": ":":")+v)}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+
gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function")JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number")for(i=0;i<space;i+=1)indent+=" ";else if(typeof space==="string")indent=space;rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number"))throw new Error("JSON.stringify");return str("",{"":value})};if(typeof JSON.parse!=="function")JSON.parse=
function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object")for(k in value)if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined)value[k]=v;else delete value[k]}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text))text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)});if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse");}})();(function(window){var rsplit=function(string,regex){var result=regex.exec(string),retArr=[],first_idx,last_idx,first_bit;while(result!==null){first_idx=result.index;last_idx=regex.lastIndex;if(first_idx!==0){first_bit=string.substring(0,first_idx);retArr.push(string.substring(0,first_idx));string=string.slice(first_idx)}retArr.push(result[0]);string=string.slice(result[0].length);result=regex.exec(string)}if(string!=="")retArr.push(string);return retArr};var chop=function(string){return string.substr(0,
string.length-1)};var extend=function(d,s){var n;for(n in s)if(s.hasOwnProperty(n))d[n]=s[n]};var EJS=function(options){if(typeof options==="string")options={"view":options};this.set_options(options);if(options.precompiled){this.template={};this.template.controller=options.controller;var to_be_evaled="/*"+this.name+"*/ "+"this.template.process = function (_CONTEXT,_VIEW) { "+"try { "+"var helpers = {}; "+"var key; "+"for (key in _VIEW) { "+"if (typeof _VIEW[key] === 'function') { "+"helpers[key] = _VIEW[key].bind(_VIEW); "+
"} "+"} "+"delete key; "+"with (helpers) { "+"delete helpers; "+"with (_CONTEXT) { "+"delete _CONTEXT; "+options.precompiled+" "+"return ___ViewO.join(''); "+"} "+"} "+"} catch (e) { "+"e.lineNumber = null; "+"throw e; "+"} "+"};";eval(to_be_evaled);EJS.update(this.name,this);return}var template=new EJS.Compiler(this.text,this.type);template.compile(options,this.name);template.controller=options.controller;EJS.update(this.name,this);this.template=template};EJS.prototype={"render":function(object,
extra_helpers){object=object||{};this._extra_helpers=extra_helpers;var v=new EJS.Helpers(object,extra_helpers||{},this.template.controller);return this.template.process.call(object,object,v)},"out":function(){return this.template.out},"set_options":function(options){this.type=options.type||EJS.type;this.cache=options.cache!==null?options.cache:EJS.cache;this.text=options.text||null;this.name=options.name||null;this.ext=options.ext||EJS.ext;this.extMatch=new RegExp(this.ext.replace(/\./,"\\."))}};
EJS.endExt=function(path,match){if(!path)return null;match.lastIndex=0;return path+(match.test(path)?"":this.ext)};EJS.Scanner=function(source,left,right){extend(this,{"left_delimiter":left+"%","right_delimiter":"%"+right,"double_left":left+"%%","double_right":"%%"+right,"left_equal":left+"%=","left_comment":left+"%#"});this.SplitRegexp=left==="["?/(\[%%)|(%%\])|(\[%=)|(\[%#)|(\[%)|(%\]\n)|(%\])|(\n)/:new RegExp("("+this.double_left+")|(%%"+this.double_right+")|("+this.left_equal+")|("+this.left_comment+
")|("+this.left_delimiter+")|("+this.right_delimiter+"\n)|("+this.right_delimiter+")|(\n)");this.source=source;this.stag=null;this.lines=0};EJS.Scanner.to_text=function(input){if(input===null||input===undefined)return"";if(input instanceof Date)return input.toDateString();if(input.toString)return input.toString();return""};EJS.Scanner.prototype={"scan":function(block){var regex=this.SplitRegexp;if(this.source!==""){var source_split=rsplit(this.source,/\n/);var i,ii;for(i=0,ii=source_split.length;i<
ii;++i){var item=source_split[i];this.scanline(item,regex,block)}}},"scanline":function(line,regex,block){++this.lines;var line_split=rsplit(line,regex);var i,ii;for(i=0,ii=line_split.length;i<ii;++i){var token=line_split[i];if(token===null)continue;try{block(token,this)}catch(e){throw{"type":"EJS.Scanner","line":this.lines};}}}};EJS.Buffer=function(pre_cmd,post_cmd){this.line=[];this.script="";this.pre_cmd=pre_cmd;this.post_cmd=post_cmd;var i,ii;for(i=0,ii=this.pre_cmd.length;i<ii;++i)this.push(pre_cmd[i])};
EJS.Buffer.prototype={"push":function(cmd){this.line.push(cmd)},"cr":function(){this.script=this.script+this.line.join("; ");this.line=[];this.script=this.script+"\n"},"close":function(){if(this.line.length>0){var i,ii;for(i=0,ii=this.post_cmd.length;i<ii;++i)this.push(this.post_cmd[i]);this.script=this.script+this.line.join("; ");this.line=null}}};EJS.Compiler=function(source,left){this.pre_cmd=["var ___ViewO = [];"];this.post_cmd=[];this.source=" ";if(source!==null){if(typeof source==="string"){source=
source.replace(/\r\n/g,"\n");source=source.replace(/\r/g,"\n");this.source=source}else if(source.innerHTML)this.source=source.innerHTML;if(typeof this.source!=="string")this.source=""}left=left||"<";var right=">";switch(left){case "[":right="]";break;case "<":break;default:throw left+" is not a supported deliminator";}this.scanner=new EJS.Scanner(this.source,left,right);this.out=""};EJS.Compiler.prototype={"compile":function(options,name){options=options||{};this.out="";var put_cmd="___ViewO.push(",
insert_cmd=put_cmd,buff=new EJS.Buffer(this.pre_cmd,this.post_cmd),content="";var clean=function(content){content=content.replace(/\\/g,"\\\\");content=content.replace(/\n/g,"\\n");content=content.replace(/"/g,'\\"');return content};this.scanner.scan(function(token,scanner){if(scanner.stag===null)switch(token){case "\n":content=content+"\n";buff.push(put_cmd+'"'+clean(content)+'");');buff.cr();content="";break;case scanner.left_delimiter:case scanner.left_equal:case scanner.left_comment:scanner.stag=
token;if(content.length>0)buff.push(put_cmd+'"'+clean(content)+'")');content="";break;case scanner.double_left:content=content+scanner.left_delimiter;break;default:content=content+token}else switch(token){case scanner.right_delimiter:switch(scanner.stag){case scanner.left_delimiter:if(content[content.length-1]==="\n"){content=chop(content);buff.push(content);buff.cr()}else buff.push(content);break;case scanner.left_equal:buff.push(insert_cmd+"(EJS.Scanner.to_text("+content+")))");break}scanner.stag=
null;content="";break;case scanner.double_right:content=content+scanner.right_delimiter;break;default:content=content+token;break}});if(content.length>0)buff.push(put_cmd+'"'+clean(content)+'")');buff.close();this.out=buff.script+";";var to_be_evaled="/*"+name+"*/ "+"this.process = function (_CONTEXT,_VIEW) { "+"try { "+"var helpers = {}; "+"var key; "+"for (key in _VIEW) { "+"if (typeof _VIEW[key] === 'function') { "+"helpers[key] = _VIEW[key].bind(_VIEW); "+"} "+"} "+"delete key; "+"with (helpers) { "+
"delete helpers; "+"with (_CONTEXT) { "+"delete _CONTEXT; "+this.out+" "+"return ___ViewO.join(''); "+"} "+"} "+"} catch (e) { "+"e.lineNumber = null; "+"throw e; "+"} "+"};";eval(to_be_evaled)}};EJS.config=function(options){EJS.cache=options.cache!==null?options.cache:EJS.cache;EJS.type=options.type!==null?options.type:EJS.type;EJS.ext=options.ext!==null?options.ext:EJS.ext;var templates_directory=EJS.templates_directory||{};EJS.templates_directory=templates_directory;EJS.get=function(path,cache){if(cache===
false)return null;if(templates_directory[path])return templates_directory[path];return null};EJS.update=function(path,template){if(path===null)return;templates_directory[path]=template};EJS.INVALID_PATH=-1};EJS.config({"cache":true,"type":"<","ext":".ejs"});EJS.Helpers=function(data,extras,controller){this._data=data;this._extras=extras;this.controller=controller;extend(this,extras)};EJS.Helpers.prototype={"view":function(options,data,helpers){if(!helpers)helpers=this._extras;if(!data)data=this._data;
return(new EJS(options)).render(data,helpers)},"to_text":function(input,null_text){if(input===null||input===undefined)return null_text||"";if(input instanceof Date)return input.toDateString();if(input.toString)return input.toString().replace(/\n/g,"<br />").replace(/''/g,"'");return""}};window.EJS=EJS})(window);(function(window){var process_selector;var fn_or=function(opts,placeholders,outer,return_params){var out=" AND ( ",out_params=[],opts_processed=[],i,ii;for(i=0,ii=opts.length;i<ii;++i)if(!return_params)opts_processed.push(process_selector(opts[i],placeholders,outer,return_params));else{var res=process_selector(opts[i],placeholders,outer,return_params);opts_processed.push(res[0]);out_params=out_params.concat(res[1])}if(!return_params)for(i=0,ii=opts_processed.length;i<ii;++i)out+="( "+opts_processed[i]+
" ) OR ";out=out.substring(0,out.length-4)+" )";return!return_params?out:[out,out_params]};process_selector=function(selector,placeholders,outer,return_params){var out="",out_params=[];var res;var key;for(key in selector)if(selector.hasOwnProperty(key))if(key[0]!=="$"){var value=selector[key];key=key.replace(/:/g,"__").replace(/\./g,"___");if(typeof value!=="object"){out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] = ";out+=!placeholders?"'"+value.toString().replace(/'/g,"\\'")+"'":"?";if(return_params)out_params.push(value)}else{var mod,
arr,i,ii;for(mod in value)if(value.hasOwnProperty(mod))if(mod[0]==="$")switch(mod.substring(1)){case "gt":out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] > "+(!placeholders?value[mod]:"?");if(return_params)out_params.push(value[mod]);break;case "gte":out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] >= "+(!placeholders?value[mod]:"?");if(return_params)out_params.push(value[mod]);break;case "lt":out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] < "+(!placeholders?value[mod]:"?");
if(return_params)out_params.push(value[mod]);break;case "lte":out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] <= "+(!placeholders?value[mod]:"?");if(return_params)out_params.push(value[mod]);break;case "ne":out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] != "+(!placeholders?"'"+value[mod].toString().replace(/'/g,"\\'")+"'":"?");if(return_params)out_params.push(value[mod]);break;case "in":if(!value[mod].length)throw"Invalid state: No items for the IN operator";out+=" AND ["+(outer!==
undefined?outer+"___":"")+key+"] IN (";if(!placeholders)out+="'"+value[mod].join("', '")+"')";else{arr=value[mod];for(i=0,ii=arr.length;i<ii;++i)arr[i]="?";out+=arr.join(", ")}out+=")";if(return_params)out_params=out_params.concat(value[mod]);break;case "nin":if(!value[mod].length)throw"Invalid state: No items for the NOT IN operator";out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] NOT IN (";if(!placeholders)out+="'"+value[mod].join("', '")+"')";else{arr=value[mod];for(i=0,ii=arr.length;i<
ii;++i)arr[i]="?";out+=arr.join(", ")}out+=")";if(return_params)out_params=out_params.concat(value[mod]);break;case "exists":out+=" AND ["+(outer!==undefined?outer+"___":"")+key+"] IS "+(value[mod]?"NOT NULL":"NULL");break;case "or":if(!return_params)out+=fn_or(value[mod],placeholders,key,return_params);else{res=out.concat(fn_or(value[mod],placeholders,key,return_params));out+=res[0];out_params=out_params.concat(res[1])}break}else if(typeof value[mod]==="object"){res=process_selector(value,placeholders,
key,return_params);if(!return_params)out+=" AND "+res;else{out+=" AND "+res[0];out_params=out_params.concat(res[1])}}else{out+=" AND ["+key+"___"+mod+"] = ";out+=!placeholders?"'"+value[mod].toString().replace(/'/g,"\\'")+"'":"?";if(return_params)out_params.push(value[mod])}}}else switch(key.substring(1)){case "or":res=fn_or(selector[key],placeholders,outer,return_params);if(!return_params)out+=res;else{out+=res[0];out_params=out_params.concat(res[1])}break}out=out.substring(5);return!return_params?
out:[out,out_params]};window.mongo2sql=function(selector){return process_selector(selector)};window.mongo2sql_parametric=function(selector){return process_selector(selector,true,undefined,true)}})(window);(function(window){var uuid=function(){var a,b,c,d;var time=Math.round((new Date).getTime()/1E3);var version=window.navigator.userAgent;var href=window.location.href;a=time.toString(16).substring(0,8);var match=version.match(/\d+/g);if(!match)throw"Invalid browser version string";var sum=0;for(var i=0,ii=match.length;i<ii;++i)sum+=parseInt(match[i],10);b=(sum*sum*sum).toString(16).substring(0,6);c=(href.length*href.length*href.length).toString(16).substring(0,4);d=Math.random().toString().substring(2);
d=parseInt(d,10);d=d.toString(16).substring(0,6);return[a,b,c,d].join("")};window.uuid=uuid})(window);var Router=Function.inherit(function(){var _namespace="";Object.defineProperty(this,"namespace",{"get":function(){return _namespace},"set":function(ns){_namespace=ns===null?"":"/"+ns}});Object.defineProperties(this,{"PARAM_HEX":{"value":/^[a-f0-9]+$/i,"writable":false},"PARAM_INTEGER":{"value":/^\d+$/,"writable":false}});this._routes=[];this._staticNS=[]},{"push":function(pattern,options){var ns=this.namespace;this._routes.push([ns===""?null:ns.substr(1),ns+pattern,options])},"pushStaticNamespace":function(ns){this._staticNS.push(ns)},
"match":function(uri,qs){var routes=this._routes,query={},result=null;if(this._staticNS.some(function(ns){if(uri==="/"+ns||(new RegExp("^/"+ns+"/")).test(uri))return true}))return result;if(!!qs){var parts=qs.split("&");parts.forEach(function(part){part=part.split("=");query[part[0]]=decodeURIComponent(part[1])})}routes.some(function(route){var pattern=route[1].replace(/\//g,"\\/"),placeholders=pattern.match(/:_?[a-z][\w\-]*/g),match,options={},params={},param_keys=[],rules,key;Object.keys(route[2]).forEach(function(key){options[key]=
route[2][key]});rules=options.params;if(placeholders!==null)placeholders.forEach(function(placeholder){placeholder=placeholder.match(/^:(_?[a-z][\w\-]*)$/);param_keys.push(placeholder[1]);pattern=pattern.replace(":"+placeholder[1],"([^/]+)")});match=(new RegExp("^"+pattern+"\\/?$")).exec(uri);if(match===null)return;if(rules instanceof RegExp){if(param_keys.some(function(key,i){if(!rules.test(match[i+1]))return true;params[key]=match[i+1]}))return}else if(rules===undefined)param_keys.forEach(function(key,
i){params[key]=match[i+1]});else if(Object.keys(rules).some(function(key){var index=param_keys.indexOf(key);if(index>-1){if(!rules[key].test(match[index+1]))return true;params[key]=match[index+1]}}))return;if(options.controller[0]===":"){key=options.controller.substr(1);options.controller=params[key];if(options.controller===undefined)throw new Error("Invalid route: Undefined parameter :"+key);}if(options.view[0]===":"){key=options.view.substr(1);options.view=params[key];if(options.view===undefined)throw new Error("Invalid route: Undefined parameter :"+
key);}if(!!qs)if(rules instanceof RegExp){if(Object.keys(query).some(function(key){if(!rules.test(query[key]))return true;params[key]=query[key]}))return}else if(rules===undefined)Object.keys(query).forEach(function(key){params[key]=query[key]});else if(Object.keys(query).some(function(key){if(rules.hasOwnProperty(key)&&!rules[key].test(query[key]))return true;params[key]=query[key]}))return;result={"namespace":route[0],"controller":options.controller,"view":options.view,"params":params};return true});
return result},"resolve":function(target){var routes=this._routes,result=null;var create_qs=function(params,param_keys){var query=[];Object.keys(params).forEach(function(key){if(["_c","_v"].indexOf(key)===-1&&param_keys.indexOf(key)===-1)query.push(key+"="+encodeURIComponent(params[key]))});return query.length>0?"?"+query.join("&"):""};routes.some(function(route){var uri=route[1],placeholders=uri.match(/:_?[a-z][\w\-]*/g),options=route[2],r_controller=options.controller,r_view=options.view,rules=
options.params,param_keys=[],params=target.params||{},key;if(route[0]!==target.namespace)return;params._c=target.controller;params._v=target.view;if(placeholders!==null)if(placeholders.some(function(placeholder){placeholder=placeholder.match(/^:(_?[a-z][\w\-]*)$/);param_keys.push(placeholder[1]);if(params[placeholder[1]]===undefined)return true}))return;if(r_controller[0]===":"){key=r_controller.substr(1);if(params[key]===undefined)return;r_controller=params[key]}if(r_view[0]===":"){key=r_view.substr(1);
if(params[key]===undefined)return;r_view=params[key]}if(r_controller!==target.controller||r_view!==target.view)return;if(rules===undefined)param_keys.forEach(function(key){uri=uri.replace(":"+key,params[key])});else if(rules instanceof RegExp){if(param_keys.some(function(key){if(!rules.test(params[key]))return true;uri=uri.replace(":"+key,params[key])}))return}else if(param_keys.some(function(key){if(rules[key]!==undefined&&!rules[key].test(params[key]))return true;uri=uri.replace(":"+key,params[key])}))return;
result=uri+create_qs(params,param_keys);return true});return result}});var Operation=Function.inherit(function(){this.input=Array.prototype.slice.call(arguments)},{"toString":function(){return"[object Operation]"},"execute":function(callback){if(typeof callback==="function")this._callback=callback;this.startup.apply(this,this.input)},"startup":function(){},"retry":function(delay){this.queue.fire("idle");setTimeout(this.execute.bind(this),delay||0)},"shutdown":function(){if(typeof this._callback==="function")this._callback()}});
var OperationQueue=Function.inherit(function(namespace){this._namespace=namespace;this.items=[];this._items_simple=JSON.parse(window.localStorage[namespace]||"[]");this._items_simple.forEach(function(item){var name=item[0].match(/^\[object ([A-Z]\w*)\]$/)[1],op=new window[name];op.input=item.slice(1);op.queue=this;this.items.push([op])},this);this._loop()},{"push":function(op,callback){this.items.push(typeof callback==="function"?[op,callback]:[op]);op.queue=this;if(this._namespace){this._items_simple.push([op.toString()].concat(op.input));
window.localStorage[this._namespace]=JSON.stringify(this._items_simple)}if(this.idle)this._loop()},"_loop":function(){var queue=this;this.idle=!this.items.length;if(this.idle){queue.fire("idle");return}setTimeout(function(){var item=queue.items[0];queue._current_item=item;try{item[0].execute(function(){if(queue._namespace){queue._items_simple.shift();window.localStorage[queue._namespace]=JSON.stringify(queue._items_simple)}queue.items.shift();if(typeof item[1]==="function")item[1].apply(this,item[0].output||
[]);queue._loop()});queue.fire("item")}catch(exc){queue._loop()}},0)},"filter":function(){this.items=Array.prototype.filter.apply(this.items,arguments)}});(function(){var upper,SQLStatement,Model;upper=function(a){return a.toUpperCase()};SQLStatement=Function.inherit(function(operation,collection){var _sort={},_data={};Object.defineProperties(this,{"operation":{get:function(){return operation}},"collection":{get:function(){return collection}},"sort":{get:function(){return _sort},set:function(value){if(typeof value==="object")_sort=value;else if(typeof value==="string"){_sort={};_sort[value]=1}}},"data":{get:function(){return _data},set:function(value){if(typeof value===
"object")_data=value}}})});Object.defineProperty(SQLStatement.prototype,"sql",{get:function(){var selector=this.selector,data=this.data,out="",fields=[],params=[],i,ii,res,sort;switch(this.operation){case "read":out+="SELECT ";if(this.fields===undefined||this.fields.length===0)this.fields=["*"];out+=this.fields.join(", ")+" ";out+="FROM ["+this.collection+"] ";if(selector&&JSON.stringify(selector)!=="{}"){res=mongo2sql_parametric(selector);params=params.concat(res[1]);out+="WHERE "+res[0]+" "}sort=
this.sort;if(JSON.stringify(sort)!=="{}"){out+="ORDER BY ";Object.getOwnPropertyNames(sort).forEach(function(field){out+="lower(["+field.replace(":","__")+"]) "+(sort[field]>0?"ASC ":"DESC ")})}if(this.limit)out+="LIMIT "+this.limit+" ";break;case "create":out+="INSERT INTO ["+this.collection+"] ";if(data===undefined)throw new Error("No data");for(i in data)if(data.hasOwnProperty(i)){fields.push("["+i.replace(":","__")+"]");params.push(data[i])}if(fields.length===0)throw new Error("No data");out+=
"("+fields.join(", ")+") VALUES (";params.forEach(function(param){out+="?, "});out=out.substr(0,out.length-2);out+=")";break;case "update":out+="UPDATE ["+this.collection+"] SET ";if(data===undefined)throw new Error("No data");for(i in data)if(data.hasOwnProperty(i)){params.push(data[i]);out+="["+i.replace(":","__")+"] = ?";out+=", "}out=out.substring(0,out.length-2)+" ";if(selector&&JSON.stringify(selector)!=="{}"){res=mongo2sql_parametric(selector);params=params.concat(res[1]);out+="WHERE "+res[0]+
" "}break;case "delete":out+="DELETE FROM ["+this.collection+"] ";if(selector&&JSON.stringify(selector)!=="{}"){res=mongo2sql_parametric(selector);params=params.concat(res[1]);out+="WHERE "+res[0]+" "}break}return[out,params]}});window.ApiOperation=Operation.inherit({"toString":function(){return"[object ApiOperation]"},"startup":function(method,uri,data){var op=this;Model.api(method,uri,{},data,function(status,response){var dumbass=status===403&&response&&response.dumbass;if(dumbass)window.document.fire("flowoff:dumbass");
if(status&&status<300||app.MODE!=="offline"){op.output=[status,response];op.shutdown()}else if(status!==404&&status!==403)op.retry(5E3);else op.shutdown()})}});Model=Function.inherit(function(doc){var d=doc||{};doc={};var skip_props=["url"];Object.getOwnPropertyNames(d).forEach(function(key){if(skip_props.indexOf(key)!==-1)return;Object.defineProperty(doc,key,Object.getOwnPropertyDescriptor(d,key))});var _stored=!!doc._id,_changed=false,fieldGetter,fieldSetter,fields=this.constructor.fields||[];Object.defineProperties(this,
{"stored":{get:function(){return _stored},set:function(value){_stored=!!value}},"changed":{get:function(){return _changed},set:function(value){_changed=!!value}},"doc":{value:doc,writable:false},"id":{get:function(){return doc._id||null},set:function(value){if(doc._id!==value){if(doc._id&&console&&console.warn)console.warn("Rewriting an UUID");doc._id=value;_changed=true;if(app.MODE==="offline")_stored=false}}},"parent":{get:function(){if(typeof this.getParent!=="function")throw new Error("No parent association");
var api_field=window[this.constructor.parent_constructor].api_field||"id";return doc._parent[api_field]||doc._parent||null},set:function(value){if(typeof this.getParent!=="function")throw new Error("No parent association");var orig=doc._parent;doc._parent=value instanceof Model?value[app.MODE==="offline"?"id":value.constructor.api_field]:value;if(app.MODE!=="offline")this._cache.parent=value instanceof Model?value:undefined;_changed=_changed||orig!==doc._parent}}});if(app.MODE!=="offline")this._cache=
{};fieldGetter=function(key){if(fields.indexOf(key)===-1)throw new Error("Unknown field: "+key);return this.doc[key]};fieldSetter=function(key,value){if(fields.indexOf(key)===-1)throw new Error("Unknown field: "+key);this.doc[key]=value;_changed=true};fields.forEach(function(key){if(key.search(":")===-1)throw new Error("Invalid field name: a namespace required");Object.defineProperty(this,key,{get:fieldGetter.bind(this,key),set:fieldSetter.bind(this,key),enumerable:true})},this);if(typeof doc._parent===
"object"&&doc._parent!==null)if(app.MODE!=="offline")this._cache.parent=new window[this.constructor.parent_constructor](doc._parent);Object.getOwnPropertyNames(doc).forEach(function(key){if(key.indexOf(":")!==-1||key[0]==="_")return;var name=key.replace(/^\w/,upper);if(typeof this["get"+name]==="function"){name=name.replace(/ies$/,"y").replace(/s$/,"");var cache,model=window[name];if(key[key.length-1]==="s"){cache=[];doc[key].forEach(function(doc){var m=new model(doc);if(app.MODE!=="offline"&&!doc._parent){m._cache._parent=
this;m.doc._parent=this.id}cache.push(m)},this)}else{cache=new model(doc[key]);if(app.MODE!=="offline"&&!doc[key]._parent){cache._cache.parent=this;m.doc._parent=this.id}}if(app.MODE!=="offline")this._cache[key]=cache;delete doc[key]}},this)},{"toString":function(){return"[object Model]"},"save":function(options,callback){if(arguments.length===1){callback=arguments[0];options={}}else if(arguments.length===0)options={};if(!this.changed){if(typeof callback==="function")callback(null);return}if(typeof this.beforeSave===
"function")this.beforeSave();var api_uri;if(options.fallback)api_uri=options.fallback;else if(this.stored||!this.constructor._has_api_parent)api_uri=this.constructor.getApiUri(this.stored?this[this.constructor.api_field]:undefined);else api_uri=window[this.constructor.parent_constructor].getApiUri(this.parent,this.key);var op=new ApiOperation(this.stored?"PUT":"POST",api_uri,this.doc);var model=this;if(app.MODE==="online"){app.queue(op,function(status,response){if(status<300){model.stored=true;if(typeof callback===
"function")callback(response)}else if(typeof callback==="function")callback(new Error("Failed to save the resource"))});return}var st=new SQLStatement(this.stored?"update":"create",this.collection),selector={_id:this.id},data={};if(this.constructor.namespace!==null){if(!app.namespace)throw new Error("Global namespace is not defined");selector._ns=app.namespace;this.doc._ns=app.namespace}st.selector=selector;st.data=this.doc;var sql=st.sql;var after_upsert=options.upsert===true;var execute=function(tx){tx.executeSql(sql[0],
sql[1],function(tx,result){if(result.rowsAffected>0){model.stored=true;model.changed=false;if(typeof callback==="function")callback(null);if(model.constructor.online!==false&&options.online!==false)app.queue(op)}else if(!after_upsert){after_upsert=true;var st=new SQLStatement("create",model.collection);st.selector=selector;st.data=model.doc;sql=st.sql;if(options.tx)execute(options.tx);else app.db.transaction(execute)}else if(model.constructor.online!==false&&options.online!==false)app.queue(op)},
function(tx,err){if(console){console.error("SQL Error: "+err.message+"; "+JSON.stringify(err));console.log("The SQL query was:",sql[0],sql[1])}if(typeof callback==="function")callback(err)})};if(options.tx)execute(options.tx);else app.db.transaction(execute)},"remove":function(options,callback){if(arguments.length===1){callback=arguments[0];options={}}else if(arguments.length===0)options={};if(!this.stored)return callback(null);if(typeof this.beforeDelete==="function")this.beforeDelete();var api_uri;
if(options.fallback)api_uri=options.fallback;else if(this.stored||!this.constructor._has_api_parent)api_uri=this.constructor.getApiUri(this.stored?this[this.constructor.api_field]:undefined);else api_uri=window[this.constructor.parent_constructor].getApiUri(this.parent,this.key);var op=new ApiOperation("DELETE",api_uri);if(app.MODE==="online"){app.queue(op,function(status,response){if(typeof callback==="function")callback(status<300?response:new Error("Failed to delete the resource"))});return}var st=
new SQLStatement("delete",this.collection),model=this,selector={_id:this.id};if(this.constructor.namespace!==null){if(!app.namespace)throw new Error("Global namespace is not defined");selector._ns=app.namespace}st.selector=selector;var sql=st.sql;var execute=function(tx){tx.executeSql(sql[0],sql[1],function(tx,result){model.stored=false;model.changed=true;if(typeof callback==="function")callback(null);if(model.constructor.online!==false&&options.online!==false)app.queue(op)},function(tx,err){if(console){console.error("SQL Error: "+
err.message+"; "+JSON.stringify(err));console.log("The SQL query was:",sql[0],sql[1])}if(typeof callback==="function")callback(err)})};if(options.tx)execute(options.tx);else app.db.transaction(execute)},"generateId":function(){this.id=uuid().replace(/\-/g,"")},"update":function(fields){Object.keys(fields).forEach(function(key){this[key]=fields[key]},this);return this},"updateTimestamp":function(key){var desc=Object.getOwnPropertyDescriptor(this,key);if(desc===undefined)throw new Error("Unknown field ("+
key+")");this[key]=Math.round((new Date).getTime()/1E3)}});Object.defineProperties(Model.prototype,{"collection":{get:function(){return this.constructor.collection},set:function(){}},"key":{get:function(){return this.constructor.collection.replace(/ies$/,"y").replace(/s$/,"")},set:function(){}}});Model.one=function(selector,options,callback){if(arguments.length===1){callback=arguments[0];options={};selector={}}else if(arguments.length===2){callback=arguments[1];options={}}selector=selector||{};options=
options||{};options.limit=1;this.all(selector,options,callback)};Model.all=function(selector,options,callback){if(arguments.length===1){callback=arguments[0];options={};selector={}}else if(arguments.length===2){callback=arguments[1];options={}}selector=selector||{};options=options||{};if(typeof callback!=="function")throw new Error("Missing callback");var M=this;if(typeof selector!=="object")selector={_id:selector};var fallback=function(){var uri=options.fallback;if(!uri){var api_field=M.api_field.replace(/^id$/,
"_id");uri=options.limit===1?M.getApiUri(selector[api_field]):M.getApiUri();var query=[];Object.keys(selector).forEach(function(key){if(key==="_ns")return;var k=key.replace(/^_id$/,"id");if(key!==api_field)query.push(k+"="+encodeURIComponent(selector[key]))});if(query.length)uri+="?"+query.join("&")}M.api("GET",uri,function(status,response){if(status!==200)return callback(options.limit!==1?[]:new M,status);if(options.limit===1){var m=new M(response instanceof Array?response[0]:response);m.remote=
true;callback(m)}else{var models=[];if(response instanceof Array===false)response=[response];response.forEach(function(item){var m=new M(item);m.remote=true;models.push(m)});callback(models,status)}})};if(options.online===true||app.MODE==="online"){fallback();return}var st=new SQLStatement("read",this.collection);if(this.namespace!==null){if(!app.namespace)throw new Error("Global namespace is not defined");selector._ns=app.namespace}st.selector=selector;if(options.limit)st.limit=options.limit;if(options.fields)st.fields=
options.fields;if(options.sort)st.sort=options.sort;else if(this.sort)st.sort=this.sort;var sql=st.sql;var execute=function(tx){tx.executeSql(sql[0],sql[1],function(tx,result){var rows=result.rows,r,rr=rows.length,models=[],doc,row;if(rr!==0||options.online===false){for(r=0;r<rr;++r){doc={};row=rows.item(r);Object.getOwnPropertyNames(row).forEach(function(key){doc[key.replace("__",":")]=row[key]});models.push(new M(doc))}callback(options.limit!==1?models:models[0]||new M,0)}else if(M.online!==false)fallback();
else callback(options.limit!==1?[]:new M,0)},function(tx,err){if(console){console.error("SQL Error: "+err.message+"; "+JSON.stringify(err));console.log("The SQL query was:",sql[0],sql[1])}callback(err)})};if(options.tx)execute(options.tx);else app.db.transaction(execute)};Model.has_one=function(has_one){if(has_one instanceof Array!==true)has_one=Array.prototype.slice.call(arguments);var createGetter=function(name,proto,sel){var key=name;name=name.replace(/^\w/,upper);sel=sel||{};proto["get"+name]=
function(selector,options,callback){if(arguments.length===2){callback=arguments[1];options=arguments[0];selector={}}if(arguments.length===1){callback=arguments[0];options={};selector={}}var model=window[name];if(model===undefined)throw new Error("Invalid association: "+name+" is not defined");Object.getOwnPropertyNames(sel).forEach(function(key){selector[key]=sel[key]});if(!options.fallback)options.fallback=this.constructor.getApiUri(this[this.constructor.api_field],key);if(app.MODE==="offline"){selector._parent=
this.id;options.online=options.online||(this.remote?true:null);return model.one(selector,options,callback)}else{if(this._cache[key]){callback(this._cache[key]);return}model.api("GET",options.fallback,function(status,response){if(status!==200){callback(new model);return}var m=new model(response);m.remote=true;this._cache[key]=m;callback(m)}.bind(this))}}},skip=false;has_one.forEach(function(key,i){if(skip){skip=false;return}skip=typeof has_one[i+1]==="string";createGetter(key,this.prototype,skip?has_one[i+
1]:null)},this)};Model.has_many=function(has_many){if(has_many instanceof Array!==true)has_many=Array.prototype.slice.call(arguments);var createGetter=function(name,proto,sel){var key=name;name=name.replace(/^\w/,upper);sel=sel||{};proto["get"+name]=function(selector,options,callback){if(arguments.length===2){callback=arguments[1];options=arguments[0];selector={}}if(arguments.length===1){callback=arguments[0];options={};selector={}}name=name.replace(/ies$/,"y").replace(/s$/,"");var model=window[name];
if(model===undefined)throw new Error("Invalid association: "+name+" is not defined");Object.getOwnPropertyNames(sel).forEach(function(key){selector[key]=sel[key]});if(!options.fallback)options.fallback=this.constructor.getApiUri(this[this.constructor.api_field],name);if(app.MODE==="offline"){selector._parent=this.id;options.online=options.online||(this.remote?true:null);return model.all(selector,options,callback)}else{if(this._cache[key]){callback(this._cache[key]);return}model.api("GET",options.fallback,
function(status,response){if(status!==200){alert("Failed to fetch "+name);return}var models=[];response.forEach(function(item){var m=new model(item);m.remote=true;models.push(m)});this._cache[key]=models;callback(models)}.bind(this))}}},skip=false;has_many.forEach(function(key,i){if(skip){skip=false;return}skip=typeof has_many[i+1]!=="string";createGetter(key,this.prototype,skip?has_many[i+1]:null)},this)};Model.belongs_to=function(belongs_to,is_api_parent){if(belongs_to instanceof Array===true||
arguments.length>1&&typeof is_api_parent!=="boolean")throw new Error("belongs_to: Multiple parents are not implemented");var name=belongs_to.replace(/^\w/,upper);this.parent_constructor=name;this._has_api_parent=!!is_api_parent;this.prototype.getParent=function(selector,options,callback){if(arguments.length===2){callback=arguments[1];options=arguments[0];selector={}}if(arguments.length===1){callback=arguments[0];options={};selector={}}var model=window[name];if(model===undefined)throw new Error("Invalid association: "+
name+" is not defined");if(!options.fallback)options.fallback=model.getApiUri(this.parent);if(app.MODE==="offline"){var api_field=window[this.constructor.parent_constructor].api_field;selector[!this.remote?"_id":api_field]=this.parent;options.online=options.online||!!this.remote;return model.one(selector,options,callback)}else{if(this._cache.parent){callback(this._cache.parent);return}model.api("GET",options.fallback,function(status,response){if(status!==200){callback(new model);return}var m=new model(response);
m.remote=true;this._cache.parent=m;callback(m)}.bind(this))}}};Model.search=function(field,q,options,callback){if(arguments.length===3&&typeof arguments[2]==="function"){callback=arguments[2];options={}}field="lower(["+field.replace(":","__")+"])";var sql=this._getSearchSQL(field,q);var M=this;var execute=function(tx){tx.executeSql(sql[0],sql[1],function(tx,result){var rows=result.rows,row;var r,rr=rows.length;var models=[];var doc;if(rr!==0){for(r=0;r<rr;++r){doc={};row=rows.item(r);Object.getOwnPropertyNames(row).forEach(function(key){doc[key.replace("__",
":")]=row[key]});models.push(new M(doc))}callback(options.limit!==1?models:models[0]||new M)}else callback(options.limit!==1?[]:new M)},function(tx,err){if(console){console.error("SQL Error: "+err.message+"; "+JSON.stringify(err));console.log("The SQL query was:",sql[0],sql[1])}callback(err)})};if(options.tx)execute(options.tx);else app.db.transaction(execute)};Model._getSearchSQL=function(field,q){var sql="SELECT * "+"FROM ["+this.collection+"] "+"WHERE [_ns] = ? ";var params=[app.namespace];q.forEach(function(word){sql+=
"AND ( "+field+" LIKE ? OR "+field+" LIKE ? "+") ";params.push(word+"%");params.push("% "+word+"%")});return[sql,params]};Model.api=function(method,uri,params,data,callback){if(arguments.length===3){callback=arguments[2];data={};params={}}else if(arguments.length===4){callback=arguments[3];data={};params=arguments[2]}data=data||{};var data_str="",xhr=new XMLHttpRequest,headers=this.headers||{};uri=uri.replace(new RegExp("./+","g"),function(a){return a[0]===":"&&a.length>2?"://":a[0]+"/"});Object.keys(params).forEach(function(key,
i){uri+=i===0?"?":"&";uri+=key+"="+encodeURIComponent(params[key])});Object.keys(data).forEach(function(key,i){data_str+=i!==0?"&":"";data_str+=key+"="+encodeURIComponent(data[key])});xhr.open(method,uri,true);Object.keys(headers).forEach(function(key){xhr.setRequestHeader(key,headers[key])});if((method==="POST"||method==="PUT")&&headers["content-type"]===undefined)xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");xhr.onreadystatechange=function(){if(this.readyState===4){if(this.status===
401){window.document.sessionexpired=true;window.document.fire("flowoff:sessionexpire")}var json;try{json=JSON.parse(this.responseText)}catch(exc){callback(Model.getStdStatus(this.status),this.responseText?{"data":this.responseText}:null,this)}if(json)callback(Model.getStdStatus(this.status),json,this)}};xhr.send(data_str||null)};Model.getStdStatus=function(status){status=Number(status);switch(status){case 1223:return 204;default:return status}};Model.getApiUri=function(id,assoc){var uri=app.get("api_root")+
"/"+this.collection.toLowerCase();if(id!==undefined){uri+="/"+id;if(assoc)uri+="/"+assoc.replace(/y$/,"ies").replace(/\w$/,function(a){return a+"s"}).toLowerCase()}return uri};Model.headers={"x-requested-with":"XMLHttpRequest"};Model.api_field="id";Model.parent_constructor="Model";window.Model=Model})();(function(){var Controller=Function.inherit(function(route){this._route=route},{"view":function(){app.data.started=true;if(typeof this[this._route.view]!=="function")throw"404 Page Not Found (Missing view)";document.fire("flowoff:callstart",this._route);this[this._route.view](this._route.params)}});window.Controller=Controller})();(function(){var fn_dynamicLink=function(event){var href=this.attr("href");if(href[0]==="#"){event.preventDefault();event.stopPropagation();app.call(href)}};var makeLinksDynamic=function(el){el.find("a[href]").forEach(function(a){a.removeEventListener("click",fn_dynamicLink,false);a.addEventListener("click",fn_dynamicLink,false)})};var Component=Function.inherit(function(){var component=this;this._components={};this.element=null;this.data={"component":this};this.NAME=this.constructor.prototype.NAME;
Object.defineProperty(this,"rendered",{get:function(){return component.element!==null}})},{"toString":function(){return"[object Component]"},"attach":function(key,component){if(component instanceof Component!==true)throw"The passed object is not a component ("+key+")";if(this._components[key]===undefined)this._components[key]=[];this._components[key].push(component);component.parent=this},"getAttached":function(key){if(this._components[key]===undefined)return[];return this._components[key].slice()},
"remove":function(key,component){var components=this._components[key],c,cc;if(components===undefined)return;if(component===undefined||component===false){delete this._components[key];if(component!==false)this.rerender(key);return}for(c=0,cc=components.length;c<cc;++c)if(components[c]===component){if(component.element)component.element.remove();delete components[c];this._components[key]=components.compact();return}},"render":function(){if(!this._template)throw"Missing component template "+this.toString();
var ejs=new EJS({"text":this._template});var html=ejs.render(this.data);var div=(new Element("div")).html(html);div.find("*[components]").forEach(function(placeholder){var key=placeholder.attr("components");if(key!==null)this.getAttached(key).forEach(function(component){if(typeof component.beforeRender==="function")component.beforeRender();placeholder.insert(component.render());if(typeof component.afterRender==="function")component.afterRender()})},this);this.element=div.firstChild;makeLinksDynamic(this.element);
return this.element},"rerender":function(key,not_rendered_only){if(!this.element)return;if(arguments.length===0){var el=this.element;if(typeof this.beforeRender==="function")this.beforeRender();el.insert({after:this.render()});el.remove();if(typeof this.afterRender==="function")this.afterRender();return}var placeholder;var element_key=this.element.attr("components");if(element_key!==null&&element_key===key)placeholder=this.element;else placeholder=this.element.find('*[components="'+key+'"]').first();
if(placeholder===undefined){if(console&&console.warn)console.warn('There is no such component placeholder "'+key+'".');return}if(!not_rendered_only)placeholder.html(null);this.getAttached(key).forEach(function(component,i){if(not_rendered_only&&component.rendered)return;if(typeof component.beforeRender==="function")component.beforeRender();if(!not_rendered_only||i===0)placeholder.insert(component.render());else placeholder.childNodes[i-1].insert({after:component.render()});if(typeof component.afterRender===
"function")component.afterRender()})},"replace":function(key,components){if(components instanceof Array!==true)components=[components];this._components[key]=[];components.forEach(function(component){if(component instanceof Component!==true)throw"One of the passed objects is not a component ("+key+")";this._components[key].push(component)},this);this.rerender(key)}});var RootComponent=Component.inherit(function(element){this.NAME="$root";this.element=element;this.element.attr("components","components")},
{"attach":function(component){return Component.prototype.attach.call(this,"components",component)},"rerender":function(){return Component.prototype.rerender.call(this,"components")}});window.Component=Component;window.RootComponent=RootComponent;EJS.Helpers.prototype.lang=function(key){return app.lang(key,this._data)}})();(function(){Object.defineProperty(window.HTMLFormElement.prototype,"values",{get:function(){var values={};this.find("input","select","textarea").forEach(function(item){var name=item.attr("name");if(name)values[name.replace("__",":")]=item.value});return values}})})();(function(){var app;var l=window.location;var upper=function(a){return a.toUpperCase()};var BootErrorHandler={"_errors":{"NOT_FOUND":{"title":"Page Not Found","content":"The page you are trying to access does not exist."},"MIGRATION_FAILED":{"title":"Database Error","content":"There was a problem setting up your database. Please, try again later."}},"handle":function(code){var error=this._errors[code]||{"title":"Unknown Error","content":"An unkown error has occured. Sorry for inconvenience."};if(app._cfg.erase)document.body.attr("class",
"bootError").html(""+'<div class="box">'+"<h1>"+error.title+"</h1>"+"<p>"+error.content+"</p>"+"<hr />"+"<p>Powered by FlowOff Framework</p>"+"</div>");else alert(error.title+"\n\n"+error.content)}};app={"set":function(key,value){this._cfg[key]=value},"get":function(key){return this._cfg[key]||null},"run":function(callback){var app=this;if(l.pathname!==this._cfg.root){l.href=l.protocol+"//"+l.host+this._cfg.root+"#!"+l.pathname;return}if(l.hash==="")l.hash="#!/";window.addEventListener("flowoff:callend",
function(){app.data.viewReady=true},false);var startup=function(){if(typeof callback==="function")callback();if(app._cfg.erase)document.body.html(null);app.tree=new RootComponent(app.get("tree_root")||document.body);app.data.hash=l.hash;if("onhashchange"in window)window.addEventListener("hashchange",function(){if(app.data.hash!==l.hash)app.call(l.hash)},false);else setInterval(function(){if(l.hash!==this.data.hash){app.call(l.hash);app.data.hash=l.hash}},50);if(app._queue instanceof OperationQueue===
false)app._queue=null;app.call(l.hash)};var mode="online";if(this._cfg.db_name&&window.openDatabase!==undefined){mode="offline";var createStateTable=function(){app.db.transaction(function(tx){tx.executeSql("CREATE TABLE [_state] ([key], [value])",[],function(tx){tx.executeSql("INSERT INTO [_state] ([key], [value]) VALUES (?, ?)",["last_migration",-1],function(tx,result){app._dbMigrate(-1,startup)})},function(tx,error){throw error;})})};this.db=window.openDatabase(this._cfg.db_name,"1.0",this._cfg.db_title,
this._cfg.db_size);this.db.transaction(function(tx){tx.executeSql("SELECT [value] FROM [_state] WHERE [key] = ?",["last_migration"],function(tx,result){if(result.rows.length===0)tx.executeSql("INSERT INTO [_state] ([key], [value]) VALUES (?, ?)",["last_migration",-1],function(){app._dbMigrate(-1,startup)});else app._dbMigrate(parseInt(result.rows.item(0).value,10),startup)},function(tx,error){createStateTable()})})}this.MODE=mode;this.ORIGINAL_MODE=mode;if(mode==="online")startup();this.data.booted=
true},"track":function(){if(this.cfg.gaTracker)this.cfg.gaTracker.push(["_trackPageview",l.hash.substring(2)])},"loadStyle":function(path,callback){var head=document.documentElement.find("head")[0];var link=new Element("link",{"rel":"stylesheet","type":"text/css","href":this._cfg.root+"css/"+path});head.insert(link);if(typeof callback==="function")(function(){try{if(link.sheet&&link.sheet.cssRules.length>0||link.styleSheet&&link.styleSheet.cssText.length>0||link.innerHTML&&link.innerHTML.length>0)callback();
else throw new Error;}catch(exc){setTimeout(arguments.callee,50)}})()},"call":function(uri){var hash=uri.search("#!")>-1?uri.split("#!")[1]:uri,qs=hash.split("?")[1],route,Controller,controller;this.data.hash="#!"+hash;if(l.hash!=="#!"+hash&&hash!=="/")l.hash="#!"+hash;hash=hash.split("?")[0];try{route=this.router.match(hash,qs);if(route===null)throw new Error("404 Page Not Found (No route)");Controller=window[route.controller.replace(/^\w/,upper)+"Controller"];if(Controller===undefined)throw new Error("404 Page Not Found (Controller file missing)");
controller=new Controller(route);this.data.params=route.params;route.params._c=route.controller;route.params._v=route.view;if(!this.data.started){var startup_mode;if(controller.startup!==undefined)startup_mode=controller.startup(route.params);if(startup_mode!==false)this.data.started=true}if(this.data.started){if(controller[route.view]===undefined)throw"404 Page Not Found (Missing view)";document.fire("flowoff:callstart",route);controller[route.view](route.params)}}catch(exc){if(!this.data.started)this._boot_error_handler.handle(exc.message.substr(0,
3)==="404"?"NOT_FOUND":"UNKNOWN");throw exc;}},"redirect":function(cv,params){this.call(this.link(cv.replace(/:$/,":default"),params))},"link":function(cv,params,options){if(cv===undefined)return this.data.hash;if(options===undefined)options={};var abs=cv.substring(0,2)==="//",uri;if(abs)cv=cv.substring(2);cv=cv.replace(/:$/,":default").split(":");if(abs&&!app._cfg.domain)throw"Invalid state: No domain set";uri=this.router.resolve({"namespace":null,"controller":cv[0],"view":cv[1],"params":params});
return(abs?"http://"+app._cfg.domain+(!options.no_port?":"+app._cfg.port:""):"#!")+(uri!==null?uri:"/error/s404")},"registerComponent":function(key,Component){this._components[key]=Component;return Component},"getComponent":function(key){return this._components[key]||null},"component":function(key,vars){if(this._components[key]===undefined)throw new Error('Undefined component "'+key+'"');var component=new this._components[key];component.NAME=key;if(component instanceof Component!==true)throw new Error("The registered object is not a component ("+
key+")");if(vars!==undefined)Object.getOwnPropertyNames(vars).forEach(function(key){Object.defineProperty(this,key,Object.getOwnPropertyDescriptor(vars,key))},component.data);return component},"lang":function(key,params){if(this._lang[key]===undefined){if(console&&console.warn)console.warn("Unknown lang key: "+key);return""}var lang=this._lang[key];if(params!==undefined){var ejs=new EJS({"text":lang});lang=ejs.render(params)}return lang},"registerLang":function(lang){var _lang=this._lang;Object.getOwnPropertyNames(lang).forEach(function(key){_lang[key]=
lang[key]})},"getState":function(callback){if(this.MODE!=="offline"){callback(null);return}if(!app.namespace)throw new Error("Global namespace is not defined.");this.db.transaction(function(tx){tx.executeSql("SELECT [key], [value] FROM [_state]",[],function(tx,result){var rows=result.rows,state={},r,rr=rows.length;for(r=0;r<rr;++r){var row=rows.item(r),val=row.value.toString(),key=row.key;var ns;if(key.search(".")!==-1){ns=key.split(".")[0];if(ns!==app.namespace)continue;key=row.key.split(".")[1]}state[key]=
val.match(/^[0-9]+$/)?Number(val):val}callback(state)})})},"setState":function(key,value,callback){if(this.MODE!=="offline"){callback();return}if(!app.namespace)throw new Error("Global namespace is not defined");key=app.namespace+"."+key;this.db.transaction(function(tx){tx.executeSql("UPDATE [_state] SET [value] = ? WHERE [key] = ?",[value,key],function(tx,result){if(result.rowsAffected!==0)callback();else tx.executeSql("INSERT INTO [_state] ([key], [value]) VALUES (?, ?)",[key,value],function(tx,
result){callback()})})})},"queue":function(op,callback){this._queue.push(op,callback)},"getQueue":function(){return this._queue},"_dbMigrate":function(last_migration,callback){if(this._migrations===undefined){this._boot_error_handler.handle("MIGRATION_FAILED");throw new Error("No migration file provided");}var app=this,m=last_migration+1,migrations=app._migrations,mm=migrations.length,q=0,qq=0;var throw_error=function(tx,error){app._boot_error_handler.handle("MIGRATION_FAILED");throw new Error("Migrating the database failed at migration: "+
m+", query: "+q+" of "+qq+"\n"+error.message);};var m_iter=function(){if(m<mm){var queries=migrations[m];queries.push(["UPDATE [_state] SET [value] = ? WHERE [key] = ?",[m,"last_migration"]]);q=0;qq=queries.length;app.db.transaction(function(tx){var q_iter=function(tx){var query=queries[q];tx.executeSql(query instanceof Array?query[0]:query,query instanceof Array?query[1]:null,q<qq-1?q_iter:m_iter,throw_error);++q};q_iter(tx)})}else callback();++m};m_iter()}};var namespace=null;Object.defineProperties(app,
{"data":{"value":{"booted":false,"hash":"","viewReady":false},"enumerable":true},"namespace":{"get":function(){return namespace},"set":function(val){namespace=val;this._queue=new OperationQueue(val);app.fire("queueset")}},"router":{"value":new Router},"_cfg":{"value":{"root":"/","api_root":"","erase":true,"domain":window.location.hostname,"port":window.location.port}},"_components":{"value":{}},"_lang":{"value":{}},"_boot_error_handler":{"value":BootErrorHandler}});Object.defineProperty(window,"app",
{"value":app,"writable":false})})();window.Iterator=function(arr,fn){this._arr=arr;this._fn=fn};window.Iterator.prototype.run=function(callback){var arr=this._arr;var fn=this._fn;var i=0;var ii=arr.length;function next(){if(i===ii){if(typeof callback==="function")callback()}else{fn.call(null,arr[i],next,i);i+=1}}next()};(function(window,document){function g(a){throw a;}var i=void 0,m=null;function n(a){return function(){return this[a]}}function o(a){return function(){return a}}var r,s=this;function aa(a){for(var a=a.split("."),b=s,c;c=a.shift();)if(b[c]!=m)b=b[c];else return m;return b}function ba(){}function t(a){var b=typeof a;if(b=="object")if(a){if(a instanceof Array)return"array";else if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if(c=="[object Window]")return"object";if(c=="[object Array]"||
typeof a.length=="number"&&typeof a.splice!="undefined"&&typeof a.propertyIsEnumerable!="undefined"&&!a.propertyIsEnumerable("splice"))return"array";if(c=="[object Function]"||typeof a.call!="undefined"&&typeof a.propertyIsEnumerable!="undefined"&&!a.propertyIsEnumerable("call"))return"function"}else return"null";else if(b=="function"&&typeof a.call=="undefined")return"object";return b}function ca(a){var b=t(a);return b=="array"||b=="object"&&typeof a.length=="number"}function u(a){return typeof a==
"string"}function v(a){return t(a)=="function"}function da(a){a=t(a);return a=="object"||a=="array"||a=="function"}var ea="closure_uid_"+Math.floor(Math.random()*2147483648).toString(36),fa=0,ga=Date.now||function(){return+new Date};function w(a,b){x.prototype[a]=b}function y(a,b){function c(){}c.prototype=b.prototype;a.o=b.prototype;a.prototype=new c;a.prototype.constructor=a}function ha(a,b){for(var c=1;c<arguments.length;c++)var d=String(arguments[c]).replace(/\$/g,"$$$$"),a=a.replace(/\%s/,d);
return a}function ia(a){if(!ja.test(a))return a;a.indexOf("&")!=-1&&(a=a.replace(ka,"&amp;"));a.indexOf("<")!=-1&&(a=a.replace(la,"&lt;"));a.indexOf(">")!=-1&&(a=a.replace(ma,"&gt;"));a.indexOf('"')!=-1&&(a=a.replace(na,"&quot;"));return a}var ka=/&/g,la=/</g,ma=/>/g,na=/\"/g,ja=/[&<>\"]/;function oa(a,b){for(var c=0,d=String(a).replace(/^[\s\xa0]+|[\s\xa0]+$/g,"").split("."),e=String(b).replace(/^[\s\xa0]+|[\s\xa0]+$/g,"").split("."),f=Math.max(d.length,e.length),h=0;c==0&&h<f;h++){var k=d[h]||"",
j=e[h]||"",l=RegExp("(\\d*)(\\D*)","g"),p=RegExp("(\\d*)(\\D*)","g");do{var q=l.exec(k)||["","",""],E=p.exec(j)||["","",""];if(q[0].length==0&&E[0].length==0)break;c=pa(q[1].length==0?0:parseInt(q[1],10),E[1].length==0?0:parseInt(E[1],10))||pa(q[2].length==0,E[2].length==0)||pa(q[2],E[2])}while(c==0)}return c}function pa(a,b){if(a<b)return-1;else if(a>b)return 1;return 0}var qa=Math.random()*2147483648|0,ra={};function sa(a){return ra[a]||(ra[a]=String(a).replace(/([A-Z])/g,"-$1").toLowerCase())}
var ta;function z(a,b,c){a.dataset?a.dataset[b]=c:a.setAttribute("data-"+sa(b),c)}function A(a,b){return a.dataset?a.dataset[b]:a.getAttribute("data-"+sa(b))}var ua={drawing:function(a){var b="";a.vb.forEach(function(a,d){if(d===0)b+="<![CDATA["+a.data.match(/;base64,(.*)/)[1]+"]]\>",b+="<drawing>";else{b+="<layer";a.color&&(b+=' color="'+a.color+'"');var e=a.data;e?(e=e.match(/^data:([\w-\/]+);base64,(.*)/),b+=' type="'+e[1]+'">',b+="<![CDATA["+e[2]+"]]\>",b+="</layer>"):b+=" />"}});b+="</drawing>";
return b}};var B={text:{tagName:"P"},h1:{tagName:"H1",Y:"text"},h2:{tagName:"H2",Y:"text"},h3:{tagName:"H3",Y:"text"},strong:{I:!0,tagName:"STRONG"},em:{I:!0,tagName:"EM"},u:{I:!0,tagName:"U"},highlight:{I:!0,tagName:"MARK",className:"highlight"},strike:{I:!0,tagName:"S"},sub:{I:!0,nb:"indexes",tagName:"SUB"},sup:{I:!0,nb:"indexes",tagName:"SUP"},image:{tagName:"IMG",Y:"text",cb:function(a){var b="<"+a.type;a.list&&(b+=' list="'+a.list+'"');a.Ya?b+=' ref="'+a.Ya+'">':a.ua?(b+=' type="image/png"',
b+=">",b+=a.ua(a)):(a=a.i.firstChild.src,a.substr(0,5)==="data:"?(a=a.match(/^data:([\w-\/]+);base64,(.*)/),b+=' type="'+a[1]+'"',b+="><![CDATA["+a[2]+"]]\>"):b+=">");return b},bb:function(a){if(a.i.getAttribute("ref"))return document.createTextNode("[Referenced images not supported]");var b=a.i.firstChild;a.i.removeChild(b);var c=new Image;c.src="data:"+a.i.getAttribute("type")+";base64,"+b.nodeValue;return c}}};function va(a,b){a||g(Error("List element does not exist."));this.list=a;this.Ba=Boolean(b)}
function wa(a,b){Array.prototype.forEach.call(b,function(a){if(a.nodeType===a.ELEMENT_NODE){var b;b=this.Ba?{i:a,type:A(a,"type"),list:A(a,"list")||m,Ya:A(a,"ref")||m,ua:A(a,"plugin")||m}:{i:a,type:a.tagName.toLowerCase(),list:a.getAttribute("list")||m};if(this.Qa(b)!==!1){if(this.Ba)Array.prototype.forEach.call(a.firstChild.childNodes,this.ga,this),(a=a.lastChild)&&a.tagName==="UL"&&wa(this,a.childNodes);else for(var a=a.childNodes,e=0,f=a.length;e<f;++e){var h=a[e],k=h.tagName?h.tagName.toLowerCase():
"null",j=B[k];if(k==="null"||!j||j.I)this.ga(h);else{wa(this,Array.prototype.slice.call(a,e-1));break}}this.Pa(b)}}},a)}va.prototype.ga=function(a){if(a.nodeType===a.ELEMENT_NODE)if(a.tagName.toLowerCase()!=="null"){var b;if(this.Ba){a:{b=Object.keys(B);for(var c=0,d=b.length;c<d;++c){var e=B[b[c]];if(e.I&&a.tagName===e.tagName&&a.className===(e.className||"")){b=b[c];break a}}b=m}b={type:b}}else b={type:a.tagName.toLowerCase()};this.Sa(b)!==!1&&(Array.prototype.forEach.call(a.childNodes,this.ga,
this),this.Ra(b))}else Array.prototype.forEach.call(a.childNodes,this.ga,this);else(a.nodeType===a.TEXT_NODE||a.nodeType===a.CDATA_SECTION_NODE)&&a.nodeValue!==""&&this.Ta(a.nodeValue)};function xa(a){this.stack=Error().stack||"";if(a)this.message=String(a)}y(xa,Error);xa.prototype.name="CustomError";function ya(a,b){b.unshift(a);xa.call(this,ha.apply(m,b));b.shift();this.Cb=a}y(ya,xa);ya.prototype.name="AssertionError";function za(a,b){g(new ya("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,
1)))}function Aa(a){return a[a.length-1]}var C=Array.prototype,D=C.indexOf?function(a,b,c){return C.indexOf.call(a,b,c)}:function(a,b,c){c=c==m?0:c<0?Math.max(0,a.length+c):c;if(u(a))return!u(b)||b.length!=1?-1:a.indexOf(b,c);for(;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1},Ba=C.forEach?function(a,b,c){C.forEach.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=u(a)?a.split(""):a,f=0;f<d;f++)f in e&&b.call(c,e[f],f,a)},Ca=C.map?function(a,b,c){return C.map.call(a,b,c)}:function(a,b,c){for(var d=
a.length,e=Array(d),f=u(a)?a.split(""):a,h=0;h<d;h++)h in f&&(e[h]=b.call(c,f[h],h,a));return e},Da=C.some?function(a,b,c){return C.some.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=u(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return!0;return!1},Ea=C.every?function(a,b,c){return C.every.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=u(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&!b.call(c,e[f],f,a))return!1;return!0};function Fa(a,b){var c;a:{c=a.length;for(var d=u(a)?a.split(""):
a,e=0;e<c;e++)if(e in d&&b.call(i,d[e],e,a)){c=e;break a}c=-1}return c<0?m:u(a)?a.charAt(c):a[c]}function Ga(a){return C.concat.apply(C,arguments)}function Ha(a){if(t(a)=="array")return Ga(a);else{for(var b=[],c=0,d=a.length;c<d;c++)b[c]=a[c];return b}}function Ia(a,b,c){return arguments.length<=2?C.slice.call(a,b):C.slice.call(a,b,c)}var Ja,Ka,La,Ma;function Na(){return s.navigator?s.navigator.userAgent:m}Ma=La=Ka=Ja=!1;var Oa;if(Oa=Na()){var Pa=s.navigator;Ja=Oa.indexOf("Opera")==0;Ka=!Ja&&Oa.indexOf("MSIE")!=
-1;La=!Ja&&Oa.indexOf("WebKit")!=-1;Ma=!Ja&&!La&&Pa.product=="Gecko"}var Qa=Ja,F=Ka,H=Ma,Ra=La,Sa=s.navigator,Ta=(Sa&&Sa.platform||"").indexOf("Mac")!=-1,Ua;a:{var Va="",Wa;if(Qa&&s.opera)var Xa=s.opera.version,Va=typeof Xa=="function"?Xa():Xa;else if(H?Wa=/rv\:([^\);]+)(\)|;)/:F?Wa=/MSIE\s+([^\);]+)(\)|;)/:Ra&&(Wa=/WebKit\/(\S+)/),Wa)var Ya=Wa.exec(Na()),Va=Ya?Ya[1]:"";if(F){var Za,$a=s.document;Za=$a?$a.documentMode:i;if(Za>parseFloat(Va)){Ua=String(Za);break a}}Ua=Va}var ab={};function I(a){return ab[a]||
(ab[a]=oa(Ua,a)>=0)}var bb=!F||I("9");!H&&!F||F&&I("9")||H&&I("1.9.1");F&&I("9");function cb(a,b){var c;c=(c=a.className)&&typeof c.split=="function"?c.split(/\s+/):[];var d=Ia(arguments,1),e;e=c;for(var f=0,h=0;h<d.length;h++)D(e,d[h])>=0||(e.push(d[h]),f++);e=f==d.length;a.className=c.join(" ");return e}function db(a,b){for(var c in a)b.call(i,a[c],c,a)}var eb="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");function fb(a,b){for(var c,d,
e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(var f=0;f<eb.length;f++)c=eb[f],Object.prototype.hasOwnProperty.call(d,c)&&(a[c]=d[c])}}function gb(a){return a?new hb(J(a)):ta||(ta=new hb)}function ib(a,b,c){c=c||document;a=a&&a!="*"?a.toUpperCase():"";if(c.querySelectorAll&&c.querySelector&&(!Ra||document.compatMode=="CSS1Compat"||I("528"))&&(a||b))return c.querySelectorAll(a+(b?"."+b:""));if(b&&c.getElementsByClassName)if(c=c.getElementsByClassName(b),a){for(var d={},e=0,f=0,
h;h=c[f];f++)a==h.nodeName&&(d[e++]=h);d.length=e;return d}else return c;c=c.getElementsByTagName(a||"*");if(b){d={};for(f=e=0;h=c[f];f++)a=h.className,typeof a.split=="function"&&D(a.split(/\s+/),b)>=0&&(d[e++]=h);d.length=e;return d}else return c}function jb(a,b){db(b,function(b,d){d=="style"?a.style.cssText=b:d=="class"?a.className=b:d=="for"?a.htmlFor=b:d in kb?a.setAttribute(kb[d],b):a[d]=b})}var kb={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",rowspan:"rowSpan",valign:"vAlign",
height:"height",width:"width",usemap:"useMap",frameborder:"frameBorder",maxlength:"maxLength",type:"type"};function lb(a){return a?a.parentWindow||a.defaultView:window}function mb(a,b,c){return nb(document,arguments)}function nb(a,b){var c=b[0],d=b[1];if(!bb&&d&&(d.name||d.type)){c=["<",c];d.name&&c.push(' name="',ia(d.name),'"');if(d.type){c.push(' type="',ia(d.type),'"');var e={};fb(e,d);d=e;delete d.type}c.push(">");c=c.join("")}c=a.createElement(c);if(d)u(d)?c.className=d:t(d)=="array"?cb.apply(m,
[c].concat(d)):jb(c,d);b.length>2&&ob(a,c,b,2);return c}function ob(a,b,c,d){function e(c){c&&b.appendChild(u(c)?a.createTextNode(c):c)}for(;d<c.length;d++){var f=c[d];ca(f)&&!(da(f)&&f.nodeType>0)?Ba(pb(f)?Ha(f):f,e):e(f)}}function qb(a,b){ob(J(a),a,arguments,1)}function rb(a,b){b.parentNode&&b.parentNode.insertBefore(a,b)}function sb(a,b){b.parentNode&&b.parentNode.insertBefore(a,b.nextSibling)}function K(a){return a&&a.parentNode?a.parentNode.removeChild(a):m}function L(a,b){if(a.contains&&b.nodeType==
1)return a==b||a.contains(b);if(typeof a.compareDocumentPosition!="undefined")return a==b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}function tb(a,b){if(a==b)return 0;if(a.compareDocumentPosition)return a.compareDocumentPosition(b)&2?1:-1;if("sourceIndex"in a||a.parentNode&&"sourceIndex"in a.parentNode){var c=a.nodeType==1,d=b.nodeType==1;if(c&&d)return a.sourceIndex-b.sourceIndex;else{var e=a.parentNode,f=b.parentNode;return e==f?ub(a,b):!c&&L(e,b)?-1*vb(a,
b):!d&&L(f,a)?vb(b,a):(c?a.sourceIndex:e.sourceIndex)-(d?b.sourceIndex:f.sourceIndex)}}d=J(a);c=d.createRange();c.selectNode(a);c.collapse(!0);d=d.createRange();d.selectNode(b);d.collapse(!0);return c.compareBoundaryPoints(s.Range.START_TO_END,d)}function vb(a,b){var c=a.parentNode;if(c==b)return-1;for(var d=b;d.parentNode!=c;)d=d.parentNode;return ub(d,a)}function ub(a,b){for(var c=b;c=c.previousSibling;)if(c==a)return-1;return 1}function wb(a){var b,c=arguments.length;if(c){if(c==1)return arguments[0]}else return m;
var d=[],e=Infinity;for(b=0;b<c;b++){for(var f=[],h=arguments[b];h;)f.unshift(h),h=h.parentNode;d.push(f);e=Math.min(e,f.length)}f=m;for(b=0;b<e;b++){for(var h=d[0][b],k=1;k<c;k++)if(h!=d[k][b])return f;f=h}return f}function J(a){return a.nodeType==9?a:a.ownerDocument||a.document}var xb={SCRIPT:1,STYLE:1,HEAD:1,IFRAME:1,OBJECT:1},yb={IMG:" ",BR:"\n"};function zb(a){var b=[];Ab(a,b,!1);return b.join("")}function Ab(a,b,c){if(!(a.nodeName in xb))if(a.nodeType==3)c?b.push(String(a.nodeValue).replace(/(\r\n|\r|\n)/g,
"")):b.push(a.nodeValue);else if(a.nodeName in yb)b.push(yb[a.nodeName]);else for(a=a.firstChild;a;)Ab(a,b,c),a=a.nextSibling}function pb(a){if(a&&typeof a.length=="number")if(da(a))return typeof a.item=="function"||typeof a.item=="string";else if(v(a))return typeof a.item=="function";return!1}function hb(a){this.G=a||s.document||document}r=hb.prototype;r.sa=n("G");r.pa=function(a,b,c){return nb(this.G,arguments)};r.createElement=function(a){return this.G.createElement(a)};r.createTextNode=function(a){return this.G.createTextNode(a)};
r.Ia=function(){return this.G.parentWindow||this.G.defaultView};r.appendChild=function(a,b){a.appendChild(b)};r.removeNode=K;r.contains=L;function Bb(){}Bb.prototype.qa=!1;Bb.prototype.P=function(){if(!this.qa)this.qa=!0,this.q()};Bb.prototype.q=function(){};var M="StopIteration"in s?s.StopIteration:Error("StopIteration");function Cb(){}Cb.prototype.next=function(){g(M)};Cb.prototype.N=function(){return this};function Db(a){if(a instanceof Cb)return a;if(typeof a.N=="function")return a.N(!1);if(ca(a)){var b=
0,c=new Cb;c.next=function(){for(;;)if(b>=a.length&&g(M),b in a)return a[b++];else b++};return c}g(Error("Not implemented"))}function Eb(a,b){if(ca(a))try{Ba(a,b,i)}catch(c){c!==M&&g(c)}else{a=Db(a);try{for(;;)b.call(i,a.next(),i,a)}catch(d){d!==M&&g(d)}}}function Fb(a){return Gb(a||arguments.callee.caller,[])}function Gb(a,b){var c=[];if(D(b,a)>=0)c.push("[...circular reference...]");else if(a&&b.length<50){c.push(Hb(a)+"(");for(var d=a.arguments,e=0;e<d.length;e++){e>0&&c.push(", ");var f;f=d[e];
switch(typeof f){case "object":f=f?"object":"null";break;case "string":break;case "number":f=String(f);break;case "boolean":f=f?"true":"false";break;case "function":f=(f=Hb(f))?f:"[fn]";break;default:f=typeof f}f.length>40&&(f=f.substr(0,40)+"...");c.push(f)}b.push(a);c.push(")\n");try{c.push(Gb(a.caller,b))}catch(h){c.push("[exception trying to get caller]\n")}}else a?c.push("[...long stack...]"):c.push("[end]");return c.join("")}function Hb(a){a=String(a);if(!Ib[a]){var b=/function ([^\(]+)/.exec(a);
Ib[a]=b?b[1]:"[Anonymous]"}return Ib[a]}var Ib={};function Jb(a,b,c,d,e){this.reset(a,b,c,d,e)}Jb.prototype.wb=0;Jb.prototype.Ga=m;Jb.prototype.Fa=m;var Kb=0;Jb.prototype.reset=function(a,b,c,d,e){this.wb=typeof e=="number"?e:Kb++;this.Db=d||ga();this.X=a;this.pb=b;this.Bb=c;delete this.Ga;delete this.Fa};Jb.prototype.$a=function(a){this.X=a};function N(a){this.qb=a}N.prototype.ka=m;N.prototype.X=m;N.prototype.oa=m;N.prototype.Ka=m;function Lb(a,b){this.name=a;this.value=b}Lb.prototype.toString=n("name");
var Mb=new Lb("SEVERE",1E3),Nb=new Lb("WARNING",900),Ob=new Lb("CONFIG",700);N.prototype.getParent=n("ka");N.prototype.$a=function(a){this.X=a};function Pb(a){if(a.X)return a.X;if(a.ka)return Pb(a.ka);za("Root logger has no level set.");return m}N.prototype.log=function(a,b,c){if(a.value>=Pb(this).value){a=this.lb(a,b,c);s.console&&s.console.markTimeline&&s.console.markTimeline("log:"+a.pb);for(b=this;b;){var c=b,d=a;if(c.Ka)for(var e=0,f=i;f=c.Ka[e];e++)f(d);b=b.getParent()}}};N.prototype.lb=function(a,
b,c){var d=new Jb(a,String(b),this.qb);if(c){d.Ga=c;var e;var f=arguments.callee.caller;try{var h;var k=aa("window.location.href");if(u(c))h={message:c,name:"Unknown error",lineNumber:"Not available",fileName:k,stack:"Not available"};else{var j,l,p=!1;try{j=c.lineNumber||c.Ab||"Not available"}catch(q){j="Not available",p=!0}try{l=c.fileName||c.filename||c.sourceURL||k}catch(E){l="Not available",p=!0}h=p||!c.lineNumber||!c.fileName||!c.stack?{message:c.message,name:c.name,lineNumber:j,fileName:l,stack:c.stack||
"Not available"}:c}e="Message: "+ia(h.message)+'\nUrl: <a href="view-source:'+h.fileName+'" target="_new">'+h.fileName+"</a>\nLine: "+h.lineNumber+"\n\nBrowser stack:\n"+ia(h.stack+"-> ")+"[end]\n\nJS stack traversal:\n"+ia(Fb(f)+"-> ")}catch(G){e="Exception trying to expose exception! You win, we lose. "+G}d.Fa=e}return d};var Qb={},Rb=m;function Sb(a){Rb||(Rb=new N(""),Qb[""]=Rb,Rb.$a(Ob));var b;if(!(b=Qb[a])){b=new N(a);var c=a.lastIndexOf("."),d=a.substr(c+1),c=Sb(a.substr(0,c));if(!c.oa)c.oa=
{};c.oa[d]=b;b.ka=c;Qb[a]=b}return b}function Tb(){}y(Tb,Bb);var Ub=Sb("goog.dom.SavedRange");Tb.prototype.restore=function(a){this.qa&&Ub.log(Mb,"Disposed SavedRange objects cannot be restored.",i);var b=this.la();a||this.P();return b};function Vb(a){this.na="goog_"+qa++;this.fa="goog_"+qa++;this.ea=gb(a.sa());a.$(this.ea.pa("SPAN",{id:this.na}),this.ea.pa("SPAN",{id:this.fa}))}y(Vb,Tb);function Wb(a,b){return u(b?a.na:a.fa)?a.ea.G.getElementById(b?a.na:a.fa):b?a.na:a.fa}function Xb(a,b){K(Wb(a,
!0));K(Wb(a,!1));return b}Vb.prototype.la=function(){var a=m,b=Wb(this,!0),c=Wb(this,!1);if(b&&c){var a=b.parentNode,b=D(a.childNodes,b),d=c.parentNode,c=D(d.childNodes,c);d==a&&(c-=1);a=Yb(a,b,d,c);a=Xb(this,a);a.select()}else Xb(this);return a};Vb.prototype.q=function(){Xb(this);this.ea=m};function O(a,b,c,d,e){this.m=!!b;a&&P(this,a,d);this.depth=e!=i?e:this.n||0;this.m&&(this.depth*=-1);this.ba=!c}y(O,Cb);r=O.prototype;r.i=m;r.n=0;r.Aa=!1;function P(a,b,c,d){if(a.i=b)a.n=typeof c=="number"?c:
a.i.nodeType!=1?0:a.m?-1:1;if(typeof d=="number")a.depth=d}r.A=function(a){this.i=a.i;this.n=a.n;this.depth=a.depth;this.m=a.m;this.ba=a.ba};r.z=function(){return new O(this.i,this.m,!this.ba,this.n,this.depth)};r.za=function(){var a=this.m?-1:1;if(this.n==a)this.n=a*-1,this.depth+=this.n*(this.m?-1:1)};r.next=function(){var a;if(this.Aa){(!this.i||this.ba&&this.depth==0)&&g(M);a=this.i;var b=this.m?-1:1;if(this.n==b){var c=this.m?a.lastChild:a.firstChild;c?P(this,c):P(this,a,b*-1)}else(c=this.m?
a.previousSibling:a.nextSibling)?P(this,c):P(this,a.parentNode,b*-1);this.depth+=this.n*(this.m?-1:1)}else this.Aa=!0;(a=this.i)||g(M);return a};r.splice=function(a){var b=this.i,c=this.m?1:-1;if(this.n==c)this.n=c*-1,this.depth+=this.n*(this.m?-1:1);this.m=!this.m;O.prototype.next.call(this);this.m=!this.m;for(var c=ca(arguments[0])?arguments[0]:arguments,d=c.length-1;d>=0;d--)sb(c[d],b);K(b)};function Zb(){}function $b(a){if(a.getSelection)return a.getSelection();else{var a=a.document,b=a.selection;
if(b){try{var c=b.createRange();if(c.parentElement){if(c.parentElement().document!=a)return m}else if(!c.length||c.item(0).document!=a)return m}catch(d){return m}return b}return m}}function ac(a){for(var b=[],c=0,d=a.Q();c<d;c++)b.push(a.H(c));return b}r=Zb.prototype;r.R=o(!1);r.sa=function(){return J(F?this.v():this.d())};r.Ia=function(){return lb(this.sa())};r.containsNode=function(a,b){return this.D(bc(cc(a),i),b)};r.wa=function(a){this.isCollapsed()||this.K();return this.insertNode(a,!0)};function dc(){var a=
ec();return a.d()&&a.g()?new Vb(a):m}function Q(a,b){O.call(this,a,b,!0)}y(Q,O);function fc(){}y(fc,Zb);fc.prototype.D=function(a,b){var c=ac(this),d=ac(a);return(b?Da:Ea)(d,function(a){return Da(c,function(c){return c.D(a,b)})})};fc.prototype.insertNode=function(a,b){b?rb(a,this.d()):sb(a,this.g());return a};fc.prototype.$=function(a,b){this.insertNode(a,!0);this.insertNode(b,!1)};function R(a,b,c,d,e){var f;if(a){this.c=a;this.f=b;this.b=c;this.e=d;if(a.nodeType==1&&a.tagName!="BR")if(a=a.childNodes,
b=a[b])this.c=b,this.f=0;else{if(a.length)this.c=Aa(a);f=!0}if(c.nodeType==1)(this.b=c.childNodes[d])?this.e=0:this.b=c}Q.call(this,e?this.b:this.c,e);if(f)try{this.next()}catch(h){h!=M&&g(h)}}y(R,Q);r=R.prototype;r.c=m;r.b=m;r.f=0;r.e=0;r.d=n("c");r.g=n("b");r.W=function(){return this.Aa&&this.i==this.b&&(!this.e||this.n!=1)};r.next=function(){this.W()&&g(M);return R.o.next.call(this)};r.za=function(){R.o.za.apply(this);L(this.i,this.b)&&g(M)};r.A=function(a){this.c=a.c;this.b=a.b;this.f=a.f;this.e=
a.e;this.t=a.t;R.o.A.call(this,a)};r.z=function(){var a=new R(this.c,this.f,this.b,this.e,this.t);a.A(this);return a};var gc,hc=(gc="ScriptEngine"in s&&s.ScriptEngine()=="JScript")?s.ScriptEngineMajorVersion()+"."+s.ScriptEngineMinorVersion()+"."+s.ScriptEngineBuildVersion():"0";function ic(){}ic.prototype.D=function(a,b){var c=b&&!a.isCollapsed(),d=a.a;try{return c?this.r(d,0,1)>=0&&this.r(d,1,0)<=0:this.r(d,0,0)>=0&&this.r(d,1,1)<=0}catch(e){return F||g(e),!1}};ic.prototype.containsNode=function(a,
b){return this.D(cc(a),b)};ic.prototype.N=function(){return new R(this.d(),this.h(),this.g(),this.k())};function S(a){this.a=a}y(S,ic);function jc(a){var b=J(a).createRange();if(a.nodeType==3)b.setStart(a,0),b.setEnd(a,a.length);else if(T(a)){for(var c,d=a;(c=d.firstChild)&&T(c);)d=c;b.setStart(d,0);for(d=a;(c=d.lastChild)&&T(c);)d=c;b.setEnd(d,d.nodeType==1?d.childNodes.length:d.length)}else c=a.parentNode,a=D(c.childNodes,a),b.setStart(c,a),b.setEnd(c,a+1);return b}function kc(a,b,c,d){var e=J(a).createRange();
e.setStart(a,b);e.setEnd(c,d);return e}r=S.prototype;r.z=function(){return new this.constructor(this.a.cloneRange())};r.v=function(){return this.a.commonAncestorContainer};r.d=function(){return this.a.startContainer};r.h=function(){return this.a.startOffset};r.g=function(){return this.a.endContainer};r.k=function(){return this.a.endOffset};r.r=function(a,b,c){return this.a.compareBoundaryPoints(c==1?b==1?s.Range.START_TO_START:s.Range.START_TO_END:b==1?s.Range.END_TO_START:s.Range.END_TO_END,a)};
r.isCollapsed=function(){return this.a.collapsed};r.select=function(a){this.ma(lb(J(this.d())).getSelection(),a)};r.ma=function(a){a.removeAllRanges();a.addRange(this.a)};r.K=function(){var a=this.a;a.extractContents();if(a.startContainer.hasChildNodes()&&(a=a.startContainer.childNodes[a.startOffset])){var b=a.previousSibling;zb(a)==""&&K(a);b&&zb(b)==""&&K(b)}};r.insertNode=function(a,b){var c=this.a.cloneRange();c.collapse(b);c.insertNode(a);c.detach();return a};r.$=function(a,b){var c=lb(J(this.d()));
if(c=ec(c))var d=c.d(),e=c.g(),f=c.h(),h=c.k();var k=this.a.cloneRange(),j=this.a.cloneRange();k.collapse(!1);j.collapse(!0);k.insertNode(b);j.insertNode(a);k.detach();j.detach();if(c){if(d.nodeType==3)for(;f>d.length;){f-=d.length;do d=d.nextSibling;while(d==a||d==b)}if(e.nodeType==3)for(;h>e.length;){h-=e.length;do e=e.nextSibling;while(e==a||e==b)}Yb(d,f,e,h).select()}};r.collapse=function(a){this.a.collapse(a)};function lc(a){this.a=a}y(lc,S);lc.prototype.ma=function(a,b){var c=b?this.g():this.d(),
d=b?this.k():this.h(),e=b?this.d():this.g(),f=b?this.h():this.k();a.collapse(c,d);(c!=e||d!=f)&&a.extend(e,f)};function mc(a,b,c,d){O.call(this,a,b,c,m,d)}y(mc,O);mc.prototype.next=function(){do mc.o.next.call(this);while(this.n==-1);return this.i};function nc(a,b){this.a=a;this.ib=b}y(nc,ic);var oc=Sb("goog.dom.browserrange.IeRange");function pc(a){var b=J(a).body.createTextRange();if(a.nodeType==1)b.moveToElementText(a),T(a)&&!a.childNodes.length&&b.collapse(!1);else{for(var c=0,d=a;d=d.previousSibling;){var e=
d.nodeType;if(e==3)c+=d.length;else if(e==1){b.moveToElementText(d);break}}d||b.moveToElementText(a.parentNode);b.collapse(!d);c&&b.move("character",c);b.moveEnd("character",a.length)}return b}r=nc.prototype;r.w=m;r.c=m;r.b=m;r.f=-1;r.e=-1;r.z=function(){var a=new nc(this.a.duplicate(),this.ib);a.w=this.w;a.c=this.c;a.b=this.b;return a};r.p=function(){this.w=this.c=this.b=m;this.f=this.e=-1};r.v=function(){if(!this.w){var a=this.a.text,b=this.a.duplicate(),c=a.replace(/ +$/,"");(c=a.length-c.length)&&
b.moveEnd("character",-c);c=b.parentElement();b=b.htmlText.replace(/(\r\n|\r|\n)+/g," ").length;if(this.isCollapsed()&&b>0)return this.w=c;for(;b>c.outerHTML.replace(/(\r\n|\r|\n)+/g," ").length;)c=c.parentNode;for(;c.childNodes.length==1&&c.innerText==(c.firstChild.nodeType==3?c.firstChild.nodeValue:c.firstChild.innerText);){if(!T(c.firstChild))break;c=c.firstChild}a.length==0&&(c=qc(this,c));this.w=c}return this.w};function qc(a,b){for(var c=b.childNodes,d=0,e=c.length;d<e;d++){var f=c[d];if(T(f)){var h=
pc(f),k=h.htmlText!=f.outerHTML;if(a.isCollapsed()&&k?a.r(h,1,1)>=0&&a.r(h,1,0)<=0:a.a.inRange(h))return qc(a,f)}}return b}r.d=function(){if(!this.c&&(this.c=rc(this,1),this.isCollapsed()))this.b=this.c;return this.c};r.h=function(){if(this.f<0&&(this.f=sc(this,1),this.isCollapsed()))this.e=this.f;return this.f};r.g=function(){if(this.isCollapsed())return this.d();if(!this.b)this.b=rc(this,0);return this.b};r.k=function(){if(this.isCollapsed())return this.h();if(this.e<0&&(this.e=sc(this,0),this.isCollapsed()))this.f=
this.e;return this.e};r.r=function(a,b,c){return this.a.compareEndPoints((b==1?"Start":"End")+"To"+(c==1?"Start":"End"),a)};function rc(a,b,c){c=c||a.v();if(!c||!c.firstChild)return c;for(var d=b==1,e=0,f=c.childNodes.length;e<f;e++){var h=d?e:f-e-1,k=c.childNodes[h],j;try{j=cc(k)}catch(l){continue}var p=j.a;if(a.isCollapsed())if(T(k)){if(j.D(a))return rc(a,b,k)}else{if(a.r(p,1,1)==0){a.f=a.e=h;break}}else if(a.D(j)){if(!T(k)){d?a.f=h:a.e=h+1;break}return rc(a,b,k)}else if(a.r(p,1,0)<0&&a.r(p,0,1)>
0)return rc(a,b,k)}return c}function sc(a,b){var c=b==1,d=c?a.d():a.g();if(d.nodeType==1){for(var d=d.childNodes,e=d.length,f=c?1:-1,h=c?0:e-1;h>=0&&h<e;h+=f){var k=d[h];if(!T(k)&&a.a.compareEndPoints((b==1?"Start":"End")+"To"+(b==1?"Start":"End"),cc(k).a)==0)return c?h:h+1}return h==-1?0:h}else return e=a.a.duplicate(),f=pc(d),e.setEndPoint(c?"EndToEnd":"StartToStart",f),e=e.text.length,c?d.length-e:e}r.isCollapsed=function(){return this.a.compareEndPoints("StartToEnd",this.a)==0};r.select=function(){this.a.select()};
r.K=function(){if(this.a.htmlText){var a=this.d(),b=this.g(),c=this.a.text,d=this.a.duplicate();d.moveStart("character",1);d.moveStart("character",-1);if(d.text!=c){var e=new mc(a,!1,!0),f=[];Eb(e,function(a){a.nodeType!=3&&this.containsNode(a)&&(f.push(a),e.za());a==b&&g(M)});this.collapse(!0);Ba(f,K);this.p()}else{this.a=d;this.a.text="";this.p();c=this.d();d=this.h();try{var h=a.nextSibling;if(a==b&&a.parentNode&&a.nodeType==3&&h&&h.nodeType==3)a.nodeValue+=h.nodeValue,K(h),this.a=pc(c),this.a.move("character",
d),this.p()}catch(k){}}}};function tc(a,b,c){var d;d=d||gb(a.parentElement());var e;b.nodeType!=1&&(e=!0,b=d.pa("DIV",m,b));a.collapse(c);d=d||gb(a.parentElement());var f=c=b.id;if(!c)c=b.id="goog_"+qa++;a.pasteHTML(b.outerHTML);(b=u(c)?d.G.getElementById(c):c)&&(f||b.removeAttribute("id"));if(e){a=b.firstChild;e=b;if((d=e.parentNode)&&d.nodeType!=11)if(e.removeNode)e.removeNode(!1);else{for(;b=e.firstChild;)d.insertBefore(b,e);K(e)}b=a}return b}r.insertNode=function(a,b){var c=tc(this.a.duplicate(),
a,b);this.p();return c};r.$=function(a,b){var c=this.a.duplicate(),d=this.a.duplicate();tc(c,a,!0);tc(d,b,!1);this.p()};r.collapse=function(a){this.a.collapse(a);a?(this.b=this.c,this.e=this.f):(this.c=this.b,this.f=this.e)};function uc(a){this.a=a}y(uc,S);uc.prototype.ma=function(a){a.collapse(this.d(),this.h());(this.g()!=this.d()||this.k()!=this.h())&&a.extend(this.g(),this.k());a.rangeCount==0&&a.addRange(this.a)};function U(a){this.a=a}y(U,S);U.prototype.r=function(a,b,c){return I("528")?U.o.r.call(this,
a,b,c):this.a.compareBoundaryPoints(c==1?b==1?s.Range.START_TO_START:s.Range.END_TO_START:b==1?s.Range.START_TO_END:s.Range.END_TO_END,a)};U.prototype.ma=function(a,b){a.removeAllRanges();b?a.setBaseAndExtent(this.g(),this.k(),this.d(),this.h()):a.setBaseAndExtent(this.d(),this.h(),this.g(),this.k())};function vc(a){return F&&!I("9")?new nc(a,J(a.parentElement())):Ra?new U(a):H?new lc(a):Qa?new uc(a):new S(a)}function cc(a){if(F&&!I("9")){var b=new nc(pc(a),J(a));if(T(a)){for(var c,d=a;(c=d.firstChild)&&
T(c);)d=c;b.c=d;b.f=0;for(d=a;(c=d.lastChild)&&T(c);)d=c;b.b=d;b.e=d.nodeType==1?d.childNodes.length:d.length;b.w=a}else b.c=b.b=b.w=a.parentNode,b.f=D(b.w.childNodes,a),b.e=b.f+1;a=b}else a=Ra?new U(jc(a)):H?new lc(jc(a)):Qa?new uc(jc(a)):new S(jc(a));return a}function T(a){var b;a:if(a.nodeType!=1)b=!1;else{switch(a.tagName){case "APPLET":case "AREA":case "BASE":case "BR":case "COL":case "FRAME":case "HR":case "IMG":case "INPUT":case "IFRAME":case "ISINDEX":case "LINK":case "NOFRAMES":case "NOSCRIPT":case "META":case "OBJECT":case "PARAM":case "SCRIPT":case "STYLE":b=
!1;break a}b=!0}return b||a.nodeType==3}function wc(){}y(wc,Zb);function bc(a,b){var c=new wc;c.L=a;c.t=!!b;return c}function Yb(a,b,c,d){var e=new wc;e.t=xc(a,b,c,d);if(a.tagName=="BR")var f=a.parentNode,b=D(f.childNodes,a),a=f;if(c.tagName=="BR")f=c.parentNode,d=D(f.childNodes,c),c=f;e.t?(e.c=c,e.f=d,e.b=a,e.e=b):(e.c=a,e.f=b,e.b=c,e.e=d);return e}r=wc.prototype;r.L=m;r.c=m;r.f=m;r.b=m;r.e=m;r.t=!1;r.z=function(){var a=new wc;a.L=this.L;a.c=this.c;a.f=this.f;a.b=this.b;a.e=this.e;a.t=this.t;return a};
r.ta=o("text");r.C=function(){return V(this).a};r.p=function(){this.c=this.f=this.b=this.e=m};r.Q=o(1);r.H=function(){return this};function V(a){var q;var b;if(!(b=a.L)){b=a.d();var c=a.h(),d=a.g(),e=a.k();if(F&&!I("9")){var f=b,h=c,k=d,j=e,l=!1;f.nodeType==1&&(h>f.childNodes.length&&oc.log(Mb,"Cannot have startOffset > startNode child count",i),h=f.childNodes[h],l=!h,f=h||f.lastChild||f,h=0);var p=pc(f);h&&p.move("character",h);f==k&&h==j?p.collapse(!0):(l&&p.collapse(!1),l=!1,k.nodeType==1&&(j>
k.childNodes.length&&oc.log(Mb,"Cannot have endOffset > endNode child count",i),q=(h=k.childNodes[j])||k.lastChild||k,k=q,j=0,l=!h),f=pc(k),f.collapse(!l),j&&f.moveEnd("character",j),p.setEndPoint("EndToEnd",f));j=new nc(p,J(b));j.c=b;j.f=c;j.b=d;j.e=e;b=j}else b=Ra?new U(kc(b,c,d,e)):H?new lc(kc(b,c,d,e)):Qa?new uc(kc(b,c,d,e)):new S(kc(b,c,d,e));b=a.L=b}return b}r.v=function(){return V(this).v()};r.d=function(){return this.c||(this.c=V(this).d())};r.h=function(){return this.f!=m?this.f:this.f=V(this).h()};
r.g=function(){return this.b||(this.b=V(this).g())};r.k=function(){return this.e!=m?this.e:this.e=V(this).k()};r.R=n("t");r.D=function(a,b){var c=a.ta();if(c=="text")return V(this).D(V(a),b);else if(c=="control")return c=yc(a),(b?Da:Ea)(c,function(a){return this.containsNode(a,b)},this);return!1};r.isCollapsed=function(){return V(this).isCollapsed()};r.N=function(){return new R(this.d(),this.h(),this.g(),this.k())};r.select=function(){V(this).select(this.t)};r.K=function(){V(this).K();this.p()};r.insertNode=
function(a,b){var c=V(this).insertNode(a,b);this.p();return c};r.$=function(a,b){V(this).$(a,b);this.p()};r.xa=function(){return new zc(this)};r.collapse=function(a){a=this.R()?!a:a;this.L&&this.L.collapse(a);a?(this.b=this.c,this.e=this.f):(this.c=this.b,this.f=this.e);this.t=!1};function zc(a){this.Ca=a.R()?a.g():a.d();this.gb=a.R()?a.k():a.h();this.Ha=a.R()?a.d():a.g();this.jb=a.R()?a.h():a.k()}y(zc,Tb);zc.prototype.la=function(){return Yb(this.Ca,this.gb,this.Ha,this.jb)};zc.prototype.q=function(){zc.o.q.call(this);
this.Ha=this.Ca=m};function Ac(){}y(Ac,fc);function Bc(a){var b=new Ac;b.a=a;return b}function Cc(a){for(var b=J(arguments[0]).body.createControlRange(),c=0,d=arguments.length;c<d;c++)b.addElement(arguments[c]);return Bc(b)}r=Ac.prototype;r.a=m;r.j=m;r.Z=m;r.p=function(){this.Z=this.j=m};r.z=function(){return Cc.apply(this,yc(this))};r.ta=o("control");r.C=function(){return this.a||document.body.createControlRange()};r.Q=function(){return this.a?this.a.length:0};r.H=function(a){a=this.a.item(a);return bc(cc(a),
i)};r.v=function(){return wb.apply(m,yc(this))};r.d=function(){return Dc(this)[0]};r.h=o(0);r.g=function(){var a=Dc(this),b=Aa(a);return Fa(a,function(a){return L(a,b)})};r.k=function(){return this.g().childNodes.length};function yc(a){if(!a.j&&(a.j=[],a.a))for(var b=0;b<a.a.length;b++)a.j.push(a.a.item(b));return a.j}function Dc(a){if(!a.Z)a.Z=yc(a).concat(),a.Z.sort(function(a,c){return a.sourceIndex-c.sourceIndex});return a.Z}r.isCollapsed=function(){return!this.a||!this.a.length};r.N=function(){return new Ec(this)};
r.select=function(){this.a&&this.a.select()};r.K=function(){if(this.a){for(var a=[],b=0,c=this.a.length;b<c;b++)a.push(this.a.item(b));Ba(a,K);this.collapse(!1)}};r.wa=function(a){a=this.insertNode(a,!0);this.isCollapsed()||this.K();return a};r.xa=function(){return new Fc(this)};r.collapse=function(){this.a=m;this.p()};function Fc(a){this.j=yc(a)}y(Fc,Tb);Fc.prototype.la=function(){for(var a=(this.j.length?J(this.j[0]):document).body.createControlRange(),b=0,c=this.j.length;b<c;b++)a.addElement(this.j[b]);
return Bc(a)};Fc.prototype.q=function(){Fc.o.q.call(this);delete this.j};function Ec(a){if(a)this.j=Dc(a),this.c=this.j.shift(),this.b=Aa(this.j)||this.c;Q.call(this,this.c,!1)}y(Ec,Q);r=Ec.prototype;r.c=m;r.b=m;r.j=m;r.d=n("c");r.g=n("b");r.W=function(){return!this.depth&&!this.j.length};r.next=function(){if(this.W())g(M);else if(!this.depth){var a=this.j.shift();P(this,a,1,1);return a}return Ec.o.next.call(this)};r.A=function(a){this.j=a.j;this.c=a.c;this.b=a.b;Ec.o.A.call(this,a)};r.z=function(){var a=
new Ec(m);a.A(this);return a};function Gc(){this.s=[];this.S=[];this.ca=this.V=m}y(Gc,fc);function Hc(a){var b=new Gc;b.S=a;b.s=Ca(a,function(a){return a.C()});return b}r=Gc.prototype;r.ob=Sb("goog.dom.MultiRange");r.p=function(){this.S=[];this.ca=this.V=m};r.z=function(){var a=new Gc;a.s=Ha(this.s);return a};r.ta=o("mutli");r.C=function(){this.s.length>1&&this.ob.log(Nb,"getBrowserRangeObject called on MultiRange with more than 1 range",i);return this.s[0]};r.Q=function(){return this.s.length};r.H=
function(a){this.S[a]||(this.S[a]=bc(vc(this.s[a]),i));return this.S[a]};r.v=function(){if(!this.ca){for(var a=[],b=0,c=this.Q();b<c;b++)a.push(this.H(b).v());this.ca=wb.apply(m,a)}return this.ca};function Ic(a){if(!a.V)a.V=ac(a),a.V.sort(function(a,c){var d=a.d(),e=a.h(),f=c.d(),h=c.h();return d==f&&e==h?0:xc(d,e,f,h)?1:-1});return a.V}r.d=function(){return Ic(this)[0].d()};r.h=function(){return Ic(this)[0].h()};r.g=function(){return Aa(Ic(this)).g()};r.k=function(){return Aa(Ic(this)).k()};r.isCollapsed=
function(){return this.s.length==0||this.s.length==1&&this.H(0).isCollapsed()};r.N=function(){return new Jc(this)};r.select=function(){var a=$b(this.Ia());a.removeAllRanges();for(var b=0,c=this.Q();b<c;b++)a.addRange(this.H(b).C())};r.K=function(){Ba(ac(this),function(a){a.K()})};r.xa=function(){return new Kc(this)};r.collapse=function(a){if(!this.isCollapsed()){var b=a?this.H(0):this.H(this.Q()-1);this.p();b.collapse(a);this.S=[b];this.V=[b];this.s=[b.C()]}};function Kc(a){this.ya=Ca(ac(a),function(a){return a.xa()})}
y(Kc,Tb);Kc.prototype.la=function(){var a=Ca(this.ya,function(a){return a.restore()});return Hc(a)};Kc.prototype.q=function(){Kc.o.q.call(this);Ba(this.ya,function(a){a.P()});delete this.ya};function Jc(a){if(a)this.J=Ca(Ic(a),function(a){return Db(a)});Q.call(this,a?this.d():m,!1)}y(Jc,Q);r=Jc.prototype;r.J=m;r.da=0;r.d=function(){return this.J[0].d()};r.g=function(){return Aa(this.J).g()};r.W=function(){return this.J[this.da].W()};r.next=function(){try{var a=this.J[this.da],b=a.next();P(this,a.i,
a.n,a.depth);return b}catch(c){if(c!==M||this.J.length-1==this.da)g(c);else return this.da++,this.next()}};r.A=function(a){this.J=Ha(a.J);Jc.o.A.call(this,a)};r.z=function(){var a=new Jc(m);a.A(this);return a};function ec(a){return(a=$b(a||window))&&Lc(a)}function Lc(a){var b,c=!1;if(a.createRange)try{b=a.createRange()}catch(d){return m}else if(a.rangeCount)if(a.rangeCount>1){b=new Gc;for(var c=0,e=a.rangeCount;c<e;c++)b.s.push(a.getRangeAt(c));return b}else b=a.getRangeAt(0),c=xc(a.anchorNode,a.anchorOffset,
a.focusNode,a.focusOffset);else return m;return b&&b.addElement?Bc(b):bc(vc(b),c)}function xc(a,b,c,d){if(a==c)return d<b;var e;if(a.nodeType==1&&b)if(e=a.childNodes[b])a=e,b=0;else if(L(a,c))return!0;if(c.nodeType==1&&d)if(e=c.childNodes[d])c=e,d=0;else if(L(c,a))return!1;return(tb(a,c)||b-d)>0}var Mc;!F||I("9");var Nc=F&&!I("8");function W(a,b){this.type=a;this.currentTarget=this.target=b}y(W,Bb);W.prototype.q=function(){delete this.type;delete this.target;delete this.currentTarget};W.prototype.va=
!1;W.prototype.Za=!0;W.prototype.preventDefault=function(){this.Za=!1};var Oc=new Function("a","return a");function Pc(a,b){a&&this.ha(a,b)}y(Pc,W);r=Pc.prototype;r.target=m;r.relatedTarget=m;r.offsetX=0;r.offsetY=0;r.clientX=0;r.clientY=0;r.screenX=0;r.screenY=0;r.button=0;r.keyCode=0;r.charCode=0;r.ctrlKey=!1;r.altKey=!1;r.shiftKey=!1;r.metaKey=!1;r.tb=!1;r.ra=m;r.ha=function(a,b){var c=this.type=a.type;W.call(this,c);this.target=a.target||a.srcElement;this.currentTarget=b;var d=a.relatedTarget;
if(d){if(H)try{Oc(d.nodeName)}catch(e){d=m}}else if(c=="mouseover")d=a.fromElement;else if(c=="mouseout")d=a.toElement;this.relatedTarget=d;this.offsetX=a.offsetX!==i?a.offsetX:a.layerX;this.offsetY=a.offsetY!==i?a.offsetY:a.layerY;this.clientX=a.clientX!==i?a.clientX:a.pageX;this.clientY=a.clientY!==i?a.clientY:a.pageY;this.screenX=a.screenX||0;this.screenY=a.screenY||0;this.button=a.button;this.keyCode=a.keyCode||0;this.charCode=a.charCode||(c=="keypress"?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=
a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.tb=Ta?a.metaKey:a.ctrlKey;this.state=a.state;this.ra=a;delete this.Za;delete this.va};r.preventDefault=function(){Pc.o.preventDefault.call(this);var a=this.ra;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,Nc)try{if(a.ctrlKey||a.keyCode>=112&&a.keyCode<=123)a.keyCode=-1}catch(b){}};r.q=function(){Pc.o.q.call(this);this.relatedTarget=this.currentTarget=this.target=this.ra=m};function Qc(){}var Rc=0;r=Qc.prototype;r.key=
0;r.U=!1;r.Da=!1;r.ha=function(a,b,c,d,e,f){v(a)?this.Ma=!0:a&&a.handleEvent&&v(a.handleEvent)?this.Ma=!1:g(Error("Invalid listener argument"));this.ia=a;this.Xa=b;this.src=c;this.type=d;this.capture=!!e;this.Ja=f;this.Da=!1;this.key=++Rc;this.U=!1};r.handleEvent=function(a){return this.Ma?this.ia.call(this.Ja||this.src,a):this.ia.handleEvent.call(this.ia,a)};function X(a,b){this.Na=b;this.M=[];a>this.Na&&g(Error("[goog.structs.SimplePool] Initial cannot be greater than max"));for(var c=0;c<a;c++)this.M.push(this.B?
this.B():{})}y(X,Bb);X.prototype.B=m;X.prototype.Ea=m;X.prototype.getObject=function(){return this.M.length?this.M.pop():this.B?this.B():{}};function Sc(a,b){a.M.length<a.Na?a.M.push(b):Tc(a,b)}function Tc(a,b){if(a.Ea)a.Ea(b);else if(da(b))if(v(b.P))b.P();else for(var c in b)delete b[c]}X.prototype.q=function(){X.o.q.call(this);for(var a=this.M;a.length;)Tc(this,a.pop());delete this.M};var Uc,Vc,Wc,Xc,Yc,Zc,$c,ad,bd,cd,dd;(function(){function a(){return{F:0,T:0}}function b(){return[]}function c(){function a(b){return h.call(a.src,
a.key,b)}return a}function d(){return new Qc}function e(){return new Pc}var f=gc&&!(oa(hc,"5.7")>=0),h;Zc=function(a){h=a};if(f){Uc=function(){return k.getObject()};Vc=function(a){Sc(k,a)};Wc=function(){return j.getObject()};Xc=function(a){Sc(j,a)};Yc=function(){return l.getObject()};$c=function(){Sc(l,c())};ad=function(){return p.getObject()};bd=function(a){Sc(p,a)};cd=function(){return q.getObject()};dd=function(a){Sc(q,a)};var k=new X(0,600);k.B=a;var j=new X(0,600);j.B=b;var l=new X(0,600);l.B=
c;var p=new X(0,600);p.B=d;var q=new X(0,600);q.B=e}else Uc=a,Vc=ba,Wc=b,Xc=ba,Yc=c,$c=ba,ad=d,bd=ba,cd=e,dd=ba})();var ed={},Y={},fd={},gd={};function hd(a,b,c,d,e){if(b)if(t(b)=="array")for(var f=0;f<b.length;f++)hd(a,b[f],c,d,e);else{var d=!!d,h=Y;b in h||(h[b]=Uc());h=h[b];d in h||(h[d]=Uc(),h.F++);var h=h[d],k=a[ea]||(a[ea]=++fa),j;h.T++;if(h[k]){j=h[k];for(f=0;f<j.length;f++)if(h=j[f],h.ia==c&&h.Ja==e){if(h.U)break;return}}else j=h[k]=Wc(),h.F++;f=Yc();f.src=a;h=ad();h.ha(c,f,a,b,d,e);c=h.key;
f.key=c;j.push(h);ed[c]=h;fd[k]||(fd[k]=Wc());fd[k].push(h);a.addEventListener?(a==s||!a.hb)&&a.addEventListener(b,f,d):a.attachEvent(b in gd?gd[b]:gd[b]="on"+b,f)}else g(Error("Invalid event type"))}function id(a,b,c,d){if(!d.ja&&d.Oa){for(var e=0,f=0;e<d.length;e++)if(d[e].U){var h=d[e].Xa;h.src=m;$c(h);bd(d[e])}else e!=f&&(d[f]=d[e]),f++;d.length=f;d.Oa=!1;f==0&&(Xc(d),delete Y[a][b][c],Y[a][b].F--,Y[a][b].F==0&&(Vc(Y[a][b]),delete Y[a][b],Y[a].F--),Y[a].F==0&&(Vc(Y[a]),delete Y[a]))}}function jd(a,
b,c,d,e){var f=1,b=b[ea]||(b[ea]=++fa);if(a[b]){a.T--;a=a[b];a.ja?a.ja++:a.ja=1;try{for(var h=a.length,k=0;k<h;k++){var j=a[k];j&&!j.U&&(f&=kd(j,e)!==!1)}}finally{a.ja--,id(c,d,b,a)}}return Boolean(f)}function kd(a,b){var c=a.handleEvent(b);if(a.Da){var d=a.key;if(ed[d]){var e=ed[d];if(!e.U){var f=e.src,h=e.type,k=e.Xa,j=e.capture;f.removeEventListener?(f==s||!f.hb)&&f.removeEventListener(h,k,j):f.detachEvent&&f.detachEvent(h in gd?gd[h]:gd[h]="on"+h,k);f=f[ea]||(f[ea]=++fa);k=Y[h][j][f];if(fd[f]){var l=
fd[f],p=D(l,e);p>=0&&C.splice.call(l,p,1);l.length==0&&delete fd[f]}e.U=!0;k.Oa=!0;id(h,j,f,k);delete ed[d]}}}return c}Zc(function(a,b){if(!ed[a])return!0;var c=ed[a],d=c.type,e=Y;if(!(d in e))return!0;var e=e[d],f,h;Mc===i&&(Mc=F&&!s.addEventListener);if(Mc){f=b||aa("window.event");var k=!0 in e,j=!1 in e;if(k){if(f.keyCode<0||f.returnValue!=i)return!0;a:{var l=!1;if(f.keyCode==0)try{f.keyCode=-1;break a}catch(p){l=!0}if(l||f.returnValue==i)f.returnValue=!0}}l=cd();l.ha(f,this);f=!0;try{if(k){for(var q=
Wc(),E=l.currentTarget;E;E=E.parentNode)q.push(E);h=e[!0];h.T=h.F;for(var G=q.length-1;!l.va&&G>=0&&h.T;G--)l.currentTarget=q[G],f&=jd(h,q[G],d,!0,l);if(j){h=e[!1];h.T=h.F;for(G=0;!l.va&&G<q.length&&h.T;G++)l.currentTarget=q[G],f&=jd(h,q[G],d,!1,l)}}else f=kd(c,l)}finally{if(q)q.length=0,Xc(q);l.P();dd(l)}return f}d=new Pc(b,this);try{f=kd(c,d)}finally{d.P()}return f});function x(a){a||g(Error("Editor area element does not exist."));this.eb=!1;this.l=a;this.aa="text";this.ub=0;this.Wa=[];this.Va=
[]}r=x.prototype;r.kb=n("l");r.load=function(a,b){var b=b||window.document,c=new va(ld(a).firstChild,!1),d=b.createDocumentFragment(),e=m,f=d;c.Qa=function(a){var c=B[a.type];if(!c)return!1;var d=b.createElement("li");z(d,"type",a.type);a.list&&z(d,"list",a.list);a=v(c.bb)?c.bb(a):b.createElement(c.tagName);c=b.createElement("ul");d.appendChild(a);d.appendChild(c);f.appendChild(d);e=a;f=c};c.Pa=function(){var a=f.parentNode.parentNode;f.childNodes.length===0&&K(f);e=m;f=a||d};c.Sa=function(a){a=B[a.type];
if(!a)return!1;var c=b.createElement(a.tagName);if(a.className)c.className=a.className;e.appendChild(c);e=c};c.Ra=function(){e=e.parentNode};c.Ta=function(a){e.appendChild(b.createTextNode(a))};wa(c,c.list.childNodes);this.l.innerHTML="";this.l.appendChild(d)};function ld(a){var b;typeof DOMParser!=="undefined"?b=(new DOMParser).parseFromString(a,"text/xml"):(b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a));return b}r.mb=function(a,b){var c=this;md(this,function(){var d=new va(c.l,
!0),e='<?xml version="1.0" encoding="utf-8"?>';e+="\n<root>";var f=1;d.Qa=function(a){var d=B[a.type],j=A(a.i,"plugin");if(j)a.ua=ua[j];if(j=A(a.i,"plugin_id"))a.vb=c.Va[Number(j)];e+=b?"\n"+Array(f+1).join("  "):"";d.cb?e+=d.cb(a)||"":(e+="<"+a.type,a.list&&(e+=' list="'+a.list+'"'),e+=">");f+=1};d.Ta=function(a){e+="<![CDATA["+a+"]]\>"};d.Sa=function(a){e+="<"+a.type+">"};d.Ra=function(a){e+="</"+a.type+">"};d.Pa=function(a){f-=1;e+="</"+a.type+">"};wa(d,d.list.childNodes);e+=b?"\n":"";e+="</root>\n";
a(e)})};function md(a,b){var c=a.Va,d=a.Wa,e=d.length;(function h(a){if(a<e){var j=d[a];j?v(j.getState)&&(c[a]=j.getState(function(b){c[a]=b;h(++a)}),c[a]&&h(++a)):h(++a)}else b()})(0)}r.yb=function(a){var b=Z(this);if(b.length){var c=ec(),d=c.d(),e=c.g(),f=c.k(),h=!1;b.some(function(b){var b=b.firstChild,j=c.z(),l=j.C();if(h)if(l.setStart(b,0),L(b,e))return l.setEnd(e,f),nd(j,a),!0;else l.setEnd(b,b.childNodes.length),nd(j,a);else if(L(b,d)){if(L(b,e))return nd(j,a),!0;h=!0;l.setEnd(b,b.childNodes.length);
nd(j,a)}},this)}};function nd(a,b){var c=B[b];if(!a.isCollapsed()){var d=a.v(),e=a.C().cloneContents();if(d.nodeType===d.TEXT_NODE&&(d=d.parentNode,d.tagName===c.tagName&&(d.className||m)===(c.className||m)))e=document.createDocumentFragment(),e.appendChild(d);d=Array.prototype.slice.call(ib(c.tagName,c.className,e));if(d.length){for(var f=0;c=d[f];++f){for(;c.firstChild;)c.parentNode.insertBefore(c.firstChild,c);c.parentNode.removeChild(c)}a.wa(e)}else{d=mb(c.tagName);if(c.className)d.className=
c.className;d.appendChild(e);a.wa(d)}}}r.xb=function(a){var b=B[a],c=dc();Z(this).forEach(function(c){var e=c.firstChild,f=mb(b.tagName,m);bc(cc(e),i).C();z(c,"type",a);qb(f,e.childNodes);rb(f,e);K(e)});this.aa=a;c.restore()};r.ab=function(a,b){var c=dc();Z(this).forEach(function(c){var e=A(c,"list");if(!b||!e)a===m?c.dataset?delete c.dataset.list:c.removeAttribute("data-"+sa("list")):z(c,"list",a),c.className+=" a",c.className=""});c.restore()};r.setActive=function(a){if(a){if(!this.l.innerHTML)this.l.innerHTML=
"",this.zb="text",this.O(this.aa);hd(this.l,"keydown",this.rb,!1,this);hd(this.l,"keyup",this.sb,!1,this)}jb(this.l,{contentEditable:a});this.eb=a};r.O=function(a,b){var c;if(!(c=a))c=B[this.aa],c=c.Y?c.Y:this.aa;var a=c,d=B[a];c=mb("li");d=mb(d.tagName);c.appendChild(d);z(c,"type",a);var e=Z(this)[0];if(e){var f=A(e,"list");f&&c.setAttribute("data-list",f);f=e.firstChild;if(f.lastChild){var h=ec().C();h.setEnd(f,f.childNodes.length);f=h.extractContents();d.appendChild(f)}sb(c,e)}else this.l.appendChild(c);
b||Yb(d,0,d,0).select();return c};r.fb=function(a,b,c){a=this.O(a,!0);a.setAttribute("contenteditable",!1);b&&z(a,"plugin",b);c&&(b=this.ub++,this.Wa[b]=c,z(a,"plugin_id",String(b)));od(this);return a};r.La=function(){var a=dc();Z(this).forEach(function(a){var c=a.previousSibling;if(c){var d=c.lastChild;d.tagName!=="UL"&&(d=mb("ul"),d.setAttribute("contenteditable",!0),c.appendChild(d));d.appendChild(a)}});a.restore()};r.Ua=function(){var a=dc(),b=this;Z(this).forEach(function(a){var d=a.parentNode;
d!==b.l&&(sb(a,d.parentNode),d.childNodes.length===0&&K(d))});a.restore()};function pd(a){var b=dc();Z(a).forEach(function(a){var b=a.previousSibling;b&&rb(a,b)});b.restore()}function qd(a){var b=dc();Z(a).forEach(function(a){var b=a.nextSibling;b&&sb(a,b)});b.restore()}function Z(a){var b=ec();return b===m?[]:rd(a,b)}function rd(a,b){var c=b.v();if(!L(a.l,c))return[];if(c===a.l&&a.l.childNodes.length===0)return[];if(c.tagName==="UL"){var d=[],c=c.getElementsByTagName("LI"),e=!1,f=b.d(),h=b.g();Array.prototype.some.call(c,
function(a){if(e)return d.push(a),L(a,h);else L(a,f)&&(e=!0,d.push(a))});return d}do{if(c.tagName==="LI")return[c];c=c.parentNode}while(c!==a.l);return[]}r.rb=function(a){switch(a.keyCode){case 13:a.preventDefault();this.O();break;case 9:a.preventDefault();a.shiftKey?this.Ua():this.La();break;case 8:var b=Z(this)[0],c=ec();c.isCollapsed()&&c.d().parentNode===b.firstChild&&c.h()===0&&A(b,"list")&&(this.ab(m),a.preventDefault());break;case 38:if(a.ctrlKey&&a.metaKey||a.ctrlKey&&a.shiftKey)pd(this),
a.preventDefault();break;case 40:if(a.ctrlKey&&a.metaKey||a.ctrlKey&&a.shiftKey)qd(this),a.preventDefault()}};r.sb=function(a){od(this);switch(a.keyCode){case 8:case 46:for(var a=ib("span","Apple-style-span",this.l),b=a.length,c,d;c=a[--b];){for(var e=c.childNodes.length;d=c.childNodes[--e];)rb(d,c);K(c)}}};function od(a){var b=a.l;if(!b.lastChild||b.lastChild.nodeType!==b.ELEMENT_NODE){for(var a=a.O("text").firstChild,c=0;b.firstChild&&b.firstChild.nodeType!==b.ELEMENT_NODE;++c)a.insertBefore(b.firstChild,
a.childNodes[c]||m);c&&Yb(a,c,a,c).select()}else A(b.lastChild,"type")!=="text"&&(a=a.O("text",!0),b.appendChild(a))}var sd=x,td="takeNote.Editor".split("."),$=s;!(td[0]in $)&&$.execScript&&$.execScript("var "+td[0]);for(var ud;td.length&&(ud=td.shift());)!td.length&&sd!==i?$[ud]=sd:$=$[ud]?$[ud]:$[ud]={};w("getArea",x.prototype.kb);w("setActive",x.prototype.setActive);w("load",x.prototype.load);w("getXML",x.prototype.mb);w("addBlock",x.prototype.O);w("addStandaloneBlock",x.prototype.fb);w("setInlineType",
x.prototype.yb);w("setBlockType",x.prototype.xb);w("setListType",x.prototype.ab);w("indentCurrentBlock",x.prototype.La);w("outdentCurrentBlock",x.prototype.Ua)})(window,document);function i(a){throw a;}var k=void 0,n=null,o,p=this;function q(){}
function r(a){var c=typeof a;if(c=="object")if(a){if(a instanceof Array)return"array";else if(a instanceof Object)return c;var b=Object.prototype.toString.call(a);if(b=="[object Window]")return"object";if(b=="[object Array]"||typeof a.length=="number"&&typeof a.splice!="undefined"&&typeof a.propertyIsEnumerable!="undefined"&&!a.propertyIsEnumerable("splice"))return"array";if(b=="[object Function]"||typeof a.call!="undefined"&&typeof a.propertyIsEnumerable!="undefined"&&!a.propertyIsEnumerable("call"))return"function"}else return"null";
else if(c=="function"&&typeof a.call=="undefined")return"object";return c}function aa(a){var c=r(a);return c=="array"||c=="object"&&typeof a.length=="number"}function s(a){return typeof a=="string"}function ba(a){return r(a)=="function"}function ca(a){a=r(a);return a=="object"||a=="array"||a=="function"}var t="closure_uid_"+Math.floor(Math.random()*2147483648).toString(36),da=0,ea=Date.now||function(){return+new Date};function v(a,c){x.prototype[a]=c}
function fa(a,c){function b(){}b.prototype=c.prototype;a.ka=c.prototype;a.prototype=new b}function ga(a){if(!ha.test(a))return a;a.indexOf("&")!=-1&&(a=a.replace(ia,"&amp;"));a.indexOf("<")!=-1&&(a=a.replace(ja,"&lt;"));a.indexOf(">")!=-1&&(a=a.replace(ka,"&gt;"));a.indexOf('"')!=-1&&(a=a.replace(la,"&quot;"));return a}var ia=/&/g,ja=/</g,ka=/>/g,la=/\"/g,ha=/[&<>\"]/;
function ma(a,c){for(var b=0,d=String(a).replace(/^[\s\xa0]+|[\s\xa0]+$/g,"").split("."),e=String(c).replace(/^[\s\xa0]+|[\s\xa0]+$/g,"").split("."),f=Math.max(d.length,e.length),g=0;b==0&&g<f;g++){var h=d[g]||"",j=e[g]||"",l=RegExp("(\\d*)(\\D*)","g"),A=RegExp("(\\d*)(\\D*)","g");do{var m=l.exec(h)||["","",""],w=A.exec(j)||["","",""];if(m[0].length==0&&w[0].length==0)break;b=na(m[1].length==0?0:parseInt(m[1],10),w[1].length==0?0:parseInt(w[1],10))||na(m[2].length==0,w[2].length==0)||na(m[2],w[2])}while(b==
0)}return b}function na(a,c){if(a<c)return-1;else if(a>c)return 1;return 0}var oa={};function pa(a){return oa[a]||(oa[a]=String(a).replace(/([A-Z])/g,"-$1").toLowerCase())}
var y=Array.prototype,z=y.indexOf?function(a,c,b){return y.indexOf.call(a,c,b)}:function(a,c,b){b=b==n?0:b<0?Math.max(0,a.length+b):b;if(s(a))return!s(c)||c.length!=1?-1:a.indexOf(c,b);for(;b<a.length;b++)if(b in a&&a[b]===c)return b;return-1},qa=y.forEach?function(a,c,b){y.forEach.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=s(a)?a.split(""):a,f=0;f<d;f++)f in e&&c.call(b,e[f],f,a)};function ra(a){return y.concat.apply(y,arguments)}
function sa(a){if(r(a)=="array")return ra(a);else{for(var c=[],b=0,d=a.length;b<d;b++)c[b]=a[b];return c}}function ta(a,c,b,d){y.splice.apply(a,ua(arguments,1))}function ua(a,c,b){return arguments.length<=2?y.slice.call(a,c):y.slice.call(a,c,b)}var B,va,wa,xa;function ya(){return p.navigator?p.navigator.userAgent:n}xa=wa=va=B=!1;var za;if(za=ya()){var Aa=p.navigator;B=za.indexOf("Opera")==0;va=!B&&za.indexOf("MSIE")!=-1;wa=!B&&za.indexOf("WebKit")!=-1;xa=!B&&!wa&&Aa.product=="Gecko"}
var C=va,Ba=xa,Ca=wa,Da=p.navigator,Ea=(Da&&Da.platform||"").indexOf("Mac")!=-1,Fa;a:{var Ga="",D;if(B&&p.opera)var Ha=p.opera.version,Ga=typeof Ha=="function"?Ha():Ha;else if(Ba?D=/rv\:([^\);]+)(\)|;)/:C?D=/MSIE\s+([^\);]+)(\)|;)/:Ca&&(D=/WebKit\/(\S+)/),D)var Ia=D.exec(ya()),Ga=Ia?Ia[1]:"";if(C){var Ja,Ka=p.document;Ja=Ka?Ka.documentMode:k;if(Ja>parseFloat(Ga)){Fa=String(Ja);break a}}Fa=Ga}var La={};function E(a){return La[a]||(La[a]=ma(Fa,a)>=0)}var Ma=!C||E("9");!Ba&&!C||C&&E("9")||Ba&&E("1.9.1");
C&&E("9");function Na(a){return(a=a.className)&&typeof a.split=="function"?a.split(/\s+/):[]}function F(a,c){var b=Na(a),d=ua(arguments,1),e;e=b;for(var f=0,g=0;g<d.length;g++)z(e,d[g])>=0||(e.push(d[g]),f++);e=f==d.length;a.className=b.join(" ");return e}function G(a,c){for(var b=Na(a),d=ua(arguments,1),e=b,f=0,g=0;g<e.length;g++)z(d,e[g])>=0&&(ta(e,g--,1),f++);a.className=b.join(" ")}function Oa(a,c){for(var b in a)c.call(k,a[b],b,a)}var Pa="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");
function Qa(a,c){for(var b,d,e=1;e<arguments.length;e++){d=arguments[e];for(b in d)a[b]=d[b];for(var f=0;f<Pa.length;f++)b=Pa[f],Object.prototype.hasOwnProperty.call(d,b)&&(a[b]=d[b])}}function Ra(a,c){Oa(c,function(b,c){c=="style"?a.style.cssText=b:c=="class"?a.className=b:c=="for"?a.htmlFor=b:c in Sa?a.setAttribute(Sa[c],b):a[c]=b})}
var Sa={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",rowspan:"rowSpan",valign:"vAlign",height:"height",width:"width",usemap:"useMap",frameborder:"frameBorder",maxlength:"maxLength",type:"type"};
function H(a,c,b){var d=arguments,e=document,f=d[0],g=d[1];if(!Ma&&g&&(g.name||g.type)){f=["<",f];g.name&&f.push(' name="',ga(g.name),'"');if(g.type){f.push(' type="',ga(g.type),'"');var h={};Qa(h,g);g=h;delete g.type}f.push(">");f=f.join("")}f=e.createElement(f);if(g)s(g)?f.className=g:r(g)=="array"?F.apply(n,[f].concat(g)):Ra(f,g);d.length>2&&Ta(e,f,d);return f}
function Ta(a,c,b){function d(b){b&&c.appendChild(s(b)?a.createTextNode(b):b)}for(var e=2;e<b.length;e++){var f=b[e];aa(f)&&!(ca(f)&&f.nodeType>0)?qa(Ua(f)?sa(f):f,d):d(f)}}function Va(a,c){a.insertBefore(c,a.childNodes[0]||n)}function Wa(a){a&&a.parentNode&&a.parentNode.removeChild(a)}function Ua(a){if(a&&typeof a.length=="number")if(ca(a))return typeof a.item=="function"||typeof a.item=="string";else if(ba(a))return typeof a.item=="function";return!1}
function I(a,c,b){a.dataset?a.dataset[c]=b:a.setAttribute("data-"+pa(c),b)}function J(a,c){return a.dataset?a.dataset[c]:a.getAttribute("data-"+pa(c))}var Xa;!C||E("9");var Ya=C&&!E("8");function K(){}K.prototype.Ba=!1;K.prototype.T=function(){if(!this.Ba)this.Ba=!0,this.C()};K.prototype.C=function(){};function L(a,c){this.type=a;this.currentTarget=this.target=c}fa(L,K);L.prototype.C=function(){delete this.type;delete this.target;delete this.currentTarget};L.prototype.ja=!1;L.prototype.Ma=!0;
L.prototype.preventDefault=function(){this.Ma=!1};var Za=new Function("a","return a");function M(a,c){a&&this.w(a,c)}fa(M,L);o=M.prototype;o.target=n;o.relatedTarget=n;o.offsetX=0;o.offsetY=0;o.clientX=0;o.clientY=0;o.screenX=0;o.screenY=0;o.button=0;o.keyCode=0;o.charCode=0;o.ctrlKey=!1;o.altKey=!1;o.shiftKey=!1;o.metaKey=!1;o.ib=!1;o.ea=n;
o.w=function(a,c){var b=this.type=a.type;L.call(this,b);this.target=a.target||a.srcElement;this.currentTarget=c;var d=a.relatedTarget;if(d){if(Ba)try{Za(d.nodeName)}catch(e){d=n}}else if(b=="mouseover")d=a.fromElement;else if(b=="mouseout")d=a.toElement;this.relatedTarget=d;this.offsetX=a.offsetX!==k?a.offsetX:a.layerX;this.offsetY=a.offsetY!==k?a.offsetY:a.layerY;this.clientX=a.clientX!==k?a.clientX:a.pageX;this.clientY=a.clientY!==k?a.clientY:a.pageY;this.screenX=a.screenX||0;this.screenY=a.screenY||
0;this.button=a.button;this.keyCode=a.keyCode||0;this.charCode=a.charCode||(b=="keypress"?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.ib=Ea?a.metaKey:a.ctrlKey;this.state=a.state;this.ea=a;delete this.Ma;delete this.ja};o.preventDefault=function(){M.ka.preventDefault.call(this);var a=this.ea;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,Ya)try{if(a.ctrlKey||a.keyCode>=112&&a.keyCode<=123)a.keyCode=-1}catch(c){}};
o.C=function(){M.ka.C.call(this);this.relatedTarget=this.currentTarget=this.target=this.ea=n};function $a(){}var ab=0;o=$a.prototype;o.key=0;o.G=!1;o.wa=!1;o.w=function(a,c,b,d,e,f){ba(a)?this.Ga=!0:a&&a.handleEvent&&ba(a.handleEvent)?this.Ga=!1:i(Error("Invalid listener argument"));this.U=a;this.La=c;this.src=b;this.type=d;this.capture=!!e;this.Fa=f;this.wa=!1;this.key=++ab;this.G=!1};o.handleEvent=function(a){return this.Ga?this.U.call(this.Fa||this.src,a):this.U.handleEvent.call(this.U,a)};
function N(a,c){this.Ja=c;this.v=[];a>this.Ja&&i(Error("[goog.structs.SimplePool] Initial cannot be greater than max"));for(var b=0;b<a;b++)this.v.push(this.L())}fa(N,K);o=N.prototype;o.u=n;o.Aa=n;o.getObject=function(){return this.v.length?this.v.pop():this.L()};function O(a,c){a.v.length<a.Ja?a.v.push(c):a.ba(c)}o.L=function(){return this.u?this.u():{}};o.ba=function(a){if(this.Aa)this.Aa(a);else if(ca(a))if(ba(a.T))a.T();else for(var c in a)delete a[c]};
o.C=function(){N.ka.C.call(this);for(var a=this.v;a.length;)this.ba(a.pop());delete this.v};var bb,cb=(bb="ScriptEngine"in p&&p.ScriptEngine()=="JScript")?p.ScriptEngineMajorVersion()+"."+p.ScriptEngineMinorVersion()+"."+p.ScriptEngineBuildVersion():"0";var db,eb,P,fb,gb,hb,ib,jb,kb,lb,mb;
(function(){function a(){return{f:0,F:0}}function c(){return[]}function b(){function a(b){return g.call(a.src,a.key,b)}return a}function d(){return new $a}function e(){return new M}var f=bb&&!(ma(cb,"5.7")>=0),g;hb=function(a){g=a};if(f){db=function(){return h.getObject()};eb=function(a){O(h,a)};P=function(){return j.getObject()};fb=function(a){O(j,a)};gb=function(){return l.getObject()};ib=function(){O(l,b())};jb=function(){return A.getObject()};kb=function(a){O(A,a)};lb=function(){return m.getObject()};
mb=function(a){O(m,a)};var h=new N(0,600);h.u=a;var j=new N(0,600);j.u=c;var l=new N(0,600);l.u=b;var A=new N(0,600);A.u=d;var m=new N(0,600);m.u=e}else db=a,eb=q,P=c,fb=q,gb=b,ib=q,jb=d,kb=q,lb=e,mb=q})();var Q={},R={},S={},T={};
function U(a,c,b,d,e){if(c)if(r(c)=="array")for(var f=0;f<c.length;f++)U(a,c[f],b,d,e);else{var d=!!d,g=R;c in g||(g[c]=db());g=g[c];d in g||(g[d]=db(),g.f++);var g=g[d],h=a[t]||(a[t]=++da),j;g.F++;if(g[h]){j=g[h];for(f=0;f<j.length;f++)if(g=j[f],g.U==b&&g.Fa==e){if(g.G)break;return}}else j=g[h]=P(),g.f++;f=gb();f.src=a;g=jb();g.w(b,f,a,c,d,e);b=g.key;f.key=b;j.push(g);Q[b]=g;S[h]||(S[h]=P());S[h].push(g);a.addEventListener?(a==p||!a.$a)&&a.addEventListener(c,f,d):a.attachEvent(c in T?T[c]:T[c]="on"+
c,f)}else i(Error("Invalid event type"))}function nb(a,c,b,d){if(!d.V&&d.Ka){for(var e=0,f=0;e<d.length;e++)if(d[e].G){var g=d[e].La;g.src=n;ib(g);kb(d[e])}else e!=f&&(d[f]=d[e]),f++;d.length=f;d.Ka=!1;f==0&&(fb(d),delete R[a][c][b],R[a][c].f--,R[a][c].f==0&&(eb(R[a][c]),delete R[a][c],R[a].f--),R[a].f==0&&(eb(R[a]),delete R[a]))}}
function ob(a,c,b,d,e){var f=1,c=c[t]||(c[t]=++da);if(a[c]){a.F--;a=a[c];a.V?a.V++:a.V=1;try{for(var g=a.length,h=0;h<g;h++){var j=a[h];j&&!j.G&&(f&=pb(j,e)!==!1)}}finally{a.V--,nb(b,d,c,a)}}return Boolean(f)}
function pb(a,c){var b=a.handleEvent(c);if(a.wa){var d=a.key;if(Q[d]){var e=Q[d];if(!e.G){var f=e.src,g=e.type,h=e.La,j=e.capture;f.removeEventListener?(f==p||!f.$a)&&f.removeEventListener(g,h,j):f.detachEvent&&f.detachEvent(g in T?T[g]:T[g]="on"+g,h);f=f[t]||(f[t]=++da);h=R[g][j][f];if(S[f]){var l=S[f],A=z(l,e);A>=0&&y.splice.call(l,A,1);l.length==0&&delete S[f]}e.G=!0;h.Ka=!0;nb(g,j,f,h);delete Q[d]}}}return b}
hb(function(a,c){if(!Q[a])return!0;var b=Q[a],d=b.type,e=R;if(!(d in e))return!0;var e=e[d],f,g;Xa===k&&(Xa=C&&!p.addEventListener);if(Xa){var h;if(!(h=c))a:{h="window.event".split(".");for(var j=p;f=h.shift();)if(j[f]!=n)j=j[f];else{h=n;break a}h=j}f=h;h=!0 in e;j=!1 in e;if(h){if(f.keyCode<0||f.returnValue!=k)return!0;a:{var l=!1;if(f.keyCode==0)try{f.keyCode=-1;break a}catch(A){l=!0}if(l||f.returnValue==k)f.returnValue=!0}}l=lb();l.w(f,this);f=!0;try{if(h){for(var m=P(),w=l.currentTarget;w;w=w.parentNode)m.push(w);
g=e[!0];g.F=g.f;for(var u=m.length-1;!l.ja&&u>=0&&g.F;u--)l.currentTarget=m[u],f&=ob(g,m[u],d,!0,l);if(j){g=e[!1];g.F=g.f;for(u=0;!l.ja&&u<m.length&&g.F;u++)l.currentTarget=m[u],f&=ob(g,m[u],d,!1,l)}}else f=pb(b,l)}finally{if(m)m.length=0,fb(m);l.T();mb(l)}return f}d=new M(c,this);try{f=pb(b,d)}finally{d.T()}return f});new N(0,100);var V="StopIteration"in p?p.StopIteration:Error("StopIteration");function W(){}W.prototype.next=function(){i(V)};W.prototype.X=function(){return this};
function qb(a){if(a instanceof W)return a;if(typeof a.X=="function")return a.X(!1);if(aa(a)){var c=0,b=new W;b.next=function(){for(;;)if(c>=a.length&&i(V),c in a)return a[c++];else c++};return b}i(Error("Not implemented"))}function rb(a,c){if(aa(a))try{qa(a,c,k)}catch(b){b!==V&&i(b)}else{a=qb(a);try{for(;;)c.call(k,a.next(),k,a)}catch(d){d!==V&&i(d)}}}
function sb(a,c){this.q={};this.d=[];var b=arguments.length;if(b>1){b%2&&i(Error("Uneven number of arguments"));for(var d=0;d<b;d+=2)this.set(arguments[d],arguments[d+1])}else if(a){var e;if(a instanceof sb){d=tb(a);ub(a);e=[];for(b=0;b<a.d.length;b++)e.push(a.q[a.d[b]])}else{var b=[],f=0;for(d in a)b[f++]=d;d=b;b=[];f=0;for(e in a)b[f++]=a[e];e=b}for(b=0;b<d.length;b++)this.set(d[b],e[b])}}o=sb.prototype;o.f=0;o.W=0;function tb(a){ub(a);return a.d.concat()}
o.clear=function(){this.q={};this.W=this.f=this.d.length=0};function ub(a){if(a.f!=a.d.length){for(var c=0,b=0;c<a.d.length;){var d=a.d[c];Object.prototype.hasOwnProperty.call(a.q,d)&&(a.d[b++]=d);c++}a.d.length=b}if(a.f!=a.d.length){for(var e={},b=c=0;c<a.d.length;)d=a.d[c],Object.prototype.hasOwnProperty.call(e,d)||(a.d[b++]=d,e[d]=1),c++;a.d.length=b}}o.get=function(a,c){return Object.prototype.hasOwnProperty.call(this.q,a)?this.q[a]:c};
o.set=function(a,c){Object.prototype.hasOwnProperty.call(this.q,a)||(this.f++,this.d.push(a),this.W++);this.q[a]=c};o.X=function(a){ub(this);var c=0,b=this.d,d=this.q,e=this.W,f=this,g=new W;g.next=function(){for(;;){e!=f.W&&i(Error("The map has changed since the iterator was created"));c>=b.length&&i(V);var g=b[c++];return a?g:d[g]}};return g};
function vb(){this.N=[];this.ia=new sb;this.Ta=this.Ua=this.Va=this.Oa=0;this.Q=new sb;this.xa=this.Sa=0;this.hb=1;this.ca=new N(0,4E3);this.ca.L=function(){return new wb};this.Pa=new N(0,50);this.Pa.L=function(){return new xb};var a=this;this.ga=new N(0,2E3);this.ga.L=function(){return String(a.hb++)};this.ga.ba=function(){};this.ab=3}function xb(){this.qa=this.Ra=this.count=0}
xb.prototype.toString=function(){var a=[];a.push(this.type," ",this.count," (",Math.round(this.Ra*10)/10," ms)");this.qa&&a.push(" [VarAlloc = ",this.qa,"]");return a.join("")};function wb(){}function yb(a,c,b,d){var e=[];b==-1?e.push("    "):e.push(zb(a.Da-b));e.push(" ",Ab(a.Da-c));a.da==0?e.push(" Start        "):a.da==1?(e.push(" Done "),e.push(zb(a.pb-a.startTime)," ms ")):e.push(" Comment      ");e.push(d,a);a.lb>0&&e.push("[VarAlloc ",a.lb,"] ");return e.join("")}
wb.prototype.toString=function(){return this.type==n?this.Za:"["+this.type+"] "+this.Za};vb.prototype.reset=function(a){this.ab=a;for(a=0;a<this.N.length;a++){var c=this.ca.id;c&&O(this.ga,c);O(this.ca,this.N[a])}this.N.length=0;this.ia.clear();this.Oa=ea();this.xa=this.Sa=this.Ta=this.Ua=this.Va=0;c=tb(this.Q);for(a=0;a<c.length;a++){var b=this.Q.get(c[a]);b.count=0;b.Ra=0;b.qa=0;O(this.Pa,b)}this.Q.clear()};
vb.prototype.toString=function(){for(var a=[],c=-1,b=[],d=0;d<this.N.length;d++){var e=this.N[d];e.da==1&&b.pop();a.push(" ",yb(e,this.Oa,c,b.join("")));c=e.Da;a.push("\n");e.da==0&&b.push("|  ")}if(this.ia.f!=0){var f=ea();a.push(" Unstopped timers:\n");rb(this.ia,function(b){a.push("  ",b," (",f-b.startTime," ms, started at ",Ab(b.startTime),")\n")})}c=tb(this.Q);for(d=0;d<c.length;d++)b=this.Q.get(c[d]),b.count>1&&a.push(" TOTAL ",b,"\n");a.push("Total tracers created ",this.Sa,"\n","Total comments created ",
this.xa,"\n","Overhead start: ",this.Va," ms\n","Overhead end: ",this.Ua," ms\n","Overhead comment: ",this.Ta," ms\n");return a.join("")};function zb(a){var a=Math.round(a),c="";a<1E3&&(c=" ");a<100&&(c="  ");a<10&&(c="   ");return c+a}function Ab(a){a=Math.round(a);return String(100+a/1E3%60).substring(1,3)+"."+String(1E3+a%1E3).substring(1,4)}new vb;
var Y={brush:{title:"Brush",mode:"source-over",cursor:"crosshair",size:2,h:{z:function(a,c,b){if(c.button===0)b.fillStyle="rgba("+a.m.join(",")+","+a.fa().pressure+")",b.lineWidth=a.D(),b.beginPath(),b.arc(c.x,c.y,b.lineWidth/2,0,Math.PI*2,!1),b.closePath(),b.fill(),a.M=c},A:function(a,c,b){var d=a.M;if(X&&c.button===0&&d)b.strokeStyle="rgba("+a.m.join(",")+","+a.fa().pressure+")",b.beginPath(),b.moveTo(d.x,d.y),b.lineTo(c.x,c.y),b.closePath(),b.stroke(),a.M=c}}},line:{title:"Line",mode:"source-over",
cursor:"crosshair",size:n,h:{z:function(a,c){if(c.button===0){var b=Y[a.b];b.o=!0;b.r=c}},A:function(a,c){if(X&&c.button===0){var b=Y[a.b].r,d=a.n.c;a.n.canvas.reset();d.strokeStyle="rgb("+a.m.join(",")+")";d.beginPath();d.moveTo(b.x,b.y);d.lineTo(c.x,c.y);d.closePath();d.stroke()}},P:function(a,c,b){var d=Y[a.b];if(d.o)d.o=!1,d=d.r,a.n.canvas.reset(),b.strokeStyle="rgb("+a.m.join(",")+")",b.lineWidth=a.D(),b.beginPath(),b.moveTo(d.x,d.y),b.lineTo(c.x,c.y),b.closePath(),b.stroke()}}},rectangle:{title:"Rectangle",
mode:"source-over",lineCap:"butt",lineJoin:"miter",cursor:"crosshair",size:n,filled:!0,h:{z:function(a,c){if(c.button===0){var b=Y[a.b];b.o=!0;b.r=c}},A:function(a,c){if(X&&c.button===0){var b=Y[a.b].r,d=c.altKey,e=a.n.canvas,f=a.n.c,g=c.y-b.y,h=c.x-b.x;c.shiftKey&&(h=h>0?Math.abs(g):-Math.abs(g));e.reset();f.strokeStyle="rgb("+a.m.join(",")+")";f.beginPath();f.rect(!d?b.x:b.x-h,!d?b.y:b.y-g,!d?h:2*h,!d?g:2*g);f.closePath();f.stroke()}},P:function(a,c,b){var d=Y[a.b];if(d.o){d.o=!1;var d=d.r,e=c.altKey,
f=a.n.canvas,g=c.y-d.y,h=c.x-d.x,j=a.D();c.shiftKey&&(h=h>0?Math.abs(g):-Math.abs(g));f.reset();b.strokeStyle="rgb("+a.m.join(",")+")";b.lineWidth=j;b.beginPath();b.rect((!e?d.x:d.x-h)+(h>0?j/2:-j/2),(!e?d.y:d.y-g)+(g>0?j/2:-j/2),(!e?h:2*h)-(h>0?j:-j),(!e?g:2*g)-(g>0?j:-j));b.closePath();b.stroke()}}}},ellipse:{title:"Ellipse",mode:"source-over",cursor:"crosshair",size:n,filled:!0,h:{z:function(a,c){if(c.button===0){var b=Y[a.b];b.o=!0;b.r=c}},A:function(a,c){if(X&&c.button===0){var b=Y[a.b].r,d=
c.altKey,e=a.n.canvas,f=a.n.c,g=c.y-b.y,h=c.x-b.x;c.shiftKey&&(h=h>0?Math.abs(g):-Math.abs(g));e.reset();f.strokeStyle="rgb("+a.m.join(",")+")";f.beginPath();f.Ca(!d?b.x:b.x-h,!d?b.y:b.y-g,!d?h:2*h,!d?g:2*g);f.closePath();f.stroke()}},P:function(a,c,b){var d=Y[a.b];if(d.o){d.o=!1;var d=d.r,e=c.altKey,f=a.n.canvas,g=c.y-d.y,h=c.x-d.x;c.shiftKey&&(h=h>0?Math.abs(g):-Math.abs(g));f.reset();b.strokeStyle="rgb("+a.m.join(",")+")";b.lineWidth=a.D();b.beginPath();b.Ca(!e?d.x:d.x-h,!e?d.y:d.y-g,!e?h:2*h,
!e?g:2*g);b.closePath();b.stroke()}}}},eraser:{title:"Eraser",mode:"destination-out",cursor:"crosshair",size:20,fb:!1,h:{focus:function(){},z:function(a,c,b){if(c.button===0)b.lineWidth=a.D(),b.beginPath(),b.arc(c.x,c.y,b.lineWidth/2,0,Math.PI*2,!1),b.closePath(),b.fill(),a.Ha=c},A:function(a,c,b){if(X&&c.button===0){var d=a.Ha;b.beginPath();b.moveTo(d.x,d.y);b.lineTo(c.x,c.y);b.closePath();b.stroke();a.Ha=c}}}},marquee:{title:"Selection",mode:"source-over",cursor:"crosshair",size:!1,l:0,h:{w:function(a){var c;
c=H("canvas",{width:a.a.clientWidth,height:a.a.clientHeight,transparent:"true","class":"selections"});a.a.appendChild(c);a.H={canvas:c,c:c.getContext("2d")};c=H("canvas",{width:a.a.clientWidth,height:a.a.clientHeight,transparent:"true","class":"selection-content"});a.a.appendChild(c);a.B={canvas:c,c:c.getContext("2d")}},blur:function(a,c){var b=Y[a.b],d=a.B.canvas,e=a.H.canvas;if(b.R){var f=d.toDataURL(),g=new Image;g.onload=function(){c.globalCompositeOperation=b.mode;c.drawImage(a,0,0)};g.src=f;
b.l=0;b.R=!1}d.reset();e.reset();b.e=k},z:function(a,c,b){var d=Y[a.b];if(d.l==2){var e=a.B.canvas,f=a.B.c,a=a.H.canvas,g=d.e;if(Bb(c.x,c.y,g)){if(!d.R)d.Y=b.getImageData.apply(b,g),d.nb=[c.x-g[0]+0.5,c.y-g[1]+0.5],f.putImageData(d.Y,g[0],g[1]),b.globalCompositeOperation="destination-out",b.beginPath(),b.rect.apply(b,g),b.closePath(),b.fill();d.l=3;d.K=c;d.J=c;return}else f=e.toDataURL(),e.reset(),a.reset(),e=new Image,e.onload=function(){b.globalCompositeOperation=d.mode;b.drawImage(this,0,0)},e.src=
f,d.l=0,d.R=!1}d.l=1;d.K=c;d.e=[c.x+0.5,c.y+0.5,0,0]},A:function(a,c){var b=Y[a.b],d;switch(b.l){case 1:d=[c.x-b.K.x,c.y-b.K.y];b.e[2]=d[0];b.e[3]=d[1];break;case 3:d=[c.x-b.J.x,c.y-b.J.y];b.e[0]+=d[0];b.e[1]+=d[1];var e=a.B.canvas,f=a.B.c;d=b.e;e.reset();f.putImageData(b.Y,d[0],d[1]);b.J=c}e=a.H.canvas;f=a.H.c;d=b.e;e.reset();f.beginPath();f.rect.apply(f,d);f.closePath();f.stroke()},P:function(a,c){var b=Y[a.b],d;switch(b.l){case 1:d=[c.x-b.K.x,c.y-b.K.y];if(d[0]===0||d[1]===0){b.e=k;break}b.e[2]=
d[0];b.e[3]=d[1];var e=a.H.canvas,f=a.H.c;d=b.e;e.reset();f.beginPath();f.rect.apply(f,d);f.closePath();f.stroke();b.l=2;break;case 3:d=[c.x-b.J.x,c.y-b.J.y],b.e[0]+=d[0],b.e[1]+=d[1],e=a.B.canvas,f=a.B.c,d=b.e,e.reset(),f.putImageData(b.Y,d[0],d[1]),b.l=2,b.R=!0}}}}};var Z={grid:{ta:!1,ra:function(a){a.O.canvas.style.display="block"},ya:function(a){a.O.canvas.style.display="none"}},"wacom-plugin":{ta:!0,ra:function(){Cb=!0},ya:function(){Cb=!1}}};
function x(a,c){this.j={t:"#FFFFFF",gb:"rgba(0, 0, 0, 0.05)",Ea:20,bb:"#000000",aa:"brush"};this.kb="brush,eraser,line,rectangle,ellipse,marquee".split(",");this.jb=["#000000","#FFFFFF","#FF0000","#00FF00","#0000FF"];this.mb={pressure:1};this.S=a;c&&Object.keys(c).forEach(function(a){this.j[a]=c[a]},this)}o=x.prototype;
o.eb=function(a){var c=this.a.clientWidth,b=this.a.clientHeight,d=this.i,e=d.length,f=H("canvas",{width:c,height:b}),g=f.getContext("2d"),h=[],j=[],l=0;d.forEach(function(d,m){if(d.t)g.fillStyle=d.t,g.fillRect(0,0,c,b),h[m]={color:d.t};else{var w=d.canvas.toDataURL(),u=new Image;u.src=w;u.ob=m;u.onload=function(){j[m]=u;h[m]={data:w};for(var b;b=j[l+1];)g.drawImage(b,0,0),l+=1;l+1===e&&(h.unshift({data:f.toDataURL()}),a(h))}}})};
o.ua=function(a){var c=this.j.Ea,b=a[0],a=a[1],d=b%c,e=a%c;d<c/2?e<c/2?(b-=d,a-=e):(b-=d,a+=c-e):e<c/2?(b+=c-d,a-=e):(b+=c-d,a+=c-e);return[b,a]};
o.Ya=function(){this.S.innerHTML="";Db(this);this.a=H("div",{"class":"area"});this.S.appendChild(this.a);this.toolbar=H("div",{"class":"sidebar"});Va(this.S,this.toolbar);Eb(this);Fb(this);this.sidebar=H("div",{"class":"sidebar"});this.S.appendChild(this.sidebar);Gb(this);Hb(this);this.options={};this.ha=H("div",{"class":"options"});this.sidebar.appendChild(this.ha);var a=H("ul");this.ha.appendChild(a);var c=Ib(this);a.appendChild(c);this.i=[];Jb(this);a=H("canvas",{width:this.a.clientWidth,height:this.a.clientHeight,
transparent:"true","class":"grid"});Va(this.a,a);this.O={canvas:a,c:a.getContext("2d")};var a=this.O.c,c=this.j.Ea,b=this.O.canvas.width,d=this.O.canvas.height;a.lineWidth=2;a.strokeStyle=this.j.gb;a.beginPath();for(var e=0;0<=b?e<b:e>b;0<=b?e+=1:e-=1)e%c===0&&(a.moveTo(e,0),a.lineTo(e,d));for(e=0;0<=d?e<d:e>d;0<=d?e+=1:e-=1)e%c===0&&(a.moveTo(0,e),a.lineTo(b,e));a.closePath();a.stroke();a=H("canvas",{width:this.a.clientWidth,height:this.a.clientHeight,transparent:"true","class":"temp"});this.a.appendChild(a);
this.n={canvas:a,c:a.getContext("2d")};Kb(this);Lb(this);Mb(this);this.Z(this.j.bb);this.$(this.j.aa)};function Eb(a){a.pa=H("ul",{"class":"tools"});a.toolbar.appendChild(a.pa);U(a.pa,"click",function(a){a=a.target;a.tagName==="LI"&&this.$(J(a,"tool"))},!1,a);Nb(a)}function Fb(a){a.ma=H("ul",{"class":"toggles"});a.toolbar.appendChild(a.ma);U(a.ma,"click",function(a){a=a.target;a.tagName==="LI"&&this.toggle(J(a,"toggle"))},!1,a);Ob(a)}
function Gb(a){a.Qa=H("div",{"class":"swatches"});a.sidebar.appendChild(a.Qa);var c=H("ul");a.Qa.appendChild(c);for(var b=a.jb,d=0,e=b.length;d<e;++d){var f=H("li");f.style.backgroundColor=b[d];I(f,"color",b[d]);c.appendChild(f)}U(c,"click",function(a){a=a.target;a.tagName==="LI"&&this.Z(J(a,"color"))},!1,a)}
function Hb(a){a.k=H("div",{"class":"layers"});a.sidebar.appendChild(a.k);var c=H("ul");a.k.appendChild(c);U(c,"click",function(a){a=a.target;if(a.nodeType===3)a=a.parentNode;switch(a.tagName){case "LI":this.s(J(a,"index"));break;case "SPAN":z(Na(a),"lock")>=0?(a=J(a.parentNode,"index"),this.i[a].p?this.Wa(a):this.Ia(a)):z(Na(a),"title")>=0&&this.s(J(a.parentNode,"index"))}},!1,a);Pb(a)}
function Pb(a){var c=H("ul",{"class":"toolbar"});a.k.appendChild(c);var b=H("li",{"class":"create"});b.setAttribute("title","New layer");U(b,"click",function(){Kb(this)},!1,a);c.appendChild(b);b=H("li",{"class":"delete"});b.setAttribute("title","Delete layer");U(b,"click",function(){this.za()},!1,a);c.appendChild(b)}
function Ib(a){var c=H("li",{"class":"size"}),b=H("input",{type:"range",min:2,max:50,value:1});c.appendChild(b);Object.defineProperty(a.options,"size",{get:function(){return b.value}});U(b,"change",function(){this.Na(b.value)},!1,a);return c}function Nb(a){a.oa={};var c=Y||{};a.kb.forEach(function(a){var d=c[a],e=H("li",{title:d.title});I(e,"tool",a);this.pa.appendChild(e);this.oa[a]=e;d.h&&typeof d.h.w==="function"&&d.h.w.call(d,this,e,n)},a)}
function Ob(a){a.na={};a.la={};Object.keys(Z||{}).forEach(function(a){var b=H("li",{title:Z[a].title});I(b,"toggle",a);this.ma.appendChild(b);this.la[a]=b},a)}function Lb(a){Object.keys(Z||{}).forEach(function(a){this.toggle(a,Z[a].ta)},a)}
function Jb(a){a.a.style.backgroundColor=a.j.t;var c={t:a.j.t};c.index=-1+a.i.push(c);a.va=c;var b=Qb(a);I(b,"index",c.index);F(b,"background");b.querySelector(".title").innerHTML="Background layer";U(b,"mouseover",function(){a.cb&&!a.va.p&&F(this,"swatch-change")});U(b,"mouseout",function(){a.cb&&!a.va.p&&G(this,"swatch-change")});c=H("span",{"class":"swatch"});c.style.backgroundColor=a.j.t;b.appendChild(c)}
function Kb(a){var c=H("canvas",{width:a.a.clientWidth,height:a.a.clientHeight,transparent:"true"}),b=a.a.querySelector(".selection-content");b?b.parentNode&&b.parentNode.insertBefore(c,b):a.a.appendChild(c);c={canvas:c,c:c.getContext("2d")};c.index=-1+a.i.push(c);b=Qb(a);b.querySelector(".title").innerHTML="New layer";I(b,"index",c.index);a.s(c.index)}
function Qb(a){var c=H("li");Va(a.k.querySelector("ul"),c);a=H("span",{"class":"title"});c.appendChild(a);a=H("span",{"class":"lock"});c.appendChild(a);return c}
function Mb(a){U(a.a,"mousedown",function(c){c.preventDefault();X=!0;if(this.g.p||a.g.canvas===k)return this.a.style.cursor="not-allowed",!1;Rb=!0;var c=Sb(this,c),b=Y[this.b];typeof a.I.z==="function"&&this.I.z.call(b,this,c,this.g.c);this.M=c;return!1},!1,a);U(a.a,"mouseup",function(a){if(X){X=!1;var b=Y[this.b];if(this.g.p)this.a.style.cursor=b.cursor||"default";a=Sb(this,a);typeof this.I.P==="function"&&this.I.P.call(b,this,a,this.g.c);this.M=a}},!1,a);U(window,"mousemove",function(a){if(X&&!this.g.p)Rb&&
a.preventDefault(),a=Sb(this,a),typeof this.I.A==="function"&&this.I.A.call(this.b,this,a,this.g.c),this.M=a},!1,a)}
function Sb(a,c){var b,d=b=0,e=a.a,f=n;do f=window.getComputedStyle(e,n),b+=e.offsetLeft-e.scrollLeft+parseInt(f.borderLeftWidth,10),d+=e.offsetTop-e.scrollTop+parseInt(f.borderTopWidth,10);while(e=e.offsetParent);b=[b,d];b=[c.clientX+window.scrollX-b[0],c.clientY+window.scrollY-b[1]];d=Y[a.b];a.na.grid&&d.fb!==!1&&(b=a.ua(b));return{x:b[0],y:b[1],button:c.button,ctrlKey:c.ctrlKey,altKey:c.altKey,shiftKey:c.shiftKey}}
o.s=function(a){var c=this.i[a];c||i(Error("Undefined layer"));if(this.g){var b=this.k.querySelector('li[data-index="'+this.g.index+'"]');b!==n&&G(b,"active")}this.g=c;F(this.k.querySelector('li[data-index="'+a+'"]'),"active");Tb(this)};o.sa=function(a){for(var c=this.i.length-1,b;b===k&&++a<=c;)b=this.i[a];if(b!==k)this.s(a);else{for(;b===k&&--a>=0;)b=this.i[a];b!==k&&this.s(a)}};
function Tb(a){var c=a.g;if(a.b&&c&&c.canvas)a=Y[a.b],c=c.c,c.globalCompositeOperation=a.mode||"source-over",c.lineWidth=a.size||1,c.lineCap=a.lineCap||"round"}o.Ia=function(a){var c=this.i[a];c||i(Error("Undefined layer"));c.p=!0;F(this.k.querySelector('li[data-index="'+a+'"]'),"locked")};o.Wa=function(a){var c=this.i[a];c||i(Error("Undefined layer"));c.p=!1;G(this.k.querySelector('li[data-index="'+a+'"]'),"locked")};
o.za=function(){var a=this.g;a||i(Error("Undefined layer"));a.p||(Wa(a.canvas),Wa(this.k.querySelector('li[data-index="'+a.index+'"]')),delete this.i[a.index],this.sa(a.index),this.g||this.s(Number(J(this.k.querySelector("li:last-child"),"index"))||0))};
o.$=function(a){var c=Y[a];c||i(Error('Undefined tool "'+a+'"'));var b=this.b;b&&(G(this.oa[b],"active"),b=Y[b],typeof b.h.blur==="function"&&b.h.blur.call(b,this,this.g.c));this.b=a;this.I=c.h||{};this.a.style.cursor=c.cursor||"default";F(this.oa[a],"active");typeof c.h.focus==="function"&&c.h.focus.call(c,this);a=Y[this.b].size;if(a===n)a=Y[this.j.aa].size;c=this.ha.querySelector(".size input");a===!1?c.disabled=!0:(c.disabled=!1,c.value=a);Tb(this)};
o.Z=function(a){if(Array.isArray(a))this.m=a;else if(typeof a==="string")a=a.charAt(0)==="#"?a.substring(1,7):a,this.m=[parseInt(a.substring(0,2),16),parseInt(a.substring(2,4),16),parseInt(a.substring(4,6),16)]};o.toggle=function(a,c){var b=Z[a];b||i(Error('Undefined toggle ("'+a+'")'));var d=typeof c!=="undefined"?Boolean(c):!this.na[a];(this.na[a]=d)?(b.ra.call(b,this),F(this.la[a],"active")):(b.ya.call(b,this),G(this.la[a],"active"))};
o.D=function(){var a=Y[this.b].size;return a===n?Y[this.j.aa].size:a};o.Na=function(a){var c=Y[this.b];if(c.size!==!1)c.size=Number(a)};o.fa=function(){var a=this.Xa;return!Cb||!a.isWacom||a.pointerType===0?this.mb:a};
function Db(a){var c=document.getElementById("wacom-plugin");a.Xa=c;if(!c)c=H("embed",{id:"wacom-plugin",type:"application/x-wacom-tablet",hidden:!0,pluginspage:"http://www.wacom.com/productsupport/plugin.php",style:"display: none"}),a.Xa=c,document.body.appendChild(c),U(window,"focus",function(){Wa(c);document.body.appendChild(c)})}var X=!1,Cb=!0,Rb;v("build",x.prototype.Ya);v("getState",x.prototype.eb);
function Bb(a,c,b){var d=!1;if(!b)return d;b[2]<0&&(b[0]+=b[2],b[2]=-b[2]);b[3]<0&&(b[1]+=b[3],b[3]=-b[3]);a>=b[0]-1&&a<=b[0]+b[2]&&c>=b[1]-1&&c<=b[1]+b[3]&&(d=!0);return d}HTMLCanvasElement.prototype.reset=function(){this.width=this.width};
CanvasRenderingContext2D.prototype.Ca=function(a,c,b,d){var e,f,g,h;g=b/2*0.5522848;h=d/2*0.5522848;e=a+b;f=c+d;b=a+b/2;d=c+d/2;this.moveTo(a,d);this.bezierCurveTo(a,d-h,b-g,c,b,c);this.bezierCurveTo(b+g,c,e,d-h,e,d);this.bezierCurveTo(e,d+h,b+g,f,b,f);this.bezierCurveTo(b-g,f,a,d+h,a,d)};var Ub=x,Vb="awesomeCanvas.Editor".split("."),$=p;!(Vb[0]in $)&&$.execScript&&$.execScript("var "+Vb[0]);for(var Wb;Vb.length&&(Wb=Vb.shift());)!Vb.length&&Ub!==k?$[Wb]=Ub:$=$[Wb]?$[Wb]:$[Wb]={};
v("applyGridToCoords",x.prototype.ua);v("activateLayer",x.prototype.s);v("activateNearestLayer",x.prototype.sa);v("lockLayer",x.prototype.Ia);v("unlockLayer",x.prototype.Wa);v("deleteActiveLayer",x.prototype.za);v("activateTool",x.prototype.$);v("activateSwatch",x.prototype.Z);v("toggle",x.prototype.toggle);v("getActiveToolSize",x.prototype.D);v("setActiveToolSize",x.prototype.Na);v("getWacomPlugin",x.prototype.fa);/*

 Offline Uploader
 --
 Ultimate solution to file uploads
 Does not require Internet connection in modern browsers.
 Falls back to classic multipart POST uploads in older ones.
 --
 @author Jan Kuca <jan@jankuca.com>, http://jankuca.com

 @licence Creative Commons 3.0 Attribution/Share-alike Unported Licence
 "As long as you keep this comment, you're fine."

*/
(function(global){function IOfflineUploader(form_el,params){}IOfflineUploader.prototype["init"]=function(){};IOfflineUploader.prototype["destroy"]=function(){};IOfflineUploader.prototype["on"]=function(type,listener,ctx){};IOfflineUploader.prototype["enable"]=function(){};IOfflineUploader.prototype["disable"]=function(){};IOfflineUploader.prototype.disabled;IOfflineUploader.prototype.params;IOfflineUploader.prototype.storage;function IOnlineUploader(params){}IOnlineUploader.prototype["uploadBase64"]=
function(name,data,callback){};function IOfflineStorage(params){}IOfflineStorage.prototype["connect"]=function(callback){};IOfflineStorage.prototype["disconnect"]=function(callback){};IOfflineStorage.prototype["store"]=function(file,data,callback){};var __slice=Array.prototype.slice;var _bind=function(fn,ctx){try{return fn.bind(ctx)}catch(err){return function(){return fn.apply(ctx,__slice.call(arguments))}}};var INDEXEDDB_SUPPORT="indexedDB"in window||"webkitIndexedDB"in window||"mozIndexedDB"in window;
var WEBSQL_SUPPORT="openDatabase"in window;var FILEAPI_SUPPORT="FileReader"in window&&"files"in window.document.createElement("input");var OFFLINE_SUPPORT=(INDEXEDDB_SUPPORT||WEBSQL_SUPPORT)&&FILEAPI_SUPPORT;var DRAGANDDROP_SUPPORT="ondrop"in window.document.body;var IE=navigator.userAgent.search("MSIE")!==-1;var OfflineUploader=function(form_el,params){params=params||{};this.params={"ns":params["ns"]||"uploader","store":params["store"]||"files","api":params["api"]||form_el.action,"drop":null};if(params["drop"]===
true)this.params["drop"]=form_el;else if(params["drop"]instanceof Element)this.params["drop"]=params["drop"];this.listeners={"beforequeue":[],"queuesuccess":[],"queuefailure":[],"queueempty":[],"uploading":[],"uploadsuccess":[],"uploadfailure":[],"dragenter":[],"dragover":[],"dragleave":[],"drop":[]};this.form_el=form_el;this.span_el=form_el.getElementsByTagName("span").item(0);this.input_el=form_el.getElementsByTagName("input").item(0);this.button_el=form_el.getElementsByTagName("button").item(0);
this.iframe_el=form_el.getElementsByTagName("iframe").item(0);this.disabled=true;this.offline=params["offline"]===false?false:OFFLINE_SUPPORT};OfflineUploader.prototype.storage=null;OfflineUploader.prototype["init"]=function(){this.addListeners();if(this.offline)this.connectStorage(_bind(function(err){if(err){this.offline=false;this["enable"]()}else this["enable"]()},this));else this["enable"]()};OfflineUploader.prototype["destroy"]=function(){this.removeListeners();if(this.offline)this.disconnectStorage()};
OfflineUploader.prototype["on"]=function(type,listener,ctx){try{this.listeners[type].push([listener,ctx!==void 0?ctx:this])}catch(err){throw new Error("Unknown event type");}};OfflineUploader.prototype["enable"]=function(){this.disabled=false;this.input_el.disabled=false;this.button_el.disabled=false;this.form_el.className=this.form_el.className.replace(/(^|\s+)disabled(\s+|$)/," ")};OfflineUploader.prototype["disable"]=function(){this.disabled=true;this.input_el.disabled=true;this.button_el.disabled=
true;this.form_el.className+=" disabled"};OfflineUploader.prototype.label=function(label){this.span_el.textContent=label;this.span_el.innerText=label};OfflineUploader.prototype.confirm=function(data){this.label("Upload a file");this["enable"]();try{data=JSON.parse(data)}catch(err){}this.fire("uploadsuccess",data)};OfflineUploader.prototype.upload=function(){if(FILEAPI_SUPPORT&&this.storage&&this.offline){var files=this.input_el.files;if(files.length!==0){this["disable"]();this.uploadFiles(files)}}else{var value=
this.input_el.value;if(value){this.beginUploading();this.form_el.submit()}}};OfflineUploader.prototype.uploadFiles=function(files){var _max=files.length-1;Array.prototype.forEach.call(files,function(file,i){if(!this.fire("beforequeue",file)){this["enable"]();return}var reader=new FileReader;reader.onloadend=_bind(function(){this.storage["store"](file,reader.result,_bind(function(err){if(err)this.fire("queuefailure",file.name);else this.fire("queuesuccess",file.name);this["enable"]()},this))},this);
reader.readAsDataURL(file)},this)};OfflineUploader.prototype.fire=function(type,detail){var listeners=this.listeners[type];if(listeners===void 0)throw new Error("Unknown event type");return listeners.every(function(listener){return listener[0].call(listener[1],detail)!==false})};OfflineUploader.prototype.connectStorage=function(callback){if(!this.storage)if(INDEXEDDB_SUPPORT)this.storage=new IndexedDBStorage(this.params);else if(WEBSQL_SUPPORT)this.storage=new WebSQLStorage(this.params);if(this.storage&&
this.storage.connect)this.storage.connect(_bind(function(err){if(err){this.offline=false;this["enable"]()}if(typeof callback==="function")callback(err||null)},this));else if(this.storage){if(typeof callback==="function")callback(null)}else if(typeof callback==="function")callback(new Error("No storage available"))};OfflineUploader.prototype.disconnectStorage=function(){if(this.storage&&this.storage.disconnect)this.storage.disconnect()};OfflineUploader.prototype.addListeners=function(){if(IE)this.addIEListeners();
else this.addStandardListeners();this.addDragAndDropListeners()};OfflineUploader.prototype.addIEListeners=function(){this.button_el.onclick=_bind(function(){this.input_el.click();if(FILEAPI_SUPPORT){this.upload();return false}},this);if(!FILEAPI_SUPPORT)this.form_el.onsubmit=_bind(function(e){var value=this.input_el.value;if(!value)return false;this.beginUploading();return true},this)};OfflineUploader.prototype.addStandardListeners=function(){this.form_el.onclick=_bind(function(){this.input_el.click()},
this);this.input_el.onchange=_bind(function(){this.upload()},this)};OfflineUploader.prototype.addDragAndDropListeners=function(){var target=this.params["drop"];if(target&&DRAGANDDROP_SUPPORT&&FILEAPI_SUPPORT){target["ondragenter"]=_bind(function(e){e.preventDefault();if(!this.disabled)this.fire("dragenter")},this);target["ondragleave"]=_bind(function(e){e.preventDefault();this.fire("dragleave")},this);target["ondragover"]=_bind(function(e){e.preventDefault();if(!this.disabled)this.fire("dragover")},
this);target["ondrop"]=_bind(function(e){e.preventDefault();if(!this.disabled){var files=e.dataTransfer.files;this.fire("drop",files);if(files.length)this.uploadFiles(files)}},this)}if(DRAGANDDROP_SUPPORT){if(FILEAPI_SUPPORT){var input_el=this.input_el;input_el["ondragenter"]=input_el["ondragover"]=input_el["ondragleave"]=input_el["ondrop"]=function(e){e.preventDefault()}}if(target)target["ondragenter"]=target["ondragover"]=target["ondragleave"]=target.ondrop=function(e){e.preventDefault()}}};OfflineUploader.prototype.removeListeners=
function(){if(IE)this.button_el.onclick=null;else this.input_el.onchange=null;if(DRAGANDDROP_SUPPORT&&this.params["drop"]){this.params["drop"]["ondragenter"]=null;this.params["drop"]["ondragover"]=null;this.params["drop"]["ondragleave"]=null;this.params["drop"]["ondrop"]=null;this.input_el["ondragenter"]=null;this.input_el["ondragover"]=null;this.input_el["ondragleave"]=null;this.input_el["ondrop"]=null}};OfflineUploader.prototype.beginUploading=function(){this["disable"]();this.label("Uploading...");
var e=this.input_el.value.match(/(\\|\/)([^\\|\/]+)$/);var name=e?e[2]:this.input_el.value;this.iframe_el.onload=_bind(function(){var body=this.iframe_el.contentWindow.document.body;var data=body.textContent||body.innerHTML||null;this.confirm(data)},this);this.fire("uploading",name)};var OnlineUploader=function(params){this.params=params||{}};OnlineUploader.prototype["uploadBase64"]=function(name,data,callback){var body=["name="+encodeURIComponent(name),"data="+encodeURIComponent(data)].join("&");
var xhr=new XMLHttpRequest;xhr.open("POST",this.params.api,true);xhr.setRequestHeader("x-requested-with","XMLHttpRequest");xhr.setRequestHeader("content-type","application/x-www-form-urlencoded; charset=UTF-8");xhr.onreadystatechange=_bind(function(){if(xhr.readyState===4)if(xhr.status<300){if(typeof callback==="function")callback(null)}else{if(typeof callback==="function")callback(new Error("Failed to upload the item. Auto-retrying in a moment."));setTimeout(_bind(function(){this["uploadBase64"](name,
data,callback)},this),5E3)}},this);xhr.send(body)};var IndexedDBStorage=function(params){this.idle=false;this.params=params};IndexedDBStorage.DB_VERSION="1.0";IndexedDBStorage.prototype=new OnlineUploader;IndexedDBStorage.prototype.constructor=IndexedDBStorage;IndexedDBStorage.prototype.db=null;IndexedDBStorage.prototype.connect=function(callback){var DB=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB;var req=DB.open(this.params["ns"],"");req.onsuccess=_bind(function(e){this.db=e.target.result;
this.build(_bind(function(){this.idle=true;this.pushQueue();if(typeof callback==="function")callback(null)},this))},this);req.onfailure=_bind(function(e){this.disconnect();if(typeof callback==="function")callback(new Error("Database connection failed"))},this)};IndexedDBStorage.prototype.disconnect=function(){if(this.db)this.db.close();this.db=null};IndexedDBStorage.prototype["store"]=function(file,data,callback){var tx=this.createTransaction(true);var req=tx.objectStore(this.params["store"]).add({name:file.name,
data:data});if(typeof callback==="function"){req.onsuccess=function(){callback(null);if(this.idle)this.pushQueue()};req.onfailure=function(){callback(new Error("Failed to store the item"))}}};IndexedDBStorage.prototype.pushQueue=function(callback){var tx=this.createTransaction(false);var IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange;var range=IDBKeyRange.leftBound(0);this.idle=true;var req=tx.objectStore(this.params["store"]).openCursor(range);req.onsuccess=_bind(function(e){var result=
e.target.result;if(result){var value=result.value;this["uploadBase64"](value.name,value.data,_bind(function(){var tx=this.createTransaction(true);var store=tx.objectStore(this.params["store"]);var req=store["delete"](result.key);req.onsuccess=_bind(function(){this.pushQueue(callback)},this)},this))}else{this.idle=true;if(typeof callback==="function")callback()}},this);req.onfailure=_bind(function(){this.idle=true},this)};IndexedDBStorage.prototype.build=function(callback){if(this.db.version===IndexedDBStorage.DB_VERSION){if(typeof callback===
"function")callback(null);return}var req=this.db.setVersion(IndexedDBStorage.DB_VERSION);req.onsuccess=_bind(function(e){this.db.createObjectStore(this.params["store"],{autoIncrement:true});if(typeof callback==="function")callback(null)},this);req.onfailure=_bind(function(){this.disconnect();callback(new Error("Database build failed"))},this)};IndexedDBStorage.prototype.createTransaction=function(write){var IDBTransaction=window.IDBTransaction||window.webkitIDBTransaction;return this.db.transaction([this.params["store"]],
write?IDBTransaction.READ_WRITE:IDBTransaction.READ_ONLY,0)};var WebSQLStorage=function(params){this.params=params};WebSQLStorage.DB_VERSION="1.0";WebSQLStorage.prototype=new OnlineUploader;WebSQLStorage.prototype.constructor=function(){OnlineUploader.apply(this,__slice.call(arguments));WebSQLStorage.apply(this,__slice.call(arguments))};WebSQLStorage.prototype.db=null;WebSQLStorage.prototype.connect=function(callback){this.db=window.openDatabase(this.params["ns"],WebSQLStorage.DB_VERSION,"",10*1024*
1024);if(!this.db){this.disconnect();callback(new Error("Database connection failed"))}else if(this.db.version===WebSQLStorage.DB_VERSION)callback(null)};WebSQLStorage.prototype.disconnect=function(){this.db=null};WebSQLStorage.prototype.build=function(db,callback){db.changeVersion(db.version,WebSQLStorage.DB_VERSION,_bind(function(tx){tx.executeSql("CREATE TABLE [?] ( "+"[id] INTEGER PRIMARY KEY AUTOINCREMENT, "+"[name], [data] "+")",[this.params["store"]],function(){if(typeof callback==="function")callback(null)},
_bind(function(){this.disconnect();callback(new Error("Database build failed"))},this))},this))};WebSQLStorage.prototype["store"]=function(file,data,callback){this.db.transaction(_bind(function(tx){var onsuccess=function(){if(typeof callback==="function")callback(null)};var onfailure=function(){if(typeof callback==="function")callback(new Error("Failed to store the item"))};tx.executeSql("INSERT INTO [?] ([name], [data]) VALUES (?, ?)",[this.params["store"],file.name,data],onsuccess,onfailure)},this))};
WebSQLStorage.prototype.pushQueue=function(callback){var store=this.params["store"];var onreadsuccess=_bind(function(tx,res){var value=res.rows[0];if(value)this["uploadBase64"](value,function(){tx.executeSql("DELETE FROM [?] WHERE [id] = ?",[store,value.id],ondeletesuccess)});else if(typeof callback==="function")callback()},this);var ondeletesuccess=_bind(function(){this.pushQueue(callback)},this);this.db.transaction(function(tx){tx.executeSql("SELECT * FROM [?] LIMIT 1",[store],onreadsuccess)})};
global["OfflineUploader"]=OfflineUploader})(window);window.MOBILE=/mobile/i.test(window.navigator.userAgent);
window.boot=function(){if(window.MOBILE)return redirectToMobile();if(!window.SUPPORTED_BROWSER)return;var run=function(){app.set("api_root","/api");app.set("db_name","skolnisesit-desktop-new");app.set("db_size",100*1024*1024);app.set("db_title","\u0160koln\u00ed se\u0161it.cz");app.set("max_file_size",20*1024*1024);app.set("sync_delay",60*1E3);app.set("free.notebook_limit",1);app.set("free.shared_notebook_limit",1);var router=app.router;router.push("/",{"controller":"default","view":"default"});router.push("/users/:username",
{"controller":"user","view":"default","params":{"username":/^[a-z0-9][\w\-\.]*$/i}});router.push("/notebooks/:id",{"controller":"notebook","view":"default","params":{"id":router.PARAM_HEX,"topics":/^[a-f0-9;]*$/i}});router.push("/notebooks/:id/sharing",{"controller":"notebook","view":"sharing","params":{"id":router.PARAM_HEX}});router.push("/session",{"controller":"session","view":"signin"});router.push("/:_c",{"controller":":_c","view":"default","params":/^[a-z][a-z0-9\-]+$/});router.push("/:_c/:_v",
{"controller":":_c","view":":_v","params":/^[a-z][a-z0-9\-]+$/});app.run()};var boot_loader=window.boot_loader=new BootLoader;require.ROOT="/js/";var boot=function(){require.js("lib/iterator/iterator.js","lib/take-note/dist/take-note.js","lib/awesome-canvas/dist/awesome-canvas.js","lib/offline-uploader/src/offline-uploader.js","app/printer.js","app/migrations.js","app/models/user.js","app/models/session.js","app/models/notebook.js","app/models/topic.js","app/models/lesson.js","app/models/attachment.js",
"app/models/request.js","app/models/search.js","app/models/changes.js","app/controllers/@base.js","app/controllers/default.js","app/controllers/session.js","app/controllers/notebook.js","app/controllers/user.js","app/lang/"+window.LANG+".js",run)};var cache=window.applicationCache;var load=function(){if(cache){cache.oncached=null;cache.ondownloading=null;cache.onprogress=null;cache.onupdateready=null;cache.onobsolete=null;cache.onerror=null}require.js("lib/flowoff/flowoff.js",function(){FlowOff.load("lib/flowoff/",
boot)})};if(!OFFLINE_SUPPORTED_BROWSER||!cache||cache.status===cache.IDLE)if(window.app)run();else load();else{cache.oncached=load;cache.ondownloading=function(){boot_loader.setProgress(0);boot_loader.setStatus("Downloading the application")};cache.onprogress=function(e){boot_loader.setProgress(e.loaded/e.total);boot_loader.setStatus("Downloading the application ("+e.loaded+(e.total?"/"+e.total:"")+")")};cache.onupdateready=function(){window.location.reload()};cache.onobsolete=window.app?run:load;
cache.onerror=function(){boot_loader.setProgressColor("#FF4400");boot_loader.setStatus("There was an error updating the application.");boot_loader.setNote("You can use the old version and the update process will take place the next time you start up the app.<br />The old version will boot now.");setTimeout(window.app?run:load,1E3)}}};
var BootLoader=Function.inherit(function(){this._buildLayout()},{"setTitle":function(title){this._title.html(title)},"setProgress":function(fr){this._progress_bar.show();this._progress.style.width=Math.min(100,fr*100)+"%"},"setProgressColor":function(color){this._progress.style.backgroundColor=color},"setStatus":function(status){this._status.html(status)},"setNote":function(note){this._note.html(note)},"_buildLayout":function(){document.body.html("");this.layout=new Element("div",{"id":"boot-loader"});
document.body.insert(this.layout);this._buildTitle();this._buildProgressBar(false);this._buildStatus();this._buildNote()},"_buildTitle":function(){var title=new Element("p",{"class":"title"});title.html("Loading&hellip;");this._title=title;this.layout.insert(title)},"_buildProgressBar":function(show){var progress_bar=new Element("div",{"class":"progress-bar","style":"display: none;"});var container=new Element("div");progress_bar.insert(container);this._progress=new Element("span");container.insert(this._progress);
progress_bar.insert(container);this._progress_bar=progress_bar;this.layout.insert(this._progress_bar)},"_buildStatus":function(){this._status=new Element("p",{"class":"status"});this.layout.insert(this._status)},"_buildNote":function(){this._note=new Element("p",{"class":"note"});this.layout.insert(this._note)}});var migrations=app._migrations=[];
migrations.push(["CREATE TABLE [sessions] ( \t\t[_id], [_parent] \t)","CREATE TABLE [users] ( \t\t[_ns], [_id], \t\t[users__username], [users__realname], \t\t[facebook__id], [facebook__picture], \t\t[date__created], \t\t[premium__expires] \t)","CREATE TABLE [notebooks] ( \t\t[_ns], [_id], [_parent], [commits__id], \t\t[__title], [__professor], [__year], \t\t[readable], [writable], [permissions__public], \t\t[date__created], [date__modified] \t)","CREATE TABLE [topics] ( \t\t[_ns], [_id], [_parent], [commits__id], \t\t[__title], \t\t[date__created], [date__modified] \t)","CREATE TABLE [lessons] ( \t\t[_ns], [_id], [_parent], [commits__id], \t\t[lesson__number], [lesson__date], \t\t[__content], [__textcontent], \t\t[date__created], [date__modified] \t)",
"CREATE TABLE [attachments] ( \t\t[_ns], [_id], [_parent], [commits__id], \t\t[__title], \t\t[files__data], [files__size], [files__type], \t\t[date__created], [date__modified] \t)","CREATE TABLE [requests] ( \t\t[_ns], [_id], \t\t[__type], \t\t[requests__subject], [requests__origin], [requests__target], \t\t[date__created], [date__modified] \t)"]);migrations.push(["ALTER TABLE [users] \t\tADD COLUMN [users__gender]"]);var Printer=function(notebook,topic_ids){this.notebook_=notebook;this.topic_ids_=Array.isArray(topic_ids)?topic_ids:[topic_ids]};Printer.prototype.open=function(){this.openPopup_();this.buildUI_();this.listenToChanges_();this.addActions_();this.loadInitalData_()};
Printer.prototype.download=function(path){var iframe=this.document.createElement("iframe");iframe.setAttribute("src",path);iframe.style.display="none";this.body.appendChild(iframe);var self=this;iframe.onload=function(){self.body.removeChild(this)};iframe=null};
Printer.prototype.openPopup_=function(){var options="status=1,toolbar=0,location=0,menubar=0,"+"directories=0,resizable=1,scrollbars=0,"+"width="+Math.min(window.innerWidth-50,800)+","+"height="+Math.min(window.innerHeight-50,600);this.popup_=window.open("","printer",options);this.document=this.popup_.document;this.body=this.document.body};
Printer.prototype.buildUI_=function(){var stylesheet=this.createScreenStylesheet_();this.document.getElementsByTagName("head")[0].appendChild(stylesheet);var stylesheet=this.createPrintStylesheet_();this.document.getElementsByTagName("head")[0].appendChild(stylesheet);this.sidebar=new Printer.Sidebar(this.document);this.preview=new Printer.Preview(this.document);this.body.appendChild(this.sidebar.element);this.body.appendChild(this.preview.element)};
Printer.prototype.createStylesheet_=function(media,path){var stylesheet=this.document.createElement("link");stylesheet.setAttribute("rel","stylesheet");stylesheet.setAttribute("type","text/css");stylesheet.setAttribute("href","http://"+window.location.host+path);stylesheet.setAttribute("media",media);return stylesheet};Printer.prototype.createScreenStylesheet_=function(){return this.createStylesheet_("screen","/css/app-printer.css")};
Printer.prototype.createPrintStylesheet_=function(){return this.createStylesheet_("print","/css/print.css")};Printer.prototype.listenToChanges_=function(){this.state_={topics:this.topic_ids_,cover:false,toc:false};var self=this;this.sidebar.onchange=function(state){self.state_=state;self.updatePreview_()}};
Printer.prototype.addActions_=function(){var self=this;var popup=this.popup_;var notebook=this.notebook_;this.sidebar.addAction("print","Print",function(){popup.print()});this.sidebar.addAction("export","Download as PDF",function(){var state=self.sidebar.getState();self.ondownload.call(self,state)})};
Printer.prototype.loadInitalData_=function(){var self=this;var notebook=this.notebook_;var open_ids=this.topic_ids_;if(app.MODE==="offline")notebook.getParent(function(user){self.sidebar.setLabel(notebook[":title"],user["users:realname"],notebook[":year"]);notebook.getTopics(function(topics){self.topics_=topics;self.sidebar.setTopics(topics,open_ids);self.updatePreview_()})});else{var uri=Notebook.getApiUri(this.notebook_.id);var params={"topics":this.topic_ids_.join(";")};Notebook.api("GET",uri,
params,function(status,response){if(status!==200)alert("Error ("+status+")");else{var topics=response.topics.map(function(doc){return new Topic(doc)});self.topics_=topics;self.sidebar.setTopics(topics,open_ids);self.updatePreview_()}})}};
Printer.prototype.updatePreview_=function(){var self=this;var state=this.state_;var open=state.topics;this.preview.clear();if(open.length){var selected=[];this.topics_.forEach(function(topic){if(open.indexOf(topic.id)===-1)return;selected.push(topic)});(function iter(i){if(i!==selected.length){var topic=selected[i];topic.getLessons(function(lessons){self.preview.pushTopic(topic,lessons);iter(++i)})}})(0)}};
Printer.Sidebar=function(doc){var self=this;this.document=doc;var element=doc.createElement("div");element.id="sidebar";this.element=element;var content=doc.createElement("div");content.className="content";element.appendChild(content);element.addEventListener("change",function(e){self.onchange.call(self,self.getState())});this.content_element=content;var button_bar=doc.createElement("div");button_bar.className="button-bar";element.appendChild(button_bar);this.button_bar=button_bar};
Printer.Sidebar.prototype.setLabel=function(title,realname,meta){var ul=this.document.createElement("ul");ul.className="label";this.element.insertBefore(ul,this.content_element);var li=this.document.createElement("li");li.className="title";li.textContent=title;ul.appendChild(li);var li=this.document.createElement("li");li.className="realname";li.textContent=realname;ul.appendChild(li);var li=this.document.createElement("li");li.className="meta";li.textContent=meta;ul.appendChild(li)};
Printer.Sidebar.prototype.setTopics=function(topics,chosen){chosen=chosen||[];var doc=this.document;var message=doc.createElement("h2");message.innerHTML="Choose topics";this.content_element.appendChild(message);var list=doc.createElement("ul");topics.forEach(function(topic){var item=doc.createElement("li");item.innerHTML="<label>"+'<input type="checkbox" class="topic" value="'+topic.id+'"'+(chosen.indexOf(topic.id)!==-1?' checked="checked"':"")+" />"+"<span>"+topic[":title"]+"</span>"+"</label>";
list.appendChild(item)});this.content_element.appendChild(list)};Printer.Sidebar.prototype.addAction=function(name,label,handler){var self=this;var button=this.document.createElement("button");button.className=name;button.innerHTML=label;button.onclick=function(){var state=self.getState();handler(state)};this.button_bar.appendChild(button)};
Printer.Sidebar.prototype.getState=function(){var content_element=this.content_element;var topics=[];var cover=false;var toc=false;var checks=content_element.querySelectorAll('input[type="checkbox"]');Array.prototype.forEach.call(checks,function(check){if(check.className==="topic"){if(check.checked)topics.push(check.value)}else if(check.className==="cover"){if(check.checked)cover=true}else if(check.className==="toc")if(check.checked)toc=true});return{topics:topics,cover:cover,toc:toc}};
Printer.Preview=function(doc){this.document=doc;var element=doc.createElement("div");element.id="preview";this.element=element};Printer.Preview.prototype.clear=function(){this.element.innerHTML=""};
Printer.Preview.prototype.pushTopic=function(topic,lessons){var doc=this.document;var page=doc.createElement("div");page.className="page";this.element.appendChild(page);var title=doc.createElement("h1");title.className="topic-title";title.textContent=topic[":title"];page.appendChild(title);lessons.forEach(function(lesson){var section=doc.createElement("div");section.className="lesson";page.appendChild(section);var header=doc.createElement("header");section.appendChild(header);var number=doc.createElement("span");
number.textContent=lesson["lesson:number"];header.appendChild(number);var date=doc.createElement("span");date.textContent=lesson["lesson:date"];header.appendChild(date);var contents=doc.createElement("div");contents.className="content";var take_note=new takeNote.Editor(contents);take_note.load(lesson[":content"],doc);section.appendChild(contents)})};var User=Model.inherit({"getFriends":function(selector,options,callback){if(arguments.length===2){callback=arguments[1];options=arguments[0];selector={}}else if(arguments.length===1){callback=arguments[0];options={};selector={}}selector._id={$ne:this.id};options.fallback=app.get("api_root")+"/friends";if(app.MODE==="offline")options.online=false;this.constructor.all(selector,options,callback)},"getAllNotebooks":function(callback){var options={fallback:this.constructor.getApiUri(this["users:username"],
"notebook")};var current_user=app.current_user;if(app.MODE==="offline"&&current_user&&current_user.id===this.id)Notebook.all({readable:true},options,callback);else this.getNotebooks(options,callback)},"getOwnNotebooks":function(callback){var user=this;this.getAllNotebooks(function(notebooks){var result=notebooks.filter(function(notebook){return notebook.parent===user.id});callback(result)})},"getSharedNotebooks":function(callback){var user=this;this.getAllNotebooks(function(notebooks){var result=
notebooks.filter(function(notebook){return notebook.parent!==user.id});callback(result)})},"isPremium":function(){return this.doc["premium:expires"]>Math.floor((new Date).getTime()/1E3)},"isAllowedTo":function(operation,scope,callback){if(this.isPremium())return callback(true);switch(operation){case "create":switch(scope){case "notebook":return this.getOwnNotebooks(function(notebooks){callback(notebooks.length<app.get("free.notebook_limit"))})}break;case "accept":switch(scope){case "notebook_sharing":return this.getSharedNotebooks(function(notebooks){callback(notebooks.length<
app.get("free.shared_notebook_limit"))})}}return callback(true)}});User.collection="users";User.fields=["users:username","users:realname","users:gender","date:created","facebook:id","facebook:picture","premium:expires"];User.sort="users:realname";User.api_field="users:username";User.has_one("session");User.has_many("notebooks",{"readable":true});var Session=Model.inherit();Session.collection="sessions";Session.fields=["facebook:access_token","date:created"];Session.namespace=null;Session.online=false;Session.belongs_to("user");
Session.fetch=function(callback){this.api("GET",app.get("api_root")+"/session",function(status,response,xhr){if(status!==200&&status!==401){alert("Cannot sign in right now");return}if(response===null||status===401){window.location.href="http://"+window.location.host+"/session";return}var session=new this;session.id=response._token;if(app.MODE==="offline"){app.namespace=response._id;User.one({"users:username":response["users:username"]},function(user){if(user instanceof Error)throw user;if(!user.stored)user.id=
response._id;user["users:username"]=response["users:username"];user["users:realname"]=response["users:realname"];user["users:gender"]=response["users:gender"];user["facebook:picture"]=response["facebook:picture"];user["premium:expires"]=response["premium:expires"];user.save({"online":false},function(){session.parent=user;session.save(function(){Session.all({_id:{$ne:session.id}},function(sessions){sessions.forEach(function(s){s.remove()});callback(session)})})})})}else{var user=new User({"_id":response._id,
"users:username":response["users:username"],"users:realname":response["users:realname"],"users:gender":response["users:gender"],"facebook:picture":response["facebook:picture"],"premium:expires":response["premium:expires"]});session.stored=true;session.parent=user;callback(session)}}.bind(this))};
Session.destroy=function(callback){var self=this;this.api("DELETE",app.get("api_root")+"/session",function(){self.all(function(sessions){var i=0;(function __loop(){if(i<sessions.length)sessions[i++].remove(__loop);else{var date=new Date(2E4);document.cookie="FLOWONSESSID=0;domain=."+document.location.hostname+";path=/;expires="+date.toUTCString();document.cookie="user_id=0;domain=."+document.location.hostname+";path=/;expires="+date.toUTCString();var old_domain=document.domain;document.domain=old_domain.match(/\.([^\.]+\.[^\.]+)$/)[1];
document.cookie="FLOWONSESSID=0;domain=."+document.domain+";path=/;expires="+date.toUTCString();document.cookie="user_id=0;domain=."+document.domain+";path=/;expires="+date.toUTCString();callback(null)}})()})})};var Notebook=Model.inherit(function(){Object.defineProperties(this,{"writable":{get:function(){return String(this.doc.writable)==="true"},set:function(value){this.doc.writable=!!value}},"readable":{get:function(){return!!this.doc.readable},set:function(value){this.doc.readable=!!value}}})},{"beforeSave":function(){this.doc["commits:id"]=window.uuid()},"shareTo":function(user,write,callback){this.constructor.api("PUT",app.get("api_root")+"/notebooks/"+this.id+"/sharing/"+user.id,{},{"write":Boolean(write)},
function(status,res){callback(status)})},"unshareFrom":function(user,callback){this.constructor.api("DELETE",app.get("api_root")+"/notebooks/"+this.id+"/sharing/"+user.id,function(status,res){callback(status)})}});Notebook.collection="notebooks";Notebook.fields=[":title",":professor",":year","permissions:public","date:created","date:modified","date:deleted","commits:id"];Notebook.sort=":title";Notebook.belongs_to("user");Notebook.has_many("topics");
Notebook.getViewData=function(params,callback){var current_user=app.current_user;Notebook.one({"_id":params.id},function(notebook){if(notebook.stored)return callback(notebook);Notebook.api("GET",Notebook.getApiUri(params.id),params.topics?{"topics":params.topics}:{},function(status,response){callback(status===200?new Notebook(response):new Notebook)})})};Notebook.getSharingInfo=function(id,callback){Notebook.api("GET",app.get("api_root")+"/notebooks/"+id+"/sharing",callback)};var Topic=Model.inherit({"beforeSave":function(){this.doc["commits:id"]=window.uuid()},"beforeDelete":function(callback){if(this._api_loaded)callback();else this.getLessons(function(lessons){var l=0,ll=lessons.length;var loop=function(){if(l++===ll)callback();lessons[l].remove(loop)}})}});Topic.collection="topics";Topic.fields=[":title","date:created","date:modified","date:deleted","commits:id"];Topic.sort="date:created";Topic.belongs_to("notebook",true);Topic.has_many("lessons");Topic.has_many("attachments");var Lesson=Model.inherit({"beforeSave":function(){this.doc["commits:id"]=window.uuid();if(!this.doc[":content"])this.doc[":content"]='<?xml version="1.0" encoding="utf-8"?>'+"\n"+"<root></root>"+"\n";this.doc[":textcontent"]=this.constructor.stripXML(this.doc[":content"]||"")}});Lesson.collection="lessons";Lesson.fields=["lesson:number","lesson:date",":content","date:created","date:modified","date:deleted","commits:id"];Lesson.sort="date:created";Lesson.belongs_to("topic",true);
Lesson.stripXML=function(html){return html.replace(/<(\/\w|text|paragraph|h1|h2|h3|code|table|image|video|audio)(\s[^>]+)?>/g," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").replace(/(^\s*|\s*$)/g,"")};window.Attachment=Model.inherit({beforeSave:function(){this.doc["commits:id"]=window.uuid()}});Attachment.collection="attachments";Attachment.fields=[":title","files:data","files:size","files:type","date:created","date:modified","commits:id"];Attachment.sort=":title";Attachment.belongs_to("topic",true);var AttachmentStorage=function(topic){this.topic=topic;this.onstore=function(){}};
AttachmentStorage.prototype.store=function(file,data,callback){var self=this;var attachment=new Attachment;attachment.generateId();attachment[":title"]=file.name;attachment["files:type"]=file.type;attachment["files:size"]=file.size;attachment["files:data"]=data;attachment.updateTimestamp("date:created","date:modified");attachment.parent=this.topic.id;attachment.save(function(err){if(err instanceof Error)return callback(err);callback(null);self.onstore(attachment)})};
AttachmentStorage.prototype.connect=function(callback){callback(null)};AttachmentStorage.prototype.disconnect=function(callback){callback(null)};window.AttachmentStorage=AttachmentStorage;var Request=Model.inherit();Request.collection="requests";Request.fields=[":type","requests:subject","requests:origin","requests:target","date:created","date:modified"];Request.sort="date:created";Request.prototype.respond=function(action,callback){var request=this;this.constructor.api("POST",this._getResponseUrl(),{action:action},function(status,response){if(status===204&&app.MODE==="offline")request.remove({online:false},function(){callback(status,response)});else callback(status,response)})};
Request.prototype._getResponseUrl=function(){switch(this[":type"]){case "sharing":return app.get("api_root")+"/notebooks/"+this["requests:subject"]+"/sharing/"+this["requests:target"]}};window.Search=Function.inherit();Search.query=function(q,callback){if(/^\s*$/.test(q))return callback(null);if(app.MODE==="offline")this._getLocalResults(q,callback);else this._getRemoteResults(q,callback)};
Search._getLocalResults=function(q,callback){q=q.split(/\s+/g).compact();if(q.length===0)return callback(null);var scopes={"users":[User,"users:realname",q],"notebooks":[Notebook,":title",q],"topics":[Topic,":title",q],"lessons":[Lesson,":textcontent",q],"attachments":[Attachment,":title",q]};var output={};var iter=new Iterator(Object.keys(scopes),function(key,next){var scope=scopes[key];scope[0].search(scope[1],scope[2],function(results){output[key]=results;next()})});iter.run(function(){callback(output)})};
Search._getRemoteResults=function(q,callback){Model.api("GET",app.get("api_root")+"/search",{"q":q},function(status,response){if(status!==200)return callback(null);callback({"users":response["users"]||[],"notebooks":response["notebooks"]||[],"topics":response["topics"]||[]})})};var Changes=function(){};Changes.request=function(callback){app.getState(function(state){var ts=Number(state["last_change_ts"])||0;Changes.requestSince(ts,function(status,ts){app.setState("last_change_ts",ts,function(){callback(status)})})})};
Changes.requestSince=function(ts,callback){var original_mode=app.MODE;app.MODE="offline";var finish=function(status,ts){app.MODE=original_mode;Changes.ts=ts;Changes.fire("idle");callback(status,ts)};var uri=app.get("api_root")+"/changes";var params={"since":ts,"attachment_data":true};Model.api("GET",uri,params,function(status,response){if(status===200&&response["changes"])Changes.handleScopedChanges_(response["changes"],function(){finish(status,response["ts"])});else finish(status,ts)});Changes.fire("downloading")};
Changes.handleScopedChanges_=function(infos,callback){var keys=Object.keys(infos);var handlers=Changes.scopeHandlers;(function scopeIter(){var key=keys.shift();if(!key)return callback();var scope=infos[key];if(scope instanceof Array)(function itemIter(){var item=scope.shift();if(item)handlers[key](item,itemIter);else scopeIter()})();else handlers[key](scope,scopeIter)})()};
Changes.removeItemOperationsFromQueue=function(id){var queue=app.getQueue();queue.filter(function(op){var input=op.input;return op instanceof ApiOperation===false||input[0]!=="DELETE"&&input[2]["_id"]!==id})};Changes.scopeHandlers={};
Changes.scopeHandlers["current_user"]=function(info,callback){var user=app.current_user;user["users:realname"]=info["users:realname"];user["users:username"]=info["users:username"];user["facebook:id"]=info["facebook:id"];user["facebook:picture"]=info["facebook:picture"];user["date:created"]=info["date:created"];user["premium:expires"]=info["premium:expires"];user.save({online:false},callback)};
Changes.scopeHandlers["friends"]=function(info,callback){var update=function(user){Changes.removeItemOperationsFromQueue(info["_id"]);if(info["_deleted"])return user.remove({online:false},callback);user.id=info["_id"];user["users:realname"]=info["users:realname"];user["users:username"]=info["users:username"];user["users:gender"]=info["users:gender"];user["facebook:id"]=info["facebook:id"];user["facebook:picture"]=info["facebook:picture"];user["date:created"]=info["date:created"];user.save({online:false},
callback)};var friend=app.current_user.friends.filter(function(user){return user.id===info["_id"]})[0];if(friend)update(friend);else User.one(info["_id"],{online:false},function(user){update(user);app.current_user.friends.push(user)})};
Changes.scopeHandlers["notebooks"]=function(info,callback){Notebook.one(info["_id"],{online:false},function(notebook){Changes.removeItemOperationsFromQueue(info["_id"]);if(info["_deleted"])return notebook.remove({online:false},callback);if(notebook["commits:id"]===info["_commit"])return callback();notebook.id=info["_id"];notebook.parent=info._parent;notebook[":title"]=info[":title"];notebook[":professor"]=info[":professor"];notebook[":year"]=info[":year"];notebook["date:created"]=info["date:created"];
notebook["date:modified"]=info["date:modified"];notebook["commits:id"]=info["_commit"];notebook.doc.readable=Boolean(info.readable);notebook.doc.writable=Boolean(info.writable);notebook.save({online:false},callback)})};
Changes.scopeHandlers["topics"]=function(info,callback){Topic.one(info["_id"],{online:false},function(topic){Changes.removeItemOperationsFromQueue(info["_id"]);if(info["_deleted"])return topic.remove({online:false},callback);if(topic["commits:id"]===info["_commit"])return callback();topic.id=info["_id"];topic.parent=info._parent;topic[":title"]=info[":title"];topic["date:created"]=info["date:created"];topic["date:modified"]=info["date:modified"];topic["commits:id"]=info["_commit"];topic.save({online:false},
callback)})};
Changes.scopeHandlers["lessons"]=function(info,callback){Lesson.one(info["_id"],{online:false},function(lesson){Changes.removeItemOperationsFromQueue(info["_id"]);if(info["_deleted"])return lesson.remove({online:false},callback);if(lesson["commits:id"]===info["_commit"])return callback();lesson.id=info["_id"];lesson.parent=info._parent;lesson["lesson:number"]=info["lesson:number"];lesson["lesson:date"]=info["lesson:date"];lesson[":content"]=info[":content"];lesson["date:created"]=info["date:created"];lesson["date:modified"]=
info["date:modified"];lesson["commits:id"]=info["_commit"];lesson.save({online:false},callback)})};
Changes.scopeHandlers["requests"]=function(info,callback){Request.one(info["_id"],{online:false},function(request){if(info["_deleted"])return request.remove({online:false},callback);request.id=info["_id"];request[":type"]=info[":type"];request["requests:subject"]=info["requests:subject"];request["requests:origin"]=info["requests:origin"];request["requests:target"]=info["requests:target"];request["date:created"]=info["date:created"];request["date:modified"]=info["date:modified"];request.save({online:false},
callback)})};
Changes.scopeHandlers["attachments"]=function(info,callback){Attachment.one(info["_id"],{online:false},function(attachment){if(info["_deleted"])return attachment.remove({online:false},callback);if(attachment["commits:id"]===info["_commit"])return callback();attachment.id=info["_id"];attachment.parent=info._parent;attachment[":title"]=info[":title"];attachment["files:data"]=info["files:data"];attachment["files:size"]=info["files:size"];attachment["files:type"]=info["files:type"];attachment["date:created"]=info["date:created"];
attachment["date:modified"]=info["date:modified"];attachment.save({online:false},callback)})};var _BaseController=Controller.inherit({"startup":function(){var that=this;app.current_user=null;app.sync=function(callback){if(that._change_checking_timeout)clearTimeout(that._change_checking_timeout);Changes.request(function(status){if(typeof callback==="function")callback(status);that._change_checking_timeout=setTimeout(app.sync,app.get("sync_delay"))})};if(this.constructor===SessionController)return;var processSession=function(session){if(session.stored){if(app.MODE==="offline")app.namespace=
session.parent;session.getParent(function(user){if(user.stored){app.current_user=user;app.namespace=user.id;user.getFriends(function(friends){user.friends=friends;if(app.MODE==="offline")that._startChangeChecking(function(){that._buildLayout();that.view()});else{that._buildLayout();that.view()}})}else{app.MODE="online";that._buildLayout();that.view()}})}else{app.MODE="online";that._buildLayout();that.view()}};if(app.MODE==="offline")Session.one({},{"online":false},processSession);else Session.fetch(processSession);
return false},"terminate":function(message){var content=app.component("content");var box=app.component("content.box",{"class":"message"});content.attach("parts",box);var section=app.component("content.box.section-message");box.attach("sections",section);var section_content=app.component("content.box.section-message.content",{message:message});section.attach("content",section_content);app.layout.replace("content",content)},"_buildLayout":function(){var layout=app.component("layout");app.layout=layout;
layout.data.home_link=app.current_user?app.link("user:",{"username":app.current_user["users:username"]}):app.link("default:");layout.data.current_user=app.current_user;document.body.html("");if(typeof layout.beforeRender==="function")layout.beforeRender();document.body.insert(layout.render());if(typeof layout.afterRender==="function")layout.afterRender();this._buildWidgets();this._buildToolbar()},"_buildToolbar":function(){var toolbar=app.component("toolbar");app.toolbar=toolbar;app.layout.replace("toolbar",
toolbar);var self=this;toolbar.element.addEventListener("click",function(e){var target=e.target;while(target.tagName!=="A"&&target!==toolbar.element)target=target.parentNode;switch(target.tagName){case "A":if(target.hasClassName("toggle")){var dropdown=target.parentNode.findOne(".dropdown");if(dropdown.style.display!=="none")dropdown.style.display="none";else dropdown.style.display=""}else{var list=target.parentNode.parentNode;var action=list.data("action");switch(action){case "block":toolbar.editor.setBlockType(target.data("type"));
break;case "inline":toolbar.editor.setInlineType(target.data("type"));break;case "list":var type=target.data("list");toolbar.editor.setListType(type==="none"?null:type);break;case "insert":switch(target.data("type")){case "drawing":self.insertDrawing_(toolbar.editor);break}break}}break}},false)},insertDrawing_:function(editor){if(!app.current_user.isPremium())return false;var ui=document.createElement("div");var drawing=new awesomeCanvas.Editor(ui);var block=editor.addStandaloneBlock("image","drawing",
drawing);block.appendChild(ui);block.addClassName("active");drawing.build();return true},_buildUserBreadcrumb:function(user){var current_user=app.current_user;var breadcrumb=app.component("breadcrumb",{"class":"user "+user["users:gender"],link:app.link("user:",{username:user["users:username"]}),label:user["users:realname"]});if(current_user){var dropdown=app.component("breadcrumb.ul");dropdown.attach("items",app.component("breadcrumb.ul.item",{"class":"user "+current_user["users:gender"],label:current_user["users:realname"],
link:app.link("user:",{username:current_user["users:username"]})}));breadcrumb.attach("dropdown",dropdown);var friends=current_user.friends;if(friends&&friends.length!==0){dropdown=app.component("breadcrumb.ul");friends.forEach(function(friend){dropdown.attach("items",app.component("breadcrumb.ul.item",{"class":"user "+friend["users:gender"],label:friend["users:realname"],link:app.link("user:",{username:friend["users:username"]})}))});breadcrumb.attach("dropdown",dropdown)}}return breadcrumb},"_startChangeChecking":function(callback){var that=
this;this._change_checking_timeout=setTimeout(function(){app.getState(function(state){if(app.layout)if(!state.last_change_ts){that._buildSyncDialog();app.sync(function(status){app.MODE=status===200?"offline":"online";that._destroySyncDialog();callback()})}else{app.widgets.sync.addClassName("syncing");app.sync(function(){app.widgets.sync.removeClassName("syncing")});callback()}else if(!state.last_change_ts){window.boot_loader.setProgress(null);window.boot_loader.setTitle(app.lang("sync.syncing"));
app.sync(function(status){app.MODE=status===200?"offline":"online";callback()})}else{callback();app.sync()}})},0)},"_buildSyncDialog":function(){var dialog=app.component("dialog",{"id":"sync-dialog","title":app.lang("sync.syncing")});app.layout.attach("dialog",dialog);app.layout.cover.show();app.layout.rerender("dialog");this._sync_dialog=dialog},"_destroySyncDialog":function(){app.layout.remove("dialog");app.layout.rerender("dialog");app.layout.cover.hide()},"_buildWidgets":function(){app.widgets=
{};app.layout.widgets=app.widgets;var group=app.component("header.widget-group");group.attach("widgets",this._buildSearchWidget());app.layout.attach("widget-groups",group);if(window.OFFLINE_SUPPORTED_BROWSER){var group=app.component("header.widget-group");group.attach("widgets",this._buildSyncWidget());app.layout.attach("widget-groups",group)}app.layout.rerender("widget-groups",true)},"_buildSearchWidget":function(){var widget=app.component("header.widget-simple",{"class":"search","title":app.lang("search")});
app.widgets.search=widget;var dropdown=app.component("header.widget.dropdown-search");widget.addEventListener("show",function(){this.element.findOne("input").focus();app.layout.hideOtherWidgets(widget)},false);widget.attach("dropdown",dropdown);widget.addEventListener("search",function(event){Search.query(event.detail,function(results){dropdown.remove("results");if(results===null)return;var index=0;results.users.forEach(function(user){dropdown.attach("results",app.component("header.widget.dropdown-search.item",
{"index":index++,"class":"user "+user["users:gender"],"title":user["users:realname"],"link":app.link("user:",{username:user["users:username"]})}))});results.notebooks.forEach(function(notebook){dropdown.attach("results",app.component("header.widget.dropdown-search.item",{"index":index++,"class":"notebook","title":notebook[":title"],"content":notebook.owner?notebook.owner["users:realname"]:null,"link":app.link("notebook:",{id:notebook.id})}))});results.topics.forEach(function(topic){dropdown.attach("results",
app.component("header.widget.dropdown-search.item",{"index":index++,"class":"topic","title":topic[":title"],"content":"("+topic.parent[":title"]+") "+(topic.snippet||""),"link":app.link("notebook:",{id:topic.parent,topics:topic.id})}))});dropdown.showResults()})},false);return widget},"_buildSyncWidget":function(){var widget=app.component("header.widget-simple",{"class":"sync","title":app.lang("sync")});app.widgets.sync=widget;widget.addEventListener("show",function(){app.layout.hideOtherWidgets(widget)},
false);var dropdown=app.component("header.widget.dropdown-sync");widget.attach("dropdown",dropdown);dropdown.setState(0);dropdown.setTime(Changes.ts);var __addListeners=function(){var queue=app.getQueue();queue.addEventListener("idle",function(){dropdown.setState(0,this.items.length)},false);queue.addEventListener("item",function(){dropdown.setState(1,this.items.length)},false);Changes.addEventListener("idle",function(){dropdown.setState(0,queue.items.length);dropdown.setTime(Changes.ts)},false);
Changes.addEventListener("downloading",function(){dropdown.setState(2)},false)};var queue=app.getQueue();if(queue)__addListeners();else app.addEventListener("queueset",__addListeners,false);return widget}});
(function(){var dateFormat=function(){var token=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[\-+]\d{4})?)\b/g,timezoneClip=/[^\-+\dA-Z]/g,pad=function(val,len){val=String(val);len=len||2;while(val.length<len)val="0"+val;return val};return function(date,mask,utc){var dF=dateFormat;if(arguments.length===1&&Object.prototype.toString.call(date)==="[object String]"&&
!/\d/.test(date)){mask=date;date=undefined}date=date?new Date(date):new Date;if(isNaN(date))throw SyntaxError("invalid date");mask=String(dF.masks[mask]||mask||dF.masks["default"]);if(mask.slice(0,4)==="UTC:"){mask=mask.slice(4);utc=true}var _=utc?"getUTC":"get",d=date[_+"Date"](),D=date[_+"Day"](),m=date[_+"Month"](),y=date[_+"FullYear"](),H=date[_+"Hours"](),M=date[_+"Minutes"](),s=date[_+"Seconds"](),L=date[_+"Milliseconds"](),o=utc?0:date.getTimezoneOffset(),flags={d:d,dd:pad(d),ddd:dF.i18n.dayNames[D],
dddd:dF.i18n.dayNames[D+7],m:m+1,mm:pad(m+1),mmm:dF.i18n.monthNames[m],mmmm:dF.i18n.monthNames[m+12],yy:String(y).slice(2),yyyy:y,h:H%12||12,hh:pad(H%12||12),H:H,HH:pad(H),M:M,MM:pad(M),s:s,ss:pad(s),l:pad(L,3),L:pad(L>99?Math.round(L/10):L),t:H<12?"a":"p",tt:H<12?"am":"pm",T:H<12?"A":"P",TT:H<12?"AM":"PM",Z:utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,""),o:(o>0?"-":"+")+pad(Math.floor(Math.abs(o)/60)*100+Math.abs(o)%60,4),S:["th","st","nd","rd"][d%10>3?0:(d%100-d%10!==
10)*d%10]};return mask.replace(token,function($0){return $0 in flags?flags[$0]:$0.slice(1,$0.length-1)})}}();dateFormat.masks={"default":"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed",
"Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]};Date.prototype.format=function(mask,utc){return dateFormat(this,mask,utc)}})();
var ComponentWithButtons=Component.inherit(function(){this._buttons={};this._default_buttons=[];this._shown_buttons=[]},{"afterRender":function(){if(JSON.stringify(this._shown_buttons)!==JSON.stringify(this._default_buttons))this.showDefaultButtons()},"defineButtons":function(buttons){var _buttons=this._buttons;Object.getOwnPropertyNames(buttons).forEach(function(key){_buttons[key]=buttons[key]})},"showButtons":function(keys){var k,kk;if(keys instanceof Array!==true)keys=Array.prototype.slice.call(arguments);
this.remove("buttons");for(k=0,kk=keys.length;k<kk;++k){var button=this._buttons[keys[k]];if(button===undefined)throw"Invalid state: No such button ("+keys[k]+")";this.attach("buttons",button)}this.rerender("buttons");this._shown_buttons=keys},"showDefaultButtons":function(){this.showButtons(this._default_buttons)},"setDefaultButtons":function(keys){if(keys instanceof Array!==true)keys=Array.prototype.slice.call(arguments);this._default_buttons=keys}});
app.registerComponent("layout",Component.inherit(function(){this.popovers=[]},{"_template":'<div id="layout">'+'<div id="header">'+'<a class="logo" href="<%= home_link %>">'+'<span class="loading"></span>'+"</a>"+'<ul class="breadcrumbs" components="breadcrumbs"></ul>'+'<div class="user-options">'+"<% if (current_user) { %>"+'<div class="identity <%= current_user["users:gender"] %>"><div>'+'<a href="<%= app.link("user:", { username: current_user["users:username"] }) %>" class="realname"><%= current_user["users:realname"] %></a> '+
'<span class="signout"><a href="<%= app.link("session:signout") %>"><%= app.lang("session.signout") %></a></span>'+'<span class="resignin"><a href="<%= app.link("session:signin") %>"><%= app.lang("session.re-signin") %></a></span>'+"</div></div>"+"<% } else { %>"+'<div class="identity"><div>'+'<a href="<%= app.link("session:signin") %>"><%= app.lang("session.signin") %></a> '+'<span><a href="<%= app.link("session:signin") %>"><%= app.lang("session.register") %></a></span>'+"</div></div>"+"<% } %>"+
'<div components="widget-groups"></div>'+"<% if (current_user && !current_user.isPremium()) { %>"+'<div class="premium">'+'<button><%= app.lang("premium.header-upgrade") %></button>'+"</div>"+"<% } %>"+"</div>"+"</div>"+'<div components="toolbar"></div>'+'<div components="content"></div>'+'<div id="popovers"></div>'+'<div id="layout-cover" style="display: none;"></div>'+'<div components="dialog"></div>'+"</div>","afterRender":function(){this.modes={};this.logo=this.element.findOne(".logo");document.addEventListener("flowoff:callstart",
function(){this.logo.addClassName("loading")}.bind(this),false);document.addEventListener("flowoff:callend",function(){this.disableAllModes();this.logo.removeClassName("loading")}.bind(this),false);document.addEventListener("flowoff:sessionexpire",function(){this.invalidateIdentity()}.bind(this),false);if(document.sessionexpired)this.invalidateIdentity();var session_refresh_el=this.element.findOne(".resignin a");if(session_refresh_el){session_refresh_el.href="javascript:;";session_refresh_el.addEventListener("click",
function(e){e.preventDefault();var showRefreshSessionLayoutCover=function(){app.layout.cover.show();app.layout.cover.html("Waiting for a session refresh&hellip;")};var hideRefereshSessionLayoutCover=function(){app.layout.cover.html("");app.layout.cover.hide()};var openRefreshSessionWindow=function(){var options="status=1,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=0,width=620,height=400";var win=window.open("","sessionexpire",options);if(win){showRefreshSessionLayoutCover();
var body=win.document.body;var style=body.style;style.fontFamily="sans-serif";style.fontSize="13px";style.textAlign="center";style.padding="20px";body.innerHTML="Loading&hellip;"}return win};var redirectRefreshSessionWindowToFacebook=function(win){var body=win.document.body;body.innerHTML="Redirecting to the session engine&hellip;";win.location.href="/session?display=popup&redirect_uri="+encodeURIComponent("/FINISH")};var checkSession=function(callback){Model.api("GET",app.get("api_root")+"/session",
callback)};var waitForRefreshSessionToFinish=function(win){var clear=function(){clearInterval(interval);hideRefereshSessionLayoutCover()};var checkWindowState=function(){if(win.closed){clear();checkSession(function(status,response){if(response&&response["_id"]===app.current_user.id)app.layout.validateIdentity();else app.redirect("session:")})}else try{var pathname=win.location.pathname;if(pathname==="/registration")window.location.href=pathname}catch(err){}};var interval=setInterval(checkWindowState,
1E3)};showRefreshSessionLayoutCover();var win=openRefreshSessionWindow();checkSession(function(status,response){if(status!==401){app.layout.validateIdentity();win.close();hideRefereshSessionLayoutCover()}else if(win){redirectRefreshSessionWindowToFacebook(win);waitForRefreshSessionToFinish(win)}})},false)}this.popovers=this.element.findOne("#popovers");this.element.addEventListener("click",this.hidePopovers_.bind(this),false);Changes.addEventListener("currentuserchange",function(){var link=app.link("user:",
{username:app.current_user["users:username"]});this.element.findOne(".logo").attr("href",link);var realname=this.element.findOne(".identity .realname");if(realname)realname.attr("href",link)}.bind(this),false);this.cover=document.getElementById("layout-cover");function onUpgradeButtonClick(){this.style.opacity="0.5";Model.api("GET",app.get("api_root")+"/session",function(status){if(status===0)alert("You need to be connected to the Internet to upgrade your account.");else window.location.href="/registration?upgrade"})}
var premium_button=this.element.findOne(".premium button");if(premium_button)premium_button.addEventListener("click",onUpgradeButtonClick,false)},"replace":function(key,components){var result=this.$super(key,components);if(key==="content"){this.hidePopovers_();document.fire("flowoff:callend")}else if(key==="breadcrumbs"){var count=components instanceof Array?components.length:1;this.element.findOne("#header .breadcrumbs").data("count",count)}return result},"registerPopover":function(popover){this.popovers.insert(popover)},
hidePopovers_:function(){this.popovers.childNodes.forEach(function(popover){popover.data("id","");popover.remove()})},"invalidateIdentity":function(){var identity=this.element.findOne(".identity");identity.addClassName("invalid")},"validateIdentity":function(){document.sessionexpired=false;var identity=this.element.findOne(".identity");identity.removeClassName("invalid")},"enableMode":function(key){this.modes[key]=app.data.params;this.element.addClassName(key+"-mode")},"disableMode":function(key){this.element.removeClassName(key+
"-mode");delete this.modes[key]},"disableAllModes":function(){var cur=app.data.params;Object.keys(this.modes).forEach(function(key){var old=this.modes[key];if(old!==undefined&&(cur._c!==old._c||cur._v!==old._v))this.disableMode(key)},this)},"enableEditingMode":function(){if(this.getAttached("toolbar").length===0)console.warn("Cannot enable editing mode: Missing toolbar component");else this.enableMode("editing")},"hideOtherWidgets":function(widget){var widgets=this.widgets;Object.keys(widgets).forEach(function(key){var w=
widgets[key];if(w!==widget){w.removeClassName("active");w.fire("hide")}})}}));
app.registerComponent("toolbar",Component.inherit({"_template":'<div id="toolbar">'+'<div class="controls">'+'<div class="group inline">'+'<ul data-action="inline">'+'<li><a data-type="strong" href="javascript:;" title="<%= app.lang("editor.inline.strong") %>"></a></li>'+'<li><a data-type="em" href="javascript:;" title="<%= app.lang("editor.inline.emphasised") %>"></a></li>'+'<li><a data-type="u" href="javascript:;" title="<%= app.lang("editor.inline.underlined") %>"></a></li>'+'<li><a data-type="strike" href="javascript:;" title="<%= app.lang("editor.inline.strike") %>"></a></li>'+
"</ul>"+"</div>"+'<div class="group block">'+'<ul data-action="block">'+'<li><a data-type="text" href="javascript:;" title="<%= app.lang("editor.block.text") %>"><span>Abcdef</span></a></li>'+'<li><a data-type="h1" href="javascript:;" title="<%= app.lang("editor.block.h1") %>"><span>Abc</span></a></li>'+'<li><a data-type="h2" href="javascript:;" title="<%= app.lang("editor.block.h2") %>"><span>Abc</span></a></li>'+'<li><a data-type="h3" href="javascript:;" title="<%= app.lang("editor.block.h3") %>"><span>Abcd</span></a></li>'+
"</ul>"+'<a class="toggle" href="javascript:;"></a>'+'<div class="dropdown" style="display: none;">'+'<ul data-action="block">'+'<li><a data-type="quote" href="javascript:;" title="<%= app.lang("editor.block.quote") %>"><span>Abcd</span></a></li>'+'<li><a data-type="code" href="javascript:;" title="<%= app.lang("editor.block.code") %>"><span>Abcde</span></a></li>'+"</ul>"+"</div>"+"</div>"+'<div class="group list">'+'<ul data-action="list">'+'<li><a data-list="none" href="javascript:;"><span></span></a></li>'+
'<li><a data-list="dash" href="javascript:;"><span></span></a></li>'+'<li><a data-list="disc" href="javascript:;"><span></span></a></li>'+'<li><a data-list="arrow" href="javascript:;"><span></span></a></li>'+'<li><a data-list="fat-arrow" href="javascript:;"><span></span></a></li>'+"</ul>"+"</div>"+'<div class="group inline">'+'<ul data-action="insert">'+"<% if (app.current_user && app.current_user.isPremium()) { %>"+'<li><a data-type="drawing" href="javascript:;" title="<%= app.lang("editor.drawing") %>"></a></li>'+
"<% } %>"+"</ul>"+"</div>"+"</div>"+'<div class="cover"></div>'+"</div>","afterRender":function(){this._cover=this.element.findOne(".cover")},"activate":function(editor){this.editor=editor;this._cover.hide()},"deactivate":function(){this._cover.show()}}));
app.registerComponent("button",Component.inherit({"_template":"<li>"+'<a href="<% if (typeof link !== "undefined") { %><%= link %><% } else { %>javascript:;<% } %>" class="button<%= component.data["class"] !== undefined ? " " + component.data["class"] : "" %>">'+"<span></span><%= label %></a>"+"</a>"+"</li>","afterRender":function(){this.element.addEventListener("click",function(e){this.fire("click")}.bind(this),false)}}));
app.registerComponent("breadcrumb",Component.inherit({"_template":'<li<%= component.data["class"] !== undefined ? \' class="\' + component.data["class"] + \'"\' : "" %>>'+'<% if (typeof link !== "undefined") { %><a href="<%= link %>"><%= label %></a>'+'<% if (typeof note !== "undefined") { %> <small><%= note %></small><% } %></a><% } else { %><%= label %><% } %>'+'<% if (component.getAttached("dropdown").length) { %>'+'<div class="dropdown">'+'<div class="content" components="dropdown"></div>'+'<span class="before"></span>'+
"</div>"+"<% } %>"+"</li>"}));app.registerComponent("breadcrumb.ul",Component.inherit({"_template":'<ul components="items"></ul>'}));
app.registerComponent("breadcrumb.ul-multiple",app.getComponent("breadcrumb.ul").inherit({"_template":"<form>"+'<ul components="items"></ul>'+'<div class="buttons">'+'<button type="submit">Show selected</button>'+"</div>"+"</form>","afterRender":function(){var that=this;this.element.addEventListener("submit",function(e){e.preventDefault();var checked=this.find('input[type="checkbox"]').filter(function(checkbox){return checkbox.checked});var values=checked.map(function(checkbox){return checkbox.value});
that.fire("select",values)},false)}}));app.registerComponent("breadcrumb.dl",Component.inherit({"_template":'<dl components="items"></dl>'}));app.registerComponent("breadcrumb.ul.item",Component.inherit({"_template":'<li<% if (component.data["class"]) { %> class="<%= component.data["class"] %>"<% } %>>'+'<% if (typeof link !== "undefined") { %><a href="<%= link %>"><%= label %></a><% } else { %><%= label %><% } %>'+"</li>"}));
app.registerComponent("breadcrumb.ul-multiple.item",Component.inherit({"_template":'<li<% if (component.data["class"]) { %> class="<%= component.data["class"] %>"<% } %>>'+'<% if (typeof value !== "undefined") { %> '+'<input type="checkbox" value="<%= value %>" <%= (selected.indexOf(value) > -1 ) ? "checked" : "" %> />'+"<% } %>"+'<% if (typeof link !== "undefined") { %>'+'<a href="<%= link %>"><%= label %></a>'+"<% } else { %>"+"<%= label %>"+"<% } %>"+"</li>",beforeRender:function(){this.data["selected"]=
this.data["selected"]||[]}}));app.registerComponent("breadcrumb.dl.title",Component.inherit({"_template":'<dt<% if (component.data["class"]) { %> class="<%= component.data["class"] %>"<% } %>>'+'<% if (typeof link !== "undefined") { %><a href="<%= link %>"><%= label %></a><% } else { %><%= label %><% } %>'+"</dt>"}));
app.registerComponent("breadcrumb.dl.item",Component.inherit({"_template":'<dd<% if (component.data["class"]) { %> class="<%= component.data["class"] %>"<% } %>>'+'<% if (typeof link !== "undefined") { %><a href="<%= link %>"><%= label %></a><% } else { %><%= label %><% } %>'+"</dd>"}));app.registerComponent("header.widget-group",Component.inherit({"_template":'<div class="group" components="widgets"></div>'}));
app.registerComponent("header.widget-simple",Component.inherit({"_template":'<div class="widget widget-simple<%= component.data["class"] ? " " + component.data["class"] : "" %>">'+'<a class="toggle" href="javascript:;" title="<%= title %>"></a>'+'<div class="dropdown">'+'<span class="before"></span>'+'<div components="dropdown"></div>'+"</div>"+"</div>","afterRender":function(){this.toggle_element=this.element.findOne(".toggle");if(this.toggle_element)this.toggle_element.addEventListener("click",
this.toggle.bind(this),false);if(this.icon)this.setIcon(this.icon)},"toggle":function(){var element=this.element;if(element.hasClassName("active")){element.removeClassName("active");this.fire("hide")}else{element.addClassName("active");this.fire("show")}},"setIcon":function(path){this.icon=path;if(this.element)this.element.style.backgroundImage="url('"+path+"')"},"addClassName":function(){this.element.addClassName.apply(this.element,arguments)},"removeClassName":function(){this.element.removeClassName.apply(this.element,
arguments)}}));
app.registerComponent("header.widget.dropdown-search",Component.inherit({"_template":'<div class="content content-search">'+"<form>"+'<p><input type="text" value="" placeholder="<%= app.lang("search.placeholder") %>" /></p>'+"</form>"+'<div><ul components="results"></ul></div>'+"</div>","afterRender":function(){var that=this;var q="";var form=this.element.findOne("form");var input=form.findOne("input");form.addEventListener("submit",function(e){e.preventDefault()},false);input.addEventListener("keydown",function(event){switch(event.keyCode){case 36:that.selectItem(0);
break;case 35:that.selectItem(that.maxIndex);break;case 38:that.selectItemAbove();event.preventDefault();break;case 40:that.selectItemBelow();event.preventDefault();break;case 33:that.selectItemPageAbove();event.preventDefault();break;case 34:that.selectItemPageBelow();event.preventDefault();break;case 13:that.go();event.preventDefault();break;case 27:that.resetForm();that.resetResults();break}},false);input.addEventListener("keyup",function(event){if(event.keyCode>=9&&event.keyCode<=47)return;var value=
input.value;that.parent.fire("search",typeof value==="string"?value:"")},false);this.form=form;this.results_element=this.element.findOne("ul").parentNode;this.selectedItemIndex=0;this.maxIndex=0},"selectItem":function(index,scroll){index=Number(index);var items=this.results_element.find("li");var item=items[index];var sel=items[this.selectedItemIndex];if(sel!==undefined)sel.removeClassName("selected");this.selectedItemIndex=index;if(item!==undefined)item.addClassName("selected");if(scroll===undefined)scroll=
true;if(scroll&&!!this.scrollbar)this.scrollbar.scrollToElement(item,20)},"selectItemAbove":function(){this.selectItem(this.selectedItemIndex-1<0?this.maxIndex:this.selectedItemIndex-1)},"selectItemPageAbove":function(){this.selectItem(this.selectedItemIndex-5<0?0:this.selectedItemIndex-5)},"selectItemBelow":function(){this.selectItem(this.selectedItemIndex+1>this.maxIndex?0:this.selectedItemIndex+1)},"selectItemPageBelow":function(){this.selectItem(this.selectedItemIndex+5>this.maxIndex?this.maxIndex:
this.selectedItemIndex+5)},"go":function(){var link=this.results_element.findOne("li.selected a");if(!!link)window.location.href=link.attr("href")},"resetForm":function(){this.form.reset()},"resetResults":function(){this.results_element.findOne("ul").html("")},"showResults":function(){this.rerender("results");this.selectItem(0);this.maxIndex=this.getAttached("results").length;this.scrollbar.update();this.scrollbar.scrollTo(0)}}));
app.registerComponent("header.widget.dropdown-search.item",Component.inherit({_template:'<li<%= component.data["class"] ? \' class="\' + component.data["class"] + \'"\' : "" %>>'+'<a href="<%= link %>">'+"<span></span>"+"<%= title %>"+'<%= content ? "<small>" + content + "</small>" : "" %>'+"</a>"+"</li>","afterRender":function(){var that=this;this.element.addEventListener("mouseover",function(){that.parent.selectItem(that.data.index,false)},false)}}));
app.registerComponent("header.widget.dropdown-sync",Component.inherit({"_template":'<div class="content content-sync">'+'<h2><%= app.lang("sync") %></h2>'+'<div class="state">&hellip;</div>'+'<p><%= app.lang("sync.lastDownload") %><br /><strong class="date">&hellip;</strong></p>'+'<p><button class="sync_now"><%= app.lang("sync.now") %></button></p>'+"</div>","afterRender":function(){this.state_element=this.element.findOne(".state");if(this.state!==undefined){this.setState(this.state,this.left);this.setTime(this.ts)}var sync_now_el=
this.element.findOne(".sync_now");sync_now_el.addEventListener("click",function(){sync_now_el.setAttribute("disabled",true);app.sync(function(){sync_now_el.removeAttribute("disabled")})},false)},"setTime":function(ts){this.ts=ts;if(this.element&&ts)this.element.findOne(".date").html((new Date(ts*1E3)).format(app.lang("format.dateTime")))},"setState":function(state,left){var that=this;this.left=left;if(this.rendered)switch(state){case 0:if(this.parent.rendered)this.parent.element.removeClassName("syncing");
if(this.state_element)this.state_element.removeClassName("active").html(left?app.lang("sync.uploadsLeft",{"left":left}):app.lang("sync.synced"));break;case 1:if(this.parent.rendered)this.parent.element.addClassName("syncing");if(this.state_element)this.state_element.addClassName("active").html(app.lang("sync.uploading",{"left":left}));break;case 2:if(this.parent.rendered)this.parent.element.addClassName("syncing");if(this.state_element)this.state_element.addClassName("active").html(app.lang("sync.downloading"));
break}this.state=state}}));
app.registerComponent("content",Component.inherit({"_template":'<div id="area-outer" class="content-area">'+'<div id="area-content-outer">'+'<div id="area-content">'+'<div id="area-content-inner" components="parts"></div>'+"</div>"+'<div id="footer">'+"<ul>"+'<li><a href="/support" target="_blank"><%= app.lang("link.support") %></a></li>'+'<li><a href="/tos" target="_blank"><%= app.lang("link.tos") %></a></li>'+'<li><a href="/pp" target="_blank"><%= app.lang("link.pp") %></a></li>'+"</ul>"+"<p>Copyright &copy; mySchoolNotebook s.r.o."+
"<% if (app.current_user) { %>"+"<% if (app.current_user.isPremium()) { %>"+' \u00b7 <%= app.lang("premium.expiresIn", { "days": Math.ceil((app.current_user["premium:expires"] - Math.round(Date.now() / 1000)) / (24 * 3600)) }) %>'+' \u00b7 <a href="javascript:;" class="premium-button"><strong><%= app.lang("premium.extend") %></strong></a>'+"<% } else { %>"+' \u00b7 <a href="javascript:;" class="premium-button"><strong><%= app.lang("premium.upgrade") %></strong</a>'+"<% } %>"+"<% } %>"+"</p>"+"</div>"+
"</div>"+"</div>",afterRender:function(){function onUpgradeButtonClick(){this.style.opacity="0.5";Model.api("GET",app.get("api_root")+"/session",function(status){if(status===0)alert("You need to be connected to the Internet to "+(app.current_user.isPremium()?"extend your premium membership.":"upgrade your account."));else window.location.href="/registration?upgrade"})}var premium_button=this.element.findOne("#footer .premium-button");if(premium_button)premium_button.addEventListener("click",onUpgradeButtonClick,
false)}}));app.registerComponent("content.options",Component.inherit({"_template":'<div class="area-options">'+'<ul class="options" components="buttons"></ul>'+'<% if (typeof previous !== "undefined") { %><span class="previous"><a href="<%= previous.link %>"><%= previous.label %></a></span><% } %>'+'<% if (typeof next !== "undefined") { %><span class="next"><a href="<%= next.link %>"><%= next.label %></a></span><% } %>'+"</div>"}));
app.registerComponent("content.box",Component.inherit({"_template":'<div class="box<%= component.data["class"] !== undefined ? " " + component.data["class"] : "" %>"<% if (component.data.id !== undefined) { %> id="<%= id %>"<% } %>>'+'<div components="title"></div>'+'<div components="sections"></div>'+"</div>"}));
app.registerComponent("content.box.title",ComponentWithButtons.inherit({"_template":'<div class="header"><div class="header-content">'+"<h2><%= title %></h2>"+'<ul class="options" components="buttons"></ul>'+"<%= component.renamable ? '<form style=\"display: none\"><input type=\"text\" /></form>' : '' %>"+"</div></div>",makeRenamable:function(){this.renamable=true;this._addRenamingButtons()},_addRenamingButtons:function(){var rename=app.component("button",{label:app.lang("button.rename")});rename.addEventListener("click",
function(){this.parent.enableEditing()});var save=app.component("button",{label:app.lang("button.save")});save.addEventListener("click",function(){this.parent.save()});var cancel=app.component("button",{label:app.lang("button.cancel")});cancel.addEventListener("click",function(){this.parent.disableEditing()});this.defineButtons({rename:rename,rename_save:save,rename_cancel:cancel})},save:function(){var h2=this.element.findOne("h2");var input=this.element.findOne("form input");var result=this.fire("rename",
input.value);if(result){h2.html(input.value.escapeHTML()).show();this.element.findOne("form").hide();this.showDefaultButtons()}else input.focus()},"enableEditing":function(){if(!this.renamable)return;var onSubmit=function(e){e.preventDefault();this.save();return false}.bind(this);var h2=this.element.findOne("h2");var input=this.element.findOne("form input");h2.hide();input.value=h2.innerText;var form=this.element.findOne("form");form.show();form.onsubmit=onSubmit;input.focus();input.select();this.showButtons("rename_save",
"rename_cancel")},disableEditing:function(){this.element.findOne("h2").show();this.element.findOne("form").hide();this.showDefaultButtons()}}));
app.registerComponent("content.box.section",Component.inherit({"_template":'<div class="section<%= component.data["class"] !== undefined ? " " + component.data["class"] : "" %>"<% if (component.data.id !== undefined) { %> id="<%= id %>"<% } %>>'+'<div components="title"></div>'+'<div components="content"></div>'+"</div>","useCollapse":function(key){if(!window.localStorage){console.info("It is not possible to make the section collapsible; the browser does not support local storage.");return}this.collapsible=
true;this.collapse_key=key;var result=window.localStorage["ui:collapse-"+key];this.collapsed=result==="1"},"activate":function(){this.element.addClassName("section-active")},"deactivate":function(){this.element.removeClassName("section-active")}}));
app.registerComponent("content.box.section-requests",ComponentWithButtons.inherit({"_template":'<div class="section-requests">'+'<% if (count > 1) { %><span class="toggle"></span><% } %>'+'<div class="items" components="items"></div>'+"</div>","afterRender":function(){var toggle=this.element.findOne(".toggle");var items=this.element.find(".items > div");if(items.length>1){toggle.show();var expanded=false;toggle.onclick=function(){expanded=!expanded;if(!expanded)toggle.removeClassName("toggle-expanded");
else toggle.addClassName("toggle-expanded")}}}}));
app.registerComponent("content.box.section-requests.item",ComponentWithButtons.inherit({"_template":'<div data-type="<%= request[":type"] %>">'+'<p><%= lang("requests." + request[":type"], component.data) %></p>'+'<ul class="options">'+'<li><a href="javascript:" class="button accept" data-action="accept">Accept</a></li>'+'<li><a href="javascript:" class="button" data-action="ignore">Ignore</a></li>'+"</ul>"+"</div>","afterRender":function(){this.parent.afterRender();var that=this;this.working=false;
var popover=app.component("popover-upgrade",{hide_title:true,message:app.lang("premium.accept_notebook_sharing.upgrade-popover.info"),position:"above"});popover.beforeRender();popover.render();popover.afterRender();app.current_user.isAllowedTo("accept","notebook_sharing",function(allowed){if(!allowed)that.element.findOne(".button.accept").style.opacity="0.5"});this.element.findOne(".options").addEventListener("click",function(e){var target=e.target;if(target.hasClassName("button")){that.working=true;
var respondToRequest=function(action){that.data.request.respond(action,function(status,response){that.working=false;if(status===204){that.element.remove();that.fire("close",action)}else that.fire("error",response.error)})};var action=target.data("action");if(action==="accept"){app.current_user.isAllowedTo("accept","notebook_sharing",function(allowed){if(allowed)respondToRequest(action);else{that.working=false;popover.show(target.parentElement)}});e.stopPropagation()}else respondToRequest(action)}},
false)}}));
app.registerComponent("content.box.section.title",ComponentWithButtons.inherit({"_template":'<div class="section-header">'+'<p class="layer status"></p>'+'<div class="section-header-content">'+'<ul class="options" components="buttons"></ul>'+'<% if (component.parent.collapsible) { %><span class="toggle<%= !component.parent.collapsed ? " toggle-expanded" : "" %>"></span><% } %>'+"<span><%= title %></span>"+"</div>"+"</div>","afterRender":function(){this.$super();if(!window.localStorage)console.info("It is not possible to collapse the section; the browser does not support local storage.");else{var parent=
this.parent;if(parent.collapsible)this.element.find(".toggle").first().addEventListener("click",function(){parent.collapsed=!parent.collapsed;parent.element.find(".content").first()[parent.collapsed?"hide":"show"]();if(!parent.collapsed)this.addClassName("toggle-expanded");else this.removeClassName("toggle-expanded");window.localStorage["ui:collapse-"+parent.collapse_key]=parent.collapsed?1:0},false)}},"setStatus":function(text){this.element.find(".status").first().html(text)}}));
app.registerComponent("content.box.section.content",Component.inherit({"_template":'<div class="content"><%= content %></div>',"afterRender":function(){if(this.parent.collapsible&&this.parent.collapsed)this.element.hide()}}));app.registerComponent("content.box.section-message",app._components["content.box.section"].inherit({}));
app.registerComponent("content.box.section-message.content",app._components["content.box.section.content"].inherit({"_template":"<div class=\"content content-message <%= (component.data['class']) ? component.data['class'] : '' %>\">"+"<%= message %>"+"</div>"}));app.registerComponent("dialog",Component.inherit({"_template":'<div class="dialog"<%= typeof id !== "undefined" ? \' id="\' + id + \'"\' : "" %>>'+"<%= title %>"+"</div>"}));
app.registerComponent("popover",Component.inherit({"_template":'<div class="popover left">'+'<div class="arrow"></div>'+'<div class="inner">'+'<h3 class="title"><%= title %></h3>'+'<div class="content">'+"<p><%= content %></p>"+"</div>"+"</div>"+"</div>"}));
app.registerComponent("popover-upgrade",app.getComponent("popover").inherit({"_template":'<div class="popover <%= position %> upgrade">'+'<div class="arrow"></div>'+'<div class="inner">'+'<% if (!hide_title) { %><h3 class="title"><%= title %></h3><% } %>'+'<div class="content">'+"<p><%= message %></p>"+'<button class="upgrade"><%= app.lang("premium.upgrade") %></button>'+'<p><a target="_blank" href="/functions#premium"><%= app.lang("premium.upgrade-popover.more-info") %></a></p>'+"</div>"+"</div>"+
"</div>",beforeRender:function(){this.data.hide_title=typeof this.data.hide_title==="undefined"?false:this.data.hide_title;this.data.title=this.data.title||app.lang("premium.upgrade-popover.title");this.data.message=this.data.message||app.lang("premium.upgrade-popover.info");this.data.position=this.data.position||"left"},afterRender:function(){this.element.addEventListener("click",function(e){e.stopPropagation()},false);this.element.findOne("button.upgrade").addEventListener("click",function(e){Model.api("GET",
app.get("api_root")+"/session",function(status){if(status===0)alert("You need to be connected to the Internet to upgrade your account.");else window.location.href="/registration?upgrade"})},false)},show:function(btn){var popover_el=this.element;var arrow_el=popover_el.findOne(".arrow");var btn_id=btn.data("id")?btn.data("id"):btn.innerHTML;if(popover_el.data("id")===btn_id){popover_el.data("id","");return popover_el.remove()}popover_el.data("id",btn_id);app.layout.registerPopover(popover_el);popover_el.style.display=
"block";var btn_rect=btn.getBoundingClientRect();var popover_rect=popover_el.getBoundingClientRect();switch(this.data.position){case "left":popover_el.style.top=btn_rect.top+(btn_rect.bottom-btn_rect.top)/2-(popover_rect.bottom-popover_rect.top)/2+"px";popover_el.style.right=window.innerWidth-btn_rect.left+7+"px";break;case "right":popover_el.style.top=btn_rect.top+(btn_rect.bottom-btn_rect.top)/2-(popover_rect.bottom-popover_rect.top)/2+"px";popover_el.style.right=window.innerWidth-btn_rect.right-
(popover_rect.right-popover_rect.left)+"px";break;case "below":popover_el.style.top=btn_rect.bottom+"px";var left=btn_rect.left+(btn_rect.right-btn_rect.left)/2-(popover_rect.right-popover_rect.left)/2;popover_el.style.left=left<0?"0px":left+"px";arrow_el.style.left=left<0?btn_rect.left+(btn_rect.right-btn_rect.left)/2+"px":"";break;case "above":popover_el.style.top=btn_rect.top-(popover_rect.bottom-popover_rect.top)+"px";var left=btn_rect.left+(btn_rect.right-btn_rect.left)/2-(popover_rect.right-
popover_rect.left)/2;popover_el.style.left=left<0?"0px":left+"px";arrow_el.style.left=left<0?btn_rect.left+(btn_rect.right-btn_rect.left)/2+"px":"";break}}}));var DefaultController=_BaseController.inherit({"default":function(params){if(app.current_user===null)app.redirect("session:signin");else app.redirect("user:",{"username":app.current_user["users:username"]})}});var SessionController=_BaseController.inherit({"startup":function(){this.$super()},"signin":function(){var that=this;app.MODE=app.ORIGINAL_MODE;Session.fetch(function(session){session.getParent(function(owner){if(owner.stored){app.namespace=owner.id;app.current_user=owner;owner.getFriends(function(friends){owner.friends=friends;that._buildLayout();if(app.MODE==="offline")that._startChangeChecking(function(){app.redirect("user:",{"username":owner["users:username"]})});else app.redirect("user:",{"username":owner["users:username"]})})}})})},
"signout":function(){Session.destroy(function(err){if(err)alert(err.message);else window.location.href="/"})}});(function(){var __bind=function(fn,me){return function(){return fn.apply(me,arguments)}};window.NotebookController=window._BaseController.inherit({"default":function(params){if(!params.id)app.redirect("default:");return Notebook.getViewData(params,__bind(function(notebook,status){if(!notebook.stored)switch(status){case 0:case 404:return this.terminate(app.lang("notebook.notExists"));case 403:return this.terminate(app.lang("notebook.notPublic"));default:return this.terminate(app.lang("error.unknown"))}return this._renderNotebook(notebook,
params)},this))},"sharing":function(params){var current_user,options,selector;if(!params.id)app.redirect("default:");current_user=app.current_user;selector={_id:params.id};options={online:!current_user};return Notebook.one(selector,options,__bind(function(notebook,status){if(!notebook.stored)switch(status){case 0:case 404:return this.terminate(app.lang("notebook.notExists"));case 403:return this.terminate(app.lang("notebook.notPublic"));default:return this.terminate(app.lang("error.unknown"))}return this._renderSharingOf(notebook)},
this))},_renderNotebook:function(notebook,params){return notebook.getParent(__bind(function(owner){var breadcrumbs;if(!owner.stored)return this.terminate(app.lang("error.unknown"));breadcrumbs=[];breadcrumbs.push(this._buildUserBreadcrumb(owner));breadcrumbs.push(this._buildNotebookBreadcrumb(notebook,owner));this._notebook=notebook;this.content=app.component("content");this._renderNotebookOptions(notebook,owner);this._renderAttachmentPopover();this._renderUpgradePopover();return notebook.getTopics(__bind(function(topics){this.topics_=
topics;var open_ids;if(!notebook.writable&&topics.length===0){this._renderMessage(app.lang("notebook.empty"));app.layout.replace("content",this.content)}else{open_ids=this._getOpenTopicIds(topics,params);this._renderTopics(topics,open_ids);if(!!notebook.writable)app.layout.enableEditingMode();app.layout.replace("content",this.content);if(params.rename)this.content.getAttached("parts").forEach(function(part){if(part.NAME==="content.box-topic")return part.getAttached("title").first().enableEditing()});
if(topics.length)breadcrumbs.push(this._buildTopicBreadcrumb(topics,open_ids,notebook))}return app.layout.replace("breadcrumbs",breadcrumbs)},this))},this))},_renderSharingOf:function(notebook){return notebook.getParent(__bind(function(owner){var box,breadcrumbs,content;breadcrumbs=[];breadcrumbs.push(this._buildUserBreadcrumb(owner));breadcrumbs.push(this._buildNotebookBreadcrumb(notebook,owner));breadcrumbs.push(this._buildSharingBreadcrumb(notebook));this._notebook=notebook;this.content=content=
app.component("content");box=this._buildSharingBox();content.attach("parts",box);return Notebook.getSharingInfo(notebook.id,__bind(function(status,info){switch(status){case 200:this._renderSharingInfoInto(box,info);break;case 404:this._renderMessage(app.lang("notebook.sharing.notReady"));break;case 401:app.layout.invalidateIdentity();this._renderMessage(app.lang("error.sessionExpired"));break;case 0:this._renderMessage(app.lang("notebook.sharing.connection.message"));break;default:this._renderMessage(app.lang("error.unknown"))}app.layout.enableMode("full");
app.layout.replace("content",content);return app.layout.replace("breadcrumbs",breadcrumbs)},this))},this))},_renderSharingInfoInto:function(box,info){var notebook,section,__handleResponse;section=app.component("content.box.section-sharing",{notebook:this._notebook,friends:app.current_user.friends,info:{write:info.write.map(function(doc){return new User(doc)}),read:info.read.map(function(doc){return new User(doc)})}});box.attach("sections",section);__handleResponse=function(callback,status){var bar,
message;bar=section.element.findOne(".settings .bar");if(status===204){bar.addClassName("active");return callback()}else{box.remove("sections");if(status===0)message=app.lang("notebook.sharing.connection.message");else message=app.lang("error.unknown");section=app.component("content.box.section-message");section.attach("content",app.component("content.box.section-message.content",{message:message}));box.attach("sections",section);return box.rerender("sections")}};notebook=this._notebook;section.addEventListener("select",
function(e){var bar,user;bar=section.element.findOne(".settings .bar");bar.removeClassName("active");user=e.detail.user;return notebook.shareTo(user,false,__handleResponse.bind(null,e.detail.callback))},false);section.addEventListener("change",function(e){var bar,user;bar=section.element.findOne(".settings .bar");bar.removeClassName("active");user=e.detail.user;return notebook.shareTo(user,Boolean(e.detail.write),__handleResponse.bind(null,e.detail.callback))},false);return section.addEventListener("remove",
function(e){var bar,user;bar=section.element.findOne(".settings .bar");bar.removeClassName("active");user=e.detail.user;return notebook.unshareFrom(user,__handleResponse.bind(null,e.detail.callback))},false)},_renderMessage:function(message){var box,parts,section;box=null;parts=this.content.getAttached("parts");parts.some(function(part){if(part.NAME==="content.box"){box=part;return true}});if(box===null){box=app.component("content.box",{"class":"message"});this.content.attach("parts",box)}section=
app.component("content.box.section-message");section.attach("content",app.component("content.box.section-message.content",{message:message}));box.remove("sections");box.attach("sections",section);return box.rerender("sections")},_buildSharingBox:function(){var box,title;box=app.component("content.box");title=app.component("content.box.title",{title:app.lang("notebook.sharingOf",{title:this._notebook[":title"],year:this._notebook[":year"]})});box.attach("title",title);return box},_buildNotebookBreadcrumb:function(notebook,
owner){var breadcrumb;breadcrumb=app.component("breadcrumb",{"class":"notebook",link:app.link("notebook:",{id:notebook.id}),label:notebook[":title"].escapeHTML()});if(owner)owner.getAllNotebooks(function(notebooks){var notebooks_yearly,years;years=[];notebooks_yearly={};notebooks.forEach(function(notebook){var year;year=notebook[":year"];if(years.indexOf(year)===-1)years.push(year);if(notebooks_yearly[year]===void 0)notebooks_yearly[year]=[];return notebooks_yearly[year].push(notebook)});years.forEach(function(year){var dropdown;
notebooks=notebooks_yearly[year];if(notebooks.length===0)return;dropdown=app.component("breadcrumb.dl");breadcrumb.attach("dropdown",dropdown);dropdown.attach("items",app.component("breadcrumb.dl.title",{label:year}));return notebooks.forEach(function(notebook){return dropdown.attach("items",app.component("breadcrumb.dl.item",{label:notebook[":title"].escapeHTML(),link:app.link("notebook:",{id:notebook.id})}))})});return breadcrumb.rerender()});return breadcrumb},_buildTopicBreadcrumb:function(topics,
open_ids,notebook){var breadcrumb,dropdown,open_titles,open_topics;open_topics=topics.filter(function(topic){return open_ids.indexOf(topic.id)!==-1});open_titles=open_topics.map(function(topic){return topic[":title"]});breadcrumb=app.component("breadcrumb",{"class":"topic",link:app.link("notebook:",{id:notebook.id,topics:open_ids.join(";")}),label:open_titles.join("; ").escapeHTML(),open_topics:open_topics});dropdown=app.component("breadcrumb.ul-multiple");breadcrumb.attach("dropdown",dropdown);topics.forEach(function(topic){return dropdown.attach("items",
app.component("breadcrumb.ul-multiple.item",{"class":"topic",value:topic.id,link:app.link("notebook:",{id:notebook.id,topics:topic.id}),label:topic[":title"].escapeHTML(),selected:open_ids}))});dropdown.addEventListener("select",function(e){return app.redirect("notebook:",{id:notebook.id,topics:e.detail.join(";")})},false);return breadcrumb},_buildSharingBreadcrumb:function(notebook){return app.component("breadcrumb",{"class":"sharing",link:app.link("notebook:sharing",{id:notebook.id}),label:app.lang("notebook.sharing")})},
_getOpenTopicIds:function(topics,params){if(params.topics)return params.topics.split(";");else if(topics.length!==0)return[topics.last().id];else return[]},_renderNotebookOptions:function(notebook,owner){var options;if(!notebook.writable)return;options=app.component("content.options");options.attach("buttons",this._buildCreateTopicNotebookOption(notebook));if(app.current_user&&app.current_user.id===owner.id)options.attach("buttons",this._buildSharingNotebookOption(notebook));return this.content.attach("parts",
options)},_renderTopicOptions:function(topic){var options;if(!this._notebook.writable)return;options=app.component("content.options");options.attach("buttons",this._buildCreateLessonTopicOption(topic));return this.content.attach("parts",options)},_buildCreateTopicNotebookOption:function(notebook){var button;button=app.component("button",{"class":"add",label:app.lang("topic.create")});button.addEventListener("click",__bind(function(){return this._createTopicOf(notebook,function(topic){return app.redirect("notebook:",
{id:notebook.id,topics:topic.id,rename:true})})},this),false);return button},_buildCreateLessonTopicOption:function(topic){var button;button=app.component("button",{"class":"add",label:app.lang("lesson.create")});button.addEventListener("click",__bind(function(){return this._createLessonOf(topic,__bind(function(lesson){var first_section,section;first_section=topic.box.getAttached("sections").first();if(first_section&&first_section.NAME==="content.box.section-message")topic.box.remove("sections");
section=this._renderLesson(lesson,topic.box);return section.enableEditing()},this))},this),false);return button},_buildSharingNotebookOption:function(notebook){return app.component("button",{"class":"sharing",label:app.lang("notebook.sharing"),link:app.link("notebook:sharing",{id:notebook.id})})},_createTopicOf:function(notebook,callback){var topic;topic=new Topic;topic.generateId();topic[":title"]=app.lang("topic.defaultTitle");topic.updateTimestamp("date:created","date:modified");topic.parent=notebook;
this.topics_.push(topic);return topic.save(function(){if(typeof callback==="function")return callback(topic)})},_createLessonOf:function(topic,callback){this._getNewLessonNumber(function(lesson_num){var lesson;lesson=new Lesson;lesson.generateId();lesson["lesson:number"]=lesson_num;lesson["lesson:date"]=(new Date).format(app.lang("format.date"));lesson[":content"]="";lesson.updateTimestamp("date:created","date:modified");lesson.parent=topic;return lesson.save(function(){if(typeof callback==="function")return callback(lesson)})})},
_getNewLessonNumber:function(callback){var topics=this.topics_.reverse();var ii=topics.length;(function iter(i){if(i!==ii)topics[i].getLessons(function(lessons){lessons=lessons.reverse();if(lessons.length===0)iter(++i);else if(!lessons.some(function(lesson){var act_num=parseInt(lesson["lesson:number"],10);if(!isNaN(act_num)){callback(String(++act_num));return true}}))iter(++i)});else callback("1")})(0)},_renderTopics:function(topics,open_ids){return topics.forEach(function(topic,t){if(open_ids.indexOf(topic.id)===
-1)return;if(!this._prev_topic)this._prev_topic=topics[t-1];this._next_topic=topics[t+1];return this._renderTopic(topic)},this)},_renderTopic:function(topic){var box;box=app.component("content.box-topic");this.content.attach("parts",box);box.attach("title",this._buildTopicTitle(topic));topic.box=box;this._renderTopicOptions(topic);topic.getLessons(__bind(function(lessons){return this._renderLessons(lessons,box)},this));return this._renderTopicSidebar(topic,box)},_renderLessons:function(lessons,box){if(lessons.length!==
0)return lessons.forEach(function(lesson){return this._renderLesson(lesson,box)},this);else return this._renderNoLessonMessageInto(box)},_renderNoLessonMessageInto:function(box){var content,section;section=app.component("content.box.section-message");content=app.component("content.box.section-message.content",{message:app.lang("lesson.none")});section.attach("content",content);box.attach("sections",section);return box.rerender("sections")},_renderLesson:function(lesson,box){var section;section=app.component("content.box.section-lesson",
{lesson:lesson});section.attach("title",this._buildLessonTitle());section.attach("content",this._buildLessonContent());box.attach("sections",section);box.rerender("sections",true);var self=this;section.addEventListener("autosave",function(){self._saveLessonWithDataFrom(section,function(){var date=(new Date).format(app.lang("format.dateTime"));var status=app.lang("lesson.saved",{date:date});section.getAttached("title").first().setStatus(status)})},false);return section},_renderTopicSidebar:function(topic,
box){this._renderTopicMenu(topic,box);this._renderAttachmentsOf(topic,box)},_renderAttachmentPopover:function(){var self=this;var popover=app.component("popover-file");this.attachment_popover_=popover;popover._notebook=this._notebook;popover.beforeRender();popover.render();popover.afterRender();var p=document.createElement("p");p.attr("class","image-title");var onDownload=function(id){var showImage=function(file){var img=new Image;img.attr("src",file["files:data"]);p.innerHTML=file[":title"];var close=
function(){img.remove();p.remove();app.layout.cover.removeEventListener("click",close);app.layout.cover.hide()};app.layout.cover.insert(img);app.layout.cover.insert(p);app.layout.cover.addEventListener("click",close);app.layout.cover.show()};var downloadFile=function(file){var iframe=document.createElement("iframe");iframe.attr("src",file["files:data"]);iframe.hide();document.body.insert(iframe);iframe.onload=function(){this.remove()};iframe=null};self.requestFile_(id,function(file){if(/^image\//.test(file["files:type"]))showImage(file);
else downloadFile(file)})};popover.addEventListener("download",function(){onDownload(this.element.data("id"))});popover.addEventListener("delete",function(){var that=this;var id=this.element.data("id");var menu=this.menu_component;Attachment.one(id,function(attachment){if(attachment.stored){if(!window.confirm(app.lang("attachment.delete.confirm",{"file_name":attachment[":title"]})))return;attachment.remove(function(){that.element.style.display="none";menu.getAttached("items").forEach(function(c){if(c.data.file.id===
id)menu.remove("items",c)})})}})});popover.addEventListener("change_title",function(){var new_title=this.element.findOne(".title input").value;var id=this.element.data("id");var that=this;var menu=this.menu_component;Attachment.one(id,function(attachment){if(attachment.stored){attachment[":title"]=new_title;attachment.save(function(){menu.getAttached("items").forEach(function(c){if(c.data.file.id===id){c.data.file[":title"]=new_title;that.data.title=new_title;c.rerender();menu.parent.fixHeight()}})})}})})},
_renderUpgradePopover:function(){var popover=app.component("popover-upgrade");this.upgrade_popover_=popover;popover.beforeRender();popover.render();popover.afterRender()},_renderTopicMenu:function(topic,box){var that=this;var notebook=this._notebook;var current_user=app.current_user;var doPrint=function(){var printer=new Printer(notebook,topic.id);printer.open();printer.ondownload=function(state){printer.download("http://"+location.host+"/api/print/notebook/"+notebook.id+"?topics="+state.topics.join(";")+
"&cover="+(state.cover?1:0)+"&toc="+(state.toc?1:0))}};var menu=app.component("content.box.menu");box.attach("menu",menu);var item=app.component("content.box.menu.item",{"class":"print",label:app.lang("button.print")});var item_export=app.component("content.box.menu.item",{"class":"export",label:app.lang("button.export-pdf")});var item_upload;if(this._notebook.writable)if(current_user.isPremium())item_upload=this._createUploadFileTopicMenuItem(topic);else item_upload=app.component("content.box.menu.item",
{"class":"fake-upload",label:app.lang("button.upload-file")});if(current_user.isPremium()){item.addEventListener("click",doPrint,false);item_export.addEventListener("click",doPrint,false)}else menu.afterRender=function(){this.element.addEventListener("click",function(e){var btn=e.target;btn=btn.nodeType===btn.TEXT_NODE?btn.parentNode:btn;if(btn.tagName!=="LI")return;that.upgrade_popover_.show(btn);e.stopPropagation()},false)};menu.attach("items",item);menu.attach("items",item_export);if(this._notebook.writable)menu.attach("items",
item_upload)},_createUploadFileTopicMenuItem:function(topic){var item;item=app.component("content.box.menu.item-upload",{label:app.lang("button.upload-file"),api:Topic.getApiUri(topic.id,"attachment")});item.afterRender=function(){var offline,uploader,uuid;uuid=window.uuid();this.element.findOne("iframe").name="upload-target-"+uuid;this.element.findOne("form").target="upload-target-"+uuid;offline=app.MODE==="offline";uploader=new OfflineUploader(this.element.findOne("form"),{drop:topic.box.element,
offline:offline});uploader.on("beforequeue",function(file){if(file.size>app.get("max_file_size")){alert("Sorry, the file "+file.name+" is larger than 20 MB.");return false}});uploader.on("uploadsuccess",function(data){var attachment;attachment=new Attachment(data);return topic.box.getAttached("menu")[1].push(attachment)});if(offline){uploader.storage=new AttachmentStorage(topic);uploader.storage.onstore=function(attachment){return topic.box.getAttached("menu")[1].push(attachment)}}return uploader.init()};
return item},requestFile_:function(id,callback){Attachment.one(id,function(file){if(file["files:data"]&&file["files:data"]!=="undefined")callback(file);else Attachment.one(id,{online:true},function(f){file["files:data"]=f["files:data"];file.save({online:false},callback(file))})})},_renderAttachmentsOf:function(topic,box){var self=this;var current_user=app.current_user;var menu=app.component("content.box.menu-files");box.attach("menu",menu);var popover_component=this.attachment_popover_;var popover=
popover_component.element;menu.afterRender=function(){this.element.addEventListener("click",function(e){var a=e.target;a=a.nodeType===a.TEXT_NODE?a.parentNode:a;if(a.tagName!=="LI")return;if(a.data("id")===popover.data("id")){popover.data("id","");return popover.remove()}var type=a.data("type");popover.data("id",a.data("id"));popover.findOne("input").value=a.data("title");popover_component.menu_component=menu;popover_component.beforeOpen();app.layout.popovers.insert(popover);var preview=popover.findOne(".preview");
preview.show();if(/^image\//.test(type)){popover.findOne("button.download").innerHTML=app.lang("button.show");self.requestFile_(popover.data("id"),function(file){var img=preview.firstChild;img.remove();img=new Image;img.attr("src",file["files:data"]);img.onerror=function(){preview.hide();popover.style.top=a_rect.top+(a_rect.bottom-a_rect.top)/2-(popover_rect.bottom-popover_rect.top)/2+"px"};preview.insert(img)})}else{popover.findOne("button.download").innerHTML=app.lang("button.download");preview.hide()}popover.style.display=
"block";var a_rect=a.getBoundingClientRect();var popover_rect=popover.getBoundingClientRect();popover.style.top=a_rect.top+(a_rect.bottom-a_rect.top)/2-(popover_rect.bottom-popover_rect.top)/2+"px";popover.style.right=window.innerWidth-a_rect.left+7+"px";e.stopPropagation()})};return topic.getAttachments(function(files){return files.forEach(function(file){return menu.push(file)})})},_buildTopicTitle:function(topic){var title;title=app.component("content.box.title",{title:topic[":title"],topic:topic});
if(this._notebook.writable){this._makeTopicTitleRenamable(title);title.defineButtons({"delete":this._buildDeleteTopicButton()});title.setDefaultButtons("rename","delete")}return title},_buildLessonTitle:function(){var title;title=app.component("content.box.section-lesson.title");if(this._notebook.writable){title.defineButtons({edit:this._buildEditLessonButton(),"delete":this._buildDeleteLessonButton(),save:this._buildSaveLessonButton(),close:this._buildCloseLessonButton()});title.setDefaultButtons("edit",
"delete")}return title},_buildLessonContent:function(){var content;return content=app.component("content.box.section-lesson.content")},_buildEditLessonButton:function(){var button;button=app.component("button",{label:app.lang("button.edit")});return button.addEventListener("click",function(){return this.parent.parent.enableEditing()},false)},_buildDeleteLessonButton:function(){var button,that;that=this;button=app.component("button",{"class":"delete",label:app.lang("button.delete")});return button.addEventListener("click",
function(){var lesson=this.parent.data.lesson;if(!window.confirm(app.lang("lesson.delete.confirm",{name:lesson["lesson:number"]})))return;return lesson.remove(__bind(function(){var box,section;section=this.parent.parent;box=section.parent;box.remove("sections",section);if(box.getAttached("sections").length===0)return that._renderNoLessonMessageInto(box)},this))},false)},_buildSaveLessonButton:function(){var button,that;that=this;button=app.component("button",{"class":"save",label:app.lang("button.save")});
return button.addEventListener("click",function(){return that._saveLessonWithDataFrom(this.parent.parent)},false)},_buildCloseLessonButton:function(){var button,that;that=this;button=app.component("button",{"class":"close",label:app.lang("button.close")});return button.addEventListener("click",function(){var section;section=this.parent.parent;return that._saveLessonWithDataFrom(section,function(){return section.disableEditing()})},false)},_saveLessonWithDataFrom:function(section,callback){var number=
section.getLessonNumber().escapeHTML();var date=section.getLessonDate().escapeHTML();section.getLessonContent(function(content){var lesson=section.data.lesson;if(lesson["lesson:number"]===number&&lesson["lesson:date"]===date&&lesson[":content"]===content){if(typeof callback==="function")callback();return}lesson["lesson:number"]=number;lesson["lesson:date"]=date;lesson[":content"]=content;lesson.updateTimestamp("date:modified");lesson.save(function(){var date,status;date=(new Date).format(app.lang("format.dateTime"));
status=app.lang("lesson.saved",{date:date});section.getAttached("title").first().setStatus(status);if(typeof callback==="function")callback()})})},_makeTopicTitleRenamable:function(title){title.makeRenamable();title.addEventListener("rename",function(e){var topic=this.data.topic;var old_title=topic[":title"];var new_title=e.detail.escapeHTML();if(new_title.trim().length<1){alert(app.lang("topic.emptyTitle"));return e.preventDefault()}topic[":title"]=new_title;if(old_title!==new_title){var topic_breadcrumb=
null;app.layout.getAttached("breadcrumbs").forEach(function(breadcrumb){if(breadcrumb.element.attr("class")==="topic")topic_breadcrumb=breadcrumb});open_titles=topic_breadcrumb.data.open_topics.map(function(topic){return topic[":title"]});topic_breadcrumb.data.label=open_titles.join("; ").escapeHTML();topic_breadcrumb.getAttached("dropdown")[0].getAttached("items").forEach(function(item){if(item.data.value===topic.id)item.data.label=new_title});app.layout.rerender("breadcrumbs")}topic.updateTimestamp("date:modified");
topic.save(function(){title.showDefaultButtons()})},false)},_buildDeleteTopicButton:function(){var button,next_topic,notebook_id;notebook_id=this._notebook.id;if(this._next_topic)next_topic=this._next_topic.id;else if(this._prev_topic)next_topic=this._prev_topic.id;else next_topic="";button=app.component("button",{"class":"delete",label:app.lang("button.delete")});return button.addEventListener("click",function(e){var topic=this.parent.data.topic;if(!window.confirm(app.lang("topic.delete.confirm",
{name:topic[":title"]})))return;return topic.remove(function(){setTimeout(function(){app.redirect("notebook:",{id:notebook_id,topics:next_topic})},0)})},false)}});app.registerComponent("content.box-topic",app.getComponent("content.box").inherit({_template:"<div class=\"box box-topic<%= component.data['class'] ? ' ' + component.data['class'] : \"\" %>\"<%= component.data.id !== undefined ? ' id=\"' + id +'\"' : '' %>>"+'<div components="title"></div>'+'<div components="sections"></div>'+"<aside>"+
'<div components="menu"></div>'+"</aside>"+"</div>",fixHeight:function(){var item,menu,y;menu=this.getAttached("menu").last();if(menu){item=menu.getAttached("items").last();if(item){y=item.element.offsetTop+item.element.clientHeight+9;if(!(this.element.clientHeight>y))return this.element.style.minHeight=y+"px"}}}}));app.registerComponent("content.box.menu",Component.inherit({_template:'<ul components="items"></ul>'}));app.registerComponent("content.box.menu-files",Component.inherit({_template:'<ul components="items" class="files"></ul>',
push:function(file){var item=app.component("content.box.menu.item-file",{file:file});var self=this;item.addEventListener("click",function(e){self.fire(e)},false);this.attach("items",item);this.rerender("items",true);return this.parent.fixHeight()}}));app.registerComponent("content.box.menu.item",Component.inherit({_template:"<li<%= component.data['class'] ? ' class=\"' + component.data['class'] + '\"' : '' %>><%= label %></li>",afterRender:function(){if(!app.current_user.isPremium())this.element.style.opacity=
"0.7";return this.element.addEventListener("click",__bind(function(){return this.fire("click")},this),false)}}));app.registerComponent("content.box.menu.item-file",app.getComponent("content.box.menu.item").inherit({_template:"<li class=\"file<%= component.data['class'] ? ' ' + component.data['class'] : '' %>\" "+'data-type="<%= file["files:type"] %>" '+'data-title="<%= file[":title"] %>" '+'data-id="<%= file.id %>" '+'><%= file[":title"] %></li>',afterRender:function(){this.element.style.opacity=
"1.0"}}));app.registerComponent("content.box.menu.item-upload",app.getComponent("content.box.menu.item").inherit({_template:"<li class=\"upload<%= component.data['class'] ? ' ' + component.data['class'] : '' %>\">"+'<form action="<%= api %>" method="post" enctype="multipart/form-data" class="disabled">'+"<span><%= label %></span>"+'<input type="file" name="file" multiple disabled />'+'<button type="submit" disabled><%= label %></button>'+'<iframe style="display: none;"></iframe>'+"</form>"+"</li>"}));
app.registerComponent("popover-file",app.getComponent("popover").inherit({"_template":'<div class="popover left">'+'<div class="arrow"></div>'+'<div class="inner">'+'<div class="title file-popover">'+'<input type="text" value="<%= title %>" readonly>'+'<div class="help">'+'<p><%= app.lang("attachment.title_edit.help") %></p>'+"</div>"+"</div>"+'<div class="content">'+'<div class="preview" style="display: none;"><img /></div>'+'<button class="btn download"></button>'+"</div>"+"</div>"+"</div>",beforeRender:function(){this.data.title=
this.data.title||"";this.data.type=this.data.type||""},_titleEditable:function(editable){editable=arguments.length>0?editable:true;this.title_help.style.display=editable?"block":"none";if(editable)this.title_input.removeAttribute("readonly");else this.title_input.setAttribute("readonly","readonly")},afterRender:function(){var that=this;var old_value="";var saveTitle=function(){if(!that.title_input.hasAttribute("readonly")){var new_value=that.title_input.value.trim();that.title_input.value=new_value;
if(new_value.length<1){alert(app.lang("attachment.emptyTitle"));return that.title_input.focus()}if(new_value!==that.data.title)that.fire("change_title");return that._titleEditable(false)}};this.title_input=this.element.findOne(".title input");this.title_help=this.element.findOne(".title .help");this.element.addEventListener("click",function(e){saveTitle();e.stopPropagation()},false);this.element.findOne(".preview").addEventListener("click",function(){that.fire("download")},false);this.element.findOne(".download").addEventListener("click",
function(){that.fire("download")},false);if(this._notebook.writable){this.title_input.addClassName("writable");var delete_button=document.createElement("button");delete_button.addClassName("btn");delete_button.addClassName("delete");delete_button.innerText=app.lang("button.delete");delete_button.addEventListener("click",function(){that.fire("delete")},false);this.element.findOne(".content").appendChild(delete_button);this.title_input.addEventListener("click",function(e){old_value=this.value;that._titleEditable();
e.stopPropagation()},false);this.title_input.addEventListener("keydown",function(e){if(e.keyCode===13)saveTitle();if(e.keyCode===27){that._titleEditable(false);this.value=old_value}},false)}},beforeOpen:function(){this._titleEditable(false)}}));app.registerComponent("content.box.section-lesson",app.getComponent("content.box.section").inherit({beforeRender:function(){this.getAttached("title").first().data.lesson=this.data.lesson;return this.getAttached("content").first().data.lesson=this.data.lesson},
afterRender:function(){this.editor=new takeNote.Editor(this.element.findOne(".lesson-content"));return this.editor.load(this.data.lesson[":content"])},getLessonNumber:function(){var title;title=this.getAttached("title").first();return title.getLessonNumber()},getLessonDate:function(){var title;title=this.getAttached("title").first();return title.getLessonDate()},getLessonContent:function(callback){this.editor.getXML(callback)},enableEditing:function(){this.editor.setActive(true);app.toolbar.activate(this.editor);
this._addEditorListeners();this.activate();var title_component=this.getAttached("title").first();title_component.element.findOne(".number").show();title_component.showButtons("save","close");var self=this;this.autosave_interval_=setInterval(function(){self.fire("autosave")},3E4)},disableEditing:function(){this.editor.setActive(false);app.toolbar.deactivate();this._removeEditorListeners();this.deactivate();var title_component=this.getAttached("title").first();if(title_component.data.lesson["lesson:number"].trim().length<
1)this.element.findOne(".number").hide();title_component.showDefaultButtons()},_addEditorListeners:function(){var date_element,editor,number_element,onAreaFocus,preventReturn,title;onAreaFocus=function(){app.toolbar.activate(editor);return editor.toolbar=app.toolbar};preventReturn=function(e){if(e.keyCode===13)return e.preventDefault()};editor=this.editor;editor.getArea().addEventListener("focus",onAreaFocus,false);title=this.getAttached("title").first();number_element=title.element.findOne(".number");
number_element.attr("contenteditable","true");number_element.addEventListener("keypress",preventReturn,false);date_element=title.element.findOne(".date");date_element.attr("contenteditable","true");date_element.addEventListener("keypress",preventReturn,false);return this._removeEditorListeners=function(){this.editor.getArea().removeEventListener("focus",onAreaFocus,false);title=this.getAttached("title").first();number_element=title.element.findOne(".number");number_element.attr("contenteditable",
"false");number_element.removeEventListener("keypress",preventReturn,false);date_element=title.element.findOne(".date");date_element.attr("contenteditable","false");return date_element.removeEventListener("keypress",preventReturn,false)}}}));app.registerComponent("content.box.section-lesson.title",app.getComponent("content.box.section.title").inherit({_template:'<div class="section-header">'+'<p class="layer status"></p>'+'<div class="section-header-content">'+'<ul class="options" components="buttons"></ul>'+
"<% if (component.parent.collapsible) { %>"+'<span class="toggle<%= !component.parent.collapsed ? " toggle-expanded" : "" %>"></span>'+"<% } %>"+'<span class="number"><%= lesson["lesson:number"] %></span>'+'<span class="date"><%= lesson["lesson:date"] %></span>'+"</div>"+"</div>",getLessonNumber:function(){if(!this.rendered)return this.data["lesson:number"];return this.element.findOne(".number").innerText.escapeHTML()},getLessonDate:function(){if(!this.rendered)return this.data["lesson:date"];return this.element.findOne(".date").innerText.escapeHTML()},
afterRender:function(){this.$super();if(this.data.lesson["lesson:number"]&&this.data.lesson["lesson:number"].trim().length<1)this.element.findOne(".number").hide()}}));app.registerComponent("content.box.section-lesson.content",app.getComponent("content.box.section.title").inherit({_template:'<div class="content">'+"<div>"+'<ul class="lesson-content"><%= lesson[":content"] %></ul>'+"</div>"+"</div>"}));app.registerComponent("content.box.section-sharing",app.getComponent("content.box.section").inherit({_template:'<div class="section section-sharing">'+
'<div class="friends">'+"<% if (friends.length !== 0) { %>"+'<span class="input"><input type="text" /><span class="reset"></span></span>'+"<ul>"+"<% friends.forEach(function (user, i) { %>"+'<li data-index="<%= i %>" data-realname="<%= user["users:realname"] %>" data-id="<%= user.id %>">'+'<img src="<%= user["facebook:picture"] || "http://graph.facebook.com/" + user["facebook:id"] + "/picture" %>" />'+'<span><%= user["users:realname"] %></span>'+"</li>"+"<% }) %>"+"</ul>"+"<% } else { %>"+'<p class="empty"><%= app.lang("notebook.sharing.noFriends") %></p>'+
"<% } %>"+"</div>"+'<div class="settings">'+'<div class="friends">'+'<p class="bar ok"><%= app.lang("notebook.sharing.saved") %></p>'+"<% if (friends.length !== 0) { %>"+"<ul>"+"<% info.write.forEach(function (user) { %>"+'<li data-id="<%= user.id %>">'+'<img src="<%= user["facebook:picture"] || "http://graph.facebook.com/" + user["facebook:id"] + "/picture" %>" />'+'<span><%= user["users:realname"] %></span>'+'<div class="write-control"><%= app.lang("notebook.sharing.allowContribution") %> <input type="checkbox" name="write" checked="checked" /></div>'+
'<span class="remove"></span>'+"</li>"+"<% }) %>"+"<% info.read.forEach(function (user) { %>"+'<li data-id="<%= user.id %>">'+'<img src="<%= user["facebook:picture"] || "http://graph.facebook.com/" + user["facebook:id"] + "/picture" %>" />'+'<span><%= user["users:realname"] %></span>'+'<div class="write-control"><%= app.lang("notebook.sharing.allowContribution") %> <input type="checkbox" name="write" /></div>'+'<span class="remove"></span>'+"</li>"+"<% }) %>"+"</ul>"+"<% } else { %>"+'<p class="empty"><%= app.lang("notebook.sharing.empty") %></p>'+
"<% } %>"+"</div>"+"<div class=\"publishing<%= notebook['permissions:public'] ? ' enabled' : '' %>\">"+'<h3><%= app.lang("notebook.publishing.didYouKnow") %></h3>'+'<p><%= app.lang("notebook.publishing.intro") %></p>'+'<a class="button"><%= !notebook[\'permissions:public\'] ? app.lang("notebook.publishing.enable") : app.lang("notebook.publishing.disable") %></a>'+"</div>"+"</div>"+"</div>",afterRender:function(){var lists;this.friends={};this.data.friends.forEach(function(user){return this[user.id]=
user},this.friends);lists=this.element.find("ul");if(lists.length!==0){this._disableSelected(lists[0]);this._addAddListener(lists);this._addChangeListener(lists);this._addSearchListener(lists[0])}return this._addPublishingListener()},_disableSelected:function(list){var selected;selected=this.data.info.write.concat(this.data.info.read).map(function(user){return user.id});return list.find("li").forEach(function(item){if(selected.indexOf(item.data("id"))!==-1)return item.addClassName("selected")})},
_addAddListener:function(lists){var that;that=this;return lists[0].addEventListener("click",function(e){var item,orig;orig=e.target;while(orig.parentNode!==this)orig=orig.parentNode;if(orig.hasClassName("selected"))return;item=orig.cloneNode(true);orig.addClassName("selected");return that.fire("select",{user:that.friends[orig.data("id")],callback:function(){var control;control=new Element("div",{"class":"write-control"});control.html(app.lang("notebook.sharing.allowContribution")+' <input type="checkbox" name="write" />');
item.insert(control);item.insert(new Element("span",{"class":"remove"}));return lists[1].insert(item)}})},false)},_addChangeListener:function(lists){var that;that=this;return lists[1].addEventListener("click",function(e){var id,li,target;li=target=e.target;while(li.parentNode!==this)li=li.parentNode;id=li.data("id");if(target.tagName==="INPUT"){target.disabled=true;return that.fire("change",{user:that.friends[id],write:target.checked,callback:function(){return target.disabled=false}})}else if(target.hasClassName("remove"))return that.fire("remove",
{user:that.friends[id],callback:function(){var el;li.remove();el=lists[0].findOne('li[data-id="'+id+'"]');if(!!el)return el.removeClassName("selected")}})},false)},_addSearchListener:function(list){var input,onKeyUp,onReset,search;search=function(q){var words;words=q.split(/\s+/g).map(function(word){return new RegExp("(^|\\s)"+word,"i")});return list.find("li").forEach(function(item){var matches,realname;realname=item.data("realname");matches=words.every(function(word){return realname.match(word)});
if(matches)return item.show();else return item.hide()})};onKeyUp=function(){return search(this.value)};onReset=function(){input.value="";input.focus();return search("")};input=list.parentNode.findOne("input");input.addEventListener("keyup",onKeyUp,false);return list.parentNode.findOne(".reset").addEventListener("click",onReset,false)},_addPublishingListener:function(){var button,enabled,notebook,togglePublishing;notebook=this.data.notebook;enabled=this.element.findOne(".publishing").hasClassName("enabled");
togglePublishing=function(e){e.preventDefault();if(this.disabled)return;this.disabled=true;enabled=!enabled;notebook["permissions:public"]=enabled;return notebook.save(__bind(function(){this.innerHTML=enabled?app.lang("notebook.publishing.disable"):app.lang("notebook.publishing.enable");return this.disabled=false},this))};button=this.element.findOne(".publishing .button");return button.addEventListener("click",togglePublishing,false)}}))}).call(this);var UserController=window._BaseController.inherit();
UserController.prototype["default"]=function(params){if(params["username"]===undefined)throw new Error("Missing username");var that=this;var current_user=app.current_user;var opts={online:current_user?null:true,fallback:User.getApiUri(params.username)};User.one({"users:username":params["username"]},opts,function(user){if(!user.stored)return that.terminate(app.lang("user.notExists"));var current_user_profile=Boolean(current_user&&current_user.id===user.id);app.layout.replace("breadcrumbs",that._buildUserBreadcrumb(user));
var content=app.component("content");var box=app.component("content.box",{"class":"user "+user["users:gender"]});content.attach("parts",box);var box_title=app.component("content.box.title-user",{title:user["users:realname"],user:user});box.attach("title",box_title);function __notebookHandler(notebooks){var notebooks_yearly={};var years=[];if(current_user_profile){var current_month=(new Date).getMonth();var current_year=(new Date).getFullYear();current_year=current_month<5?current_year-1+"/"+current_year:
current_year+"/"+(current_year+1);notebooks_yearly[current_year]=[];years.push(current_year)}notebooks.forEach(function(notebook){var year=notebook[":year"];if(notebooks_yearly[year]===undefined){notebooks_yearly[year]=[];years.push(year)}notebooks_yearly[year].push(notebook)});years=years.sort().reverse();var yy=years.length;function loopYears(y,callbackYears){if(y===yy)return callbackYears();var year=years[y++];var notebooks=notebooks_yearly[year];var section=app.component("content.box.section");
box.attach("sections",section);var section_title=app.component("content.box.section.title",{title:year});section.attach("title",section_title);var section_content=app.component("content.box.section-notebooks.content");section.attach("content",section_content);if(current_user_profile)section.useCollapse("year-#{year}");var ii=notebooks.length;function loopNotebooks(i,callbackNotebooks){if(i===ii)return callbackNotebooks();var notebook=notebooks[i++];var item=app.component("content.box.section-notebooks.content.item",
{editable:current_user_profile,notebook:notebook});item.addEventListener("submit",function(e){notebook.update(e.detail);notebook.save(function(){item.update()})},false);item.addEventListener("delete",function(e){if(notebook.parent===user.id)notebook.remove(function(){item.element.remove()});else notebook.unshareFrom(user,function(status){switch(status){case 204:item.element.remove();if(!notebook.remote)notebook.remove();break;case 0:alert(app.lang("notebook.sharing.cancel.offline"));break;default:alert("An error occurred. Sorry!")}})});
section_content.attach("items",item);if(notebook.parent===null||notebook.parent===user[!notebook.remote?"id":User.api_field]){if(!current_user_profile)item.data["class"]=notebook.writable?"writable":"readable";loopNotebooks(i,callbackNotebooks)}else{item.data["class"]=notebook.writable?"writable":"readable";notebook.getParent(function(parent){item.data.owner=parent;loopNotebooks(i,callbackNotebooks)})}}loopNotebooks(0,function(){if(current_user_profile){var item=app.component("content.box.section-notebooks.content.item-create",
{notebook:{":year":year}});item.addEventListener("submit",function(e){var notebook=new Notebook;notebook.generateId();notebook.update(e.detail);notebook.parent=current_user;notebook.doc.readable=true;notebook.doc.writable=true;notebook.save(function(){app.redirect("notebook:",{"id":notebook.id})})},false);section_content.attach("items",item)}loopYears(y,callbackYears)})}loopYears(0,function(){if(years.length===0){var section=app.component("content.box.section");box.attach("sections",section);var section_content=
app.component("content.box.section-message.content",{"class":"static",message:'<div class="no-notebooks"></div>'});section.attach("content",section_content)}if(current_user_profile)that._renderRequestsInto(box);app.layout.replace("content",content)})}var notebooks_by_year={};user.getAllNotebooks(__notebookHandler)})};
UserController.prototype._renderRequestsInto=function(box){var opts={online:true,fallback:"/api/requests/sharing"};Request.all({":type":"sharing"},opts,function(requests){if(!requests.length)return;var section=app.component("content.box.section-requests",{count:requests.length});box.attach("sections",section);box.rerender("sections",true);var i=0;(function iter(){if(i===requests.length)return;var request=requests[i++];User.one(request["requests:origin"],function(user){if(!user.stored)return;Notebook.one(request["requests:subject"],
function(notebook){if(!notebook.stored)return;var item=app.component("content.box.section-requests.item",{request:request,origin:user,subject:notebook});section.attach("items",item);section.rerender("items",true);item.addEventListener("close",function(e){if(e.detail==="accept")app.redirect("notebook:",{"id":notebook.id})},false);iter()})})})()})};
app.registerComponent("content.box.title-user",app.getComponent("content.box.title").inherit({_template:'<div class="header">'+'<div class="header-content">'+"<h2><%= title %></h2>"+'<a class="fbprofile" target="_blank" href="http://facebook.com/profile.php?id=<%= user["facebook:id"] %>"><span><%= app.lang("user.fb.profile") %></span></a>'+'<ul class="options" components="buttons"></ul>'+"</div>"+"</div>"}));
app.registerComponent("content.box.section-notebooks.content",app.getComponent("content.box.section.content").inherit({_template:'<div class="content">'+'<ul class="section-notebooks" components="items"></ul>'+"</div>"}));
app.registerComponent("content.box.section-notebooks.content.item",Component.inherit({_template:'<li class="notebook<%= component.data["class"] !== undefined ? " " + component.data["class"] : "" %>">'+"<%# static %>"+'<div class="notebook-data">'+'<span class="icon">'+'<% if (notebook["permissions:public"]) { %><span class="public" title="<%= app.lang("notebook.public") %>"></span><% } %>'+"</span>"+'<h4><a href="<%= app.link("notebook:", { id: notebook.id }) %>"><%= notebook[":title"].escapeHTML() %></a></h4>'+
'<small><span><%= (notebook[":professor"] || "").escapeHTML() %></span>'+'<% if (typeof owner !== "undefined" && component.data["class"] !== undefined) { %>'+'<br /><a href="<%= app.link("user:", { "username": owner["users:username"] }) %>"><%= owner["users:realname"] %></a>'+"<% } %>"+"</small>"+'<span class="overflow"></span>'+"</div>"+"<%# option buttons %>"+'<% if (component.data["class"] === undefined) { %>'+'<ul class="options-top">'+'<li class="delete"><span><%= app.lang("button.deleteNotebook") %></span></li>'+
"</ul>"+'<ul class="options-bottom">'+'<li class="edit"><span><%= app.lang("button.edit") %></span></li>'+'<li class="sharing"><span><%= app.lang("button.sharing") %></span></li>'+"</ul>"+"<%# form %>"+'<form style="display:none">'+"<div>"+'<input type="text" class="h4" name="__title" placeholder="<%= app.lang("title") %>" spellcheck="false" autofocus value="<%= notebook[":title"].escapeHTML() %>" /><br />'+'<input type="text" class="small" name="__professor" placeholder="<%= app.lang("professor") %>" spellcheck="false" value="<%= (notebook[":professor"] || "").escapeHTML() %>" />'+
"</div>"+'<ul class="options-bottom">'+'<li class="ok"><span><%= app.lang("button.save") %></span></li>'+'<li class="cancel"><span><%= app.lang("button.cancel") %></span></li>'+"</ul>"+"</form>"+"<%# delete dialog %>"+'<div class="inline-dialog delete-dialog" style="display:none">'+"<div>"+'<p><%= app.lang("notebook.delete.confirm") %></p>'+'<a href="javascript:;" class="button cancel"><%= app.lang("button.cancel") %></a>'+'<a href="javascript:;" class="button delete"><%= app.lang("button.deleteNotebook") %></a>'+
"</div>"+"</div>"+"<% } else if (editable) { %>"+'<ul class="options-top">'+'<li class="delete"><span><%= app.lang("button.cancelSharing") %></span></li>'+"</ul>"+"<%# sharing cancellation dialog %>"+'<div class="inline-dialog delete-dialog" style="display:none">'+"<div>"+'<p><%= app.lang("notebook.sharing.cancel.confirm") %></p>'+'<a href="javascript:;" class="button cancel"><%= app.lang("button.no") %></a>'+'<a href="javascript:;" class="button delete"><%= app.lang("button.cancelSharing") %></a>'+
"</div>"+"</div>"+"<% } %>"+"</li>",afterRender:function(){this._addLinkListeners();this._addOptionListeners()},_addLinkListeners:function(){var that=this;var el=this.element.findOne(".notebook-data");el.addEventListener("click",function(){app.call(app.link("notebook:",{"id":that.data.notebook.id}))},false);el.find("a").forEach(function(a){a.addEventListener("click",function(e){e.stopPropagation()},false)})},_addOptionListeners:function(){var that=this;this.element.find("li").forEach(function(option){option.addEventListener("click",
function(e){if(this.hasClassName("delete"))that._initiateDeleting();else if(this.hasClassName("edit"))that._initiateEditing();else if(this.hasClassName("sharing"))app.call(app.link("notebook:sharing",{"id":that.data.notebook.id}))},false)})},_initiateDeleting:function(){var that=this;this.element.addClassName("active");this.element.findOne(".delete-dialog").show();this.element.findOne(".delete-dialog .cancel").addEventListener("click",function(){that.element.removeClassName("active");that.element.findOne(".delete-dialog").hide()},
false);this.element.findOne(".delete-dialog .delete").addEventListener("click",function(){that.fire("delete")},false)},_initiateEditing:function(){this.element.addClassName("active");var form=this.element.findOne("form");form.show();this._addEditingListeners()},_addEditingListeners:function(){var that=this;var form=this.element.findOne("form");function fn_submit(){if(form.values[":title"].trim().length<1){alert(app.lang("notebook.emptyTitle"));return form.findOne('input[type="text"]').focus()}that.fire("submit",
form.values);that._removeEditingListeners();return false}function fn_close(){that._removeEditingListeners();that.element.removeClassName("active");form.hide()}function onInputKeyDown(e){if(e.keyCode===13)fn_submit();else if(e.keyCode===27)fn_close()}function preventSubmit(e){e.preventDefault();return false}form.addEventListener("submit",preventSubmit,false);form.find('input[type="text"]').forEach(function(input){input.addEventListener("keydown",onInputKeyDown,false)});form.findOne(".ok").addEventListener("click",
fn_submit,false);form.findOne(".cancel").addEventListener("click",fn_close,false);this._removeEditingListeners=function(){form=that.element.findOne("form");form.removeEventListener("submit",preventSubmit,false);form.findOne(".ok").removeEventListener("click",fn_submit,false);form.findOne(".cancel").removeEventListener("click",fn_close,false);form.find('input[type="text"]').forEach(function(input){input.removeEventListener("keydown",onInputKeyDown,false)})}},update:function(){var notebook=this.data.notebook;
var el=this.element.findOne(".notebook-data");el.findOne("h4").html(notebook[":title"].escapeHTML());el.findOne("small").html(notebook[":professor"].escapeHTML());this.element.removeClassName("active");this.element.findOne("form").hide()}}));
app.registerComponent("content.box.section-notebooks.content.item-create",Component.inherit({_template:'<li class="notebook-placeholder">'+'<div class="notebook-data">'+'<span class="icon"></span>'+"</div>"+'<form style="display: none">'+"<div>"+'<input type="text" class="h4" name="__title" placeholder="<%= app.lang("title") %>" spellcheck="false" autofocus value="" /><br />'+'<input type="text" class="small" name="__professor" placeholder="<%= app.lang("professor") %>" spellcheck="false" value="" />'+
'<input type="hidden" name="__year" value="<%= notebook[":year"] %>" />'+"</div>"+'<ul class="options-bottom">'+'<li class="ok"><span><%= app.lang("button.save") %></span></li>'+'<li class="cancel"><span><%= app.lang("button.cancel") %></span></li>'+"</ul>"+"</form>"+'<div class="inline-dialog">'+"<div>"+'<a href="javascript:;" class="button"><span></span><%= app.lang("notebook.create") %></a>'+"</div>"+"</div>"+'<div class="upgrade-popover" style="display: none">'+'<span class="close"></span>'+'<p><%= app.lang("premium.notebook.upgrade-popover.info") %></p>'+
'<a class="button"><%= app.lang("premium.upgrade") %></a>'+'<p><a target="_blank" href="/functions#premium"><%= app.lang("premium.upgrade-popover.more-info") %></a></p>'+"</div>"+"</li>",afterRender:function(){this._addButtonListener();this._addFormListeners()},_addButtonListener:function(){var that=this;function onUpgradeButtonClick(){this.style.opacity="0.5";Model.api("GET",app.get("api_root")+"/session",function(status){if(status===0)alert("You need to be connected to the Internet to upgrade your account.");
else window.location.href="/registration?upgrade"})}var popover=this.element.findOne(".upgrade-popover");popover.findOne(".close").addEventListener("click",function(){that.element.findOne(".inline-dialog").style.opacity="1";popover.findOne(".button").removeEventListener("click",onUpgradeButtonClick,false);popover.hide()},false);this.element.findOne("a.button").addEventListener("click",function(e){e.preventDefault();app.current_user.isAllowedTo("create","notebook",function(allowed){var el=that.element;
if(allowed){el.removeClassName("notebook-placeholder").addClassName("notebook");el.addClassName("active");el.findOne(".inline-dialog").hide();el.findOne("form").show()}else{el.findOne(".inline-dialog").style.opacity="0.5";popover.show();popover.findOne(".button").addEventListener("click",onUpgradeButtonClick,false)}});return false},false)},_addFormListeners:function(){var that=this;var form=this.element.findOne("form");function fn_submit(){if(form.values[":title"].trim().length<1){alert(app.lang("notebook.create.emptyTitle"));
return form.findOne('input[type="text"]').focus()}that.disableInputs();that.fire("submit",form.values)}function fn_close(){var el=that.element;el.addClassName("notebook-placeholder").removeClassName("notebook");el.removeClassName("active");that.enableInputs();el.findOne("form").hide();el.findOne(".inline-dialog").show();el.findOne("a.button").focus()}form.addEventListener("submit",function(e){e.preventDefault();return false},false);form.find('input[type="text"]').forEach(function(input){input.addEventListener("keydown",
function(e){if(e.keyCode===13)fn_submit();else if(e.keyCode===27)fn_close()},false)});form.findOne(".ok").addEventListener("click",fn_submit,false);form.findOne(".cancel").addEventListener("click",fn_close,false)},disableInputs:function(){var form=this.element.findOne("form");form.findOne(".ok").hide();form.find("input").forEach(function(input){input.disabled=true})},enableInputs:function(){var form=this.element.findOne("form");form.findOne(".ok").show();form.find("input").forEach(function(input){input.disabled=
false})}}));

