
// Copyright (c) 2007-2009 Metaweb Technologies unless otherwise stated. See license.html

;var CONFIG={APPEDITOR_VERSION:'acrid/dev/24:83328',ACRE_METAWEB_API_ADDR:'www.freebase.com',GRAPH_SHORTNAME:'OTG',ACRE_HOST_SUFFIX:'dev.freebaseapps.com'};;shortcut={'all_shortcuts':{},'add':function(shortcut_combination,callback,opt){var default_options={'type':'keydown','propagate':false,'disable_in_input':false,'target':document,'keycode':false}
if(!opt)opt=default_options;else{for(var dfo in default_options){if(typeof opt[dfo]=='undefined')opt[dfo]=default_options[dfo];}}
var ele=opt.target
if(typeof opt.target=='string')ele=document.getElementById(opt.target);var ths=this;shortcut_combination=shortcut_combination.toLowerCase();var func=function(e){e=e||window.event;if(opt['disable_in_input']){var element;if(e.target)element=e.target;else if(e.srcElement)element=e.srcElement;if(element.nodeType==3)element=element.parentNode;if(element.tagName=='INPUT'||element.tagName=='TEXTAREA')return;}
if(e.keyCode)code=e.keyCode;else if(e.which)code=e.which;var character=String.fromCharCode(code).toLowerCase();if(code==188)character=",";if(code==190)character=".";var keys=shortcut_combination.split("-");var kp=0;var shift_nums={"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"}
var special_keys={'esc':27,'escape':27,'tab':9,'space':32,'return':13,'enter':13,'backspace':8,'scrolllock':145,'scroll_lock':145,'scroll':145,'capslock':20,'caps_lock':20,'caps':20,'numlock':144,'num_lock':144,'num':144,'pause':19,'break':19,'insert':45,'home':36,'delete':46,'end':35,'pageup':33,'page_up':33,'pu':33,'pagedown':34,'page_down':34,'pd':34,'left':37,'up':38,'right':39,'down':40,'f1':112,'f2':113,'f3':114,'f4':115,'f5':116,'f6':117,'f7':118,'f8':119,'f9':120,'f10':121,'f11':122,'f12':123}
var modifiers={shift:{wanted:false,pressed:false},ctrl:{wanted:false,pressed:false},alt:{wanted:false,pressed:false},meta:{wanted:false,pressed:false}};if(e.ctrlKey)modifiers.ctrl.pressed=true;if(e.shiftKey)modifiers.shift.pressed=true;if(e.altKey)modifiers.alt.pressed=true;if(e.metaKey)modifiers.meta.pressed=true;for(var i=0;k=keys[i],i<keys.length;i++){if(k=='ctrl'||k=='control'){kp++;modifiers.ctrl.wanted=true;}else if(k=='shift'){kp++;modifiers.shift.wanted=true;}else if(k=='alt'){kp++;modifiers.alt.wanted=true;}else if(k=='meta'){kp++;modifiers.meta.wanted=true;}else if(k.length>1){if(special_keys[k]==code)kp++;}else if(opt['keycode']){if(opt['keycode']==code)kp++;}else{if(character==k)kp++;else{if(shift_nums[character]&&e.shiftKey){character=shift_nums[character];if(character==k)kp++;}}}}
if(kp==keys.length&&modifiers.ctrl.pressed==modifiers.ctrl.wanted&&modifiers.shift.pressed==modifiers.shift.wanted&&modifiers.alt.pressed==modifiers.alt.wanted&&modifiers.meta.pressed==modifiers.meta.wanted){callback(e);if(!opt['propagate']){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault();}
return false;}}}
this.all_shortcuts[shortcut_combination]={'callback':func,'target':ele,'event':opt['type']};if(ele.addEventListener)ele.addEventListener(opt['type'],func,false);else if(ele.attachEvent)ele.attachEvent('on'+opt['type'],func);else ele['on'+opt['type']]=func;},'remove':function(shortcut_combination){shortcut_combination=shortcut_combination.toLowerCase();var binding=this.all_shortcuts[shortcut_combination];delete(this.all_shortcuts[shortcut_combination])
if(!binding)return;var type=binding['event'];var ele=binding['target'];var callback=binding['callback'];if(ele.detachEvent)ele.detachEvent('on'+type,callback);else if(ele.removeEventListener)ele.removeEventListener(type,callback,false);else ele['on'+type]=false;}};;jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};;(function(){var _mjt=window.mjt;var mjt=window.mjt={};mjt.noConflict=function(){window.mjt=_mjt;return mjt;};mjt.NAME='mjt';mjt.VERSION='0.9.1';mjt.LICENSE="========================================================================\n"+"Copyright (c) 2007-2009, Metaweb Technologies, Inc.\n"+"All rights reserved.\n"+"\n"+"Redistribution and use in source and binary forms, with or without\n"+"modification, are permitted provided that the following conditions\n"+"are met:\n"+"    * Redistributions of source code must retain the above copyright\n"+"      notice, this list of conditions and the following disclaimer.\n"+"    * Redistributions in binary form must reproduce the above\n"+"      copyright notice, this list of conditions and the following\n"+"      disclaimer in the documentation and/or other materials provided\n"+"      with the distribution.\n"+"\n"+"THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES ``AS IS'' AND ANY\n"+"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"+"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n"+"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB TECHNOLOGIES BE\n"+"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"+"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"+"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n"+"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n"+"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n"+"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n"+"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"+"========================================================================\n";})();var JSON=JSON||{};(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return 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={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\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){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.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.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
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(mjt){if(typeof mjt.services=='undefined')
mjt.services={};mjt.debug=0;var _next_unique_id={};mjt.uniqueid=function(prefix){var id=_next_unique_id[prefix];if(typeof id!=='number')
id=1;_next_unique_id[prefix]=id+1;return prefix+'_'+id;};var spew_to_page=function(msg,args){var output=document.createElement('div');var tag;var text;tag=document.createElement('h3');tag.style.backgroundColor='#fff0f0';tag.appendChild(document.createTextNode(msg));output.appendChild(tag);for(var ai=0;ai<args.length;ai++){var value=args[ai];if(value instanceof Array){tag=document.createElement('div');tag.innerHTML=mjt.flatten_markup(value);output.appendChild(tag);continue;}
tag=document.createElement('pre');if(typeof(value)=='string'){text=value;}else{try{text=JSON.stringify(value);}catch(e){text=''+value;}}
text=text.replace(/\r?\n/g,'\r\n');tag.appendChild(document.createTextNode(text));output.appendChild(tag);}
var container=document.getElementById('mjt_debug_output');if(!container)
container=document.getElementsByTagName('body')[0];if(container)
container.appendChild(output);};(function(){if(typeof console!='object'||typeof console.log=='undefined'){if(typeof document!='undefined'){mjt.error=function(){spew_to_page('error',arguments);return'';};mjt.warn=function(){spew_to_page('warning',arguments);return'';};mjt.log=function(){return'';};mjt.note=function(){return'';};mjt.openlog=function(){return'';};mjt.closelog=function(){return'';};mjt.assert=function(){return'';};}else if(typeof Packages!='undefined'){var os=java.lang.System.err;mjt.error=function(){os.println('error: '+mjt._format_arguments(arguments));return'';};mjt.warn=function(){os.println('error: '+mjt._format_arguments(arguments));return'';};mjt.log=function(){os.println('log: '+mjt._format_arguments(arguments));return'';};mjt.note=function(){os.println('note: '+mjt._format_arguments(arguments));return'';};mjt.openlog=function(){return'';};mjt.closelog=function(){return'';};mjt.assert=function(){return'';};}}else if(typeof console.debug=='function'){mjt.error=function(){console.error.apply(console,arguments);return'';};mjt.warn=function(){console.warn.apply(console,arguments);return'';};mjt.log=function(){console.log.apply(console,arguments);return'';};mjt.note=function(){if(mjt.debug)
console.info.apply(console,arguments);return'';};if(typeof console.group!='undefined'){mjt.openlog=function(){if(mjt.debug)
console.group.apply(console,arguments);};}else{mjt.openlog=mjt.log;}
if(typeof console.groupEnd!='undefined'){mjt.closelog=function(){if(mjt.debug)
console.groupEnd.apply(console,arguments);return'';};}else{mjt.closelog=function(){return'';};}
mjt.assert=function(b){if(!b){console.error.apply(console,arguments);throw new Error('assertion failed');}
return'';};}else{mjt.error=function(){console.log('error: '+mjt._format_arguments(arguments));return'';};mjt.warn=function(){console.log('warning: '+mjt._format_arguments(arguments));return'';};mjt.log=function(){return'';};mjt.note=function(){return'';};mjt.openlog=function(){return'';};mjt.closelog=function(){return'';};mjt.assert=function(){return'';};}})();var _uri_ok_chars={'~':true,'!':true,'*':true,'(':true,')':true,'-':true,'_':true,'.':true,',':true,':':true,'@':true,'$':true,"'":true,'/':true};mjt.formquote=function(x){if(/^[-A-Za-z0-9~!*()_.',:@$\/]*$/.test(x))
return x;return encodeURIComponent(x).replace('%2C',',','g').replace('%3A',':','g').replace('%40','@','g').replace('%24','$','g').replace('%2F','/','g');};mjt.formencode=function(values){var qtext=[];var sep='';var k,v,ki,ks=[];for(k in values)
ks.push(k);ks.sort();for(ki in ks){k=ks[ki];v=values[k];if(typeof v=='undefined')continue;if(!(v instanceof Array))
v=[v];for(var a in v){var lv=v[a];qtext.push(sep);sep='&';qtext.push(mjt.formquote(k));qtext.push('=');qtext.push(mjt.formquote(lv));}}
return qtext.join('');};mjt.formdecode=function(qstr){if(typeof qstr=='undefined'||qstr===null)
return{};qstr=qstr.replace(/^\s*/m,'').replace(/\s+$/m,'');if(qstr=='')
return{};var qdict={};var qpairs=qstr.split('&');for(var i=0;i<qpairs.length;i++){var splitpt=qpairs[i].indexOf('=');if(splitpt<1){mjt.log('bad uri query argument, missing "=": ',qpairs[i]);continue;}
var m=[qpairs[i].substring(0,splitpt),qpairs[i].substring(splitpt+1)];var k=decodeURIComponent(m[0].replace(/\+/g,' '));var v=decodeURIComponent(m[1].replace(/\+/g,' '));if(k in qdict){if(qdict[k]instanceof Array)
qdict[k].push(v);else
qdict[k]=[qdict[k],v];}else{qdict[k]=v;}}
return qdict;};mjt.form_url=function(base,values){var q=values&&mjt.formencode(values);if(q=='')
return base;return base+'?'+mjt.formencode(values);};mjt.htmlencode=function(s){if(typeof(s)!='string')
s=''+s;return s.replace(/\&/g,'&amp;').replace(/\</g,'&lt;').replace(/\>/g,'&gt;').replace(/\"/g,'&quot;');};mjt.label_package=function(dotpath){var o=window;if(dotpath){var path=dotpath.split('.');while(path.length){o=o[path.shift()];}
if(typeof o=='function')
o=o.prototype;if((typeof o=='object'||typeof o=='function')&&o!==null)
o._package_name=dotpath;else
mjt.log('missing package',dotpath);}
var isFunction=function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");};for(var k in o){var defn=o[k];if(mjt&&mjt.Task&&isFunction(defn)&&typeof defn.prototype=='object'&&defn.prototype instanceof mjt.Task){defn.prototype._task_class=dotpath+'.'+k;}}};})(mjt);(function(mjt){var _safe_constructor_token=['safe_constructor_token'];var isFunction=function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");};var makeArray=function(a){var r=[];if(typeof a!="array")
for(var i=0,al=a.length;i<al;i++)
r.push(a[i]);else
r=a.slice(0);return r;};mjt.thunk=function(method,obj){return mjt.vthunk(arguments);};mjt.vthunk=function(){var bound_this,bound_func,bound_args;var arg0=arguments[0];if(typeof arg0=='object'&&typeof arg0.length=='number'){bound_args=makeArray(arg0);}else{bound_args=makeArray(arguments);}
arg0=bound_args.shift();if(typeof arg0=='string'){bound_this=bound_args.shift();bound_func=arg0;if(!isFunction(bound_this[bound_func])){mjt.warn('mjt.thunk:',bound_func,'is not a method of',bound_this);}}else{bound_this=null;bound_func=arg0;if(!isFunction(bound_func)){mjt.error('mjt.thunk:',bound_func,'is not a function');}}
var thunk_id=arguments.callee._next_thunk_id||1;arguments.callee._next_thunk_id=thunk_id+1;var thunk=function(){var self=arguments.callee;var call_args=self.bound_args.concat(makeArray(arguments));var obj=self.bound_this===null?this:self.bound_this;var func=self.bound_func;if(typeof func=='string')
func=obj[func];if(!isFunction(func)){mjt.error('mjt.thunk: bad function',self,self.bound_func,obj);}
return func.apply(obj,call_args);};thunk.bound_this=bound_this;thunk.bound_func=bound_func;thunk.bound_args=bound_args;thunk.thunk_id=thunk_id;return thunk;}
mjt.vcall=function(thunkspec){var call_args=makeArray(arguments).slice(1);return mjt.vthunk(thunkspec).apply(this,call_args);};mjt.vapply=function(thunkspec,call_args){return mjt.vthunk(thunkspec).apply(this,call_args);};mjt.Task=function(){if(arguments.length!==1||arguments[0]!==_safe_constructor_token){mjt.error('new mjt.Task() is illegal');throw new Error("don't call mjt.Task()");}};mjt.Task.prototype.toString=function(){return'['+this._task_id+']';};mjt.Task.prototype.toMarkup=function(){return'<span class="mjt_task">task '
+this._task_id+':'+this.state+'</span>';};if(typeof Object.getPrototypeOf!=="function"){if(typeof"test".__proto__==="object"){Object.getPrototypeOf=function(object){return object.__proto__;};}else{Object.getPrototypeOf=function(object){return object.constructor.prototype;};}}
mjt.define_task=function(sooper,params){var task_ctor=function(){var obj;var args=makeArray(arguments);if(this instanceof arguments.callee){if(args.length!==1||args[0]!==_safe_constructor_token){throw new Error('Task class should not be invoked with new ()');}else{return undefined;}}else{obj=new arguments.callee(_safe_constructor_token);obj._factory=this;}
var tmpa=[];for(var tmp=arguments.callee;tmp!==undefined;tmp=tmp.__super){tmpa.push(tmp);}
while(tmpa.length){var ctor=tmpa.pop();if(ctor.prototype.hasOwnProperty('init'))
ctor.prototype.init.apply(obj,args);}
if(typeof arguments.callee._auto_enqueue!='undefined'){obj.enqueue();}
return obj;};if(!sooper)
sooper=mjt.Task;task_ctor.prototype=new sooper(_safe_constructor_token);task_ctor.prototype.constructor=task_ctor;task_ctor.__super=sooper;task_ctor.prototype.parameters=params||[];return task_ctor;};mjt.Task._default_timeout=10000;mjt.Task.pending=null;mjt.Task._on_pending_empty=[];mjt.Task.await_pending_empty=function(){var t=mjt.Task();if(this.pending===null)
return t.ready();this._on_pending_empty.push(t);return t;};mjt.Task.add_pending=function(task){if(this.pending===null)
this.pending={};this.pending[task._task_id]=task;};mjt.Task.delete_pending=function(task){delete this.pending[task._task_id];var pending_empty=true;for(var pk in this.pending){pending_empty=false;break;}
if(pending_empty)
this.pending=null;while(this.pending==null&&this._on_pending_empty.length)
this._on_pending_empty.shift().ready();};mjt.Task.prototype.init=function(){mjt.assert(typeof this.state==='undefined');this.state='init';this._onready=[];this._onerror=[];this._timeout=null;this._prereqs={};this._task_id=mjt.uniqueid(this._task_class?this._task_class:'task');mjt.Task.add_pending(this);for(var i=0;i<this.parameters.length;i++){var param=this.parameters[i];this[param.name]=typeof arguments[i]!='undefined'?arguments[i]:param['default'];}
return this;};mjt.Task.prototype.set_timeout=function(msec){if(typeof msec==='undefined')
msec=mjt.Task._default_timeout;if(this._timeout!==null)
mjt.error('timeout already set');if(typeof setTimeout!='undefined')
this._timeout=setTimeout(mjt.thunk('timeout',this),msec);return this;};mjt.Task.prototype.clear_timeout=function(){if(this._timeout!==null)
clearTimeout(this._timeout);this._timeout=null;return this;};mjt.Task.prototype.require=function(prereq){if(this.state!=='init')
throw new Error('task.enqueue() already called - too late for .require()');if(prereq.state=='ready')
return this;if(this.state=='error')
return this;if(prereq.state=='error')
return this._prereq_error(prereq);this._prereqs[prereq._task_id]=prereq;prereq.onready('_prereq_ready',this,prereq).onerror('_prereq_error',this,prereq);return this;};mjt.Task.prototype.enqueue=function(){if(this.state!='init')
return this;this.state='wait';if(mjt.Task.debug){mjt.openlog(this,'.enqueue()');}
try{for(var k in this._prereqs)
this._prereqs[k].enqueue();return this._prereqs_check();}finally{mjt.closelog();}};mjt.Task.prototype._prereqs_check=function(){if(this._prereqs===null)
return this;for(var prereq in this._prereqs)
return this;if(this.state=='init')
return this;this._prereqs=null;this.request();return this;};mjt.Task.prototype.request=function(){return this.ready();};mjt.Task.prototype._prereq_ready=function(prereq){if(this._prereqs===null)
return this;delete this._prereqs[prereq._task_id];return this._prereqs_check();};mjt.Task.prototype._prereq_error=function(prereq){if(this._prereqs===null)
return this;this._prereqs=null;var msg=prereq.messages[0];return this.error(msg.code,msg.message,msg.text);};mjt.Task.prototype.onready=function(THUNK_ARGS){if(this.state=='ready'){mjt.vcall(arguments,this.result);}else if(this._onready instanceof Array){this._onready.push(mjt.vthunk(arguments));}
return this;};mjt.Task.prototype.onerror=function(THUNK_ARGS){if(this.state=='error'){var code=this.messages[0].code;var message=this.messages[0].message;var full=this.messages[0].text;mjt.vcall(arguments,code,message,full);}else if(this._onerror instanceof Array){this._onerror.push(mjt.vthunk(arguments));}
return this;};mjt.Task.prototype.ondone=function(THUNK_ARGS){this.onready.apply(this,arguments);this.onerror.apply(this,arguments);return this;};mjt.Task.prototype._state_notify=function(state,callbacks,args){if(!mjt.Task.debug){for(var i=0;i<callbacks.length;i++){var cb=callbacks[i];cb.apply(this,args);}
return this;}
if(!callbacks.length){mjt.log(this,'.on'+state);}
for(var i=0;i<callbacks.length;i++){var cb=callbacks[i];if(typeof cb.bound_func!=='undefined')
mjt.openlog(this,'.on'+state,' -> '+cb.bound_this+'.',cb.bound_func,cb.bound_args,cb);else
mjt.openlog(this,'.on'+state,cb);try{cb.apply(this,args);}finally{mjt.closelog();}}
return this;};mjt.Task.prototype.ready=function(result){if(this._prereqs!==null){for(var k in this._prereqs){if(typeof this._prereqs[k]=='undefined')
continue;mjt.error('task.ready() called with remaining prereqs',this);throw new Error('task.ready() called with remaining prereqs');break;}}
if(this.state=='init'){this._prereqs=null;this.state='wait';}
if(this.state!=='wait'){throw new Error('task.ready() called in bad state "'+this.state+'", should be "wait"');}
this._onerror=null;this.clear_timeout();this.state='ready';var callbacks=this._onready;this._onready=null;this.result=result;mjt.Task.delete_pending(this);this._state_notify('ready',callbacks,[result]);return this;};mjt.Task.prototype._error=function(messages,error_chain){this._prereqs=null;this._onready=null;this.clear_timeout();var callbacks=this._onerror;this._onerror=null;if(this.state=='init'){this._prereqs=null;this.state='wait';}
if(this.state!=='wait'){throw new Error('task.error() called in bad state "'+this.state+'". Error was '+messages[0].message);}
this.state='error';this.messages=messages;this._error_chain=error_chain;var task_info=this;var args=[messages[0].code,messages[0].message,messages[0].text,task_info];mjt.Task.delete_pending(this);this._state_notify('error',callbacks,args);return this;};mjt.Task.prototype.error=function(code,message,full){var messages=[{code:code,message:message,text:(typeof full!=='undefined')?full:''}];return this._error(messages);};mjt.Task.prototype.error_nest=function(failed_task){return this._error(failed_task.messages,failed_task);};mjt.Task.prototype.timeout=function(){this._timeout=null;return this.error('/user/mjt/messages/task_timeout','task timed out - possible unreachable server?');};mjt.Succeed=mjt.define_task(null,[{name:'succeed_result','default':null}]);mjt.Succeed.prototype.request=function(){return this.ready(this.succeed_result);};mjt.Fail=mjt.define_task(null,[{name:'fail_code','default':'mjt_fail'},{name:'fail_message','default':'error signaled using mjt.Fail'},{name:'fail_full','default':''}]);mjt.Fail.prototype.request=function(){return this.error(this.fail_code,this.fail_message,this.fail_full);};})(mjt);(function(mjt){mjt.PagerSlice=mjt.define_task(null,[{name:'pager'},{name:'start'},{name:'count'}]);mjt.PagerSlice.prototype.init=function(){this.chunks=this.pager.slice_chunks(this.start,this.count);var chunks=this.chunks;for(var i=0;i<chunks.length;i++)
this.require(chunks[i]);return this.enqueue();};mjt.PagerSlice.prototype.request=function(){var chunks=this.chunks;var results=[];var end=this.start+this.count;for(var i=0;i<chunks.length;i++){var chunk=chunks[i];var starti=this.start-chunk.start;if(starti<0)continue;var count=starti+this.count;if(starti+count>chunk.count)
count=chunk.count-starti;if(count<=0)continue;if(starti==0&&count==chunk.count)
results=results.concat(chunk.result);else
results=results.concat(chunk.result.slice(starti,count));}
return this.ready(results);};mjt.Pager=function(first_chunk){this.chunks=[];this.chunks_waiting=0;this.add_chunk(first_chunk);};mjt.Pager.prototype._next_chunk=function(count){var last_chunk=this.chunks[this.chunks.length-1];var task=last_chunk.next(count);this.add_chunk(task);return task;};mjt.Pager.prototype.add_chunk=function(task){task.enqueue();this.chunks_waiting++;task.onready('chunk_ready',this).onerror('chunk_error',this);this.chunks.push(task);return this;};mjt.Pager.prototype.chunk_ready=function(){this.chunks_waiting--;};mjt.Pager.prototype.chunk_error=function(){this.chunks_waiting--;};mjt.Pager.prototype.slice_chunks=function(start,count){var slice=[];var end=start+count;var chunks=this.chunks;var nexti=0;for(var ci=0;ci<chunks.length;ci++){var chunk=this.chunks[ci];if(chunk.start>=end)continue;if(chunk.start+chunk.end<=start)continue;slice.push(chunk);nexti=chunk.start+chunk.count;}
if(end>nexti){slice.push(this._next_chunk(end-nexti));}
return slice;};mjt.Pager.prototype.slicetask=function(start,count){return mjt.PagerSlice(this,start,count);};mjt.Pager.prototype.slice=function(start,count,onready,onerror){this.slicetask(start,count).onready(onready).onerror(onerror);};})(mjt);(function(mjt){mjt.dynamic_script=function(tag_id,url,text){var head=document.getElementsByTagName('head')[0];var tag=document.createElement('script');tag.type='text/javascript';if(typeof tag_id=='string')
tag.id=tag_id;if(typeof url!=='undefined')
tag.src=url;if(typeof text!=='undefined'){if(/WebKit|Khtml/i.test(navigator.userAgent))
throw new Error('safari doesnt evaluate dynamic script text');tag.text=text;}
head.appendChild(tag);return tag;};mjt.dynamic_iframe=function(id,url){var iframe=document.createElement('iframe');if(typeof id=='string')
iframe.id=id;iframe.style.display='none';iframe.className='mjt_dynamic';iframe.setAttribute('src',url);return iframe;};mjt.AsyncScript=mjt.define_task(null,{name:'url'});mjt.AsyncScript.prototype.request=function(){var task=this;var js=mjt.dynamic_script(null,this.url);if(/WebKit|Khtml/i.test(navigator.userAgent)){var iframe=mjt.dynamic_iframe();iframe.onload=function(){task.ready(null);};document.getElementsByTagName('body')[0].appendChild(iframe);}else{js.onreadystatechange=function(){if(/complete|loaded/.test(js.readyState))
task.ready(null);};js.onload=function(){task.ready(null);};}};mjt.AsyncIframe=mjt.define_task(null,{name:'url'});mjt.AsyncIframe.prototype.request=function(){this.domid=mjt.uniqueid('mjt_iframe');this.iframe=mjt.dynamic_iframe(this.domid,this.url);var task=this;var iframe=this.iframe;function inner_document(){var idoc=(iframe.contentWindow||iframe.contentDocument);if(idoc.document)
return idoc.document;return idoc;}
iframe.onload=function(){task.ready(inner_document(iframe));};iframe.onreadystatechange=function(){if(iframe.readyState=='complete'){task.ready(inner_document(iframe));}};document.getElementsByTagName('body')[0].appendChild(iframe);};})(mjt);(function(mjt){var _tbl=[0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D];mjt.crc32=function(str,crc){if(typeof crc=='undefined')crc=0;var n=0;var x=0;var tbl=_tbl;crc=crc^(-1);for(var i=0,iTop=str.length;i<iTop;i++){n=(crc^str.charCodeAt(i))&0xFF;crc=(crc>>>8)^tbl[n];}
return crc^(-1);};mjt.hash=function(s){return(mjt.crc32(s)+0x80000000).toString(16).toUpperCase();};})(mjt);(function(mjt){mjt.JsonP=mjt.define_task();mjt.JsonP._cb={};mjt.JsonP._cache={};mjt.JsonP.flush_cache=function(){mjt.JsonP._cache={};};mjt.JsonP.prototype.init=function(){this.url=null;this._cbid=null;return this;};mjt.JsonP.prototype.generate_callback_id=function(urlbase){if(typeof urlbase=='undefined'){this._cbid=mjt.uniqueid('cb');return this;}
this._cbid='c'+mjt.hash(this.url);if(typeof mjt.JsonP._cb[this._cbid]=='undefined')
return this;mjt.log('info: repeated jsonp url hash',this._cbid,this.url);this._cbid=mjt.uniqueid('cb');return this;};mjt.JsonP.prototype.install=function(){mjt.JsonP._cache[this.url]=this;this.generate_callback_id(this.url);var cbstr=this.callback_param+'=mjt.JsonP._cb.'+this._cbid;var qsep=/\?/.test(this.url)?'&':'?';this.cburl=this.url+qsep+cbstr;var jsonp=this;this._f=function(response){delete mjt.JsonP._cb[jsonp._cbid];jsonp.ready(response);};mjt.JsonP._cb[this._cbid]=this._f;this.onerror(function jsonp_error_cleanup(code,msg){function warn_stale_jsonp_response(){mjt.log('JSONP already completed with ',code,':',msg);delete mjt.JsonP._cb[jsonp._cbid];}
warn_stale_jsonp_response._stale_jsonp_timed_out=new Date();mjt.JsonP._cb[jsonp._cbid]=warn_stale_jsonp_response;});return this._send_request();};mjt.JsonP.prototype.request=function(){if(!this.url)
throw new Error('jsonp.url should be set, not '+this.url);if(typeof mjt.JsonP._cache[this.url]=='undefined'){return this.install();}
var original=mjt.JsonP._cache[this.url];if(!(typeof original['cache_controller']=='undefined'||original.cache_controller===null||original.cache_controller.is_fresh(original))){delete mjt.JsonP._cache[this.url];return this.install();}
return original.onready('ready',this).onerror('error',this);};mjt.JsonP.prototype._send_request=function(){mjt.dynamic_script(undefined,this.cburl);return this;};mjt.JsonP.prototype.jsonp_request_form=function(urlbase,form,callback_param){var urlquery=typeof form=='string'?form:mjt.formencode(form);var url=urlbase;if(urlquery)
url+='?'+urlquery;this.url=url;if(typeof acre==='undefined'&&url.length>2083){mjt.warn('mjt.JsonP: Warning: Adding a SCRIPT tag with a url of '+url.length+' chars. This is too long for Internet Explorer 7');mjt.log(url);}
this.callback_param=callback_param;return this.enqueue();};})(mjt);(function(mjt){mjt.Xhr=mjt.define_task(null,[{name:'method'},{name:'url'},{name:'content_type','default':null},{name:'body','default':null},{name:'headers','default':null}]);mjt.Xhr.prototype.init=function(){var xhr;if(typeof XMLHttpRequest!="undefined"){xhr=new XMLHttpRequest();}else if(typeof ActiveXObject!="undefined"){xhr=new ActiveXObject("MSXML2.XmlHttp");}else{return this.error('no XMLHttpRequest found');}
if(this.headers===null)
this.headers={};this.xhr=xhr;return this;};mjt.Xhr.prototype.request=function(){var task=this;var xhr=this.xhr;xhr.onreadystatechange=function(e){if(xhr.readyState!=4)
return task;xhr.onreadystatechange=function(){};if((''+xhr.status).charAt(0)=='2')
return task.ready(xhr);return task.error('/apiary/http/status/'+xhr.status,xhr.statusText,xhr.responseText);};xhr.open(this.method,this.url,true);if(this.content_type!==null)
xhr.setRequestHeader('Content-Type',this.content_type);xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');for(header in this.headers){xhr.setRequestHeader(header,this.headers[header]);}
if(this.body===null){var r=xhr.send('');}else{var r=xhr.send(this.body);this.body=null;}
return this;};mjt.XhrFormPost=function(url,form,headers){var body=mjt.formencode(form);return mjt.Xhr('POST',url,'application/x-www-form-urlencoded',body,headers);};})(mjt);(function(mjt){if(typeof mjt.freebase=='undefined')
mjt.freebase={};mjt.freebase.default_service_url='http://www.freebase.com';mjt.freebase.set_service_url=function(service_url){var loc;if(typeof window!='undefined')
loc=window.location.protocol+'//'+window.location.host;if(typeof acre!='undefined')
loc=acre.environ.server_protocol+'//'+acre.environ.host;mjt.freebase.service_url=service_url;mjt.freebase.xhr_ok=mjt.freebase.service_url==loc?true:false;if(typeof mjt.freebase.SchemaCache!='undefined'){this.schema_cache=new this.SchemaCache(this);}};mjt.freebase.set_service_url(mjt.freebase.default_service_url);function FreebaseCacheController(){var _mwLastWriteTime=mjt.freebase.readCookie('mwLastWriteTime');this.is_fresh=function(task){if(/\/api\/service\/touch$/.test(task.url)){return false;}
var mwLastWriteTime=mjt.freebase.readCookie('mwLastWriteTime');return(_mwLastWriteTime==mwLastWriteTime);};}
mjt.freebase.FreebaseJsonPTask=mjt.define_task();mjt.freebase.FreebaseJsonPTask.prototype.service_request=function(path,form){var service_url=mjt.freebase.service_url;if(typeof this.service_url!='undefined'&&this.service_url)
service_url=this.service_url;var url=service_url+path;this.jsonp=mjt.JsonP();if(typeof mjt.freebase.readCookie!='undefined'){this.jsonp.cache_controller=new FreebaseCacheController();}
this.jsonp.set_timeout().jsonp_request_form(url,form,'callback').onready('handle_envelope',this).onerror('handle_error_jsonp',this);return this;};mjt.freebase.FreebaseJsonPTask.prototype.handle_envelope=function(o){if(o.code!='/api/status/ok'){var msg=o.messages[0];return this.error(msg.code,msg.message,msg);}
return this.response(o);};mjt.freebase.FreebaseJsonPTask.prototype.handle_error_jsonp=function(){this.error.apply(this,arguments);};mjt.freebase.FreebaseJsonPTask.prototype.request=function(){mjt.error('must override BaseTask.request()');};mjt.freebase.FreebaseJsonPTask.prototype.response=function(o){mjt.error('must override BaseTask.response()');};mjt.freebase.MqlRead=mjt.define_task(mjt.freebase.FreebaseJsonPTask,[{name:'query'},{name:'qenv','default':{}}]);mjt.freebase.MqlRead.prototype.build_envelope=function(){var envelope={escape:false};for(var k in this.qenv)
envelope[k]=this.qenv[k];envelope.query=this.query;if(this.query instanceof Array){if(typeof envelope.cursor=='undefined'){envelope.cursor=true;this.start=0;}
this.requested_count=this.query[0].limit||100;}
return envelope;};mjt.freebase.MqlRead.prototype.request=function(){var envelope=this.build_envelope();var s=JSON.stringify(envelope);return this.service_request('/api/service/mqlread',{query:s});};mjt.freebase.MqlRead.prototype.response=function(o){if(o.result===null)
return this.error('/user/mjt/messages/empty_result','no results found');if(typeof o.cursor==='string')
this.next_cursor=o.cursor;if(o.result instanceof Array){this.count=o.result.length;this.more_available=false;if(this.count>=this.requested_count&&this.next_cursor!=false)
this.more_available=true;}
return this.ready(o.result);};mjt.freebase.MqlRead.prototype.next=function(reqcount){if(this.state!=='ready'){throw new Error('MqlRead.next(): bad state '+this.state);}
if(!this.more_available){mjt.warn('paging .next(): no more items',this);return null;}
var qold=this.query[0]
var q={};for(var k in qold){if(qold.hasOwnProperty(k))
q[k]=qold[k];}
if(typeof reqcount!='undefined')
q.limit=reqcount;var task=mjt.freebase.MqlRead([q],{cursor:this.next_cursor});task.start=this.start+this.count;return task;};mjt.freebase.MqlReadMultiple=mjt.define_task(mjt.freebase.FreebaseJsonPTask);mjt.freebase.MqlReadMultiple.prototype.init=function(){this.reads={};};mjt.freebase.MqlReadMultiple.prototype.request=function(){var queries={};for(var k in this.reads)
queries[k]=this.reads[k].build_envelope();var s=JSON.stringify(queries);return this.service_request('/api/service/mqlread',{queries:s});};mjt.freebase.MqlReadMultiple.prototype.mqlread=function(key,task){this.reads[key]=task;return this;};mjt.freebase.MqlReadMultiple.prototype.response=function(o){for(var k in this.reads){var task=this.reads[k];task.handle_envelope(o[k]);}
return this.ready(o.result);};mjt.freebase.TransGet=mjt.define_task(mjt.freebase.FreebaseJsonPTask,[{name:'id'},{name:'trans_type','default':'raw'},{name:'values','default':null}]);mjt.freebase.TransGet.prototype.request=function(){if(this.values===null)this.values={};var path='/api/trans/'+this.trans_type+this.id;return this.service_request(path,this.values);};mjt.freebase.TransGet.prototype.response=function(o){o.result.media_type=o.result.media_type.replace(/^\/media_type\//,'');if(typeof o.result.text_encoding=='string')
o.result.text_encoding=o.result.text_encoding.replace(/^\/media_type\/text_encoding\//,'');return this.ready(o.result);};mjt.freebase.Touch=mjt.define_task(mjt.freebase.FreebaseJsonPTask,[{name:'service_url','default':null}]);mjt.freebase.Touch.prototype.request=function(){return this.service_request('/api/service/touch');};mjt.freebase.Touch.prototype.response=function(o){return this.ready(null);};})(mjt);(function(mjt){var setIso8601=function(dateObject,formattedString){var comps=(formattedString.indexOf("T")==-1)?formattedString.split(" "):formattedString.split("T");dateObject=setIso8601Date(dateObject,comps[0]);if(comps.length==2){dateObject=setIso8601Time(dateObject,comps[1]);}
return dateObject;};var fromIso8601=function(formattedString){return setIso8601(new Date(0,0),formattedString);};var setIso8601Date=function(dateObject,formattedString){var regexp="^([0-9]{4})((-?([0-9]{2})(-?([0-9]{2}))?)|"+"(-?([0-9]{3}))|(-?W([0-9]{2})(-?([1-7]))?))?$";var d=formattedString.match(new RegExp(regexp));if(!d){mjt.log("invalid date string: "+formattedString);return NaN;}
var year=d[1];var month=d[4];var date=d[6];var dayofyear=d[8];var week=d[10];var dayofweek=d[12]||1;dateObject.setFullYear(year);if(dayofyear){dateObject.setMonth(0);dateObject.setDate(Number(dayofyear));}
else if(week){dateObject.setMonth(0);dateObject.setDate(1);var day=dateObject.getDay()||7;var offset=Number(dayofweek)+(7*Number(week));if(day<=4){dateObject.setDate(offset+1-day);}
else{dateObject.setDate(offset+8-day);}}else{if(month){dateObject.setDate(1);dateObject.setMonth(month-1);}
if(date){dateObject.setDate(date);}}
return dateObject;};var fromIso8601Date=function(formattedString){return setIso8601Date(new Date(0,0),formattedString);};var setIso8601Time=function(dateObject,formattedString){var timezone="Z|(([-+])([0-9]{2})(:?([0-9]{2}))?)$";var d=formattedString.match(new RegExp(timezone));var offset=0;if(d){if(d[0]!='Z'){offset=(Number(d[3])*60)+Number(d[5]||0);if(d[2]!='-'){offset*=-1;}}
offset-=dateObject.getTimezoneOffset();formattedString=formattedString.substr(0,formattedString.length-d[0].length);}
var regexp="^([0-9]{2})(:?([0-9]{2})(:?([0-9]{2})(\.([0-9]+))?)?)?$";d=formattedString.match(new RegExp(regexp));if(!d){mjt.log("invalid time string: "+formattedString);return NaN;}
var hours=d[1];var mins=Number(d[3]||0);var secs=d[5]||0;var ms=d[7]?(Number("0."+d[7])*1000):0;dateObject.setHours(hours);dateObject.setMinutes(mins);dateObject.setSeconds(secs);dateObject.setMilliseconds(ms);if(offset!==0){dateObject.setTime(dateObject.getTime()+offset*60000);}
return dateObject;};var fromIso8601Time=function(formattedString){return setIso8601Time(new Date(0,0),formattedString);};var toRfc3339=function(dateObject,selector){if(!dateObject){dateObject=new Date();}
var _=function(str,len,c,dir){var out=String(str);if(!c){c='0';}
if(!dir){dir=1;}
while(out.length<len){if(dir>0){out=c+out;}else{out+=c;}}
return out;}
var formattedDate=[];if(selector!="timeOnly"){var date=[_(dateObject.getFullYear(),4),_(dateObject.getMonth()+1,2),_(dateObject.getDate(),2)].join('-');formattedDate.push(date);}
if(selector!="dateOnly"){var time=[_(dateObject.getHours(),2),_(dateObject.getMinutes(),2),_(dateObject.getSeconds(),2)].join(':');var timezoneOffset=dateObject.getTimezoneOffset();time+=(timezoneOffset>0?"-":"+")+
_(Math.floor(Math.abs(timezoneOffset)/60),2)+":"+
_(Math.abs(timezoneOffset)%60,2);formattedDate.push(time);}
return formattedDate.join('T');};var fromRfc3339=function(rfcDate){if(rfcDate.indexOf("Tany")!=-1){rfcDate=rfcDate.replace("Tany","");}
var dateObject=new Date();return setIso8601(dateObject,rfcDate);};var toISO8601String=function(date,format,offset){if(!format){format=6;}
if(!offset){offset='Z';}else{var d=offset.match(/([-+])([0-9]{2}):([0-9]{2})/);var offsetnum=(Number(d[2])*60)+Number(d[3]);offsetnum*=((d[1]=='-')?-1:1);date=new Date(Number(Number(date)+(offsetnum*60000)));}
var zeropad=function(num){return((num<10)?'0':'')+num;};var str="";str+=date.getUTCFullYear();if(format>1){str+="-"+zeropad(date.getUTCMonth()+1);}
if(format>2){str+="-"+zeropad(date.getUTCDate());}
if(format>3){str+="T"+zeropad(date.getUTCHours())+":"+zeropad(date.getUTCMinutes());}
if(format>5){var secs=Number(date.getUTCSeconds()+"."+
((date.getUTCMilliseconds()<100)?'0':'')+
zeropad(date.getUTCMilliseconds()));str+=":"+zeropad(secs);}else if(format>4){str+=":"+zeropad(date.getUTCSeconds());}
if(format>3){str+=offset;}
return str;};mjt.freebase.date_from_iso=function(isodate){if(typeof isodate=='undefined'||isodate===null)
return NaN;return fromIso8601(isodate.toString());};mjt.freebase.date_to_iso=function(d){return toISO8601String(d);};})(mjt);(function(mjt){mjt.freebase.imgurl=function(cid,maxwidth,maxheight,mode,errorid){var qargs={};if(typeof maxwidth!=='undefined'){qargs.maxwidth=maxwidth;}
if(typeof maxheight!=='undefined'){qargs.maxheight=maxheight;}
if(typeof mode!=='undefined'){qargs.mode=mode;}
if(typeof mode!=='undefined'){qargs.errorid=errorid;}
return mjt.form_url(this.service_url+'/api/trans/image_thumb'
+mjt.formquote(cid),qargs);};mjt.freebase.extend_query=function(query,paths){if(typeof paths=='undefined')
paths={};if(typeof query=='undefined')
throw new Error('extend_query: MQL query is undefined');for(var path in paths){var val=paths[path];var pathkeys=path.split('.');var last_key=pathkeys.pop();var obj=query instanceof Array?query[0]:query;for(var i=0;i<pathkeys.length;i++){var key=pathkeys[i];if(typeof obj[key]!='object'||obj[key]===null){obj[key]={};}
obj=obj[key];if(obj instanceof Array){if(obj.length==0)
obj=[{}];if(obj.length>1)
throw new Error('extend_query: path '+JSON.stringify(path)
+' references an array with more than one element');obj=obj[0];}}
if(obj===null||typeof obj!='object'){throw new Error('extend_query: path '+JSON.stringify(path)
+' does not exist in query');}
obj[last_key]=val;}
return query;};})(mjt);(function(mjt){var mqlkey_start='A-Za-z0-9';var mqlkey_char='A-Za-z0-9_-';var MQLKEY_VALID=new RegExp('^['+mqlkey_start+']['+mqlkey_char+']*$');var MQLKEY_CHAR_MUSTQUOTE=new RegExp('([^'+mqlkey_char+'])','g');mjt.freebase.mqlkey_quote=function(s){if(MQLKEY_VALID.exec(s))
return s;var convert=function(a,b){var hex=b.charCodeAt(0).toString(16).toUpperCase();if(hex.length==2)
hex='00'+hex;return'$'+hex;};x=s.replace(MQLKEY_CHAR_MUSTQUOTE,convert);if(x.charAt(0)=='-'||x.charAt(0)=='_'){x=convert(x,x.charAt(0))+x.substr(1);}
return x;}
mjt.freebase.mqlkey_unquote=function(x){x=x.replace(/\$([0-9A-Fa-f]{4})/g,function(a,b){return String.fromCharCode(parseInt(b,16));});return x;}
var mqlid_to_mqlurlid=function(id){if(id.charAt(0)==='~'){return id;}
if(id.charAt(0)==='#'){return'%23'+id.substr(1);}
if(id.charAt(0)!=='/'){return'BAD-ID';}
var segs=id.split('/');var keys=[];for(var i=1;i<segs.length;i++){var seg=segs[i];keys.push(encodeURIComponent(mqlkey_unquote(seg)));}
return'/'.join(keys);}})(mjt);(function(mjt,fb){fb.readCookie=function(name){if(typeof acre!='undefined'){if(typeof acre.environ.cookies[name]=='undefined')
return'';var cookie=acre.environ.cookies[name];return cookie.value;}
if(typeof document=='undefined')return'';var cookieValue="";name+="=";if(document.cookie.length>0){var offset=document.cookie.indexOf(name);if(offset!=-1){offset+=name.length;var end=document.cookie.indexOf(";",offset);if(end==-1)end=document.cookie.length;cookieValue=document.cookie.substring(offset,end);}}
return cookieValue;};fb.parse_metaweb_cookies=function(){function _cookieItem(c,i){var s=c.indexOf('|'+i+'_');if(s!=-1){s=s+2+i.length;var e=c.indexOf('|',s);if(e!=-1)
return decodeURIComponent(c.substr(s,e-s));}
return null;}
mjt.freebase.freebase_user=null;var cookieInfo=fb.readCookie("metaweb-user-info");if(cookieInfo.indexOf('A|')==0){var user={type:'/type/user'};user.id=_cookieItem(cookieInfo,'p');user.guid=_cookieItem(cookieInfo,'g');user.name=_cookieItem(cookieInfo,'u');if(!user.id)
user.id=user.guid;mjt.freebase.freebase_user=user;}};fb.parse_metaweb_cookies();fb.FreebaseXhrTask=mjt.define_task(null);fb.FreebaseXhrTask.prototype.init=function(){};fb.FreebaseXhrTask.prototype.xhr_request=function(method,url,content_type,body){url=fb.service_url+url;this.xhr=mjt.Xhr(method,url,content_type,body).enqueue();this.xhr.onready('xhr_ready',this).onerror('xhr_error',this,this.xhr.xhr);return this;};fb.FreebaseXhrTask.prototype.xhr_form_post=function(url,form){url=fb.service_url+url;this.xhr=mjt.XhrFormPost(url,form).enqueue();this.xhr.onready('xhr_ready',this).onerror('xhr_error',this,this.xhr.xhr);return this;};fb.FreebaseXhrTask.prototype.request=function(){};fb.FreebaseXhrTask.prototype.xhr_ready=function(xhr){var prect=xhr.getResponseHeader('content-type');var ct=prect?prect.replace(/;.*$/,''):'';if(!ct.match(/^(application\/json|text\/javascript|text\/plain)$/))
return this.error('/user/mjt/messages/json_response_expected','status: '+xhr.status+', content-type: '+ct,xhr.responseText);var o=JSON.parse(xhr.responseText);this.envelope=o;if(o.code!=='/api/status/ok')
return this.error(o.code,o.messages[0].message,o.messages[0]);return this.ready(o.result);};fb.FreebaseXhrTask.prototype.xhr_error=function(xhr,code,msg,info){var errjson=null;try{errjson=JSON.parse(info);var errmsg=errjson.messages[0];return this.error(errmsg.code,errmsg.message,errmsg);}catch(e){return this.error(code,msg,info);}};fb.TransUnsafe=mjt.define_task(null,[{name:'id'}]);fb.TransUnsafe.prototype.xhr_request=function(method,url,content_type,body){url=fb.service_url+url;this.xhr=mjt.Xhr(method,url,content_type,body).enqueue();this.xhr.onready('xhr_ready',this).onerror('xhr_error',this,this.xhr.xhr);return this;};fb.TransUnsafe.prototype.xhr_ready=function(xhr){var prect=xhr.getResponseHeader('content-type');var ct=prect?prect.replace(/;.*$/,''):'';this.content_type=ct;this.responseText=xhr.responseText
return this.ready();};fb.TransUnsafe.prototype.xhr_error=function(xhr,code,msg,info){return this.error(code,msg,info);};fb.TransUnsafe.prototype.request=function(){var path='/api/trans/unsafe'+this.id;return this.xhr_request('GET',path);};fb.MqlWrite=mjt.define_task(fb.FreebaseXhrTask,[{name:'query'},{name:'qenv','default':{}}]);fb.MqlWrite.prototype.request=function(){var qenv={query:this.query};for(var k in this.qenv)
qenv[k]=this.qenv[k];var qstr=JSON.stringify(qenv);return this.xhr_form_post('/api/service/mqlwrite',{query:qstr});};fb.FlushCache=mjt.define_task(fb.FreebaseXhrTask);fb.FlushCache.prototype.request=function(){return this.xhr_request('POST','/api/service/touch');};fb.FlushCache.prototype.xhr_ready=function(xhr){return this.ready(null);};fb.Upload=mjt.define_task(fb.FreebaseXhrTask,[{name:'content_type'},{name:'body'},{name:'values'}]);fb.Upload.prototype.request=function(){var path='/api/service/upload';var qargs=mjt.formencode(this.values);if(qargs)
path+='?'+qargs;return this.xhr_request('POST',path,this.content_type,this.body);};fb.Signin=mjt.define_task(fb.FreebaseXhrTask,[{name:'username'},{name:'password'},{name:'domain','default':null},{name:'options','default':{}}]);fb.Signin.prototype.request=function(){if(typeof this.username=='undefined')
return this.xhr_form_post('/api/account/logout',{});var form={username:this.username,password:this.password};if(this.domain!==null)
form.domain=this.domain;for(var k in this.options)
form[k]=this.options[k];return this.xhr_form_post('/api/account/login',form).ondone('clear_password',this);};fb.Signin.prototype.clear_password=function(){delete this.password;return this;};})(mjt,mjt.freebase);(function(mjt){mjt.bless=function(html){return new mjt.Markup(html);};mjt.Markup=function(html){this.html=html;};mjt.Markup.prototype.toMarkup=function(){return this.html;};(function(){function bad_markup_element(v,msg,markup){markup.push('<span style="outline-style:solid;color:red;">');if(msg){markup.push(msg);markup.push('</span>');}else{markup.push('bad markup element, type [');markup.push(typeof(v));markup.push(']</span>');}}
function flatn(x,markup){switch(typeof x){case'object':if(x===null){bad_markup_element(x,'[null]',markup);}else if(x instanceof Array){for(var i=0;i<x.length;i++)
flatn(x[i],markup);}else if(typeof x.toMarkupList==='function'){flatn(x.toMarkupList(),markup);}else if(typeof x.toMarkup==='function'){markup.push(x.toMarkup());}else if(typeof x.toString==='function'){markup.push(mjt.htmlencode(x.toString()));}else{bad_markup_element(x,'[object]',markup);}
break;case'undefined':bad_markup_element(x,'[undefined]',markup);break;case'string':markup.push(mjt.htmlencode(x));break;case'boolean':markup.push(String(x));break;case'number':markup.push(String(x));break;case'function':bad_markup_element(x,'[function]',markup);break;};return markup;}
mjt.flatten_markup=function(v){return flatn(v,[]).join('');};})();mjt.make_attr_safe=function(v){return mjt.bless(mjt.flatten_markup(v).replace(/\</g,'&lt;').replace(/\>/g,'&gt;').replace(/\"/g,'&quot;'));};})(mjt);(function(mjt){mjt._eventcb={};mjt._id_to_element=function(top){if(typeof(top)=='string'){var e=document.getElementById(top);if(!e){mjt.note('no element with id '+top);return null;}else{top=e;}}
if(top.nodeName=='IFRAME'){var idoc=(top.contentWindow||top.contentDocument);if(idoc.document)
idoc=idoc.document;top=idoc.getElementsByTagName('body')[0];}
return top;}
mjt.kws=function(){var kws={};for(var i=0;i<arguments.length;i+=2){kws[arguments[i]]=arguments[i+1];}
return kws;};mjt.foreach=function(self,items,func){var i,l,r;if((typeof items=='string')||(items instanceof Array)||(typeof jQuery=='object'&&items instanceof jQuery)){l=items.length;for(i=0;i<l;i++){r=func.apply(self,[i,items[i]]);}}else if(typeof items==='object'){if(typeof document!='undefined'&&typeof items.item!='undefined'&&items.item===document.childNodes.item){l=items.length;for(i=0;i<l;i++)
func.apply(self,[i,items.item(i)]);}else{for(i in items)
if(items.hasOwnProperty(i))
func.apply(self,[i,items[i]]);}}};mjt.ondomready=function(f,self){var queue=mjt._ondomready_queue;if(mjt._ondomready_timer===null){mjt._ondomready_timer=setTimeout(mjt._ondomready_run,20);}
queue.push(f);queue.push(self);};mjt._ondomready_queue=[];mjt._ondomready_timer=null;mjt._ondomready_run=function(){mjt._ondomready_timer=null;var queue=mjt._ondomready_queue;mjt._ondomready_queue=[];while(queue.length){var f=queue.shift();var self=queue.shift();f.apply(self);}};mjt.cleanup_noquote=function(m,escapetag){var s=mjt.flatten_markup(m);s=s.replace(/&quot;/g,'"').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');if(typeof escapetag!='undefined'){var rx=new RegExp('</('+escapetag+'\\s*)>','ig');s=s.replace(rx,'<\\/$1>');}
return mjt.bless(s);};mjt.ref=function(name){var s=['<a href="view?name=',mjt.formquote(name),'">',mjt.htmlencode(name),'</a>'].join('');return new mjt.Markup(s);};mjt.TemplateCall=function(raw_tfunc){this.raw_tfunc=raw_tfunc;delete this._markup;};mjt.TemplateCall.prototype.toMarkupList=function(){return this._markup;};mjt.TemplateCall.prototype.toMarkup=function(){return mjt.flatten_markup(this._markup);};mjt.TemplateCall.prototype.redisplay=function(){var tfunc=this.this_tfunc;var tcall=new tfunc();tcall.prev_tcall=this;tcall.subst_id=this.subst_id;tcall.render(this.targs).display();return tcall;};mjt.TemplateCall.prototype.display=function(target_id,targs){if(typeof acre!='undefined')
return this;if(typeof target_id!='undefined')
this.subst_id=target_id;var top=mjt._id_to_element(this.subst_id);if(!top){return this;}
if(typeof this._markup!='undefined')
mjt.replace_html(top,this);return this;};mjt.TemplateCall.prototype.render=function(targs){var html;if(typeof targs!='undefined')
this.targs=targs;var raw_tfunc=this.raw_tfunc;if(typeof window=='undefined'||typeof window.navigator.appName=='undefined'){this._markup=raw_tfunc.apply(this,this.targs);return this;}
try{this._markup=raw_tfunc.apply(this,this.targs);}catch(e){e.tcall=this;var codeblock=this.tpackage._codeblock;if(codeblock===null){throw e;}
codeblock.handle_exception('applying tfunc '+this.signature,e);var tstates=[];for(var t in this.tasks){var tt=this.tasks[t];if(typeof tt==='object'&&tt!==null){tstates.push(t+':'+tt.state);}else{tstates.push(t+':'+typeof tt);}}
this._markup=[mjt.bless('<h3>error applying '),this.signature,' to id=',this.subst_id,mjt.bless('</h3>'),'states:[',tstates.join(' '),']'];throw e;}
return this;};mjt.TemplateCall.prototype.mktask=function(name,task){this.tasks[name]=task;var tcall=this;if(task.state=='init')
task.enqueue();return task.ondone(function(){tcall.render().display();});};mjt.tfunc_factory=function(signature,rawtfunc,tpackage,has_tasks,toplevel){var _inline_tcall=function(){var ctor=arguments.callee;if(this instanceof ctor){this.tasks={};this.exports={};this.defs=this.exports;if(typeof mjt.deprecate=='function')
mjt.deprecate(this,'defs','.exports');return undefined;}
if(0&&!ctor.prototype.has_tasks&&!toplevel){return rawtfunc.apply(ctor.prototype,arguments);}
var self=new ctor();var targs=[];for(var ai=0;ai<arguments.length;ai++)
targs[ai]=arguments[ai];var tname=self.signature.replace(/\(.*\)$/,'');if(ctor.prototype.has_tasks)
self.subst_id=mjt.uniqueid('tcall__'+tname);else
self.subst_id=null;self.render(targs);return self;};_inline_tcall.prototype=new mjt.TemplateCall(rawtfunc);_inline_tcall.prototype.signature=signature;_inline_tcall.prototype.tpackage=tpackage;_inline_tcall.prototype.has_tasks=has_tasks;_inline_tcall.prototype.this_tfunc=_inline_tcall;return _inline_tcall;};})(mjt);(function(mjt){mjt.TemplatePackage=function(){this.source=null;this.output_prefix=null;this._template_strings=null;this._compiled=null;this._codeblock=null;this.debug_locs=null;this.output_mode=null;this._template_fragments=null;this.namespace=null;};mjt.TemplatePackage.prototype.runtime={_break_token:mjt._break_token,_continue_token:mjt._continue_token,bless:mjt.bless,cleanup_noquote:mjt.cleanup_noquote,foreach:mjt.foreach,htmlencode:mjt.htmlencode,make_attr_safe:mjt.make_attr_safe,ondomready:mjt.ondomready,ref:mjt.ref,tfunc_factory:mjt.tfunc_factory,uniqueid:mjt.uniqueid};mjt.TemplatePackage.prototype.init_from_json=function(info){if(typeof info.file!='undefined')
this.source=info.file;if(typeof info.stringtable!='undefined')
this._template_strings=info.stringtable;this._codeblock=null;if(typeof info.code=='string'){this._codeblock=new mjt.Codeblock(this.source,info.code);}else if(typeof info.code=='function'){this._compiled=info.code;}
if(typeof info.debug_locs!='undefined')
this.debug_locs=info.debug_locs;if(typeof info.output_mode!='undefined')
this.output_mode=info.output_mode;return this;};mjt.TemplatePackage.prototype.init_from_js=function(obj){var code=obj.def;var info=obj.info;this.init_from_json(info);this._compiled=code;return this;};mjt.TemplatePackage.prototype.get_metadata=function(){var pkgjson={file:this.source,stringtable:this._template_strings,debug_locs:this.debug_locs,output_mode:this.output_mode};return pkgjson;};mjt.TemplatePackage.prototype.toJSON=function(){var pkgjson=this.get_metadata();if(this._codeblock===null){mjt.warn('TemplatePackage.toJSON: complete source code unavailable',this.source);pkgjson.code=this._compiled;}else{pkgjson.code=this._codeblock.codestr;}
return JSON.stringify(pkgjson);};mjt.TemplatePackage.prototype.toJS=function(strip){var codestr=null;if(this._codeblock===null){mjt.warn('TemplatePackage.toJS: complete source code unavailable',this.source);codestr=this._compiled;}else{codestr='(function () {'+this._codeblock.codestr+'})()';}
var strs=['{def: ',codestr,',\ninfo:',JSON.stringify(this.get_metadata()),'}\n'];return strs.join('');};mjt.TemplatePackage.prototype.lookup_line=function(js_lineno){if(!(debug_locs instanceof Array)||js_lineno>=this.debug_locs.length)
return null;return this.debug_locs[js_lineno-1];};mjt.TemplatePackage.prototype.compile_document=function(top){var t0=(new Date()).getTime();var compiler=new mjt.TemplateCompiler();compiler.compile_top(top,'rawmain()',this.output_prefix);var dt=(new Date()).getTime()-t0;var info={source:this.source,stringtable:compiler.strings,code:(compiler.codestr+'; return rawmain;'),debug_locs:compiler.debug_locs,output_mode:compiler.output_mode};return this.init_from_json(info);}
mjt.TemplatePackage.prototype.load_document=function(top,targs){this.source+='#'+top.id,this.compile_document(top);return this.load(targs);};mjt.TemplatePackage.prototype.toplevel=function(targs){if(this.namespace===null)
this.load(targs);return this.namespace;};mjt.TemplatePackage.prototype.load=function(targs){this._template_fragments=[];for(var tsi=0;tsi<this._template_strings.length;tsi++)
this._template_fragments[tsi]=mjt.bless(this._template_strings[tsi]);if(this._compiled===null){if(this._codeblock===null){mjt.error('TemplatePackage has no code',this.source);}else{this._compiled=this._codeblock.evaluate();}}
if(typeof targs=='undefined')
targs=[];this._args=targs;var mainfunc=mjt.tfunc_factory("_main()",this._compiled,this,false,true);var tcall=new mainfunc();tcall.render(this._args);this.tcall=tcall;tcall.pkg=this;if(typeof this._compiled.doc_content_type!='undefined')
tcall.doc_content_type=this._compiled.doc_content_type;if(typeof tcall.exports._main!='undefined'){throw new Error("_main() is illegal as a template function name");}
this.namespace=tcall.exports;this.namespace._main=mainfunc;if(typeof tcall.exports.main!='undefined'){throw new Error("main() is illegal as a template function name");}
this.namespace.main=mainfunc;if(typeof mjt.deprecate=='function')
mjt.deprecate(this.namespace,'main','._main');return this;};})(mjt);(function(mjt){mjt.error_html=function(e,codestr,target_id){var source=[];if(codestr&&e.lineNumber){var lineno=e.lineNumber;var lines=codestr.split('\n');if(lineno<0)
lineno=0;if(lineno>=lines.length)
lineno=lines.length-1;var line0=lineno-10;if(line0<0)line0=0;var cx=[];var line;source.push(mjt.bless(['\n<pre>']));for(line=line0;line<lineno;line++)
cx.push(lines[line]);source.push(cx.join('\n'));source.push(mjt.bless(['</pre>\n<pre style="color:red">']));source.push(lines[lineno]+'\n');source.push(mjt.bless(['</pre>\n<pre>']));cx=[];for(line=lineno+1;line<lines.length;line++)
cx.push(lines[line]);source.push(cx.join('\n'));source.push(mjt.bless(['</pre>\n']));}
var html=[mjt.bless(['<div class="mjt_error"']),(target_id?[mjt.bless([' id="']),target_id,mjt.bless(['"'])]:[]),mjt.bless(['>']),e.name,': ',e.message,source,mjt.bless(['</div>\n'])];html=html.concat(source);return html;};mjt.Codeblock=function(name,codestr){this.name=name;this.codestr=codestr;this.basefile=null;this.baseline=null;};mjt.Codeblock.prototype.handle_exception=function(msg,e){if(typeof e.mjt_error!='undefined')
return;var safari=false;if(typeof e.sourceURL!='undefined'){e.fileName=e.sourceURL;}
if(typeof e.line!='undefined'){safari=true;e.lineNumber=e.line;}
if(!(e instanceof Error)){e.mjt_error={name:'Unknown exception',fileName:'',message:''+e};}else{e.mjt_error={fileName:e.fileName,lineNumber:e.lineNumber,name:e.name,message:e.message,stack:e.stack,rhinoException:e.rhinoException};}
if(!this.basefile&&!safari){}else if(typeof e.stack=='string'){var filerx=this.basefile.replace(/(\W)/g,'\\$1')+':(\\d+)\n';filerx=new RegExp(filerx);var m=filerx.exec(e.stack);if(m){var lineno=parseInt(m[1])-this.baseline;if(lineno>0)
this.log_error_context(msg,e,lineno);}}else if(e.fileName==this.basefile||safari){var lineno;if(safari){lineno=e.lineNumber-1;}
else{lineno=e.lineNumber-this.baseline;}
if(lineno>0){e.mjt_error.lineNumber=lineno;e.mjt_error.fileName='<generated code>';this.log_error_context(msg,e,lineno);}}};mjt.Codeblock.prototype.log_error_context=function(msg,e,lineno){var cx=this.extract_context(this.codestr,lineno,5);var pfx='---'+lineno+'-->  ';var spc=[];for(var i=0;i<pfx.length;i++)
spc.push(' ');spc=spc.join('');var cxtext=[spc,cx.prev_lines.join('\n'+spc),'\n',pfx,cx.the_line,'\n',spc,cx.next_lines.join('\n'+spc)].join('');mjt.error('error',msg,'\n    '+e.name+': '+e.message+'\n',cxtext);};mjt.Codeblock.prototype.extract_context=function(codestr,lineno,radius){var source=[];var lines=codestr.split('\n');if(lineno<0)
lineno=0;if(lineno>=lines.length)
lineno=lines.length-1;var line0=lineno-radius;if(line0<0)line0=0;var prev_lines=[];for(line=line0;line<lineno;line++)
prev_lines.push(lines[line]);var the_line=lines[lineno];var next_lines=[];for(line=lineno+1;line<lines.length&&line<lineno+radius;line++)
next_lines.push(lines[line]);return{prev_lines:prev_lines,the_line:the_line,next_lines:next_lines};};mjt.Codeblock.prototype.evaluate=function(){var t0=(new Date()).getTime();var code=[this.codestr];code=['var __mjt_eval = (function(){',this.codestr,'})(); __mjt_eval;\n'];var codestr=code.join('');if(mjt.debug)
mjt.log('evaluating code '+this.name,{click_me:'view code',codestr:codestr});var result;if(0&&typeof console!='undefined'&&typeof console.trace=='function'){result=eval(codestr);}else if(typeof window=='undefined'||typeof window.navigator.appName=='undefined'){result=eval(codestr);}else{try{null();}catch(e){this.baseline=e.lineNumber+2;this.basefile=e.fileName;}
try{result=eval(codestr);}catch(e){this.handle_exception('evaluating codeblock '+this.name,e);throw e;}}
var dt=(new Date()).getTime()-t0;mjt.note('evaluated code in ',dt,'msec, ',codestr.length,'chars, got ',typeof result);return result;};})(mjt);(function(mjt){mjt.Scope=function(template,parent,decl){this.template=template;if(!parent)parent=null;this.parent=parent;if(!decl)decl='[unnamed]';this.decl=decl;this.tasks={};this.toplevel=false;this.toplevel_prefix=null;};mjt.TemplateCompiler=function(){this.strings=[];this.codestr=null;this.debug_locs=[];this.source_loc=null;this.compiler_dt=null;this._markup=[];this._code=[];this.next_unique_id={};this.debug=mjt.debug;this.browser_dom=(typeof navigator!='undefined');this.browser_target=true;this.document_content_type=null;this.set_output_mode('html');this.mjtns_re=/^(?:mjt\.|mjt:|acre:)(.+)$/;this._ie_attribute_bs=this.browser_dom&&/MSIE/.test(navigator.userAgent);};mjt.TemplateCompiler.prototype.set_output_mode=function(mode){this.output_mode=mode;this.empty_tags={};this.boolean_attrs={};this.preserve_space_tags={};this.noescape_tags={};switch(mode){case'text':break;case'xml':break;case'html':this.empty_tags={area:1,base:1,basefont:1,br:1,col:1,frame:1,hr:1,img:1,input:1,isindex:1,link:1,meta:1,param:1};this.boolean_attrs={selected:1,checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1};this.preserve_space_tags={pre:1,textarea:1};this.noescape_tags={script:1,style:1};break;default:throw new Error('set_output_mode: unknown mode "'+mode+'"');break;}};mjt.TemplateCompiler.prototype.compile_top=function(top,toplevel_def,toplevel_prefix){this.scope=new mjt.Scope(this,null,'[toplevel]');this.scope.toplevel=true;if(typeof toplevel_prefix!='undefined')
this.scope.toplevel_prefix=toplevel_prefix;this.scope.toplevel_def=toplevel_def;this.compile_node(top);this.codestr=this._code.join('');this._code=null;this._markup=null;if(this.codestr==''){throw new Error('template compiled with no output');}};mjt.TemplateCompiler.prototype.uniqueid=function(prefix){var id=this.next_unique_id[prefix];if(typeof id!=='number')
id=1;this.next_unique_id[prefix]=id+1;return prefix+'_'+id;};mjt.TemplateCompiler.prototype._ampRE=/\&/g;mjt.TemplateCompiler.prototype._ltRE=/\</g;mjt.TemplateCompiler.prototype._gtRE=/\>/g;mjt.TemplateCompiler.prototype.htmlencode=function(s){return s.replace(this._ampRE,'&amp;').replace(this._ltRE,'&lt;').replace(this._gtRE,'&gt;');};mjt.TemplateCompiler.prototype.jsencode=function(s){return JSON.stringify([s]).replace(/^[^"]*/,'').replace(/[^"]*$/,'');};mjt.TemplateCompiler.prototype.flush_markup=function(no_output,ignore_whitespace){if(this._markup.length==0)
return-1;var s=this._markup.join('');this._markup=[];if(ignore_whitespace&&/^\s*$/.exec(s))
return-1;var texti=this.strings.length;this.strings[texti]=s;if(this.debug){var indent='                                                  ';var commentstart='// ';var x=s.replace(/\r?\n/gm,'\n'+indent+commentstart);var c='__m[__n++]=__ts['+texti+'];';if(c.length<indent.length)
c+=indent.substr(c.length);this.emit(c,commentstart,x,'\n');}else if(!no_output){this.emit('__m[__n++]=__ts[',texti,'];\n');}
return texti;};mjt.TemplateCompiler.prototype.emit=function(){if(this._markup.length)
this.flush_markup();for(var i=0;i<arguments.length;i++){var arg=''+arguments[i];var lines=arg.split('\n');for(var li=0;li<lines.length;li++){if(li>0){this._code.push('\n');this.debug_locs.push(this.source_loc);}
this._code.push(lines[li]);}}};mjt.TemplateCompiler.prototype.emitln=function(){this.emit.apply(this,arguments);this.emit('\n');};mjt.TemplateCompiler.prototype.markup=function(){for(var i=0;i<arguments.length;i++){this._markup.push(arguments[i]);}};mjt.TemplateCompiler.prototype.warn=function(s){this.markup('<span style="outline-style:solid;color:red;">',this.htmlencode(s),'</span>');};mjt.TemplateCompiler.prototype.compile_task=function(taskname,n){if(n.firstChild===null||n.firstChild.nodeType!=3||n.firstChild.nextSibling!==null){throw new Error('mjt.task='+taskname+' declaration may only contain text');}
var mq=n.firstChild.nodeValue;if(mq.match(/;\s*$/)){mjt.warn('mjt.task=',taskname,'definition should not end with a semicolon');mq=mq.replace(/;\s*$/,'');}
if(this.browser_dom&&mq.match(/\/\/ /)){mjt.warn('"//" comments in mjt.task=',taskname,'definition will fail on IE6');}
this.emitln('var ',taskname,' = this.tasks && this.tasks.',taskname,';');this.emitln('if (!',taskname,') { ',taskname,' = this.mktask("',taskname,'", (\n',mq,')); }');this.scope.has_tasks=true;};mjt.TemplateCompiler.prototype.compile_text=function(s,attrtext,trim_leading_ws,trim_trailing_ws,complex_substitutions_only){var endsimplesub=/[^A-Za-z0-9_.]/gm;var closebrace=/\}/gm;var closebracket=/\]/gm;var has_subs=false;if(typeof attrtext=='undefined')
attrtext=false;if(typeof trim_leading_ws=='undefined')
trim_leading_ws=false;if(typeof trim_trailing_ws=='undefined')
trim_trailing_ws=false;if(typeof complex_substitutions_only=='undefined')
complex_substitutions_only=false;var m,ss,nlines;var slen=s.length;var lasti=0;var si=s.indexOf('$',lasti)
if(si==-1){nlines=s.split('\n').length-1;if(trim_leading_ws)
s=s.replace(/^\s+/m,'');if(trim_trailing_ws)
s=s.replace(/\s+$/m,'');this.markup(this.htmlencode(s));this.source_loc+=nlines;return false;}
while(si>=0){ss=s.substring(lasti,si);nlines=ss.split('\n').length-1;if(lasti==0&&trim_leading_ws)
ss=ss.replace(/^\s+/m,'');this.markup(this.htmlencode(ss));this.source_loc+=nlines;si++;if(si>=slen){this.warn('premature end of $ substitution in '+this.jsencode(s));return has_subs;}
switch(s.charAt(si)){case'$':if(complex_substitutions_only){this.markup('$');break;}
si++;this.markup('$');break;case'(':this.markup('$');break;case'{':closebrace.lastIndex=si+1;m=closebrace.exec(s);if(m===null){this.warn('missing close after ${ in '+this.jsencode(s));return has_subs;}
ss=s.substring(si+1,closebrace.lastIndex-1);si=closebrace.lastIndex;if(/\{/.test(ss))
throw new Error('template compiler: "{" and "}" are forbidden inside "${...}"');if(attrtext)
this.emitln('__m[__n++]=__pkg.runtime.make_attr_safe(',ss,');');else
this.emitln('__m[__n++]=(',ss,');');has_subs=true;this.source_loc+=ss.split('\n').length-1;break;case'[':if(complex_substitutions_only){this.markup('$');break;}
if(attrtext)
throw new Error('template compiler: "$[...]" is illegal in an attribute');closebracket.lastIndex=si+1;m=closebracket.exec(s);if(m===null){this.warn('missing close after $[ in '+this.jsencode(s));return has_subs;}
ss=s.substring(si+1,closebracket.lastIndex-1);si=closebracket.lastIndex;if(/\[/.test(ss))
throw new Error('template compiler: "[" and "]" are forbidden inside "$[...]"');this.emitln('__m[__n++]=__pkg.runtime.ref(',this.jsencode(ss),');');has_subs=true;this.source_loc+=ss.split('\n').length-1;break;default:if(complex_substitutions_only){this.markup('$');break;}
endsimplesub.lastIndex=si;m=endsimplesub.exec(s);if(m===null){ss=s.substring(si);si=slen;}else if(m.index>si){ss=s.substring(si,m.index);si=m.index;}else{this.warn('unknown character following $ in '+this.jsencode(s));return has_subs;}
if(attrtext)
this.emitln('__m[__n++]=__pkg.runtime.make_attr_safe(',ss,');');else
this.emitln('__m[__n++]=',ss,';');has_subs=true;}
lasti=si;si=s.indexOf('$',lasti);}
if(lasti>=0&&lasti<slen){ss=s.substring(lasti);nlines=ss.split('\n').length-1;if(trim_trailing_ws)
ss=ss.replace(/\s+$/m,'');this.markup(this.htmlencode(ss));this.source_loc+=nlines;}
return has_subs;};mjt.TemplateCompiler.prototype.compile_onevent_attr=function(aname,avalue){var uvar=this.uniqueid(aname+'_cb');this.emitln('var ',uvar,' = __pkg.runtime.uniqueid("',aname,'");');this.emitln('mjt._eventcb[',uvar,'] = function (event) {');this.emit(avalue);this.emitln('}');return('return mjt._eventcb.${'+uvar+'}.apply(this, [event])');};mjt.TemplateCompiler.prototype.get_attributes=function(n,attrs,mjtattrs){var mjttag=this.mjtns_re.exec(n.nodeName);var src_attr=null;var srcattrs=n.attributes;for(var ai=0;ai<srcattrs.length;ai++){var attr=srcattrs[ai];if(!attr.specified)continue;var aname=attr.nodeName;var m=this.mjtns_re.exec(aname);if(m){var mname=m[1];mjtattrs[mname]=attr.nodeValue;continue;}
if(mjttag){if(typeof mjtattrs[aname]!='undefined')
throw new Error('template compiler: ignoring template attribute override '
+aname+'='+attr.nodeValue);mjtattrs[aname]=attr.nodeValue;continue;}
if(aname=='src'){src_attr=attr.nodeValue;continue;}
var a={name:aname};if(typeof attr.nodeValue!='undefined')
a.value=attr.nodeValue;if(this.browser_dom){if(aname.substr(0,2)=='on'){mjt.warn(aname,'="..."','will break on IE6, use','mjt.'+aname);}
if(this._ie_attribute_bs){if(aname=="style"){a.value=''+n.style.cssText;}else if(aname=='CHECKED'){aname='checked';a.value='1';}else{var ie_whatever=n.getAttribute(aname,2);if(ie_whatever)
a.value=ie_whatever;}}
if(typeof a.value=='number')
a.value=''+a.value;}
attrs.push(a);}
if(this.browser_dom&&this._ie_attribute_bs&&n.nodeName=="INPUT"){a={name:'value',value:n.value};attrs.push(a);}
if(typeof mjtattrs.src!='undefined'){attrs.push({name:'src',value:mjtattrs.src});}else if(src_attr!==null){attrs.push({name:'src',value:src_attr});}};mjt.TemplateCompiler.prototype.compile_choose=function(cn,choose){var choose_state='init';var tablevar=false;var default_label=false;if(choose){this.emitln('switch (',choose,') {');choose_state='dispatch_init';}
var n=cn.firstChild;while(n!=null){var nextchild=n.nextSibling;var nt=n.nodeType;if(nt==3){if(n.nodeValue.match(/[^ \t\r\n]/)){mjt.warn('only whitespace text is allowed in mjt.choose, found','"'+n.nodeValue+'"');}
n=nextchild;continue;}
if(nt==1){var next_choose_state=choose_state;var mjtattrs={};var attrs=[];this.get_attributes(n,attrs,mjtattrs);var defaultcase=false;if(typeof(mjtattrs.when)!='undefined'){defaultcase=false;}else if(typeof(mjtattrs.otherwise)!='undefined'){defaultcase=true;}else{mjt.warn('all elements inside mjt.choose must have a mjt.when= or mjt.otherwise= attribute');break;}
if(choose_state=='init'){if(defaultcase){this.emitln('{');next_choose_state='closed';}else{this.emitln('if (',mjtattrs.when,') {');next_choose_state='open';}}else if(choose_state=='open'){if(defaultcase){this.emitln('} else {');next_choose_state='closed';}else{this.emitln('} else if (',mjtattrs.when,') {');next_choose_state='open';}}else if(choose_state.match(/^dispatch/)){if(choose_state!='dispatch_init')
this.emitln('break;');if(defaultcase){this.emitln('default:');next_choose_state='dispatch';}else{this.emit('case ');this.emit(this.jsencode(mjtattrs.when));this.emitln(':');next_choose_state='dispatch';}}
this.compile_node(n,{choose_state:'in_choose'});choose_state=next_choose_state;}
n=nextchild;}
if(choose==''){this.emitln('}');}else{if(choose_state!='dispatch_init')
this.emitln('break;');this.emitln('};');}};mjt.TemplateCompiler.prototype.compile_def=function(defattr,n){var defn=defattr.match(/^([^(]+)\(([^)]*)\)$/);if(!defn){mjt.warn('bad mjt.def=',defattr,': must contain an argument list');return;}
var defname=defn[1];var defargs=defn[2];if(this.debug)
this.emitln('// mjt.def=',defattr);this.emitln('var ',defname,' = function (',defargs,') {');this.scope=new mjt.Scope(this,this.scope,defattr);this.emitln('var __m=[],__n=0;');};mjt.TemplateCompiler.prototype.complete_def=function(){this.scope=this.scope.parent;if(this.scope.toplevel&&this.output_mode=='text')
this.emitln('return __pkg.runtime.cleanup_noquote(__m);');else
this.emitln('return __m;');this.emitln('};');};mjt.TemplateCompiler.prototype.generate_open_tag=function(tagname,attrs,attrcode,generate_tcall_id){this.markup('<',tagname);var static_attrs={};for(var ai=0;ai<attrs.length;ai++){var a=attrs[ai];if(typeof(a.value)=='function'){mjt.warn('ignoring function-valued attr',tagname,a.name,a.value);continue;}
static_attrs[a.name]=a.value;}
if('id'in static_attrs)
generate_tcall_id=false;if(attrcode){var dvar=this.uniqueid('dattrs');var svar=this.uniqueid('sattrs');this.emitln('var ',dvar,' = (',attrcode,');');this.emitln('var ',svar,' = {};');for(ai=0;ai<attrs.length;ai++){var k=attrs[ai].name;var v=attrs[ai].value;this.emit('if (!(',this.jsencode(k),' in ',dvar,')) {');{if(k in this.boolean_attrs){this.markup(' ',k);}else{this.markup(' ',k,'="');this.compile_text(v,true);this.markup('"');}}
this.emitln(' }');}
if(generate_tcall_id)
this.emitln('if (this.subst_id && !("id" in ',dvar,')) ',dvar,'.id=this.subst_id;');var divar=this.uniqueid('di');this.emitln('for (var ',divar,' in ',dvar,') {');this.emitln("__m[__n++]=' ' + "+divar+";");this.emitln("__m[__n++]=__pkg.runtime.bless('=\"');");this.emitln("__m[__n++]=__pkg.runtime.htmlencode(''+"+dvar+"["+divar+"]);");this.emitln("__m[__n++]=__pkg.runtime.bless('\"');");this.emitln('}');}else{for(ai=0;ai<attrs.length;ai++){var a=attrs[ai];this.markup(' ',a.name,'="');this.compile_text(a.value,true);this.markup('"');}
if(generate_tcall_id){this.emitln('if (this.subst_id) { __m[__n++]=__pkg.runtime.bless(\' id="\' + this.subst_id + \'"\'); }');}}};mjt.TemplateCompiler.prototype.compile_node=function(n,options){if(typeof(options)=='undefined')
options={};var choose_state='none';if(typeof(options.choose_state)!='undefined')
choose_state=options.choose_state;if(typeof n.getUserData!='undefined'){try{var lineno=n.getUserData('lineNumber');if(lineno!==null){if(typeof lineno=='string')
lineno=parseInt(lineno);this.source_loc=lineno;}}catch(e){this.source_loc=null;}}
switch(n.nodeType){case 1:this.compile_element(n,choose_state);break;case 2:break;case 3:var text=n.nodeValue;this.compile_text(text,false,options.trim_leading_ws,options.trim_trailing_ws);break;case 4:mjt.log('CDATA node');this.compile_text(n.nodeValue,false);break;case 5:this.markup('&'+n.nodeName+';');break;case 6:mjt.warn('template compiler: skipping dom node type',n.nodeType);break;case 7:mjt.warn('template compiler: got <? ?>',n.nodeName,n.nodeValue);break;case 8:if(this.output_mode!='text')
this.markup('<!--'+n.nodeValue+'-->');break;case 9:mjt.warn('template compiler: skipping dom node type',n.nodeType);break;case 10:this.markup('<!DOCTYPE '+n.nodeName+' PUBLIC "'+n.publicId+'" "'+n.systemId+'">');mjt.warn('ignoring DOCTYPE',n.nodeName,n.nodeValue);break;case 11:mjt.warn('template compiler: skipping dom node type',n.nodeType);break;case 12:mjt.warn('template compiler: skipping dom node type',n.nodeType);break;default:mjt.warn('template compiler: unknown dom node type',n.nodeType);return;}};mjt.TemplateCompiler.prototype.compile_element=function(n,choose_state){var completions=[];var render_outer_tag=true;var tagname=n.nodeName;var tagname_lower=tagname.toLowerCase();var mjtattrs={};var attrs=[];this.get_attributes(n,attrs,mjtattrs);if(this.scope.toplevel){if(typeof mjtattrs.def!='undefined')
throw new Error('template compiler: def="'+mjtattrs.def+'" illegal at top element');mjtattrs.def=this.scope.toplevel_def;}
if(this.output_mode=='text')
mjtattrs.strip='1';var mjttag=this.mjtns_re.exec(n.nodeName);if(mjttag){switch(mjttag[1]){case'script':mjtattrs.script='';break;case'none':mjt.warn('<mjt:none> is deprecated, use <mjt:block> instead');mjtattrs.strip='1';break;case'block':mjtattrs.strip='1';break;case'task':mjt.log('got mjt:task');if(typeof mjtattrs['var']=='string'){mjtattrs.task=mjtattrs['var'];}else{mjt.error('mjt:task requires var= or mjt:var= attribute');}
break;case'doc':if(!this.scope.toplevel){mjt.error('mjt:doc is only legal as the toplevel tag');}
mjtattrs.strip='1';if(typeof mjtattrs.type!='undefined')
this.document_content_type=mjtattrs.type;else
this.document_content_type='text/html';if(typeof mjtattrs['xml-pi']!='undefined'){if(mjtattrs['xml-pi']=='true'||mjtattrs['xml-pi']=='1')
this.scope.toplevel_prefix='<?xml version="1.0" encoding="utf-8" ?>\n';else if(mjtattrs['xml-pi']=='false'||mjtattrs['xml-pi']=='0')
this.scope.toplevel_prefix=null;}
if(this.document_content_type=='text/html')
this.set_output_mode('html');else if(/^text\//.test(this.document_content_type))
this.set_output_mode('text');else if(/^application\/.*xml$/.test(this.document_content_type))
this.set_output_mode('xml');else
this.set_output_mode('xml');break;default:mjt.error('ignoring unknown mjt tag',tagname);break;}}
var subcompiler=null;var trim_whitespace=false;if(typeof mjtattrs.trim!='undefined')
trim_whitespace=true;if(n.firstChild!==null){subcompiler=function(n){var child=n.firstChild;var opts={};if(trim_whitespace)
opts.trim_leading_ws=true;while(child!=null){var nextchild=child.nextSibling;if(trim_whitespace&&nextchild===null)
opts.trim_trailing_ws=true;this.compile_node(child,opts);opts={};child=nextchild;}};}
if(tagname_lower=='script'&&this.browser_dom){return;}
if(tagname_lower in this.noescape_tags){subcompiler=function(n){var bodyelt=n.firstChild;if(bodyelt===null)
return;if(bodyelt.nodeType!=3||bodyelt.nextSibling){mjt.warn('<'+tagname+'> tag should contain only text');return;}
var body=bodyelt.nodeValue;var bad_body_re=new RegExp('<\/'+tagname);if(body.match(bad_body_re)){mjt.warn('illegal content for HTML script tag, removed');}else{this.emitln(' __m[__n++]=(function () {');this.emitln('var __m=[],__n=0;');var has_subs=this.compile_text(bodyelt.nodeValue,false,false,false,true);this.emitln('return __pkg.runtime.cleanup_noquote(__m, '
+this.jsencode(tagname_lower)+');');this.emitln('})();');}};}
if(typeof(mjtattrs.task)!='undefined'){this.compile_task(mjtattrs.task,n);return;}
if(typeof(mjtattrs.def)!='undefined'){if(typeof(attrs.id)!='undefined'){mjt.warn('mjt.def=',mjtattrs.def,'must not have an id="..." attribute');}
this.compile_def(mjtattrs.def,n);if(this.scope.parent.toplevel){this.emitln('var __pkg = this.tpackage;');this.emitln('var exports = this.exports;');this.emitln('var __ts=__pkg._template_fragments;');if(this.scope.parent.toplevel_prefix!=null)
this.markup(this.scope.parent.toplevel_prefix);}
completions.push(function(){var defscope=this.scope;if(defscope.has_tasks){if(!render_outer_tag||typeof(mjtattrs.strip)!='undefined'){mjt.error('can\'t strip toplevel tag of mjt.def="'+mjtattrs.def+'" tag because it contains tasks');}}
this.complete_def();var defname=mjtattrs.def.replace(/\(.*/,'');if(this.scope.toplevel&&this.document_content_type!=null){this.emitln(defname,'.doc_content_type = ',this.jsencode(this.document_content_type),';');}
if(!this.scope.toplevel){var templatevar='__pkg';this.emitln(defname,' = __pkg.runtime.tfunc_factory(',this.jsencode(mjtattrs.def),', ',defname,', ',templatevar,', ',defscope.has_tasks,', ',false,');');}
if(this.scope.parent&&this.scope.parent.toplevel)
this.emitln('exports.',defname,' = ',defname,';');});}
if(typeof(mjtattrs['when'])!='undefined'){this.flush_markup();if(choose_state!='in_choose')
mjt.warn('unexpected mjt.when, in choice state',choose_state);completions.push(function(){this.flush_markup();});}
if(typeof(mjtattrs['otherwise'])!='undefined'){this.flush_markup();if(choose_state!='in_choose')
mjt.warn('unexpected mjt.otherwise, in choice state ',choose_state);completions.push(function(){this.flush_markup();});}
if(typeof(mjtattrs['for'])!='undefined'){var matches=/^(\w+)(\s*,\s*(\w+))?\s+in\s+(.+)$/.exec(mjtattrs['for']);if(!matches){if(mjtattrs['for'].charAt(0)=='('){this.emitln('for ',mjtattrs['for'],' {');completions.push(function(){this.emitln('}');});}else{mjt.warn('bad mjt.for= syntax');}}else{var var1=matches[1];var var2=matches[3];var forexpr=matches[4];var itemid,indexid;if(!var2){indexid=this.uniqueid(var1+'_index');itemid=var1;}else{indexid=var1;itemid=var2;}
this.emitln('__pkg.runtime.foreach(this, (',forexpr,'), function (',indexid,', ',itemid,') {');var onceid=this.uniqueid('once');this.emitln('var ',onceid,' = 1;');this.emitln('while (',onceid,') {');completions.push(function(){this.emitln(onceid,'--;');this.emitln('} /* while once */');this.emitln('return ',onceid,' ? __pkg.runtime._break_token :  __pkg.runtime._continue_token;');this.emitln('}); /* foreach */');});}}
if(typeof(mjtattrs['if'])!='undefined'){this.emitln('if (',mjtattrs['if'],') {');completions.push(function(){this.emitln('}');});}
if(typeof(mjtattrs['elif'])!='undefined'){this.flush_markup(false,true);this.emitln('else if (',mjtattrs['elif'],') {');completions.push(function(){this.emitln('}');});}
if(typeof(mjtattrs['else'])!='undefined'){this.flush_markup(false,true);this.emitln('else {');completions.push(function(){this.emitln('}');});}
if(typeof(mjtattrs.script)!='undefined'){var ondomready=false;switch(mjtattrs.script){case'':break;case'1':break;case'ondomready':ondomready=true;break;default:mjt.warn('reserved mjtattrs.script= value:',mjtattrs.script);break;}
if(ondomready){this.emitln('__pkg.runtime.ondomready(function () {');}
var textnode=n.firstChild;if(!textnode){}else if(textnode.nodeType!=3||textnode.nextSibling){mjt.warn("the mjt.script element can only contain javascript text, not HTML.  perhaps you need to quote '<', '>', or '&' (this is unlike a <script> tag!)");}else{var txt=textnode?textnode.nodeValue:'';if(txt.match(/\/\/ /)&&this.browser_dom){mjt.warn('"//" comments in mjt.script= definition will fail on IE6');}
var codelines=txt.split('\n');for(var li=0;li<codelines.length;li++){this.emitln(codelines[li]);this.source_loc++;}}
if(ondomready){this.emitln('}, this);');}
render_outer_tag=false;subcompiler=null;}
if(typeof(mjtattrs.choose)!='undefined'){this.flush_markup();subcompiler=function(n){this.compile_choose(n,mjtattrs.choose);};}
if(typeof(mjtattrs.replace)!='undefined'){render_outer_tag=false;subcompiler=function(n){this.emitln('__m[__n++]=(',mjtattrs.replace,');');};}
if(typeof(mjtattrs.content)!='undefined'){subcompiler=function(n){this.emitln('__m[__n++]=(',mjtattrs.content,');');};}
for(var evname in mjtattrs){if(evname.substr(0,2)!='on')continue;if(!this.browser_target){mjt.warn('mjt:onevent= attributes only make sense if targeting a browser');continue;}
a={name:evname,value:this.compile_onevent_attr(evname,mjtattrs[evname])};attrs.push(a);}
if(this.debug&&this.browser_dom&&typeof(mjtattrs.def)!='undefined'){attrs.push({name:'mjt_template',value:mjtattrs.def});}
var stripexpr=(typeof(mjtattrs.strip)!='undefined')?mjtattrs.strip:null;var stripvar=null;if(stripexpr=='1')
render_outer_tag=false;if(render_outer_tag){var attrcode=(typeof(mjtattrs.attrs)!='undefined')?mjtattrs.attrs:null;if(stripexpr!==null){stripvar=this.uniqueid('strip');this.emitln('var ',stripvar,' = (',stripexpr,');');this.emitln('if (!',stripvar,') {');}
if(typeof mjtattrs.def!='undefined')
this.generate_open_tag(tagname,attrs,attrcode,true);else
this.generate_open_tag(tagname,attrs,attrcode,false);if(subcompiler===null&&this.output_mode=='xml')
this.markup('/>');else
this.markup('>');if(stripexpr!==null)
this.emitln('}');}
if(subcompiler!==null){if(tagname_lower in this.empty_tags)
mjt.warn('tag "'+tagname+'" must be empty, content ignored');else
subcompiler.apply(this,[n]);}
if(render_outer_tag){if(subcompiler===null&&this.output_mode=='xml'){}else if(tagname_lower in this.empty_tags){}else if(stripvar){this.emitln('if (!',stripvar,') {');this.markup('</',tagname,'>');this.emitln('}');}else{this.markup('</',tagname,'>');}}
for(var ci=completions.length-1;ci>=0;ci--){completions[ci].apply(this,[]);}};})(mjt);(function(mjt){mjt.run=function(target,tfunc,targs){var target_id;if(typeof mjt.app=='undefined'){mjt.app=new mjt.App();}
if(arguments.length==0){var pkg=new mjt.TemplatePackage();return mjt.run_page(pkg);}
if(typeof target===null){throw new Error('mjt.run: null target');}else if(typeof target=='string'){target_id=target;target=document.getElementById(target_id);}else if(typeof target=='object'){if(target.id=='')
target.id=mjt.uniqueid('run_target');target_id=target.id;}
if(arguments.length==1){var pkg=new mjt.TemplatePackage();pkg.source=window.location.protocol+'//'
+window.location.host+window.location.pathname
+'#'+target_id;return mjt.run_element(pkg,target,targs);}
if(typeof tfunc!=='function'){mjt.error('invalid template function',tfunc,arguments);throw new Error('mjt.run: invalid args');}
var tcall=new tfunc();tcall.subst_id=target_id;tcall.render(targs).display();return tcall.exports;};var load_page_metadata=function(pkg,head){var elts=[];var e;for(e=head.firstChild;e!==null;e=e.nextSibling){if(e.nodeType!=1)
continue;elts.push(e);}
for(var i=0;i<elts.length;i++){e=elts[i];switch(e.nodeName){case'TITLE':pkg.title=e.innerHTML;break;case'META':switch(e.name){case'description':pkg.summary=e.content;break;case'author':pkg.author=e.content;break;case'content-language':pkg.language=e.content;break;case'x-mjt-id':pkg.id=e.content;break;}
break;case'SCRIPT':break;case'STYLE':break;default:break;}}};mjt.run_page=function(pkg){load_page_metadata(pkg,document.getElementsByTagName('head')[0]);var prereq_task=mjt.Succeed();pkg.source=window.location.protocol+'//'
+window.location.host+window.location.pathname;var target=document.createElement('div');var body=document.getElementsByTagName('body')[0];var e=body.firstChild;while(e!==null){var tmp=e;e=e.nextSibling;if(tmp.nodeName==='IFRAME'&&tmp.className==='mjt_dynamic'){continue;}
body.removeChild(tmp);target.appendChild(tmp);}
if(1){target.id=mjt.uniqueid('mjt_body');target.style.display='none';body.appendChild(target);}
if(body.style.display=='none')
body.style.display='';prereq_task.enqueue().onready(function(r){mjt.run_element(pkg,target,[]);});return pkg.namespace;};mjt.run_element=function(pkg,target,targs){pkg.load_document(target,targs);pkg.tcall.subst_id=target.id;pkg.tcall.display();return pkg.tcall.exports;};mjt.load_element=function(top){var topelt=typeof top=='string'?document.getElementById(top):top;var pkg=new mjt.TemplatePackage();pkg.source=window.location.protocol+'//'
+window.location.host+window.location.pathname;if(typeof top=='string')
pkg.source+='#'+top;pkg.load_document(topelt,[]);return pkg;};mjt.load_from_iframe=function(top){var pkg=new mjt.TemplatePackage();pkg.source=window.location.protocol+'//'
+window.location.host+window.location.pathname;var topelt=top;if(typeof top=='string')
topelt=document.getElementById(top);if(topelt.nodeName!='IFRAME'){mjt.error('called mjt.load_from_iframe on node tag',topelt.nodeName);return null;}
var idoc=topelt.contentWindow||topelt.contentDocument;if(idoc.document)
idoc=idoc.document;topelt=idoc.getElementsByTagName('body')[0];pkg.load_document(topelt,[]);return pkg.namespace;};mjt.load_string=function(mjthtml){var tag=document.createElement('div');tag.innerHTML=mjthtml;return mjt.load_element(tag);};mjt.replace_html=function(top,html){var tmpdiv=document.createElement('div');var htmltext=mjt.flatten_markup(html);tmpdiv.innerHTML=htmltext;if(top.parentNode===null){mjt.warn('attempt to replace html that has already been replaced?');return;}
var newtop=tmpdiv.firstChild;if(newtop===null){mjt.warn('bad html in replace_innerhtml');return;}
if(newtop.nextSibling){mjt.warn('template output should have a single toplevel node');newtop=tmpdiv;}
top.parentNode.replaceChild(newtop,top);if(newtop.style&&newtop.style.display=='none')
newtop.style.display='';};})(mjt);;if(typeof jQuery!='undefined')(function($){if(typeof $=='undefined')
return;$.fn.mjt=function(markup){var html=mjt.flatten_markup(markup);return this.each(function(){this.innerHTML=html;});};})(jQuery);(function(mjt){mjt.App=function(argschema){if(typeof argschema=='undefined')
argschema={};this.state=null;this.yui_history_id='mjtapp';this.argschema={'mjt.server':{key:'mjt.server',statekey:'service_url',validator:mjt.validators.service_host},'mjt.debug':{key:'mjt.debug',statekey:'debug',validator:mjt.validators.flag}};for(var k in argschema){this.argschema[k]=argschema[k];}
this._onstatechange={};this.init();};mjt.App.prototype.init=function(){this.init_state();mjt.service_url=this.state.service_url;mjt.freebase.set_service_url(this.state.service_url);mjt.debug=this.state.debug;mjt.Task.debug=this.state.debug;mjt.urlquery=this.state;return this;};mjt.App.prototype.onstatechange=function(THUNK_ARGS){var tid=mjt.uniqueid('statecb');this._onstatechange[tid]=mjt.vthunk(arguments);return this;};mjt.App.prototype.refresh=function(){for(var k in this._onstatechange){this._onstatechange[k].apply(this,[]);}
return this;};mjt.App.prototype._handle_onhistory=function(rstate){mjt.log('yui setting state',rstate,typeof this.state);if(rstate===null){rstate=YAHOO.util.History.getCurrentState(this.yui_history_id);mjt.log('yui history onLoadEvent:',rstate);}else{mjt.log('yui history state:',rstate);}
this.state=rison.decode_object(rstate);this.refresh();};mjt.App.prototype.init_state=function(){var qstr;var qstate=null;if(typeof window!='undefined')
qstr=window.location.search;if(typeof acre!='undefined')
qstr=acre.environ.query_string;if(typeof(qstr)=='string'&&qstr.length>0&&qstr.charAt(0)=='?')
this.state=qstate=this.decode_uristate(qstr.substr(1));else
this.state=this.decode_uristate('');if(typeof YAHOO==='undefined'||!YAHOO.util.History)
return this;var history=YAHOO.util.History;var init_state=history.getBookmarkedState(this.yui_history_id);if(!init_state){init_state=rison.encode_object(this.state);}
mjt.log('yui history initial state',init_state);history.register(this.yui_history_id,init_state,mjt.vthunk('_handle_onhistory',this));if(qstate!==null){}
history.onLoadEvent.subscribe(mjt.vthunk('_handle_onhistory',this,null));history.initialize('yui-history-iframe','yui-history-field');return this;};mjt.App.prototype.mark_history=function(){if(this.yui_history_id===null){return;}
var rstate=rison.encode_object(this.state);YAHOO.util.History.navigate(this.yui_history_id,rstate);};mjt.Validator=function(){};mjt.Validator.prototype.encode=function(v){if(v==this.default_value)
return undefined;return this.encodestr(v);};mjt.Validator.prototype.decode=function(v){if(typeof v=='undefined')
return this.default_value;return this.decodestr(v);};mjt.validators={};mjt.validators.flag=new mjt.Validator();mjt.validators.flag.default_value=false;mjt.validators.flag.encodestr=function(bool){return bool?'1':undefined;};mjt.validators.flag.decodestr=function(str){return str=='1'?true:false;};mjt.validators.service_host=new mjt.Validator();mjt.validators.service_host.default_value='http://www.freebase.com';mjt.validators.service_host.encodestr=function(server){var host=server.replace(/^http:\/\//,'');if(typeof window!='undefined'&&host==window.location.host)
return'.';return host;};mjt.validators.service_host.decodestr=function(server){if(server.substr(0,4)=='http')
url=server;else if(server=='.'){if(typeof window!='undefined')
url=window.location.protocol+'//'+window.location.host;if(typeof acre!='undefined')
url=acre.environ.server_protocol+'//'+acre.environ.host}else
url='http://'+server;return url;};mjt.App.prototype.encode_uristate=function(values){var qd={};var state_encoded={};var k,argspec;var args_by_statekey={}
for(k in this.argschema){argspec=this.argschema[k];args_by_statekey[argspec.statekey]=argspec;}
for(k in this.state){argspec=args_by_statekey[k];if(typeof argspec!='undefined')
qd[argspec.key]=argspec.validator.encode(this.state[k]);else
qd[k]=this.state[k];}
for(k in values){argspec=args_by_statekey[k];if(typeof argspec!='undefined')
qd[argspec.key]=argspec.validator.encode(values[k]);else
qd[k]=values[k];}
for(k in qd){if(typeof qd[k]=='undefined')
delete qd[k];}
return mjt.formencode(qd);};mjt.App.prototype.decode_uristate=function(qstr){var state={};var qd=mjt.formdecode(qstr);var argspec,k;for(k in qd){argspec=this.argschema[k];if(typeof argspec!='undefined')
state[argspec.statekey]=argspec.validator.decode(qd[k]);else
state[k]=qd[k];}
for(k in this.argschema){argspec=this.argschema[k];var skey=argspec.statekey;if(!(skey in state))
state[skey]=argspec.validator.default_value;}
return state;};mjt.App.prototype.href=function(base,values){if(typeof base=='undefined'||base===null)
base=location.protocol+'//'+location.host+location.pathname;var qstr=this.encode_uristate(values);return base+(qstr?'?'+qstr:'');};})(mjt);;if(!window.freebase)
window.freebase={};if(!window.freebase.controls)
window.freebase.controls={};(function($,fb){$.fn._freebaseInput=function(control,options){if(!options)options={};return this.attr("autocomplete","off").each(function(){control.release(this);$(this).unbind("focus",control.delegate("focus")).focus(control.delegate("focus"));if(typeof this['fb_id']=='undefined')
this.fb_id=control.counter++;control.cache[this.fb_id]=null;var o={};$.extend(o,control.default_options,options);control.option_hash[this.fb_id]=o;});};fb.log=fb.error=fb.debug=function(){};if(typeof console!="undefined"&&console.log&&console.error){fb.log=console.log;fb.error=console.error;fb.debug=console.debug;};fb.delegate=function(fn,thisArg,argArray){if(typeof argArray=="undefined")
argArray=[];var dg=function(){var f_args=[];for(var i=0,len=arguments.length;i<len;i++)
f_args.push(arguments[i]);if(arguments.callee&&arguments.callee.fn)
return(arguments.callee.fn.apply(arguments.callee.thisArg,arguments.callee.argArray.concat(f_args)));return undefined;};dg.thisArg=thisArg;dg.fn=fn;dg.argArray=argArray;fb.autoclean(dg,fb.clean_delegate);return(dg);};fb.clean_delegate=function(f){if(f)
f.thisArg=f.fn=f.argArray=null;};fb.clean_image=function(i){if(i)
i.onload=i.onerror=null;};fb.clean_expando=function(obj){if(obj)
delete obj.fb_data;};fb.AUTOCLEAN_HEAP={};fb.AUTOCLEAN_SERIAL_NO=0;fb.autoclean=function(obj,finalizer){obj._autoclean_serial_no=fb.AUTOCLEAN_SERIAL_NO++;if(finalizer)
obj._autoclean_finalizer=finalizer;fb.AUTOCLEAN_HEAP[obj._autoclean_serial_no]=obj;};fb.autoclean_gc=function(){for(var k in fb.AUTOCLEAN_HEAP){var obj=fb.AUTOCLEAN_HEAP[k];if('_autoclean_finalizer'in obj)
obj._autoclean_finalizer(obj)}
fb.AUTOCLEAN_HEAP={};}
fb.finalize=function(obj){if(!obj||!('_autoclean_serial_no'in obj))
return;var serial_no=obj._autoclean_serial_no;delete fb.AUTOCLEAN_HEAP[serial_no];if('_autoclean_finalizer'in obj)
obj._autoclean_finalizer(obj);}
$(window).unload(fb.autoclean_gc);fb.state=function(){};fb.state.prototype={enter:function(data){},exit:function(data){},handle:function(data){}};fb.state_machine=function(states){this.current_state=null;this.states={};var owner=this;$.each(states,function(i,n){n[1].sm=owner;owner.states[n[0]]=n[1];if(i==0)
owner.current_state=n[0];});if(!this.current_state)
throw"StateMachine must be initialized with at least one state";this.states[this.current_state].enter();};fb.state_machine.prototype={transition:function(to_state,exit_data,enter_data,data){var target=this.states[to_state];if(!target)
throw("Unrecongized state:"+to_state);var source=this.states[this.current_state];source.exit(exit_data);target.enter(enter_data);this.current_state=to_state;this.handle(data);},handle:function(data){if(data)
this.states[this.current_state].handle(data);}};fb.InputControl=function(){this.default_options={};this.counter=0;this.cache={};this.option_hash={};this.sm=null;this.delegates={};this.manage_delay=200;this.release_delay=100;};fb.InputControl.prototype={delegate:function(fname,argArray){if(!this.delegates[fname])
this.delegates[fname]=fb.delegate(this[fname],this);this.delegates[fname].argArray=argArray?argArray:[];return this.delegates[fname];},options:function(input){var o=this.option_hash[input.fb_id];if(!o)
throw"Unknown input";return o;},transition:function(state){if(this.sm)
this.sm.transition(state);},handle:function(data){if(this.sm)
this.sm.handle(data);},val:function(input){var v=$(input).val();if(v==null)
return"";return $.trim(v);},name:function(obj){if(obj.text!=null)
return obj.text;if(obj.name!=null)
return obj.name;return"unknown";},delay:function(l){var t=.3;if(l>0)
t=1/(6*(l-0.7))+.3;return t*1000;},manage:function(input){this.release(input);var owner=this;$.each(["blur","keydown","keypress","keyup","input","paste"],function(i,n){$(input).bind(n,owner.delegate(n));});this.transition("start");this.manage_hook(input);},manage_hook:function(input){},release:function(input){var owner=this;$.each(["blur","keydown","keypress","keyup","input","paste"],function(i,n){$(input).unbind(n,owner.delegate(n));});this.transition("start");this.release_hook(input);},release_hook:function(input){},focus:function(e){window.clearTimeout(this.manage_timeout);var input=e.target;try{this.options(input);}
catch(e){return;}
this.manage_timeout=window.setTimeout(this.delegate("manage",[input]),this.manage_delay);},blur:function(e){window.clearTimeout(this.release_timeout);var input=$(e.target)[0];if(this.dont_release){this._input=input;return;}
this.release_timeout=window.setTimeout(this.delegate("release",[input]),this.release_delay);},keydown:function(e){switch(e.keyCode){case 38:case 40:e.preventDefault();break;default:break;}},keypress:function(e){switch(e.keyCode){case 38:case 40:if(!e.shiftKey)
e.preventDefault();break;case 13:this.enterkey(e);break;case 27:this.escapekey(e);break;default:break;}},keyup:function(e){switch(e.keyCode){case 38:e.preventDefault();this.uparrow(e);break;case 40:e.preventDefault();this.downarrow(e);break;case 9:case 13:case 16:case 17:case 18:case 27:case 37:case 39:case 224:break;default:this.textchange(e);break;}},input:function(e){this.textchange(e);},paste:function(e){this.textchange(e);},uparrow:function(e){this.handle({id:"UPARROW",input:e.target});},downarrow:function(e){this.handle({id:"DOWNARROW",input:e.target});},enterkey:function(e){this.handle({id:"ENTERKEY",input:e.target,domEvent:e});},escapekey:function(e){this.handle({id:"ESCAPEKEY",input:e.target});},textchange:function(e){window.clearTimeout(this.textchange_timeout);var txt=this.val(e.target);var delay=this.delay(txt.length);this.textchange_timeout=window.setTimeout(this.delegate("textchange_delay",[e.target]),delay);},textchange_delay:function(input){this.handle({id:"TEXTCHANGE",input:input});}};fb.InputSelectControl=function(){fb.InputControl.call(this);this.min_len=1;this.fudge=8;this.loadmsg_delay=500;this.sm=new fb.state_machine([["start",new state_start(this)],["getting",new state_getting(this)],["selecting",new state_selecting(this)]]);};fb.InputSelectControl.prototype=new fb.InputControl();fb.InputSelectControl.prototype.constructor=fb.InputSelectControl;var p=fb.InputSelectControl.prototype;p.release_hook=function(input){this.list_hide();};p.click_listitem=function(li){this.handle({id:"LISTITEM_CLICK",item:li,input:this._input});};p.mousedown_list=function(e){this.dont_release=true;};p.mouseup_list=function(e){if(this._input){$(this._input).unbind("focus",this.delegate("focus"));$(this._input).focus();window.setTimeout(this.delegate("reset_focus",[this._input]),0);}
this.dont_release=false;};p.reset_focus=function(input){$(input).focus(this.delegate("focus"));};p.list_load=function(input){throw"You must override InputSelectControl.prototype.list_load";};p.list_receive=function(input,txt,o){if(o.status!=='200 OK'){fb.error("list_receive",o.code,o.messages,o);return;}
var result=[];if("list"in o&&"listItems"in o.list)
result=o.list.listItems;else if("result"in o)
result=o.result;else if("results"in o)
result=o.results;else if("query"in o&&"result"in o.query)
result=o.query.result;else{fb.error("list_receive",o.code,"Unrecognized list result",o);return;}
this.list_receive_hook(input,txt,result);this.handle({id:"LIST_RESULT",input:input,result:result});};p.list_receive_hook=function(input,txt,result){};p.list_show=function(input,result){if(!input)
return;if(!result)
result=[];var options=this.options(input);var txt=this.val(input);var list=null;if(!$("#fbs_list").length){$(document.body).append('<div style="display:none;position:absolute" id="fbs_list" class="fbs-topshadow">'+'<div class="fbs-bottomshadow">'+'<ul class="fbs-ul"></ul>'+'</div>'+'</div>');list=$("> .fbs-ul")[0];}
if(!list)
list=$("#fbs_list > .fbs-bottomshadow > .fbs-ul")[0];$("#fbs_list > .fbs-bottomshadow").unbind().mousedown(this.delegate("mousedown_list")).mouseup(this.delegate("mouseup_list")).scroll(this.delegate("mousedown_list"));$("li",list).each(function(i,n){$(n).unbind();});$(list).empty();var filter=this.filter;if(typeof options.filter=="function")
filter=options.filter;if(!result.length)
$(list).append(this.create_list_item({id:"NO_MATCHES",text:"no matches"},null,options).addClass("fbs-li-nomatch"));var filtered=[];$.each(result,function(i,n){if(filter.apply(null,[n,txt]))
filtered.push(n);});filtered=this.filter_hook(filtered,result);var owner=this;$.each(filtered,function(i,n){$(list).append(owner.create_list_item(n,txt,options));});this.list_show_hook(list,input,options);var pos=$(input).offset({border:true,padding:true});var top=pos.top+input.clientHeight+this.fudge;$("#fbs_list").css({top:top,left:pos.left,width:options.width}).show();};p.list_show_hook=function(list,input,options){};p.filter_hook=function(filtered,result){return filtered;};p.list_hide=function(){$("#fbs_list").hide();this.list_hide_hook();};p.list_hide_hook=function(){};p.create_list_item=function(data,txt,options){var li=$("<li class='fbs-li'></li>")[0];var trans=this.transform;if(typeof options.transform=="function")
trans=options.transform;var html=trans.apply(this,[data,txt]);$(li).append(html);if("text"in data)
data.name=data.text;li.fb_data=data;fb.autoclean(li,fb.clean_expando);var owner=this;return $(li).mouseover(function(e){owner.list_select(null,this,options);}).click(function(e){owner.click_listitem(this);});};p.filter=function(data,txt){return true;};p.transform=function(data,txt){return data;};p.loading_show=function(input){this.list_hide();if(!$("#fbs_loading").length){$(document.body).append('<div style="display:none;position:absolute" id="fbs_loading" class="fbs-topshadow">'+'<div class="fbs-bottomshadow">'+'<ul class="fbs-ul">'+'<li class="fbs-li">'+'<div class="fbs-li-name">loading...</div>'+'</li>'+'</ul>'+'</div>'+'</div>');}
var options=this.options(input);var pos=$(input).offset({border:true,padding:true});var top=pos.top+input.clientHeight+this.fudge;$("#fbs_loading").css({top:top,left:pos.left,width:options.width}).show();};p.loading_hide=function(){$("#fbs_loading").hide();};p.list_select=function(index,li,options){var sli=null;$("#fbs_list > .fbs-bottomshadow > .fbs-ul > li").each(function(i,n){if(i==index||li==n){$(n).addClass("fbs-li-selected");sli=n;}
else
$(n).removeClass("fbs-li-selected");});this.list_select_hook(sli,options);return sli;};p.list_select_hook=function(sli,options){};p.list_length=function(){return $("#fbs_list > .fbs-bottomshadow > .fbs-ul > li").length;};p.list_selection=function(returnObj){if(!returnObj)
returnObj={};returnObj.index=-1;returnObj.item=null;$("#fbs_list > .fbs-bottomshadow > .fbs-ul > li").each(function(i,n){if(n.className.indexOf("fbs-li-selected")!=-1){returnObj.index=i;returnObj.item=n;return false;}});return returnObj;}
p.list_select_next=function(options){var len=this.list_length();var obj=this.list_selection();var index=obj.index+1;if(index>=0&&index<len)
return this.list_select(index,null,options);else if(options.soft)
return this.list_select(null,null,options);else if(len>0)
return this.list_select(0,null,options);return null;};p.list_select_prev=function(options){var len=this.list_length();var obj=this.list_selection();var index=obj.index-1;if(index>=0&&index<len)
return this.list_select(index,null,options);else if(options.soft){if(index<-1&&len>0)
return this.list_select(len-1,null,options);else
return this.list_select(null,null,options);}
else if(len>0)
return this.list_select(len-1,null,options);return null;};p.scroll_into_view=function(elt,p){if(elt)
elt.scrollIntoView(false);};p.em_text=function(text,em_str){var em=text;var index=text.toLowerCase().indexOf(em_str.toLowerCase());if(index>=0){em=text.substring(0,index)+'<em class="fbs-em">'+
text.substring(index,index+em_str.length)+'</em>'+
text.substring(index+em_str.length);}
return em;};p.caret_last=function(input){var l=this.val(input).length;if(input.createTextRange){var range=input.createTextRange();;range.collapse(true);range.moveEnd("character",l);range.moveStart("character",l);range.select();}
else if(input.setSelectionRange){input.setSelectionRange(l,l);}};function select_state(c){fb.state.call(this);this.c=c;};select_state.prototype=new fb.state();select_state.prototype.constructor=select_state;function state_start(c){select_state.call(this,c);};state_start.prototype=new select_state();state_start.prototype.constructor=state_start;state_start.prototype.handle=function(data){if(!data||!data.input)
return;var options=this.c.options(data.input);switch(data.id){case"TEXTCHANGE":case"DOWNARROW":var txt=this.c.val(data.input);if(txt.length>=this.c.min_len)
this.sm.transition("getting",null,data);else
this.c.list_hide();break;case"ENTERKEY":$(data.input).trigger("fb-submit",[{name:this.c.val(data.input)}]);break;default:break;};};function state_getting(c){select_state.call(this,c);};state_getting.prototype=new select_state();state_getting.prototype.constructor=state_getting;state_getting.prototype.enter=function(data){window.clearTimeout(this.loadmsg_timeout);if(!data||!data.input)
return;this.loadmsg_timeout=window.setTimeout(this.c.delegate("loading_show",[data.input]),this.c.loadmsg_delay);this.c.list_load(data.input);};state_getting.prototype.exit=function(data){window.clearTimeout(this.loadmsg_timeout);this.c.loading_hide();};state_getting.prototype.handle=function(data){if(!data||!data.input)
return;var options=this.c.options(data.input);switch(data.id){case"TEXTCHANGE":this.sm.transition("start",null,null,data);break;case"LIST_RESULT":this.sm.transition("selecting",null,data);break;case"ENTERKEY":$(data.input).trigger("fb-submit",[{name:this.c.val(data.input)}]);break;case"ESCAPEKEY":this.c.list_hide();this.sm.transition("start");break;default:break;};};function state_selecting(c){select_state.call(this,c);};state_selecting.prototype=new select_state();state_selecting.prototype.constructor=state_selecting;state_selecting.prototype.enter=function(data){if(!data||!data.input||!data.result)
return;this.c.list_show(data.input,data.result);var options=this.c.options(data.input);if(!options.soft)
this.c.list_select(0,null,options);};state_selecting.prototype.exit=function(data){this.c.list_select(null);};state_selecting.prototype.handle=function(data){if(!data||!data.input)
return;var options=this.c.options(data.input);switch(data.id){case"TEXTCHANGE":this.sm.transition("start",null,null,data);break;case"DOWNARROW":$("#fbs_list").show();var li=this.c.list_select_next(options);this.c.scroll_into_view(li);break;case"UPARROW":$("#fbs_list").show();var li=this.c.list_select_prev(options);this.c.scroll_into_view(li);break;case"ENTERKEY":var s=this.c.list_selection();if(s.index==-1||!s.item){this.sm.transition("start",null,null,data);return;}
if($("#fbs_list").css("display")!="none")
data.domEvent.preventDefault();else{$(data.input).trigger("fb-submit",[s.item.fb_data]);return;}
data.id="LISTITEM_CLICK";data.item=s.item;case"LISTITEM_CLICK":if(!data.item)
return;switch(data.item.fb_data.id){case"NO_MATCHES":break;default:var txt=$(".fbs-li-name",data.item).text();$(data.input).val(txt);this.c.caret_last(data.input);$(data.input).trigger("fb-select",[data.item.fb_data]).trigger("suggest",[data.item.fb_data]);this.c.list_hide();break;}
break;case"ESCAPEKEY":this.c.list_hide();this.sm.transition("start");break;default:break;};};function use_jsonp(options){if(!options.service_url)
return false;var pathname_len=window.location.pathname.length;var hostname=window.location.href;var hostname=hostname.substr(0,hostname.length-pathname_len);if(hostname==options.service_url)
return false;return true;}
$.fn.freebaseSuggest=function(options){return $(this)._freebaseInput(fb.suggest.getInstance(),options);};function SuggestControl(){fb.InputSelectControl.call(this);this.default_options={width:275,soft:false,suggest_new:null,flyout:true,service_url:"http://www.freebase.com",ac_path:"/api/service/search",ac_param:{type:"/common/topic",start:0,limit:20},ac_qstr:"prefix",blurb_path:"/api/trans/blurb",blurb_param:{maxlength:300},thumbnail_path:"/api/trans/image_thumb",thumbnail_param:{},filter:null,transform:null};};SuggestControl.prototype=new fb.InputSelectControl();SuggestControl.prototype.constructor=SuggestControl;SuggestControl.instance=null;SuggestControl.getInstance=function(){if(!SuggestControl.instance)
SuggestControl.instance=new SuggestControl();return SuggestControl.instance;};var p=SuggestControl.prototype;p.list_load=function(input){if(!input)
return;if(!"fb_id"in input)
return;var txt=this.val(input);if(!txt.length)
return;if(!this.cache[input.fb_id])
this.cache[input.fb_id]={};if(txt in this.cache[input.fb_id]){window.clearTimeout(this.handle_timeout);this.handle_timeout=window.setTimeout(this.delegate("handle",[{id:"LIST_RESULT",input:input,result:this.cache[input.fb_id][txt]}]),0);return;}
var options=this.options(input);var txt=this.val(input);var param=options.ac_param;param[options.ac_qstr]=txt;$.ajax({type:"GET",url:options.service_url+options.ac_path,data:param,success:this.delegate("list_receive",[input,txt]),dataType:use_jsonp(options)?"jsonp":"json",cache:true});};p.list_receive_hook=function(input,txt,result){if(!this.cache[input.fb_id])
this.cache[input.fb_id]={};this.cache[input.fb_id][txt]=result;};p.list_show_hook=function(list,input,options){if(!$(list).next(".fbs-selectnew").length)
$(list).after('<div style="display:none;" class="fbs-selectnew"></div>');var suggest_new=$(list).next(".fbs-selectnew")[0];if(options.suggest_new){var owner=this;$(suggest_new).unbind().empty().append(options.suggest_new).show().mouseover(function(e){$(e.target).addClass("fbs-selectnew-selected");owner.list_select(null);owner.flyout_hide();}).mouseout(function(e){$(this).removeClass("fbs-selectnew-selected");}).click(function(e){$(input).trigger("fb-select-new",[{name:owner.val(input)}]).trigger("suggest-new",[{name:owner.val(input)}]);owner.list_hide();owner.transition("start");});}
else
$(suggest_new).unbind().hide();};p.list_hide_hook=function(){this.flyout_hide();};p.list_select_hook=function(sli,options){this.flyout_hide();if(sli&&options&&options.flyout&&sli.fb_data&&sli.fb_data.id!="NO_MATCHES")
this.flyout(sli,options);};p.transform=function(data,txt){var owner=this;var types=[];if(data.type)
$.each(data.type,function(i,n){if(n.id!='/common/topic')
types.push(owner.name(n));});types=types.join(", ");var domains=[];if(data.domain)
$.each(data.domain,function(i,n){domains.push(owner.name(n));});domains=domains.join(", ");var aliases=[];if(data.alias)
$.each(data.alias,function(i,n){aliases.push(n);});aliases=aliases.join(", ");var props=[];if(data.properties)
$.each(data.properties,function(i,n){props.push(n);});props=props.join(", ");var div=document.createElement("div");$(div).append('<div class="fbs-li-aliases"></div>'+'<div class="fbs-li-name"></div>'+'<div class="fbs-li-types"></div>'+'<div class="fbs-li-domains"></div>'+'<div class="fbs-li-props"></div>');if(aliases.length){var text=$(".fbs-li-aliases",div).append(document.createTextNode("("+aliases+")")).text();if(txt)
$(".fbs-li-aliases",div).empty().append(this.em_text(text,txt));}
else
$(".fbs-li-aliases",div).remove();var text=$(".fbs-li-name",div).append(document.createTextNode(this.name(data))).text();if(txt)
$(".fbs-li-name",div).empty().append(this.em_text(text,txt));if(types.length)
$(".fbs-li-types",div).append(document.createTextNode(types));else
$(".fbs-li-types",div).remove();if(domains.length)
$(".fbs-li-domains",div).append(document.createTextNode(domains));else
$(".fbs-li-domains",div).remove();if(props.length)
$(".fbs-li-props",div).append(document.createTextNode(props));else
$(".fbs-li-props",div).remove();return div.innerHTML;};p.flyout=function(li,options){this.flyout_callback=this.flyout_resources(li,options);};p.flyout_resources=function(li,options){var data=li.fb_data;var data_types=["article","image"];var cb=new FlyoutResourcesHandler(this,li,options);var owner=this;$.each(data_types,function(i,n){var id=data[n];if(id&&typeof id=='object')
id=id.id;owner.flyout_resource_load(n,id,options,cb);});return cb;};p.flyout_resource_load=function(data_type,data_id,options,cb){if(data_type=="article"){if(data_id)
this.blurb_load(data_id,options,cb);else
cb.receive("blurb","&nbsp;");}
else if(data_type=="image"){if(data_id)
this.image_load(data_id,options,cb);else
cb.receive("image","#");}};function FlyoutResourcesHandler(owner,li,options){this.owner=owner;this.li=li;this.options=options;};FlyoutResourcesHandler.prototype={receive:function(data_type,data){if(!this.owner)return;this[data_type]={data:data};if(this.image&&this.blurb)
this.owner.flyout_show(this.li,this.options,this.image.data,this.blurb.data);},destroy:function(){this.owner=this.li=this.options=this.image=this.blurb=null;}};p.flyout_hide=function(){if(this.flyout_callback)
this.flyout_callback.destroy();$("#fbs_flyout").hide();};p.flyout_show=function(li,options,img_src,blurb){if("none"==$("#fbs_list").css("display"))
return;var s=this.list_selection().item;if(!(li==s&&li.fb_data.id==s.fb_data.id))
return;if(!$("#fbs_flyout").length){$(document.body).append('<div style="display:none;position:absolute" id="fbs_flyout" class="fbs-topshadow">'+'<div class="fbs-bottomshadow">'+'<div class="fbs-flyout-container">'+'<div class="fbs-flyout-name"></div>'+'<div class="fbs-flyout-image"></div>'+'<div class="fbs-flyout-types"></div>'+'<div class="fbs-flyout-domains"></div>'+'<div class="fbs-flyout-blurb"></div>'+'</div>'+'</div>'+'</div>');}
$("#fbs_flyout .fbs-flyout-name").empty().append('<a href="'+this.freebase_url(li.fb_data.id,options)+'">'+$(".fbs-li-name",li).text()+'</a>');$("#fbs_flyout .fbs-flyout-image").empty();if(img_src!="#")
$("#fbs_flyout .fbs-flyout-image").append('<img src="'+img_src+'"/>');$("#fbs_flyout .fbs-flyout-types").empty().append($(".fbs-li-types",li).text());$("#fbs_flyout .fbs-flyout-domains").empty().append($(".fbs-li-domains",li).text());$("#fbs_flyout .fbs-flyout-blurb").empty().append(blurb);var pos=$("#fbs_list > .fbs-bottomshadow > .fbs-ul").offset();var left=pos.left+options.width;var sl=document.body.scrollLeft;var ww=$(window).width();if((left+options.width)>(sl+ww))
left=pos.left-options.width;$("#fbs_flyout").css({top:pos.top,left:left,width:options.width}).show();};p.blurb_receive=function(id,cb,o){if(typeof o=="object"){if(o.status!=='200 OK'){fb.error("SuggestControl.blurb_receive",o.code,o.messages,o);return;}
o=o.result.body;}
cb.receive("blurb",o);};p.blurb_load=function(id,options,cb){$.ajax({type:"GET",url:options.service_url+this.blurb_path(id,options),data:options.blurb_param,success:this.delegate("blurb_receive",[id,cb]),dataType:use_jsonp(options)?"jsonp":null,cache:true});};p.image_load=function(id,options,cb){var i=new Image();var src=this.thumbnail_url(id,options);i.onload=fb.delegate(cb.receive,cb,["image",src]);i.onerror=fb.delegate(cb.receive,cb,["image",src]);fb.autoclean(i,fb.clean_image);i.src=src;};p.blurb_path=function(id,options){return options.blurb_path+this.quote_id(id);};p.thumbnail_url=function(id,options){var url=options.service_url+options.thumbnail_path+
this.quote_id(id);var qs=$.param(options.thumbnail_param);if(qs)
url+="?"+qs;return url;};p.freebase_url=function(id,options){var url=options.service_url+"/view"+this.quote_id(id);return url;};p.quote_id=function(id){if(id.charAt(0)=='/')
return id;else
return('/'+encodeURIComponent(id));};fb.suggest=SuggestControl;})(jQuery,window.freebase.controls);;__whitespace={" ":true,"\t":true,"\n":true,"\f":true,"\r":true};difflib={defaultJunkFunction:function(c){return c in __whitespace;},stripLinebreaks:function(str){return str.replace(/^[\n\r]*|[\n\r]*$/g,"");},stringAsLines:function(str){var lfpos=str.indexOf("\n");var crpos=str.indexOf("\r");var linebreak=((lfpos>-1&&crpos>-1)||crpos<0)?"\n":"\r";var lines=str.split(linebreak);for(var i=0;i<lines.length;i++){lines[i]=difflib.stripLinebreaks(lines[i]);}
return lines;},__reduce:function(func,list,initial){if(initial!=null){var value=initial;var idx=0;}else if(list){var value=list[0];var idx=1;}else{return null;}
for(;idx<list.length;idx++){value=func(value,list[idx]);}
return value;},__ntuplecomp:function(a,b){var mlen=Math.max(a.length,b.length);for(var i=0;i<mlen;i++){if(a[i]<b[i])return-1;if(a[i]>b[i])return 1;}
return a.length==b.length?0:(a.length<b.length?-1:1);},__calculate_ratio:function(matches,length){return length?2.0*matches/length:1.0;},__isindict:function(dict){return function(key){return key in dict;};},__dictget:function(dict,key,defaultValue){return key in dict?dict[key]:defaultValue;},SequenceMatcher:function(a,b,isjunk){this.set_seqs=function(a,b){this.set_seq1(a);this.set_seq2(b);}
this.set_seq1=function(a){if(a==this.a)return;this.a=a;this.matching_blocks=this.opcodes=null;}
this.set_seq2=function(b){if(b==this.b)return;this.b=b;this.matching_blocks=this.opcodes=this.fullbcount=null;this.__chain_b();}
this.__chain_b=function(){var b=this.b;var n=b.length;var b2j=this.b2j={};var populardict={};for(var i=0;i<b.length;i++){var elt=b[i];if(elt in b2j){var indices=b2j[elt];if(n>=200&&indices.length*100>n){populardict[elt]=1;delete b2j[elt];}else{indices.push(i);}}else{b2j[elt]=[i];}}
for(var elt in populardict)
delete b2j[elt];var isjunk=this.isjunk;var junkdict={};if(isjunk){for(var elt in populardict){if(isjunk(elt)){junkdict[elt]=1;delete populardict[elt];}}
for(var elt in b2j){if(isjunk(elt)){junkdict[elt]=1;delete b2j[elt];}}}
this.isbjunk=difflib.__isindict(junkdict);this.isbpopular=difflib.__isindict(populardict);}
this.find_longest_match=function(alo,ahi,blo,bhi){var a=this.a;var b=this.b;var b2j=this.b2j;var isbjunk=this.isbjunk;var besti=alo;var bestj=blo;var bestsize=0;var j=null;var j2len={};var nothing=[];for(var i=alo;i<ahi;i++){var newj2len={};var jdict=difflib.__dictget(b2j,a[i],nothing);for(var jkey in jdict){j=jdict[jkey];if(j<blo)continue;if(j>=bhi)break;newj2len[j]=k=difflib.__dictget(j2len,j-1,0)+1;if(k>bestsize){besti=i-k+1;bestj=j-k+1;bestsize=k;}}
j2len=newj2len;}
while(besti>alo&&bestj>blo&&!isbjunk(b[bestj-1])&&a[besti-1]==b[bestj-1]){besti--;bestj--;bestsize++;}
while(besti+bestsize<ahi&&bestj+bestsize<bhi&&!isbjunk(b[bestj+bestsize])&&a[besti+bestsize]==b[bestj+bestsize]){bestsize++;}
while(besti>alo&&bestj>blo&&isbjunk(b[bestj-1])&&a[besti-1]==b[bestj-1]){besti--;bestj--;bestsize++;}
while(besti+bestsize<ahi&&bestj+bestsize<bhi&&isbjunk(b[bestj+bestsize])&&a[besti+bestsize]==b[bestj+bestsize]){bestsize++;}
return[besti,bestj,bestsize];}
this.get_matching_blocks=function(){if(this.matching_blocks!=null)return this.matching_blocks;var la=this.a.length;var lb=this.b.length;var queue=[[0,la,0,lb]];var matching_blocks=[];var alo,ahi,blo,bhi,qi,i,j,k,x;while(queue.length){qi=queue.pop();alo=qi[0];ahi=qi[1];blo=qi[2];bhi=qi[3];x=this.find_longest_match(alo,ahi,blo,bhi);i=x[0];j=x[1];k=x[2];if(k){matching_blocks.push(x);if(alo<i&&blo<j)
queue.push([alo,i,blo,j]);if(i+k<ahi&&j+k<bhi)
queue.push([i+k,ahi,j+k,bhi]);}}
matching_blocks.sort(difflib.__ntuplecomp);var i1=j1=k1=block=0;var non_adjacent=[];for(var idx in matching_blocks){block=matching_blocks[idx];i2=block[0];j2=block[1];k2=block[2];if(i1+k1==i2&&j1+k1==j2){k1+=k2;}else{if(k1)non_adjacent.push([i1,j1,k1]);i1=i2;j1=j2;k1=k2;}}
if(k1)non_adjacent.push([i1,j1,k1]);non_adjacent.push([la,lb,0]);this.matching_blocks=non_adjacent;return this.matching_blocks;}
this.get_opcodes=function(){if(this.opcodes!=null)return this.opcodes;var i=0;var j=0;var answer=[];this.opcodes=answer;var block,ai,bj,size,tag;var blocks=this.get_matching_blocks();for(var idx in blocks){block=blocks[idx];ai=block[0];bj=block[1];size=block[2];tag='';if(i<ai&&j<bj){tag='replace';}else if(i<ai){tag='delete';}else if(j<bj){tag='insert';}
if(tag)answer.push([tag,i,ai,j,bj]);i=ai+size;j=bj+size;if(size)answer.push(['equal',ai,i,bj,j]);}
return answer;}
this.get_grouped_opcodes=function(n){if(!n)n=3;var codes=this.get_opcodes();if(!codes)codes=[["equal",0,1,0,1]];var code,tag,i1,i2,j1,j2;if(codes[0][0]=='equal'){code=codes[0];tag=code[0];i1=code[1];i2=code[2];j1=code[3];j2=code[4];codes[0]=[tag,Math.max(i1,i2-n),i2,Math.max(j1,j2-n),j2];}
if(codes[codes.length-1][0]=='equal'){code=codes[codes.length-1];tag=code[0];i1=code[1];i2=code[2];j1=code[3];j2=code[4];codes[codes.length-1]=[tag,i1,Math.min(i2,i1+n),j1,Math.min(j2,j1+n)];}
var nn=n+n;var groups=[];for(var idx in codes){code=codes[idx];tag=code[0];i1=code[1];i2=code[2];j1=code[3];j2=code[4];if(tag=='equal'&&i2-i1>nn){groups.push([tag,i1,Math.min(i2,i1+n),j1,Math.min(j2,j1+n)]);i1=Math.max(i1,i2-n);j1=Math.max(j1,j2-n);}
groups.push([tag,i1,i2,j1,j2]);}
if(groups&&groups[groups.length-1][0]=='equal')groups.pop();return groups;}
this.ratio=function(){matches=difflib.__reduce(function(sum,triple){return sum+triple[triple.length-1];},this.get_matching_blocks(),0);return difflib.__calculate_ratio(matches,this.a.length+this.b.length);}
this.quick_ratio=function(){var fullbcount,elt;if(this.fullbcount==null){this.fullbcount=fullbcount={};for(var i=0;i<this.b.length;i++){elt=this.b[i];fullbcount[elt]=difflib.__dictget(fullbcount,elt,0)+1;}}
fullbcount=this.fullbcount;var avail={};var availhas=difflib.__isindict(avail);var matches=numb=0;for(var i=0;i<this.a.length;i++){elt=this.a[i];if(availhas(elt)){numb=avail[elt];}else{numb=difflib.__dictget(fullbcount,elt,0);}
avail[elt]=numb-1;if(numb>0)matches++;}
return difflib.__calculate_ratio(matches,this.a.length+this.b.length);}
this.real_quick_ratio=function(){var la=this.a.length;var lb=this.b.length;return _calculate_ratio(Math.min(la,lb),la+lb);}
this.isjunk=isjunk?isjunk:difflib.defaultJunkFunction;this.a=this.b=null;this.set_seqs(a,b);}};var CodeMirrorConfig=window.CodeMirrorConfig||{};var CodeMirror=(function(){function setDefaults(object,defaults){for(var option in defaults){if(!object.hasOwnProperty(option))
object[option]=defaults[option];}}
function forEach(array,action){for(var i=0;i<array.length;i++)
action(array[i]);}
setDefaults(CodeMirrorConfig,{stylesheet:"",path:"",parserfile:[],basefiles:["util.js","stringstream.js","select.js","undo.js","editor.js","tokenize.js"],iframeClass:null,passDelay:200,passTime:50,continuousScanning:false,saveFunction:null,onChange:null,undoDepth:50,undoDelay:800,disableSpellcheck:true,textWrapping:true,readOnly:false,width:"100%",height:"300px",autoMatchParens:false,parserConfig:null,tabMode:"indent",reindentOnLoad:false,activeTokens:null,cursorActivity:null,lineNumbers:false,indentUnit:2});function wrapLineNumberDiv(place){return function(node){var container=document.createElement("DIV"),nums=document.createElement("DIV"),scroller=document.createElement("DIV");container.style.position="relative";nums.style.position="absolute";nums.style.height="100%";if(nums.style.setExpression){try{nums.style.setExpression("height","this.previousSibling.offsetHeight + 'px'");}
catch(e){}}
nums.style.top="0px";nums.style.overflow="hidden";place(container);container.appendChild(node);container.appendChild(nums);scroller.className="CodeMirror-line-numbers";nums.appendChild(scroller);}}
function applyLineNumbers(frame){var win=frame.contentWindow,doc=win.document,nums=frame.nextSibling,scroller=nums.firstChild;var nextNum=1,barWidth=null;function sizeBar(){if(!frame.offsetWidth||!win.Editor){for(var cur=frame;cur.parentNode;cur=cur.parentNode){if(cur!=document){clearInterval(sizeInterval);return;}}}
if(nums.offsetWidth!=barWidth){barWidth=nums.offsetWidth;nums.style.left="-"+(frame.parentNode.style.marginLeft=barWidth+"px");}}
function update(){var diff=20+Math.max(doc.body.offsetHeight,frame.offsetHeight)-scroller.offsetHeight;for(var n=Math.ceil(diff/10);n>0;n--){var div=document.createElement("DIV");div.appendChild(document.createTextNode(nextNum++));scroller.appendChild(div);}
nums.scrollTop=doc.body.scrollTop||doc.documentElement.scrollTop||0;}
sizeBar();update();win.addEventHandler(win,"scroll",update);win.addEventHandler(win,"resize",update);var sizeInterval=setInterval(sizeBar,500);}
function CodeMirror(place,options){if(options.dumbTabs)options.tabMode="spaces";else if(options.normalTab)options.tabMode="default";this.options=options=options||{};setDefaults(options,CodeMirrorConfig);var frame=this.frame=document.createElement("IFRAME");if(options.iframeClass)frame.className=options.iframeClass;frame.frameBorder=0;frame.src="javascript:false;";frame.style.border="0";frame.style.width=options.width;frame.style.height=options.height;frame.style.display="block";if(place.appendChild){var node=place;place=function(n){node.appendChild(n);};}
if(options.lineNumbers)place=wrapLineNumberDiv(place);place(frame);frame.CodeMirror=this;this.win=frame.contentWindow;if(typeof options.parserfile=="string")
options.parserfile=[options.parserfile];if(typeof options.stylesheet=="string")
options.stylesheet=[options.stylesheet];var html=["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"];html.push("<style type=\"text/css\">",CodeMirrorConfig.INLINE_CSS,"</style> <script type=\"text/javascript\">",CodeMirrorConfig.INLINE_JS,"</script>");html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\""+
(options.disableSpellcheck?"false":"true")+"\"></body></html>");var doc=this.win.document;doc.open();doc.write(html.join(""));doc.close();}
CodeMirror.prototype={init:function(){if(this.options.initCallback)this.options.initCallback(this);if(this.options.lineNumbers)applyLineNumbers(this.frame);if(this.options.reindentOnLoad)this.reindent();},getCode:function(){return this.editor.getCode();},setCode:function(code){this.editor.importCode(code);},selection:function(){this.focusIfIE();return this.editor.selectedText();},reindent:function(){this.editor.reindent();},reindentSelection:function(){this.focusIfIE();this.editor.reindentSelection(null);},focusIfIE:function(){if(this.win.select.ie_selection)this.focus();},focus:function(){this.win.focus();if(this.editor.selectionSnapshot)
this.win.select.selectCoords(this.win,this.editor.selectionSnapshot);},replaceSelection:function(text){this.focus();this.editor.replaceSelection(text);return true;},replaceChars:function(text,start,end){this.editor.replaceChars(text,start,end);},getSearchCursor:function(string,fromCursor){return this.editor.getSearchCursor(string,fromCursor);},undo:function(){this.editor.win.select.scrollToNode(this.editor.history.undo());},redo:function(){this.editor.win.select.scrollToNode(this.editor.history.redo());},historySize:function(){return this.editor.history.historySize();},clearHistory:function(){this.editor.history.clear();},grabKeys:function(callback,filter){this.editor.grabKeys(callback,filter);},ungrabKeys:function(){this.editor.ungrabKeys();},setParser:function(name){this.editor.setParser(name);},cursorPosition:function(start){this.focusIfIE();return this.editor.cursorPosition(start);},firstLine:function(){return this.editor.firstLine();},lastLine:function(){return this.editor.lastLine();},nextLine:function(line){return this.editor.nextLine(line);},prevLine:function(line){return this.editor.prevLine(line);},lineContent:function(line){return this.editor.lineContent(line);},setLineContent:function(line,content){this.editor.setLineContent(line,content);},insertIntoLine:function(line,position,content){this.editor.insertIntoLine(line,position,content);},selectLines:function(startLine,startOffset,endLine,endOffset){this.win.focus();this.editor.selectLines(startLine,startOffset,endLine,endOffset);},nthLine:function(n){var line=this.firstLine();for(;n>1&&line!==false;n--)
line=this.nextLine(line);return line;},lineNumber:function(line){var num=0;while(line!==false){num++;line=this.prevLine(line);}
return num;},jumpToLine:function(n){this.selectLines(this.nthLine(n),0);this.win.focus();},currentLine:function(){return this.lineNumber(this.cursorPosition().line);}};CodeMirror.InvalidLineHandle={toString:function(){return"CodeMirror.InvalidLineHandle";}};CodeMirror.replace=function(element){if(typeof element=="string")
element=document.getElementById(element);return function(newElement){element.parentNode.replaceChild(newElement,element);};};CodeMirror.fromTextArea=function(area,options){if(typeof area=="string")
area=document.getElementById(area);options=options||{};if(area.style.width&&options.width==null)
options.width=area.style.width;if(area.style.height&&options.height==null)
options.height=area.style.height;if(options.content==null)options.content=area.value;if(area.form){function updateField(){area.value=mirror.getCode();}
if(typeof area.form.addEventListener=="function")
area.form.addEventListener("submit",updateField,false);else
area.form.attachEvent("onsubmit",updateField);}
function insert(frame){if(area.nextSibling)
area.parentNode.insertBefore(frame,area.nextSibling);else
area.parentNode.appendChild(frame);}
area.style.display="none";var mirror=new CodeMirror(insert,options);return mirror;};CodeMirror.isProbablySupported=function(){var match;if(window.opera)
return Number(window.opera.version())>=9.52;else if(/Apple Computers, Inc/.test(navigator.vendor)&&(match=navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
return Number(match[1])>=3;else if(document.selection&&window.ActiveXObject&&(match=navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
return Number(match[1])>=6;else if(match=navigator.userAgent.match(/gecko\/(\d{8})/i))
return Number(match[1])>=20050901;else if(match=navigator.userAgent.match(/AppleWebKit\/(\d+)/))
return Number(match[1])>=525;else
return null;};return CodeMirror;})();CodeMirrorConfig.INLINE_JS=[';var internetExplorer=document.selection&&window.ActiveXObject&&/MSIE/.test(navigator.userAgent);var webkit=/AppleWebKit/.test(navigator.userAgent);var safari=/Apple Computers, Inc/.test(navigator.vendor);function method(obj,name){return function(){obj[name].apply(obj,arguments);};}','var StopIteration={toString:function(){return"StopIteration"}};function forEach(iter,f){if(iter.next){try{while(true)f(iter.next());}','catch(e){if(e!=StopIteration)throw e;}}','else{for(var i=0;i<iter.length;i++)','f(iter[i]);}}','function map(iter,f){var accum=[];forEach(iter,function(val){accum.push(f(val));});return accum;}','function matcher(regexp){return function(value){return regexp.test(value);};}','function hasClass(element,className){var classes=element.className;return classes&&new RegExp("(^| )"+className+"($| )").test(classes);}','function insertAfter(newNode,oldNode){var parent=oldNode.parentNode;parent.insertBefore(newNode,oldNode.nextSibling);return newNode;}','function removeElement(node){if(node.parentNode)','node.parentNode.removeChild(node);}','function clearElement(node){while(node.firstChild)','node.removeChild(node.firstChild);}','function isAncestor(node,child){while(child=child.parentNode){if(node==child)','return true;}','return false;}','var nbsp="\\u00a0";var matching={"{":"}","[":"]","(":")","}":"{","]":"[",")":"("};function normalizeEvent(event){if(!event.stopPropagation){event.stopPropagation=function(){this.cancelBubble=true;};event.preventDefault=function(){this.returnValue=false;};}','if(!event.stop){event.stop=function(){this.stopPropagation();this.preventDefault();};}','if(event.type=="keypress"){event.code=(event.charCode==null)?event.keyCode:event.charCode;event.character=String.fromCharCode(event.code);}','return event;}','function addEventHandler(node,type,handler,removeFunc){function wrapHandler(event){handler(normalizeEvent(event||window.event));}','if(typeof node.addEventListener=="function"){node.addEventListener(type,wrapHandler,false);if(removeFunc)return function(){node.removeEventListener(type,wrapHandler,false);};}','else{node.attachEvent("on"+type,wrapHandler);if(removeFunc)return function(){node.detachEvent("on"+type,wrapHandler);};}}','function nodeText(node){return node.textContent||node.innerText||node.nodeValue||"";}','function nodeTop(node){var top=0;while(node.offsetParent){top+=node.offsetTop;node=node.offsetParent;}','return top;};window.stringStream=function(source){var current="";var pos=0;var accum="";function ensureChars(){while(pos==current.length){accum+=current;current="";pos=0;try{current=source.next();}','catch(e){if(e!=StopIteration)throw e;else return false;}}','return true;}','return{peek:function(){if(!ensureChars())return null;return current.charAt(pos);},next:function(){if(!ensureChars()){if(accum.length>0)','throw"End of stringstream reached without emptying buffer (\'"+accum+"\').";else','throw StopIteration;}','return current.charAt(pos++);},get:function(){var temp=accum;accum="";if(pos>0){temp+=current.slice(0,pos);current=current.slice(pos);pos=0;}','return temp;},push:function(str){current=current.slice(0,pos)+str+current.slice(pos);},lookAhead:function(str,consume,skipSpaces,caseInsensitive){function cased(str){return caseInsensitive?str.toLowerCase():str;}','str=cased(str);var found=false;var _accum=accum,_pos=pos;if(skipSpaces)this.nextWhileMatches(/[\\s\\u00a0]/);while(true){var end=pos+str.length,left=current.length-pos;if(end<=current.length){found=str==cased(current.slice(pos,end));pos=end;break;}','else if(str.slice(0,left)==cased(current.slice(pos))){accum+=current;current="";try{current=source.next();}','catch(e){break;}','pos=0;str=str.slice(left);}','else{break;}}','if(!(found&&consume)){current=accum.slice(_accum.length)+current;pos=_pos;accum=_accum;}','return found;},more:function(){return this.peek()!==null;},applies:function(test){var next=this.peek();return(next!==null&&test(next));},nextWhile:function(test){var next;while((next=this.peek())!==null&&test(next))','this.next();},matches:function(re){var next=this.peek();return(next!==null&&re.test(next));},nextWhileMatches:function(re){var next;while((next=this.peek())!==null&&re.test(next))','this.next();},equals:function(ch){return ch===this.peek();},endOfLine:function(){var next=this.peek();return next==null||next=="\\n";}};};;var select={};(function(){select.ie_selection=document.selection&&document.selection.createRangeCollection;function topLevelNodeAt(node,top){while(node&&node.parentNode!=top)','node=node.parentNode;return node;}','function topLevelNodeBefore(node,top){while(!node.previousSibling&&node.parentNode!=top)','node=node.parentNode;return topLevelNodeAt(node.previousSibling,top);}','var fourSpaces="\\u00a0\\u00a0\\u00a0\\u00a0";select.scrollToNode=function(element){if(!element)return;var doc=element.ownerDocument,body=doc.body,win=(doc.defaultView||doc.parentWindow),html=doc.documentElement,atEnd=!element.nextSibling||!element.nextSibling.nextSibling||!element.nextSibling.nextSibling.nextSibling;var compensateHack=0;while(element&&!element.offsetTop){compensateHack++;element=element.previousSibling;}','if(compensateHack==0)atEnd=false;var y=compensateHack*(element?element.offsetHeight:0),x=0,pos=element;while(pos&&pos.offsetParent){y+=pos.offsetTop;if(pos.nodeName!="BR")','x+=pos.offsetLeft;pos=pos.offsetParent;}','var scroll_x=body.scrollLeft||html.scrollLeft||0,scroll_y=body.scrollTop||html.scrollTop||0,screen_x=x-scroll_x,screen_y=y-scroll_y,scroll=false;if(screen_x<0||screen_x>(win.innerWidth||html.clientWidth||0)){scroll_x=x;scroll=true;}','if(screen_y<0||atEnd||screen_y>(win.innerHeight||html.clientHeight||0)-50){scroll_y=atEnd?1e10:y;scroll=true;}','if(scroll)win.scrollTo(scroll_x,scroll_y);};select.scrollToCursor=function(container){select.scrollToNode(select.selectionTopNode(container,true)||container.firstChild);};var currentSelection=null;select.snapshotChanged=function(){if(currentSelection)currentSelection.changed=true;};select.snapshotReplaceNode=function(from,to,length,offset){if(!currentSelection)return;function replace(point){if(from==point.node){currentSelection.changed=true;if(length&&point.offset>length){point.offset-=length;}','else{point.node=to;point.offset+=(offset||0);}}}','replace(currentSelection.start);replace(currentSelection.end);};select.snapshotMove=function(from,to,distance,relative,ifAtStart){if(!currentSelection)return;function move(point){if(from==point.node&&(!ifAtStart||point.offset==0)){currentSelection.changed=true;point.node=to;if(relative)point.offset=Math.max(0,point.offset+distance);else point.offset=distance;}}','move(currentSelection.start);move(currentSelection.end);};if(select.ie_selection){function selectionNode(win,start){var range=win.document.selection.createRange();range.collapse(start);function nodeAfter(node){var found=null;while(!found&&node){found=node.nextSibling;node=node.parentNode;}','return nodeAtStartOf(found);}','function nodeAtStartOf(node){while(node&&node.firstChild)node=node.firstChild;return{node:node,offset:0};}','var containing=range.parentElement();if(!isAncestor(win.document.body,containing))return null;if(!containing.firstChild)return nodeAtStartOf(containing);var working=range.duplicate();working.moveToElementText(containing);working.collapse(true);for(var cur=containing.firstChild;cur;cur=cur.nextSibling){if(cur.nodeType==3){var size=cur.nodeValue.length;working.move("character",size);}','else{working.moveToElementText(cur);working.collapse(false);}','var dir=range.compareEndPoints("StartToStart",working);if(dir==0)return nodeAfter(cur);if(dir==1)continue;if(cur.nodeType!=3)return nodeAtStartOf(cur);working.setEndPoint("StartToEnd",range);return{node:cur,offset:size-working.text.length};}','return nodeAfter(containing);}','select.markSelection=function(win){currentSelection=null;var sel=win.document.selection;if(!sel)return;var start=selectionNode(win,true),end=selectionNode(win,false);if(!start||!end)return;currentSelection={start:start,end:end,window:win,changed:false};};select.selectMarked=function(){if(!currentSelection||!currentSelection.changed)return;var win=currentSelection.window,doc=win.document;function makeRange(point){var range=doc.body.createTextRange(),node=point.node;if(!node){range.moveToElementText(currentSelection.window.document.body);range.collapse(false);}','else if(node.nodeType==3){range.moveToElementText(node.parentNode);var offset=point.offset;while(node.previousSibling){node=node.previousSibling;offset+=(node.innerText||"").length;}','range.move("character",offset);}','else{range.moveToElementText(node);range.collapse(true);}','return range;}','var start=makeRange(currentSelection.start),end=makeRange(currentSelection.end);start.setEndPoint("StartToEnd",end);start.select();};select.selectionTopNode=function(container,start){var selection=container.ownerDocument.selection;if(!selection)return false;var range=selection.createRange(),range2=range.duplicate();range.collapse(start);var around=range.parentElement();if(around&&isAncestor(container,around)){range2.moveToElementText(around);if(range.compareEndPoints("StartToStart",range2)==1)','return topLevelNodeAt(around,container);}','function moveToNodeStart(range,node){if(node.nodeType==3){var count=0,cur=node.previousSibling;while(cur&&cur.nodeType==3){count+=cur.nodeValue.length;cur=cur.previousSibling;}','if(cur){try{range.moveToElementText(cur);}','catch(e){return false;}','range.collapse(false);}','else range.moveToElementText(node.parentNode);if(count)range.move("character",count);}','else{try{range.moveToElementText(node);}','catch(e){return false;}}','return true;}','var start=0,end=container.childNodes.length-1;while(start<end){var middle=Math.ceil((end+start)/2),node=container.childNodes[middle];if(!node)return false;if(!moveToNodeStart(range2,node))return false;if(range.compareEndPoints("StartToStart",range2)==1)','start=middle;else','end=middle-1;}','return container.childNodes[start]||null;};select.focusAfterNode=function(node,container){var range=container.ownerDocument.body.createTextRange();range.moveToElementText(node||container);range.collapse(!node);range.select();};select.somethingSelected=function(win){var sel=win.document.selection;return sel&&(sel.createRange().text!="");};function insertAtCursor(window,html){var selection=window.document.selection;if(selection){var range=selection.createRange();range.pasteHTML(html);range.collapse(false);range.select();}}','select.insertNewlineAtCursor=function(window){insertAtCursor(window,"<br>");};select.insertTabAtCursor=function(window){insertAtCursor(window,fourSpaces);};select.cursorPos=function(container,start){var selection=container.ownerDocument.selection;if(!selection)return null;var topNode=select.selectionTopNode(container,start);while(topNode&&topNode.nodeName!="BR")','topNode=topNode.previousSibling;var range=selection.createRange(),range2=range.duplicate();range.collapse(start);if(topNode){range2.moveToElementText(topNode);range2.collapse(false);}','else{try{range2.moveToElementText(container);}','catch(e){return null;}','range2.collapse(true);}','range.setEndPoint("StartToStart",range2);return{node:topNode,offset:range.text.length};};select.setCursorPos=function(container,from,to){function rangeAt(pos){var range=container.ownerDocument.body.createTextRange();if(!pos.node){range.moveToElementText(container);range.collapse(true);}','else{range.moveToElementText(pos.node);range.collapse(false);}','range.move("character",pos.offset);return range;}','var range=rangeAt(from);if(to&&to!=from)','range.setEndPoint("EndToEnd",rangeAt(to));range.select();}','select.selectionCoords=function(win){var selection=win.document.selection;if(!selection)return null;var start=selection.createRange(),end=start.duplicate();start.collapse(true);end.collapse(false);var body=win.document.body;return{start:{x:start.boundingLeft+body.scrollLeft-1,y:start.boundingTop+body.scrollTop},end:{x:end.boundingLeft+body.scrollLeft-1,y:end.boundingTop+body.scrollTop}};};select.selectCoords=function(win,coords){if(!coords)return;var range1=win.document.body.createTextRange(),range2=range1.duplicate();try{range1.moveToPoint(coords.start.x,coords.start.y);range2.moveToPoint(coords.end.x,coords.end.y);range1.setEndPoint("EndToStart",range2);range1.select();}catch(e){}};}','else{select.markSelection=function(win){var selection=win.getSelection();if(!selection||selection.rangeCount==0)','return(currentSelection=null);var range=selection.getRangeAt(0);currentSelection={start:{node:range.startContainer,offset:range.startOffset},end:{node:range.endContainer,offset:range.endOffset},window:win,changed:false};function normalize(point){while(point.node.nodeType!=3&&point.node.nodeName!="BR"){var newNode=point.node.childNodes[point.offset]||point.node.nextSibling;point.offset=0;while(!newNode&&point.node.parentNode){point.node=point.node.parentNode;newNode=point.node.nextSibling;}','point.node=newNode;if(!newNode)','break;}}','normalize(currentSelection.start);normalize(currentSelection.end);};select.selectMarked=function(){var cs=currentSelection;if(!(cs&&(cs.changed||(webkit&&cs.start.node==cs.end.node))))return;var win=cs.window,range=win.document.createRange();function setPoint(point,which){if(point.node){if(point.offset==0)','range["set"+which+"Before"](point.node);else','range["set"+which](point.node,point.offset);}','else{range.setStartAfter(win.document.body.lastChild||win.document.body);}}','setPoint(cs.end,"End");setPoint(cs.start,"Start");selectRange(range,win);};function selectRange(range,window){var selection=window.getSelection();selection.removeAllRanges();selection.addRange(range);};function selectionRange(window){var selection=window.getSelection();if(!selection||selection.rangeCount==0)','return false;else','return selection.getRangeAt(0);}','select.selectionTopNode=function(container,start){var range=selectionRange(container.ownerDocument.defaultView);if(!range)return false;var node=start?range.startContainer:range.endContainer;var offset=start?range.startOffset:range.endOffset;if(window.opera&&!start&&range.endContainer==container&&range.endOffset==range.startOffset+1&&container.childNodes[range.startOffset]&&container.childNodes[range.startOffset].nodeName=="BR")','offset--;if(node.nodeType==3){if(offset>0)','return topLevelNodeAt(node,container);else','return topLevelNodeBefore(node,container);}','else if(node.nodeName=="HTML"){return(offset==1?null:container.lastChild);}','else if(node==container){return(offset==0)?null:node.childNodes[offset-1];}','else{if(offset==node.childNodes.length)','return topLevelNodeAt(node,container);else if(offset==0)','return topLevelNodeBefore(node,container);else','return topLevelNodeAt(node.childNodes[offset-1],container);}};select.focusAfterNode=function(node,container){var win=container.ownerDocument.defaultView,range=win.document.createRange();range.setStartBefore(container.firstChild||container);if(node&&!node.firstChild)','range.setEndAfter(node);else if(node)','range.setEnd(node,node.childNodes.length);else','range.setEndBefore(container.firstChild||container);range.collapse(false);selectRange(range,win);};select.somethingSelected=function(win){var range=selectionRange(win);return range&&!range.collapsed;};function insertNodeAtCursor(window,node){var range=selectionRange(window);if(!range)return;range.deleteContents();range.insertNode(node);webkitLastLineHack(window.document.body);range=window.document.createRange();range.selectNode(node);range.collapse(false);selectRange(range,window);}','select.insertNewlineAtCursor=function(window){insertNodeAtCursor(window,window.document.createElement("BR"));};select.insertTabAtCursor=function(window){insertNodeAtCursor(window,window.document.createTextNode(fourSpaces));};select.cursorPos=function(container,start){var range=selectionRange(window);if(!range)return;var topNode=select.selectionTopNode(container,start);while(topNode&&topNode.nodeName!="BR")','topNode=topNode.previousSibling;range=range.cloneRange();range.collapse(start);if(topNode)','range.setStartAfter(topNode);else','range.setStartBefore(container);return{node:topNode,offset:range.toString().length};};select.setCursorPos=function(container,from,to){var win=container.ownerDocument.defaultView,range=win.document.createRange();function setPoint(node,offset,side){if(!node)','node=container.firstChild;else','node=node.nextSibling;if(!node)','return;if(offset==0){range["set"+side+"Before"](node);return true;}','var backlog=[]','function decompose(node){if(node.nodeType==3)','backlog.push(node);else','forEach(node.childNodes,decompose);}','while(true){while(node&&!backlog.length){decompose(node);node=node.nextSibling;}','var cur=backlog.shift();if(!cur)return false;var length=cur.nodeValue.length;if(length>=offset){range["set"+side](cur,offset);return true;}','offset-=length;}}','to=to||from;if(setPoint(to.node,to.offset,"End")&&setPoint(from.node,from.offset,"Start"))','selectRange(range,win);};}})();;function History(container,maxDepth,commitDelay,editor,onChange){this.container=container;this.maxDepth=maxDepth;this.commitDelay=commitDelay;this.editor=editor;this.parent=editor.parent;this.onChange=onChange;var initial={text:"",from:null,to:null};this.first=initial;this.last=initial;this.firstTouched=false;this.history=[];this.redoHistory=[];this.touched=[];}','History.prototype={scheduleCommit:function(){var self=this;this.parent.clearTimeout(this.commitTimeout);this.commitTimeout=this.parent.setTimeout(function(){self.tryCommit();},this.commitDelay);},touch:function(node){this.setTouched(node);this.scheduleCommit();},undo:function(){this.commit();if(this.history.length){var item=this.history.pop();this.redoHistory.push(this.updateTo(item,"applyChain"));if(this.onChange)this.onChange();return this.chainNode(item);}},redo:function(){this.commit();if(this.redoHistory.length){var item=this.redoHistory.pop();this.addUndoLevel(this.updateTo(item,"applyChain"));if(this.onChange)this.onChange();return this.chainNode(item);}},clear:function(){this.history=[];this.redoHistory=[];},historySize:function(){return{undo:this.history.length,redo:this.redoHistory.length};},push:function(from,to,lines,programmaticChange){var chain=[];for(var i=0;i<lines.length;i++){var end=(i==lines.length-1)?to:this.container.ownerDocument.createElement("BR");chain.push({from:from,to:end,text:cleanText(lines[i])});from=end;}','this.pushChains([chain],from==null&&to==null);if(!programmaticChange&&this.onChange)this.onChange();},pushChains:function(chains,doNotHighlight){this.commit(doNotHighlight);this.addUndoLevel(this.updateTo(chains,"applyChain"));this.redoHistory=[];},chainNode:function(chains){for(var i=0;i<chains.length;i++){var start=chains[i][0],node=start&&(start.from||start.to);if(node)return node;}},reset:function(){this.history=[];this.redoHistory=[];},textAfter:function(br){return this.after(br).text;},nodeAfter:function(br){return this.after(br).to;},nodeBefore:function(br){return this.before(br).from;},tryCommit:function(){if(!window.History)return;if(this.editor.highlightDirty())this.commit(true);else this.scheduleCommit();},commit:function(doNotHighlight){this.parent.clearTimeout(this.commitTimeout);if(!doNotHighlight)this.editor.highlightDirty(true);var chains=this.touchedChains(),self=this;if(chains.length){this.addUndoLevel(this.updateTo(chains,"linkChain"));this.redoHistory=[];if(this.onChange)this.onChange();}},updateTo:function(chains,updateFunc){var shadows=[],dirty=[];for(var i=0;i<chains.length;i++){shadows.push(this.shadowChain(chains[i]));dirty.push(this[updateFunc](chains[i]));}','if(updateFunc=="applyChain")','this.notifyDirty(dirty);return shadows;},notifyDirty:function(nodes){forEach(nodes,method(this.editor,"addDirtyNode"))','this.editor.scheduleHighlight();},linkChain:function(chain){for(var i=0;i<chain.length;i++){var line=chain[i];if(line.from)line.from.historyAfter=line;else this.first=line;if(line.to)line.to.historyBefore=line;else this.last=line;}},after:function(node){return node?node.historyAfter:this.first;},before:function(node){return node?node.historyBefore:this.last;},setTouched:function(node){if(node){if(!node.historyTouched){this.touched.push(node);node.historyTouched=true;}}','else{this.firstTouched=true;}},addUndoLevel:function(diffs){this.history.push(diffs);if(this.history.length>this.maxDepth)','this.history.shift();},touchedChains:function(){var self=this;var nullTemp=null;function temp(node){return node?node.historyTemp:nullTemp;}','function setTemp(node,line){if(node)node.historyTemp=line;else nullTemp=line;}','function buildLine(node){var text=[];for(var cur=node?node.nextSibling:self.container.firstChild;cur&&cur.nodeName!="BR";cur=cur.nextSibling)','if(cur.currentText)text.push(cur.currentText);return{from:node,to:cur,text:cleanText(text.join(""))};}','var lines=[];if(self.firstTouched)self.touched.push(null);forEach(self.touched,function(node){if(node&&node.parentNode!=self.container)return;if(node)node.historyTouched=false;else self.firstTouched=false;var line=buildLine(node),shadow=self.after(node);if(!shadow||shadow.text!=line.text||shadow.to!=line.to){lines.push(line);setTemp(node,line);}});function nextBR(node,dir){var link=dir+"Sibling",search=node[link];while(search&&search.nodeName!="BR")','search=search[link];return search;}','var chains=[];self.touched=[];forEach(lines,function(line){if(!temp(line.from))return;var chain=[],curNode=line.from,safe=true;while(true){var curLine=temp(curNode);if(!curLine){if(safe)break;else curLine=buildLine(curNode);}','chain.unshift(curLine);setTemp(curNode,null);if(!curNode)break;safe=self.after(curNode);curNode=nextBR(curNode,"previous");}','curNode=line.to;safe=self.before(line.from);while(true){if(!curNode)break;var curLine=temp(curNode);if(!curLine){if(safe)break;else curLine=buildLine(curNode);}','chain.push(curLine);setTemp(curNode,null);safe=self.before(curNode);curNode=nextBR(curNode,"next");}','chains.push(chain);});return chains;},shadowChain:function(chain){var shadows=[],next=this.after(chain[0].from),end=chain[chain.length-1].to;while(true){shadows.push(next);var nextNode=next.to;if(!nextNode||nextNode==end)','break;else','next=nextNode.historyAfter||this.before(end);}','return shadows;},applyChain:function(chain){var cursor=select.cursorPos(this.container,false),self=this;function removeRange(from,to){var pos=from?from.nextSibling:self.container.firstChild;while(pos!=to){var temp=pos.nextSibling;removeElement(pos);pos=temp;}}','var start=chain[0].from,end=chain[chain.length-1].to;removeRange(start,end);for(var i=0;i<chain.length;i++){var line=chain[i];if(i>0)','self.container.insertBefore(line.from,end);var node=makePartSpan(fixSpaces(line.text),this.container.ownerDocument);self.container.insertBefore(node,end);if(cursor&&cursor.node==line.from){var cursordiff=0;var prev=this.after(line.from);if(prev&&i==chain.length-1){for(var match=0;match<cursor.offset&&line.text.charAt(match)==prev.text.charAt(match);match++);if(cursor.offset>match)','cursordiff=line.text.length-prev.text.length;}','select.setCursorPos(this.container,{node:line.from,offset:Math.max(0,cursor.offset+cursordiff)});}','else if(cursor&&(i==chain.length-1)&&cursor.node&&cursor.node.parentNode!=this.container){select.setCursorPos(this.container,{node:line.from,offset:line.text.length});}}','this.linkChain(chain);return start;}};;function makeWhiteSpace(n){var buffer=[],nb=true;for(;n>0;n--){buffer.push((nb||n==1)?nbsp:" ");nb=!nb;}','return buffer.join("");}','function fixSpaces(string){if(string.charAt(0)==" ")string=nbsp+string.slice(1);return string.replace(/\\t/g,function(){return makeWhiteSpace(indentUnit);}).replace(/[ \\u00a0]{2,}/g,function(s){return makeWhiteSpace(s.length);});}','function cleanText(text){return text.replace(/\\u00a0/g," ").replace(/\\u200b/g,"");}','function makePartSpan(value,doc){var text=value;if(value.nodeType==3)text=value.nodeValue;else value=doc.createTextNode(text);var span=doc.createElement("SPAN");span.isPart=true;span.appendChild(value);span.currentText=text;return span;}','var webkitLastLineHack=webkit?function(container){var last=container.lastChild;if(!last||!last.isPart||last.textContent!="\\u200b")','container.appendChild(makePartSpan("\\u200b",container.ownerDocument));}:function(){};var Editor=(function(){var newlineElements={"P":true,"DIV":true,"LI":true};function asEditorLines(string){var tab=makeWhiteSpace(indentUnit);return map(string.replace(/\\t/g,tab).replace(/\\u00a0/g," ").replace(/\\r\\n?/g,"\\n").split("\\n"),fixSpaces);}','function simplifyDOM(root,atEnd){var doc=root.ownerDocument;var result=[];var leaving=true;function simplifyNode(node,top){if(node.nodeType==3){var text=node.nodeValue=fixSpaces(node.nodeValue.replace(/[\\r\\u200b]/g,"").replace(/\\n/g," "));if(text.length)leaving=false;result.push(node);}','else if(node.nodeName=="BR"&&node.childNodes.length==0){leaving=true;result.push(node);}','else{forEach(node.childNodes,simplifyNode);if(!leaving&&newlineElements.hasOwnProperty(node.nodeName)){leaving=true;if(!atEnd||!top)','result.push(doc.createElement("BR"));}}}','simplifyNode(root,true);return result;}','function traverseDOM(start){function yield(value,c){cc=c;return value;}','function push(fun,arg,c){return function(){return fun(arg,c);};}','function stop(){cc=stop;throw StopIteration;};var cc=push(scanNode,start,stop);var owner=start.ownerDocument;var nodeQueue=[];function pointAt(node){var parent=node.parentNode;var next=node.nextSibling;return function(newnode){parent.insertBefore(newnode,next);};}','var point=null;function insertPart(part){var text="\\n";if(part.nodeType==3){select.snapshotChanged();part=makePartSpan(part,owner);text=part.currentText;}','part.dirty=true;nodeQueue.push(part);point(part);return text;}','function writeNode(node,c,end){var toYield=[];forEach(simplifyDOM(node,end),function(part){toYield.push(insertPart(part));});return yield(toYield.join(""),c);}','function partNode(node){if(node.isPart&&node.childNodes.length==1&&node.firstChild.nodeType==3){node.currentText=node.firstChild.nodeValue;return!/[\\n\\t\\r]/.test(node.currentText);}','return false;}','function scanNode(node,c){if(node.nextSibling)','c=push(scanNode,node.nextSibling,c);if(partNode(node)){nodeQueue.push(node);return yield(node.currentText,c);}','else if(node.nodeName=="BR"){nodeQueue.push(node);return yield("\\n",c);}','else{var end=!node.nextSibling;point=pointAt(node);removeElement(node);return writeNode(node,c,end);}}','return{next:function(){return cc();},nodes:nodeQueue};}','function nodeSize(node){if(node.nodeName=="BR")','return 1;else','return node.currentText.length;}','function startOfLine(node){while(node&&node.nodeName!="BR")node=node.previousSibling;return node;}','function endOfLine(node,container){if(!node)node=container.firstChild;else if(node.nodeName=="BR")node=node.nextSibling;while(node&&node.nodeName!="BR")node=node.nextSibling;return node;}','function time(){return new Date().getTime();}','function SearchCursor(editor,string,fromCursor){this.editor=editor;this.history=editor.history;this.history.commit();this.atOccurrence=false;this.fallbackSize=15;var cursor;if(fromCursor&&(cursor=select.cursorPos(this.editor.container))){this.line=cursor.node;this.offset=cursor.offset;}','else{this.line=null;this.offset=0;}','this.valid=!!string;var target=string.split("\\n"),self=this;this.matches=(target.length==1)?function(){var match=cleanText(self.history.textAfter(self.line).slice(self.offset)).indexOf(string);if(match>-1)','return{from:{node:self.line,offset:self.offset+match},to:{node:self.line,offset:self.offset+match+string.length}};}:function(){var firstLine=cleanText(self.history.textAfter(self.line).slice(self.offset));var match=firstLine.lastIndexOf(target[0]);if(match==-1||match!=firstLine.length-target[0].length)','return false;var startOffset=self.offset+match;var line=self.history.nodeAfter(self.line);for(var i=1;i<target.length-1;i++){if(cleanText(self.history.textAfter(line))!=target[i])','return false;line=self.history.nodeAfter(line);}','if(cleanText(self.history.textAfter(line)).indexOf(target[target.length-1])!=0)','return false;return{from:{node:self.line,offset:startOffset},to:{node:line,offset:target[target.length-1].length}};};}','SearchCursor.prototype={findNext:function(){if(!this.valid)return false;this.atOccurrence=false;var self=this;if(this.line&&!this.line.parentNode){this.line=null;this.offset=0;}','function saveAfter(pos){if(self.history.textAfter(pos.node).length>pos.offset){self.line=pos.node;self.offset=pos.offset+1;}','else{self.line=self.history.nodeAfter(pos.node);self.offset=0;}}','while(true){var match=this.matches();if(match){this.atOccurrence=match;saveAfter(match.from);return true;}','this.line=this.history.nodeAfter(this.line);this.offset=0;if(!this.line){this.valid=false;return false;}}},select:function(){if(this.atOccurrence){select.setCursorPos(this.editor.container,this.atOccurrence.from,this.atOccurrence.to);select.scrollToCursor(this.editor.container);}},replace:function(string){if(this.atOccurrence){var end=this.editor.replaceRange(this.atOccurrence.from,this.atOccurrence.to,string);this.line=end.node;this.offset=end.offset;this.atOccurrence=false;}}};function Editor(options){this.options=options;window.indentUnit=options.indentUnit;this.parent=parent;this.doc=document;var container=this.container=this.doc.body;this.win=window;this.history=new History(container,options.undoDepth,options.undoDelay,this,options.onChange);var self=this;if(!Editor.Parser)','throw"No parser loaded.";if(options.parserConfig&&Editor.Parser.configure)','Editor.Parser.configure(options.parserConfig);if(!options.readOnly)','select.setCursorPos(container,{node:null,offset:0});this.dirty=[];if(options.content)','this.importCode(options.content);else','container.appendChild(this.doc.createElement("BR"));if(!options.readOnly){if(options.continuousScanning!==false){this.scanner=this.documentScanner(options.passTime);this.delayScanning();}','function setEditable(){if(document.body.contentEditable!=undefined&&internetExplorer)','document.body.contentEditable="true";else','document.designMode="on";document.documentElement.style.borderWidth="0";if(!options.textWrapping)','container.style.whiteSpace="nowrap";}','try{setEditable();}','catch(e){var focusEvent=addEventHandler(document,"focus",function(){focusEvent();setEditable();},true);}','addEventHandler(document,"keydown",method(this,"keyDown"));addEventHandler(document,"keypress",method(this,"keyPress"));addEventHandler(document,"keyup",method(this,"keyUp"));function cursorActivity(){self.cursorActivity(false);}','addEventHandler(document.body,"mouseup",cursorActivity);addEventHandler(document.body,"cut",cursorActivity);addEventHandler(document.body,"paste",function(event){cursorActivity();var text=null;try{var clipboardData=event.clipboardData||window.clipboardData;if(clipboardData)text=clipboardData.getData(\'Text\');}','catch(e){}','if(text!==null){self.replaceSelection(text);event.stop();}});addEventHandler(document.body,"beforepaste",method(this,"reroutePasteEvent"));if(this.options.autoMatchParens)','addEventHandler(document.body,"click",method(this,"scheduleParenBlink"));}','else if(!options.textWrapping){container.style.whiteSpace="nowrap";}}','function isSafeKey(code){return(code>=16&&code<=18)||(code>=33&&code<=40);}','Editor.prototype={importCode:function(code){this.history.push(null,null,asEditorLines(code),true);this.history.reset();},getCode:function(){if(!this.container.firstChild)','return"";var accum=[];select.markSelection(this.win);forEach(traverseDOM(this.container.firstChild),method(accum,"push"));webkitLastLineHack(this.container);select.selectMarked();return cleanText(accum.join(""));},checkLine:function(node){if(node===false||!(node==null||node.parentNode==this.container))','throw parent.CodeMirror.InvalidLineHandle;},cursorPosition:function(start){if(start==null)start=true;var pos=select.cursorPos(this.container,start);if(pos)return{line:pos.node,character:pos.offset};else return{line:null,character:0};},firstLine:function(){return null;},lastLine:function(){if(this.container.lastChild)return startOfLine(this.container.lastChild);else return null;},nextLine:function(line){this.checkLine(line);var end=endOfLine(line,this.container);return end||false;},prevLine:function(line){this.checkLine(line);if(line==null)return false;return startOfLine(line.previousSibling);},selectLines:function(startLine,startOffset,endLine,endOffset){this.checkLine(startLine);var start={node:startLine,offset:startOffset},end=null;if(endOffset!==undefined){this.checkLine(endLine);end={node:endLine,offset:endOffset};}','select.setCursorPos(this.container,start,end);select.scrollToCursor(this.container);},lineContent:function(line){this.checkLine(line);var accum=[];for(line=line?line.nextSibling:this.container.firstChild;line&&line.nodeName!="BR";line=line.nextSibling)','accum.push(nodeText(line));return cleanText(accum.join(""));},setLineContent:function(line,content){this.history.commit();this.replaceRange({node:line,offset:0},{node:line,offset:this.history.textAfter(line).length},content);this.addDirtyNode(line);this.scheduleHighlight();},insertIntoLine:function(line,position,content){var before=null;if(position=="end"){before=endOfLine(line,this.container);}','else{for(var cur=line?line.nextSibling:this.container.firstChild;cur;cur=cur.nextSibling){if(position==0){before=cur;break;}','var text=nodeText(cur);if(text.length>position){before=cur.nextSibling;content=text.slice(0,position)+content+text.slice(position);removeElement(cur);break;}','position-=text.length;}}','var lines=asEditorLines(content),doc=this.container.ownerDocument;for(var i=0;i<lines.length;i++){if(i>0)this.container.insertBefore(doc.createElement("BR"),before);this.container.insertBefore(makePartSpan(lines[i],doc),before);}','this.addDirtyNode(line);this.scheduleHighlight();},selectedText:function(){var h=this.history;h.commit();var start=select.cursorPos(this.container,true),end=select.cursorPos(this.container,false);if(!start||!end)return"";if(start.node==end.node)','return h.textAfter(start.node).slice(start.offset,end.offset);var text=[h.textAfter(start.node).slice(start.offset)];for(var pos=h.nodeAfter(start.node);pos!=end.node;pos=h.nodeAfter(pos))','text.push(h.textAfter(pos));text.push(h.textAfter(end.node).slice(0,end.offset));return cleanText(text.join("\\n"));},replaceSelection:function(text){this.history.commit();var start=select.cursorPos(this.container,true),end=select.cursorPos(this.container,false);if(!start||!end)return;end=this.replaceRange(start,end,text);select.setCursorPos(this.container,end);webkitLastLineHack(this.container);},reroutePasteEvent:function(){if(this.capturingPaste||window.opera)return;this.capturingPaste=true;var te=parent.document.createElement("TEXTAREA");te.style.position="absolute";te.style.left="-500px";te.style.width="10px";te.style.top=nodeTop(frameElement)+"px";parent.document.body.appendChild(te);parent.focus();te.focus();var self=this;this.parent.setTimeout(function(){self.capturingPaste=false;self.win.focus();if(self.selectionSnapshot)','self.win.select.selectCoords(self.win,self.selectionSnapshot);var text=te.value;if(text)self.replaceSelection(text);removeElement(te);},10);},replaceRange:function(from,to,text){var lines=asEditorLines(text);lines[0]=this.history.textAfter(from.node).slice(0,from.offset)+lines[0];var lastLine=lines[lines.length-1];lines[lines.length-1]=lastLine+this.history.textAfter(to.node).slice(to.offset);var end=this.history.nodeAfter(to.node);this.history.push(from.node,end,lines);return{node:this.history.nodeBefore(end),offset:lastLine.length};},getSearchCursor:function(string,fromCursor){return new SearchCursor(this,string,fromCursor);},reindent:function(){if(this.container.firstChild)','this.indentRegion(null,this.container.lastChild);},reindentSelection:function(direction){if(!select.somethingSelected(this.win)){this.indentAtCursor(direction);}','else{var start=select.selectionTopNode(this.container,true),end=select.selectionTopNode(this.container,false);if(start===false||end===false)return;this.indentRegion(start,end,direction);}},grabKeys:function(eventHandler,filter){this.frozen=eventHandler;this.keyFilter=filter;},ungrabKeys:function(){this.frozen="leave";this.keyFilter=null;},setParser:function(name){Editor.Parser=window[name];if(this.container.firstChild){forEach(this.container.childNodes,function(n){if(n.nodeType!=3)n.dirty=true;});this.addDirtyNode(this.firstChild);this.scheduleHighlight();}},keyDown:function(event){if(this.frozen=="leave")this.frozen=null;if(this.frozen&&(!this.keyFilter||this.keyFilter(event.keyCode))){event.stop();this.frozen(event);return;}','var code=event.keyCode;this.delayScanning();if(this.options.autoMatchParens)','this.scheduleParenBlink();if(code==13){if(event.ctrlKey&&!event.altKey){this.reparseBuffer();}','else{select.insertNewlineAtCursor(this.win);this.indentAtCursor();select.scrollToCursor(this.container);}','event.stop();}','else if(code==9&&this.options.tabMode!="default"&&!event.ctrlKey){this.handleTab(!event.ctrlKey&&!event.shiftKey);event.stop();}','else if(code==32&&event.shiftKey&&this.options.tabMode=="default"){this.handleTab(true);event.stop();}','else if(code==36&&!event.shiftKey&&!event.ctrlKey){if(this.home())','event.stop();}','else if((code==219||code==221)&&event.ctrlKey&&!event.altKey){this.blinkParens(event.shiftKey);event.stop();}','else if(event.metaKey&&!event.shiftKey&&(code==37||code==39)){var cursor=select.selectionTopNode(this.container);if(cursor===false||!this.container.firstChild)return;if(code==37)select.focusAfterNode(startOfLine(cursor),this.container);else{var end=endOfLine(cursor,this.container);select.focusAfterNode(end?end.previousSibling:this.container.lastChild,this.container);}','event.stop();}','else if((event.ctrlKey||event.metaKey)&&!event.altKey){if((event.shiftKey&&code==90)||code==89){return;select.scrollToNode(this.history.redo());event.stop();}','else if(code==90||(safari&&code==8)){return;select.scrollToNode(this.history.undo());event.stop();}','else if(code==83&&this.options.saveFunction){return;this.options.saveFunction();event.stop();}}},keyPress:function(event){var electric=Editor.Parser.electricChars,self=this;if((this.frozen&&(!this.keyFilter||this.keyFilter(event.keyCode)))||event.code==13||(event.code==9&&this.options.tabMode!="default")||(event.keyCode==32&&event.shiftKey&&this.options.tabMode=="default"))','event.stop();else if(electric&&electric.indexOf(event.character)!=-1)','this.parent.setTimeout(function(){self.indentAtCursor(null);},0);else if((event.character=="v"||event.character=="V")&&(event.ctrlKey||event.metaKey)&&!event.altKey)','this.reroutePasteEvent();},keyUp:function(event){this.cursorActivity(isSafeKey(event.keyCode));},indentLineAfter:function(start,direction){var whiteSpace=start?start.nextSibling:this.container.firstChild;if(whiteSpace&&!hasClass(whiteSpace,"whitespace"))','whiteSpace=null;var firstText=whiteSpace?whiteSpace.nextSibling:(start?start.nextSibling:this.container.firstChild);var nextChars=(start&&firstText&&firstText.currentText)?firstText.currentText:"";var newIndent=0,curIndent=whiteSpace?whiteSpace.currentText.length:0;if(direction!=null&&this.options.tabMode=="shift")','newIndent=direction?curIndent+indentUnit:Math.max(0,curIndent-indentUnit)','else if(start)','newIndent=start.indentation(nextChars,curIndent,direction);else if(Editor.Parser.firstIndentation)','newIndent=Editor.Parser.firstIndentation(nextChars,curIndent,direction);var indentDiff=newIndent-curIndent;if(indentDiff<0){if(newIndent==0){if(firstText)select.snapshotMove(whiteSpace.firstChild,firstText.firstChild,0);removeElement(whiteSpace);whiteSpace=null;}','else{select.snapshotMove(whiteSpace.firstChild,whiteSpace.firstChild,indentDiff,true);whiteSpace.currentText=makeWhiteSpace(newIndent);whiteSpace.firstChild.nodeValue=whiteSpace.currentText;}}','else if(indentDiff>0){if(whiteSpace){whiteSpace.currentText=makeWhiteSpace(newIndent);whiteSpace.firstChild.nodeValue=whiteSpace.currentText;}','else{whiteSpace=makePartSpan(makeWhiteSpace(newIndent),this.doc);whiteSpace.className="whitespace";if(start)insertAfter(whiteSpace,start);else this.container.insertBefore(whiteSpace,this.container.firstChild);}','if(firstText)select.snapshotMove(firstText.firstChild,whiteSpace.firstChild,curIndent,false,true);}','if(indentDiff!=0)this.addDirtyNode(start);return whiteSpace;},highlightAtCursor:function(){var pos=select.selectionTopNode(this.container,true);var to=select.selectionTopNode(this.container,false);if(pos===false||to===false)return;select.markSelection(this.win);if(this.highlight(pos,endOfLine(to,this.container),true,20)===false)','return false;select.selectMarked();return true;},handleTab:function(direction){if(this.options.tabMode=="spaces")','select.insertTabAtCursor(this.win);else','this.reindentSelection(direction);},home:function(){var cur=select.selectionTopNode(this.container,true),start=cur;if(cur===false||!(!cur||cur.isPart||cur.nodeName=="BR")||!this.container.firstChild)','return false;while(cur&&cur.nodeName!="BR")cur=cur.previousSibling;var next=cur?cur.nextSibling:this.container.firstChild;if(next&&next!=start&&next.isPart&&hasClass(next,"whitespace"))','select.focusAfterNode(next,this.container);else','select.focusAfterNode(cur,this.container);select.scrollToCursor(this.container);return true;},scheduleParenBlink:function(){if(this.parenEvent)this.parent.clearTimeout(this.parenEvent);var self=this;this.parenEvent=this.parent.setTimeout(function(){self.blinkParens();},300);},blinkParens:function(jump){if(!window.select)return;if(this.parenEvent)this.parent.clearTimeout(this.parenEvent);this.parenEvent=null;function paren(node){if(node.currentText){var match=node.currentText.match(/^[\\s\\u00a0]*([\\(\\)\\[\\]{}])[\\s\\u00a0]*$/);return match&&match[1];}}','function forward(ch){return/[\\(\\[\\{]/.test(ch);}','var ch,self=this,cursor=select.selectionTopNode(this.container,true);if(!cursor||!this.highlightAtCursor())return;cursor=select.selectionTopNode(this.container,true);if(!(cursor&&((ch=paren(cursor))||(cursor=cursor.nextSibling)&&(ch=paren(cursor)))))','return;var className=cursor.className,dir=forward(ch),match=matching[ch];function tryFindMatch(){var stack=[],ch,ok=true;;for(var runner=cursor;runner;runner=dir?runner.nextSibling:runner.previousSibling){if(runner.className==className&&runner.nodeName=="SPAN"&&(ch=paren(runner))){if(forward(ch)==dir)','stack.push(ch);else if(!stack.length)','ok=false;else if(stack.pop()!=matching[ch])','ok=false;if(!stack.length)break;}','else if(runner.dirty||runner.nodeName!="SPAN"&&runner.nodeName!="BR"){return{node:runner,status:"dirty"};}}','return{node:runner,status:runner&&ok};}','function blink(node,ok){node.style.fontWeight="bold";node.style.color=ok?"#8F8":"#F88";self.parent.setTimeout(function(){node.style.fontWeight="";node.style.color="";},500);}','while(true){var found=tryFindMatch();if(found.status=="dirty"){this.highlight(found.node,endOfLine(found.node));found.node.dirty=false;continue;}','else{blink(cursor,found.status);if(found.node){blink(found.node,found.status);if(jump)select.focusAfterNode(found.node.previousSibling,this.container);}','break;}}},indentAtCursor:function(direction){if(!this.container.firstChild)return;if(!this.highlightAtCursor())return;var cursor=select.selectionTopNode(this.container,false);if(cursor===false)','return;var lineStart=startOfLine(cursor);var whiteSpace=this.indentLineAfter(lineStart,direction);if(cursor==lineStart&&whiteSpace)','cursor=whiteSpace;if(cursor==whiteSpace)','select.focusAfterNode(cursor,this.container);},indentRegion:function(start,end,direction){var current=(start=startOfLine(start)),before=start&&startOfLine(start.previousSibling);if(end.nodeName!="BR")end=endOfLine(end,this.container);do{var next=endOfLine(current,this.container);if(current)this.highlight(before,next,true);this.indentLineAfter(current,direction);before=current;current=next;}while(current!=end);select.setCursorPos(this.container,{node:start,offset:0},{node:end,offset:0});},cursorActivity:function(safe){if(internetExplorer){this.container.createTextRange().execCommand("unlink");this.selectionSnapshot=select.selectionCoords(this.win);}','var activity=this.options.cursorActivity;if(!safe||activity){var cursor=select.selectionTopNode(this.container,false);if(cursor===false||!this.container.firstChild)return;cursor=cursor||this.container.firstChild;if(activity)activity(cursor);if(!safe){this.scheduleHighlight();this.addDirtyNode(cursor);}}},reparseBuffer:function(){forEach(this.container.childNodes,function(node){node.dirty=true;});if(this.container.firstChild)','this.addDirtyNode(this.container.firstChild);},addDirtyNode:function(node){node=node||this.container.firstChild;if(!node)return;for(var i=0;i<this.dirty.length;i++)','if(this.dirty[i]==node)return;if(node.nodeType!=3)','node.dirty=true;this.dirty.push(node);},scheduleHighlight:function(){var self=this;this.parent.clearTimeout(this.highlightTimeout);this.highlightTimeout=this.parent.setTimeout(function(){self.highlightDirty();},this.options.passDelay);},getDirtyNode:function(){while(this.dirty.length>0){var found=this.dirty.pop();try{while(found&&found.parentNode!=this.container)','found=found.parentNode','if(found&&(found.dirty||found.nodeType==3))','return found;}catch(e){}}','return null;},highlightDirty:function(force){if(!window.select)return;if(!this.options.readOnly)select.markSelection(this.win);var start,endTime=force?null:time()+this.options.passTime;while((time()<endTime||force)&&(start=this.getDirtyNode())){var result=this.highlight(start,endTime);if(result&&result.node&&result.dirty)','this.addDirtyNode(result.node);}','if(!this.options.readOnly)select.selectMarked();if(start)this.scheduleHighlight();return this.dirty.length==0;},documentScanner:function(passTime){var self=this,pos=null;return function(){if(!window.select)return;if(pos&&pos.parentNode!=self.container)','pos=null;select.markSelection(self.win);var result=self.highlight(pos,time()+passTime,true);select.selectMarked();var newPos=result?(result.node&&result.node.nextSibling):null;pos=(pos==newPos)?null:newPos;self.delayScanning();};},delayScanning:function(){if(this.scanner){this.parent.clearTimeout(this.documentScan);this.documentScan=this.parent.setTimeout(this.scanner,this.options.continuousScanning);}},highlight:function(from,target,cleanLines,maxBacktrack){var container=this.container,self=this,active=this.options.activeTokens;var endTime=(typeof target=="number"?target:null);if(!container.firstChild)','return;while(from&&(!from.parserFromHere||from.dirty)){if(maxBacktrack!=null&&from.nodeName=="BR"&&(--maxBacktrack)<0)','return false;from=from.previousSibling;}','if(from&&!from.nextSibling)','return;function correctPart(token,part){return!part.reduced&&part.currentText==token.value&&part.className==token.style;}','function shortenPart(part,minus){part.currentText=part.currentText.substring(minus);part.reduced=true;}','function tokenPart(token){var part=makePartSpan(token.value,self.doc);part.className=token.style;return part;}','function maybeTouch(node){if(node){var old=node.oldNextSibling;if(lineDirty||old===undefined||node.nextSibling!=old)','self.history.touch(node);node.oldNextSibling=node.nextSibling;}','else{var old=self.container.oldFirstChild;if(lineDirty||old===undefined||self.container.firstChild!=old)','self.history.touch(null);self.container.oldFirstChild=self.container.firstChild;}}','var traversal=traverseDOM(from?from.nextSibling:container.firstChild),stream=stringStream(traversal),parsed=from?from.parserFromHere(stream):Editor.Parser.make(stream);var parts={current:null,get:function(){if(!this.current)','this.current=traversal.nodes.shift();return this.current;},next:function(){this.current=null;},remove:function(){container.removeChild(this.get());this.current=null;},getNonEmpty:function(){var part=this.get();while(part&&part.nodeName=="SPAN"&&part.currentText==""){var old=part;this.remove();part=this.get();select.snapshotMove(old.firstChild,part&&(part.firstChild||part),0);}','return part;}};var lineDirty=false,prevLineDirty=true,lineNodes=0;forEach(parsed,function(token){var part=parts.getNonEmpty();if(token.value=="\\n"){if(part.nodeName!="BR")','throw"Parser out of sync. Expected BR.";if(part.dirty||!part.indentation)lineDirty=true;maybeTouch(from);from=part;part.parserFromHere=parsed.copy();part.indentation=token.indentation;part.dirty=false;if(endTime==null&&part==target)throw StopIteration;if((endTime!=null&&time()>=endTime)||(!lineDirty&&!prevLineDirty&&lineNodes>1&&!cleanLines))','throw StopIteration;prevLineDirty=lineDirty;lineDirty=false;lineNodes=0;parts.next();}','else{if(part.nodeName!="SPAN")','throw"Parser out of sync. Expected SPAN.";if(part.dirty)','lineDirty=true;lineNodes++;if(correctPart(token,part)){part.dirty=false;parts.next();}','else{lineDirty=true;var newPart=tokenPart(token);container.insertBefore(newPart,part);if(active)active(newPart,token,self);var tokensize=token.value.length;var offset=0;while(tokensize>0){part=parts.get();var partsize=part.currentText.length;select.snapshotReplaceNode(part.firstChild,newPart.firstChild,tokensize,offset);if(partsize>tokensize){shortenPart(part,tokensize);tokensize=0;}','else{tokensize-=partsize;offset+=partsize;parts.remove();}}}}});maybeTouch(from);webkitLastLineHack(this.container);return{node:parts.getNonEmpty(),dirty:lineDirty};}};return Editor;})();addEventHandler(window,"load",function(){var CodeMirror=window.frameElement.CodeMirror;CodeMirror.editor=new Editor(CodeMirror.options);this.parent.setTimeout(method(CodeMirror,"init"),0);});;function tokenizer(source,state){function isWhiteSpace(ch){return ch!="\\n"&&/^[\\s\\u00a0]*$/.test(ch);}','var tokenizer={state:state,take:function(type){if(typeof(type)=="string")','type={style:type,type:type};type.content=(type.content||"")+source.get();if(!/\\n$/.test(type.content))','source.nextWhile(isWhiteSpace);type.value=type.content+source.get();return type;},next:function(){if(!source.more())throw StopIteration;var type;if(source.equals("\\n")){source.next();return this.take("whitespace");}','if(source.applies(isWhiteSpace))','type="whitespace";else','while(!type)','type=this.state(source,function(s){tokenizer.state=s;});return this.take(type);}};return tokenizer;};var XMLParser=Editor.Parser=(function(){var Kludges={autoSelfClosers:{"br":true,"img":true,"hr":true,"link":true,"input":true,"meta":true,"col":true,"frame":true,"base":true,"area":true},doNotIndent:{"pre":true,"!cdata":true}};var NoKludges={autoSelfClosers:{},doNotIndent:{"!cdata":true}};var UseKludges=Kludges;var alignCDATA=false;var tokenizeXML=(function(){function inText(source,setState){var ch=source.next();if(ch=="<"){if(source.equals("!")){source.next();if(source.equals("[")){if(source.lookAhead("[CDATA[",true)){setState(inBlock("xml-cdata","]]>"));return null;}','else{return"xml-text";}}','else if(source.lookAhead("--",true)){setState(inBlock("xml-comment","-->"));return null;}','else{return"xml-text";}}','else if(source.equals("?")){source.next();source.nextWhileMatches(/[\\w\\._\\-]/);setState(inBlock("xml-processing","?>"));return"xml-processing";}','else{if(source.equals("/"))source.next();setState(inTag);return"xml-punctuation";}}','else if(ch=="&"){while(!source.endOfLine()){if(source.next()==";")','break;}','return"xml-entity";}','else{source.nextWhileMatches(/[^&<\\n]/);return"xml-text";}}','function inTag(source,setState){var ch=source.next();if(ch==">"){setState(inText);return"xml-punctuation";}','else if(/[?\\/]/.test(ch)&&source.equals(">")){source.next();setState(inText);return"xml-punctuation";}','else if(ch=="="){return"xml-punctuation";}','else if(/[\\\'\\"]/.test(ch)){setState(inAttribute(ch));return null;}','else{source.nextWhileMatches(/[^\\s\\u00a0=<>\\"\\\'\\/?]/);return"xml-name";}}','function inAttribute(quote){return function(source,setState){while(!source.endOfLine()){if(source.next()==quote){setState(inTag);break;}}','return"xml-attribute";};}','function inBlock(style,terminator){return function(source,setState){while(!source.endOfLine()){if(source.lookAhead(terminator,true)){setState(inText);break;}','source.next();}','return style;};}','return function(source,startState){return tokenizer(source,startState||inText);};})();function parseXML(source){var tokens=tokenizeXML(source);var cc=[base];var tokenNr=0,indented=0;var currentTag=null,context=null;var consume,marked;function push(fs){for(var i=fs.length-1;i>=0;i--)','cc.push(fs[i]);}','function cont(){push(arguments);consume=true;}','function pass(){push(arguments);consume=false;}','function mark(style){marked=style;}','function expect(text){return function(style,content){if(content==text)cont();else mark("xml-error")||cont(arguments.callee);};}','function pushContext(tagname,startOfLine){var noIndent=UseKludges.doNotIndent.hasOwnProperty(tagname)||(context&&context.noIndent);context={prev:context,name:tagname,indent:indented,startOfLine:startOfLine,noIndent:noIndent};}','function popContext(){context=context.prev;}','function computeIndentation(baseContext){return function(nextChars,current){var context=baseContext;if(context&&context.noIndent)','return current;if(alignCDATA&&/<!\\[CDATA\\[/.test(nextChars))','return 0;if(context&&/^<\\//.test(nextChars))','context=context.prev;while(context&&!context.startOfLine)','context=context.prev;if(context)','return context.indent+indentUnit;else','return 0;};}','function base(){return pass(element,base);}','var harmlessTokens={"xml-text":true,"xml-entity":true,"xml-comment":true,"xml-processing":true};function element(style,content){if(content=="<")cont(tagname,attributes,endtag(tokenNr==1));else if(content=="</")cont(closetagname,expect(">"));else if(style=="xml-cdata"){if(!context||context.name!="!cdata")pushContext("!cdata");if(/\\]\\]>$/.test(content))popContext();cont();}','else if(harmlessTokens.hasOwnProperty(style))cont();else mark("xml-error")||cont();}','var legal_namespace_tags={acre:{doc:true,block:true,script:true}};function style_for_tagname(tagname){var r=tagname.split(\':\');if(!r){return"xml-tagname";}','var ns=r[0];var tag=r[1];var legal_tags=legal_namespace_tags[ns];if(!legal_tags){return"xml-tagname";}','if(legal_tags[tag]){return"xml-tagname-"+ns;}','return"xml-error";}','function tagname(style,content){if(style=="xml-name"){currentTag=content.toLowerCase();var tagstyle=style_for_tagname(currentTag);mark(tagstyle);cont();}','else{currentTag=null;pass();}}','function closetagname(style,content){if(style=="xml-name"&&context&&content.toLowerCase()==context.name){var tagstyle=style_for_tagname(context.name);mark(tagstyle);popContext();}','else{mark("xml-error");}','cont();}','function endtag(startOfLine){return function(style,content){if(content=="/>"||(content==">"&&UseKludges.autoSelfClosers.hasOwnProperty(currentTag)))cont();else if(content==">")pushContext(currentTag,startOfLine)||cont();else mark("xml-error")||cont(arguments.callee);};}','function attributes(style){if(style=="xml-name")mark("xml-attname")||cont(attribute,attributes);else pass();}','function attribute(style,content){if(content=="=")cont(value);else if(content==">"||content=="/>")pass(endtag);else pass();}','function value(style){if(style=="xml-attribute")cont(value);else pass();}','return{indentation:function(){return indented;},next:function(){var token=tokens.next();if(token.style=="whitespace"&&tokenNr==0)','indented=token.value.length;else','tokenNr++;if(token.content=="\\n"){indented=tokenNr=0;token.indentation=computeIndentation(context);}','if(token.style=="whitespace"||token.type=="xml-comment")','return token;while(true){consume=marked=false;cc.pop()(token.style,token.content);if(consume){if(marked)','token.style=marked;return token;}}},copy:function(){var _cc=cc.concat([]),_tokenState=tokens.state,_context=context;var parser=this;return function(input){cc=_cc.concat([]);tokenNr=indented=0;context=_context;tokens=tokenizeXML(input,_tokenState);return parser;};}};}','return{make:parseXML,electricChars:"/",configure:function(config){if(config.useHTMLKludges!=null)','UseKludges=config.useHTMLKludges?Kludges:NoKludges;if(config.alignCDATA)','alignCDATA=config.alignCDATA;}};})();;var CSSParser=Editor.Parser=(function(){var tokenizeCSS=(function(){function normal(source,setState){var ch=source.next();if(ch=="@"){source.nextWhileMatches(/\\w/);return"css-at";}','else if(ch=="/"&&source.equals("*")){setState(inCComment);return null;}','else if(ch=="<"&&source.equals("!")){setState(inSGMLComment);return null;}','else if(ch=="="){return"css-compare";}','else if(source.equals("=")&&(ch=="~"||ch=="|")){source.next();return"css-compare";}','else if(ch=="\\""||ch=="\'"){setState(inString(ch));return null;}','else if(ch=="#"){source.nextWhileMatches(/\\w/);return"css-hash";}','else if(ch=="!"){source.nextWhileMatches(/[ \\t]/);source.nextWhileMatches(/\\w/);return"css-important";}','else if(/\\d/.test(ch)){source.nextWhileMatches(/[\\w.%]/);return"css-unit";}','else if(/[,.+>*\\/]/.test(ch)){return"css-select-op";}','else if(/[;{}:\\[\\]]/.test(ch)){return"css-punctuation";}','else{source.nextWhileMatches(/[\\w\\\\\\-_]/);return"css-identifier";}}','function inCComment(source,setState){var maybeEnd=false;while(!source.endOfLine()){var ch=source.next();if(maybeEnd&&ch=="/"){setState(normal);break;}','maybeEnd=(ch=="*");}','return"css-comment";}','function inSGMLComment(source,setState){var dashes=0;while(!source.endOfLine()){var ch=source.next();if(dashes>=2&&ch==">"){setState(normal);break;}','dashes=(ch=="-")?dashes+1:0;}','return"css-comment";}','function inString(quote){return function(source,setState){var escaped=false;while(!source.endOfLine()){var ch=source.next();if(ch==quote&&!escaped)','break;escaped=!escaped&&ch=="\\\\";}','if(!escaped)','setState(normal);return"css-string";};}','return function(source,startState){return tokenizer(source,startState||normal);};})();function indentCSS(inBraces,inRule,base){return function(nextChars){if(!inBraces||/^\\}/.test(nextChars))return base;else if(inRule)return base+indentUnit*2;else return base+indentUnit;};}','function parseCSS(source,basecolumn){basecolumn=basecolumn||0;var tokens=tokenizeCSS(source);var inBraces=false,inRule=false;var iter={next:function(){var token=tokens.next(),style=token.style,content=token.content;if(style=="css-identifier"&&inRule)','token.style="css-value";if(style=="css-hash")','token.style=inRule?"css-colorcode":"css-identifier";if(content=="\\n")','token.indentation=indentCSS(inBraces,inRule,basecolumn);if(content=="{")','inBraces=true;else if(content=="}")','inBraces=inRule=false;else if(inBraces&&content==";")','inRule=false;else if(inBraces&&style!="css-comment"&&style!="whitespace")','inRule=true;return token;},copy:function(){var _inBraces=inBraces,_inRule=inRule,_tokenState=tokens.state;return function(source){tokens=tokenizeCSS(source,_tokenState);inBraces=_inBraces;inRule=_inRule;return iter;};}};return iter;}','return{make:parseCSS,electricChars:"}"};})();;var tokenizeJavaScript=(function(){function nextUntilUnescaped(source,end){var escaped=false;var next;while(!source.endOfLine()){var next=source.next();if(next==end&&!escaped)','return false;escaped=!escaped&&next=="\\\\";}','return escaped;}','var keywords=function(){function result(type,style){return{type:type,style:"js-"+style};}','var keywordA=result("keyword a","keyword");var keywordB=result("keyword b","keyword");var keywordC=result("keyword c","keyword");var operator=result("operator","keyword");var atom=result("atom","atom");return{"if":keywordA,"while":keywordA,"with":keywordA,"else":keywordB,"do":keywordB,"try":keywordB,"finally":keywordB,"return":keywordC,"break":keywordC,"continue":keywordC,"new":keywordC,"delete":keywordC,"throw":keywordC,"in":operator,"typeof":operator,"instanceof":operator,"var":result("var","keyword"),"function":result("function","keyword"),"catch":result("catch","keyword"),"for":result("for","keyword"),"switch":result("switch","keyword"),"case":result("case","keyword"),"default":result("default","keyword"),"true":atom,"false":atom,"null":atom,"undefined":atom,"NaN":atom,"Infinity":atom};}();var isOperatorChar=/[+\\-*&%\\/=<>!?|]/;var isHexDigit=/[0-9A-Fa-f]/;var isWordChar=/[\\w\\$_]/;function jsTokenState(inside,regexp){return function(source,setState){var newInside=inside;var type=jsToken(inside,regexp,source,function(c){newInside=c;});var newRegexp=type.type=="operator"||type.type=="keyword c"||type.type.match(/^[\\[{}\\(,;:]$/);if(newRegexp!=regexp||newInside!=inside)','setState(jsTokenState(newInside,newRegexp));return type;};}','function jsToken(inside,regexp,source,setInside){function readHexNumber(){source.next();source.nextWhileMatches(isHexDigit);return{type:"number",style:"js-atom"};}','function readNumber(){source.nextWhileMatches(/[0-9]/);if(source.equals(".")){source.next();source.nextWhileMatches(/[0-9]/);}','if(source.equals("e")||source.equals("E")){source.next();if(source.equals("-"))','source.next();source.nextWhileMatches(/[0-9]/);}','return{type:"number",style:"js-atom"};}','function readWord(){source.nextWhileMatches(isWordChar);var word=source.get();var known=keywords.hasOwnProperty(word)&&keywords.propertyIsEnumerable(word)&&keywords[word];return known?{type:known.type,style:known.style,content:word}:{type:"variable",style:"js-variable",content:word};}','function readRegexp(){nextUntilUnescaped(source,"/");source.nextWhileMatches(/[gi]/);return{type:"regexp",style:"js-string"};}','function readMultilineComment(start){var newInside="/*";var maybeEnd=(start=="*");while(true){if(source.endOfLine())','break;var next=source.next();if(next=="/"&&maybeEnd){newInside=null;break;}','maybeEnd=(next=="*");}','setInside(newInside);return{type:"comment",style:"js-comment"};}','function readOperator(){source.nextWhileMatches(isOperatorChar);return{type:"operator",style:"js-operator"};}','function readString(quote){var endBackSlash=nextUntilUnescaped(source,quote);setInside(endBackSlash?quote:null);return{type:"string",style:"js-string"};}','if(inside=="\\""||inside=="\'")','return readString(inside);var ch=source.next();if(inside=="/*")','return readMultilineComment(ch);else if(ch=="\\""||ch=="\'")','return readString(ch);else if(/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch))','return{type:ch,style:"js-punctuation"};else if(ch=="0"&&(source.equals("x")||source.equals("X")))','return readHexNumber();else if(/[0-9]/.test(ch))','return readNumber();else if(ch=="/"){if(source.equals("*"))','{source.next();return readMultilineComment(ch);}','else if(source.equals("/"))','{nextUntilUnescaped(source,null);return{type:"comment",style:"js-comment"};}','else if(regexp)','return readRegexp();else','return readOperator();}','else if(isOperatorChar.test(ch))','return readOperator();else','return readWord();}','return function(source,startState){return tokenizer(source,startState||jsTokenState(false,true));};})();;var JSParser=Editor.Parser=(function(){var atomicTypes={"atom":true,"number":true,"variable":true,"string":true,"regexp":true};var json=false;function JSLexical(indented,column,type,align,prev,info){this.indented=indented;this.column=column;this.type=type;if(align!=null)','this.align=align;this.prev=prev;this.info=info;}','function indentJS(lexical){return function(firstChars){var firstChar=firstChars&&firstChars.charAt(0),type=lexical.type;var closing=firstChar==type;if(type=="vardef")','return lexical.indented+4;else if(type=="form"&&firstChar=="{")','return lexical.indented;else if(type=="stat"||type=="form")','return lexical.indented+indentUnit;else if(lexical.info=="switch"&&!closing)','return lexical.indented+(/^(?:case|default)\\b/.test(firstChars)?indentUnit:2*indentUnit);else if(lexical.align)','return lexical.column-(closing?1:0);else','return lexical.indented+(closing?0:indentUnit);};}','function parseJS(input,basecolumn){var tokens=tokenizeJavaScript(input);var cc=[statements];var context=null;var lexical=new JSLexical((basecolumn||0)-indentUnit,0,"block",false);var column=0;var indented=0;var consume,marked;var parser={next:next,copy:copy};function next(){while(cc[cc.length-1].lex)','cc.pop()();var token=tokens.next();if(token.type=="whitespace"&&column==0)','indented=token.value.length;column+=token.value.length;if(token.content=="\\n"){indented=column=0;if(!("align"in lexical))','lexical.align=false;token.indentation=indentJS(lexical);}','if(token.type=="whitespace"||token.type=="comment")','return token;if(!("align"in lexical))','lexical.align=true;while(true){consume=marked=false;cc.pop()(token.type,token.content);if(consume){if(marked)','token.style=marked;else if(token.type=="variable"&&inScope(token.content))','token.style="js-localvariable";return token;}}}','function copy(){var _context=context,_lexical=lexical,_cc=cc.concat([]),_tokenState=tokens.state;return function copyParser(input){context=_context;lexical=_lexical;cc=_cc.concat([]);column=indented=0;tokens=tokenizeJavaScript(input,_tokenState);return parser;};}','function push(fs){for(var i=fs.length-1;i>=0;i--)','cc.push(fs[i]);}','function cont(){push(arguments);consume=true;}','function pass(){push(arguments);consume=false;}','function mark(style){marked=style;}','function pushcontext(){context={prev:context,vars:{"this":true,"arguments":true}};}','function popcontext(){context=context.prev;}','function register(varname){if(context){mark("js-variabledef");context.vars[varname]=true;}}','function inScope(varname){var cursor=context;while(cursor){if(cursor.vars[varname])','return true;cursor=cursor.prev;}','return false;}','function pushlex(type,info){var result=function(){lexical=new JSLexical(indented,column,type,null,lexical,info)};result.lex=true;return result;}','function poplex(){lexical=lexical.prev;}','poplex.lex=true;function expect(wanted){return function expecting(type){if(type==wanted)cont();else cont(arguments.callee);};}','function statements(type){return pass(statement,statements);}','function statement(type){if(type=="var")cont(pushlex("vardef"),vardef1,expect(";"),poplex);else if(type=="keyword a")cont(pushlex("form"),expression,statement,poplex);else if(type=="keyword b")cont(pushlex("form"),statement,poplex);else if(type=="{"&&json)cont(pushlex("}"),commasep(objprop,"}"),poplex);else if(type=="{")cont(pushlex("}"),block,poplex);else if(type=="function")cont(functiondef);else if(type=="for")cont(pushlex("form"),expect("("),pushlex(")"),forspec1,expect(")"),poplex,statement,poplex);else if(type=="variable")cont(pushlex("stat"),maybelabel);else if(type=="switch")cont(pushlex("form"),expression,pushlex("}","switch"),expect("{"),block,poplex,poplex);else if(type=="case")cont(expression,expect(":"));else if(type=="default")cont(expect(":"));else if(type=="catch")cont(pushlex("form"),pushcontext,expect("("),funarg,expect(")"),statement,poplex,popcontext);else pass(pushlex("stat"),expression,expect(";"),poplex);}','function expression(type){if(atomicTypes.hasOwnProperty(type))cont(maybeoperator);else if(type=="function")cont(functiondef);else if(type=="keyword c")cont(expression);else if(type=="(")cont(pushlex(")"),expression,expect(")"),poplex,maybeoperator);else if(type=="operator")cont(expression);else if(type=="[")cont(pushlex("]"),commasep(expression,"]"),poplex,maybeoperator);else if(type=="{")cont(pushlex("}"),commasep(objprop,"}"),poplex,maybeoperator);}','function maybeoperator(type){if(type=="operator")cont(expression);else if(type=="(")cont(pushlex(")"),expression,commasep(expression,")"),poplex,maybeoperator);else if(type==".")cont(property,maybeoperator);else if(type=="[")cont(pushlex("]"),expression,expect("]"),poplex,maybeoperator);}','function maybelabel(type){if(type==":")cont(poplex,statement);else pass(maybeoperator,expect(";"),poplex);}','function property(type){if(type=="variable"){mark("js-property");cont();}}','function objprop(type){if(type=="variable")mark("js-property");if(atomicTypes.hasOwnProperty(type))cont(expect(":"),expression);}','function commasep(what,end){function proceed(type){if(type==",")cont(what,proceed);else if(type==end)cont();else cont(expect(end));};return function commaSeparated(type){if(type==end)cont();else pass(what,proceed);};}','function block(type){if(type=="}")cont();else pass(statement,block);}','function vardef1(type,value){if(type=="variable"){register(value);cont(vardef2);}','else cont();}','function vardef2(type,value){if(value=="=")cont(expression,vardef2);else if(type==",")cont(vardef1);}','function forspec1(type){if(type=="var")cont(vardef1,forspec2);else if(type==";")pass(forspec2);else if(type=="variable")cont(formaybein);else pass(forspec2);}','function formaybein(type,value){if(value=="in")cont(expression);else cont(maybeoperator,forspec2);}','function forspec2(type,value){if(type==";")cont(forspec3);else if(value=="in")cont(expression);else cont(expression,expect(";"),forspec3);}','function forspec3(type){if(type==")")pass();else cont(expression);}','function functiondef(type,value){if(type=="variable"){register(value);cont(functiondef);}','else if(type=="(")cont(pushcontext,commasep(funarg,")"),statement,popcontext);}','function funarg(type,value){if(type=="variable"){register(value);cont();}}','return parser;}','return{make:parseJS,electricChars:"{}:",configure:function(obj){if(obj.json!=null)json=obj.json;}};})();;var HTMLMixedParser=Editor.Parser=(function(){if(!(CSSParser&&JSParser&&XMLParser))','throw new Error("CSS, JS, and XML parsers must be loaded for HTML mixed mode to work.");XMLParser.configure({useHTMLKludges:true});function parseMixed(stream){var htmlParser=XMLParser.make(stream),localParser=null,inTag=false;var iter={next:top,copy:copy};function top(){var token=htmlParser.next();if(token.content=="<")','inTag=true;else if((token.style.indexOf("xml-tagname")==0)&&inTag===true)','inTag=token.content.toLowerCase();else if(token.content==">"){if(inTag=="script")','iter.next=local(JSParser,"</script");else if(inTag=="acre:script")','iter.next=local(JSParser,"</acre:script");else if(inTag=="style")','iter.next=local(CSSParser,"</style");inTag=false;}','return token;}','function local(parser,tag){var baseIndent=htmlParser.indentation();localParser=parser.make(stream,baseIndent+indentUnit);return function(){if(stream.lookAhead(tag,false,false,true)){localParser=null;iter.next=top;return top();}','var token=localParser.next();var lt=token.value.lastIndexOf("<"),sz=Math.min(token.value.length-lt,tag.length);if(lt!=-1&&token.value.slice(lt,lt+sz).toLowerCase()==tag.slice(0,sz)&&stream.lookAhead(tag.slice(sz),false,false,true)){stream.push(token.value.slice(lt));token.value=token.value.slice(0,lt);}','if(token.indentation){var oldIndent=token.indentation;token.indentation=function(chars){if(chars=="</")','return baseIndent;else','return oldIndent(chars);}}','return token;};}','function copy(){var _html=htmlParser.copy(),_local=localParser&&localParser.copy(),_next=iter.next,_inTag=inTag;return function(_stream){stream=_stream;htmlParser=_html(_stream);localParser=_local&&_local(_stream);iter.next=_next;inTag=_inTag;return iter;};}','return iter;}','return{make:parseMixed,electricChars:"{}/:"};})();;var DummyParser=Editor.Parser=(function(){function tokenizeDummy(source){while(!source.endOfLine())source.next();return"text";}','function parseDummy(source){function indentTo(n){return function(){return n;}}','source=tokenizer(source,tokenizeDummy);var space=0;var iter={next:function(){var tok=source.next();if(tok.type=="whitespace"){if(tok.value=="\\n")tok.indentation=indentTo(space);else space=tok.value.length;}','return tok;},copy:function(){var _space=space;return function(_source){space=_space;source=tokenizer(_source,tokenizeDummy);return iter;};}};return iter;}','return{make:parseDummy};})();',''].join("\n");CodeMirrorConfig.INLINE_CSS=['.editbox{margin:.4em;padding:0;font-family:monospace;color:black;}','.editbox p{margin:0;}','span.xml-tagname{color:#90c;}','span.xml-attribute{color:#396;}','span.xml-punctuation{color:#777;}','span.xml-attname{color:#06c;}','span.xml-comment{color:#aaa;}','span.xml-cdata{color:#000;}','span.xml-processing{color:#999;}','span.xml-entity{color:#c33;}','span.xml-error{color:#F00;}','span.xml-text{color:black;}','span.xml-tagname-acre{color:#f60;}','.editbox{margin:.4em;padding:0;font-family:monospace;color:black;}','pre.code,.editbox{color:#666666;}','.editbox p{margin:0;}','span.js-punctuation{color:#777;}','span.js-operator{color:#000;}','span.js-keyword{color:#630;}','span.js-atom{color:#90c;}','span.js-variable{color:#06c;}','span.js-variabledef{color:#09f;}','span.js-localvariable{color:#06c;}','span.js-string{color:#396;}','span.js-property{color:#996;}','span.js-comment{color:#aaa;}','.editbox{margin:.4em;padding:0;font-family:monospace;font-size:13px;color:black;}','pre.code,.editbox{color:#777;}','.editbox p{margin:0;}','span.css-at{color:#663;}','span.css-unit{color:#c63;}','span.css-value{color:#996;}','span.css-identifier{color:#000;}','span.css-important{color:#f00;}','span.css-colorcode{color:#099;}','span.css-comment{color:#aaa;}','span.css-string{color:#c33;}',''].join("\n");;var assert={};assert.critical=function(cond,message){if(cond){return;}
if(typeof mjt!=="undefined"&&mjt.error){mjt.error('Internal Error: '+message);}else{if(typeof console!=="undefined"&&console.error){console.error('Internal Error: '+message);}}
if(document.getElementById('error-dialog')){return;}
var html='';html+='<div style="font-weight:bold;">Internal Error</div>';html+=message;html+='<div style="padding-top: 5px";><a href="http://www.metaweb.com/error-acre.html" target="_blank">Please report this error!</a></div>';assert.error_dialog(html);};assert.error_dialog=function(message_html){var close_html='<div id="error-dialog" style="float:right; color: #1170a3; margin: -10px -5px 0 0; cursor: pointer;" onclick="document.body.removeChild(this.parentNode);">x</div>';var div=document.createElement('div');div.style.cssText='position: absolute; top: 30px; left: 50%; width: 350px; margin: 0 0 0 -175px; padding: 15px; background-color: #fce2db; border: 1px solid #f3c5ac; color: #676767; font-size: 12px; z-index: 100;';div.innerHTML=close_html+message_html;document.body.appendChild(div);};var unicode={};unicode.escape_char=function(aChar){var hex=aChar.charCodeAt(0).toString(16).toUpperCase();if(hex.length===1){return"\\u000"+hex;}
if(hex.length===2){return"\\u00"+hex;}
if(hex.length===3){return"\\u0"+hex;}
if(hex.length===4){return"\\u"+hex;}
return null;};unicode.escape_str=function(str){return str.replace(/[^\u0020-\u007F]/g,unicode.escape_char);};(function(){var COOKIE_OPTS={expires:30};var _localStore_cache={};$.extend({localStore:function(key,val,use_cookie){var hostname=document.location.hostname;var prefix=document.location.protocol;if(typeof val!=="undefined"){var valstr=JSON.stringify(val);if(!use_cookie&&window.globalStorage){if(val===null){delete window.globalStorage[hostname][prefix+key];}else{window.globalStorage[hostname][prefix+key]=valstr;}}else if(!use_cookie&&window.localStorage){if(val===null){window.localStorage.removeItem(prefix+key);}else{window.localStorage.setItem(prefix+key,valstr);}}else if(use_cookie!==false){if(val===null){$.cookie(key,null,COOKIE_OPTS);}else{$.cookie(key,valstr,COOKIE_OPTS);}}else{if(val===null){delete _localStore_cache[key];}else{_localStore_cache[key]=valstr;}}
return val;}
else{if(!use_cookie&&window.globalStorage){if(window.globalStorage[hostname][prefix+key]){val=window.globalStorage[hostname][prefix+key].value;}}else if(!use_cookie&&window.localStorage){val=window.localStorage.getItem(prefix+key);}else if(use_cookie!==false){val=$.cookie(key);}else{val=_localStore_cache[key];}
if(val!=""&&val!==null&&val!==undefined){return JSON.parse(val,null);}}
return null;}});})();;if(typeof this.CONFIG==='undefined'){window.alert('Internal Error: CONFIG not defined. Is config.js defined for this hostname?');}
function FreebaseStore(){this._loaded=false;this._name=null;this._url=null;this._acre_server=null;this._handlers=[];this._user=null;return this;}
(function(){function _get_file_id(file){return file.get_app().get_path()+'/'+mjt.freebase.mqlkey_quote(file.get_name());}
function _idpath_to_host(idpath,server){var revpath=[server];var path=idpath.split('/');for(var i=1;i<path.length;i++){revpath.unshift(path[i]);}
return revpath.join('.');}
var APP_EDITOR_SERVICE_PATH="/appeditor/";if(window.location.host===CONFIG.ACRE_METAWEB_API_ADDR){APP_EDITOR_SERVICE_PATH="/tools/appeditor/services/";}
var AppEditorXhr=mjt.define_task(mjt.freebase.FreebaseXhrTask,[{name:'service'},{name:'args'}]);AppEditorXhr.prototype.request=function(){return this.xhr_form_post(APP_EDITOR_SERVICE_PATH+this.service,this.args);};var AppEditorJsonp=mjt.define_task(mjt.freebase.FreebaseJsonPTask,[{name:'service'},{name:'args'}]);AppEditorJsonp.prototype.request=function(){return this.service_request(APP_EDITOR_SERVICE_PATH+this.service,this.args);};AppEditorJsonp.prototype.response=function(o){return this.ready(o.result);};var AppEditorFileUpload=mjt.define_task(null,[{name:'service'},{name:'form'},{name:'args'}]);AppEditorFileUpload.prototype.dynamic_iframe=function(id){var iframe=document.createElement('iframe');if(typeof id==='string'){iframe.id=id;iframe.name=id;}
iframe.style.display='none';iframe.className='mjt_dynamic';return iframe;};AppEditorFileUpload.prototype.request=function(){this.domid=mjt.uniqueid('mjt_iframe');var iframe=this.dynamic_iframe(this.domid);$('body').append(iframe);var form=this.form;function inner_document(){var idoc=(iframe.contentWindow||iframe.contentDocument);if(idoc.document){return idoc.document;}
return idoc;}
var task=this;function _on_timeout(){task.error('timeout','Upload timed out - no response from server.');}
iframe.onload=function(){window.clearTimeout(timeout);var response_text=$(inner_document(iframe).body).text();var o=JSON.parse(response_text);if(o.code==='/api/status/ok'){task.result=o.result;task.ready(task.result);}else{task.error(o.code,o.messages[0].message);}
window.setTimeout(function(){$(iframe).remove();},1);};var timeout=window.setTimeout(_on_timeout,15000);form.attr({target:this.domid,action:mjt.form_url(APP_EDITOR_SERVICE_PATH+this.service,this.args),method:'POST',enctype:'multipart/form-data'}).submit();};FreebaseStore.prototype.Jsonp=AppEditorJsonp;FreebaseStore.prototype.Xhr=AppEditorXhr;FreebaseStore.prototype.FileUpload=AppEditorFileUpload;FreebaseStore.prototype.t_init=function(){var store=this;mjt.app=new mjt.App();mjt.freebase.service_url=window.location.protocol+'//'+window.location.host;mjt.freebase.xhr_ok=true;store._url='http://'+CONFIG.ACRE_METAWEB_API_ADDR;store._name=CONFIG.GRAPH_SHORTNAME;store._acre_server=CONFIG.ACRE_HOST_SUFFIX;var inittask=this.Jsonp('init_store').onready(function(r){store._user=null;store._user_apps=null;store._handlers=r.acre_handlers;if(r.user){store._user=new AcreUser(store,r.user);store._user_apps=r.user.apps;mjt.freebase.freebase_user={name:r.user.name,id:'/user/'+r.user.name};}});return inittask.enqueue();};var TestCookies=mjt.define_task(null,[{name:'store'}]);TestCookies.prototype.request=function(){this.url='http://'+this.store.get_app_host('/freebase/apps/appeditor')+'/check_thirdparty_cookies';var task=this;this.jsonp=mjt.JsonP();this.jsonp.set_timeout().jsonp_request_form(this.url,null,'callback').onready(function(r){if(r.result==='success'){task.ready();}else{task.error();}}).onerror('error',task);};FreebaseStore.prototype.TestCookies=TestCookies;FreebaseStore.prototype.get_user=function(){return this._user;};FreebaseStore.prototype.get_user_apps=function(){return this._user_apps;};FreebaseStore.prototype.set_user_apps=function(user_apps){this._user_apps=user_apps;};FreebaseStore.prototype.t_refresh_user_apps=function(){var store=this;store.Jsonp('list_user_apps').enqueue().onready(function(user_apps){store._user_apps=user_apps;})};FreebaseStore.prototype.get_url=function(){return this._url;};FreebaseStore.prototype.get_name=function(){var name=this._name?this._name:'???';if(name==='OTG'){name='';}
return name;};FreebaseStore.prototype.get_acre_handlers=function(){return this._handlers;};FreebaseStore.prototype.get_supported_mime_types=function(acre_handler){assert.critical(acre_handler,'Can\'t list supported mimetype');return this._handlers[acre_handler].supported_mime_types;};FreebaseStore.prototype.get_acre_home_url=function(path){return'http://'+this._acre_server.substr(4)+path||'';};FreebaseStore.prototype.get_app_host=function(app){var host;if(typeof app==='string'){host=_idpath_to_host(app,this._acre_server);}else{host=_idpath_to_host(app.get_path(),this._acre_server);if(app.is_version()){host=app.get_version_label()+'.'+host;}}
return host;};FreebaseStore.prototype.get_app_view_url=function(app){return this.get_url()+'/view'+app.get_path();};FreebaseStore.prototype.get_file_acre_url=function(file,preview){return'http://'+this.get_app_host(file.get_app())+'/'+file.get_name()+(preview?'?acre.console=1':'');};FreebaseStore.prototype.get_file_view_url=function(file){return this._url+'/view'+_get_file_id(file);};FreebaseStore.prototype.get_user_default_app_path=function(user){return'/user/'+user.get_name();};FreebaseStore.prototype.get_user_default_app_host=function(user){return _idpath_to_host('/user/'+user.get_name())+this._acre_server;};FreebaseStore.prototype.get_user_view_url=function(user){return this._url+'/view/user/'+user.get_name();};FreebaseStore.prototype.get_user_image_url=function(user){return this._url+'/api/trans/image_thumb/user/'+user.get_name()+"?maxwidth=30&maxheight=30&mode=fillcrop";};FreebaseStore.prototype.get_user_account_url=function(kind){var url;switch(kind){case'signin':url=this._url+'/signin/login?mw_cookie_scope=domain&onsignin='+encodeURIComponent(window.location.href);break;case'signout':url=this._url+'/api/account/logout?mw_cookie_scope=domain&onsucceed='+encodeURIComponent(window.location.href);break;case'register':url=this._url+'/signin/register';break;case'settings':url=this._url+'/user/account?mw_cookie_scope=domain&done='+encodeURIComponent(window.location.href);break;default:assert.critical(false,'Unknown kind ',kind);break;}
return url;};FreebaseStore.prototype.validate_filename=function(name){var RESERVED_KEYS={'acre':true,'status':'','api':true};if(!(/^[A-Za-z][\-_0-9A-Za-z\.]+$/).test(name)){return false;}
if(name in RESERVED_KEYS){return false;}
return true;};mjt.label_package('FreebaseStore');})();;var AcreDoc;(function(){var DEFAULT_ACRE_HANDLER_KEY='mjt';var DEFAULT_MEDIA_TYPE='text/plain';var CLASSNAME='file';AcreDoc=function(app,name,properties,initial_state){assert.critical(app,'Must specify app when creating a file');this._app=app;if(name&&this._app.get_store().validate_filename(name)){this._name=name;}else{this._name=this._app.get_untitled_file_name();}
this._acre_handler=properties.acre_handler||DEFAULT_ACRE_HANDLER_KEY;this._mime_type=properties.content_type||DEFAULT_MEDIA_TYPE;this._revision=properties.revision||null;this._based_on=properties.based_on||null;this._dom_element=document.createElement('div');this._dom_element.className=CLASSNAME;this._event_handlers={};this._initial_state=initial_state||null;var dirty=!this.has_been_saved();this._dirty_state={content:dirty,metadata:dirty};this._loaded_editors={};this._current_editor=null;this._app.register_file(this);return this;};AcreDoc.prototype.t_get_history=function(limit){var file=this;var args={fileid:file.get_fileid()}
var task=file.get_store().Jsonp('get_file_history',args);return task.enqueue();};AcreDoc.prototype.t_get_revision=function(revision){var args={fileid:this.get_fileid(),revision:revision||this.get_revision()}
return this.get_store().Jsonp('get_file_revision',args);};AcreDoc.prototype.hide=function(){this._current_editor.hide();$(this._dom_element).hide();};AcreDoc.prototype.destroy=function(){var file=this;for(var key in this._loaded_editors){var ed=this._loaded_editors[key];if(ed.destroy){ed.destroy();}}
$(file._dom_element).remove();file=null;};AcreDoc.prototype.is_writable=function(){return this.get_app().is_writable();};AcreDoc.prototype.has_been_saved=function(){return!!this._revision;};AcreDoc.prototype.is_dirty=function(kind){if(kind){return this._dirty_state[kind];}else{for(var k in this._dirty_state){if(this._dirty_state[k]===true){return true;}}}
return false;};AcreDoc.prototype.get_element=function(){return this._dom_element;};AcreDoc.prototype.get_store=function(){return this.get_app().get_store();};AcreDoc.prototype.get_app=function(){return this._app;};AcreDoc.prototype.get_name=function(){return this._name;};AcreDoc.prototype.get_fileid=function(){return this.get_app().get_path()+'/'+mjt.freebase.mqlkey_quote(this.get_name());};AcreDoc.prototype.get_relative_path=function(){return this.get_name();};AcreDoc.prototype.get_revision=function(){return this._revision;};AcreDoc.prototype.get_acre_handler=function(){return this._acre_handler;};AcreDoc.prototype.get_mime_type=function(){return this._mime_type;};AcreDoc.prototype.is_library=function(){return this._library;};AcreDoc.prototype.get_based_on=function(key){return this._based_on;};AcreDoc.prototype.get_view_url=function(){return this.get_store().get_file_view_url(this);};AcreDoc.prototype.get_acre_url=function(preview){return this.get_store().get_file_acre_url(this,preview);};AcreDoc.prototype.set_acre_handler=function(acre_handler){assert.critical(acre_handler,'Trying to set an undefined acre handler');this._acre_handler=acre_handler;this._dirty_state.metadata=true;this.mark_editor_dirty();};AcreDoc.prototype.set_mime_type=function(mime_type){assert.critical(mime_type,'Trying to set an undefined mime type');this._mime_type=mime_type;this._dirty_state.content=true;this.mark_editor_dirty();};AcreDoc.prototype.t_save=function(force_save){var file=this;var args={fileid:file.get_fileid(),content_type:file.get_mime_type()};if(!file.has_been_saved()||file.is_dirty('metadata')){args.acre_handler=file.get_acre_handler();}
if(!file.has_been_saved()&&file.get_based_on()){args.based_on=file.get_based_on().id;}
if(!force_save&&file.get_revision()){args.revision=file.get_revision();}
var save_task;var state=file.get_editor_state();if(state.text){args.text=state.text;save_task=file.get_store().Xhr("save_text_file",args)}else{save_task=file.get_store().FileUpload("save_binary_file",state.form,args)}
save_task.onready(function(r){if(r.revision){file._revision=r.revision;}
if(r.content_type){file._mime_type=r.content_type;}
file._dirty_state.content=false;file._dirty_state.metadata=false;}).onerror(function(code,message,info){mjt.warn('Save of',file.get_name(),'failed: ',code,' - ',message,info);});var flush_task=this.get_app().t_flush_cache().require(save_task);return flush_task.enqueue();};AcreDoc.prototype.t_revert=function(revision){var file=this;var args={fileid:file.get_fileid(),revision:revision};var reverttask=file.get_store().Xhr('set_file_revision',args).onready(function(r){file._revision=revision;file._dirty_state.content=false;if(r.text){file.set_editor_state({text:r.text});}else if(r.file){file.mark_editor_dirty();file.t_editor_show(file.get_editor_name());}}).onerror(function(code,message,info){mjt.warn('Revert of',file.get_name(),'failed: ',code,' - ',message,info);});var flush_task=this.get_app().t_flush_cache().require(reverttask);return flush_task.enqueue();};AcreDoc.prototype.t_delete=function(){var file=this;var args={appid:file.get_app().get_path(),name:file.get_name()};function _clean_up_file(){file.get_app().unregister_file(file.get_name());file.destroy();}
if(!file.has_been_saved()){return mjt.Succeed().enqueue().onready(_clean_up_file);}
var deltask=file.get_store().Xhr('delete_app_file',args).onready(_clean_up_file).onerror(function(code,message,info){mjt.warn('Delete of',file.get_name(),'failed: ',code,' - ',message,info);});var flush_task=this.get_app().t_flush_cache().require(deltask);return flush_task.enqueue();};AcreDoc.prototype.t_move=function(new_name){assert.critical(new_name,'Can\'t rename without a name');var file=this;var args={fileid:file.get_fileid(),name:new_name};var renametask=file.get_store().Xhr('rename_file',args).onready(function(){var old_name=file.get_name();file.get_app().unregister_file(old_name);file._name=new_name;file.get_app().register_file(file);}).onerror(function(code,message,info){mjt.warn('Rename of',file.get_name(),'failed: ',code,' - ',message,info);});var flush_task=this.get_app().t_flush_cache().require(renametask);return flush_task.enqueue();};AcreDoc.prototype.t_clone=function(app_path,new_name){assert.critical(app_path,'Can\'t clone without an app path');var file=this;var clonetask=file.get_store().AcreDocClone(file,app_path,new_name).enqueue().onerror(function(code,message,info){mjt.warn('Rename of',file.get_name(),'failed: ',code,' - ',message,info);});var flush_task=this.get_app().t_flush_cache().require(clonetask);return flush_task.enqueue();};AcreDoc.prototype.is_editor_loaded=function(editor_name){var loaded=false;if(editor_name){loaded=this._loaded_editors[editor_name]?true:false;}else{for(var ed in this._loaded_editors){loaded=true;break;}}
return loaded;};AcreDoc.prototype.get_editor_name=function(){for(var key in EDITORS){if(this._current_editor&&this._current_editor instanceof EDITORS[key].editor_class){return key;}}
return false;};AcreDoc.prototype.t_editor_show=function(editor_name,prefs){var file=this;var old_editor_state=null;var EditorClass=EDITORS[editor_name].editor_class;if(file._current_editor){if(!(file._current_editor instanceof EditorClass)){old_editor_state=file.get_editor_state();file._current_editor.hide();}
if(typeof file._loaded_editors[editor_name]!='undefined'){if(file._loaded_editors[editor_name]._dirty){old_editor_state=file.get_editor_state();file._current_editor.destroy();delete file._loaded_editors[editor_name];}else{file._current_editor=file._loaded_editors[editor_name];if(old_editor_state){file.set_editor_state(old_editor_state);}
file._current_editor.show(prefs);return mjt.Succeed().enqueue();}}}else if(file._initial_state){old_editor_state=file._initial_state;file._initial_state=null;}
var inittask=EditorClass.t_load(file).onready(function(new_editor){file._current_editor=file._loaded_editors[editor_name]=new_editor;if(old_editor_state){file.set_editor_state(old_editor_state);}
file._current_editor.show(prefs);}).onerror(function(code,message,info){mjt.warn('Loading of',file.get_name(),'failed: ',code,' - ',message,info);});return inittask.enqueue();};AcreDoc.prototype.get_editor_state=function(){var state=null;if(this._current_editor){state=this._current_editor.get_state();}else if(this._initial_state){state=this._initial_state;}
return state;};AcreDoc.prototype.set_editor_state=function(state){assert.critical(state,'Trying to set undefined editor state');if(this._current_editor){this._current_editor.set_state(state);}
return;};AcreDoc.prototype.mark_editor_dirty=function(){this._current_editor._dirty=true;};AcreDoc.prototype.get_editor_supported_features=function(feature){var supports=EDITORS[this.get_editor_name()].supports;if(feature){return!!supports[feature];}else{return supports;}};AcreDoc.prototype.register_editor_event_handlers=function(event_handlers){for(var event_name in event_handlers){this._event_handlers[event_name]=event_handlers[event_name];}};AcreDoc.prototype.trigger_editor_event=function(event_name,args){if(event_name=='change'){this._dirty_state.content=true;}
if(this._event_handlers[event_name]){this._event_handlers[event_name].apply(this,args);}};AcreDoc.prototype.editor_undo=function(){if(!this._current_editor||!this._current_editor.undo){return;}
this._current_editor.undo();};AcreDoc.prototype.editor_redo=function(){if(!this._current_editor||!this._current_editor.redo){return;}
this._current_editor.redo();};AcreDoc.prototype.editor_indent=function(){if(!this._current_editor||!this._current_editor.reindentSelection){return;}
this._current_editor.reindentSelection();};AcreDoc.prototype.get_editor_linenum=function(){return this._current_editor._linenum;};AcreDoc.prototype.editor_goto_line=function(linenum){if(!this._current_editor||!this._current_editor.goto_line){return;}
this._current_editor.goto_line(linenum);};})();;var AcreApp;(function(){var DEFAULT_FILENAME='index';AcreApp=function(store,path){this._store=store;this._path=path;this._version=null;this._name="Untitled";this._oauth_enabled=null;this._write_user=null;this._listed=null;this._release=null;this._hosts=[];this._versions=[];this._authors={};this._files={};this._untitled_label='untitled_';this._untitled_counter=1;return this;};AcreApp.prototype.t_load=function(){var app=this;var loadtask=app._store.Jsonp('get_app',{appid:app._path}).onready(function(r){app._path=r.appid;app._version=r.version;app._name=r.name||'Untitled';app._oauth_enabled=r.oauth_enabled;app._write_user=r.write_user;app._listed=r.listed;app._release=r.release;app._hosts=r.hosts;app._versions=r.versions;for(var key in r.authors){var user=r.authors[key];app._authors[user.name]=new AcreUser(app.get_store(),user);}
for(var key in r.files){new AcreDoc(app,r.files[key].name,r.files[key]);}
if(app.is_writable()){if(!app._write_user&&app._oauth_enabled===null){app.t_set_oauth_enabled(true);}
if(app._write_user&&app._oauth_enabled===true){app.t_set_oauth_enabled(false);}}})
return loadtask.enqueue();};AcreApp.prototype.t_flush_cache=function(all_hosts){var touch=mjt.freebase.Touch('http://'+this.get_store().get_app_host(this))
if(all_hosts){var hosts=this.get_hosts();for(var i=0;i<hosts.length;i++){mjt.freebase.Touch('http://'+hosts[i].host).enqueue();}}
return touch;};AcreApp.prototype.destroy=function(){for(var f in this._files){this._files[f].destroy();}
for(var u in this._authors){this._authors[u].destroy();}
app=null;};AcreApp.prototype.register_file=function(file){var re=new RegExp(this._untitled_label+'(\\d+)');var r=re.exec(file.get_name());if(r&&r.length){var counter=parseInt(r[1],10);if(this._untitled_counter<=counter){this._untitled_counter=counter+1;}}
this._files[file.get_name()]=file;};AcreApp.prototype.unregister_file=function(filename){delete this._files[filename];};AcreApp.prototype.is_dirty=function(){var files=this.get_files();for(var f in files){if(files[f].is_dirty()){return true;}}
return false;};AcreApp.prototype.get_store=function(){return this._store;};AcreApp.prototype.get_path=function(){return this._path;};AcreApp.prototype.get_versioned_path=function(){return this._version?this.get_path()+'/'+this._version:this.get_path();};AcreApp.prototype.get_name=function(){var path_segments=this._path.split('/');var name=path_segments.pop();return name;};AcreApp.prototype.get_display_name=function(){return this._name;};AcreApp.prototype.get_released_version=function(){return this._release;};AcreApp.prototype.get_versions=function(){return this._versions;};AcreApp.prototype.get_hosts=function(){return this._hosts;};AcreApp.prototype.get_files=function(){return this._files;};AcreApp.prototype.get_file=function(name){if(name){var segs=name.split('/');if(segs.length>1){var lib=this.get_library(segs[0]);return lib.get_file(segs[1]);}else{return this._files[name];}}
if(this._files[DEFAULT_FILENAME]){return this._files[DEFAULT_FILENAME];}else{var file;var files=this.get_files();for(var f in files){file=files[f];if(file){return file;}}}
return null;};AcreApp.prototype.get_untitled_file_name=function(){var name=this._untitled_label+this._untitled_counter;return name;};AcreApp.prototype.get_base_url=function(){return this._store.get_app_host(this);};AcreApp.prototype.get_view_url=function(){return this._store.get_app_view_url(this);};AcreApp.prototype.is_version=function(){return!!this._version;};AcreApp.prototype.get_version_label=function(){return this._version;};AcreApp.prototype.get_version_timestamp=function(version){var ver=version?version:this._version;for(var i=0;i<this._versions.length;i++){var v=this._versions[i];if(v.name==ver){return v.as_of_time;}}
return null;};AcreApp.prototype.t_save_all=function(){var task=mjt.Succeed();for(var id in this._files){var file=this._files[id];if(file.is_dirty()){task.require(file.t_save());}}
var flush_task=this.t_flush_cache().require(task);return flush_task.enqueue();};AcreApp.prototype.t_get_history=function(limit){var app=this;var args={appid:app.get_path()}
if(limit){args.limit=limit;}
var task=app.get_store().Jsonp('get_app_history',args);return task.enqueue();};AcreApp.prototype.t_set_listing=function(name,description,listed){var app=this
var args={appid:app.get_path()}
if(name){args.name=name;}
if(name){args.description=description;}
if(name){args.listed=listed;}
var update=app.get_store().Xhr('set_app_properties',args).onready(function(){if(name){app._display_name=name;}}).onerror(function(code,message,info){mjt.warn('Changing app listing of',app.get_name(),'failed: ',code,' - ',message,info);});return update.enqueue();};AcreApp.prototype.t_move=function(new_path){var app=this;var args={appid:app.get_path(),to_appid:new_path};var movetask=app.get_store().Xhr('move_app',args).onready(function(){app._path=new_path;}).onerror(function(code,message,info){mjt.warn('Move of',app.get_display_name(),'failed: ',code,' - ',message,info);});var flush_task=this.t_flush_cache().require(movetask);return flush_task.enqueue();};AcreApp.prototype.t_delete=function(){var app=this;var args={appid:app.get_path()};var deletetask=this.get_store().Xhr('delete_app',args).enqueue().onready(function(){app.destroy();}).onerror(function(code,message,detail){mjt.warn('Failed to delete app: '+code+', '+message+', '+detail);});return deletetask;};AcreApp.prototype.t_set_host=function(host){var app=this;var args={appid:app.get_path(),host:host};var pubtask=app.get_store().Xhr('set_app_host',args).onready(function(o){app._hosts=o.hosts;if(o.listed){app._listed=true;}}).onerror(function(code,message,info){mjt.warn('Setting release URL of',app.get_display_name(),'failed: ',code,' - ',message,info);});var flush_task=this.t_flush_cache(true).require(pubtask);return flush_task.enqueue();};AcreApp.prototype.t_set_release=function(version){var app=this;var args={appid:app.get_path(),version:version};var pubtask=app.get_store().Xhr('set_app_release',args).onready(function(o){app._hosts=o.hosts;app._versions=o.versions;app._release=o.release;}).onerror(function(code,message,info){mjt.warn('Setting release of',app.get_display_name(),'failed: ',code,' - ',message,info);});var flush_task=this.t_flush_cache(true).require(pubtask);return flush_task.enqueue();};AcreApp.prototype.t_add_version=function(version){var app=this;var args={appid:app.get_path(),version:version};var addversiontask=this.get_store().Xhr('create_app_version',args).onready(function(r){app._versions=r.versions;}).onerror(function(code,message,detail){mjt.warn('Failed to add version: '+code+', '+message+', '+detail);});return addversiontask.enqueue();};AcreApp.prototype.t_remove_version=function(version){var app=this;var args={appid:app.get_path(),version:version};var removeversiontask=this.get_store().Xhr('delete_app_version',args).onready(function(r){app._versions=r.versions;}).onerror(function(code,message,detail){mjt.warn('Failed to remove version: '+code+', '+message+', '+detail);});return removeversiontask.enqueue();};AcreApp.prototype.is_writable=function(){return this.is_author()&&!this.is_version();};AcreApp.prototype.is_author=function(){return this.get_store().get_user()?(this.get_store().get_user().get_name()in this.get_authors()):false;};AcreApp.prototype.is_oauth_enabled=function(){return!!this._oauth_enabled;};AcreApp.prototype.get_authors=function(){return this._authors;};AcreApp.prototype.get_write_user=function(){return this._authors[this._write_user];};AcreApp.prototype.t_add_author=function(username){var app=this;var args={appid:app.get_path(),username:username};var addtask=this.get_store().Xhr('add_app_author',args).onready(function(r){var new_author=new AcreUser(app._store,r.authors[username]);app._authors[username]=new_author;}).onerror(function(code,message,detail){mjt.warn('Failed to add author: '+code+', '+message+', '+detail);});return addtask.enqueue();};AcreApp.prototype.t_remove_author=function(username){var app=this;var args={appid:app.get_path(),username:username};var removetask=this.get_store().Xhr('remove_app_author',args).onready(function(){delete app._authors[username];}).onerror(function(code,message,detail){mjt.warn('Failed to add author: '+code+', '+message+', '+detail);});return removetask.enqueue();};AcreApp.prototype.t_get_apikeys=function(){var app=this;var args={appid:app.get_path()};var getapikeytask=this.get_store().Xhr('list_app_apikeys',args).onerror(function(code,message,detail){mjt.warn('Failed to get API Keys: '+code+', '+message+', '+detail);});return getapikeytask.enqueue();};AcreApp.prototype.t_add_apikey=function(name,key,secret){var app=this;var args={appid:app.get_path(),name:name,token:key,secret:secret};var addkeytask=this.get_store().Xhr('create_app_apikey',args).onerror(function(code,message,detail){mjt.warn('Failed to add api key: '+code+', '+message+', '+detail);});return addkeytask.enqueue();};AcreApp.prototype.t_remove_apikey=function(name){var app=this;var args={appid:app.get_path(),name:name};var removekeytask=this.get_store().Xhr('delete_app_apikey',args).onerror(function(code,message,detail){mjt.warn('Failed to add api key: '+code+', '+message+', '+detail);});return removekeytask.enqueue();};AcreApp.prototype.t_set_oauth_enabled=function(enabled){var app=this;if(app.is_oauth_enabled()==enabled){return mjt.Succeed().enqueue();}
if(!(enabled===true||enabled===false)){return mjt.Fail(500,'Must set oauth_enabled to true or false').enqueue();}
var args={appid:app.get_path(),enable:enabled};var oauthtask=app.get_store().Xhr('set_app_oauth_enabled',args).onready(function(){app._oauth_enabled=enabled;}).onerror(function(code,message,info){mjt.warn('Setting OAuth enabled for ',app.get_name(),'failed: ',code,' - ',message,info);});return oauthtask.enqueue();};AcreApp.prototype.t_set_writeuser=function(enabled){var app=this;if(!!app.get_write_user()==enabled){return mjt.Succeed().enqueue();}
if(!(enabled===true||enabled===false)){return mjt.Fail(500,'Must set write_user to true or false (current user)').enqueue();}
var args={appid:app.get_path(),enable:enabled};var writeusertask=app.get_store().Xhr('set_app_writeuser',args).onready(function(r){if(enabled){app._write_user=r.write_user;}
else{app._write_user=null;}}).onerror(function(code,message,info){mjt.warn('Setting write user for ',app.get_name(),'failed: ',code,' - ',message,info);});return writeusertask.enqueue();};AcreApp.prototype.t_set_write_permissions=function(type,user){var app=this;var write_user_enabled=null;var oauth_enabled=null;var task=mjt.Succeed().onerror(function(code,message,info){mjt.warn('Setting write user for ',app.get_name(),'failed: ',code,' - ',message,info);});if(type!='oauth'&&this.is_oauth_enabled()){oauth_enabled=false;}
if(type!='writeuser'&&this.get_write_user()){write_user_enabled=false;}
if(type=='oauth'&&!this.is_oauth_enabled()){oauth_enabled=true;}
if(type=='writeuser'&&!this.get_write_user()){write_user_enabled=true;}
if(oauth_enabled!==null){var oauthtask=app.t_set_oauth_enabled(oauth_enabled);task.require(oauthtask);}
if(write_user_enabled!==null){var writeusertask=app.t_set_writeuser(write_user_enabled);task.require(writeusertask);}
return task.enqueue();};})();;var AcreUser;(function(){AcreUser=function(store,properties){this._store=store;this._name=properties.name||null;this._full_name=properties.full_name||null;this._image=properties.image||null;return this;};AcreUser.prototype.destroy=function(){var self=this;self=null;};AcreUser.prototype.get_name=function(){return this._name;};AcreUser.prototype.get_full_name=function(){return this._full_name;};AcreUser.prototype.get_image_url=function(){return this._store.get_user_image_url(this);};AcreUser.prototype.get_view_url=function(){return this._store.get_user_view_url(this);};AcreUser.prototype.get_default_app_host=function(){return this._store.get_user_default_app_host(this);};AcreUser.prototype.get_default_app_path=function(){return this._store.get_user_default_app_path(this);};})();;var EDITORS={};;(function(){var CreateCodeMirror=mjt.define_task(null,[{name:'parent'},{name:'editor_config'}]);CreateCodeMirror.prototype._task_class='CreateCodeMirror';CreateCodeMirror.prototype.request=function(){var task=this;var editor=new CodeMirror(this.parent,this.editor_config);this.editor_config.initCallback=function(mirror){task.ready(editor);};editor.get_state=function(){return{text:this.editor.getCode()};};editor.set_state=function(obj){this.editor.importCode(obj.text);};};function determine_parser(file){var parser='DummyParser';var CODEMIRROR_DOCTYPE_MAP={'mqlquery':'JSParser','acre_script':'JSParser','mjt':'HTMLMixedParser'};var CODEMIRROR_MEDIATYPE_MAP={'text/html':'HTMLMixedParser','text/css':'CSSParser','text/javascript':'JSParser','application/json':'JSParser'};var acre_handler=file.get_acre_handler();if(acre_handler&&acre_handler!=='passthrough'){if(acre_handler in CODEMIRROR_DOCTYPE_MAP){parser=CODEMIRROR_DOCTYPE_MAP[acre_handler];}}else{var mime_type=file.get_mime_type();if(mime_type in CODEMIRROR_MEDIATYPE_MAP){parser=CODEMIRROR_MEDIATYPE_MAP[mime_type];}}
return parser;}
CodeMirror.t_load=function(file){var editor_config=$.extend(true,{},EDITORS.CodeMirror.config);editor_config.readOnly=!file.is_writable();if(editor_config.readOnly){$(file.get_element()).addClass('readonly').append("<div class='readonly-warning'>READ ONLY</div>");}
editor_config.onChange=function(){var history=file._loaded_editors["CodeMirror"].historySize();file.trigger_editor_event('change',[history.undo,history.redo]);};var top_element=document.createElement('div');$(top_element).css({height:'100%',width:'100%'});$(file.get_element()).append(top_element);var loadtask;var task=CreateCodeMirror(top_element,editor_config).onready(function(editor){editor.setParser(determine_parser(file));if(loadtask){editor.set_state({text:loadtask.result.text});}
editor._file=file;editor._top_element=top_element;$('>div',top_element).css('height','100%');file.trigger_editor_event('newframe',[editor.frame]);editor_config.cursorActivity=CodeMirror.prototype.make_line_highlighter(editor,file);if(!editor_config.readOnly){editor._codeAssist=new CodeAssist(editor.frame,editor,{isMjt:file.get_acre_handler()=='mjt'});}});if(file.has_been_saved()&&!file.is_editor_loaded()){loadtask=file.t_get_revision();task.require(loadtask);}
return task;};CodeMirror.prototype.make_line_highlighter=function(editor,file){var last;return function(){var file_prefs=file._current_editor._prefs;if(!file_prefs.margin||file_prefs.softwrap){return;}
var linenum=editor.lineNumber(editor.cursorPosition().line)-1;if(linenum!==last){var linenumber_container=$('.CodeMirror-line-numbers,',file.get_element());var linenumbers=$('>div',linenumber_container);last=last||0;$(linenumbers[last]).removeClass('current-line');$(linenumbers[linenum]).addClass('current-line');file.trigger_editor_event('linechange',[linenum+1]);last=linenum;file._current_editor._linenum=last+1;}};};CodeMirror.prototype.destroy=function(){var editor=this;if("_codeAssist"in editor){editor._codeAssist.dispose();editor._codeAssist=null;}
editor.hide();$(editor._top_element).remove();editor=null;};CodeMirror.prototype.show=function(prefs){var editor=this;editor._prefs=prefs;this.win.document.body.style.whiteSpace=prefs.softwrap?'':'nowrap';$('.CodeMirror-line-numbers').toggle(prefs.margin&&!prefs.softwrap);if(editor._codeAssist){editor._codeAssist.putSetting("dotTrigger",prefs.dotTrigger);}
$(editor._top_element).show();};CodeMirror.prototype.hide=function(){var editor=this;$(editor._top_element).hide();};CodeMirror.prototype.goto_line=function(linenum){try{this.jumpToLine(linenum);}catch(e){this.selectLines(this.prevLine(this.lastLine()),0);}};})();EDITORS.CodeMirror={editor_class:CodeMirror,supports:{hotswap:true,mimetype_change:true,margin:true,linenumbers:true,softwrap:true,undo:true,indent:true,codeassist:true},config:{height:'100%',marginWidth:45,autoMatchParens:true,passDelay:100,undoDelay:250,path:'codemirror/js/',parserfile:['parsexml.js','parsecss.js','tokenizejavascript.js','parsejavascript.js','parsehtmlmixed.js','parsedummy.js'],stylesheet:['codemirror/css/xmlcolors_acrid.css','codemirror/css/jscolors_acrid.css','codemirror/css/csscolors_acrid.css'],lineNumbers:true,tabMode:"shift",dotTrigger:false}};;function EditorMargin(container,options){this._container=container;this._container.innerHTML='<div style=\'position: relative; left: 0; top: 0; width: 100%; height: 100%\'></div>';var lines=[];for(var i=0;i<100;i++){lines.push('<div>0</div>');}
this._lineMetricDiv=this._createLayer();this._lineMetricDiv.style.visibility='hidden';this._lineMetricDiv.innerHTML=lines.join('');this._fontMetricDiv=this._createLayer();this._fontMetricDiv.style.visibility='hidden';this._fontMetricDiv.style.height='100em';this._lineNumberDiv=this._createLayer();this._lineNumberDiv.className='editor-margin-line-numbers';this._firstRenderedLine=0;this._renderedLineCount=0;this._currentLine=-1;}
(function(){EditorMargin.get_layout_metrics=function(win,elmt){var style;if(win.getComputedStyle){style=win.getComputedStyle(elmt,null);return{paddingTop:style.getPropertyValue('padding-top'),marginTop:style.getPropertyValue('margin-top')};}else{style=elmt.currentStyle;return{paddingTop:style.paddingTop,marginTop:style.marginTop};}};EditorMargin.prototype={dispose:function(){},redraw:function(layoutMetrics,scrollInfo){var lineHeight=this._lineMetricDiv.offsetHeight/100;var fontHeight=this._fontMetricDiv.offsetHeight/100;var lineToFontHeightRatio=lineHeight/fontHeight;var maxLineCount=null;if(scrollInfo.contentHeight!==null){maxLineCount=Math.floor(scrollInfo.contentHeight/lineHeight);}
var newFirstVisibleLine=Math.floor(scrollInfo.scrollY/lineHeight);var newLastVisibleLine=Math.ceil((scrollInfo.scrollY+scrollInfo.visibleHeight)/lineHeight)-1;if(maxLineCount!==null){newLastVisibleLine=Math.min(newLastVisibleLine,maxLineCount-1);}
var renderedLastLine=this._firstRenderedLine+this._renderedLineCount;if(newFirstVisibleLine<this._firstRenderedLine||newFirstVisibleLine>=renderedLastLine||newLastVisibleLine>=renderedLastLine||(maxLineCount!==null&&maxLineCount<newLastVisibleLine)){var newVisibleLineCount=newLastVisibleLine-newFirstVisibleLine+1;var newFirstRenderedLine=Math.max(0,newFirstVisibleLine-newVisibleLineCount);var newLastRenderedLine=newLastVisibleLine+newVisibleLineCount;if(maxLineCount!==null){newLastRenderedLine=Math.min(newLastRenderedLine,maxLineCount-1);}
this._lineNumberDiv.style.paddingTop=(lineToFontHeightRatio*newFirstRenderedLine)+'em';var html=[];for(var i=newFirstRenderedLine;i<=newLastRenderedLine;i++){html.push('<div>'+(i+1)+'</div>');}
this._lineNumberDiv.innerHTML=html.join('');this._firstRenderedLine=newFirstRenderedLine;this._renderedLineCount=newLastRenderedLine-newFirstRenderedLine+1;this._highlightCurrentLine();}
var parseIntoPixels=function(s){try{if(s.indexOf("px")>0){return parseInt(s.replace(/px$/g,''),10);}else if(s.indexOf("em")>0){return Math.round(parseFloat(s.replace(/em$/g,''),10)*fontHeight);}}catch(e){}
return 0;};this._lineNumberDiv.style.top=(-scrollInfo.scrollY+
parseIntoPixels(layoutMetrics.paddingTop)+
parseIntoPixels(layoutMetrics.marginTop))+'px';},_createLayer:function(){var layerDiv=document.createElement('div');layerDiv.style.position='absolute';this._container.firstChild.appendChild(layerDiv);return layerDiv;},setCurrentLine:function(line){if(line!==this._currentLine){this._unhighlightCurrentLine();this._currentLine=line;this._highlightCurrentLine();}},_unhighlightCurrentLine:function(){if(this._currentLine!==-1){var childNodes=this._lineNumberDiv.childNodes;var index=this._currentLine-this._firstRenderedLine;if(index>=0&&index<childNodes.length){childNodes[index].className='';}}},_highlightCurrentLine:function(){if(this._currentLine!==-1){var childNodes=this._lineNumberDiv.childNodes;var index=this._currentLine-this._firstRenderedLine;if(index>=0&&index<childNodes.length){childNodes[index].className='edit-margin-current-line-number';}}}};})();var TextareaEditor;(function(){TextareaEditor=function(options){var self=this;self._edit_element=document.createElement('textarea');if(options.cssClassName){self._edit_element.className=options.cssClassName;}
if(options.readOnly){$(self._edit_element).attr('readonly','yes').addClass('readonly');$(self._top_element).append("<div class='readonly-warning'>READ ONLY</div></div>");}
if(options.on_change){self.timeout_id=null;var handler=function(e){if(self.timeout_id){window.clearTimeout(self.timeout_id);}
self.timeout_id=window.setTimeout(options.on_change,300);};var events=['input','drop'];if(!$.browser.mozilla){events.push('paste','keypress');}
for(var i=0;i<events.length;i++){$(self._edit_element).bind(events[i],handler);}}};TextareaEditor.t_load=function(file){var editor_config=EDITORS.TextareaEditor.config;editor_config.readOnly=!file.is_writable();editor_config.on_change=function(e){file.trigger_editor_event('change',[]);};var editor=new TextareaEditor(editor_config);editor._top_element=document.createElement('div');$(editor._top_element).css({height:'100%',width:'100%'});$(file.get_element()).append(editor._top_element);$(editor._top_element).append(editor._edit_element);editor._margin_width=editor_config.marginWidth;editor._margin_element=document.createElement('div');editor._margin_element.className='edit-margin';$(editor._top_element).append(editor._margin_element);var task=mjt.Succeed(editor);if(file.has_been_saved()&&!file.is_editor_loaded()){var loadtask=file.t_get_revision().onready(function(r){editor.set_state({text:r.text});});task.require(loadtask);}
return task;};TextareaEditor.prototype.destroy=function(){var editor=this;$(editor._top_element).remove();editor=null;};TextareaEditor.prototype.show=function(prefs){var editor=this;editor._prefs=prefs;if(prefs.margin){if(!editor.editorMargin){editor.editorMargin=new EditorMargin(editor._margin_element,{});}
editor._scroll_callback=function(){editor._redraw_editor_margin();};if($.browser.msie){editor._edit_element.onscroll=editor._scroll_callback;}else{$(editor._edit_element).bind('scroll',editor._scroll_callback);}}
editor._resize_callback=function(){editor._on_resize();};$(window).bind('resize',editor._resize_callback);editor._on_resize();$(editor._top_element).show();};TextareaEditor.prototype.hide=function(){var editor=this;$(editor._top_element).hide();$(editor._edit_element).unbind('scroll',editor._scroll_callback);$(window).unbind('resize',this._resize_callback);};TextareaEditor.prototype.get_state=function(){return{text:this._edit_element.value};};TextareaEditor.prototype.set_state=function(obj){this._edit_element.value=obj.text;};TextareaEditor.prototype._on_resize=function(){if(this._prefs.margin){$(this._edit_element).css('left',this._margin_width);$(this._edit_element).width($(this._top_element).width()-this._margin_width);$(this._margin_element).width(this._margin_width);$(this._margin_element).show();this._redraw_editor_margin();}else{$(this._edit_element).css('left',0).width($(this._top_element).width());$(this._margin_element).hide();}};TextareaEditor.prototype._redraw_editor_margin=function(){if(this._prefs.margin){try{var scrollInfo=this._get_scroll_info();var layoutMetrics=this._get_layout_metrics();this.editorMargin.redraw(layoutMetrics,scrollInfo);}catch(e){}}};TextareaEditor.prototype._get_scroll_info=function(){return{scrollY:$(this._edit_element).scrollTop(),visibleHeight:$(this._edit_element).innerHeight(),contentHeight:null};};TextareaEditor.prototype._get_layout_metrics=function(){return EditorMargin.get_layout_metrics(window,this._edit_element);};})();EDITORS.TextareaEditor={editor_class:TextareaEditor,supports:{hotswap:true,mimetype_change:true,margin:true},config:{cssClassName:'Editor-view',marginWidth:45}};;var QueryEditor=function(parent,editor_config,task){var cuecardComposition;parent.innerHTML='<div style="position: relative">'+'<div style="position: absolute;"></div>'+'<div style="position: absolute;"></div>'+'</div>';var queryEditorDiv=parent.firstChild.childNodes[0];var outputPaneDiv=parent.firstChild.childNodes[1];var self=this;var resize=function(){var margin=10;var spacing=10;var width=Math.max(100,parent.offsetWidth);var halfWidth=Math.round((width-2*margin-spacing)/2)+"px";var height=Math.max(100,parent.offsetHeight);parent.firstChild.style.width="100%";parent.firstChild.style.height=height+"px";var innerHeight=height-2*margin;var queryEditorHeight=innerHeight;$(queryEditorDiv).css("top",margin+"px").css("height",queryEditorHeight+"px");$(queryEditorDiv).css("left",margin+"px").css("width",halfWidth);$(outputPaneDiv).css("right",margin+"px").css("width",halfWidth).css("top",margin+"px").css("height",innerHeight+"px");cuecardComposition.queryEditor.layout();cuecardComposition.outputPane.layout();};editor_config.focusOnReady=true;editor_config.onReady=function(){task.ready(self);};cuecardComposition=CueCard.createComposition({queryEditorElement:queryEditorDiv,queryEditorOptions:editor_config,outputPaneElement:outputPaneDiv,outputPaneOptions:{verticalPadding:4,horizontalPadding:4}});this.composition=cuecardComposition;cuecardComposition.queryEditor._onRun=function(forceCleanUp){this.run(true);};this.get_state=function(){return{text:cuecardComposition.queryEditor.content()};};this.set_state=function(obj){cuecardComposition.queryEditor.content(obj.text);};this.destroy=function(){$(parent).hide();$(parent).remove();};this.show=function(prefs){this._prefs=prefs;if(prefs.emql){this.composition.queryEditor._getQueryEnvelope=function(){return{extended:1}};}
$(window).bind('resize',resize);$('.cuecard-queryEditor-controls-bottom').mjt(ui.templates.query_button_bar());$(self._file.get_element()).show();$(parent).show();resize();};this.hide=function(){$(parent).hide();$(window).unbind('resize',resize);};this.undo=function(){cuecardComposition.queryEditor._editor.editor.history.undo();};this.redo=function(){cuecardComposition.queryEditor._editor.editor.history.redo();};this.reindentSelection=function(){cuecardComposition.queryEditor._editor.editor.reindentSelection();};this.query_assist=function(){cuecardComposition.queryEditor.startAssistAtCursor();};this.query_run=function(){cuecardComposition.queryEditor.run(this._file.is_writable());};this.query_redangle=function(){var self=this;var qe=cuecardComposition.queryEditor;var m=qe.getQueryModelAndContext();var q=m.model;q.toInsideOutQueryJson(m.context,CueCard.UI.createBlockingContinuations(function(cont,q2){qe.content(CueCard.jsonize(q2,qe.getJsonizingSettings()));}));};this.generate_template=function(){var self=this;var name=ui.get_app().get_untitled_file_name();var metadata={acre_handler:'mjt'};var m=cuecardComposition.queryEditor.getQueryModelAndContext();var q=m.model.toQueryJson();CueCard.CodeGeneration.serializers["acre-template"].generateQueryCall=function(context,writer,utils,queryJSON,variables,qVar,oVar){writer.appendIndent();writer.append("<acre:script>");writer.appendLineBreak();writer.indent();if(self._prefs.emql){writer.appendIndent();writer.append('acre.require("/freebase/apps/emql/api_extender");');writer.appendLineBreak();}
writer.appendIndent();writer.append('var '+qVar+' = acre.require("'+self._file.get_name()+'").query');writer.append(";");writer.appendLineBreak();if(self._prefs.emql){writer.appendIndent();writer.append('var '+oVar+' = acre.freebase.mqlread('+qVar+', {extended:1});');writer.appendLineBreak();}else{writer.appendIndent();writer.append('var '+oVar+' = acre.freebase.mqlread('+qVar+');');writer.appendLineBreak();}
writer.unindent();writer.appendIndent();writer.append("</acre:script>");writer.appendLineBreak();return oVar+".result";};var text=CueCard.CodeGeneration.generate(q,CueCard.CodeGeneration.serializers["acre-template"],{indentLevel:1});text='<html>\r'+'<head>\r\r'+'  <title>Query-Generated Template</title>\r\r'+'  <style type="text/css" media="screen">\r'+'    * { vertical-align: baseline; font-weight: inherit; font-family: inherit; \r'+'        font-style: inherit; font-size: inherit; border: 0 none; outline: 0; padding: 0; margin: 0; }\r'+'    body { margin: 15px; }\r'+'    ul { list-style: none; }\r'+'    li { padding: 3px; }\r'+'    table { border-collapse: collapse; border-spacing: 0; width: 100%; }\r'+'    th, td { border: 1px solid #ddd; vertical-align: top; padding: 6px; }\r'+'    th { width: 20%; text-align: right; font-size: 11px; font-weight: bold; padding: 6px; color: #666; background: #f5f5f5; }\r'+'    td { width: 80%; font-size: 12px; }\r'+'    img { padding: 1px; border: 1px solid #ccc;}\r'+'    ins { color: #aaa; text-decoration: none;}\r'+'  </style>\r\r'+'</head>\r\r'+''+'<body>\r'+
text+'  \r'+'  <!-- Freebase attribution template -->\r'+'  ${acre.require("/freebase/apps/attribution/templates").blanket()}\r'+'</body>\r'+'</html>\r';ui.do_file_create_new(name,metadata,{text:text});};this.goto_line=function(linenum){var cm=cuecardComposition.queryEditor._editor.editor;try{cm.jumpToLine(linenum);}catch(e){cm.selectLines(cm.prevLine(cm.lastLine()),0);}};};(function(){var CreateQueryEditor=mjt.define_task(null,[{name:'parent'},{name:'editor_config'}]);CreateQueryEditor.prototype.request=function(){return new QueryEditor(this.parent,this.editor_config,this);};QueryEditor.t_load=function(file){var editor_config=$.extend(true,{},EDITORS.QueryEditor.config);editor_config.readOnly=!file.is_writable();editor_config.onChange=function(){try{var history=file._loaded_editors["QueryEditor"].composition.queryEditor._editor.historySize();file.trigger_editor_event('change',[history.undo,history.redo]);}catch(e){}};var top_element=document.createElement('div');$(top_element).css({height:'100%',width:'100%'});$(file.get_element()).hide().append(top_element);var loadtask;var task=CreateQueryEditor(top_element,editor_config).onready(function(editor){editor.composition.queryEditor._editor.setParser('JSParser');if(loadtask){editor.set_state({text:loadtask.result.text});}
editor._file=file;editor._top_element=top_element;$('>div',top_element).css('height','100%');$('.cuecard-queryEditor-controls-top').hide();if(editor_config.readOnly){$(file.get_element()).addClass('readonly');$('.cuecard-queryEditor-inner',file.get_element()).append("<div class='readonly-warning'>READ ONLY</div>");}
$('<a class="cuecard-permalink" href="javascript:{}">Open in Query Editor</a>').click(function(evt){var url="http://www.freebase.com/app/queryeditor?q="+
encodeURIComponent(editor.composition.queryEditor.getUnresolvedQuery());window.open(url,"_blank");}).appendTo($(top_element).find('.cuecard-outputPane')[0]);file.trigger_editor_event('newframe',[editor.composition.queryEditor._editor.frame]);});if(file.has_been_saved()&&!file.is_editor_loaded()){loadtask=file.t_get_revision();task.require(loadtask);}
return task;};})();EDITORS.QueryEditor={editor_class:QueryEditor,supports:{undo:true,indent:true,inline_preview:true,emql:true},config:{height:'100%',marginWidth:45,autoMatchParens:true,passDelay:100,undoDelay:250,path:'codemirror/js/',parserfile:['parsexml.js','parsecss.js','tokenizejavascript.js','parsejavascript.js','parsehtmlmixed.js','parsedummy.js'],stylesheet:['codemirror/css/xmlcolors_acrid.css','codemirror/css/jscolors_acrid.css','codemirror/css/csscolors_acrid.css'],lineNumbers:true,tabMode:"shift",emql:false}};;var ImageEditor;(function(){ImageEditor=function(options){var self=this;this.supports_mime_type_change=false;this.ui_element=document.createElement('div');if(options.cssClassName){self.ui_element.className=options.cssClassName;}
this.file=options.file;this.readOnly=options.readOnly;if(options.onChange){this.on_change=options.onChange;}};ImageEditor.t_load=function(file){var editor_config=EDITORS.ImageEditor.config;editor_config.readOnly=!file.is_writable();editor_config.onChange=function(undos,redos){file.trigger_editor_event('change',[undos,redos]);};var editor=new ImageEditor(editor_config);editor.file=file;$(file.get_element()).append(editor.ui_element);return mjt.Succeed(editor);};ImageEditor.prototype.destroy=function(){var editor=this;$(editor.ui_element).remove();editor=null;};ImageEditor.prototype.show=function(prefs){var self=this;var uploadprompt='Upload an image';self._prefs=prefs;$(self.ui_element).empty();this.file._dirty_state.content=false;if(self.file.has_been_saved()){uploadprompt='Replace this image';}
if(!self.readOnly){self.form_element=$('<form class="image-upload"><label for="image-browse">'+uploadprompt+':</label> <input id="image-browse" type="file" name="file" size="40"></form>');$(self.form_element).change(self.on_change);$(self.ui_element).append(self.form_element);}
var filename=self.file.get_name();var app=self.file.get_app();var host=app.get_store().get_app_host(app);if(self.file.has_been_saved()){if(self.file.get_mime_type().substr(0,6)==='image/'){var img=$('<div class="image-preview"><p>'+filename+':</p><img src=\"/api/trans/raw'+this.file.get_revision()+'\"/></div>').appendTo(self.ui_element);}else if(this.file.get_revision()){$('<a href=\'http://'+host+'/'+filename+'\'>download file</a>').appendTo(this.ui_element);}}
$(self.ui_element).append('<div class="image-attribution"><img src="img/freebase-cc-by-61x23.png" alt="Freebase CC-BY" width="61" height="23" /><p>All images included in Acre apps are released under <a href="http://creativecommons.org/licenses/by/3.0/">CC-BY</a>.</p></div>');$(this.ui_element).show();};ImageEditor.prototype.hide=function(){$(this.ui_element).hide();};ImageEditor.prototype.get_state=function(){return{form:this.form_element};};ImageEditor.prototype.set_state=function(obj){this.show();return;};})();EDITORS.ImageEditor={editor_class:ImageEditor,supports:{},config:{cssClassName:'Editor-view'}};;var ui={};$(document).ready(function(){if($.browser.msie&&$.browser.version<"8.0"){assert.critical(false,"Internet Explorer 6 and 7 are not supported.  IE8+, Firefox 3+ and Safari 3+ are.");return;}
CueCard.freebaseServiceUrl='http://'+CONFIG.ACRE_METAWEB_API_ADDR;CueCard.helper='http://dev21.cuecard.dfhuynh.user.'+CONFIG.ACRE_HOST_SUFFIX+'/';ui.set_store(new FreebaseStore());var store=ui.get_store();store.t_init().onready(function(){ui.set_user(store.get_user());ui.init();store.TestCookies(store).enqueue().onerror(function(code,message,info){ui.MessagePanel.error("Your browser configuration may not always let you see your latest "+"changes when clicking <b>View</b> (third-party cookies).<br/><br/>"+"Hold down the <b>Shift</b> key when clicking the browser <b>Refresh</b> button to ensure "+"you're seeing the latest.");});}).onerror(function(code,message,info){assert.critical(false,"Error connecting to Freebase<br/>"+message);mjt.error(code,message,info);});});(function(){ui.init=function(){ui._setup_css_classes();ui.shortcut.register_keys(document);window.onbeforeunload=ui.warn_user_about_unsaved_files;$(document).keydown(function(e){return!(e.which===8&&e.target.nodeName!=='INPUT'&&e.target.nodeName!=='TEXTAREA');});ui.templates=mjt.run('mjtstuff');$('#mjtmain').mjt(ui.templates.body());$('.exit').live('click',ui.do_hide_overlays);$('.app-link').live('click',function(e){if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey){}else{var new_app=$(this).attr("apppath");ui.do_hide_overlays();if(ui.get_app()&&ui.get_app().is_dirty()){ui.do_show_dialog('files_dirty',[new_app]);}else{ui.do_choose_app(new_app);}
return false;}});ui.check_browser_hash();setInterval(ui.check_browser_hash,250);};ui._setup_css_classes=function(){if($.browser.msie&&$.browser.version>"7.0"){$('body').addClass("ie");}
if(jQuery.browser.mozilla&&jQuery.browser.version.substr(0,3)=="1.8"){$('body').addClass("ffx2");}};ui.refresh_app_templates=function(state){var app=ui.get_app();$('#header').mjt(ui.templates.header(state));if(app){$('#list-column').mjt(ui.templates.list_column());if(app.is_writable()){$('#about-bar').hide();}else{$('#about-bar').mjt(ui.templates.about_bar()).show();}}};ui.refresh_file_templates=function(){$('#file-list').mjt(ui.templates.file_list());$('#button-bar').mjt(ui.templates.button_bar());ui.finish_drawing();};ui.finish_drawing=function(){$('.refresh').show();$(window).trigger('resize');ui.set_state();};ui.do_show_dialog=function(dialogname,args){ui.do_hide_overlays();function _hide_dialogs(){ui.do_hide_dialog_overlays();$(document).unbind('keydown',_key_handler);}
function _key_handler(e){if(e.keyCode==27){_hide_dialogs();}}
var dialog;if(dialogname=='welcome'){dialog=$("<div id='"+dialogname+"'></div>").mjt(ui.templates[dialogname+'_dialog'].apply(this,args||[])).prependTo(document.body);}else{$("<div id='dialog-overlay'></div>").prependTo(document.body);$(document).bind('keydown',_key_handler);var dialog=$("<div id='dialog-"+dialogname+"' class='dialog'></div>").mjt(ui.templates[dialogname+'_dialog'].apply(this,args||[])).prepend("<div class='dialog-close' onclick='ui.do_hide_overlays()'></div>").prependTo(document.body);}
dialog.css('left',($(document).width()-dialog.width())/2).show();return false;};ui.do_show_menu=function(menuname,args){function _hide_menus(){ui.do_hide_menu_overlays();$(document).unbind('keydown',_key_handler);}
function _key_handler(e){if(e.keyCode==27){_hide_menus();}}
$('#button-'+menuname).addClass('button-open');var offset=$('#button-'+menuname).offset();var button_height=$('#button-'+menuname).height();$("<div id='menu-overlay'></div>").prependTo(document.body).click(_hide_menus);$(document).bind('keydown',_key_handler);$("<div id='menu-"+menuname+"' class='menu'></div>").css({top:offset.top+button_height+10,left:offset.left}).prependTo(document.body).mjt(ui.templates[menuname+'_menu'].apply(this,args||[]));return false;};ui.do_setup_submenu=function(menu_item_id,submenuname,args){var mouseenter_timer;var mouseleave_timer;var menu_drawn=false;var menu_item=$('#'+menu_item_id);var parent_menu=menu_item.closest('.menu');var submenu=$("<div id='menu-"+submenuname+"' class='menu submenu'></div>");menu_item.mouseenter(function(e){mouseenter_timer=setTimeout(function(){if(!menu_drawn){submenu.css({top:menu_item.offset().top,left:parent_menu.offset().left+parent_menu.width()}).prependTo(document.body).mjt(ui.templates[submenuname+'_menu'].apply(this,args||[])).mouseenter(function(e){clearTimeout(mouseleave_timer);}).mouseleave(function(e){clearTimeout(mouseenter_timer);mouseleave_timer=setTimeout(function(){submenu.css('visibility','hidden');},100);});menu_drawn=true;}else{submenu.css('visibility','visible');}},250);}).mouseleave(function(e){clearTimeout(mouseenter_timer);mouseleave_timer=setTimeout(function(){submenu.css('visibility','hidden');},100);});};ui.do_hide_dialog_overlays=function(){$('#dialog-overlay, .dialog').remove();};ui.do_hide_menu_overlays=function(){$('#menu-overlay, .menu').remove();$('.button-open').removeClass('button-open');};ui.do_hide_overlays=function(){ui.do_hide_dialog_overlays();ui.do_hide_menu_overlays();};ui.do_hide_welcome=function(){$('#welcome').remove();};var _first_time=true;var _current_store;var _current_user;var _current_app;var _current_file;var _current_line;var _current_file_is_dirty=false;var _changing_state=false;var NUM_RECENTS_TO_STORE=16;ui.check_browser_hash=function(){if(_changing_state){return;}
var new_hash=ui._get_browser_hash();if(new_hash=='0'){ui.set_state();return;}
if(_first_time||ui._ui_state_to_browser_hash()!==new_hash){_first_time=false;var args=mjt.app.decode_uristate(new_hash);ui.do_choose_app(args.app,args.file,args.line,args.create);}};ui._get_browser_hash=function(){var i,href;href=window.location.href;i=href.indexOf("#");return i>=0?href.substr(i+1):"";};ui._ui_state_to_browser_hash=function(){if(typeof ui.get_app()=='undefined'){return null;}
var state={};if(ui.get_app()){state.app=ui.get_app().get_versioned_path();}
if(ui.get_file()){state.file=ui.get_file().get_relative_path();}
return mjt.app.encode_uristate(state);};ui.set_state=function(){var app=ui.get_app();var file=ui.get_file();_current_file_is_dirty=file?file.is_dirty():null;var title="";if(app){title+=(app.get_display_name()||app.get_path())+" - ";}
if(file){title+=file.get_name()+" - ";}
title+="Freebase App Editor";document.title=title;var hash=ui._ui_state_to_browser_hash();if(hash!==ui._get_browser_hash()){window.location.hash=hash;}
_changing_state=false;};ui.clear_state=function(){_current_app=null;_current_file=null;_current_line=null;_current_file_is_dirty=null;};ui.get_store=function(){return _current_store;};ui.set_store=function(obj){_current_store=obj;};ui.set_user=function(user){_current_user=user;};ui.get_app=function(){if(!_current_app){return null;}
return _current_app;};ui.get_file=function(){if(!_current_file){return null;}
return _current_file;};ui.get_line=function(){return _current_line;};ui.get_user=function(){return _current_user;};ui.get_recents=function(kind,keep_first){var recent=$.localStore('recent_'+kind,undefined,false);if(recent===null){recent=[];}
if(!keep_first&&recent&&recent.length>0){recent.shift();}
return recent;};ui.add_recent=function(kind,value,replace){var recent=$.localStore('recent_'+kind,undefined,false);if(!recent||!jQuery.isArray(recent)){recent=[];}
var val=JSON.stringify(value);for(var i=0;i<recent.length;i++){var ival=JSON.stringify(recent[i]);if(ival==val||(kind=='apps'&&recent[i].path==replace)){recent.splice(i,1);}}
recent.unshift(value);if(recent&&recent.length>NUM_RECENTS_TO_STORE){var removed=recent.splice(NUM_RECENTS_TO_STORE);if(kind=='apps'){for(var j=0;j<removed.length;j++){ui.clear_recents(removed[j]);}}}
$.localStore('recent_'+kind,recent,false);};ui.clear_recents=function(kind){$.localStore('recent_'+kind,null,false);};ui.do_choose_app=function(appid,filename,linenum,create){_changing_state=true;function _no_app(){ui.clear_state();ui.set_state();ui.refresh_app_templates('open');var recent_apps=ui.get_recents('apps',true);if(create=='app'){ui.do_show_dialog('new_app');}else if(recent_apps.length>0){var last_app=recent_apps.shift();$.localStore('recent_apps',recent_apps,false);ui.do_choose_app(last_app.path);}else if(ui.get_user()){ui.do_show_dialog('welcome',[true]);}else{ui.do_show_dialog('welcome');}}
function _select_file(){if(create=='file'){ui.set_state();ui.do_show_dialog('add_file');}else{ui.do_choose_file(filename,linenum);}}
var current_app=ui.get_app();var current_app_path=current_app?current_app.get_versioned_path():null;if(appid&&current_app&&appid==current_app_path){ui.refresh_app_templates();_select_file();return;}
ui.do_hide_overlays();ui.do_hide_welcome();$('.refresh').hide();if(!appid){_no_app();return;}
if(current_app){current_app.destroy();}
ui.refresh_app_templates('loading');var new_app=new AcreApp(ui.get_store(),appid);new_app.t_load().onready(function(){_current_app=new_app;ui.add_recent('apps',{path:new_app.get_path(),name:new_app.get_display_name()});_current_file=null;ui.refresh_app_templates();_select_file();}).onerror(function(code,message,info){if(code=='/service/get_app/no_app'){ui.MessagePanel.error(message?message:'Error loading app: '+appid+'. '+message||'');_no_app();}else{assert.critical(false,"Error connecting to Freebase<br/>"+message);mjt.error(code,message,info);ui.clear_state();ui.set_state();ui.refresh_app_templates('open');}});};ui.do_choose_file=function(filename,linenum){_changing_state=true;function _show_file(){var file=ui.get_file();if(!file){return ui.refresh_file_templates();}
var editor_name=ui._get_desired_editor_classname();file.t_editor_show(editor_name,ui.get_editor_prefs()).onready(function(){if(!linenum){linenum=file.get_editor_linenum();}
if(linenum){setTimeout(function(){file.editor_goto_line(linenum);},0);}
ui.refresh_file_templates();ui.set_state();});}
var app=ui.get_app();var old_file=ui.get_file();var file=app.get_file(filename);if(!file){file=app.get_file();}
if(!file||file==old_file){_show_file(linenum);return;}
_current_file=file;_current_file_is_dirty=file.is_dirty();if(!file.is_editor_loaded()){$('#file-area').append(file.get_element());ui._register_editor_event_handlers(file);}
if(old_file){old_file.hide();}
$(file.get_element()).show();_show_file(linenum);};ui.do_run_view=function(args,preview){var file=ui.get_file();if(file.get_acre_handler()=="mqlquery"){file._current_editor.query_run();return;}
var preview_url=ui.get_file().get_acre_url(preview);var PreviewWindow=window.open('about:blank',ui.get_app().get_path().replace(/[\/-]/g,'_'));if(!PreviewWindow){ui.MessagePanel.error("A window couldn't be opened.  Tell your web browser to allow this site to open pop up windows and try again to continue.");return false;}
ui.do_app_save_all(function(){PreviewWindow.location=preview_url;PreviewWindow.focus();});};ui.do_account_link=function(kind){location.href=ui.get_store().get_user_account_url(kind);return false;};ui.do_acre_home_link=function(path){location.href=ui.get_store().get_acre_home_url(path);return false;};ui.do_app_create_new=function(appid,display_name,clone_id){var args={appid:appid};if(display_name){args.name=display_name;}
if(clone_id){args.clone=clone_id;}
ui.MessagePanel.doing('Creating: '+display_name+'...');ui.get_store().Xhr("create_app",args).enqueue().onready(function(user_apps){ui.MessagePanel.info('Created: '+display_name);ui.do_choose_app(appid)
ui.get_store().set_user_apps(user_apps);}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error creating: '+key+'. '+message||'');});};ui.do_app_move=function(new_path){var app=ui.get_app();var old_path=app.get_path();_changing_state=true;ui.MessagePanel.doing("Moving app...");app.t_move(new_path).onready(function(r){ui.set_state();ui.add_recent('apps',{path:app.get_path(),name:app.get_display_name()},old_path);ui.get_store().t_refresh_user_apps();ui.MessagePanel.info("App moved to "+new_path);}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error moving: '+app.get_display_name());});};ui.do_app_set_host=function(host){var app=ui.get_app();ui.MessagePanel.doing("Updating release URL for "+app.get_display_name()+"...");app.t_set_host(host).onready(function(){ui.MessagePanel.info("Release URL updated");$('#app-hosts-list').mjt(ui.templates.app_hosts_list());}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error updating release URL for: '+app.get_display_name());});};ui.do_app_set_release=function(version){var app=ui.get_app();ui.MessagePanel.doing("Updating release of "+app.get_display_name()+"...");app.t_set_release(version).onready(function(){ui.MessagePanel.info("Release updated to "+version);$('#app-versions-add').mjt(ui.templates.app_versions_list());$('#app-hosts-list').mjt(ui.templates.app_hosts_list());}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error releasing: '+app.get_display_name());});};ui.do_app_add_version=function(key){var app=ui.get_app();ui.MessagePanel.doing("Creating version "+key);app.t_add_version(key).onready(function(){ui.MessagePanel.info("Created version "+key);$('#app-versions-add').mjt(ui.templates.app_versions_list());}).onerror(function(code,msg,full,task){ui.MessagePanel.error('Failed to add version. '+msg);});};ui.do_app_remove_version=function(key){var app=ui.get_app();ui.MessagePanel.doing("Removing version "+key);app.t_remove_version(key).onready(function(r){ui.MessagePanel.info("Removing version "+key);$('#app-versions-add').mjt(ui.templates.app_versions_list(r));});};ui.do_app_set_listing=function(new_name,new_description,listed){var app=ui.get_app();ui.MessagePanel.doing("Updating app name...");app.t_set_listing(new_name,new_description,listed).onready(function(){if(new_name){ui.add_recent('apps',{path:app.get_path(),name:app.get_display_name()},app.get_path());}
ui.MessagePanel.info("Updated app name");ui.refresh_app_templates();}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error changing app name');});};ui.do_app_add_author=function(username){var app=ui.get_app();app.t_add_author(username).onready(function(){var authors=ui.get_app().get_authors();$('#app-authors-list').mjt(ui.templates.app_authors_list(authors));});};ui.do_app_remove_author=function(username){var app=ui.get_app();app.t_remove_author(username).onready(function(){var authors=ui.get_app().get_authors();$('#app-authors-list').mjt(ui.templates.app_authors_list(authors));});};ui.do_app_set_write_permissions=function(type){var app=ui.get_app();ui.MessagePanel.doing('Setting write permissions...');app.t_set_write_permissions(type,ui.get_user()).onready(function(r){ui.MessagePanel.info('New write permissions set.');}).onerror(function(code,msg,full,task){ui.MessagePanel.error('Failed to change write permissions: '+msg);});};ui.do_app_add_apikey=function(name,key,secret){var app=ui.get_app();ui.MessagePanel.doing("Adding API key for "+name+"...");app.t_add_apikey(name,key,secret).onready(function(r){ui.MessagePanel.info(name+" API key added.");$('#app-apikeys-add').mjt(ui.templates.app_apikeys_list(r.keys));}).onerror(function(code,msg,full,task){ui.MessagePanel.error('Failed to add API key: '+msg);});};ui.do_app_remove_apikey=function(name){var app=ui.get_app();ui.MessagePanel.doing("Deleting API key for "+name+"...");app.t_remove_apikey(name).onready(function(r){ui.MessagePanel.info(name+" API key deleted.");$('#app-apikeys-add').mjt(ui.templates.app_apikeys_list(r.keys));}).onerror(function(code,msg,full,task){ui.MessagePanel.error('Failed to delete API key: '+msg);});};ui.do_app_save_all=function(callback){var app=ui.get_app();if(!app.is_dirty()){callback();return;}
ui.MessagePanel.doing("Saving all files...");app.t_save_all().onready(function(){ui.MessagePanel.info("All files saved.");ui.refresh_file_templates();setTimeout(callback,500);}).onerror(function(code,msg,full,task){ui.MessagePanel.error('Failed to save all files: '+msg);});};ui.do_app_delete=function(){var app=ui.get_app();ui.MessagePanel.doing('Deleting: '+app.get_display_name()+'...');app.t_delete().onready(function(user_apps){ui.get_store().set_user_apps(user_apps);ui.MessagePanel.info('Deleted app');_current_app=null;var recent_apps=ui.get_recents('apps',true);if(recent_apps.length>0){var last_app=recent_apps.shift();$.localStore('recent_apps',recent_apps,false);}
ui.do_choose_app();}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error deleting: '+app.get_display_name());});};ui.do_file_create_new=function(name,metadata,state){if(ui.get_app().get_file(name)){ui.MessagePanel.error('File with that name already exists');return;}
var file=new AcreDoc(ui.get_app(),name,metadata,state);ui.do_choose_file(file.get_name());};ui.do_file_set_acre_handler=function(acre_handler){var file=ui.get_file();file.set_acre_handler(acre_handler);ui.do_choose_file(file.get_name());};ui.do_file_set_mime_type=function(mime_type){var file=ui.get_file();file.set_mime_type(mime_type);ui.do_choose_file(file.get_name());};ui.do_file_save=function(force){var file=ui.get_file();if(!file.is_dirty()){return;}
ui.MessagePanel.doing('Saving file: '+file.get_name()+'...');file.t_save(force).enqueue().onready(function(r){file.t_editor_show(ui._get_desired_editor_classname(),ui.get_editor_prefs());ui.refresh_file_templates();ui.MessagePanel.info('File saved: '+file.get_name());}).onerror(function(code,message,info){if(code=="/api/status/error/upload/content_mismatch"){ui.MessagePanel.error('Saved version of this file has changed since it was loaded.');ui.do_show_dialog("file_save_conflict",[info.info.existing_content,info.info.requested_content]);}else if(code=="/api/status/error/auth"){ui.MessagePanel.error('You are not currently signed in.  To not lose your changes, sign in in a new tab or window and then try again.');}else{ui.MessagePanel.error(message||'Error saving: '+file.get_name());}
file.t_editor_show(ui._get_desired_editor_classname(),ui.get_editor_prefs());ui.refresh_file_templates();});};ui.do_file_save_as=function(app_path,new_name){var old_file=ui.get_file();var new_app=(app_path==old_file.get_app().get_path())?old_file.get_app():new AcreApp(ui.get_store(),app_path);var new_file_props={acre_handler:old_file.get_acre_handler(),content_type:old_file.get_mime_type(),based_on:old_file.get_app().get_path()+'/'+mjt.freebase.mqlkey_quote(old_file.get_name())};var new_file=new AcreDoc(new_app,new_name,new_file_props,old_file.get_editor_state());ui.MessagePanel.doing('Saving file as: '+new_name+'...');new_file.t_save().enqueue().onready(function(r){if(new_app==ui.get_app()){ui.do_choose_file(new_file.get_name());}else{new_app.destroy();}
ui.MessagePanel.info('File created: '+new_name);}).onerror(function(code,message,info){if(info&&info.code=="/api/status/error/auth"){ui.MessagePanel.error('You are not currently signed in.  To not lose your changes, sign in in a new tab or window and then try again.');}else{ui.MessagePanel.error(message||'Error creating: '+new_name);}});};ui.do_file_revert=function(revision){var file=ui.get_file();if(!revision){revision=file.get_revision();}
ui.MessagePanel.doing('Reverting file: '+file.get_name()+'...');file.t_revert(revision).onready(function(){ui.MessagePanel.info('File reverted: '+file.get_name());ui.refresh_file_templates();}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error reverting: '+file.get_name());});};ui.do_file_move=function(new_name,status_el){var file=ui.get_file();var old_name=file.get_name();if(new_name==old_name){return;}
if(ui.get_app().get_file(new_name)){ui.MessagePanel.error('The name "'+new_name+'" is already taken. Please choose a different name.',status_el);return;}
ui.MessagePanel.doing('Renaming...',status_el);file.t_move(new_name).onready(function(r){ui.MessagePanel.info('File renamed to "'+new_name+'".',status_el);$('#button-name').attr('disabled','disabled');ui.do_choose_file(file.get_name());}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error naming file: '+file.get_name(),status_el);});};ui.do_file_delete=function(filename){var file=filename?ui.get_app().get_file(filename):ui.get_file();ui.MessagePanel.doing('Deleting file:'+file.get_name()+'...');file.t_delete().onready(function(r){ui.MessagePanel.info('File deleted: '+file.get_name());_current_file=null;ui.do_choose_file();}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error deleting: '+file.get_name());});};ui.do_file_clone=function(app_path,new_name){var file=ui.get_file();ui.MessagePanel.doing('Cloning file:'+file.get_name()+'...');file.t_clone(app_path,new_name).onready(function(file_data){ui.MessagePanel.info('File cloned: '+file.get_name()+' to '+app_path);if(app_path==ui.get_app().get_path()){var new_file=new AcreDoc(file.get_app(),file_data.name,file_data.metadata);ui.do_choose_file(new_file.get_name());}}).onerror(function(code,message,info){ui.MessagePanel.error(message?message:'Error cloning: '+file.get_name());});};ui.do_file_editor_undo=function(){var file=ui.get_file();file.editor_undo();};ui.do_file_editor_redo=function(){var file=ui.get_file();file.editor_redo();};ui.do_file_editor_goto_line=function(linenum){var file=ui.get_file();file.editor_goto_line(linenum);};ui.do_file_editor_indent=function(){var file=ui.get_file();file.editor_indent();};function decrock_html(text){text=text.replace(/<style[^>]+>/g,'<style>');text=text.replace(/type=['"]text\/(css|javascript)['"]/g,'');return text;}
function decrock_acre(text){text=text.replace(/<acre:script>/g,'<script>').replace(/<\/acre:script>/g,'</script>');text=text.replace(/<\/?acre:block[^>]*>/g,'');text=text.replace(/<([^>]+) acre:[^>]+/g,'<$1>');text=decrock_html(text);return text;}
function decrock_css(text){if(!(/^\s*@charset\s+"UTF-8";/.test(text))){text='@charset "UTF-8"; '+text;}
return text;}
ui.get_file_check_options=function(){var options={bitwise:true,eqeqeq:true,forin:true,sub:true,undef:true,useful:1};var acre_predef=['acre','JSON','XMLHttpRequest','console','mjt'];switch(ui.get_file().get_acre_handler()){case'mqlquery':break;case'acre_script':options.predef=acre_predef;break;case'mjt':options.useful=0;options.predef=acre_predef;options.before_check=decrock_acre;break;case'passthrough':options.browser=true;switch(ui.get_file().get_mime_type()){case'application/json':break;case'text/javascript':break;case'text/html':options.before_check=decrock_html;break;case'text/css':options.before_check=decrock_css;break;case'text/plain':options.useful=0;break;default:options.useful=-1;break;}
break;default:options.useful=-1;break;}
return options;};function _display_jslint_error(err_div,extra){var msg=err_div.attr('title');ui.MessagePanel.clear();ui.MessagePanel.error(msg+(extra||''));var linenum=err_div.text();ui.get_file().editor_goto_line(linenum);}
ui.do_click_error=function(e){var target=$(e.target);if(target.hasClass('jslint-error')){_display_jslint_error(target);}};ui.do_file_check=function(){ui.do_hide_overlays();var linenumber_container=$('.CodeMirror-line-numbers,.editor-margin-line-numbers',ui.get_file().get_element());$('>div.jslint-error',linenumber_container).attr('title','').removeClass('jslint-error');ui.MessagePanel.clear();var jslint_options=ui.get_file_check_options();assert.critical(jslint_options,'missing jslint_options');var source_code=ui.get_file().get_editor_state().text;if(jslint_options.before_check){source_code=jslint_options.before_check(source_code);}
var ok=JSLINT(source_code,jslint_options);if(ok){ui.MessagePanel.info('No syntax errors found');}else{var errors=JSLINT.errors;var popup_text='Found '+errors.length+' errors.  Click any of the red line numbers below to see corresponding error details.';var linenumbers=$('>div',linenumber_container);if(!linenumbers.length){errors=errors.slice(0,3);popup_text=$.map(errors,function(e){if(e){return'Line: '+e.line+' '+e.reason;}});}else{for(var i=0;i<errors.length;i++){var e=errors[i];if(e){var line=linenumbers.eq(e.line);line.addClass('jslint-error');line.attr('title',line.attr('title')+' '+e.reason);}}}
ui.MessagePanel.error(popup_text);ui.get_file().editor_goto_line(errors[0].line+1);}};var DEFAULT_PREFS={syntax:true,margin:true,softwrap:false,dotTrigger:false,flw:200,t_mjt:true,t_acre_script:true,t_mqlquery:true,t_passthrough:true,t_binary:true,emql:false};ui.get_editor_prefs=function(key){function _get_pref(key){var setting=$.localStore(key);if(setting===null){return DEFAULT_PREFS[key];}
else if(setting=='1'){return true;}
else if(setting=='0'){return false;}
else{return setting;}}
if(key){return _get_pref(key);}else{var prefs={};for(var k in DEFAULT_PREFS){prefs[k]=_get_pref(k);}
return prefs;}};ui.set_editor_prefs=function(arg1,arg2){if(arguments.length==1){prefs=arg1;}else if(arguments.length==2){prefs={};prefs[arg1]=arg2;}
for(var key in prefs){var value;if(prefs[key]===true){value='1';}
else if(prefs[key]===false){value='0';}
else{value=prefs[key];}
$.localStore(key,value);}};ui._get_desired_editor_classname=function(){var file=this.get_file();var acre_handler=file.get_acre_handler();if(acre_handler=='binary'){return"ImageEditor";}else if(acre_handler=='mqlquery'){return"QueryEditor";}else{if(ui.get_editor_prefs('syntax')){assert.critical(typeof CodeMirror!=="undefined","CodeMirror has not initalized. (Metaweb internal: did you run ./codemirror/build.sh)");return"CodeMirror";}else{return"TextareaEditor";}}
assert.critical(false,"Could not deterime editor to use");return null;};ui._register_editor_event_handlers=function(file){file.register_editor_event_handlers({change:ui.editor_change_handler,linechange:ui.editor_linechange_handler,newframe:ui.editor_newframe_handler});};ui.editor_change_handler=function(undos,redos){if(_current_file_is_dirty!=ui.get_file().is_dirty()){ui.refresh_file_templates();}
if(undos>0){if(!ui._has_undos){$('#button-undo').removeAttr('disabled');}
ui._has_undos=true;}else{if(ui._has_undos){$('#button-undo').attr('disabled','disabled');}
ui._has_undos=false;}
if(redos>0){if(!ui._has_redos){$('#button-redo').removeAttr('disabled');}
ui._has_redos=true;}else{if(ui._has_redos){$('#button-redo').attr('disabled','disabled');}
ui._has_redos=false;}};ui.editor_linechange_handler=function(linenum){_current_line=linenum;$('#linenumber').val(linenum);};ui.editor_newframe_handler=function(frame){var fdoc=frame.contentWindow?frame.contentWindow.document:frame.contentDocument;ui.shortcut.register_keys(fdoc);};ui.warn_user_about_unsaved_files=function(){if(ui&&ui.get_app()&&ui.get_app().is_dirty()){return"You have unsaved files! The changes you made to these files will be lost if you leave this page.";}else{return undefined;}};ui.get_app_url=function(app_path){return'http://'+ui.get_store().get_app_host(app_path);};ui.get_appeditor_url=function(obj,filename){var app_path;if(typeof obj=='string'){app_path=obj;}else if(obj instanceof AcreDoc){app_path=obj.get_app().get_versioned_path();filename=obj.get_relative_path();}else if(obj instanceof AcreApp){app_path=obj.get_versioned_path();}
var url=window.location.protocol+'//'+window.location.host+window.location.pathname;if(app_path){url+='#app='+app_path;}
if(filename){url+='&file='+filename;}
return url;};ui.get_human_timestamp=function(timestamp){var t=mjt.freebase.date_from_iso(timestamp);return t.toLocaleString();};ui.get_relative_timestamp=function(timestamp){var c=new Date();var t=mjt.freebase.date_from_iso(timestamp);var d=c.getTime()-t.getTime();var dY=Math.floor(d/(365*30*24*60*60*1000));var dM=Math.floor(d/(30*24*60*60*1000));var dD=Math.floor(d/(24*60*60*1000));var dH=Math.floor(d/(60*60*1000));var dN=Math.floor(d/(60*1000));if(dY>0){return dY===1?"1 year ago":dY+" years ago";}
if(dM>0){return dM===1?"1 month ago":dM+" months ago";}
if(dD>0){return dD===1?"1 day ago":dD+" days ago";}
if(dH>0){return dH===1?"1 hour ago":dH+" hours ago";}
if(dN>0){return dN===1?"1 minute ago":dN+" minutes ago";}
if(dN===0){return"less than a minute ago";}
if(dN<0){return"in the future???";}};ui.order_handler_files=function(app){var ordered_filenames={};var files=app.get_files();for(var f in files){handler=files[f].get_acre_handler();if(typeof ordered_filenames[handler]=='undefined'){ordered_filenames[handler]=[];}
ordered_filenames[handler].push(files[f].get_name());}
for(var h in ordered_filenames){ordered_filenames[h].sort(function(a,b){return a.localeCompare(b);});}
return ordered_filenames;};ui.order_lib_files=function(lib){var filenames=[];var files=lib.get_files();for(var f in files){filenames.push(files[f].get_name());}
filenames.sort(function(a,b){return a.localeCompare(b);});return filenames;};ui.watch_inputs=function(button_name,options){function _compare_inputs(){var any_result=false;var result={};jQuery.each(options.inputs,function(input,test){var new_value;var el=$('#'+input)[0];if(typeof el=='undefined'){el=$("input[name='"+input+"']")[0];}
if(typeof el=='undefined'){return;}
if(el.tagName=='TEXTAREA'){new_value=jQuery.trim($('#'+input).val());}else if(el.tagName=='INPUT'){var type=$(el).attr('type');if(type=='text'){new_value=jQuery.trim($('#'+input).val());}
else if(type=='radio'){new_value=$("input[name='"+input+"']:checked").val();}
else if(type=='checkbox'){new_value=$('#'+input).attr('checked');}}else if(el.tagName=='SELECT'){new_value=$('#'+input+' :selected').val();}
if(new_value!=options.inputs[input]){any_result=true;result[input]=new_value;}});return any_result?result:false;}
function _update_inputs(){var res=_compare_inputs();if(res){$('#button-'+button_name).removeAttr('disabled').addClass('button-primary');if(options.change){options.change.apply(this,[res]);}}else{$('#button-'+button_name).attr('disabled','disabled').removeClass('button-primary');}}
function _watch_input(input){$('#'+input).bind('change',function(e){_update_inputs();});}
function _watch_text_input(input){var timer;$('#'+input).bind('keyup',function(e){clearTimeout(timer);timer=setTimeout(_update_inputs,options.text_delay||300);});}
function _watch_radio_input(input){$("input[name='"+input+"']").bind('click',function(){_update_inputs();});}
jQuery.each(options.inputs,function(input,test){var el=$('#'+input)[0];if(typeof el=='undefined'){el=$("input[name='"+input+"']")[0];}
if(typeof el=='undefined'){return;}
if(el.tagName=='TEXTAREA'){_watch_text_input(input,test);}else if(el.tagName=='INPUT'){var type=$(el).attr('type');if(type=='text'){_watch_text_input(input);}
else if(type=='radio'){_watch_radio_input(input);}
else{_watch_input(input);}}else if(el.tagName=='SELECT'){_watch_input(input);}});$('#button-'+button_name).unbind('click').click(function(){var final_changes=_compare_inputs();options.submit.apply(this,[final_changes]);if(options.update_on_submit){jQuery.extend(options.inputs,final_changes);_update_inputs();}});};ui.get_diff=function(text1,text2){var blob1_lines=difflib.stringAsLines(text1);var blob2_lines=difflib.stringAsLines(text2);var matches=new difflib.SequenceMatcher(blob1_lines,blob2_lines);var opc=matches.get_opcodes();var data={baseTextLines:blob1_lines,newTextLines:blob2_lines,opcodes:opc};return data;};ui.MessagePanel=(function(){var SECONDS=1000;var timer;var hide_func;var last_level;function _show(el,log_type,str,duration){if(typeof el==='undefined'){el='#message-panel';}
if(last_level&&last_level==='error'){mjt.error('MessagePanel: Already displaying error. Ignoring: '+log_type+': '+str);}else{$(el).hide().mjt(ui.templates.message_panel(log_type,str));last_level=log_type;window.clearTimeout(timer);hide_func=function(){$(el).empty();hide_func=null;last_level=null;};timer=window.setTimeout(hide_func,duration);$(el).slideDown(300);}}
function _clear(){window.clearTimeout(timer);if(hide_func){hide_func();}}
return{doing:function(str,el){_show(el,'doing',str,2000*SECONDS);return'';},info:function(str,el){_show(el,'info',str,4*SECONDS);return'';},error:function(str,el){_show(el,'error',str,6*SECONDS);return'';},clear:_clear};})();ui.shortcut={};(function(){var shortcut_config=[{op:'Code Assist'},{op:'Open App',key:'O',action:function(){ui.do_show_menu('apps',[true]);}},{op:'Save File',key:'S',action:function(){ui.do_file_save();}},{op:'View',key:'Shift-P',action:function(){ui.do_run_view(null,false);}},{op:'View with Console',key:'P',action:function(){ui.do_run_view(null,true);}},{op:'Undo',key:'Z',action:function(){ui.do_file_editor_undo();}},{op:'Redo',key:'Shift-Z',action:function(){ui.do_file_editor_redo();}},{op:'Redo',key:'Y',action:function(){ui.do_file_editor_redo();}},{op:'Check Syntax',key:'Shift-C',action:function(){ui.do_file_check();}},{op:'Indent Selection',key:'Shift-I',action:function(){ui.do_file_editor_indent();}},{op:'Jump to Line',key:'J',action:function(){$('#linenumber').focus().select();}}];var _isMac=(navigator.platform.indexOf('Mac')===0);var modifier=_isMac?'Meta':'Ctrl';ui.shortcut.register_keys=function(target){$.each(shortcut_config,function(i,config){var keys=modifier+'-'+config.key;var func=config.action;shortcut.add(keys,func,{target:target});});};ui.shortcut.get_shortcuts=function(){return shortcut_config;};ui.shortcut.get_keys=function(op){var key;if(op=='Code Assist'){key=(navigator.platform.indexOf('Mac')===0?'Alt-':'Ctrl-')+'Space';}else{$.each(shortcut_config,function(i,config){if(config.op==op){key=(navigator.platform.indexOf('Mac')===0?'&#8984;-':'Ctrl-')+config.key;}});}
return key;};})();})();;"use strict";JSLINT=(function(){var adsafe_id,adsafe_may,adsafe_went,anonname,approved,atrule={'import':true,media:true,'font-face':true,page:true},banned={apply:true,'arguments':true,call:true,callee:true,caller:true,constructor:true,'eval':true,prototype:true,unwatch:true,valueOf:true,watch:true},boolOptions={adsafe:true,bitwise:true,browser:true,cap:true,css:true,debug:true,eqeqeq:true,evil:true,forin:true,fragment:true,immed:true,laxbreak:true,newcap:true,nomen:true,on:true,onevar:true,passfail:true,plusplus:true,regexp:true,rhino:true,undef:true,safe:true,sidebar:true,strict:true,sub:true,white:true,widget:true},browser={alert:true,blur:true,clearInterval:true,clearTimeout:true,close:true,closed:true,confirm:true,console:true,Debug:true,defaultStatus:true,document:true,event:true,focus:true,frames:true,getComputedStyle:true,history:true,Image:true,length:true,location:true,moveBy:true,moveTo:true,name:true,navigator:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:true,opener:true,opera:true,Option:true,parent:true,print:true,prompt:true,resizeBy:true,resizeTo:true,screen:true,scroll:true,scrollBy:true,scrollTo:true,setInterval:true,setTimeout:true,status:true,top:true,XMLHttpRequest:true},cssAttributeData,cssAny,cssColorData={"aliceblue":true,"antiquewhite":true,"aqua":true,"aquamarine":true,"azure":true,"beige":true,"bisque":true,"black":true,"blanchedalmond":true,"blue":true,"blueviolet":true,"brown":true,"burlywood":true,"cadetblue":true,"chartreuse":true,"chocolate":true,"coral":true,"cornflowerblue":true,"cornsilk":true,"crimson":true,"cyan":true,"darkblue":true,"darkcyan":true,"darkgoldenrod":true,"darkgray":true,"darkgreen":true,"darkkhaki":true,"darkmagenta":true,"darkolivegreen":true,"darkorange":true,"darkorchid":true,"darkred":true,"darksalmon":true,"darkseagreen":true,"darkslateblue":true,"darkslategray":true,"darkturquoise":true,"darkviolet":true,"deeppink":true,"deepskyblue":true,"dimgray":true,"dodgerblue":true,"firebrick":true,"floralwhite":true,"forestgreen":true,"fuchsia":true,"gainsboro":true,"ghostwhite":true,"gold":true,"goldenrod":true,"gray":true,"green":true,"greenyellow":true,"honeydew":true,"hotpink":true,"indianred":true,"indigo":true,"ivory":true,"khaki":true,"lavender":true,"lavenderblush":true,"lawngreen":true,"lemonchiffon":true,"lightblue":true,"lightcoral":true,"lightcyan":true,"lightgoldenrodyellow":true,"lightgreen":true,"lightpink":true,"lightsalmon":true,"lightseagreen":true,"lightskyblue":true,"lightslategray":true,"lightsteelblue":true,"lightyellow":true,"lime":true,"limegreen":true,"linen":true,"magenta":true,"maroon":true,"mediumaquamarine":true,"mediumblue":true,"mediumorchid":true,"mediumpurple":true,"mediumseagreen":true,"mediumslateblue":true,"mediumspringgreen":true,"mediumturquoise":true,"mediumvioletred":true,"midnightblue":true,"mintcream":true,"mistyrose":true,"moccasin":true,"navajowhite":true,"navy":true,"oldlace":true,"olive":true,"olivedrab":true,"orange":true,"orangered":true,"orchid":true,"palegoldenrod":true,"palegreen":true,"paleturquoise":true,"palevioletred":true,"papayawhip":true,"peachpuff":true,"peru":true,"pink":true,"plum":true,"powderblue":true,"purple":true,"red":true,"rosybrown":true,"royalblue":true,"saddlebrown":true,"salmon":true,"sandybrown":true,"seagreen":true,"seashell":true,"sienna":true,"silver":true,"skyblue":true,"slateblue":true,"slategray":true,"snow":true,"springgreen":true,"steelblue":true,"tan":true,"teal":true,"thistle":true,"tomato":true,"turquoise":true,"violet":true,"wheat":true,"white":true,"whitesmoke":true,"yellow":true,"yellowgreen":true},cssBorderStyle,cssLengthData={'%':true,'cm':true,'em':true,'ex':true,'in':true,'mm':true,'pc':true,'pt':true,'px':true},escapes={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','/':'\\/','\\':'\\\\'},funct,functions,global,htmltag={a:{},abbr:{},acronym:{},address:{},applet:{},area:{empty:true,parent:' map '},b:{},base:{empty:true,parent:' head '},bdo:{},big:{},blockquote:{},body:{parent:' html noframes '},br:{empty:true},button:{},canvas:{parent:' body p div th td '},caption:{parent:' table '},center:{},cite:{},code:{},col:{empty:true,parent:' table colgroup '},colgroup:{parent:' table '},dd:{parent:' dl '},del:{},dfn:{},dir:{},div:{},dl:{},dt:{parent:' dl '},em:{},embed:{},fieldset:{},font:{},form:{},frame:{empty:true,parent:' frameset '},frameset:{parent:' html frameset '},h1:{},h2:{},h3:{},h4:{},h5:{},h6:{},head:{parent:' html '},html:{parent:'*'},hr:{empty:true},i:{},iframe:{},img:{empty:true},input:{empty:true},ins:{},kbd:{},label:{},legend:{parent:' fieldset '},li:{parent:' dir menu ol ul '},link:{empty:true,parent:' head '},map:{},menu:{},meta:{empty:true,parent:' head noframes noscript '},noframes:{parent:' html body '},noscript:{parent:' body head noframes '},object:{},ol:{},optgroup:{parent:' select '},option:{parent:' optgroup select '},p:{},param:{empty:true,parent:' applet object '},pre:{},q:{},samp:{},script:{empty:true,parent:' body div frame head iframe p pre span '},select:{},small:{},span:{},strong:{},style:{parent:' head ',empty:true},sub:{},sup:{},table:{},tbody:{parent:' table '},td:{parent:' tr '},textarea:{},tfoot:{parent:' table '},th:{parent:' tr '},thead:{parent:' table '},title:{parent:' head '},tr:{parent:' table tbody thead tfoot '},tt:{},u:{},ul:{},'var':{}},ids,implied,inblock,indent,jsonmode,lines,lookahead,member,membersOnly,nexttoken,noreach,option,predefined,prereg,prevtoken,pseudorule={'first-child':true,link:true,visited:true,hover:true,active:true,focus:true,lang:true,'first-letter':true,'first-line':true,before:true,after:true},rhino={defineClass:true,deserialize:true,gc:true,help:true,load:true,loadClass:true,print:true,quit:true,readFile:true,readUrl:true,runCommand:true,seal:true,serialize:true,spawn:true,sync:true,toint32:true,version:true},scope,sidebar={System:true},src,stack,standard={Array:true,Boolean:true,Date:true,decodeURI:true,decodeURIComponent:true,encodeURI:true,encodeURIComponent:true,Error:true,'eval':true,EvalError:true,Function:true,isFinite:true,isNaN:true,JSON:true,Math:true,Number:true,Object:true,parseInt:true,parseFloat:true,RangeError:true,ReferenceError:true,RegExp:true,String:true,SyntaxError:true,TypeError:true,URIError:true},standard_member={E:true,LN2:true,LN10:true,LOG2E:true,LOG10E:true,PI:true,SQRT1_2:true,SQRT2:true,MAX_VALUE:true,MIN_VALUE:true,NEGATIVE_INFINITY:true,POSITIVE_INFINITY:true},syntax={},tab,token,urls,warnings,widget={alert:true,animator:true,appleScript:true,beep:true,bytesToUIString:true,Canvas:true,chooseColor:true,chooseFile:true,chooseFolder:true,closeWidget:true,COM:true,convertPathToHFS:true,convertPathToPlatform:true,CustomAnimation:true,escape:true,FadeAnimation:true,filesystem:true,Flash:true,focusWidget:true,form:true,FormField:true,Frame:true,HotKey:true,Image:true,include:true,isApplicationRunning:true,iTunes:true,konfabulatorVersion:true,log:true,md5:true,MenuItem:true,MoveAnimation:true,openURL:true,play:true,Point:true,popupMenu:true,preferenceGroups:true,preferences:true,print:true,prompt:true,random:true,Rectangle:true,reloadWidget:true,ResizeAnimation:true,resolvePath:true,resumeUpdates:true,RotateAnimation:true,runCommand:true,runCommandInBg:true,saveAs:true,savePreferences:true,screen:true,ScrollBar:true,showWidgetPreferences:true,sleep:true,speak:true,Style:true,suppressUpdates:true,system:true,tellWidget:true,Text:true,TextArea:true,Timer:true,unescape:true,updateNow:true,URL:true,Web:true,widget:true,Window:true,XMLDOM:true,XMLHttpRequest:true,yahooCheckLogin:true,yahooLogin:true,yahooLogout:true},xmode,xquote,ax=/@cc|<\/?|script|\]*s\]|<\s*!|&lt/i,cx=/[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,tx=/^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(global|extern|jslint|member|members)?|=|\/)?|\*[\/=]?|\+[+=]?|-[\-=]?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/,hx=/^\s*(['"=>\/&#]|<(?:\/|\!(?:--)?)?|[a-zA-Z][a-zA-Z0-9_\-]*|[0-9]+|--|.)/,nx=/[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,nxg=/[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,ox=/[>&]|<[\/!]?|--/,lx=/\*\/|\/\*/,ix=/^([a-zA-Z_$][a-zA-Z0-9_$]*)$/,jx=/^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i,ux=/&|\+|\u00AD|\.\.|\/\*|%[^;]|base64|url|expression|data|mailto/i,sx=/^\s*([{:#*%.=,>+\[\]@()"';*]|[a-zA-Z0-9_][a-zA-Z0-9_\-]*|<\/|\/\*)/,ssx=/^\s*([@#!"'};:\-%.=,+\[\]()*_]|[a-zA-Z][a-zA-Z0-9._\-]*|\/\*?|\d+(?:\.\d+)?|<\/)/,qx=/[^a-zA-Z0-9-_\/ ]/,dx=/[\[\]\/\\"'*<>.&:(){}+=#]/,rx={outer:hx,html:hx,style:sx,styleproperty:ssx};function F(){}
if(typeof Object.create!=='function'){Object.create=function(o){F.prototype=o;return new F();};}
function combine(t,o){var n;for(n in o){if(o.hasOwnProperty(n)){t[n]=o[n];}}}
String.prototype.entityify=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');};String.prototype.isAlpha=function(){return(this>='a'&&this<='z\uffff')||(this>='A'&&this<='Z\uffff');};String.prototype.isDigit=function(){return(this>='0'&&this<='9');};String.prototype.supplant=function(o){return this.replace(/\{([^{}]*)\}/g,function(a,b){var r=o[b];return typeof r==='string'||typeof r==='number'?r:a;});};String.prototype.name=function(){if(ix.test(this)){return this;}
if(nx.test(this)){return'"'+this.replace(nxg,function(a){var c=escapes[a];if(c){return c;}
return'\\u'+('0000'+a.charCodeAt().toString(16)).slice(-4);})+'"';}
return'"'+this+'"';};function assume(){if(!option.safe){if(option.rhino){combine(predefined,rhino);}
if(option.browser||option.sidebar){combine(predefined,browser);}
if(option.sidebar){combine(predefined,sidebar);}
if(option.widget){combine(predefined,widget);}}}
function quit(m,l,ch){throw{name:'JSLintError',line:l,character:ch,message:m+" ("+Math.floor((l/lines.length)*100)+"% scanned)."};}
function warning(m,t,a,b,c,d){var ch,l,w;t=t||nexttoken;if(t.id==='(end)'){t=token;}
l=t.line||0;ch=t.from||0;w={id:'(error)',raw:m,evidence:lines[l]||'',line:l,character:ch,a:a,b:b,c:c,d:d};w.reason=m.supplant(w);JSLINT.errors.push(w);if(option.passfail){quit('Stopping. ',l,ch);}
warnings+=1;if(warnings===50){quit("Too many errors.",l,ch);}
return w;}
function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d);}
function error(m,t,a,b,c,d){var w=warning(m,t,a,b,c,d);quit("Stopping, unable to continue.",w.line,w.character);}
function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d);}
var lex=(function lex(){var character,from,line,s;function nextLine(){var at;line+=1;if(line>=lines.length){return false;}
character=0;s=lines[line].replace(/\t/g,tab);at=s.search(cx);if(at>=0){warningAt("Unsafe character.",line,at);}
return true;}
function it(type,value){var i,t;if(type==='(color)'){t={type:type};}else if(type==='(punctuator)'||(type==='(identifier)'&&syntax.hasOwnProperty(value))){t=syntax[value]||syntax['(error)'];if(!t.id){t=syntax[type];}}else{t=syntax[type];}
t=Object.create(t);if(type==='(string)'||type==='(range)'){if(jx.test(value)){warningAt("Script URL.",line,from);}}
if(type==='(identifier)'){t.identifier=true;if(option.nomen&&value.charAt(0)==='_'){warningAt("Unexpected '_' in '{a}'.",line,from,value);}}
t.value=value;t.line=line;t.character=character;t.from=from;i=t.id;if(i!=='(endline)'){prereg=i&&(('(,=:[!&|?{};'.indexOf(i.charAt(i.length-1))>=0)||i==='return');}
return t;}
return{init:function(source){if(typeof source==='string'){lines=source.replace(/\r\n/g,'\n').replace(/\r/g,'\n').split('\n');}else{lines=source;}
line=-1;nextLine();from=0;},range:function(begin,end){var c,value='';from=character;if(s.charAt(0)!==begin){errorAt("Expected '{a}' and instead saw '{b}'.",line,character,begin,s.charAt(0));}
for(;;){s=s.slice(1);character+=1;c=s.charAt(0);switch(c){case'':errorAt("Missing '{a}'.",line,character,c);break;case end:s=s.slice(1);character+=1;return it('(range)',value);case xquote:case'\\':case'\'':case'"':warningAt("Unexpected '{a}'.",line,character,c);}
value+=c;}},token:function(){var b,c,captures,d,depth,high,i,l,low,q,t;function match(x){var r=x.exec(s),r1;if(r){l=r[0].length;r1=r[1];c=r1.charAt(0);s=s.substr(l);character+=l;from=character-r1.length;return r1;}}
function string(x){var c,j,r='';if(jsonmode&&x!=='"'){warningAt("Strings must use doublequote.",line,character);}
if(xquote===x||(xmode==='scriptstring'&&!xquote)){return it('(punctuator)',x);}
function esc(n){var i=parseInt(s.substr(j+1,n),16);j+=n;if(i>=32&&i<=126&&i!==34&&i!==92&&i!==39){warningAt("Unnecessary escapement.",line,character);}
character+=n;c=String.fromCharCode(i);}
j=0;for(;;){while(j>=s.length){j=0;if(xmode!=='html'||!nextLine()){errorAt("Unclosed string.",line,from);}}
c=s.charAt(j);if(c===x){character+=1;s=s.substr(j+1);return it('(string)',r,x);}
if(c<' '){if(c==='\n'||c==='\r'){break;}
warningAt("Control character in string: {a}.",line,character+j,s.slice(0,j));}else if(c===xquote){warningAt("Bad HTML string",line,character+j);}else if(c==='<'){if(option.safe&&xmode==='html'){warningAt("ADsafe string violation.",line,character+j);}else if(s.charAt(j+1)==='/'&&(xmode||option.safe)){warningAt("Expected '<\\/' and instead saw '</'.",line,character);}else if(s.charAt(j+1)==='!'&&(xmode||option.safe)){warningAt("Unexpected '<!' in a string.",line,character);}}else if(c==='\\'){if(xmode==='html'){if(option.safe){warningAt("ADsafe string violation.",line,character+j);}}else if(xmode==='styleproperty'){j+=1;character+=1;c=s.charAt(j);if(c!==x){warningAt("Escapement in style string.",line,character+j);}}else{j+=1;character+=1;c=s.charAt(j);switch(c){case xquote:warningAt("Bad HTML string",line,character+j);break;case'\\':case'\'':case'"':case'/':break;case'b':c='\b';break;case'f':c='\f';break;case'n':c='\n';break;case'r':c='\r';break;case't':c='\t';break;case'u':esc(4);break;case'v':c='\v';break;case'x':if(jsonmode){warningAt("Avoid \\x-.",line,character);}
esc(2);break;default:warningAt("Bad escapement.",line,character);}}}
r+=c;character+=1;j+=1;}}
for(;;){if(!s){return it(nextLine()?'(endline)':'(end)','');}
while(xmode==='outer'){i=s.search(ox);if(i===0){break;}else if(i>0){character+=1;s=s.slice(i);break;}else{if(!nextLine()){return it('(end)','');}}}
t=match(rx[xmode]||tx);if(!t){if(xmode==='html'){return it('(error)',s.charAt(0));}else{t='';c='';while(s&&s<'!'){s=s.substr(1);}
if(s){errorAt("Unexpected '{a}'.",line,character,s.substr(0,1));}}}else{if(c.isAlpha()||c==='_'||c==='$'){return it('(identifier)',t);}
if(c.isDigit()){if(xmode!=='style'&&!isFinite(Number(t))){warningAt("Bad number '{a}'.",line,character,t);}
if(xmode!=='styleproperty'&&s.substr(0,1).isAlpha()){warningAt("Missing space after '{a}'.",line,character,t);}
if(c==='0'){d=t.substr(1,1);if(d.isDigit()){if(token.id!=='.'&&xmode!=='styleproperty'){warningAt("Don't use extra leading zeros '{a}'.",line,character,t);}}else if(jsonmode&&(d==='x'||d==='X')){warningAt("Avoid 0x-. '{a}'.",line,character,t);}}
if(t.substr(t.length-1)==='.'){warningAt("A trailing decimal point can be confused with a dot '{a}'.",line,character,t);}
return it('(number)',t);}
switch(t){case'"':case"'":return string(t);case'//':if(src||(xmode&&xmode!=='script')){warningAt("Unexpected comment.",line,character);}else if(xmode==='script'&&/<\s*\//i.test(s)){warningAt("Unexpected <\/ in comment.",line,character);}else if((option.safe||xmode==='script')&&ax.test(s)){warningAt("Dangerous comment.",line,character);}
s='';token.comment=true;break;case'/*':if(src||(xmode&&xmode!=='script'&&xmode!=='style'&&xmode!=='styleproperty')){warningAt("Unexpected comment.",line,character);}
if(option.safe&&ax.test(s)){warningAt("ADsafe comment violation.",line,character);}
for(;;){i=s.search(lx);if(i>=0){break;}
if(!nextLine()){errorAt("Unclosed comment.",line,character);}else{if(option.safe&&ax.test(s)){warningAt("ADsafe comment violation.",line,character);}}}
character+=i+2;if(s.substr(i,1)==='/'){errorAt("Nested comment.",line,character);}
s=s.substr(i+2);token.comment=true;break;case'/*global':case'/*extern':case'/*members':case'/*member':case'/*jslint':case'*/':return{value:t,type:'special',line:line,character:character,from:from};case'':break;case'/':if(prereg){depth=0;captures=0;l=0;for(;;){b=true;c=s.charAt(l);l+=1;switch(c){case'':errorAt("Unclosed regular expression.",line,from);return;case'/':if(depth>0){warningAt("Unescaped '{a}'.",line,from+l,'/');}
c=s.substr(0,l-1);q={g:true,i:true,m:true};while(q[s.charAt(l)]===true){q[s.charAt(l)]=false;l+=1;}
character+=l;s=s.substr(l);return it('(regexp)',c);case'\\':c=s.charAt(l);if(c<' '){warningAt("Unexpected control character in regular expression.",line,from+l);}else if(c==='<'){warningAt("Unexpected escaped character '{a}' in regular expression.",line,from+l,c);}
l+=1;break;case'(':depth+=1;b=false;if(s.charAt(l)==='?'){l+=1;switch(s.charAt(l)){case':':case'=':case'!':l+=1;break;default:warningAt("Expected '{a}' and instead saw '{b}'.",line,from+l,':',s.charAt(l));}}else{captures+=1;}
break;case')':if(depth===0){warningAt("Unescaped '{a}'.",line,from+l,')');}else{depth-=1;}
break;case' ':q=1;while(s.charAt(l)===' '){l+=1;q+=1;}
if(q>1){warningAt("Spaces are hard to count. Use {{a}}.",line,from+l,q);}
break;case'[':if(s.charAt(l)==='^'){l+=1;}
q=false;klass:do{c=s.charAt(l);l+=1;switch(c){case'[':case'^':warningAt("Unescaped '{a}'.",line,from+l,c);q=true;break;case'-':if(q){q=false;}else{warningAt("Unescaped '{a}'.",line,from+l,'-');q=true;}
break;case']':if(!q){warningAt("Unescaped '{a}'.",line,from+l-1,'-');}
break klass;case'\\':c=s.charAt(l);if(c<' '){warningAt("Unexpected control character in regular expression.",line,from+l);}else if(c==='<'){warningAt("Unexpected escaped character '{a}' in regular expression.",line,from+l,c);}
l+=1;q=true;break;case'/':warningAt("Unescaped '{a}'.",line,from+l-1,'/');q=true;break;case'<':if(xmode==='script'){c=s.charAt(l);if(c==='!'||c==='/'){warningAt("HTML confusion in regular expression '<{a}'.",line,from+l,c);}}
q=true;break;default:q=true;}}while(c);break;case'.':if(option.regexp){warningAt("Unexpected '{a}'.",line,from+l,c);}
break;case']':case'?':case'{':case'}':case'+':case'*':warningAt("Unescaped '{a}'.",line,from+l,c);break;case'<':if(xmode==='script'){c=s.charAt(l);if(c==='!'||c==='/'){warningAt("HTML confusion in regular expression '<{a}'.",line,from+l,c);}}}
if(b){switch(s.charAt(l)){case'?':case'+':case'*':l+=1;if(s.charAt(l)==='?'){l+=1;}
break;case'{':l+=1;c=s.charAt(l);if(c<'0'||c>'9'){warningAt("Expected a number and instead saw '{a}'.",line,from+l,c);}
l+=1;low=+c;for(;;){c=s.charAt(l);if(c<'0'||c>'9'){break;}
l+=1;low=+c+(low*10);}
high=low;if(c===','){l+=1;high=Infinity;c=s.charAt(l);if(c>='0'&&c<='9'){l+=1;high=+c;for(;;){c=s.charAt(l);if(c<'0'||c>'9'){break;}
l+=1;high=+c+(high*10);}}}
if(s.charAt(l)!=='}'){warningAt("Expected '{a}' and instead saw '{b}'.",line,from+l,'}',c);}else{l+=1;}
if(s.charAt(l)==='?'){l+=1;}
if(low>high){warningAt("'{a}' should not be greater than '{b}'.",line,from+l,low,high);}}}}
c=s.substr(0,l-1);character+=l;s=s.substr(l);return it('(regexp)',c);}
return it('(punctuator)',t);case'#':if(xmode==='html'||xmode==='styleproperty'){for(;;){c=s.charAt(0);if((c<'0'||c>'9')&&(c<'a'||c>'f')&&(c<'A'||c>'F')){break;}
character+=1;s=s.substr(1);t+=c;}
if(t.length!==4&&t.length!==7){warningAt("Bad hex color '{a}'.",line,from+l,t);}
return it('(color)',t);}
return it('(punctuator)',t);default:if(xmode==='outer'&&c==='&'){character+=1;s=s.substr(1);for(;;){c=s.charAt(0);character+=1;s=s.substr(1);if(c===';'){break;}
if(!((c>='0'&&c<='9')||(c>='a'&&c<='z')||c==='#')){errorAt("Bad entity",line,from+l,character);}}
break;}
return it('(punctuator)',t);}}}}};}());function addlabel(t,type){if(t==='hasOwnProperty'){error("'hasOwnProperty' is a really bad name.");}
if(option.safe&&funct['(global)']){warning('ADsafe global: '+t+'.',token);}
if(funct.hasOwnProperty(t)){warning(funct[t]===true?"'{a}' was used before it was defined.":"'{a}' is already defined.",nexttoken,t);}
funct[t]=type;if(type==='label'){scope[t]=funct;}else if(funct['(global)']){global[t]=funct;if(implied.hasOwnProperty(t)){warning("'{a}' was used before it was defined.",nexttoken,t);delete implied[t];}}else{funct['(scope)'][t]=funct;}}
function doOption(){var b,obj,filter,o=nexttoken.value,t,v;switch(o){case'*/':error("Unbegun comment.");break;case'/*global':case'/*extern':if(option.safe){warning("ADsafe restriction.");}
obj=predefined;break;case'/*members':case'/*member':o='/*members';if(!membersOnly){membersOnly={};}
obj=membersOnly;break;case'/*jslint':if(option.safe){warning("ADsafe restriction.");}
obj=option;filter=boolOptions;}
for(;;){t=lex.token();if(t.id===','){t=lex.token();}
while(t.id==='(endline)'){t=lex.token();}
if(t.type==='special'&&t.value==='*/'){break;}
if(t.type!=='(string)'&&t.type!=='(identifier)'&&o!=='/*members'){error("Bad option.",t);}
if(filter){if(filter[t.value]!==true&&t.value!=='indent'){error("Bad option.",t);}
v=lex.token();if(v.id!==':'){error("Expected '{a}' and instead saw '{b}'.",t,':',t.value);}
v=lex.token();if(t.value==='indent'){b=+v.value;if(typeof b!=='number'||!isFinite(b)||b<=0||Math.floor(b)!==b){error("Expected a small integer and instead saw '{a}'.",v,v.value);}
obj.white=true;}else if(v.value==='true'){b=true;}else if(v.value==='false'){b=false;}else{error("Expected '{a}' and instead saw '{b}'.",t,'true',t.value);}}else{b=true;}
obj[t.value]=b;}
if(filter){assume();}}
function peek(p){var i=p||0,j=0,t;while(j<=i){t=lookahead[j];if(!t){t=lookahead[j]=lex.token();}
j+=1;}
return t;}
function advance(id,t){switch(token.id){case'(number)':if(nexttoken.id==='.'){warning("A dot following a number can be confused with a decimal point.",token);}
break;case'-':if(nexttoken.id==='-'||nexttoken.id==='--'){warning("Confusing minusses.");}
break;case'+':if(nexttoken.id==='+'||nexttoken.id==='++'){warning("Confusing plusses.");}
break;}
if(token.type==='(string)'||token.identifier){anonname=token.value;}
if(id&&nexttoken.id!==id){if(t){if(nexttoken.id==='(end)'){warning("Unmatched '{a}'.",t,t.id);}else{warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.",nexttoken,id,t.id,t.line+1,nexttoken.value);}}else if(nexttoken.type!=='(identifier)'||nexttoken.value!==id){warning("Expected '{a}' and instead saw '{b}'.",nexttoken,id,nexttoken.value);}}
prevtoken=token;token=nexttoken;for(;;){nexttoken=lookahead.shift()||lex.token();if(nexttoken.id==='(end)'||nexttoken.id==='(error)'){return;}
if(nexttoken.type==='special'){doOption();}else{if(nexttoken.id!=='(endline)'){break;}}}
if(!option.evil&&nexttoken.value==='eval'){warning("eval is evil.",nexttoken);}}
function parse(rbp,initial){var left,o;if(nexttoken.id==='(end)'){error("Unexpected early end of program.",token);}
advance();if(option.safe&&predefined[token.value]===true&&(nexttoken.id!=='('&&nexttoken.id!=='.')){warning('ADsafe violation.',token);}
if(initial){anonname='anonymous';funct['(verb)']=token.value;}
if(initial===true&&token.fud){left=token.fud();}else{if(token.nud){o=token.exps;left=token.nud();}else{if(nexttoken.type==='(number)'&&token.id==='.'){warning("A leading decimal point can be confused with a dot: '.{a}'.",token,nexttoken.value);advance();return token;}else{error("Expected an identifier and instead saw '{a}'.",token,token.id);}}
while(rbp<nexttoken.lbp){o=nexttoken.exps;advance();if(token.led){left=token.led(left);}else{error("Expected an operator and instead saw '{a}'.",token,token.id);}}
if(initial&&!o){warning("Expected an assignment or function call and instead saw an expression.",token);}}
return left;}
function abut(left,right){left=left||token;right=right||nexttoken;if(left.line!==right.line||left.character!==right.from){warning("Unexpected space after '{a}'.",right,left.value);}}
function adjacent(left,right){left=left||token;right=right||nexttoken;if(option.white||xmode==='styleproperty'||xmode==='style'){if(left.character!==right.from&&left.line===right.line){warning("Unexpected space after '{a}'.",right,left.value);}}}
function nospace(left,right){left=left||token;right=right||nexttoken;if(option.white&&!left.comment){if(left.line===right.line){adjacent(left,right);}}}
function nonadjacent(left,right){if(option.white){left=left||token;right=right||nexttoken;if(left.character===right.from){warning("Missing space after '{a}'.",nexttoken,left.value);}}}
function nobreaknonadjacent(left,right){left=left||token;right=right||nexttoken;if(!option.laxbreak&&left.line!==right.line){warning("Bad line breaking before '{a}'.",right,right.id);}else if(option.white){left=left||token;right=right||nexttoken;if(left.character===right.from){warning("Missing space after '{a}'.",nexttoken,left.value);}}}
function indentation(bias){var i;if(option.white&&nexttoken.id!=='(end)'){i=indent+(bias||0);if(nexttoken.from!==i){warning("Expected '{a}' to have an indentation of {b} instead of {c}.",nexttoken,nexttoken.value,i,nexttoken.from);}}}
function nolinebreak(t){if(t.line!==nexttoken.line){warning("Line breaking error '{a}'.",t,t.value);}}
function comma(){if(token.line!==nexttoken.line){if(!option.laxbreak){warning("Bad line breaking before '{a}'.",token,nexttoken.id);}}else if(token.character!==nexttoken.from&&option.white){warning("Unexpected space after '{a}'.",nexttoken,token.value);}
advance(',');nonadjacent(token,nexttoken);}
function symbol(s,p){var x=syntax[s];if(!x||typeof x!=='object'){syntax[s]=x={id:s,lbp:p,value:s};}
return x;}
function delim(s){return symbol(s,0);}
function stmt(s,f){var x=delim(s);x.identifier=x.reserved=true;x.fud=f;return x;}
function blockstmt(s,f){var x=stmt(s,f);x.block=true;return x;}
function reserveName(x){var c=x.id.charAt(0);if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){x.identifier=x.reserved=true;}
return x;}
function prefix(s,f){var x=symbol(s,150);reserveName(x);x.nud=(typeof f==='function')?f:function(){if(option.plusplus&&(this.id==='++'||this.id==='--')){warning("Unexpected use of '{a}'.",this,this.id);}
this.right=parse(150);this.arity='unary';return this;};return x;}
function type(s,f){var x=delim(s);x.type=s;x.nud=f;return x;}
function reserve(s,f){var x=type(s,f);x.identifier=x.reserved=true;return x;}
function reservevar(s,v){return reserve(s,function(){if(this.id==='this'){if(option.safe){warning("ADsafe violation.",this);}}
return this;});}
function infix(s,f,p,w){var x=symbol(s,p);reserveName(x);x.led=function(left){if(!w){nobreaknonadjacent(prevtoken,token);nonadjacent(token,nexttoken);}
if(typeof f==='function'){return f(left,this);}else{this.left=left;this.right=parse(p);return this;}};return x;}
function relation(s,f){var x=symbol(s,100);x.led=function(left){nobreaknonadjacent(prevtoken,token);nonadjacent(token,nexttoken);var right=parse(100);if((left&&left.id==='NaN')||(right&&right.id==='NaN')){warning("Use the isNaN function to compare with NaN.",this);}else if(f){f.apply(this,[left,right]);}
this.left=left;this.right=right;return this;};return x;}
function isPoorRelation(node){return(node.type==='(number)'&&!+node.value)||(node.type==='(string)'&&!node.value)||node.type==='true'||node.type==='false'||node.type==='undefined'||node.type==='null';}
function assignop(s,f){symbol(s,20).exps=true;return infix(s,function(left,that){var l;that.left=left;if(option.safe){l=left;do{if(predefined[l.value]===true){warning('ADsafe violation.',l);}
l=l.left;}while(l);}
if(left){if(left.id==='.'||left.id==='['){if(left.left.value==='arguments'){warning('Bad assignment.',that);}
that.right=parse(19);return that;}else if(left.identifier&&!left.reserved){if(funct[left.value]==='exception'){warning("Do not assign to the exception parameter.",left);}
that.right=parse(19);return that;}
if(left===syntax['function']){warning("Expected an identifier in an assignment and instead saw a function invocation.",token);}}
error("Bad assignment.",that);},20);}
function bitwise(s,f,p){var x=symbol(s,p);reserveName(x);x.led=(typeof f==='function')?f:function(left){if(option.bitwise){warning("Unexpected use of '{a}'.",this,this.id);}
this.left=left;this.right=parse(p);return this;};return x;}
function bitwiseassignop(s){symbol(s,20).exps=true;return infix(s,function(left,that){if(option.bitwise){warning("Unexpected use of '{a}'.",that,that.id);}
nonadjacent(prevtoken,token);nonadjacent(token,nexttoken);if(left){if(left.id==='.'||left.id==='['||(left.identifier&&!left.reserved)){parse(19);return left;}
if(left===syntax['function']){warning("Expected an identifier in an assignment, and instead saw a function invocation.",token);}}
error("Bad assignment.",that);},20);}
function suffix(s,f){var x=symbol(s,150);x.led=function(left){if(option.plusplus){warning("Unexpected use of '{a}'.",this,this.id);}
this.left=left;return this;};return x;}
function optionalidentifier(){if(nexttoken.reserved&&nexttoken.value!=='arguments'){warning("Expected an identifier and instead saw '{a}' (a reserved word).",nexttoken,nexttoken.id);}
if(nexttoken.identifier){advance();return token.value;}}
function identifier(){var i=optionalidentifier();if(i){return i;}
if(token.id==='function'&&nexttoken.id==='('){warning("Missing name in function statement.");}else{error("Expected an identifier and instead saw '{a}'.",nexttoken,nexttoken.value);}}
function reachable(s){var i=0,t;if(nexttoken.id!==';'||noreach){return;}
for(;;){t=peek(i);if(t.reach){return;}
if(t.id!=='(endline)'){if(t.id==='function'){warning("Inner functions should be listed at the top of the outer function.",t);break;}
warning("Unreachable '{a}' after '{b}'.",t,t.value,s);break;}
i+=1;}}
function statement(noindent){var i=indent,r,s=scope,t=nexttoken;if(t.id===';'){warning("Unnecessary semicolon.",t);advance(';');return;}
if(t.identifier&&!t.reserved&&peek().id===':'){advance();advance(':');scope=Object.create(s);addlabel(t.value,'label');if(!nexttoken.labelled){warning("Label '{a}' on {b} statement.",nexttoken,t.value,nexttoken.value);}
if(jx.test(t.value+':')){warning("Label '{a}' looks like a javascript url.",t,t.value);}
nexttoken.label=t.value;t=nexttoken;}
if(!noindent){indentation();}
r=parse(0,true);if(!t.block){if(nexttoken.id!==';'){warningAt("Missing semicolon.",token.line,token.from+token.value.length);}else{abut(token,nexttoken);advance(';');nonadjacent(token,nexttoken);}}
indent=i;scope=s;return r;}
function use_strict(){if(nexttoken.type==='(string)'&&/^use +strict(?:,.+)?$/.test(nexttoken.value)){advance();advance(';');return true;}else{return false;}}
function statements(begin){var a=[],f,p;if(begin&&!use_strict()&&option.strict){warning('Missing "use strict" statement.',nexttoken);}
if(option.adsafe){switch(begin){case'script':if(!adsafe_may){if(nexttoken.value!=='ADSAFE'||peek(0).id!=='.'||(peek(1).value!=='id'&&peek(1).value!=='go')){error('ADsafe violation: Missing ADSAFE.id or ADSAFE.go.',nexttoken);}}
if(nexttoken.value==='ADSAFE'&&peek(0).id==='.'&&peek(1).value==='id'){if(adsafe_may){error('ADsafe violation.',nexttoken);}
advance('ADSAFE');advance('.');advance('id');advance('(');if(nexttoken.value!==adsafe_id){error('ADsafe violation: id does not match.',nexttoken);}
advance('(string)');advance(')');advance(';');adsafe_may=true;}
break;case'lib':if(nexttoken.value==='ADSAFE'){advance('ADSAFE');advance('.');advance('lib');advance('(');advance('(string)');comma();f=parse(0);if(f.id!=='function'){error('The second argument to lib must be a function.',f);}
p=f.funct['(params)'];if(p&&p!=='lib'){error("Expected '{a}' and instead saw '{b}'.",f,'lib',p);}
advance(')');advance(';');return a;}else{error("ADsafe lib violation.");}}}
while(!nexttoken.reach&&nexttoken.id!=='(end)'){if(nexttoken.id===';'){warning("Unnecessary semicolon.");advance(';');}else{a.push(statement());}}
return a;}
function block(f){var a,b=inblock,s=scope,t;inblock=f;if(f){scope=Object.create(scope);}
nonadjacent(token,nexttoken);t=nexttoken;if(nexttoken.id==='{'){advance('{');if(nexttoken.id!=='}'||token.line!==nexttoken.line){indent+=option.indent;if(!f&&nexttoken.from===indent+option.indent){indent+=option.indent;}
if(!f){use_strict();}
a=statements();indent-=option.indent;indentation();}
advance('}',t);}else{warning("Expected '{a}' and instead saw '{b}'.",nexttoken,'{',nexttoken.value);noreach=true;a=[statement()];noreach=false;}
funct['(verb)']=null;scope=s;inblock=b;return a;}
function idValue(){return this;}
function countMember(m){if(membersOnly&&membersOnly[m]!==true){warning("Unexpected /*member '{a}'.",nexttoken,m);}
if(typeof member[m]==='number'){member[m]+=1;}else{member[m]=1;}}
function note_implied(token){var name=token.value,line=token.line+1,a=implied[name];if(typeof a==='function'){a=false;}
if(!a){a=[line];implied[name]=a;}else if(a[a.length-1]!==line){a.push(line);}}
function cssName(){if(nexttoken.identifier){advance();return true;}}
function cssNumber(){if(nexttoken.id==='-'){advance('-');advance('(number)');}
if(nexttoken.type==='(number)'){advance();return true;}}
function cssString(){if(nexttoken.type==='(string)'){advance();return true;}}
function cssColor(){var i,number;if(nexttoken.identifier){if(nexttoken.value==='rgb'){advance();advance('(');for(i=0;i<3;i+=1){number=nexttoken.value;if(nexttoken.type!=='(number)'||number<0){warning("Expected a positive number and instead saw '{a}'",nexttoken,number);advance();}else{advance();if(nexttoken.id==='%'){advance('%');if(number>100){warning("Expected a percentage and instead saw '{a}'",token,number);}}else{if(number>255){warning("Expected a small number and instead saw '{a}'",token,number);}}}}
advance(')');return true;}else if(cssColorData[nexttoken.value]===true){advance();return true;}}else if(nexttoken.type==='(color)'){advance();return true;}
return false;}
function cssLength(){if(nexttoken.id==='-'){advance('-');adjacent();}
if(nexttoken.type==='(number)'){advance();if(nexttoken.type!=='(string)'&&cssLengthData[nexttoken.value]===true){adjacent();advance();}else if(+token.value!==0){warning("Expected a linear unit and instead saw '{a}'.",nexttoken,nexttoken.value);}
return true;}
return false;}
function cssLineHeight(){if(nexttoken.id==='-'){advance('-');adjacent();}
if(nexttoken.type==='(number)'){advance();if(nexttoken.type!=='(string)'&&cssLengthData[nexttoken.value]===true){adjacent();advance();}
return true;}
return false;}
function cssWidth(){if(nexttoken.identifier){switch(nexttoken.value){case'thin':case'medium':case'thick':advance();return true;}}else{return cssLength();}}
function cssMargin(){if(nexttoken.identifier){if(nexttoken.value==='auto'){advance();return true;}}else{return cssLength();}}
function cssAttr(){if(nexttoken.identifier&&nexttoken.value==='attr'){advance();advance('(');if(!nexttoken.identifier){warning("Expected a name and instead saw '{a}'.",nexttoken,nexttoken.value);}
advance();advance(')');return true;}
return false;}
function cssCommaList(){while(nexttoken.id!==';'){if(!cssName()&&!cssString()){warning("Expected a name and instead saw '{a}'.",nexttoken,nexttoken.value);}
if(nexttoken.id!==','){return true;}
comma();}}
function cssCounter(){if(nexttoken.identifier&&nexttoken.value==='counter'){advance();advance('(');if(!nexttoken.identifier){}
advance();if(nexttoken.id===','){comma();if(nexttoken.type!=='(string)'){warning("Expected a string and instead saw '{a}'.",nexttoken,nexttoken.value);}
advance();}
advance(')');return true;}
if(nexttoken.identifier&&nexttoken.value==='counters'){advance();advance('(');if(!nexttoken.identifier){warning("Expected a name and instead saw '{a}'.",nexttoken,nexttoken.value);}
advance();if(nexttoken.id===','){comma();if(nexttoken.type!=='(string)'){warning("Expected a string and instead saw '{a}'.",nexttoken,nexttoken.value);}
advance();}
if(nexttoken.id===','){comma();if(nexttoken.type!=='(string)'){warning("Expected a string and instead saw '{a}'.",nexttoken,nexttoken.value);}
advance();}
advance(')');return true;}
return false;}
function cssShape(){var i;if(nexttoken.identifier&&nexttoken.value==='rect'){advance();advance('(');for(i=0;i<4;i+=1){if(!cssLength()){warning("Expected a number and instead saw '{a}'.",nexttoken,nexttoken.value);break;}}
advance(')');return true;}
return false;}
function cssUrl(){var url;if(nexttoken.identifier&&nexttoken.value==='url'){nexttoken=lex.range('(',')');url=nexttoken.value;advance();if(option.safe&&ux.test(url)){error("ADsafe URL violation.");}
urls.push(url);return true;}
return false;}
cssAny=[cssUrl,function(){for(;;){if(nexttoken.identifier){switch(nexttoken.value.toLowerCase()){case'url':cssUrl();break;case'expression':warning("Unexpected expression '{a}'.",nexttoken,nexttoken.value);advance();break;default:advance();}}else{if(nexttoken.id===';'||nexttoken.id==='!'||nexttoken.id==='(end)'||nexttoken.id==='}'){return true;}
advance();}}}];cssBorderStyle=['none','hidden','dotted','dashed','solid','double','ridge','inset','outset'];cssAttributeData={background:[true,'background-attachment','background-color','background-image','background-position','background-repeat'],'background-attachment':['scroll','fixed'],'background-color':['transparent',cssColor],'background-image':['none',cssUrl],'background-position':[2,[cssLength,'top','bottom','left','right','center']],'background-repeat':['repeat','repeat-x','repeat-y','no-repeat'],'border':[true,'border-color','border-style','border-width'],'border-bottom':[true,'border-bottom-color','border-bottom-style','border-bottom-width'],'border-bottom-color':cssColor,'border-bottom-style':cssBorderStyle,'border-bottom-width':cssWidth,'border-collapse':['collapse','separate'],'border-color':['transparent',4,cssColor],'border-left':[true,'border-left-color','border-left-style','border-left-width'],'border-left-color':cssColor,'border-left-style':cssBorderStyle,'border-left-width':cssWidth,'border-right':[true,'border-right-color','border-right-style','border-right-width'],'border-right-color':cssColor,'border-right-style':cssBorderStyle,'border-right-width':cssWidth,'border-spacing':[2,cssLength],'border-style':[4,cssBorderStyle],'border-top':[true,'border-top-color','border-top-style','border-top-width'],'border-top-color':cssColor,'border-top-style':cssBorderStyle,'border-top-width':cssWidth,'border-width':[4,cssWidth],bottom:[cssLength,'auto'],'caption-side':['bottom','left','right','top'],clear:['both','left','none','right'],clip:[cssShape,'auto'],color:cssColor,content:['open-quote','close-quote','no-open-quote','no-close-quote',cssString,cssUrl,cssCounter,cssAttr],'counter-increment':[cssName,'none'],'counter-reset':[cssName,'none'],cursor:[cssUrl,'auto','crosshair','default','e-resize','help','move','n-resize','ne-resize','nw-resize','pointer','s-resize','se-resize','sw-resize','w-resize','text','wait'],direction:['ltr','rtl'],display:['block','compact','inline','inline-block','inline-table','list-item','marker','none','run-in','table','table-caption','table-cell','table-column','table-column-group','table-footer-group','table-header-group','table-row','table-row-group'],'empty-cells':['show','hide'],'float':['left','none','right'],font:['caption','icon','menu','message-box','small-caption','status-bar',true,'font-size','font-style','font-weight','font-family'],'font-family':cssCommaList,'font-size':['xx-small','x-small','small','medium','large','x-large','xx-large','larger','smaller',cssLength],'font-size-adjust':['none',cssNumber],'font-stretch':['normal','wider','narrower','ultra-condensed','extra-condensed','condensed','semi-condensed','semi-expanded','expanded','extra-expanded'],'font-style':['normal','italic','oblique'],'font-variant':['normal','small-caps'],'font-weight':['normal','bold','bolder','lighter',cssNumber],height:[cssLength,'auto'],left:[cssLength,'auto'],'letter-spacing':['normal',cssLength],'line-height':['normal',cssLineHeight],'list-style':[true,'list-style-image','list-style-position','list-style-type'],'list-style-image':['none',cssUrl],'list-style-position':['inside','outside'],'list-style-type':['circle','disc','square','decimal','decimal-leading-zero','lower-roman','upper-roman','lower-greek','lower-alpha','lower-latin','upper-alpha','upper-latin','hebrew','katakana','hiragana-iroha','katakana-oroha','none'],margin:[4,cssMargin],'margin-bottom':cssMargin,'margin-left':cssMargin,'margin-right':cssMargin,'margin-top':cssMargin,'marker-offset':[cssLength,'auto'],'max-height':[cssLength,'none'],'max-width':[cssLength,'none'],'min-height':cssLength,'min-width':cssLength,opacity:cssNumber,outline:[true,'outline-color','outline-style','outline-width'],'outline-color':['invert',cssColor],'outline-style':['dashed','dotted','double','groove','inset','none','outset','ridge','solid'],'outline-width':cssWidth,overflow:['auto','hidden','scroll','visible'],padding:[4,cssLength],'padding-bottom':cssLength,'padding-left':cssLength,'padding-right':cssLength,'padding-top':cssLength,position:['absolute','fixed','relative','static'],quotes:[8,cssString],right:[cssLength,'auto'],'table-layout':['auto','fixed'],'text-align':['center','justify','left','right'],'text-decoration':['none','underline','overline','line-through','blink'],'text-indent':cssLength,'text-shadow':['none',4,[cssColor,cssLength]],'text-transform':['capitalize','uppercase','lowercase','none'],top:[cssLength,'auto'],'unicode-bidi':['normal','embed','bidi-override'],'vertical-align':['baseline','bottom','sub','super','top','text-top','middle','text-bottom',cssLength],visibility:['visible','hidden','collapse'],'white-space':['normal','pre','nowrap'],width:[cssLength,'auto'],'word-spacing':['normal',cssLength],'z-index':['auto',cssNumber]};function styleAttribute(){var v;while(nexttoken.id==='*'||nexttoken.id==='#'||nexttoken.value==='_'){if(!option.css){warning("Unexpected '{a}'.",nexttoken,nexttoken.value);}
advance();}
if(nexttoken.id==='-'){if(!option.css){warning("Unexpected '{a}'.",nexttoken,nexttoken.value);}
advance('-');if(!nexttoken.identifier){warning("Expected a non-standard style attribute and instead saw '{a}'.",nexttoken,nexttoken.value);}
advance();return cssAny;}else{if(!nexttoken.identifier){warning("Excepted a style attribute, and instead saw '{a}'.",nexttoken,nexttoken.value);}else{if(cssAttributeData.hasOwnProperty(nexttoken.value)){v=cssAttributeData[nexttoken.value];}else{v=cssAny;if(!option.css){warning("Unrecognized style attribute '{a}'.",nexttoken,nexttoken.value);}}}
advance();return v;}}
function styleValue(v){var i=0,n,once,match,round,start=0,vi;switch(typeof v){case'function':return v();case'string':if(nexttoken.identifier&&nexttoken.value===v){advance();return true;}
return false;}
for(;;){if(i>=v.length){return false;}
vi=v[i];i+=1;if(vi===true){break;}else if(typeof vi==='number'){n=vi;vi=v[i];i+=1;}else{n=1;}
match=false;while(n>0){if(styleValue(vi)){match=true;n-=1;}else{break;}}
if(match){return true;}}
start=i;once=[];for(;;){round=false;for(i=start;i<v.length;i+=1){if(!once[i]){if(styleValue(cssAttributeData[v[i]])){match=true;round=true;once[i]=true;break;}}}
if(!round){return match;}}}
function substyle(){var v;for(;;){if(nexttoken.id==='}'||nexttoken.id==='(end)'||xquote&&nexttoken.id===xquote){return;}
while(nexttoken.id===';'){warning("Misplaced ';'.");advance(';');}
v=styleAttribute();advance(':');if(nexttoken.identifier&&nexttoken.value==='inherit'){advance();}else{styleValue(v);}
while(nexttoken.id!==';'&&nexttoken.id!=='!'&&nexttoken.id!=='}'&&nexttoken.id!=='(end)'&&nexttoken.id!==xquote){warning("Unexpected token '{a}'.",nexttoken,nexttoken.value);advance();}
if(nexttoken.id==='!'){advance('!');adjacent();if(nexttoken.identifier&&nexttoken.value==='important'){advance();}else{warning("Expected '{a}' and instead saw '{b}'.",nexttoken,'important',nexttoken.value);}}
if(nexttoken.id==='}'||nexttoken.id===xquote){warning("Missing '{a}'.",nexttoken,';');}else{advance(';');}}}
function stylePattern(){var name;if(nexttoken.id==='{'){warning("Expected a style pattern, and instead saw '{a}'.",nexttoken,nexttoken.id);}else if(nexttoken.id==='@'){advance('@');name=nexttoken.value;if(nexttoken.identifier&&atrule[name]===true){advance();return name;}
warning("Expected an at-rule, and instead saw @{a}.",nexttoken,name);}
for(;;){if(nexttoken.identifier){if(!htmltag.hasOwnProperty(nexttoken.value)){warning("Expected a tagName, and instead saw {a}.",nexttoken,nexttoken.value);}
advance();}else{switch(nexttoken.id){case'>':case'+':advance();if(!nexttoken.identifier||!htmltag.hasOwnProperty(nexttoken.value)){warning("Expected a tagName, and instead saw {a}.",nexttoken,nexttoken.value);}
advance();break;case':':advance(':');if(pseudorule[nexttoken.value]!==true){warning("Expected a pseudo, and instead saw :{a}.",nexttoken,nexttoken.value);}
advance();if(nexttoken.value==='lang'){advance('(');if(!nexttoken.identifier){warning("Expected a lang code, and instead saw :{a}.",nexttoken,nexttoken.value);}
advance(')');}
break;case'#':advance('#');if(!nexttoken.identifier){warning("Expected an id, and instead saw #{a}.",nexttoken,nexttoken.value);}
advance();break;case'*':advance('*');break;case'.':advance('.');if(!nexttoken.identifier){warning("Expected a class, and instead saw #.{a}.",nexttoken,nexttoken.value);}
advance();break;case'[':advance('[');if(!nexttoken.identifier){warning("Expected an attribute, and instead saw [{a}].",nexttoken,nexttoken.value);}
advance();if(nexttoken.id==='='||nexttoken.id==='~='||nexttoken.id==='|='){advance();if(nexttoken.type!=='(string)'){warning("Expected a string, and instead saw {a}.",nexttoken,nexttoken.value);}
advance();}
advance(']');break;default:error("Expected a CSS selector, and instead saw {a}.",nexttoken,nexttoken.value);}}
if(nexttoken.id==='</'||nexttoken.id==='{'||nexttoken.id==='(end)'){return'';}
if(nexttoken.id===','){comma();}}}
function styles(){while(nexttoken.id!=='</'&&nexttoken.id!=='(end)'){stylePattern();xmode='styleproperty';if(nexttoken.id===';'){advance(';');}else{advance('{');substyle();xmode='style';advance('}');}}}
function doBegin(n){if(n!=='html'&&!option.fragment){if(n==='div'&&option.adsafe){error("ADSAFE: Use the fragment option.");}else{error("Expected '{a}' and instead saw '{b}'.",token,'html',n);}}
if(option.adsafe){if(n==='html'){error("Currently, ADsafe does not operate on whole HTML documents. It operates on <div> fragments and .js files.",token);}
if(option.fragment){if(n!=='div'){error("ADsafe violation: Wrap the widget in a div.",token);}}else{error("Use the fragment option.",token);}}
option.browser=true;assume();}
function doAttribute(n,a,v){var u,x;if(a==='id'){u=typeof v==='string'?v.toUpperCase():'';if(ids[u]===true){warning("Duplicate id='{a}'.",nexttoken,v);}
if(option.adsafe){if(adsafe_id){if(v.slice(0,adsafe_id.length)!==adsafe_id){warning("ADsafe violation: An id must have a '{a}' prefix",nexttoken,adsafe_id);}else if(!/^[A-Z]+_[A-Z]+$/.test(v)){warning("ADSAFE violation: bad id.");}}else{adsafe_id=v;if(!/^[A-Z]+_$/.test(v)){warning("ADSAFE violation: bad id.");}}}
x=v.search(dx);if(x>=0){warning("Unexpected character '{a}' in {b}.",token,v.charAt(x),a);}
ids[u]=true;}else if(a==='class'||a==='type'||a==='name'){x=v.search(qx);if(x>=0){warning("Unexpected character '{a}' in {b}.",token,v.charAt(x),a);}
ids[u]=true;}else if(a==='href'||a==='background'||a==='content'||a==='data'||a.indexOf('src')>=0||a.indexOf('url')>=0){if(option.safe&&ux.test(v)){error("ADsafe URL violation.");}
urls.push(v);}else if(a==='for'){if(option.adsafe){if(adsafe_id){if(v.slice(0,adsafe_id.length)!==adsafe_id){warning("ADsafe violation: An id must have a '{a}' prefix",nexttoken,adsafe_id);}else if(!/^[A-Z]+_[A-Z]+$/.test(v)){warning("ADSAFE violation: bad id.");}}else{warning("ADSAFE violation: bad id.");}}}else if(a==='name'){if(option.adsafe&&v.indexOf('_')>=0){warning("ADsafe name violation.");}}}
function doTag(n,a){var i,t=htmltag[n],x;src=false;if(!t){error("Unrecognized tag '<{a}>'.",nexttoken,n===n.toLowerCase()?n:n+' (capitalization error)');}
if(stack.length>0){if(n==='html'){error("Too many <html> tags.",token);}
x=t.parent;if(x){if(x.indexOf(' '+stack[stack.length-1].name+' ')<0){error("A '<{a}>' must be within '<{b}>'.",token,n,x);}}else if(!option.adsafe&&!option.fragment){i=stack.length;do{if(i<=0){error("A '<{a}>' must be within '<{b}>'.",token,n,'body');}
i-=1;}while(stack[i].name!=='body');}}
switch(n){case'div':if(option.adsafe&&stack.length===1&&!adsafe_id){warning("ADSAFE violation: missing ID_.");}
break;case'script':xmode='script';advance('>');indent=nexttoken.from;if(a.lang){warning("lang is deprecated.",token);}
if(option.adsafe&&stack.length!==1){warning("ADsafe script placement violation.",token);}
if(a.src){if(option.adsafe&&(!adsafe_may||!approved[a.src])){warning("ADsafe unapproved script source.",token);}
if(a.type){warning("type is unnecessary.",token);}}else{if(adsafe_went){error("ADsafe script violation.",token);}
statements('script');}
xmode='html';advance('</');if(!nexttoken.identifier&&nexttoken.value!=='script'){warning("Expected '{a}' and instead saw '{b}'.",nexttoken,'script',nexttoken.value);}
advance();xmode='outer';break;case'style':xmode='style';advance('>');styles();xmode='html';advance('</');if(!nexttoken.identifier&&nexttoken.value!=='style'){warning("Expected '{a}' and instead saw '{b}'.",nexttoken,'style',nexttoken.value);}
advance();xmode='outer';break;case'input':switch(a.type){case'radio':case'checkbox':case'text':case'button':case'file':case'reset':case'submit':case'password':case'file':case'hidden':case'image':break;default:warning("Bad input type.");}
if(option.adsafe&&a.autocomplete!=='off'){warning("ADsafe autocomplete violation.");}
break;case'applet':case'body':case'embed':case'frame':case'frameset':case'head':case'iframe':case'img':case'noembed':case'noframes':case'object':case'param':if(option.adsafe){warning("ADsafe violation: Disallowed tag: "+n);}
break;}}
function closetag(n){return'</'+n+'>';}
function html(){var a,attributes,e,n,q,t,v,w=option.white,wmode;xmode='html';xquote='';stack=null;for(;;){switch(nexttoken.value){case'<':xmode='html';advance('<');attributes={};t=nexttoken;if(!t.identifier){warning("Bad identifier {a}.",t,t.value);}
n=t.value;if(option.cap){n=n.toLowerCase();}
t.name=n;advance();if(!stack){stack=[];doBegin(n);}
v=htmltag[n];if(typeof v!=='object'){error("Unrecognized tag '<{a}>'.",t,n);}
e=v.empty;t.type=n;for(;;){if(nexttoken.id==='/'){advance('/');if(nexttoken.id!=='>'){warning("Expected '{a}' and instead saw '{b}'.",nexttoken,'>',nexttoken.value);}
break;}
if(nexttoken.id&&nexttoken.id.substr(0,1)==='>'){break;}
if(!nexttoken.identifier){if(nexttoken.id==='(end)'||nexttoken.id==='(error)'){error("Missing '>'.",nexttoken);}
warning("Bad identifier.");}
option.white=true;nonadjacent(token,nexttoken);a=nexttoken.value;option.white=w;advance();if(!option.cap&&a!==a.toLowerCase()){warning("Attribute '{a}' not all lower case.",nexttoken,a);}
a=a.toLowerCase();xquote='';if(attributes.hasOwnProperty(a)){warning("Attribute '{a}' repeated.",nexttoken,a);}
if(a.slice(0,2)==='on'){if(!option.on){warning("Avoid HTML event handlers.");}
xmode='scriptstring';advance('=');q=nexttoken.id;if(q!=='"'&&q!=="'"){error("Missing quote.");}
xquote=q;wmode=option.white;option.white=false;advance(q);statements('on');option.white=wmode;if(nexttoken.id!==q){error("Missing close quote on script attribute.");}
xmode='html';xquote='';advance(q);v=false;}else if(a==='style'){xmode='scriptstring';advance('=');q=nexttoken.id;if(q!=='"'&&q!=="'"){error("Missing quote.");}
xmode='styleproperty';xquote=q;advance(q);substyle();xmode='html';xquote='';advance(q);v=false;}else{if(nexttoken.id==='='){advance('=');v=nexttoken.value;if(!nexttoken.identifier&&nexttoken.id!=='"'&&nexttoken.id!=='\''&&nexttoken.type!=='(string)'&&nexttoken.type!=='(number)'&&nexttoken.type!=='(color)'){warning("Expected an attribute value and instead saw '{a}'.",token,a);}
advance();}else{v=true;}}
attributes[a]=v;doAttribute(n,a,v);}
doTag(n,attributes);if(!e){stack.push(t);}
xmode='outer';advance('>');break;case'</':xmode='html';advance('</');if(!nexttoken.identifier){warning("Bad identifier.");}
n=nexttoken.value;if(option.cap){n=n.toLowerCase();}
advance();if(!stack){error("Unexpected '{a}'.",nexttoken,closetag(n));}
t=stack.pop();if(!t){error("Unexpected '{a}'.",nexttoken,closetag(n));}
if(t.name!==n){error("Expected '{a}' and instead saw '{b}'.",nexttoken,closetag(t.name),closetag(n));}
if(nexttoken.id!=='>'){error("Missing '{a}'.",nexttoken,'>');}
xmode='outer';advance('>');break;case'<!':if(option.safe){warning("ADsafe HTML violation.");}
xmode='html';for(;;){advance();if(nexttoken.id==='>'||nexttoken.id==='(end)'){break;}
if(nexttoken.id==='--'){warning("Unexpected --.");}}
xmode='outer';advance('>');break;case'<!--':xmode='html';if(option.safe){warning("ADsafe HTML violation.");}
for(;;){advance();if(nexttoken.id==='(end)'){error("Missing '-->'.");}
if(nexttoken.id==='<!'||nexttoken.id==='<!--'){error("Unexpected '<!' in HTML comment.");}
if(nexttoken.id==='--'){advance('--');break;}}
abut();xmode='outer';advance('>');break;case'(end)':return;default:if(nexttoken.id==='(end)'){error("Missing '{a}'.",nexttoken,'</'+stack[stack.length-1].value+'>');}else{advance();}}
if(stack&&stack.length===0&&(option.adsafe||!option.fragment||nexttoken.id==='(end)')){break;}}
if(nexttoken.id!=='(end)'){error("Unexpected material after the end.");}}
type('(number)',idValue);type('(string)',idValue);syntax['(identifier)']={type:'(identifier)',lbp:0,identifier:true,nud:function(){var v=this.value,s=scope[v];if(typeof s==='function'){s=false;}
if(s&&(s===funct||s===funct['(global)'])){if(!funct['(global)']){switch(funct[v]){case'unused':funct[v]='var';break;case'label':warning("'{a}' is a statement label.",token,v);break;}}}else if(funct['(global)']){if(option.undef){warning("'{a}' is not defined.",token,v);}
note_implied(token);}else{switch(funct[v]){case'closure':case'function':case'var':case'unused':warning("'{a}' used out of scope.",token,v);break;case'label':warning("'{a}' is a statement label.",token,v);break;case'outer':case true:break;default:if(s===true){funct[v]=true;}else if(typeof s!=='object'){if(option.undef){warning("'{a}' is not defined.",token,v);}else{funct[v]=true;}
note_implied(token);}else{switch(s[v]){case'function':case'var':case'unused':s[v]='closure';funct[v]='outer';break;case'closure':case'parameter':funct[v]='outer';break;case'label':warning("'{a}' is a statement label.",token,v);}}}}
return this;},led:function(){error("Expected an operator and instead saw '{a}'.",nexttoken,nexttoken.value);}};type('(regexp)',function(){return this;});delim('(endline)');delim('(begin)');delim('(end)').reach=true;delim('</').reach=true;delim('<!');delim('<!--');delim('-->');delim('(error)').reach=true;delim('}').reach=true;delim(')');delim(']');delim('"').reach=true;delim("'").reach=true;delim(';');delim(':').reach=true;delim(',');delim('#');delim('@');reserve('else');reserve('case').reach=true;reserve('catch');reserve('default').reach=true;reserve('finally');reservevar('arguments');reservevar('eval');reservevar('false');reservevar('Infinity');reservevar('NaN');reservevar('null');reservevar('this');reservevar('true');reservevar('undefined');assignop('=','assign',20);assignop('+=','assignadd',20);assignop('-=','assignsub',20);assignop('*=','assignmult',20);assignop('/=','assigndiv',20).nud=function(){error("A regular expression literal can be confused with '/='.");};assignop('%=','assignmod',20);bitwiseassignop('&=','assignbitand',20);bitwiseassignop('|=','assignbitor',20);bitwiseassignop('^=','assignbitxor',20);bitwiseassignop('<<=','assignshiftleft',20);bitwiseassignop('>>=','assignshiftright',20);bitwiseassignop('>>>=','assignshiftrightunsigned',20);infix('?',function(left,that){that.left=left;that.right=parse(10);advance(':');that['else']=parse(10);return that;},30);infix('||','or',40);infix('&&','and',50);bitwise('|','bitor',70);bitwise('^','bitxor',80);bitwise('&','bitand',90);relation('==',function(left,right){if(option.eqeqeq){warning("Expected '{a}' and instead saw '{b}'.",this,'===','==');}else if(isPoorRelation(left)){warning("Use '{a}' to compare with '{b}'.",this,'===',left.value);}else if(isPoorRelation(right)){warning("Use '{a}' to compare with '{b}'.",this,'===',right.value);}
return this;});relation('===');relation('!=',function(left,right){if(option.eqeqeq){warning("Expected '{a}' and instead saw '{b}'.",this,'!==','!=');}else if(isPoorRelation(left)){warning("Use '{a}' to compare with '{b}'.",this,'!==',left.value);}else if(isPoorRelation(right)){warning("Use '{a}' to compare with '{b}'.",this,'!==',right.value);}
return this;});relation('!==');relation('<');relation('>');relation('<=');relation('>=');bitwise('<<','shiftleft',120);bitwise('>>','shiftright',120);bitwise('>>>','shiftrightunsigned',120);infix('in','in',120);infix('instanceof','instanceof',120);infix('+',function(left,that){var right=parse(130);if(left&&right&&left.id==='(string)'&&right.id==='(string)'){left.value+=right.value;left.character=right.character;if(jx.test(left.value)){warning("JavaScript URL.",left);}
return left;}
that.left=left;that.right=right;return that;},130);prefix('+','num');infix('-','sub',130);prefix('-','neg');infix('*','mult',140);infix('/','div',140);infix('%','mod',140);suffix('++','postinc');prefix('++','preinc');syntax['++'].exps=true;suffix('--','postdec');prefix('--','predec');syntax['--'].exps=true;prefix('delete',function(){var p=parse(0);if(!p||(p.id!=='.'&&p.id!=='[')){warning("Expected '{a}' and instead saw '{b}'.",nexttoken,'.',nexttoken.value);}}).exps=true;prefix('~',function(){if(option.bitwise){warning("Unexpected '{a}'.",this,'~');}
parse(150);return this;});prefix('!','not');prefix('typeof','typeof');prefix('new',function(){var c=parse(155),i;if(c&&c.id!=='function'){if(c.identifier){c['new']=true;switch(c.value){case'Object':warning("Use the object literal notation {}.",token);break;case'Array':warning("Use the array literal notation [].",token);break;case'Number':case'String':case'Boolean':case'Math':warning("Do not use {a} as a constructor.",token,c.value);break;case'Function':if(!option.evil){warning("The Function constructor is eval.");}
break;case'Date':case'RegExp':break;default:if(c.id!=='function'){i=c.value.substr(0,1);if(option.newcap&&(i<'A'||i>'Z')){warning("A constructor name should start with an uppercase letter.",token);}}}}else{if(c.id!=='.'&&c.id!=='['&&c.id!=='('){warning("Bad constructor.",token);}}}else{warning("Weird construction. Delete 'new'.",this);}
adjacent(token,nexttoken);if(nexttoken.id!=='('){warning("Missing '()' invoking a constructor.");}
this.first=c;return this;});syntax['new'].exps=true;infix('.',function(left,that){adjacent(prevtoken,token);var m=identifier();if(typeof m==='string'){countMember(m);}
that.left=left;that.right=m;if(!option.evil&&left&&left.value==='document'&&(m==='write'||m==='writeln')){warning("document.write can be a form of eval.",left);}
if(option.adsafe){if(left&&left.value==='ADSAFE'){if(m==='id'||m==='lib'){warning("ADsafe violation.",that);}else if(m==='go'){if(xmode!=='script'){warning("ADsafe violation.",that);}else if(adsafe_went||nexttoken.id!=='('||peek(0).id!=='(string)'||peek(0).value!==adsafe_id||peek(1).id!==','){error("ADsafe violation: go.",that);}
adsafe_went=true;adsafe_may=false;}}}
if(option.safe){for(;;){if(banned[m]===true){warning("ADsafe restricted word '{a}'.",token,m);}
if(predefined[left.value]!==true||nexttoken.id==='('){break;}
if(standard_member[m]===true){if(nexttoken.id==='.'){warning("ADsafe violation.",that);}
break;}
if(nexttoken.id!=='.'){warning("ADsafe violation.",that);break;}
advance('.');token.left=that;token.right=m;that=token;m=identifier();if(typeof m==='string'){countMember(m);}}}
return that;},160,true);infix('(',function(left,that){abut(prevtoken,token);nospace();var n=0,p=[];if(left){if(left.type==='(identifier)'){if(left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)){if(left.value!=='Number'&&left.value!=='String'&&left.value!=='Boolean'&&left.value!=='Date'){if(left.value==='Math'){warning("Math is not a function.",left);}else if(option.newcap){warning("Missing 'new' prefix when invoking a constructor.",left);}}}}else if(left.id==='.'){if(option.safe&&left.left.value==='Math'&&left.right==='random'){warning("ADsafe violation.",left);}}}
if(nexttoken.id!==')'){for(;;){p[p.length]=parse(10);n+=1;if(nexttoken.id!==','){break;}
comma();}}
advance(')');if(option.immed&&left.id==='function'&&nexttoken.id!==')'){warning("Wrap the entire immediate function invocation in parens.",that);}
nospace(prevtoken,token);if(typeof left==='object'){if(left.value==='parseInt'&&n===1){warning("Missing radix parameter.",left);}
if(!option.evil){if(left.value==='eval'||left.value==='Function'||left.value==='execScript'){warning("eval is evil.",left);}else if(p[0]&&p[0].id==='(string)'&&(left.value==='setTimeout'||left.value==='setInterval')){warning("Implied eval is evil. Pass a function instead of a string.",left);}}
if(!left.identifier&&left.id!=='.'&&left.id!=='['&&left.id!=='('&&left.id!=='&&'&&left.id!=='||'&&left.id!=='?'){warning("Bad invocation.",left);}}
that.left=left;return that;},155,true).exps=true;prefix('(',function(){nospace();var v=parse(0);advance(')',this);nospace(prevtoken,token);if(option.immed&&v.id==='function'){if(nexttoken.id==='('){warning("Move the invocation into the parens that contain the function.",nexttoken);}else{warning("Do not wrap function literals in parens unless they are to be immediately invoked.",this);}}
return v;});infix('[',function(left,that){nospace();var e=parse(0),s;if(e&&e.type==='(string)'){if(option.safe&&banned[e.value]===true){warning("ADsafe restricted word '{a}'.",that,e.value);}
countMember(e.value);if(!option.sub&&ix.test(e.value)){s=syntax[e.value];if(!s||!s.reserved){warning("['{a}'] is better written in dot notation.",e,e.value);}}}else if(!e||(e.type!=='(number)'&&(e.id!=='+'||e.arity!=='unary'))){if(option.safe){warning('ADsafe subscripting.');}}
advance(']',that);nospace(prevtoken,token);that.left=left;that.right=e;return that;},160,true);prefix('[',function(){this.first=[];if(nexttoken.id===']'){advance(']');return;}
var b=token.line!==nexttoken.line;if(b){indent+=option.indent;if(nexttoken.from===indent+option.indent){indent+=option.indent;}}
for(;;){if(b&&token.line!==nexttoken.line){indentation();}
parse(10);if(nexttoken.id===','){comma();if(nexttoken.id===','){warning("Extra comma.",token);}else if(nexttoken.id===']'){warning("Extra comma.",token);break;}}else{if(b){indent-=option.indent;indentation();}
break;}}
advance(']',this);return;},160);(function(x){x.nud=function(){var b,i,s,seen={};b=token.line!==nexttoken.line;if(b){indent+=option.indent;if(nexttoken.from===indent+option.indent){indent+=option.indent;}}
for(;;){if(nexttoken.id==='}'){break;}
if(b){indentation();}
i=optionalidentifier(true);if(!i){if(nexttoken.id==='(string)'){i=nexttoken.value;if(ix.test(i)){s=syntax[i];}
advance();}else if(nexttoken.id==='(number)'){i=nexttoken.value.toString();advance();}else{error("Expected '{a}' and instead saw '{b}'.",nexttoken,'}',nexttoken.value);}}
if(seen[i]===true){warning("Duplicate member '{a}'.",nexttoken,i);}
seen[i]=true;countMember(i);advance(':');nonadjacent(token,nexttoken);parse(10);if(nexttoken.id===','){comma();if(nexttoken.id===','||nexttoken.id==='}'){warning("Extra comma.",token);}}else{break;}}
if(b){indent-=option.indent;indentation();}
advance('}',this);return;};x.fud=function(){error("Expected to see a statement and instead saw a block.",token);};}(delim('{')));function varstatement(prefix){var name,value;if(funct['(onevar)']&&option.onevar){warning("Too many var statements.");}else if(!funct['(global)']){funct['(onevar)']=true;}
this.first=[];for(;;){nonadjacent(token,nexttoken);addlabel(identifier(),'unused');if(prefix){break;}
name=token;this.first.push(token);if(nexttoken.id==='='){nonadjacent(token,nexttoken);advance('=');nonadjacent(token,nexttoken);if(peek(0).id==='='&&nexttoken.identifier){error("Variable {a} was not declared correctly.",nexttoken,nexttoken.value);}
value=parse(0);name.first=value;}
if(nexttoken.id!==','){break;}
comma();}
return this;}
stmt('var',varstatement);stmt('new',function(){warning("'new' should not be used as a statement.");});function functionparams(){var i,t=nexttoken,p=[];advance('(');nospace();if(nexttoken.id===')'){advance(')');nospace(prevtoken,token);return;}
for(;;){i=identifier();p.push(i);addlabel(i,'parameter');if(nexttoken.id===','){comma();}else{advance(')',t);nospace(prevtoken,token);return p.join(', ');}}}
function doFunction(i){var s=scope;scope=Object.create(s);funct={'(name)':i||'"'+anonname+'"','(line)':nexttoken.line+1,'(context)':funct,'(breakage)':0,'(loopage)':0,'(scope)':scope};token.funct=funct;functions.push(funct);if(i){addlabel(i,'function');}
funct['(params)']=functionparams();block(false);scope=s;funct=funct['(context)'];}
blockstmt('function',function(){if(inblock){warning("Function statements cannot be placed in blocks. Use a function expression or move the statement to the top of the outer function.",token);}
var i=identifier();adjacent(token,nexttoken);addlabel(i,'unused');doFunction(i);if(nexttoken.id==='('&&nexttoken.line===token.line){error("Function statements are not invocable. Wrap the whole function invocation in parens.");}});prefix('function',function(){var i=optionalidentifier();if(i){adjacent(token,nexttoken);}else{nonadjacent(token,nexttoken);}
doFunction(i);if(funct['(loopage)']&&nexttoken.id!=='('){warning("Be careful when making functions within a loop. Consider putting the function in a closure.");}
return this;});blockstmt('if',function(){var t=nexttoken;advance('(');nonadjacent(this,t);nospace();parse(20);if(nexttoken.id==='='){warning("Expected a conditional expression and instead saw an assignment.");advance('=');parse(20);}
advance(')',t);nospace(prevtoken,token);block(true);if(nexttoken.id==='else'){nonadjacent(token,nexttoken);advance('else');if(nexttoken.id==='if'||nexttoken.id==='switch'){statement(true);}else{block(true);}}
return this;});blockstmt('try',function(){var b,e,s;if(option.adsafe){warning("ADsafe try violation.",this);}
block(false);if(nexttoken.id==='catch'){advance('catch');nonadjacent(token,nexttoken);advance('(');s=scope;scope=Object.create(s);e=nexttoken.value;if(nexttoken.type!=='(identifier)'){warning("Expected an identifier and instead saw '{a}'.",nexttoken,e);}else{addlabel(e,'exception');}
advance();advance(')');block(false);b=true;scope=s;}
if(nexttoken.id==='finally'){advance('finally');block(false);return;}else if(!b){error("Expected '{a}' and instead saw '{b}'.",nexttoken,'catch',nexttoken.value);}});blockstmt('while',function(){var t=nexttoken;funct['(breakage)']+=1;funct['(loopage)']+=1;advance('(');nonadjacent(this,t);nospace();parse(20);if(nexttoken.id==='='){warning("Expected a conditional expression and instead saw an assignment.");advance('=');parse(20);}
advance(')',t);nospace(prevtoken,token);block(true);funct['(breakage)']-=1;funct['(loopage)']-=1;}).labelled=true;reserve('with');blockstmt('switch',function(){var t=nexttoken,g=false;funct['(breakage)']+=1;advance('(');nonadjacent(this,t);nospace();this.condition=parse(20);advance(')',t);nospace(prevtoken,token);nonadjacent(token,nexttoken);t=nexttoken;advance('{');nonadjacent(token,nexttoken);indent+=option.indent;this.cases=[];for(;;){switch(nexttoken.id){case'case':switch(funct['(verb)']){case'break':case'case':case'continue':case'return':case'switch':case'throw':break;default:warning("Expected a 'break' statement before 'case'.",token);}
indentation(-option.indent);advance('case');this.cases.push(parse(20));g=true;advance(':');funct['(verb)']='case';break;case'default':switch(funct['(verb)']){case'break':case'continue':case'return':case'throw':break;default:warning("Expected a 'break' statement before 'default'.",token);}
indentation(-option.indent);advance('default');g=true;advance(':');break;case'}':indent-=option.indent;indentation();advance('}',t);if(this.cases.length===1||this.condition.id==='true'||this.condition.id==='false'){warning("This 'switch' should be an 'if'.",this);}
funct['(breakage)']-=1;funct['(verb)']=undefined;return;case'(end)':error("Missing '{a}'.",nexttoken,'}');return;default:if(g){switch(token.id){case',':error("Each value should have its own case label.");return;case':':statements();break;default:error("Missing ':' on a case clause.",token);}}else{error("Expected '{a}' and instead saw '{b}'.",nexttoken,'case',nexttoken.value);}}}}).labelled=true;stmt('debugger',function(){if(!option.debug){warning("All 'debugger' statements should be removed.");}});stmt('do',function(){funct['(breakage)']+=1;funct['(loopage)']+=1;block(true);advance('while');var t=nexttoken;nonadjacent(token,t);advance('(');nospace();parse(20);if(nexttoken.id==='='){warning("Expected a conditional expression and instead saw an assignment.");advance('=');parse(20);}
advance(')',t);nospace(prevtoken,token);funct['(breakage)']-=1;funct['(loopage)']-=1;}).labelled=true;blockstmt('for',function(){var s,t=nexttoken;funct['(breakage)']+=1;funct['(loopage)']+=1;advance('(');nonadjacent(this,t);nospace();if(peek(nexttoken.id==='var'?1:0).id==='in'){if(nexttoken.id==='var'){advance('var');varstatement(true);}else{switch(funct[nexttoken.value]){case'unused':funct[nexttoken.value]='var';break;case'var':break;default:warning("Bad for in variable '{a}'.",nexttoken,nexttoken.value);}
advance();}
advance('in');parse(20);advance(')',t);s=block(true);if(!option.forin&&(s.length>1||typeof s[0]!=='object'||s[0].value!=='if')){warning("The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.",this);}
funct['(breakage)']-=1;funct['(loopage)']-=1;return this;}else{if(nexttoken.id!==';'){if(nexttoken.id==='var'){advance('var');varstatement();}else{for(;;){parse(0,'for');if(nexttoken.id!==','){break;}
comma();}}}
nolinebreak(token);advance(';');if(nexttoken.id!==';'){parse(20);if(nexttoken.id==='='){warning("Expected a conditional expression and instead saw an assignment.");advance('=');parse(20);}}
nolinebreak(token);advance(';');if(nexttoken.id===';'){error("Expected '{a}' and instead saw '{b}'.",nexttoken,')',';');}
if(nexttoken.id!==')'){for(;;){parse(0,'for');if(nexttoken.id!==','){break;}
comma();}}
advance(')',t);nospace(prevtoken,token);block(true);funct['(breakage)']-=1;funct['(loopage)']-=1;}}).labelled=true;stmt('break',function(){var v=nexttoken.value;if(funct['(breakage)']===0){warning("Unexpected '{a}'.",nexttoken,this.value);}
nolinebreak(this);if(nexttoken.id!==';'){if(token.line===nexttoken.line){if(funct[v]!=='label'){warning("'{a}' is not a statement label.",nexttoken,v);}else if(scope[v]!==funct){warning("'{a}' is out of scope.",nexttoken,v);}
advance();}}
reachable('break');});stmt('continue',function(){var v=nexttoken.value;if(funct['(breakage)']===0){warning("Unexpected '{a}'.",nexttoken,this.value);}
nolinebreak(this);if(nexttoken.id!==';'){if(token.line===nexttoken.line){if(funct[v]!=='label'){warning("'{a}' is not a statement label.",nexttoken,v);}else if(scope[v]!==funct){warning("'{a}' is out of scope.",nexttoken,v);}
advance();}}
reachable('continue');});stmt('return',function(){nolinebreak(this);if(nexttoken.id==='(regexp)'){warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator.");}
if(nexttoken.id!==';'&&!nexttoken.reach){nonadjacent(token,nexttoken);parse(20);}
reachable('return');});stmt('throw',function(){nolinebreak(this);nonadjacent(token,nexttoken);parse(20);reachable('throw');});reserve('void');reserve('class');reserve('const');reserve('enum');reserve('export');reserve('extends');reserve('float');reserve('goto');reserve('import');reserve('let');reserve('super');function jsonValue(){function jsonObject(){var o={},t=nexttoken;advance('{');if(nexttoken.id!=='}'){for(;;){if(nexttoken.id==='(end)'){error("Missing '}' to match '{' from line {a}.",nexttoken,t.line+1);}else if(nexttoken.id==='}'){warning("Unexpected comma.",token);break;}else if(nexttoken.id===','){error("Unexpected comma.",nexttoken);}else if(nexttoken.id!=='(string)'){warning("Expected a string and instead saw {a}.",nexttoken,nexttoken.value);}
if(o[nexttoken.value]===true){warning("Duplicate key '{a}'.",nexttoken,nexttoken.value);}else if(nexttoken.value==='__proto__'){warning("Stupid key '{a}'.",nexttoken,nexttoken.value);}else{o[nexttoken.value]=true;}
advance();advance(':');jsonValue();if(nexttoken.id!==','){break;}
advance(',');}}
advance('}');}
function jsonArray(){var t=nexttoken;advance('[');if(nexttoken.id!==']'){for(;;){if(nexttoken.id==='(end)'){error("Missing ']' to match '[' from line {a}.",nexttoken,t.line+1);}else if(nexttoken.id===']'){warning("Unexpected comma.",token);break;}else if(nexttoken.id===','){error("Unexpected comma.",nexttoken);}
jsonValue();if(nexttoken.id!==','){break;}
advance(',');}}
advance(']');}
switch(nexttoken.id){case'{':jsonObject();break;case'[':jsonArray();break;case'true':case'false':case'null':case'(number)':case'(string)':advance();break;case'-':advance('-');if(token.character!==nexttoken.from){warning("Unexpected space after '-'.",token);}
adjacent(token,nexttoken);advance('(number)');break;default:error("Expected a JSON value.",nexttoken);}}
var itself=function(s,o){var a,i;JSLINT.errors=[];predefined=Object.create(standard);if(o){a=o.predef;if(a instanceof Array){for(i=0;i<a.length;i+=1){predefined[a[i]]=true;}}
if(o.adsafe){o.safe=true;}
if(o.safe){o.browser=false;o.css=false;o.debug=false;o.eqeqeq=true;o.evil=false;o.forin=false;o.nomen=true;o.on=false;o.rhino=false;o.safe=true;o.sidebar=false;o.strict=true;o.sub=false;o.undef=true;o.widget=false;predefined.Date=false;predefined['eval']=false;predefined.Function=false;predefined.Object=false;predefined.ADSAFE=true;predefined.lib=true;}
option=o;}else{option={};}
option.indent=option.indent||4;adsafe_id='';adsafe_may=false;adsafe_went=false;approved={};if(option.approved){for(i=0;i<option.approved.length;i+=1){approved[option.approved[i]]=option.approved[i];}}else{approved.test='test';}
tab='';for(i=0;i<option.indent;i+=1){tab+=' ';}
indent=0;global=Object.create(predefined);scope=global;funct={'(global)':true,'(name)':'(global)','(scope)':scope,'(breakage)':0,'(loopage)':0};functions=[];ids={};urls=[];src=false;xmode=false;stack=null;member={};membersOnly=null;implied={};inblock=false;lookahead=[];jsonmode=false;warnings=0;lex.init(s);prereg=true;prevtoken=token=nexttoken=syntax['(begin)'];assume();try{advance();if(nexttoken.value.charAt(0)==='<'){html();if(option.adsafe&&!adsafe_went){warning("ADsafe violation: Missing ADSAFE.go.",this);}}else{switch(nexttoken.id){case'{':case'[':option.laxbreak=true;jsonmode=true;jsonValue();break;case'@':case'*':case'#':case'.':case':':xmode='style';advance();if(token.id!=='@'||!nexttoken.identifier||nexttoken.value!=='charset'){error('A css file should begin with @charset "UTF-8";');}
advance();if(nexttoken.type!=='(string)'&&nexttoken.value!=='UTF-8'){error('A css file should begin with @charset "UTF-8";');}
advance();advance(';');styles();break;default:if(option.adsafe&&option.fragment){warning("ADsafe violation.",this);}
statements('lib');}}
advance('(end)');}catch(e){if(e){JSLINT.errors.push({reason:e.message,line:e.line||nexttoken.line,character:e.character||nexttoken.from},null);}}
return JSLINT.errors.length===0;};function to_array(o){var a=[],k;for(k in o){if(o.hasOwnProperty(k)){a.push(k);}}
return a;}
itself.report=function(option,sep){var a=[],c,e,f,i,k,l,m='',n,o=[],s,v,cl,ex,va,un,ou,gl,la;function detail(h,s,sep){if(s.length){o.push('<div><i>'+h+'</i> '+
s.sort().join(sep||', ')+'</div>');}}
s=to_array(implied);k=JSLINT.errors.length;if(k||s.length>0){o.push('<div id=errors><i>Error:</i>');if(s.length>0){s.sort();for(i=0;i<s.length;i+=1){s[i]='<code>'+s[i]+'</code>&nbsp;<i>'+
implied[s[i]].join(' ')+'</i>';}
o.push('<p><i>Implied global:</i> '+s.join(', ')+'</p>');c=true;}
for(i=0;i<k;i+=1){c=JSLINT.errors[i];if(c){e=c.evidence||'';o.push('<p>Problem'+(isFinite(c.line)?' at line '+(c.line+1)+' character '+(c.character+1):'')+': '+c.reason.entityify()+'</p><p class=evidence>'+
(e&&(e.length>80?e.slice(0,77)+'...':e).entityify())+'</p>');}}
o.push('</div>');if(!c){return o.join('');}}
if(!option){o.push('<br><div id=functions>');if(urls.length>0){detail("URLs<br>",urls,'<br>');}
s=to_array(scope);if(s.length===0){if(jsonmode){if(k===0){o.push('<p>JSON: good.</p>');}else{o.push('<p>JSON: bad.</p>');}}else{o.push('<div><i>No new global variables introduced.</i></div>');}}else{o.push('<div><i>Global</i> '+s.sort().join(', ')+'</div>');}
for(i=0;i<functions.length;i+=1){f=functions[i];cl=[];ex=[];va=[];un=[];ou=[];gl=[];la=[];for(k in f){if(f.hasOwnProperty(k)&&k.charAt(0)!=='('){v=f[k];switch(v){case'closure':cl.push(k);break;case'exception':ex.push(k);break;case'var':va.push(k);break;case'unused':un.push(k);break;case'label':la.push(k);break;case'outer':ou.push(k);break;case true:gl.push(k);break;}}}
o.push('<br><div class=function><i>'+f['(line)']+'</i> '+
(f['(name)']||'')+'('+
(f['(params)']||'')+')</div>');detail('Closure',cl);detail('Variable',va);detail('Exception',ex);detail('Outer',ou);detail('Global',gl);detail('<big><b>Unused</b></big>',un);detail('Label',la);}
a=[];for(k in member){if(typeof member[k]==='number'){a.push(k);}}
if(a.length){a=a.sort();m='<br><pre>/*members ';l=10;for(i=0;i<a.length;i+=1){k=a[i];n=k.name();if(l+n.length>72){o.push(m+'<br>');m='    ';l=1;}
l+=n.length+2;if(member[k]===1){n='<i>'+n+'</i>';}
if(i<a.length-1){n+=', ';}
m+=n;}
o.push(m+'<br>*/</pre>');}
o.push('</div>');}
return o.join('');};itself.edition='2009-05-02';return itself;}());;function CodeAssist(container,editor,options){this._container=container;this._editor=editor;this._options=options;this._assistKeyComboDetected=false;this._autoAssistTimerID=null;var self=this;try{$(editor.win.document).keyup(function(evt){return self._onEditorKeyUp(evt);}).keydown(function(evt){return self._onEditorKeyDown(evt);}).keypress(function(evt){return self._onEditorKeyPress(evt);}).mousedown(function(evt){return self._onEditorMouseDown(evt);});}catch(e){alert("Unable to install keyup handler on codemirror window");}}
CodeAssist.helperUrl="http://acreassist.freebaseapps.com/";CodeAssist.prototype.dispose=function(){this._cancelPopup();this._cancelAutoAssist();};CodeAssist.prototype.getSetting=function(name){switch(name){case"dotTrigger":return this._options.dotTrigger;}
return null;};CodeAssist.prototype.putSetting=function(name,value){switch(name){case"dotTrigger":this._options.dotTrigger=value;break;}};CodeAssist.prototype._onEditorMouseDown=function(evt){};CodeAssist.prototype._onEditorKeyDown=function(evt){if(evt.keyCode==32&&(evt.ctrlKey||evt.metaKey||evt.altKey)){this._assistKeyComboDetected=true;evt.preventDefault();return false;}else if(evt.keyCode==8){this._cancelPopup();}};CodeAssist.prototype._onEditorKeyUp=function(evt){if(this._assistKeyComboDetected){this._assistKeyComboDetected=false;this.startAssistAtCursor("");evt.preventDefault();return false;}};CodeAssist.prototype._onEditorKeyPress=function(evt){if((!evt.shiftKey&&evt.keyCode==32)||evt.charCode==32){return;}
this._cancelAutoAssist();if(!(evt.ctrlKey||evt.metaKey||evt.altKey)){if(this._options.dotTrigger&&((!evt.shiftKey&&evt.keyCode==46)||evt.charCode==46)){this._scheduleAutoAssist(".");}else if((!evt.shiftKey&&evt.keyCode==188)||evt.charCode==44){this._scheduleAutoAssist(",");}else if((evt.shiftKey&&evt.keyCode==57)||evt.charCode==40){this._scheduleAutoAssist("(");}else if((evt.shiftKey&&evt.keyCode==48)||evt.charCode==41){this._cancelPopup();}else if(evt.keyCode==38||evt.keyCode==40||evt.keyCode==33||evt.keyCode==34||evt.keyCode==35||evt.keyCode==36){this._cancelPopup();}}};CodeAssist.prototype._cancelAutoAssist=function(){if(this._autoAssistTimerID!=null){window.clearTimeout(this._autoAssistTimerID);this._autoAssistTimerID=null;}};CodeAssist.prototype._scheduleAutoAssist=function(trigger){var self=this;this._autoAssistTimerID=window.setTimeout(function(){self._autoAssistTimerID=null;self.startAssistAtCursor(trigger);},trigger=="."?1000:200);};CodeAssist.prototype._findCurrentNode=function(p,l,col,s){var veryFirstContentNode=this._editor.win.document.body.firstChild;var previousNode=p.line||veryFirstContentNode;var node=previousNode.nextSibling;var c=col;while(c>0&&node!=null&&(node.nodeType!=1||node.tagName.toLowerCase()!="br")&&node.firstChild!=null&&node.firstChild.nodeValue.length<c){c-=node.firstChild.nodeValue.length;previousNode=node;node=node.nextSibling;}
var left,top,height;if(node==null||node.tagName.toLowerCase()=="br"){if(node!=null){var offset=$(node).offset();if($.browser.msie&&previousNode!=null&&previousNode.tagName.toLowerCase()!="br"){left=previousNode.offsetWidth;height=previousNode.offsetHeight;}else{left=offset.left;height=node.offsetHeight;}}else{var offset=$(previousNode).offset();var charCount=previousNode.firstChild?previousNode.firstChild.nodeValue.length:0;left=offset.left+(charCount==0?0:(c*previousNode.offsetWidth/charCount));height=previousNode.offsetHeight;}
top=offset.top;}else{var offset=$(node).offset();var charCount=node.firstChild?node.firstChild.nodeValue.length:0;left=offset.left+(charCount==0?0:(c*node.offsetWidth/charCount));top=offset.top;height=node.offsetHeight;}
var currentNode;var currentNodeOffset;if(node!=null){return{left:left,top:top,height:height,currentNode:node,currentNodeOffset:c};}else{return{left:left,top:top,height:height,currentNode:previousNode,currentNodeOffset:(previousNode!=null&&previousNode.firstChild!=null)?previousNode.firstChild.nodeValue.length:0}}};CodeAssist.prototype.startAssistAtCursor=function(trigger){this._cancelPopup();this._cancelAutoAssist();var p=this._editor.cursorPosition(false);var l=this._editor.lineNumber(p.line)-1;var col=p.character;var s=this._editor.lineContent(p.line);var currentNodeInfo=this._findCurrentNode(p,l,col,s);var currentNode=currentNodeInfo.currentNode;var currentNodeOffset=currentNodeInfo.currentNodeOffset;if(currentNodeOffset==null){return;}
var text;var cursorOffset;if(currentNode.className.indexOf("xml-")==0){var checkEscape=false;if(currentNode.className=="xml-attribute"){var attributeName="";var pnode=currentNode.previousSibling;while(pnode!=null&&pnode.className!="xml-tagname"&&pnode.className!="xml-tagname-acre"){if(pnode.className=="xml-attname"){attributeName=pnode.firstChild.nodeValue;}
pnode=pnode.previousSibling;}
text=currentNode.firstChild.nodeValue.replace(/^["']/,'').replace(/["']$/,'');cursorOffset=currentNodeOffset-1;checkEscape=attributeName.indexOf("acre:")<0&&(pnode==null||pnode.className!="xml-tagname-acre");}else if(currentNode.className=="xml-text"){text=currentNode.firstChild.nodeValue;cursorOffset=currentNodeOffset;checkEscape=true;}else{return;}
var startCode=0;if(checkEscape){var text2=text.substr(0,cursorOffset);var brace=text2.lastIndexOf("{");var closeBrace=text2.lastIndexOf("}");if(brace>0&&text2.charAt(brace-1)=="$"&&closeBrace<brace){startCode=brace+1;}else{var dollar=text2.lastIndexOf("$");if(dollar>=0&&closeBrace<dollar){startCode=dollar+1;}else{return;}}}
text=text.substr(startCode);cursorOffset-=startCode;}else if(currentNode.tagName.toLowerCase()=="br"||currentNode.className=="whitespace"||(currentNode.className.indexOf("js-")==0&&currentNode.className!="js-comment")){if((currentNode.tagName.toLowerCase()=="br"||currentNode.className=="whitespace")&&this._options.isMjt){var pnode=currentNode.previousSibling;while(pnode!=null&&pnode.className.indexOf("xml-")<0&&pnode.className.indexOf("js-")!=0){pnode=pnode.previousSibling;}
if(pnode==null){return;}else if(pnode.className=="xml-punctuation"&&pnode.firstChild.nodeValue==">"){var pnode2=pnode.previousSibling;if(pnode2==null||pnode2.className!="xml-tagname-acre"||pnode2.firstChild.nodeValue!="acre:script"){return;}}else if(pnode.className.indexOf("xml-")==0){return;}}
text=s;cursorOffset=col;var precedingCode=[];var pnode=currentNode.previousSibling;while(pnode!=null&&pnode.className.indexOf("xml-")<0){if(pnode.tagName.toLowerCase()=="br"){precedingCode.unshift("\n");}else{precedingCode.unshift(pnode.firstChild.nodeValue);}
pnode=pnode.previousSibling;}
precedingCode=precedingCode.join("");text=precedingCode+
(currentNode.firstChild!=null?currentNode.firstChild.nodeValue.substr(0,currentNodeOffset):"");cursorOffset=precedingCode.length+currentNodeOffset;}else{return;}
if(trigger=="("||trigger==","){this._internalStartFunctionArgumentAssist({left:currentNodeInfo.left,top:currentNodeInfo.top,height:currentNodeInfo.height},l,col,text,cursorOffset);}else{this._internalStartApiAssist({left:currentNodeInfo.left,top:currentNodeInfo.top,height:currentNodeInfo.height},l,col,text,cursorOffset);}};CodeAssist.prototype._cancelPopup=function(){if("_popup"in this&&this._popup!=null){this._popup.cancel();this._popup=null;}};CodeAssist.prototype._internalStartApiAssist=function(positioning,editorLine,editorColumn,code,codeOffset){var tokenizer=new CodeAssist.QueryTokenizer(code,0,codeOffset);var tokens=[];var token;while((token=tokenizer.token())!=null){tokens.push(token);tokenizer.next();}
if(tokens.length>0&&tokens[tokens.length-1].type==CodeAssist.Token.Types.numberLiteral){return;}
var segments=[];for(var i=tokens.length-1;i>=0;i--){var token=tokens[i];if(token.type==CodeAssist.Token.Types.identifier){segments.unshift(token.content);}else if(token.type==CodeAssist.Token.Types.operator&&token.content=="."){segments.unshift(".");}else if(token.type==CodeAssist.Token.Types.error){if(segments.length==0){return;}else{break;}}else if(token.type!=CodeAssist.Token.Types.whitespace){break;}}
segments=segments.join("");while(true){var segments2=segments.replace(/\.\./g,'.');if(segments!=segments2){segments=segments2;}else{break;}}
var self=this;var offset=$(this._container).offset();offset.left-=this._editor.win.document.body.scrollLeft+document.body.scrollLeft;offset.top-=this._editor.win.document.body.scrollTop+document.body.scrollTop;var dot=segments.lastIndexOf(".");if(dot>=0){var prefix=segments.substr(dot+1);segments=segments.substr(0,dot);}else{var prefix=segments;segments="";}
var replaceToken=function(text,onDone,offset,extent){try{var line=self._editor.nthLine(editorLine+1);var startCol=editorColumn-prefix.length;var endCol=editorColumn;self._editor.selectLines(line,startCol,line,endCol);self._editor.editor.replaceSelection(text);}catch(e){}
offset=offset||text.length;extent=extent||text.length;window.setTimeout(function(){self._editor.selectLines(line,startCol+offset,line,startCol+extent);self._editor.editor.highlightAtCursor();self._editor.focus();if(onDone){onDone(startCol+extent);}},100);};var onCommit=function(entry){self._cancelPopup();if(typeof entry=="string"){replaceToken(entry);}else if(entry.type=="module"){replaceToken(entry.label+".",function(){self.startAssistAtCursor();});}else if(entry.type=="hash"){replaceToken(entry.label+"[");}else if(entry.type=="function"){var argCount="paramInfo"in entry?entry.paramInfo.length:entry.params.length;if(argCount>0){replaceToken(entry.label+"(",function(newColumn){var p=self._editor.cursorPosition(false);var l=self._editor.lineNumber(p.line)-1;var col=p.character;var s=self._editor.lineContent(p.line);var currentNodeInfo=self._findCurrentNode(p,l,col,s);self._showFunctionArgumentAssistance(entry,0,currentNodeInfo);});}else{replaceToken(entry.label+"()");}}else{replaceToken(entry.label);}};var onKeyDown=function(evt,text){if(editorColumn>0&&evt.keyCode==8&&text.length==0){self._cancelPopup();self._editor.focus();var line=self._editor.nthLine(editorLine+1);self._editor.selectLines(line,editorColumn-1,line,editorColumn);self._editor.editor.replaceSelection("");}else if(evt.keyCode==190||evt.charCode==46){replaceToken(text+".",function(){self.startAssistAtCursor();});}else if(evt.keyCode==57||evt.charCode==40){replaceToken(text+"(",function(){self._scheduleAutoAssist("(");});}else{return;}
evt.returnValue=false;evt.cancelBubble=true;if("preventDefault"in evt){evt.preventDefault();}
return false;};var createPopup=function(){self._popup=new CueCard.Popup(Math.round(offset.left+positioning.left),Math.round(offset.top+positioning.top),Math.round(positioning.height),[window,self._editor.win],{onCancel:function(mode){if(mode=="key"){self._editor.focus();}}});self._popup.elmt.html('<div></div>');};if(segments.length==0){createPopup();new CueCard.SuggestionController(self._popup,self._popup.elmt[0].firstChild,new CodeAssist.SearchSuggestor(this._getLocalVariables(),onCommit,onKeyDown),prefix);}else{var url=CodeAssist.helperUrl+"assist?segments="+encodeURIComponent(segments);var onDone=function(o){if(o.length>0){createPopup();new CueCard.SuggestionController(self._popup,self._popup.elmt[0].firstChild,new CodeAssist.ScopedSuggestor(o,onCommit,onKeyDown),prefix);}};var onError=function(){};CueCard.JsonpQueue.call(url,onDone,onError);}};CodeAssist.prototype._getLocalVariables=function(){var results=[];var trim=function(s){return s.replace(/^\s+/,'').replace(/\s+$/,'');};var elmts=this._editor.win.document.getElementsByTagName("span");for(var i=0;i<elmts.length;i++){var variableElmt=elmts[i];if(variableElmt.className=="js-variable"){var pnode=variableElmt.previousSibling;var isDeclaration=false;var isFunction=false;while(pnode!=null){if(pnode.className=="js-keyword"){var keyword=trim(pnode.firstChild.nodeValue);if(keyword=="var"){isDeclaration=true;}else if(keyword=="function"){isDeclaration=true;isFunction=true;}
break;}else if(pnode.className!="whitespace"){break;}
pnode=pnode.previousSibling;}
if(isDeclaration){var name=trim(variableElmt.firstChild.nodeValue);results.push({label:name,type:"var",description:isFunction?"local function":"local variable"});}}else if(variableElmt.className=="js-variabledef"){var name=trim(variableElmt.firstChild.nodeValue);results.push({label:name,type:"var",description:"local variable or function argument"});}}
return results;};CodeAssist.prototype._internalStartFunctionArgumentAssist=function(positioning,editorLine,editorColumn,code,codeOffset){var tokenizer=new CodeAssist.QueryTokenizer(code,0,codeOffset);var tokens=[];var token;while((token=tokenizer.token())!=null&&tokens.length<1000){tokens.push(token);tokenizer.next();}
if(tokens.length==0){return;}
var nestingLevel=0;var argumentIndex=0;for(var i=tokens.length-1;i>=0;i--){var token=tokens[i];if(token.type==CodeAssist.Token.Types.delimiter){if(token.content=="("||token.content=="["||token.content=="{"){if(nestingLevel==0){i--;break;}else{nestingLevel--;}}else if(token.content==")"||token.content=="]"||token.content=="}"){nestingLevel++;}else if(token.content==","){if(nestingLevel==0){argumentIndex++;}}}}
if(token==null||nestingLevel>0){return;}
var segments=[];for(;i>=0;i--){var token=tokens[i];if(token.type==CodeAssist.Token.Types.identifier){segments.unshift(token.content);}else if(token.type==CodeAssist.Token.Types.operator&&token.content=="."){segments.unshift(".");}else if(token.type!=CodeAssist.Token.Types.whitespace){break;}}
segments=segments.join("");while(true){var segments2=segments.replace(/\.\./g,'.');if(segments!=segments2){segments=segments2;}else{break;}}
if(segments.length==0){return;}
var self=this;var createPopup=function(){var offset=$(self._container).offset();offset.left-=self._editor.win.document.body.scrollLeft+document.body.scrollLeft;offset.top-=self._editor.win.document.body.scrollTop+document.body.scrollTop;self._popup=new CueCard.Popup(Math.round(offset.left+positioning.left),Math.round(offset.top+positioning.top),Math.round(positioning.height),[window,self._editor.win],{});};var url=CodeAssist.helperUrl+"assist_args?segments="+encodeURIComponent(segments);var onDone=function(o){if(o){createPopup();self._showFunctionArgumentAssistance(o,argumentIndex,positioning);}};var onError=function(){};CueCard.JsonpQueue.call(url,onDone,onError);};CodeAssist.prototype._showFunctionArgumentAssistance=function(entry,argumentIndex,positioning){var self=this;var offset=$(this._container).offset();offset.left-=this._editor.win.document.body.scrollLeft+document.body.scrollLeft;offset.top-=this._editor.win.document.body.scrollTop+document.body.scrollTop;if(this._popup==null){this._popup=new CueCard.Popup(Math.round(offset.left+positioning.left),Math.round(offset.top+positioning.top),Math.round(positioning.height),[window,this._editor.win],{onCancel:function(mode){if(mode=="key"){self._editor.focus();}}});}else{this._popup.elmt.empty();}
var divLine=$('<div class="codeAssist-argumentAssist-singleLine"></div>').appendTo(this._popup.elmt);if("paramInfo"in entry){for(var i=0;i<entry.paramInfo.length;i++){var info=entry.paramInfo[i];if(i>0){$('<span>, </span>').appendTo(divLine);}
if(i==argumentIndex){$('<b>'+info.name+'</b>').appendTo(divLine);var details=$('<div class="codeAssist-argumentAssist-details">'+'<span class="codeAssist-argumentAssist-type">'+info.type+'</span>'+', <span class="codeAssist-argumentAssist-optional">'+(info.optional?'optional':'required')+'</span>'+': <span class="codeAssist-argumentAssist-description">'+info.description+'</span>'+'</div>').appendTo(this._popup.elmt);if("structure"in info){var structureDiv=$('<div class="codeAssist-argumentAssist-structure">Keys:</div>').appendTo(details);var structureList=$('<ul></ul>').appendTo(structureDiv);for(var j=0;j<info.structure.length;j++){var field=info.structure[j];$('<li>'+field.name+' ('+field.type+'): '+field.description+'</li>').appendTo(structureList);}}}else{$('<span>'+info.name+'</span>').appendTo(divLine);}}}else{for(var i=0;i<entry.params.length;i++){if(i>0){$('<span>, </span>').appendTo(divLine);}
if(i==argumentIndex){$('<b>'+entry.params[i]+'</b>').appendTo(divLine);}else{$('<span>'+entry.params[i]+'</span>').appendTo(divLine);}}}
this._popup.reposition();};CodeAssist.renderApiSuggestion=function(suggestion,prefix){if("type"in suggestion&&suggestion.type=="function"){if("paramInfo"in suggestion){var params=[];$.each(suggestion.paramInfo,function(){params.push(this.name);});suggestion.hint="("+params.join(", ")+"): "+suggestion.description;}else{suggestion.hint="("+suggestion.params.join(", ")+"): "+suggestion.description;}}else if("description"in suggestion){suggestion.hint=suggestion.description;}
var label=suggestion.label;if(prefix.length>0){var offset=label.toLowerCase().indexOf(prefix);label=label.substr(0,offset)+"<b>"+label.substr(offset,prefix.length)+"</b>"+label.substr(offset+prefix.length);}
var className="cuecard-suggestion-entry codeAssist-entry";var deprecation="";if("deprecated"in suggestion&&suggestion.deprecated){className+=" codeAssist-deprecated";deprecation='<div class="codeAssist-deprecation">Deprecated';if("see"in suggestion){deprecation+=" - see "+(typeof suggestion.see=='string'?suggestion.see:suggestion.see.join(", "));}
deprecation+="</div>";}
suggestion.elmt=$('<a class="'+className+'" href="javascript:{}">'+'<span class="codeAssist-entry-title">'+label+'</span>'+deprecation+
("hint"in suggestion?(' <span class="cuecard-suggestion-hint">'+suggestion.hint+'</span>'):'')+'</a>');};CodeAssist.ScopedSuggestor=function(o,onCommit,onKeyDown){this._suggestions=o;this._onCommit=onCommit;this.onKeyDown=onKeyDown;for(var i=0;i<this._suggestions.length;i++){var suggestion=this._suggestions[i];CodeAssist.renderApiSuggestion(suggestion,"");}};CodeAssist.ScopedSuggestor.prototype.getSuggestions=function(prefix,onDone){var suggestions=[];for(var i=0;i<this._suggestions.length;i++){var suggestion=this._suggestions[i];if(prefix.length==0||suggestion.label.indexOf(prefix)>=0){suggestions.push(suggestion);}}
onDone(suggestions);};CodeAssist.ScopedSuggestor.prototype.commit=function(entry){this._onCommit(entry);};CodeAssist.SearchSuggestor=function(localVariables,onCommit,onKeyDown){this._localVariables=localVariables;this._onCommit=onCommit;this.onKeyDown=onKeyDown;for(var i=0;i<localVariables.length;i++){var suggestion=localVariables[i];CodeAssist.renderApiSuggestion(suggestion,"");}};CodeAssist.SearchSuggestor.prototype.getSuggestions=function(prefix,onDone){var url=CodeAssist.helperUrl+
(prefix.length==0?"assist?segments=":("search?q="+encodeURIComponent(prefix)));var suggestions=[];for(var i=0;i<this._localVariables.length;i++){var localVariable=this._localVariables[i];if(prefix.length==0||localVariable.label.toLowerCase().indexOf(prefix)>=0){suggestions.push(localVariable);}}
var onDone2=function(o){for(var i=0;i<o.length;i++){var suggestion=o[i];CodeAssist.renderApiSuggestion(suggestion,prefix);suggestions.push(suggestion);}
onDone(suggestions);};var onError=function(){onDone(suggestions);};CueCard.JsonpQueue.call(url,onDone2,onError);};CodeAssist.SearchSuggestor.prototype.commit=function(entry){this._onCommit(entry);};CodeAssist.QueryTokenizer=function(text,startIndex,endIndex){this._text=text+" ";this._maxIndex=endIndex;this._index=startIndex;this._line=0;this._col=0;this.next();};CodeAssist.QueryTokenizer.prototype.token=function(){return this._token;};CodeAssist.QueryTokenizer.prototype.index=function(){return this._index;};CodeAssist.QueryTokenizer._whitespaces=" \t\r\n";CodeAssist.QueryTokenizer.prototype.next=function(){this._token=null;if(this._index<this._maxIndex){var c1=this._text.charAt(this._index);var c2=this._text.charAt(this._index+1);var self=this;function advance(){self._index++;self._col++;}
function makeCurrentPos(){return new CodeAssist.TokenPos(self._index,self._line,self._col);};function makeCurrentPosAndIncrement(){var pos=makeCurrentPos();advance();return pos;};function makeSimpleToken(type,startPos,text){var endPos=makeCurrentPos();self._pos=endPos;self._token=new CodeAssist.Token(type,text||self._text.substring(startPos.offset,endPos.offset),startPos,endPos);};function parseWhitespace(){var startPos=makeCurrentPos();while(self._index<self._maxIndex){var c=self._text.charAt(self._index);if(CodeAssist.QueryTokenizer._whitespaces.indexOf(c)<0){break;}
if(c=="\n"){self._line++;self._col=0;}else{self._col++;}
self._index++;}
makeSimpleToken(CodeAssist.Token.Types.whitespace,startPos);};function parseString(opener){var startPos=makeCurrentPos();advance();var text="";var properlyClosed=false;while(self._index<self._maxIndex){c1=self._text.charAt(self._index);if(c1==opener){advance();properlyClosed=true;break;}else if(c1=='\r'||c1=='\n'){break;}
if(c1=="\\"){advance();text+=self._text.charAt(self._index);}else{text+=c1;}
advance();}
makeSimpleToken(CodeAssist.Token.Types[properlyClosed?"stringLiteral":"error"],startPos,text);};function parseNumber(){var startPos=makeCurrentPos();var sign=1;if(c1=='+'){advance();}else if(c1=='-'){advance();sign=-1;}
while(self._index<self._maxIndex&&CodeAssist.QueryTokenizer._isDigit(self._text.charAt(self._index))){advance();}
if(self._index<self._maxIndex&&self._text.charAt(self._index)=='.'){advance();while(self._index<self._maxIndex&&CodeAssist.QueryTokenizer._isDigit(self._text.charAt(self._index))){advance();}}
makeSimpleToken(CodeAssist.Token.Types.numberLiteral,startPos);};var keywords={"function":true,"return":true,"if":true,"else":true,"for":true,"while":true,"do":true,"break":true,"break":true,"switch":true,"case":true,"default":true,"with":true,"try":true,"catch":true,"finally":true,"throw":true,"instanceof":true,"typeof":true,"in":true};function parseIdentifier(){var startPos=makeCurrentPos();while(self._index<self._maxIndex){var c3=self._text.charAt(self._index);if(CodeAssist.QueryTokenizer._identifierCharacters.indexOf(c3)>=0||CodeAssist.QueryTokenizer._identifierPrefix.indexOf(c3)>=0){advance();}else{break;}}
var endPos=makeCurrentPos();var content=self._text.substring(startPos.offset,endPos.offset);self._pos=endPos;if(content in keywords){self._token=new CodeAssist.Token(CodeAssist.Token.Types.keyword,content,startPos,endPos);}else{self._token=new CodeAssist.Token(CodeAssist.Token.Types.identifier,content,startPos,endPos);}};function parseLineComment(){var startPos=makeCurrentPos();advance();advance();while(self._index<self._maxIndex&&self._text.charAt(self._index)!="\n"){advance();}
var endPos=makeCurrentPos();var content=self._text.substring(startPos.offset,endPos.offset);self._pos=endPos;self._token=new CodeAssist.Token(CodeAssist.Token.Types.endOfLineComment,content,startPos,endPos);};function parseComment(){var startPos=makeCurrentPos();advance();advance();var properlyClosed=false;while(self._index<self._maxIndex){c1=self._text.charAt(self._index);c2=self._text.charAt(self._index+1);if(c1=="*"&&c2=="/"){advance();advance();properlyClosed=true;break;}else{advance();}}
var endPos=makeCurrentPos();var content=self._text.substring(startPos.offset,endPos.offset);self._pos=endPos;self._token=new CodeAssist.Token(CodeAssist.Token.Types[properlyClosed?"comment":"error"],content,startPos,endPos);};function parseRegex(){var startPos=makeCurrentPos();advance();var properlyClosed=false;while(self._index<self._maxIndex){c1=self._text.charAt(self._index);advance();if(c1=="/"){properlyClosed=true;break;}else if(c1=="\\"&&self._index<self._maxIndex){advance();}}
if(self._index<self._maxIndex&&"gi".indexOf(self._text.charAt(self._index))>=0){advance();}
var endPos=makeCurrentPos();var content=self._text.substring(startPos.offset,endPos.offset);self._pos=endPos;self._token=new CodeAssist.Token(CodeAssist.Token.Types[properlyClosed?"regexLiteral":"error"],content,startPos,endPos);};function parseOperator(){makeSimpleToken(CodeAssist.Token.Types.operator,makeCurrentPosAndIncrement());};if(CodeAssist.QueryTokenizer._whitespaces.indexOf(c1)>=0){parseWhitespace();}else if(c1=="/"){if(c2=="/"){parseLineComment();}else if(c2=="*"){parseComment();}else{if(CodeAssist.QueryTokenizer._whitespaces.indexOf(c2)>=0){makeSimpleToken(CodeAssist.Token.Types.operator,makeCurrentPosAndIncrement());}else{parseRegex();}}}else if("[{()}],:;".indexOf(c1)>=0){makeSimpleToken(CodeAssist.Token.Types.delimiter,makeCurrentPosAndIncrement());}else if(c1=='"'||c1=="'"){parseString(c1);}else if(c1=="-"||c1=="+"||CodeAssist.QueryTokenizer._isDigit(c1)){parseNumber();}else if("<>=!+-*/?&.".indexOf(c1)>=0){parseOperator();}else if(CodeAssist.QueryTokenizer._identifierPrefix.indexOf(c1)>=0){parseIdentifier();}else{makeSimpleToken(CodeAssist.Token.Types.error,makeCurrentPosAndIncrement());}}
return this._token;};CodeAssist.QueryTokenizer._isDigit=function(c){return"0123456789".indexOf(c)>=0;};CodeAssist.QueryTokenizer._identifierPrefix="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$";CodeAssist.QueryTokenizer._identifierCharacters="0123456789";CodeAssist.TokenPos=function(offset,line,col){this.offset=offset;this.line=line;this.col=col;}
CodeAssist.Token=function(type,content,start,end){this.type=type;this.content=content;this.start=start;this.end=end;};CodeAssist.Token.Types={error:-1,whitespace:0,operator:1,delimiter:2,numberLiteral:3,stringLiteral:4,booleanLiteral:5,regexLiteral:6,keyword:7,identifier:8,comment:9,endOfLineComment:10};

/* suppress.js */
window.__cuecard_suppress_loading=true;


/* cuecard-api.js */
if(!("CueCard" in window)){(function(){window.CueCard={loaded:false,loadingScriptsCount:0,error:null,helper:"http://cuecard.dfhuynh.user.dev.freebaseapps.com/",freebaseServiceUrl:"http://www.freebase.com/",params:{bundle:true,externals:true}};
var F=function(G){return G.getElementsByTagName("head")[0];
};
CueCard.findScript=function(M,I){var L=M.documentElement.getElementsByTagName("head");
for(var J=0;
J<L.length;
J++){var K=L[J].firstChild;
while(K!=null){if(K.nodeType==1&&K.tagName.toLowerCase()=="script"){var G=K.src;
var H=G.indexOf(I);
if(H>=0){return G;
}}K=K.nextSibling;
}}return null;
};
CueCard.includeJavascriptFile=function(L,I,G,M){G=G||"";
if(L.body==null){try{var J="'"+G.replace(/'/g,"&apos")+"'";
L.write("<script src='"+I+"' onerror="+J+(M?" charset='"+M+"'":"")+" type='text/javascript'>"+G+"<\/script>");
return ;
}catch(K){}}var H=L.createElement("script");
if(G){try{H.innerHTML=G;
}catch(K){}H.setAttribute("onerror",G);
}if(M){H.setAttribute("charset",M);
}H.type="text/javascript";
H.language="JavaScript";
H.src=I;
return F(L).appendChild(H);
};
CueCard.includeJavascriptFiles=function(J,G,I){for(var H=0;
H<I.length;
H++){CueCard.includeJavascriptFile(J,G+I[H]);
}CueCard.loadingScriptsCount+=I.length;
};
CueCard.includeCssFile=function(J,G){if(J.body==null){try{J.write("<link rel='stylesheet' href='"+G+"' type='text/css'/>");
return ;
}catch(I){}}var H=J.createElement("link");
H.setAttribute("rel","stylesheet");
H.setAttribute("type","text/css");
H.setAttribute("href",G);
F(J).appendChild(H);
};
CueCard.includeCssFiles=function(J,G,I){for(var H=0;
H<I.length;
H++){CueCard.includeCssFile(J,G+I[H]);
}};
CueCard.parseURLParameters=function(J,S,P){S=S||{};
P=P||{};
if(typeof J=="undefined"){J=location.href;
}var I=J.indexOf("?");
if(I<0){return S;
}J=(J+"#").slice(I+1,J.indexOf("#"));
var M=J.split("&"),L,R={};
var G=window.decodeURIComponent||unescape;
for(var O=0;
L=M[O];
O++){var T=L.indexOf("=");
var H=G(L.slice(0,T).replace(/\+/g," "));
var K=R[H];
if(typeof K=="undefined"){K=[];
}else{if(!(K instanceof Array)){K=[K];
}}R[H]=K.concat(G(L.slice(T+1).replace(/\+/g," ")));
}for(var O in R){if(!R.hasOwnProperty(O)){continue;
}var Q=P[O]||String;
var N=R[O];
if(!(N instanceof Array)){N=[N];
}if(Q===Boolean&&N[0]=="false"){S[O]=false;
}else{S[O]=Q.apply(this,N);
}}return S;
};
if(typeof CueCard_urlPrefix=="string"){CueCard.urlPrefix=CueCard_urlPrefix;
}else{var B=CueCard.findScript(document,"cuecard-api.js");
if(B==null){CueCard.error=new Error("Failed to derive URL prefix for CueCard API code files");
return ;
}CueCard.urlPrefix=B.substr(0,B.indexOf("cuecard-api.js"));
}CueCard.parseURLParameters(B,CueCard.params,{bundle:Boolean,externals:Boolean});
CueCard.externalPrefix=CueCard.urlPrefix+"external/";
CueCard.codemirrorPrefix=CueCard.externalPrefix+"CodeMirror/";
CueCard.jqueryuiPrefix=CueCard.externalPrefix+"jquery-ui/";
if(!(window.__cuecard_suppress_loading)){var E=["http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",CueCard.jqueryuiPrefix+"jquery-ui-1.7.1.custom.min.js",CueCard.codemirrorPrefix+"js/codemirror.js",CueCard.externalPrefix+"json2.js",CueCard.externalPrefix+"jquery.cookie.js"];
var D=["cuecard.js","mql-syntax.js","indent-writer.js","jsonize.js","queue.js","query-parser.js","query-model.js","ui.js","popup.js","topic-suggestors.js","static-choices-suggestor.js","property-suggestor.js","type-suggestor.js","suggestion-controller.js","query-editor.js","output-pane.js","control-pane.js","code-generation.js","example-dialog.js","examples.js","languages.js","x-metaweb-costs.js"];
var C=[CueCard.jqueryuiPrefix+"theme/jquery-ui-1.7.1.custom.css"];
var A=["cuecard.css","query-editor.css","popup.css","suggestion.css","output-pane.css","control-pane.css","example-dialog.css"];
if(CueCard.params.externals){CueCard.includeJavascriptFiles(document,"",E);
CueCard.includeCssFiles(document,"",C);
}if(CueCard.params.bundle){CueCard.includeJavascriptFiles(document,CueCard.urlPrefix,["cuecard-bundle.js"]);
CueCard.includeCssFiles(document,CueCard.urlPrefix,["cuecard-bundle.css"]);
}else{CueCard.includeJavascriptFiles(document,CueCard.urlPrefix+"scripts/",D);
CueCard.includeCssFiles(document,CueCard.urlPrefix+"styles/",A);
}}CueCard.loaded=true;
})();
}

/* cuecard-bundle.js */
CueCard.CodeGeneration={serializers:{}};
CueCard.CodeGeneration.generate=function(M,R,P){var O="";
var Q={_variables:{},createVariable:function(A){if(A in this._variables){return A+this._variables[A]++;
}else{this._variables[A]=1;
return A;
}}};
var S=Q.createVariable("q");
var N=Q.createVariable("o");
var L=new CueCard.SerializingContext(null);
L.setProperty("indentString","indentString" in P?P.indentString:"  ");
L.setProperty("indentLevel","indentLevel" in P?P.indentLevel:0);
L.setProperty("stream",{append:function(A){O+=A;
}});
R.prepareRootContext(L,P);
var K=new CueCard.IndentWriter(L);
var T=R.generateQueryCall(L,K,Q,M,P.variables,S,N);
L.setProperty("start",function(){return T;
});
L.setProperty("stop",function(){});
CueCard.CodeGeneration._processNode(M,R,L,K,Q);
return O;
};
CueCard.CodeGeneration._deriveElementName=function(G,H){if(G==null){var F=H.getProperty("path");
if(F!=null){if(F.charAt(0)=="!"){var E=F.substr(Math.max(F.indexOf(":")+1,1)).split("/");
return E[Math.max(0,E.length-2)];
}else{var E=F.substr(F.indexOf(":")+1).split("/");
return E[E.length-1];
}}}else{var E=G.split("/");
return E[E.length-1];
}return"entry";
};
CueCard.CodeGeneration._isImagePath=function(B){if(B.charAt(0)=="!"){return false;
}B=B.substr(B.indexOf(":")+1);
return B=="/common/topic/image"||B=="image";
};
CueCard.CodeGeneration._isImageNode=function(C){if(C==null||typeof C!="object"){return false;
}if(C instanceof Array){if(C.length==1&&typeof C[0]=="object"){C=C[0];
}else{return false;
}}for(var D in C){if(D!="id"&&D!="guid"&&!CueCard.QueryNode.isMqlKeyword(D)){return false;
}}return true;
};
CueCard.CodeGeneration._processNode=function(P,Y,S,d,W){if(P==null){var X=S.getProperty("start")(true,false);
Y.outputSimpleFieldValue(X,S,d);
S.getProperty("stop")(true,false);
}else{if(typeof P!="object"){return ;
}else{if(P instanceof Array){if(P.length==0){var T=CueCard.CodeGeneration._deriveElementName(null,S);
var c=W.createVariable(T);
var b=W.createVariable(T.charAt(0));
var X=S.getProperty("start")(false,false);
Y.openNodeArray(S,d,W,X,c,b,"values");
Y.outputSimpleFieldValue(c,S,d);
Y.closeNodeArray(S,d,W,X,c,b,"values");
S.getProperty("stop")(false,false);
}else{if(P.length>1||typeof P[0]!="object"||"__identifier__" in P){return ;
}else{var Q=new CueCard.SerializingContext(S);
Q.setProperty("in-array",true);
arguments.callee(P[0],Y,Q,d,W);
}}}else{if(P["optional"]!="forbidden"){var Z=null;
var U=0;
for(var R in P){if(P.hasOwnProperty(R)&&R!="*"&&!CueCard.QueryNode.isMqlKeyword(R)){U++;
var V=P[R];
if(R.charAt(0)!="!"){var a=R.substr(R.indexOf(":")+1);
if(a=="type"||a=="/type/object/type"){if(V!=null&&typeof V=="string"){Z=V;
}}}}}CueCard.CodeGeneration._processTypedObjectNode(P,Z,U,Y,S,d,W);
}}}}};
CueCard.CodeGeneration._processTypedObjectNode=function(b,h,S,W,i,Y,V){var j=null;
var f=null;
var T=null;
var g,Z;
var U=("optional" in b&&b.optional===true);
function X(){var A=CueCard.CodeGeneration._deriveElementName(h,i);
f=V.createVariable(A);
if(i.getProperty("in-array")){T=V.createVariable(A.charAt(0));
}}if(i.getProperty("in-array")){var d=(S>0&&!("*" in b));
var g=function(){if(j==null){j=i.getProperty("start")(false,U);
X();
W.openNodeArray(i,Y,V,j,f,T,d?"fields":"object");
}return f;
};
var Z=function(){if(j!=null){W.closeNodeArray(i,Y,V,j,f,T,d?"fields":"object");
i.getProperty("stop")(false,U);
}};
}else{var g=function(){if(j==null){j=i.getProperty("start")(false,U);
X();
W.openNode(i,Y,V,j,f);
}return f;
};
var Z=function(){if(j!=null){W.closeNode(i,Y,V,j,f);
i.getProperty("stop")(false,U);
}};
}if(S==0||"*" in b){W.generateEmptyObjectNode(i,Y,V,g());
}else{for(var c in b){if(b.hasOwnProperty(c)&&c!="*"&&!CueCard.QueryNode.isMqlKeyword(c)){var e=b[c];
if(CueCard.CodeGeneration._isImagePath(c)&&CueCard.CodeGeneration._isImageNode(e)){W.generateImageField(i,Y,V,c,e,g);
}else{var a=W.createFieldContext(i,Y,V,c,g);
a.setProperty("path",c);
CueCard.CodeGeneration._processNode(e,W,a,Y,V);
}}}if("*" in b){var e=b["*"];
var a=W.openWildcardField(i,Y,V,g,e);
CueCard.CodeGeneration._processNode(e,W,a,Y,V);
W.closeWildcardField(i,Y,V,g,e);
}}Z();
};
CueCard.CodeGeneration.serializers["acre-template"]={prepareRootContext:function(D,C){},generateQueryCall:function(M,J,N,K,I,H,L){J.appendIndent();
J.append("<acre:script>");
J.appendLineBreak();
J.indent();
J.appendIndent();
J.append("var "+H+" = ");
CueCard.jsonize(K,{context:M,variables:I,resolveVariables:false});
J.append(";");
J.appendLineBreak();
J.appendIndent();
J.appendLineBreak();
J.appendIndent();
J.append("var "+L+" = acre.freebase.mqlread("+H+");");
J.appendLineBreak();
J.unindent();
J.appendIndent();
J.append("</acre:script>");
J.appendLineBreak();
return L+".result";
},outputSimpleFieldValue:function(E,D,F){F.append("${"+E+"}");
},openNodeArray:function(M,K,N,J,L,H,I){K.appendLineBreak();
K.appendIndent();
K.append('<ul acre:if="'+J+'.length != 0">');
K.appendLineBreak();
K.indent();
K.appendIndent();
K.append('<li acre:for="'+H+", "+L+" in "+J+'">');
if(I=="fields"){K.append("<table>");
}if(I=="fields"||I=="object"){K.appendLineBreak();
K.indent();
}},closeNodeArray:function(M,K,N,J,L,H,I){if(I=="fields"||I=="object"){K.unindent();
K.appendIndent();
}if(I=="fields"){K.append("</table>");
}K.append("</li>");
K.appendLineBreak();
K.unindent();
K.appendIndent();
K.append("</ul>");
K.appendLineBreak();
K.appendIndent();
K.append('<div acre:else=""><ins>[no element]</ins></div>');
K.appendLineBreak();
K.appendLineBreak();
},openNode:function(J,H,F,G,I){H.appendIndent();
H.append("<acre:script>var "+I+" = "+G+";</acre:script>");
H.appendLineBreak();
H.appendIndent();
H.append("<table>");
H.appendLineBreak();
H.indent();
},closeNode:function(J,H,F,G,I){H.unindent();
H.appendIndent();
H.append("</table>");
H.appendLineBreak();
},createFieldContext:function(K,J,G,L,H){var I=new CueCard.SerializingContext(K);
I.setProperty("in-array",false);
I.setProperty("start",function(A,B){var C=H();
J.appendIndent();
J.append("<tr><th>"+L+":</th>");
J.appendLineBreak();
J.indent();
J.appendIndent();
J.append("<td"+(B?" acre:if=\"'"+L+"' in "+C+" && "+C+"['"+L+"'] != null\"":"")+">");
if(!A){J.appendLineBreak();
J.indent();
}return C+"['"+L+"']";
});
I.setProperty("stop",function(A,B){if(!A){J.unindent();
J.appendIndent();
}J.append("</td>");
J.appendLineBreak();
if(B){J.appendIndent();
J.append('<td acre:else=""><ins>[no value]</ins></td>');
J.appendLineBreak();
}J.unindent();
J.appendIndent();
J.append("</tr>");
J.appendLineBreak();
});
return I;
},generateImageField:function(M,X,S,T,R,N){var O=N();
var U=O+"['"+T+"']";
X.appendIndent();
X.append("<tr><th>"+T+":</th>");
X.appendLineBreak();
X.indent();
X.appendIndent();
X.append("<td acre:if=\"'"+T+"' in "+O+" && "+U+' != null">');
X.appendLineBreak();
X.indent();
var Q=(R instanceof Array);
X.appendIndent();
if(Q){R=R[0];
var P=S.createVariable("image");
var V=S.createVariable("i");
var W=("guid" in R)?("/guid/${"+P+".guid.substr(1)}"):("${"+P+".id}");
X.append('<img acre:for="'+V+", "+P+" in "+U+'" src="${acre.environ.freebase_service_url}/api/trans/image_thumb'+W+'?mode=fillcrop&amp;maxwidth=100&amp;maxheight=100" /></td>');
}else{var W=("guid" in R)?("/guid/${"+U+".guid.substr(1)}"):("${"+U+".id}");
X.append('<img src="${acre.environ.freebase_service_url}/api/trans/image_thumb'+W+'?mode=fillcrop&amp;maxwidth=100&amp;maxheight=100" /></td>');
}X.appendLineBreak();
X.unindent();
X.appendIndent();
X.append('<td acre:else=""><ins>[no image]</ins></td>');
X.appendLineBreak();
X.unindent();
X.appendIndent();
X.append("</tr>");
X.appendLineBreak();
},openWildcardField:function(K,R,Q,L,O){var M=L();
var T=Q.createVariable("field");
var N=Q.createVariable("value");
R.appendIndent();
R.append('<tr acre:for="'+T+", "+N+" in "+M+'"><td>${'+T+"}:</td>");
R.appendLineBreak();
R.indent();
var P=N;
var S=new CueCard.SerializingContext(K);
S.setProperty("in-array",false);
S.setProperty("start",function(A,B){R.appendIndent();
R.append("<td>");
if(!A){R.appendLineBreak();
R.indent();
}return P;
});
S.setProperty("stop",function(A,B){if(!A){R.unindent();
R.appendIndent();
}R.append("</td>");
R.appendLineBreak();
});
return S;
},closeWildcardField:function(I,H,J,G,F){H.unindent();
H.appendIndent();
H.append("</tr>");
H.appendLineBreak();
},generateEmptyObjectNode:function(M,K,N,J){var H=N.createVariable("field");
var L=N.createVariable("value");
K.appendIndent();
K.append("<table>");
K.appendLineBreak();
K.indent();
var I=L;
K.appendIndent();
K.append('<tr acre:for="'+H+", "+L+" in "+J+'"><th>${'+H+"}:</th>");
K.appendLineBreak();
K.indent();
K.appendIndent();
K.append('<td acre:if="'+I+' instanceof Array">${'+I+".join(', ')}</td>");
K.appendLineBreak();
K.appendIndent();
K.append('<td acre:else="">${'+I+"}</td>");
K.appendLineBreak();
K.unindent();
K.appendIndent();
K.append("</tr>");
K.appendLineBreak();
K.unindent();
K.appendIndent();
K.append("</table>");
K.appendLineBreak();
}};
CueCard.ControlPane=function(D,C){this._elmt=$(D);
this._options=C||{};
this._constructUI();
this.layout();
};
CueCard.ControlPane.prototype.dispose=function(){};
CueCard.ControlPane.prototype.layout=function(){var B=(this._elmt[0].firstChild.offsetHeight-this._elmt[0].firstChild.firstChild.firstChild.offsetHeight-28)+"px";
this._elmt.find(".cuecard-controlPane-tabBody").css("height",B);
};
CueCard.ControlPane.prototype._constructUI=function(){var G=this._idPrefix="t"+Math.floor(1000000*Math.random());
function H(A,B){return'<li class="tab"><a href="#'+G+"-"+A+'"><span>'+B+"</span></a></li>";
}function E(A){return'<div class="cuecard-controlPane-tabBody" id="'+G+"-"+A+'"></div>';
}this._elmt.html('<div class="cuecard-controlPane"><div id="'+G+'"><ul>'+H(0,"Tools")+H(1,"Variables")+H(2,"Envelope")+H(3,"Settings")+'</ul><div class="tabbed-content">'+E(0)+E(1)+E(2)+E(3)+"</div></div></div>");
$("#"+G).tabs();
var F=this._elmt.find(".cuecard-controlPane-tabBody");
this._toolsTabBody=$(F[0]);
this._variablesTabBody=$(F[1]);
this._envelopeTabBody=$(F[2]);
this._settingsTabBody=$(F[3]);
this._constructToolsTabBody();
this._constructVariablesTabBody();
this._constructEnvelopeTabBody();
this._constructSettingsTabBody();
};
CueCard.ControlPane.prototype._constructToolsTabBody=function(){var E="r"+Math.floor(1000000*Math.random());
var D=this;
var F=function(A,C,B){return'<div class="cuecard-controlPane-powerTool"><button cc:command="'+A+'">'+C+'</button><div class="cuecard-controlPane-powerTool-hint">'+B+"</div></div>";
};
this._toolsTabBody.html('<div class="cuecard-controlPane-section"><table><tr valign="top"><td>'+F("qualify","Qualify All Properties",'Expand all properties to their full IDs (e.g., "id" &rarr; "/type/object/id").')+F("redangle","Turn Inside Out","Take the inner most query node {...} that contains the text cursor and make it the outermost query node.")+F("generate","Generate Acre Template","Generate an ACRE template that can render the result of this query.")+F("one-liner","One-liner","Reformat query into a one-liner.")+'</td><td width="40%">Results of tools<br/><input type="radio" name="'+E+'" value="replace" checked="true"> replace query (undo-able)<br/><input type="radio" name="'+E+'" value="output"> go into output pane</td></tr></table></div>');
this._toolsTabBody.find("button").click(function(A){return D._onCommandClick(A,this,this.getAttribute("cc:command"));
});
};
CueCard.ControlPane.prototype._constructVariablesTabBody=function(){this._variablesTabBody.html('<table class="cuecard-controlPane-variables"><tr><th width="30%">name</th><th width="50%">value</th><th></th></tr></table><div><button>Add</button></div>');
var C=this;
var D=function(J){var B=C._variablesTabBody.find("table")[0];
var A=B.insertRow(B.rows.length);
var I=A.insertCell(0);
I.innerHTML="<input />";
var K=A.insertCell(1);
K.innerHTML="<input />";
var L=A.insertCell(2);
L.innerHTML="<button>Remove</button>";
$(L.firstChild).click(function(){$(A).remove();
});
if(!(J)){I.firstChild.focus();
}};
this._variablesTabBody.find("button").click(D);
D(true);
};
CueCard.ControlPane.prototype._constructEnvelopeTabBody=function(){var G=function(B,C,A){return"<tr><td>"+B+"</td><td>"+C+(A.length>0?('<div class="cuecard-controlPane-hint">'+A+"</div>"):"")+"</td></tr>";
};
var J=['<option value="">--</option>'];
for(var H=0;
H<CueCard.Languages.length;
H++){var F=CueCard.Languages[H];
J.push('<option value="'+F.id+'">'+F.name+" ("+F.id+")</option>");
}this._envelopeAsOfTimeID="i"+Math.floor(1000000*Math.random());
this._envelopeUsePermissionOfID="i"+Math.floor(1000000*Math.random());
this._envelopeCursorID="i"+Math.floor(1000000*Math.random());
this._envelopePageID="i"+Math.floor(1000000*Math.random());
this._envelopeTabBody.html('<div class="cuecard-controlPane-explanation">The query envelope contains directives to the query engine, specifying how to execute the query or how to return the results.</div><table class="cuecard-controlPane-configurations">'+G("as_of_time",'<input name="'+this._envelopeAsOfTimeID+'" '+("as_of_time" in this._options?'value="'+this._options.as_of_time+'"':"")+"/>","Resolve the query based on data in Freebase as of the given time in ISO8601 format, e.g., 2009-02-28, 2009-03-13T22:16:40")+G("use_permission_of",'<input name="'+this._envelopeUsePermissionOfID+'" '+("use_permission_of" in this._options?'value="'+this._options.use_permission_of+'"':"")+"/>",'Specify the id of an object (typically a user, domain or type) whose permission you want to copy (<a href="http://freebaseapps.com/docs/mql/ch06.html#id2972357" target="_blank">more details</a>).')+G("page",'<input name="'+this._envelopePageID+'" /> <button class="cuecard-controlPane-configurations-page">Previous</button><button class="cuecard-controlPane-configurations-page">Next</button>','Page number starting from 1 if there is a "limit" property in the top level query node.')+G("cursor",'<div><input type="radio" name="'+this._envelopeCursorID+'" checked value=""> unspecified (return all results, possibly time-out)</div><div><input type="radio" name="'+this._envelopeCursorID+'" value="true"> true (start pagination with page size equal "limit" option in query)</div><div><input type="radio" name="'+this._envelopeCursorID+'" value="custom"> continue from cursor: <div class="cuecard-controlPane-configurations-cursor"><input type="text" name="'+this._envelopeCursorID+'" /><button class="cuecard-controlPane-configurations-cursor">Paste from Last Result</button> <button cc:run="true">Paste &amp; Run</button></div></div>',"")+G("lang",'<select class="cuecard-controlPane-configurations-languages">'+J.join("")+"</select>","Return text values in the given language (specified with the language's Freebase ID)")+G("escape",'<select><option value="">--</option><option value="html">html</option><option value="false">false</option></select>',"")+G("uniqueness_failure",'<select><option value="">--</option><option value="soft">soft</option></select>',"")+"</table>");
var I=this;
this._envelopeTabBody.find("input[type='text'][name='"+this._envelopeCursorID+"']").bind("change",function(){I._envelopeTabBody.find("input[type='radio'][value='custom']")[0].checked=true;
});
this._envelopeTabBody.find("button.cuecard-controlPane-configurations-cursor").click(function(){if(I._options.outputPane!=null){var A=I._options.outputPane.getJson();
if(A!==undefined&&A!==null&&"cursor" in A){I._envelopeTabBody.find("input[type='text'][name='"+I._envelopeCursorID+"']")[0].value=A.cursor;
I._envelopeTabBody.find("input[type='radio'][value='custom']")[0].checked=true;
if(I._options.queryEditor!=null&&this.getAttribute("cc:run")=="true"){I._options.queryEditor.run();
}}}});
this._envelopeTabBody.find("button.cuecard-controlPane-configurations-page").click(function(){var D=I._envelopeTabBody.find("input[type='text'][name='"+I._envelopePageID+"']")[0];
var A=D.value;
var C;
try{C=parseInt(A);
}catch(B){}if(typeof C!="number"||isNaN(C)){C=1;
}if(this.innerHTML=="Previous"){C--;
}else{C++;
}if(C<1){D.value="1";
return ;
}else{D.value=C;
if(I._options.queryEditor!=null){I._options.queryEditor.run();
}}});
};
CueCard.ControlPane.prototype._constructSettingsTabBody=function(){this._settingsTabBody.html('<div><input type="checkbox"'+($.cookie("cc_cp_clean")=="1"?" checked":"")+'> Always clean up query before running</div><div><input type="checkbox"'+($.cookie("cc_cp_align")=="0"?"":" checked")+'> Align JSON property values with spaces</div><div style="display: none;"><input type="checkbox"> Try running query as you edit</div><div><input type="checkbox"'+($.cookie("cc_cp_multi")=="0"?"":" checked")+"> Show error messages with multiple lines on multiple lines</div>");
};
CueCard.ControlPane.prototype._onCommandClick=function(D,F,E){switch(E){case"redangle":this._redangle();
break;
case"qualify":this._qualify();
break;
case"generate":this._generateCode();
break;
case"one-liner":this._oneLiner();
break;
}};
CueCard.ControlPane.prototype._redangle=function(){var F=this;
var D=this._options.queryEditor.getQueryModelAndContext();
var E=D.model;
E.toInsideOutQueryJson(D.context,CueCard.UI.createBlockingContinuations(function(B,A){F._setOutputJSON(A);
}));
};
CueCard.ControlPane.prototype._qualify=function(){var F=this;
var D=this._options.queryEditor.getQueryModelAndContext();
var E=D.model;
E.qualifyAllProperties(CueCard.UI.createBlockingContinuations(function(A){F._setOutputJSON(E.toQueryJson({qualifyAllProperties:true}));
}));
};
CueCard.ControlPane.prototype._generateCode=function(){var E=this._options.queryEditor.getQueryModelAndContext();
var F=E.model.toQueryJson();
var G=CueCard.CodeGeneration.generate(F,CueCard.CodeGeneration.serializers["acre-template"],{variables:this.getVariables()});
var H=$('<div title="Generated Acre Template"><textarea style="width: 100%; height: 100%; font-family: monospace; font-size: 12px;" wrap="off"></textarea></div>').appendTo(document.body);
H.find("textarea")[0].value=G;
H.find("textarea")[0].select();
H.dialog({modal:true,position:"center",width:800,height:500,buttons:{"OK":function(){H.dialog("close");
H.remove();
}}});
};
CueCard.ControlPane.prototype._oneLiner=function(){var E=this._options.queryEditor.getQueryModelAndContext();
var G=E.model.toQueryJson();
var F=this.getVariables();
var H=this.getJsonizingSettings({variables:F,resolveVariables:false});
H.breakLines=false;
this._options.queryEditor.content(CueCard.jsonize(G,H));
};
CueCard.ControlPane.prototype._setOutputJSON=function(B){switch(this._toolsTabBody.find("input:checked")[0].value){case"replace":this._options.queryEditor.content(CueCard.jsonize(B,this.getJsonizingSettings()));
break;
case"output":this._options.outputPane.setJSONContent(B,this.getJsonizingSettings());
break;
}};
CueCard.ControlPane.prototype.getQueryEnvelopeSetting=function(D){switch(D){case"as_of_time":var C=this._envelopeTabBody.find("input[name='"+this._envelopeAsOfTimeID+"']")[0].value;
if(C.length>0){return C;
}break;
}return null;
};
CueCard.ControlPane.prototype.getQueryEnvelope=function(){var J={};
var N=this._envelopeTabBody.find("input[name='"+this._envelopeAsOfTimeID+"']")[0].value;
if(N.length>0){J.as_of_time=N;
}var L=this._envelopeTabBody.find("input[name='"+this._envelopeUsePermissionOfID+"']")[0].value;
if(L.length>0){J.use_permission_of=L;
}var R=this._envelopeTabBody.find("input[name='"+this._envelopePageID+"']")[0].value;
if(R.length>0){try{J.page=parseInt(R);
}catch(J){}}var Q=this._envelopeTabBody.find("select");
var P=function(A){return Q[A].options[Q[A].selectedIndex].value;
};
var M=P(0);
if(M.length>0){J.lang=M;
}var O=P(1);
if(O.length>0){J.escape=(O=="false")?false:O;
}var K=P(2);
if(K.length>0){J.uniqueness_failure=K;
}switch(this._envelopeTabBody.find("input[type='radio'][name='"+this._envelopeCursorID+"']:checked")[0].value){case"true":J.cursor=true;
break;
case"custom":J.cursor=this._envelopeTabBody.find("input[type='text'][name='"+this._envelopeCursorID+"']")[0].value;
break;
}return J;
};
CueCard.ControlPane.prototype.getSetting=function(D){var E=this._settingsTabBody.find("input");
switch(D){case"cleanup":var F=E[0].checked;
$.cookie("cc_cp_clean",F?"1":"0",{expires:365});
return F;
case"alignJSONPropertyValues":var F=E[1].checked;
$.cookie("cc_cp_align",F?"1":"0",{expires:365});
return F;
case"liveQuery":var F=E[2].checked;
$.cookie("cc_cp_live",F?"1":"0",{expires:365});
return F;
case"multilineErrorMessages":var F=E[3].checked;
$.cookie("cc_cp_multi",F?"1":"0",{expires:365});
return F;
}return false;
};
CueCard.ControlPane.prototype.getJsonizingSettings=function(B){B=B||{};
B.indentCount=2;
B.alignFieldValues=this.getSetting("alignJSONPropertyValues");
return B;
};
CueCard.ControlPane.prototype.getVariables=function(){var L={};
var M=this._variablesTabBody.find("table")[0];
for(var N=1;
N<M.rows.length;
N++){var J=M.rows[N];
var H=J.cells[0].firstChild.value;
var K=J.cells[1].firstChild.value;
try{K=JSON.parse(K);
}catch(I){}L[H]=K;
}return L;
};
CueCard.createComposition=function(K){var L=new CueCard.QueryEditor(K.queryEditorElement,K["queryEditorOptions"]);
var H=null;
var J=null;
if("outputPaneElement" in K){var I=K["outputPaneOptions"]||{};
I.queryEditor=L;
H=new CueCard.OutputPane(K.outputPaneElement,I);
L.setOutputPane(H);
}if("controlPaneElement" in K){var G=K["controlPaneOptions"]||{};
G.queryEditor=L;
if(H!=null){G.outputPane=H;
}J=new CueCard.ControlPane(K.controlPaneElement,G);
L.setControlPane(J);
}return{queryEditor:L,outputPane:H,controlPane:J};
};
CueCard.ExampleDialog=function(B){this._options=B||{};
this._constructUI();
};
CueCard.ExampleDialog._dialog=null;
CueCard.ExampleDialog.prototype.dispose=function(){};
CueCard.ExampleDialog.prototype._constructUI=function(){if(CueCard.ExampleDialog._dialog==null){CueCard.ExampleDialog._dialog=$('<div id="cuecard-examples-dialog" title="Examples"><div class="cuecard-examples-dialog-columnHeader cuecard-examples-dialog-column-0">Techniques</div><div class="cuecard-examples-dialog-columnHeader cuecard-examples-dialog-column-1">Examples</div><div class="cuecard-examples-dialog-columnHeader cuecard-examples-dialog-column-2">Query</div><div class="cuecard-examples-dialog-columnBody cuecard-examples-dialog-column-0"></div><div class="cuecard-examples-dialog-columnBody cuecard-examples-dialog-column-1"></div><textarea class="cuecard-examples-dialog-columnBody cuecard-examples-dialog-column-2 cuecard-examples-query" readonly="true" wrap="off" /></div>').appendTo(document.body);
var R=CueCard.ExampleDialog._dialog.find("textarea")[0];
var L=CueCard.ExampleDialog._dialog.find(".cuecard-examples-dialog-columnBody");
var O=function(){var C=10;
var B=5;
var G=$("#cuecard-examples-dialog")[0];
var A=G.offsetHeight-35;
L.css("top","30px").css("height",A+"px");
var D=200;
var H=(G.offsetWidth-2*C-2*B)-D;
var E=Math.round(H*0.5);
var F=Math.round(H*0.5);
$(".cuecard-examples-dialog-column-0").css("left",C+"px").css("width",D+"px");
$(".cuecard-examples-dialog-column-1").css("left",(C+D+B)+"px").css("width",E+"px");
$(".cuecard-examples-dialog-column-2").css("left",(C+D+E+2*B)+"px").css("width",F+"px");
};
var U={"all":[]};
var S=function(){CueCard.ExampleDialog._dialog.find(".cuecard-examples-example").removeClass("cuecard-examples-example-selected");
};
var M=function(B,A){S();
$(B).addClass("cuecard-examples-example-selected");
R.value=CueCard.jsonize(CueCard.Examples[A].query,{indentCount:2});
};
var T=function(C,D){$('<a href="javascript:{}" class="cuecard-examples-example" id="cuecard-example-'+C+'">'+D.name+"</a>").click(function(){M(this,C);
}).appendTo(L[1]);
for(var A=0;
A<D.techniques.length;
A++){var B=D.techniques[A];
if(B in U){U[B].push(C);
}else{U[B]=[C];
}}};
CueCard.Examples.sort(function(B,A){return B.name.localeCompare(A.name);
});
for(var V=0;
V<CueCard.Examples.length;
V++){T(V,CueCard.Examples[V]);
}var N=function(D,C){CueCard.ExampleDialog._dialog.find(".cuecard-examples-technique").removeClass("cuecard-examples-technique-selected");
$(D).addClass("cuecard-examples-technique-selected");
if(C=="all"){CueCard.ExampleDialog._dialog.find(".cuecard-examples-example").show();
}else{CueCard.ExampleDialog._dialog.find(".cuecard-examples-example").hide();
var B=U[C];
for(var A=0;
A<B.length;
A++){$("#cuecard-example-"+B[A]).show();
}}S();
R.value="";
};
var P=function(A){$('<a href="javascript:{}" class="cuecard-examples-technique'+(A=="all"?" cuecard-examples-technique-selected":"")+'">'+A+" ("+(A=="all"?CueCard.Examples.length:U[A].length)+")</a>").click(function(){N(this,A);
}).appendTo(L[0]);
};
for(var V=0;
V<CueCard.ExampleTechniques.length;
V++){P(CueCard.ExampleTechniques[V]);
}$.ui.dialog.defaults.bgiframe=true;
CueCard.ExampleDialog._dialog.dialog({autoOpen:false,modal:true,resizable:true,position:"center",minWidth:800,minHeight:300,resize:O,open:O});
}var Q=this;
CueCard.ExampleDialog._dialog.dialog("option","width",$(window).width()-150).dialog("option","height",$(window).height()-200).dialog("option","buttons",{"Paste & Run":function(){$(this).dialog("close");
Q._options.onDone(CueCard.ExampleDialog._dialog.find("textarea")[0].value);
},"Cancel":function(){$(this).dialog("close");
}});
CueCard.ExampleDialog._dialog.dialog("open");
};
CueCard.ExampleTechniques=["all","basic","sorting","text search","range constraint","date query","multiple constraints on same property","limiting number of results","geographic location","compound value type (CVT)","schema inspection","attribution","adding data"];
CueCard.Examples=[{name:"Vietnamese restaurants in Aspen, Colorado",query:[{"/business/business_location/address":{"citytown":"Aspen","state_province_region":"Colorado"},"cuisine":"Vietnamese","name":null,"id":null,"type":"/dining/restaurant"}],techniques:["basic","geographic location"]},{name:"Properties of /music/artist",query:[{"id":"/music/artist","properties":[{}],"type":"/type/type"}],techniques:["schema inspection"]},{name:"All types created by the user jamie",query:[{"creator":"/user/jamie","name":null,"id":null,"type":"/type/type"}],techniques:["attribution"]},{name:"Cloud classifications sorted by name",query:[{"clouds":[],"name":null,"id":null,"sort":"name","type":"/meteorology/cloud_classification"}],techniques:["basic","sorting"]},{name:"U.S. states containing cities whose names start with 'Blue' or 'Red'",query:[{"a:contains":[{"name":null,"id":null,"name~=":"^Red","type":"/location/citytown"}],"b:contains":[{"name":null,"id":null,"name~=":"^Blue","type":"/location/citytown"}],"b:type":"/location/us_state","name":null,"id":null,"type":"/location/location"}],techniques:["text search","multiple constraints on same property"]},{name:"2 of The Police's albums and their tracks",query:{"album":[{"id":null,"limit":2,"name":null,"track":[]}],"id":null,"name":"The Police","type":"/music/artist"},techniques:["basic","limiting number of results"]},{name:"25 Songs with the word 'love' in their titles, with release date, album and artist",query:[{"album":{"artist":[],"name":null,"id":null,"release_date":null},"limit":25,"name":null,"name~=":"Love*","type":"/music/track"}],techniques:["text search","limiting number of results","date query"]},{name:"Films starring both Joe Pesci and Robert de Niro, showing their full cast",query:[{"a:starring":[{"actor":"Joe Pesci"}],"b:starring":[{"actor":"Robert de Niro"}],"name":null,"id":null,"starring":[{"actor":null}],"type":"/film/film"}],techniques:["multiple constraints on same property","compound value type (CVT)"]},{name:"32 actors born in the 1960s, with two films of each actor",query:[{"/people/person/date_of_birth":null,"/people/person/date_of_birth<":"1970","/people/person/date_of_birth>=":"1960","film":[{"film":null,"id":null,"limit":2}],"limit":35,"name":null,"id":null,"type":"/film/actor"}],techniques:["multiple constraints on same property","date query","limiting number of results","range constraint"]},{name:"Directors who have directed both Parker Posey and any actor named Robert (in possibly different films)",query:[{"a:film":[{"name":null,"id":null,"starring":{"actor":"Parker Posey"}}],"b:film":[{"name":null,"id":null,"starring":{"actor":null,"actor~=":"Robert*"}}],"name":null,"id":null,"type":"/film/director"}],techniques:["multiple constraints on same property","text search","compound value type (CVT)"]},{name:"Music artists with albums containing a track called 'One Tree Hill'",query:[{"album":[{"name":null,"id":null,"track":[{"length":null,"name":"One Tree Hill"}]}],"name":null,"id":null,"type":"/music/artist"}],techniques:["compound value type (CVT)","basic"]},{name:"Everything about 'Jimi Hendrix'",query:{"*":null,"name":"Jimi Hendrix","type":"/music/artist"},techniques:["basic"]},{name:"Kevin Bacon's films, with cast, producers, music, etc.",query:[{"film":[{"film":{"imdb_id":[],"music":[],"name":null,"id":null,"produced_by":[],"starring":[{"actor":[{}]}],"type":[]}}],"name":"Kevin Bacon","type":"/film/actor"}],techniques:["basic","compound value type (CVT)"]},{name:"When 'Star Wars Episode IV' was added to the database, and by whom",query:[{"creator":null,"id":"/wikipedia/en/Star_Wars_Episode_IV","name":null,"timestamp":null,"type":"/film/film"}],techniques:["attribution"]},{name:"Tracks on Synchronicity longer than 300 seconds",query:[{"artist":"The Police","name":"Synchronicity","track":[{"length":null,"length>":300,"name":null}],"type":"/music/album"}],techniques:["range constraint"]},{name:"Properties of a particular type (/government/politician)",query:{"id":"/government/politician","properties":[],"type":"/type/type"},techniques:["schema inspection"]},{name:"Properties of a particular property (/type/object/name)",query:{"*":null,"id":"/type/object/name","type":"/type/property"},techniques:["schema inspection"]},{name:"Types in a particular domain (/music)",query:{"id":"/music","type":"/type/domain","types":[]},techniques:["schema inspection"]},{name:"Creating a new topic given a name and a type",query:{"create":"unless_exists","name":"Test Object 1","type":"/base/mqlexamples/testobject","id":null,"guid":null},techniques:["adding data"]},{name:"Setting a basic unique property to a topic",query:{"name":"Test Object 1","type":"/base/mqlexamples/testobject","id":null,"basic_property":{"value":42,"connect":"update"}},techniques:["adding data"]},{name:"Connecting one topic to another",query:{"name":"Test Object 1","type":"/base/mqlexamples/testobject","id":null,"link_to_topic":{"name":"Test Object 2","type":"/base/mqlexamples/testobject","id":null,"connect":"insert"}},techniques:["adding data"]},{name:"Deleting a link between two topics",query:{"name":"Test Object 1","type":"/base/mqlexamples/testobject","id":null,"link_to_topic":{"name":"Test Object 2","type":"/base/mqlexamples/testobject","id":null,"connect":"delete"}},techniques:["adding data"]}];
CueCard.SerializingContext=function(B){this._parent=B;
this._root=(B==null)?this:B.getRoot();
this._properties={};
};
CueCard.SerializingContext.prototype={getProperty:function(B){return(B in this._properties)?this._properties[B]:(this._parent!=null?this._parent.getProperty(B):null);
},setProperty:function(C,D){this._properties[C]=D;
},getRoot:function(){return this._root;
},getRootProperty:function(B){return this.getRoot().getProperty(B);
},setRootProperty:function(C,D){return this.getRoot().setProperty(C,D);
},create:function(){return new SerializingContext(this);
}};
CueCard.IndentWriter=function(B){this._context=B;
this._stream=B.getProperty("stream");
};
CueCard.IndentWriter.prototype={appendLineBreak:function(){this._stream.append("\n");
},appendIndent:function(){var F=this._context.getRootProperty("indentLevel");
var E=this._context.getRootProperty("indentString");
for(var D=0;
D<F;
D++){this._stream.append(E);
}},indent:function(){this._context.setRootProperty("indentLevel",this._context.getRootProperty("indentLevel")+1);
},unindent:function(){this._context.setRootProperty("indentLevel",this._context.getRootProperty("indentLevel")-1);
},append:function(B){this._stream.append(B);
}};
(function(){var R={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"'":"\\'","\\":"\\\\"};
function J(A){if(/["\\\x00-\x1f]/.test(A)){return A.replace(/([\x00-\x1f\\"])/g,function(B,C){var D=R[C];
if(D){return D;
}D=C.charCodeAt();
return"\\u00"+Math.floor(D/16).toString(16)+(D%16).toString(16);
});
}else{return A;
}}function O(A){return A!=null&&typeof A=="object"&&!(A instanceof Array)&&!("__identifier__" in A);
}function K(A){return A!=null&&A instanceof Array;
}function M(B){for(var A in B){if(B.hasOwnProperty(A)){return true;
}}return false;
}function P(A){return A.length==0||(A.length==1&&O(A[0])&&!M(A[0]));
}var L=CueCard.jsonize=function(U,G){G=(G)?G:{};
var A="";
var F=("quoteAllFieldNames" in G)?G.quoteAllFieldNames:true;
var B=("variables" in G)?G.variables:{};
var I=("resolveVariables" in G)?G.resolveVariables:false;
if("context" in G){var V=new CueCard.SerializingContext(G.context);
}else{var E=("indentCount" in G)?G.indentCount:4;
var C="";
for(var D=0;
D<E;
D++){C+=" ";
}var V=new CueCard.SerializingContext(null);
V.setProperty("indentCount",E);
V.setProperty("indentString",C);
V.setProperty("indentLevel",0);
V.setProperty("stream",{append:function(S){A+=S;
}});
}V.setProperty("maxFieldLength",("maxFieldLength" in G)?G.maxFieldLength:15);
V.setProperty("breakLines",("breakLines" in G)?G.breakLines:true);
V.setProperty("alignFieldValues",("alignFieldValues" in G)?G.alignFieldValues:true);
V.setProperty("collapseSingleObjectArray",("collapseSingleObjectArray" in G)?G.collapseSingleObjectArray:true);
V.setProperty("variables",B);
V.setProperty("resolveVariables",I);
V.setProperty("encodeJavascriptString",("encodeJavascriptString" in G)?G["encodeJavascriptString"]:J);
V.setRootProperty("fieldNameEncoder",{_m:{},encode:function(S){if(S in this._m){return this._m[S];
}else{var T=J(S);
this._m[S]=T=(F||/\W/.test(T))?('"'+T+'"'):T;
return T;
}}});
V.setProperty("path",[]);
V.setRootProperty("contextualize",("contextualize" in G)?G.contextualize:function(T,S){return T;
});
var H=new CueCard.IndentWriter(V);
L.converters["anything"](U,V,H);
return A;
};
L.converters={"anything":function(A,C,B){if(A==null){L.converters["null"](A,C,B);
}else{if(A instanceof Array){L.converters["array"](A,C,B);
}else{if(A instanceof Object){L.converters["object"](A,C,B);
}else{L.converters[typeof A](A,C,B);
}}}},"array":function(B,G,E){var D=G.getProperty("breakLines");
if(B.length==0){E.append("[]");
return ;
}else{if(B.length==1){if(O(B[0])){if(M(B[0])){if(G.getProperty("collapseSingleObjectArray")){E.append("[");
var A=B[0];
L.converters["object"](A,G,E);
E.append("]");
return ;
}}else{E.append("[{}]");
return ;
}}}}E.append("[");
if(D){E.appendLineBreak();
E.indent();
}else{E.append(" ");
}var C=B.length;
for(var H=0;
H<C;
H++){var A=B[H];
var F=L.converters[A==null?"null":typeof A];
if(F){if(D){E.appendIndent();
}F(A,G,E);
if(H<C-1){E.append(",");
}if(D){E.appendLineBreak();
}else{E.append(" ");
}}}if(D){E.unindent();
E.appendIndent();
}E.append("]");
},"boolean":function(C,B,A){A.append(String(C));
},"null":function(C,B,A){A.append("null");
},"undefined":function(C,B,A){A.append("undefined");
},"number":function(C,B,A){A.append(isFinite(C)?String(C):"null");
},"object":function(b,h,A){if(b instanceof Array){L.converters["array"](b,h,A);
}else{if("__identifier__" in b){var g=b["__identifier__"];
var B=h.getProperty("resolveVariables");
var e=h.getProperty("variables");
if(g in e){if(B){var H=e[g];
L.converters["anything"](H,h,A);
}else{A.append(g);
}}else{L.converters["anything"](g,h,A);
}}else{var I=h.getRootProperty("contextualize");
var D=h.getProperty("path");
var G=h.getProperty("breakLines");
var i=h.getProperty("alignFieldValues");
A.append("{");
if(G){A.appendLineBreak();
A.indent();
}else{A.append(" ");
}var f=0;
var d=0;
var F=h.getRootProperty("fieldNameEncoder");
for(var C in b){if(b.hasOwnProperty(C)){var H=b[C];
f++;
if(!O(H)&&(!K(H)||P(H))){d=Math.max(d,F.encode(C).length);
}}}d=Math.min(d,h.getProperty("maxFieldLength"));
for(var C in b){if(b.hasOwnProperty(C)){var H=b[C];
var j=L.converters[H==null?"null":typeof H];
var c=F.encode(C);
if(G){A.appendIndent();
}A.append(c);
A.append(": ");
if(G&&i&&(!O(H)&&(!K(H)||P(H)))){for(var E=c.length;
E<d;
E++){A.append(" ");
}}D.unshift({field:C});
j(H,I(h,D),A);
D.shift();
f--;
if(f>0){A.append(",");
}if(G){A.appendLineBreak();
}else{A.append(" ");
}}}if(G){A.unindent();
A.appendIndent();
}A.append("}");
}}},"string":function(C,B,A){A.append('"'+B.getProperty("encodeJavascriptString")(C)+'"');
},"null":function(C,B,A){A.append("null");
}};
function N(){var B={};
for(var A=0;
A<arguments.length;
A++){B[arguments[A]]=true;
}return function(C,E){if(E.length>0&&E[0].field in B){var D=C.create();
D.setProperty("breakLines",false);
return D;
}else{return C;
}};
}function Q(A){return function(C,B){if(B.length==A){var D=C.create();
D.setProperty("breakLines",false);
return D;
}else{return C;
}};
}})();
CueCard.Languages=[{name:"Afrikaans",id:"/lang/af"},{name:"Akkadian",id:"/lang/kk"},{name:"Albanian",id:"/lang/sq"},{name:"Amharic",id:"/lang/am"},{name:"Arabic",id:"/lang/ar"},{name:"Armenian",id:"/lang/hy"},{name:"Artificial",id:"/lang/art"},{name:"Asturian",id:"/lang/ast"},{name:"Australian languages",id:"/lang/aus"},{name:"Azerbaijani",id:"/lang/az"},{name:"Balinese",id:"/lang/ban"},{name:"Bambara",id:"/lang/bm"},{name:"Bantu",id:"/lang/bnt"},{name:"Basque",id:"/lang/eu"},{name:"Batak",id:"/lang/btk"},{name:"Belarusian",id:"/lang/be"},{name:"Bengali",id:"/lang/bn"},{name:"Bhojpuri",id:"/lang/bho"},{name:"Bosnian",id:"/lang/bs"},{name:"Breton",id:"/lang/br"},{name:"Bulgarian",id:"/lang/bg"},{name:"Buriat",id:"/lang/bua"},{name:"Catalan",id:"/lang/ca"},{name:"Cebuano",id:"/lang/ceb"},{name:"Cherokee",id:"/lang/chr"},{name:"Chichewa",id:"/lang/ny"},{name:"Chinese",id:"/lang/zh"},{name:"Cornish",id:"/lang/kw"},{name:"Corsican",id:"/lang/co"},{name:"Cree",id:"/lang/cr"},{name:"Creoles",id:"/lang/cpf"},{name:"Croatian",id:"/lang/hr"},{name:"Czech",id:"/lang/cs"},{name:"Danish",id:"/lang/da"},{name:"Duala",id:"/lang/dua"},{name:"Dutch",id:"/lang/nl"},{name:"English",id:"/lang/en"},{name:"Esperanto",id:"/lang/eo"},{name:"Estonian",id:"/lang/et"},{name:"Faroese",id:"/lang/fo"},{name:"Filipino",id:"/lang/fil"},{name:"Finnish",id:"/lang/fi"},{name:"French",id:"/lang/fr"},{name:"Frisian",id:"/lang/fy"},{name:"Friulian",id:"/lang/fur"},{name:"Fulah",id:"/lang/ff"},{name:"Ga",id:"/lang/gaa"},{name:"Gaelic",id:"/lang/gd"},{name:"Gallegan",id:"/lang/gl"},{name:"Georgian",id:"/lang/ka"},{name:"German",id:"/lang/de"},{name:"Germanic",id:"/lang/gem"},{name:"Greek",id:"/lang/el"},{name:"Guarani",id:"/lang/gn"},{name:"Haitian",id:"/lang/ht"},{name:"Hausa",id:"/lang/ha"},{name:"Hawaiian",id:"/lang/haw"},{name:"Hebrew",id:"/lang/he"},{name:"Hindi",id:"/lang/hi"},{name:"Hungarian",id:"/lang/hu"},{name:"Icelandic",id:"/lang/is"},{name:"Indonesian",id:"/lang/id"},{name:"Inuktitut",id:"/lang/ku"},{name:"Inuktitut",id:"/lang/iu"},{name:"Irish",id:"/lang/ga"},{name:"Italian",id:"/lang/it"},{name:"Japanese",id:"/lang/ja"},{name:"Judeo-Arabic",id:"/lang/jrb"},{name:"Kalaallisut",id:"/lang/kl"},{name:"Khmer",id:"/lang/km"},{name:"Kinyarwanda",id:"/lang/rw"},{name:"Klingon",id:"/lang/tlh"},{name:"Kongo",id:"/lang/kg"},{name:"Korean",id:"/lang/ko"},{name:"Ladino",id:"/lang/lad"},{name:"Latin",id:"/lang/la"},{name:"Latvian",id:"/lang/lv"},{name:"Limburgan",id:"/lang/li"},{name:"Lingala",id:"/lang/ln"},{name:"Lithuanian",id:"/lang/lt"},{name:"Low German",id:"/lang/nds"},{name:"Luxembourgish",id:"/lang/lb"},{name:"Macedonian",id:"/lang/mk"},{name:"Malagasy",id:"/lang/mg"},{name:"Malay",id:"/lang/ms"},{name:"Malayalam",id:"/lang/ml"},{name:"Maltese",id:"/lang/mt"},{name:"Mandingo",id:"/lang/man"},{name:"Manx",id:"/lang/gv"},{name:"Maori",id:"/lang/mi"},{name:"Marathi",id:"/lang/mr"},{name:"Mohawk",id:"/lang/moh"},{name:"Moldavian",id:"/lang/mo"},{name:"Mongolian",id:"/lang/mn"},{name:"Nahuatl",id:"/lang/nah"},{name:"Navajo",id:"/lang/nv"},{name:"Neapolitan",id:"/lang/nap"},{name:"Nepali",id:"/lang/ne"},{name:"Norse,",id:"/lang/non"},{name:"Northern Sami",id:"/lang/se"},{name:"Norwegian",id:"/lang/no"},{name:"Norwegian Nynorsk",id:"/lang/nn"},{name:"Occitan",id:"/lang/oc"},{name:"Panjabi",id:"/lang/pa"},{name:"Papiamento",id:"/lang/pap"},{name:"Persian",id:"/lang/fa"},{name:"Polish",id:"/lang/pl"},{name:"Portuguese",id:"/lang/pt"},{name:"Pushto",id:"/lang/ps"},{name:"Quechua",id:"/lang/qu"},{name:"Raeto-Romance",id:"/lang/rm"},{name:"Romanian",id:"/lang/ro"},{name:"Romany",id:"/lang/rom"},{name:"Russian",id:"/lang/ru"},{name:"Sakha",id:"/lang/sah"},{name:"Sanskrit",id:"/lang/sa"},{name:"Sardinian",id:"/lang/sc"},{name:"Scots",id:"/lang/sco"},{name:"Serbian",id:"/lang/sr"},{name:"Shona",id:"/lang/sn"},{name:"Sicilian",id:"/lang/scn"},{name:"Slovak",id:"/lang/sk"},{name:"Slovenian",id:"/lang/sl"},{name:"Songhai",id:"/lang/son"},{name:"Spanish",id:"/lang/es"},{name:"Sundanese",id:"/lang/su"},{name:"Swahili",id:"/lang/sw"},{name:"Swedish",id:"/lang/sv"},{name:"Syriac",id:"/lang/syr"},{name:"Tagalog",id:"/lang/tl"},{name:"Tahitian",id:"/lang/ty"},{name:"Tajik",id:"/lang/tg"},{name:"Tamashek",id:"/lang/tmh"},{name:"Tamil",id:"/lang/ta"},{name:"Telugu",id:"/lang/te"},{name:"Thai",id:"/lang/th"},{name:"Tibetan",id:"/lang/bo"},{name:"Tonga",id:"/lang/to"},{name:"Turkish",id:"/lang/tr"},{name:"Turkmen",id:"/lang/tk"},{name:"Tuvinian",id:"/lang/tyv"},{name:"Ukrainian",id:"/lang/uk"},{name:"Urdu",id:"/lang/ur"},{name:"Uzbek",id:"/lang/uz"},{name:"Vietnamese",id:"/lang/vi"},{name:"Welsh",id:"/lang/cy"},{name:"Wolof",id:"/lang/wo"},{name:"Xhosa",id:"/lang/xh"},{name:"Yiddish",id:"/lang/yi"},{name:"Yoruba",id:"/lang/yo"},{name:"Zulu",id:"/lang/zu"}];
CueCard.MqlSyntax={};
CueCard.MqlSyntax.KeywordSuggestions=[{label:"*",hint:"(keyword)",qualifiedProperty:"*",result:"*"},{label:"connect",hint:"(keyword)",qualifiedProperty:"connect",result:"connect"},{label:"create",hint:"(keyword)",qualifiedProperty:"create",result:"create"},{label:"estimate-count",hint:"(keyword)",qualifiedProperty:"estimate-count",result:"estimate-count"},{label:"limit",hint:"(keyword)",qualifiedProperty:"limit",result:"limit"},{label:"optional",hint:"(keyword)",qualifiedProperty:"optional",result:"optional"},{label:"return",hint:"(keyword)",qualifiedProperty:"return",result:"return"},{label:"sort",hint:"(keyword)",qualifiedProperty:"sort",result:"sort"}];
CueCard.MqlSyntax.KeywordValueHints={"*":{choices:[{label:"null",hint:"return a single value",result:null},{label:"[]",hint:"return a list of values",result:[],offset:1},{label:"{}",hint:"return a single object",result:{},offset:1},{label:"[{}]",hint:"return a list of objects",result:[{}],offset:2}]},"connect":{choices:[{label:"insert",hint:"attach a value or object to a non-unique property, or attach the first value or object to a unique property",result:"insert"},{label:"update",hint:"attach a value or object to a unique property replacing any value or object that was previously connected",result:"update"},{label:"replace",hint:"update unique properties and performs an insert for non-unique properties",result:"replace"},{label:"delete",hint:"detach a value or object from any property",result:"delete"}]},"create":{choices:[{label:"unless_exists",hint:"look for a matching object and create it if it doesn't exist",result:"unless_exists"},{label:"unless_connected",hint:"look for a matching object connected to the parent query, and create and connect it if it doesn't exist",result:"unless_connected"},{label:"unconditional",hint:"create the specified object without looking for a match (dangerous; ues carefully)",result:"unconditional"}]},"estimate-count":{choices:[{label:"null",hint:"(keyword)",result:null}]},"limit":{html:'Use a positive integer to limit how many results to return, or <span class="cuecard-code">0</span> for all available results.'},"optional":{choices:[{label:"true",hint:"(keyword)",result:true},{label:"false",hint:"(keyword)",result:false},{label:"required",hint:"(keyword)",result:"required"},{label:"forbidden",hint:"(keyword)",result:"forbidden"}]},"return":{choices:[{label:"count",hint:"(keyword)",result:"count"},{label:"estimate-count",hint:"(keyword)",result:"estimate-count"}]},"sort":{html:'Use a property name in the same query node. Prefix it with <span class="cuecard-code">-</span> to sort in descending order. For more complex ordering, see <a href="">this documentation</a>.'}};
CueCard.MqlSyntax.UniqueTopicValueSuggestions=[{label:"null",hint:"returns a single topic ID",result:null},{label:"{}",hint:"returns a single topic object with a default set of properties",result:{},offset:1},{label:'{ "id" : null, "name" : null }',hint:"returns a single topic object with id and name",result:{"id":null,"name":null}}];
CueCard.MqlSyntax.TopicValueSuggestions=[{label:"[]",hint:"returns a list of topic IDs or topic names",result:[],offset:1},{label:"[{}]",hint:"returns a list of topic objects with a default set of properties",result:[{}],offset:2},{label:'[{ "id" : null, "name" : null, "optional" : true, "limit" : 10 }]',hint:"returns an optional, limited list of topic objects with id and name",result:[{"id":null,"name":null,"optional":true,"limit":10}]}];
CueCard.MqlSyntax.SingleValueSuggestions=[{label:"null",hint:"returns a single value",result:null},{label:'{ "value" : null, "type" : null }',hint:"returns a value with type",result:{"value":null,"type":null}}];
CueCard.MqlSyntax.UniqueStringLiteralValueSuggestions=[{label:"null",hint:"returns a single string",result:null},{label:'{ "value" : null, "lang" : null, "optional" : true }',hint:"returns a single string with more options",result:{"value":null,"lang":null,"optional":true}}];
CueCard.MqlSyntax.StringLiteralValueSuggestions=[{label:"[]",hint:"returns a list of strings",result:null},{label:'[{ "value" : null, "lang" : null, "optional" : true }]',hint:"returns a list of strings with more options",result:[{"value":null,"lang":null,"optional":true}]}];
CueCard.MqlSyntax.UniqueLiteralValueSuggestions=[{label:"null",hint:"returns a single value",result:null},{label:'{ "value" : null, "optional" : true }',hint:"returns a single value with more options",result:{"value":null,"optional":true}}];
CueCard.MqlSyntax.LiteralValueSuggestions=[{label:"[]",hint:"returns a list of values",result:null},{label:'[{ "value" : null, "optional" : true }]',hint:"returns a list of values with more options",result:[{"value":null,"optional":true}]}];
CueCard.OutputPane=function(D,C){this._elmt=$(D);
this._options=C||{};
this._jsonResult=null;
this._lastJsonOutputMode=$.cookie("cc_op_mode")=="text"?"text":"tree";
this._treeConstructed=false;
this._constructUI();
this.layout();
};
CueCard.OutputPane.prototype.dispose=function(){};
CueCard.OutputPane.prototype.layout=function(){var O=this._elmt[0];
var M=this._elmt[0].firstChild.firstChild.firstChild.firstChild;
var K=10;
var P=O.offsetHeight-M.offsetHeight-("verticalPadding" in this._options?this._options.verticalPadding:12);
var J=O.offsetWidth-("horizontalPadding" in this._options?this._options.horizontalPadding:8);
var I=P-($.support.boxModel?2*K:0);
var N=J-($.support.boxModel?2*K:0);
try{this._elmt.find(".cuecard-outputPane-tabBody").css("padding","0px").width(J).height(P);
this._elmt.find(".cuecard-outputPane-status, .cuecard-outputPane-tree").css("padding",K+"px").css("left","0px").css("top","0px").width(N).height(I);
this._elmt.find(".cuecard-outputPane-textarea").css("padding","0px").css("left","0px").css("top","0px").width(J).height(P);
}catch(L){}};
CueCard.OutputPane.prototype._constructUI=function(){var J=this;
var H=this._idPrefix="t"+Math.floor(1000000*Math.random());
function I(A,B){return'<li class="tab"><a href="#'+H+"-"+A+'">'+B+"</a></li>";
}function F(A){return'<div class="cuecard-outputPane-tabBody" id="'+H+"-"+A+'"></div>';
}this._elmt.css("overflow","hidden");
this._elmt.html('<div class="cuecard-outputPane"><div id="'+H+'"><ul>'+I(0,"Tree")+I(1,"Text")+I(2,"Status")+'</ul><div class="tabbed-content">'+F(0)+F(1)+F(2)+"</div></div></div>");
var G=this._elmt.find(".cuecard-outputPane-tabBody");
this._treeTabBody=$(G[0]);
this._textTabBody=$(G[1]);
this._statusTabBody=$(G[2]);
this._constructTextTabBody();
this._constructTreeTabBody();
this._constructStatusTabBody();
this._tabs=$("#"+H);
this._tabs.tabs().bind("tabsselect",function(B,A){window.__cc_tree_disposePopup();
if(A.index==0){J._lastJsonOutputMode="tree";
if(J._jsonResult!=null&&!J._treeConstructed){J._constructTree();
}}else{if(A.index==1){J._lastJsonOutputMode="text";
}}$.cookie("cc_op_mode",J._lastJsonOutputMode,{expires:365});
});
this._tabs.tabs("select",(this._lastJsonOutputMode=="tree")?0:1);
};
CueCard.OutputPane.prototype.setJSONContent=function(D,C){this._jsonResult=D;
this._textarea[0].value=CueCard.jsonize(D,C||{indentCount:2});
if(this._lastJsonOutputMode=="tree"){this._constructTree();
this._tabs.tabs("select",0);
}else{this._tree.empty();
this._treeConstructed=false;
this._tabs.tabs("select",1);
}};
CueCard.OutputPane.prototype.setStatus=function(B){this._tabs.tabs("select",2);
this._statusTabBody[0].firstChild.innerHTML=B;
this._jsonResult=null;
this._textarea[0].value="";
this._tree.empty();
this._treeConstructed=false;
};
CueCard.OutputPane.prototype.getJson=function(){return this._jsonResult;
};
CueCard.OutputPane.prototype.renderResponseHeaders=function(L){var P=[];
P.push('<div class="cuecard-outputPane-responseHeaders">');
if("x-metaweb-tid"){var J=L["x-metaweb-tid"];
P.push("<h3>x-metaweb-tid (transaction ID)</h3>");
P.push('<div><a target="_blank" href="http://stats.metaweb.com/query/transaction?tid='+encodeURIComponent(J)+'">'+J+"</a></div>");
}var O=L["x-metaweb-cost"];
if(O){O=O.split(",");
P.push("<h3>x-metaweb-cost header components</h3>");
P.push("<table>");
P.push("<tr><th>code</th><th>value</th><th>meaning</th><th>subsystem</th></tr>");
var N=true;
for(var Q=0;
Q<O.length;
Q++){var R=O[Q].split("=");
R[0]=R[0].replace(/^\s+/,"").replace(/\s+$/,"");
var K=CueCard.XMetawebCosts[R[0]];
P.push("<tr class='"+(N?"cuecard-outputPane-odd":"cuecard-outputPane-even")+((K!==undefined&&"important" in K&&K.important)?" cuecard-outputPane-cost-important":"")+"'>");
P.push("<td>"+R[0]+"</td>");
P.push("<td>"+R[1]+"</td>");
P.push("<td>"+(K!==undefined?K.meaning:"--")+"</td>");
P.push("<td>"+(K!==undefined?K.subsystem:"--")+"</td>");
P.push("</tr>");
N=!N;
}P.push("</table>");
}P.push("<h3>response headers</h3>");
P.push("<table>");
var N=true;
for(var M in L){if(M!="x-metaweb-cost"&&M!="x-metaweb-tid"){P.push("<tr class='"+(N?"cuecard-outputPane-odd":"cuecard-outputPane-even")+"'><td>"+M+"</td><td>"+L[M]+"</td></tr>");
N=!N;
}}P.push("</table>");
P.push("</div>");
this.setStatus(P.join(""));
};
CueCard.OutputPane.prototype._constructTextTabBody=function(){this._textarea=$('<textarea readonly="true" wrap="off"></textarea>').addClass("cuecard-outputPane-textarea").appendTo(this._textTabBody);
};
CueCard.OutputPane.prototype._constructTreeTabBody=function(){this._tree=$("<div></div>").addClass("cuecard-outputPane-tree").appendTo(this._treeTabBody);
};
CueCard.OutputPane.prototype._constructStatusTabBody=function(){this._statusTabBody.html('<div class="cuecard-outputPane-status"></div>');
};
CueCard.OutputPane.prototype._constructCustomTabBody=function(){};
CueCard.OutputPane.prototype._constructTree=function(){var Q=this;
this._treeConstructed=true;
var M=[];
var S=function(B,A){return'<img class="cuecard-outputPane-tree-toggle" onclick="__cc_tree_toggle(this);" src="'+CueCard.urlPrefix+"images/"+B+'" '+(A?"":' style="display: none;"')+"/>";
};
var O=function(A){M.push(A);
};
var W=function(A){return"<a class='cuecard-outputPane-tree-explore' target='_blank' href='"+CueCard.freebaseServiceUrl+"tools/explore"+A+"'>xp</a>";
};
var X=function(A,B){O("<a target='_blank' class='cuecard-outputPane-tree-dataLink' href='"+CueCard.freebaseServiceUrl+"view"+A+"' onmouseover='__cc_tree_mouseOverTopic(this)' onmouseout='__cc_tree_mouseOutTopic(this)' fbid='"+A+"'>"+B+"</a>"+W(A));
};
var P=function(A,B){O("<a target='_blank' class='cuecard-outputPane-tree-dataLink' href='"+CueCard.freebaseServiceUrl+"view"+A+"' onmouseover='__cc_tree_mouseOverImage(this)' onmouseout='__cc_tree_mouseOutImage(this)' fbid='"+A+"'>"+B+"</a>"+W(A));
};
var V=function(A){O("<a target='_blank' class='cuecard-outputPane-tree-dataLink' href='"+A+"' onmouseover='__cc_tree_mouseOverImage(this)' onmouseout='__cc_tree_mouseOutImage(this)'>"+JSON.stringify(A)+"</a>");
};
var R=function(A,B){O("<a target='_blank' class='cuecard-outputPane-tree-dataLink' href='"+CueCard.freebaseServiceUrl+"view"+A+"' onmouseover='__cc_tree_mouseOverArticle(this)' onmouseout='__cc_tree_mouseOutArticle(this)' fbid='"+A+"'>"+B+"</a>"+W(A));
};
var N=function(B,A,C){if(B=="image"||B=="/common/topic/image"){P(A,C);
}else{if(B=="article"||B=="/common/topic/article"){R(A,C);
}else{X(A,C);
}}};
var T=function(B,A){return B.length>A.length&&B.substr(0,A.length)==A;
};
var U=function(F,H,A){if(F==null){H.startBody(false);
O("<span>"+JSON.stringify(F)+"</span>");
H.endBody(false);
}else{if(typeof F!="object"){H.startBody(false);
var B=A[0];
var D=A.length>1?A[1]:"";
if(B=="id"||B=="/type/object/id"){N(D,F,JSON.stringify(F));
}else{if(B=="guid"||B=="/type/object/guid"){N(D,"/guid/"+F.substr(1),JSON.stringify(F));
}else{if(B=="type"||B=="/type/object/type"){O("<a target='_blank' href='"+CueCard.freebaseServiceUrl+"type/schema"+F+"'>"+JSON.stringify(F)+"</a>"+W(F));
}else{if(typeof F=="string"&&(T(F,"http://")||T(F,"https://")||T(F,"ftp://"))){if(T(F,"http://chart.apis.google.com/chart?")){V(F);
}else{O("<a target='_blank' href='"+F+"'>"+JSON.stringify(F)+"</a>");
}}else{O("<span>"+JSON.stringify(F)+"</span>");
}}}}H.endBody(false);
}else{if(F instanceof Array){if(F.length==0){H.startBody(false);
O("<span>[]</span>");
H.endBody(false);
}else{var I=(F.length>1&&typeof F[0]=="object")?"":' style="display: none;"';
H.startBody(true,'<span cc:mode="normal">[ <a href="javascript:{}" class="cuecard-outputPane-tree-all" onclick="__cc_tree_expandAll(this);"'+I+'>expand all</a><span class="cuecard-outputPane-tree-toggles"'+I+'> &bull; </span><a href="javascript:{}" class="cuecard-outputPane-tree-all" onclick="__cc_tree_collapseAll(this);"'+I+'>collapse all</a><span class="cuecard-outputPane-tree-toggles"'+I+'> &bull; </span><a href="javascript:{}" class="cuecard-outputPane-tree-all" onclick="__cc_tree_flip(this);"'+I+">1-by-1</a></span>",'<span style="display: none;">[ '+(F.length>1?(F.length+" elements"):"1 element")+" ]</span>");
O('<div class="cuecard-outputPane-tree-arrayBody cuecard-outputPane-tree-normalMode">');
var G=function(K,L,J){return{startBody:function(c,d,b){if(c){O('<div class="cuecard-outputPane-tree-arrayElement">'+S("expanded.png",true)+S("collapsed.png",false)+'<span class="cuecard-outputPane-tree-memberName">'+K+":</span> "+d+b+"<span>"+(L?'<a href="javascript:{}" class="cuecard-outputPane-tree-flipControl" onclick="__cc_tree_flipPrevious(this);">previous</a> ':"")+(J?'<a href="javascript:{}" class="cuecard-outputPane-tree-flipControl" onclick="__cc_tree_flipNext(this);">next</a>':"")+"</span>");
}else{O('<div class="cuecard-outputPane-tree-arrayElement"><span class="cuecard-outputPane-tree-memberName">'+K+":</span> ");
}},endBody:function(Z){O("</div>");
}};
};
for(var C=0;
C<F.length;
C++){U(F[C],G(C,C>0,C<F.length-1),A);
}O("</div>");
H.endBody(true);
}}else{H.startBody(true,"<span>{</span>",'<span style="display: none;">{...}</span>');
O('<div class="cuecard-outputPane-tree-objectBody cuecard-outputPane-tree-normalMode">');
var G=function(J){return{startBody:function(Z,K,L){if(Z){O('<div class="cuecard-outputPane-tree-objectField">'+S("expanded.png",true)+S("collapsed.png",false)+'<span class="cuecard-outputPane-tree-memberName">'+J+":</span> "+K+L+"<span></span>");
}else{O('<div class="cuecard-outputPane-tree-objectField"><span class="cuecard-outputPane-tree-memberName">'+J+":</span> ");
}},endBody:function(K){O("</div>");
}};
};
for(var E in F){U(F[E],G(E),[E].concat(A));
}O("</div>");
H.endBody(true);
}}}};
U(this._jsonResult,{startBody:function(A){},endBody:function(){}},["__root__"]);
this._tree.html(M.join(""));
};
window.__cc_tree_toggle=function(F){var D=F.src.indexOf("expanded.png")>0;
var E=F.parentNode;
if(D){window.__cc_tree_collapse(E);
}else{window.__cc_tree_expand(E);
}};
window.__cc_tree_expand=function(G){if(G.firstChild.tagName.toLowerCase()=="img"){var E=G.lastChild;
E.style.display="block";
G.childNodes[0].style.display="inline";
G.childNodes[1].style.display="none";
var F=E.previousSibling.previousSibling;
var H=F.previousSibling;
H.style.display="inline";
F.style.display="none";
}};
window.__cc_tree_collapse=function(G){if(G.firstChild.tagName.toLowerCase()=="img"){var E=G.lastChild;
E.style.display="none";
G.childNodes[0].style.display="none";
G.childNodes[1].style.display="inline";
var F=E.previousSibling.previousSibling;
var H=F.previousSibling;
H.style.display="none";
F.style.display="inline";
}};
(function(){var B=function(F){var A=F.parentNode.getAttribute("cc:mode");
var H=F.parentNode.nextSibling.nextSibling.nextSibling;
if(A=="flip"){for(var G=0;
G<H.childNodes.length;
G++){H.childNodes[G].style.display="block";
}F.parentNode.setAttribute("cc:mode","normal");
$(F.parentNode.parentNode).find("> div.cuecard-outputPane-tree-arrayBody").addClass("cuecard-outputPane-tree-normalMode").removeClass("cuecard-outputPane-tree-flipMode");
}};
window.__cc_tree_expandAll=function(A){B(A);
var F=A.parentNode.nextSibling.nextSibling.nextSibling;
for(var E=0;
E<F.childNodes.length;
E++){__cc_tree_expand(F.childNodes[E]);
}};
window.__cc_tree_collapseAll=function(A){B(A);
var F=A.parentNode.nextSibling.nextSibling.nextSibling;
for(var E=0;
E<F.childNodes.length;
E++){__cc_tree_collapse(F.childNodes[E]);
}};
window.__cc_tree_flip=function(H){var G=H.parentNode.getAttribute("cc:mode");
var J=H.parentNode.nextSibling.nextSibling.nextSibling;
if(G=="normal"){for(var I=0;
I<J.childNodes.length;
I++){var A=J.childNodes[I];
A.style.display=I==0?"block":"none";
__cc_tree_expand(A);
}H.parentNode.setAttribute("cc:mode","flip");
$(H.parentNode.parentNode).find("> div.cuecard-outputPane-tree-arrayBody").removeClass("cuecard-outputPane-tree-normalMode").addClass("cuecard-outputPane-tree-flipMode");
}};
window.__cc_tree_flipPrevious=function(A){var D=A.parentNode.parentNode;
D.style.display="none";
D.previousSibling.style.display="block";
};
window.__cc_tree_flipNext=function(A){var D=A.parentNode.parentNode;
D.style.display="none";
D.nextSibling.style.display="block";
};
window.__cc_tree_mouseOverTopic=function(D){var A=D.getAttribute("fbid");
$.getJSON("http://hotshot.dfhuynh.user.dev.freebaseapps.com/html?id="+A+"&callback=?",function(F){var C=__cc_tree_createPopup(D);
$(C).addClass("cuecard-outputPane-tree-popup-topic").html(F);
});
};
window.__cc_tree_mouseOutTopic=function(A){__cc_tree_disposePopup();
};
window.__cc_tree_mouseOverImage=function(G){var A=G.getAttribute("fbid");
if(A!=null&&A.length>0){var H=CueCard.freebaseServiceUrl+"api/trans/image_thumb"+A+"?mode=fillcrop&amp;maxwidth=100&amp;maxheight=100";
}else{var H=G.href;
}var F=__cc_tree_createPopup(G);
F.innerHTML="<img src='"+H+"' />";
};
window.__cc_tree_mouseOutImage=function(A){__cc_tree_disposePopup();
};
window.__cc_tree_mouseOverArticle=function(D){var A=D.getAttribute("fbid");
$.getJSON(CueCard.freebaseServiceUrl+"api/trans/blurb"+A+"?callback=?",function(H){var G=H.result.body;
var C=__cc_tree_createPopup(D);
$(C).addClass("cuecard-outputPane-tree-popup-article").html(G);
});
};
window.__cc_tree_mouseOutArticle=function(A){__cc_tree_disposePopup();
};
window.__cc_tree_createPopup=function(F){var A=document.getElementById("cuecard-outputPane-tree-popup");
if(A==null){A=document.createElement("div");
A.id="cuecard-outputPane-tree-popup";
A.className="cuecard-outputPane-tree-popup";
A.onmouseover=window.__cc_tree_disposePopup;
document.body.appendChild(A);
}var E=$(F).offset();
A.style.top=(E.top+F.offsetHeight+10)+"px";
A.style.left=(E.left)+"px";
return A;
};
window.__cc_tree_disposePopup=function(){var A=document.getElementById("cuecard-outputPane-tree-popup");
if(A!=null){A.parentNode.removeChild(A);
}};
})();
CueCard.Popup=function(G,H,F,I,J){this._left=G;
this._top=H;
this._height=F;
this._windows=I;
this._handlers=J||{};
this._pendingContinuations=[];
this.elmt=$('<div class="cuecard-popup-container"></div>').css("top",(this._top+this._height)+"px").css("left",this._left+"px").appendTo("body");
this._addEventHandlers();
};
CueCard.Popup.prototype.addPendingContinuation=function(B){this._pendingContinuations.push(B);
};
CueCard.Popup.prototype.reposition=function(){var D=this.elmt.height();
var C=this.elmt.width();
if(this._top+this._height+D>=$(window).height()){this.elmt.css("top",(this._top-D-5)+"px");
}else{this.elmt.css("top",(this._top+this._height)+"px");
}if(this._left+C>=$(window).width()){this.elmt.css("left",($(window).width()-C-25)+"px");
}else{this.elmt.css("left",(this._left)+"px");
}};
CueCard.Popup.prototype.close=function(){this._remove();
this._pendingContinuations=null;
};
CueCard.Popup.prototype.cancel=function(){if(this.elmt!=null){this._remove();
this._cancelPendingContinuations();
this._pendingContinuations=null;
}};
CueCard.Popup.prototype._remove=function(){this._removeEventHandlers();
this.elmt.remove();
this.elmt=null;
};
CueCard.Popup.prototype._cancelPendingContinuations=function(){for(var C=0;
C<this._pendingContinuations.length;
C++){try{this._pendingContinuations[C].cancel();
}catch(D){}}this._pendingContinuations=[];
};
CueCard.Popup.prototype._addEventHandlers=function(){var E=this;
this._handleKeyDown=function(A){return E._onKeyDown(A);
};
this._handleMouseDown=function(A){return E._onMouseDown(A);
};
for(var H=0;
H<this._windows.length;
H++){var F=this._windows[H];
try{$(F.document).keydown(this._handleKeyDown).mousedown(this._handleMouseDown);
}catch(G){alert("Unable to install keyup handler on codemirror window");
}}};
CueCard.Popup.prototype._removeEventHandlers=function(){var E=this;
for(var H=0;
H<this._windows.length;
H++){var F=this._windows[H];
try{$(F.document).unbind("keydown",this._handleKeyDown).unbind("mousedown",this._handleMouseDown);
}catch(G){alert("Unable to install keyup handler on codemirror window");
}}};
CueCard.Popup.prototype._onKeyDown=function(B){if(B.keyCode==27){this.cancel();
if("onCancel" in this._handlers){this._handlers["onCancel"]("key");
}}};
CueCard.Popup.prototype._onMouseDown=function(B){if(this.mouseEventOutsidePopup(B)){this.cancel();
if("onCancel" in this._handlers){this._handlers["onCancel"]("mouse");
}}};
CueCard.Popup.prototype.mouseEventOutsidePopup=function(C){if(C.currentTarget!=this.elmt[0].ownerDocument){return true;
}else{var D=this.elmt.offset();
if(C.pageX<D.left||C.pageX>D.left+this.elmt.width()||C.pageY<D.top||C.pageY>D.top+this.elmt.height()){return true;
}}return false;
};
CueCard.PropertySuggestor=function(G,H,F,E){this._popup=G;
this._defaultSuggestions=H;
this._entries=F;
this._onCommit=E;
};
CueCard.PropertySuggestor.prototype.getSuggestions=function(T,N){T=T.toLowerCase();
var U=[];
var S={};
for(var V=0;
V<this._entries.length;
V++){var R=this._entries[V];
if(T.length==0){U.push(R);
}else{if(R.label.toLowerCase().indexOf(T)>=0){U.push(R);
}else{for(var L=0;
L<R.expectedTypes.length;
L++){var M=R.expectedTypes[L];
if(M.name.toLowerCase().indexOf(T)>=0){U.push({label:R.label,hint:R.hint+" &rarr; type "+M.id,qualifiedProperty:R.qualifiedProperty,result:R.result,offset:R["offset"],extent:R["extent"]});
S[R.qualifiedProperty]=true;
break;
}}}}}for(var V=0;
V<this._defaultSuggestions.length;
V++){var R=this._defaultSuggestions[V];
if(T.length==0||R.label.toLowerCase().indexOf(T)>=0){U.push(R);
}}if(T.length<3&&U.length>3){N(U);
}else{var Q=this;
var P=CueCard.UI.createBlockingContinuations(function(G,C){for(var F=0;
F<C.result.length;
F++){var D=C.result[F];
if(!(D.id in S)&&"/type/property/schema" in D&&D["/type/property/schema"]!=null&&D["/type/property/schema"].length>0&&"key" in D&&D.key!=null&&D.key.length>0){var B="/type/property/expected_type" in D&&D["/type/property/expected_type"]!=null?D["/type/property/expected_type"]:[];
var E={label:D.key[0],hint:"of type "+D["/type/property/schema"][0].id,qualifiedProperty:D.id,expectedTypes:B};
var A='"'+D.id+'" : ';
CueCard.QueryEditor.setPropertySuggestionSuffix(B.length>0?B[0]:"",E,E["/type/property/unique"],A);
U.push(E);
}}N(U);
});
this._popup.addPendingContinuation(P);
var O=CueCard.helper+"suggest-arbitrary-properties?q="+encodeURIComponent(T);
CueCard.JsonpQueue.call(O,P.onDone,P.onError);
}};
CueCard.PropertySuggestor.prototype.commit=function(B){this._onCommit(B);
};
CueCard.QueryEditor=function(L,M){this._container=L;
this._options=M;
this._outputPane=null;
this._controlPane=null;
this._warnWrites=false;
this._assistKeyComboDetected=false;
this._popup=null;
var N=this;
this._overflowInput=$("<input></input>").css("position","absolute").css("left","-500px").css("top","0px").appendTo(document.body);
this._container.innerHTML='<div class="cuecard-queryEditor-inner"></div>';
this._controlTopContainer=$('<div class="cuecard-queryEditor-controls-top"><table width="100%" cellspacing="0" cellpadding="0"><tr><td width="99%"></td></tr></table></div>').appendTo(this._container.firstChild);
this._iframeContainer=$('<div class="cuecard-queryEditor-content"></div>').appendTo(this._container.firstChild);
this._controlBottomContainer=$('<div class="cuecard-queryEditor-controls-bottom"><table width="100%" cellspacing="0" cellpadding="0"><tr><td width="90%"></td></tr><tr><td width="90%"></td></tr></table></div>').appendTo(this._container.firstChild);
this._constructButtons();
this.layout();
var J="[{\n  \n}]";
var I=1;
var K=2;
if("content" in M){J=M.content;
I=0;
K=0;
}var H={path:CueCard.codemirrorPrefix+"js/",parserfile:["tokenizejavascript.js","parsejavascript.js"],stylesheet:CueCard.urlPrefix+"styles/codemirror-jscolors.css",height:"100%",autoMatchParens:true,textWrapping:false,readOnly:"readOnly" in M?M.readOnly:false,content:J,initCallback:function(C){N._onReady();
try{var B=N._editor.nthLine(I+1);
N._editor.selectLines(B,K,B,K);
}catch(A){}if("onReady" in M){M["onReady"]();
}if(M["focusOnReady"]){N.focus();
}}};
if("onChange" in M){H.onChange=M.onChange;
}this._editor=new CodeMirror(function(A){N._iframeContainer.append(A);
},H);
};
CueCard.QueryEditor.nativeTypes={"/type/int":true,"/type/float":true,"/type/boolean":true,"/type/rawstring":true,"/type/uri":true,"/type/datetime":true,"/type/bytestring":true,"/type/value":true,"/type/text":true,"/type/enumeration":true};
CueCard.QueryEditor.prototype.dispose=function(){this._cancelPopup();
$(this._editor._top_element).remove();
this._overflowInput.remove();
this._controlTopContainer.remove();
this._controlBottomContainer.remove();
this._iframeContainer.remove();
this._editor=null;
this._overflowInput=null;
this._controlTopContainer=null;
this._controlBottomContainer=null;
this._iframeContainer=null;
};
CueCard.QueryEditor.prototype.layout=function(){var B=this._container.offsetHeight-this._controlTopContainer[0].offsetHeight-this._controlBottomContainer[0].offsetHeight;
this._iframeContainer.css("top",this._controlTopContainer[0].offsetHeight+"px").css("height",B+"px");
};
CueCard.QueryEditor.prototype.setOutputPane=function(B){this._outputPane=B;
};
CueCard.QueryEditor.prototype.getOutputPane=function(){return this._outputPane;
};
CueCard.QueryEditor.prototype.setControlPane=function(B){this._controlPane=B;
};
CueCard.QueryEditor.prototype.getControlPane=function(){return this._controlPane;
};
CueCard.QueryEditor.prototype._constructButtons=function(){var J=this;
var H=this._controlTopContainer.find("tr");
var F=function(D,B,C){var A=H[0].insertCell(D);
A.className=B?"cuecard-queryEditor-controls-leftAligned":"cuecard-queryEditor-controls-rightAligned";
A.appendChild(C);
};
var I=this._controlBottomContainer.find("tr");
var G=function(L,B,D,A){var E=I[0].insertCell(L);
var C=I[1].insertCell(L);
E.className=B?"cuecard-queryEditor-controls-leftAligned":"cuecard-queryEditor-controls-rightAligned";
C.className=E.className+" cuecard-queryEditor-buttonHint";
E.appendChild(D);
C.appendChild($('<span class="cuecard-queryEditor-buttonHint">'+A+"</span>")[0]);
};
F(0,true,$('<button class="cuecard-queryEditor-examples">Examples...</button>').click(function(A){J._showExamples();
})[0]);
F(1,true,$('<span><a href="http://www.freebase.com/docs/data" target="_blank">MQL&nbsp;Tutorial</a>&nbsp;&bull;&nbsp;<a href="http://freebaseapps.com/docs/mql" target="_blank">MQL&nbsp;Reference</a></span>')[0]);
F(3,false,$('<button class="cuecard-queryEditor-undo">Undo</button>').click(function(A){J._editor.editor.history.undo();
})[0]);
F(4,false,$('<button class="cuecard-queryEditor-redo">Redo</button>').click(function(A){J._editor.editor.history.redo();
})[0]);
F(5,false,$('<button class="cuecard-queryEditor-redo">Clear</button>').click(function(A){J.content("");
J.focus();
})[0]);
G(0,true,$('<button class="cuecard-queryEditor-queryAssist">Query&nbsp;Assist</button>').click(function(A){J.startAssistAtCursor();
})[0],"Tab");
G(1,true,$('<button class="cuecard-queryEditor-explainQuery">Explain&nbsp;Query</button>').click(function(A){alert("Not Yet Implemented");
}).hide()[0],"");
G(3,false,$('<button class="cuecard-queryEditor-cleanUp">Clean&nbsp;Up</button>').click(function(A){J._onCleanUp();
})[0],"");
G(4,false,$('<button class="cuecard-queryEditor-run">Run</button>').click(function(A){J._onRun(false);
})[0],"Ctrl-Enter");
};
CueCard.QueryEditor.prototype.focus=function(){this._editor.focus();
return this;
};
CueCard.QueryEditor.prototype.content=function(E){if(E==undefined){return this._editor.getCode();
}else{var F=this._editor.getCode();
if(F!=E){var D=this._editor.editor;
D.history.push(null,null,this._editor.win.fixSpaces(E.replace(/\t/g,"  ").replace(/\u00a0/g," ")).replace(/\r\n?/g,"\n").split("\n"));
D.addDirtyNode();
D.scheduleHighlight();
if(D.history.onChange){D.history.onChange();
}}return this;
}};
CueCard.QueryEditor.prototype.getUnresolvedQuery=function(){var C=this.getQueryModelAndContext();
var D=C.model.toQueryJson();
return CueCard.jsonize(D,this.getJsonizingSettings({breakLines:false,variables:this._getVariables(),resolveVariables:false}));
};
CueCard.QueryEditor.prototype.getResolvedQueryEnvelope=function(B){return this._getResolvedQueryEnvelope(false,B);
};
CueCard.QueryEditor.prototype.getJsonizingSettings=function(B){if(this._controlPane){return this._controlPane.getJsonizingSettings(B);
}else{B=B||{};
if(!("indentCount" in B)){B.indentCount=2;
}return B;
}};
CueCard.QueryEditor.prototype._getVariables=function(){if(this._controlPane){return this._controlPane.getVariables();
}else{return{};
}};
CueCard.QueryEditor.prototype._getQueryEnvelope=function(){if(this._controlPane){return this._controlPane.getQueryEnvelope();
}else{return{};
}};
CueCard.QueryEditor.prototype._getResolvedQueryEnvelope=function(M,O){O=O||{};
var L=this.getQueryModelAndContext();
var N=L.model.toQueryJson();
O.isWriteQuery=this._isWriteQuery(N);
var S=this._getQueryEnvelope();
var Q=this._getVariables();
if(M){this.content(CueCard.jsonize(N,this.getJsonizingSettings({variables:Q,resolveVariables:false})));
try{var P=this.getQueryModelAndContext();
var R=P.model.getCursorFromContext(L.context);
var K=this._editor.nthLine(R.line+1);
this._editor.selectLines(K,R.col);
}catch(T){}}S.query=N;
return CueCard.jsonize(S,this.getJsonizingSettings({breakLines:false,variables:Q,resolveVariables:true}));
};
CueCard.QueryEditor.prototype._isWriteQuery=function(D){var C=function(B){if(B==null){return false;
}else{if(B instanceof Array){if(B.length>0&&typeof B[0]=="object"){for(var F=0;
F<B.length;
F++){if(C(B[F])){return true;
}}return false;
}else{return false;
}}else{if(typeof B=="object"){for(var A in B){if(A=="connect"||A=="create"||C(B[A])){return true;
}}return false;
}else{return false;
}}}};
return C(D);
};
CueCard.QueryEditor.prototype.getMqlReadURL=function(){var D={};
var F=this.getResolvedQueryEnvelope(D);
var E=CueCard.freebaseServiceUrl+"api/service/"+(D.isWriteQuery?"mqlwrite":"mqlread");
if("service" in this._options&&this._options.service!=null){E=this._options.service;
}return E+"?query="+encodeURIComponent(F);
};
CueCard.QueryEditor.prototype.run=function(H){if(this._outputPane!=null){var L={};
var J=this._getResolvedQueryEnvelope(H||(this._controlPane&&this._controlPane.getSetting("cleanup")),L);
if(L.isWriteQuery&&!this._warnWrites&&CueCard.helper.indexOf("sandbox")<0){if(window.confirm("Your query will write data into Freebase.\nAre you sure you want to do that?")){this._warnWrites=true;
}else{return ;
}}var M=CueCard.helper+(L.isWriteQuery?"mqlwrite":"mqlread")+"?"+("emql" in this._options&&this._options.emql?"emql=1&":"")+("debug" in this._options?("debug="+this._options.debug+"&"):"")+("service" in this._options&&this._options.service!=null?("service="+encodeURIComponent(this._options.service)+"&"):"");
var N=this;
var I=function(A){if(A["error"]=="unauthorized"){N._outputPane.setStatus("Query editor is not authorized to write on your behalf.");
N._options.onUnauthorizedMqlWrite();
}else{N._outputPane.renderResponseHeaders(A.headers);
var B={};
if(N._controlPane!=null&&N._controlPane.getSetting("multilineErrorMessages")&&"code" in A.body&&A.body.code=="/api/status/error"&&"messages" in A.body&&A.body.messages!=null){B["encodeJavascriptString"]=function(C){return C;
};
}N._outputPane.setJSONContent(A.body,N.getJsonizingSettings(B));
}};
var K=function(A){alert(A);
};
this._outputPane.setStatus("Querying...");
if(L.isWriteQuery||J.length>1024){$.post(M,{"query":J},I,"json");
}else{CueCard.JsonpQueue.call(M+"query="+encodeURIComponent(J),I,K);
}}if("onRun" in this._options){this._options["onRun"]();
}};
CueCard.QueryEditor.prototype.getQueryModelAndContext=function(){var E=this._editor.cursorPosition(false);
var F=this._editor.lineNumber(E.line)-1;
var D=E.character;
return CueCard.QueryParser.parseForContext(this._editor.getCode(),0,F,D);
};
CueCard.QueryEditor.prototype._onReady=function(){var C=this;
try{$(this._editor.win.document).keyup(function(A){return C._onEditorKeyUp(A);
}).keydown(function(A){return C._onEditorKeyDown(A);
}).mousedown(function(A){return C._onEditorMouseDown(A);
});
}catch(D){alert("Unable to install keyup handler on codemirror window");
}if("cleanUp" in this._options&&this._options.cleanUp){this._onCleanUp();
}};
CueCard.QueryEditor.prototype._onRun=function(B){this.run(B);
};
CueCard.QueryEditor.prototype._onCleanUp=function(){var D=this.getQueryModelAndContext();
var F=D.model.toQueryJson();
var E=this._getVariables();
this.content(CueCard.jsonize(F,this.getJsonizingSettings({variables:E,resolveVariables:false})));
};
CueCard.QueryEditor.prototype._onEditorMouseDown=function(B){};
CueCard.QueryEditor.prototype._onEditorKeyDown=function(B){if(B.keyCode==9||(B.keyCode==32&&(B.ctrlKey||B.metaKey||B.altKey))){this._assistKeyComboDetected=true;
B.preventDefault();
return false;
}else{this._assistKeyComboDetected=false;
if((B.metaKey||B.ctrlKey)&&B.keyCode==13){this._onRun(B.shiftKey);
}}};
CueCard.QueryEditor.prototype._onEditorKeyUp=function(B){if(this._assistKeyComboDetected){this._assistKeyComboDetected=false;
this.startAssistAtCursor();
B.preventDefault();
return false;
}};
CueCard.QueryEditor.prototype.startAssistAtCursor=function(){var O=this._editor.cursorPosition(false);
var W=this._editor.lineNumber(O.line)-1;
var N=O.character;
var Q=this._editor.lineContent(O.line);
var U=this._editor.win.document.body.firstChild;
var S=O.line||U;
var X=S.nextSibling;
var T=N;
while(T>0&&X!=null&&X.tagName.toLowerCase()!="br"&&X.firstChild!=null&&X.firstChild.nodeValue.length>=T){T-=X.firstChild.nodeValue.length;
S=X;
X=X.nextSibling;
}if(X==null||X.tagName.toLowerCase()=="br"){if(X!=null){var V=$(X).offset();
if($.browser.msie&&S!=null&&S.tagName.toLowerCase()!="br"){var M=S.offsetWidth;
var R=S.offsetHeight;
}else{var M=V.left;
var R=X.offsetHeight;
}}else{var V=$(S).offset();
var P=S.firstChild?S.firstChild.nodeValue.length:0;
var M=V.left+(P==0?0:(T*S.offsetWidth/P));
var R=S.offsetHeight;
}this._startAssist(W,N,{left:M,top:V.top,height:R});
}else{var V=$(X).offset();
var P=X.firstChild?X.firstChild.nodeValue.length:0;
this._startAssist(W,N,{left:V.left+(P==0?0:(T*X.offsetWidth/P)),top:V.top,height:X.offsetHeight});
}};
CueCard.QueryEditor.prototype._startAssist=function(M,P,O){this._cancelPopup();
if(O!=null){var L=$(this._iframeContainer).offset();
L.left-=this._editor.win.document.body.scrollLeft+document.body.scrollLeft;
L.top-=this._editor.win.document.body.scrollTop+document.body.scrollTop;
var N=this;
this._popup=new CueCard.Popup(Math.round(L.left+O.left),Math.round(L.top+O.top),Math.round(O.height),[window,this._editor.win],{onCancel:function(A){if(A=="key"){N.focus();
}}});
this._popup.elmt.html('<div class="cuecard-popup-message">Please wait...</div>');
var Q=this.getQueryModelAndContext();
if(Q.context.length>0){var K=Q.context[Q.context.length-1];
if("relative" in K){if(K.node.type==CueCard.QueryNode.TYPE_NONTERMINAL){if(K.relative=="path"||K.relative=="before"){this._startSuggestProperties(M,P,Q,K);
return ;
}else{if(K.relative=="space"){var R=K.node.links[K.child];
this._startSuggestValues(M,P,Q,K,R);
return ;
}}}else{if(K.node.type==CueCard.QueryNode.TYPE_TERMINAL){var R=null;
if(Q.context.length>1){var J=Q.context[Q.context.length-2];
R=J.node.links[J.child];
}this._startSuggestValues(M,P,Q,K,R);
return ;
}}}else{var R=null;
if(Q.context.length>1){var J=Q.context[Q.context.length-2];
if(J.node.type==CueCard.QueryNode.TYPE_NONTERMINAL){R=J.node.links[J.child];
}else{if(Q.context.length>2){J=Q.context[Q.context.length-3];
R=J.node.links[J.child];
}}}this._startSuggestValues(M,P,Q,K,R);
return ;
}}}this._popup.elmt.html('<div class="cuecard-popup-message">Sorry, we don\'t know how to assist you here. Send us a link to this exact query using the links at the upper right corner and we will investigate. Thank you!</div>');
};
CueCard.QueryEditor.prototype._cancelPopup=function(){if(this._popup!=null){this._popup.cancel();
this._popup=null;
}};
CueCard.QueryEditor.prototype._startSuggestProperties=function(H,J,I,G){var L=this;
var K=(G.relative=="path")?G.node.links[G.child].token:null;
this._startBufferInput();
this._prepareQueryForSuggestions(I,H,J,K,function(F,C,E,A){var B=function(Y,Z){var W=[];
var V=[];
var U=[];
Z.node.getDeclaredTypes(W);
Z.node.getDeclaredIDs(V);
Z.node.getDeclaredGUIDs(U);
var T=[];
if(W.length>0){T.push("t="+encodeURIComponent(W.join(",")));
}if(V.length>0){T.push("i="+encodeURIComponent(V.join(",")));
}if(U.length>0){T.push("g="+encodeURIComponent(U.join(",")));
}if(Z.property!=null){T.push("p="+encodeURIComponent(Z.property));
T.push("r="+Z.reverse);
}var X=CueCard.helper+"suggest-properties?"+T.join("&");
CueCard.JsonpQueue.call(X,Y.extend(D).onDone,F.onError);
return true;
};
var D=function(P,O){L._suggestProperties(I,O,C+L._stopBufferInput(),E);
};
I.model.locateInnerMostNonTerminal(I.context,F.extend(B));
return true;
});
};
CueCard.QueryEditor.prototype._startBufferInput=function(){this._overflowInput[0].value="";
this._overflowInput[0].focus();
};
CueCard.QueryEditor.prototype._stopBufferInput=function(){return this._overflowInput[0].value;
};
CueCard.QueryEditor.prototype._suggestProperties=function(T,W,V,Y){this._popup.elmt.empty();
this._popup.elmt.html("<div></div>");
var d=[];
for(var Z in W.properties){var l=W.properties[Z];
var a=Z.lastIndexOf("/");
var f=Z.substr(a+1);
var i=Z.substr(0,a);
var g=l.explicit;
if("parentProperty" in l){var e='"'+l.parentProperty+'" : [{ "'+f+'" : ';
var h=(l.unique?"null":"[]");
var U=" }]";
d.push({label:f,hint:"of type "+i+" (through "+l.parentProperty+")",qualifiedProperty:Z,result:e+h+U,offset:e.length,extent:h.length,expectedTypes:l.expectedTypes});
}else{var e='"'+(g?f:Z)+'" : ';
var k=l.expectedTypes.length>0?l.expectedTypes[0].id:"";
var X={label:f,hint:"of type "+i,qualifiedProperty:Z,expectedTypes:l.expectedTypes};
CueCard.QueryEditor.setPropertySuggestionSuffix(k,X,l.unique,e);
d.push(X);
}}var b=this;
var j=new CueCard.PropertySuggestor(this._popup,CueCard.MqlSyntax.KeywordSuggestions,d,Y);
var c=new CueCard.SuggestionController(this._popup,this._popup.elmt[0].firstChild,j,V);
};
CueCard.QueryEditor.setPropertySuggestionSuffix=function(I,H,G,F){var J=null;
if(I=="/common/image"||I=="/common/document"){J='{ "id" : null, "optional" : true, "limit" : 3 }';
if(!G){J="["+J+"]";
}}else{if(I=="/measurement_unit/dated_integer"){J='{ "number" : null, "date" : null }';
if(G){J="["+J+"]";
}}else{if(I=="/measurement_unit/dated_money_value"){J='{ "amount" : null, "valid_date" : null, "currency" : null }';
if(G){J="["+J+"]";
}}else{if(I.indexOf("/type/")==0){J=(G?"null":"[]");
}else{J=(G?"{}":"[{}]");
}}}}H.result=F+J;
H.offset=F.length;
H.extent=J.length;
};
CueCard.QueryEditor.prototype._startSuggestValues=function(I,K,J,H,L){var N=this;
var M=("token" in H)?H.token:null;
this._startBufferInput();
this._prepareQueryForSuggestions(J,I,K,M,function(A,W,d,E){W+=N._stopBufferInput();
if(L!=null&&!L.reverse&&CueCard.QueryNode.isMqlKeyword(L.path)){N._suggestValuesForKeyword(I,K,J,H,L.path,W,d);
}else{function F(){N._popup.elmt.empty();
N._popup.elmt.html('<div></div><div class="cuecard-suggestion-hint-message">Keep typing to search for topics of types fitting this point in the query.</div>');
}var D=L.qualifiedProperty;
var G=L.reverse;
if(!G&&(D=="/type/object/id"||D=="/type/object/guid"||D=="/type/object/name")){var X=function(f,S){F();
var U=[];
S.node.getDeclaredTypes(U);
if("property" in S&&S.property!=null){var O=S.property;
var V=S.reverse;
if(G){U.push(O.substr(0,O.lastIndexOf("/")));
}else{if(O in E){var Q=E[O].expectedTypes;
for(var T=0;
T<Q.length;
T++){U.push(Q[T].id);
}}}}var R=new CueCard.TypeBasedTopicSuggestor(N._popup,CueCard.MqlSyntax.SingleValueSuggestions,U,L.property,d);
var P=new CueCard.SuggestionController(N._popup,N._popup.elmt[0].firstChild,R,W);
};
J.model.locateInnerMostNonTerminal(J.context,A.extend(X));
return true;
}else{F();
var B;
var a=false;
if(G){B=[D.substr(0,D.lastIndexOf("/"))];
}else{if(D=="/type/object/type"){B=["/type/type"];
}else{if(D in E){a=E[D].unique;
B=[];
var b=E[D].expectedTypes;
for(var C=0;
C<b.length;
C++){B.push(b[C].id);
}}else{if(D=="/type/text/lang"){B=["/type/lang"];
}else{B=[];
}}}}var Z=(B.length==1)?B[0]:null;
if(Z!==null&&Z in CueCard.QueryEditor.nativeTypes){var c=new CueCard.StaticChoicesSuggestor(CueCard.MqlSyntax[Z=="/type/text"?(a?"UniqueStringLiteralValueSuggestions":"StringLiteralValueSuggestions"):(a?"UniqueLiteralValueSuggestions":"LiteralValueSuggestions")],d);
}else{var c=new CueCard.TypeBasedTopicSuggestor(N._popup,CueCard.MqlSyntax[a?"UniqueTopicValueSuggestions":"TopicValueSuggestions"],B,"id",d);
}var Y=new CueCard.SuggestionController(N._popup,N._popup.elmt[0].firstChild,c,W);
}}});
};
CueCard.QueryEditor.prototype._suggestValuesForKeyword=function(M,Q,R,U,S,T,O){this._popup.elmt.empty();
var L=CueCard.MqlSyntax.KeywordValueHints[S];
if("html" in L){this._popup.elmt.html('<div class="cuecard-suggestion-hint-message">'+L.html+"</div>");
this.focus();
}else{this._popup.elmt.html("<div></div>");
var P=this;
var N=new CueCard.StaticChoicesSuggestor(L.choices,O);
var V=new CueCard.SuggestionController(this._popup,this._popup.elmt[0].firstChild,N,T);
}};
CueCard.QueryEditor.prototype._prepareQueryForSuggestions=function(W,f,V,e,b){var U=this;
var c="";
var Z;
var a=function(G,D,H,E,B){var C=(E===undefined||typeof H!=="string")?CueCard.jsonize(H,{breakLines:false}):H;
var I=D+(typeof E=="number"?E:C.length);
var F=I+(typeof B=="number"?B:0);
U._editor.editor.replaceSelection(C);
var A=U._editor.nthLine(G+1);
U._editor.selectLines(A,I,A,F);
};
if(e!=null){var R=0;
var S=e.start.col;
if(/^['"]/.test(e.content)){R=1;
}c=e.content.substring(R,V-S).replace(/['"]$/,"");
Z=function(A,B,C){var D=U._editor.nthLine(e.start.line+1);
U._editor.selectLines(D,e.start.col,D,e.end.col);
a(e.start.line,e.start.col,A,B,C);
};
}else{var X=this._editor.cursorPosition(true);
var Q=this._editor.lineNumber(X.line)-1;
var Y=X.character;
Z=function(A,B,C){var D=U._editor.nthLine(Q+1);
U._editor.selectLines(D,Y,D,Y);
a(Q,Y,A,B,C);
};
}var T=function(A){U._popup.close();
if(typeof A=="string"){Z(A);
}else{Z(A.result,A["offset"],A["extent"]);
}};
var d=CueCard.UI.createBlockingContinuations(function(B,A){return b(B,c,T,A||{});
});
this._popup.addPendingContinuation(d);
W.model.qualifyAllProperties(d);
};
CueCard.QueryEditor.prototype._showExamples=function(C){var D=this;
new CueCard.ExampleDialog({onDone:function(A){D.content(A);
D._onRun(false);
}});
};
CueCard.QueryNode=function(B){this.type=B;
this.value=null;
this.isArray=false;
this.startToken=null;
this.endToken=null;
this.links=[];
};
CueCard.QueryNode.TYPE_MISSING=-1;
CueCard.QueryNode.TYPE_TERMINAL=0;
CueCard.QueryNode.TYPE_NONTERMINAL=1;
CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY=2;
CueCard.QueryNode.prototype.toQueryJson=function(B){B=B||{};
if(!("qualifyAllProperties" in B)){B.qualifyAllProperties=false;
}if(!("excludeChild" in B)){B.excludeChild=-1;
}return this._toQueryJson(B);
};
CueCard.QueryNode.prototype._toQueryJson=function(R){var W={qualifyAllProperties:R.qualifyAllProperties,excludeChild:-1};
if(this.type==CueCard.QueryNode.TYPE_TERMINAL){if(this.isArray){var Y=[];
for(var P=0;
P<this.value.length;
P++){var V=this.value[P];
Y.push(V!=null?V._toQueryJson(W):null);
}return Y;
}else{if(this.startToken.type==CueCard.Token.Types.identifier){return{"__identifier__":this.value};
}else{return this.value;
}}}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){var Y=[];
for(var P=0;
P<this.elements.length;
P++){Y.push(this.elements[P]._toQueryJson(W));
}return Y;
}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){var Q={};
var O=false;
var Z=0;
for(var P=0;
P<this.links.length;
P++){if(P!=R.excludeChild){var N=this.links[P];
if(N.path.length>0){var S=N.getPath(R.qualifyAllProperties);
if(S in Q&&N.namespace.length==0){while(S in Q){N.namespace="ns"+Z+++":";
S=N.getPath(R.qualifyAllProperties);
}}var X=N.value!=null?N.value._toQueryJson(W):null;
Q[S]=X;
if(N.getUnnamespacedQualifiedPath()=="/type/object/type"&&X!=null&&(!(X instanceof Array)||X.length>0)){O=true;
}}}}if(!O&&"expectedTypes" in R&&R.expectedTypes.length>0){var T=[];
for(var P=0;
P<R.expectedTypes.length;
P++){var U=R.expectedTypes[P];
if(U!="/type/object"&&U!="/common/topic"){T.push(U);
}}if(T.length==1){Q["type"]=T[0];
}else{if(T.length>1){Q["type|="]=T;
}}}return Q;
}else{return null;
}}}};
CueCard.QueryNode.isMqlKeyword=function(B){switch(B){case"limit":case"sort":case"*":case"return":case"count":case"estimate-count":case"optional":case"create":case"connect":return true;
}return false;
};
CueCard.QueryNode.prototype.getDeclaredTypes=function(G){var E=null;
if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){E=this.links;
}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){E=this.elements[0].links;
}}if(E!=null){for(var H=0;
H<E.length;
H++){var F=E[H];
if(F.qualifiedProperty=="/type/object/type"&&!F.reverse){F.getValuesOfType(G,"string");
}}}};
CueCard.QueryNode.prototype.getDeclaredIDs=function(G){var E=null;
if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){E=this.links;
}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){E=this.elements[0].links;
}}if(E!=null){for(var H=0;
H<E.length;
H++){var F=E[H];
if(F.qualifiedProperty=="/type/object/id"&&!F.reverse){F.getValuesOfType(G,"string");
}}}};
CueCard.QueryNode.prototype.getDeclaredGUIDs=function(F){var E=null;
if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){E=this.links;
}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){E=this.elements[0].links;
}}if(E!=null){for(var H=0;
H<E.length;
H++){var G=E[H];
if(G.qualifiedProperty=="/type/object/guid"&&!G.reverse){G.getValuesOfType(F,"string");
}}}};
CueCard.QueryNode.prototype.qualifyAllProperties=function(B){this._qualifyAllProperties([],{},B);
};
CueCard.QueryNode.prototype._qualifyAllProperties=function(Y,i,l){if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){var V=[];
var h=false;
var g=[];
var Z=[];
var a=[];
for(var X=0;
X<this.links.length;
X++){var j=this.links[X];
if(j.value.type==CueCard.QueryNode.TYPE_NONTERMINAL||j.value.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY||j.value.type==CueCard.QueryNode.TYPE_MISSING){V.push(j);
}if(j.qualifiedProperty=="/type/object/type"&&!j.reverse){j.getValuesOfType(g,"string");
}else{if(j.qualifiedProperty=="/type/object/id"&&!j.reverse){j.getValuesOfType(Z,"string");
}else{if(j.qualifiedProperty=="/type/object/guid"&&!j.reverse){j.getValuesOfType(a,"string");
}else{if(j.qualifiedProperty!=null&&j.qualifiedProperty.length>0){var b=j.qualifiedProperty.lastIndexOf("/");
if(b>0){g.push(j.qualifiedProperty.substr(0,b));
}}else{if(!CueCard.QueryNode.isMqlKeyword(j.property)){h=true;
}}}}}}g=g.concat(Y);
var W={};
for(var X=g.length-1;
X>=0;
X--){W[g[X]]=true;
}g=[];
for(var e in W){g.push(e);
}if(!h&&V.length==0){l.onDone(i);
return ;
}var d=this;
var T=function(F){var D=F.properties;
var C=F.qualifications;
for(var B=0;
B<d.links.length;
B++){var A=d.links[B];
if(A.qualifiedProperty.length==0&&!CueCard.QueryNode.isMqlKeyword(A.property)){A.qualifiedProperty=C[A.property]||A.property;
}}for(var E in D){i[E]=D[E];
}(function(){if(V.length==0){l.onDone(i);
}else{var G=V.shift();
var L=[];
if(G.qualifiedProperty in D){var H=D[G.qualifiedProperty].expectedTypes;
for(var J=0;
J<H.length;
J++){L.push(H[J].id);
}}L.push("/common/topic");
L.push("/type/object");
if(G.value.type==CueCard.QueryNode.TYPE_NONTERMINAL){G.value.expectedTypes=L;
}else{if(G.value.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){var K=G.value.elements;
for(var I=0;
I<K.length;
I++){K[I].expectedTypes=L;
}}}G.value._qualifyAllProperties(L,i,{onDone:arguments.callee,onError:l.onError});
}})();
};
var U=[];
if(g.length>0){U.push("t="+encodeURIComponent(g.join(",")));
}if(Z.length>0){U.push("i="+encodeURIComponent(Z.join(",")));
}if(a.length>0){U.push("g="+encodeURIComponent(a.join(",")));
}var k=CueCard.helper+"qualify-properties?"+U.join("&");
CueCard.JsonpQueue.call(k,T,l.onError);
}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){var X=0;
var f=this.elements;
var c=function(){if(X<f.length){f[X++]._qualifyAllProperties(Y,i,{onDone:arguments.callee,onError:l.onError});
}else{l.onDone(i);
}};
c();
}else{l.onDone();
}}};
CueCard.QueryNode.prototype.getCursorFromContext=function(B){return this._getCursorFromContext(B,0);
};
CueCard.QueryNode.prototype._getCursorFromContext=function(G,J){var F=G[J];
if(this.type==CueCard.QueryNode.TYPE_MISSING){var H=this.startToken;
return{line:H.start.line,col:H.start.col};
}else{if(this.type==CueCard.QueryNode.TYPE_TERMINAL){if(this.isArray){if(F.relative=="inside"){if(F.child<this.value.length){return this.value[F.child]._getCursorFromContext(G,J+1);
}else{var H=this.endToken;
return{line:H.start.line,col:H.start.col};
}}else{if(F.child<this.value.length){var I=this.value[F.child];
var H=I.startToken;
return{line:H.start.line,col:H.start.col};
}else{var H=this.startToken;
return{line:H.end.line,col:H.end.col};
}}}else{var H=this.startToken;
return{line:H.start.line,col:H.start.col+("offset" in F?F.offset:0)};
}}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){if(F.relative=="inside"){if(F.child<this.elements.length){return this.elements[F.child]._getCursorFromContext(G,J+1);
}else{var H=this.endToken;
return{line:H.start.line,col:H.start.col};
}}else{if(F.child<this.elements.length){var I=this.elements[F.child];
var H=I.startToken;
return{line:H.start.line,col:H.start.col};
}else{var H=this.startToken;
return{line:H.end.line,col:H.end.col};
}}}else{if(F.relative=="inside"){if(F.child<this.links.length){return this.links[F.child].value._getCursorFromContext(G,J+1);
}else{var H=this.endToken;
return{line:H.start.line,col:H.start.col};
}}else{if(F.relative=="before"){if(F.child<this.links.length){var I=this.links[F.child].value;
var H=I.startToken;
return{line:H.start.line,col:H.start.col};
}else{var H=this.startToken;
return{line:H.end.line,col:H.end.col};
}}else{if(F.child<this.links.length){if(F.relative=="path"){var H=this.links[F.child].token;
return{line:H.start.line,col:H.start.col+("offset" in F?F.offset:0)};
}else{var H=this.links[F.child].value.startToken;
return{line:H.start.line,col:H.start.col};
}}else{var H=this.endToken;
return{line:H.end.line,col:H.end.col};
}}}}}}};
CueCard.QueryNode.prototype.toInsideOutQueryJson=function(E,D){var F=this;
this.qualifyAllProperties({onDone:function(){D.onDone(F._toInsideOutQueryJson(E,0,null,null));
},onError:D.onError});
};
CueCard.QueryNode.prototype._toInsideOutQueryJson=function(O,R,S,T){if(S!=null&&!(T instanceof Array)){T=[T];
}if(R<O.length){var L=O[R];
if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){if("child" in L&&L.relative=="inside"){var M=L.child;
if(M<this.links.length){var K=this.links[M];
if(K.value.type==CueCard.QueryNode.TYPE_NONTERMINAL||K.value.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){var P=K.getInverseQualifiedPath();
var Q=this.toQueryJson({excludeChild:M});
if(S!=null){if(Q instanceof Array){Q[0][S]=T;
}else{Q[S]=T;
}}return K.value._toInsideOutQueryJson(O,R+1,P,Q);
}}}}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){if("child" in L&&L.relative=="inside"){var M=L.child;
if(this.elements.length>1){throw new Error("Cannot turn a query inside out if a query node has siblings");
}else{if(M==0){var N=this.elements[M]._toInsideOutQueryJson(O,R+1,S,T);
return(N instanceof Array)?N:[N];
}else{return null;
}}}}}}var N=this.toQueryJson({expectedTypes:("expectedTypes" in this)?this.expectedTypes:[]});
if(S!=null){if(typeof N==Array){N[0][S]=T;
}else{N[S]=T;
}}return N;
};
CueCard.QueryNode.prototype.locateInnerMostNonTerminal=function(E,D){var F=this;
this.qualifyAllProperties({onDone:function(){var A=F._locateInnerMostNonTerminal(E,0);
D.onDone(A!=null?A:{node:F,property:null,reverse:false});
},onError:D.onError});
};
CueCard.QueryNode.prototype._locateInnerMostNonTerminal=function(K,N){if(N<K.length){var H=K[N];
if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL){if("child" in H&&H.relative=="inside"){var I=H.child;
if(I<this.links.length){var L=this.links[I];
if(L.value.type==CueCard.QueryNode.TYPE_NONTERMINAL||L.value.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){var M=L.value._locateInnerMostNonTerminal(K,N+1);
if(M==null){M={node:L.value};
}if(!("property" in M)){M.property=L.qualifiedProperty;
M.reverse=L.reverse;
}return M;
}}}}else{if(this.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){if("child" in H&&H.relative=="inside"){var I=H.child;
if(I<this.elements.length){var J=this.elements[I];
var M=J._locateInnerMostNonTerminal(K,N+1);
if(M==null){M={node:J};
}return M;
}}}}}return null;
};
CueCard.QueryNodeLink=function(G,J){this.path=G;
this.token=J;
this.reverse=false;
this.namespace="";
this.property="";
this.originalProperty="";
this.qualifiedProperty="";
this.suffix="";
this.value=null;
if(G.length>0){if(G.charAt(0)=="!"){this.reverse=true;
G=G.substr(1);
}}if(G.length>0){var I=G.indexOf(":");
if(I>=0){this.namespace=G.substr(0,I+1);
G=G.substr(I+1);
if(G.length>0&&G.charAt(0)=="!"){this.reverse=true;
G=G.substr(1);
}}}if(G.length>=2){var H=G.substr(G.length-2);
if(H==">="||H=="<="||H=="~="){this.suffix=H;
G=G.substr(0,G.length-2);
}}if(G.length>1&&this.suffix==""){var H=G.substr(G.length-1);
if(H=="<"||H==">"){this.suffix=H;
G=G.substr(0,G.length-1);
}}this.originalProperty=G;
if(G.length>0){if(G.charAt(0)=="/"){this.qualifiedProperty=G;
var F=G.lastIndexOf("/");
this.property=G.substr(F+1);
}else{this.property=G;
}}if(this.qualifiedProperty==""){if(this.property=="type"){this.qualifiedProperty="/type/object/type";
}else{if(this.property=="id"){this.qualifiedProperty="/type/object/id";
}else{if(this.property=="guid"){this.qualifiedProperty="/type/object/guid";
}else{if(this.property=="name"){this.qualifiedProperty="/type/object/name";
}else{if(this.property=="lang"){this.qualifiedProperty="/type/text/lang";
}else{if(CueCard.QueryNode.isMqlKeyword(this.property)){this.qualifiedProperty=this.property;
}}}}}}}};
CueCard.QueryNodeLink.prototype.getQualifiedPath=function(){return(this.reverse?"!":"")+this.namespace+this.qualifiedProperty+this.suffix;
};
CueCard.QueryNodeLink.prototype.getInverseQualifiedPath=function(){return(this.reverse?"":"!")+this.namespace+this.qualifiedProperty+this.suffix;
};
CueCard.QueryNodeLink.prototype.getUnnamespacedQualifiedPath=function(){return(this.reverse?"!":"")+this.qualifiedProperty+this.suffix;
};
CueCard.QueryNodeLink.prototype.getPath=function(C){var D=(C&&this.qualifiedProperty.length>0)?this.qualifiedProperty:this.originalProperty;
return(this.reverse?"!":"")+this.namespace+D+this.suffix;
};
CueCard.QueryNodeLink.prototype.getValuesOfType=function(L,K){var N=function(A){if(A.isArray){var D=A.value;
for(var B=0;
B<D.length;
B++){var C=D[B];
if(C.type==CueCard.QueryNode.TYPE_TERMINAL&&C.value!=null&&typeof C.value==K){L.push(C.value);
}}}else{if(A.value!=null&&typeof A.value==K){L.push(A.value);
}}};
var I=this.value;
if(I.type==CueCard.QueryNode.TYPE_TERMINAL){N(I);
}else{if(I.type==CueCard.QueryNode.TYPE_NONTERMINAL||I.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){var H=I.type==CueCard.QueryNode.TYPE_NONTERMINAL?I.links:I.elements[0].links;
for(var M=0;
M<H.length;
M++){var J=H[M];
if(J.qualifiedProperty=="/type/value/value"&&J.value.type==CueCard.QueryNode.TYPE_TERMINAL){N(J.value);
}}}}};
CueCard.QueryParser={};
CueCard.QueryParser.parseForContext=function(l,w,c,t){var k=new CueCard.QueryTokenizer(l,w);
var s=k.token();
var q=[];
var n=CueCard.Token.Types;
var j=function(){if(q.length==0){s=k.next();
}else{s=q.shift();
}};
var i=function(A){if(A==0){return s;
}else{while(A>q.length){q.push(k.next());
}return q[A-1];
}};
var z=function(){while(s!=null&&(s.type==n.whitespace||s.type==n.unrecognized)){j();
}};
var u=function(A){return new CueCard.Token(CueCard.Token.Types.phantom,"",A.start,A.start);
};
var r=function(){if(s!=null){return s;
}else{return new CueCard.Token(CueCard.Token.Types.phantom,"",k.index(),k.index());
}};
var h=function(){var A=new CueCard.QueryNode(CueCard.QueryNode.TYPE_MISSING);
A.startToken=A.endToken=u(r());
return A;
};
var d=function(){var A=new CueCard.QueryNode(CueCard.QueryNode.TYPE_TERMINAL);
A.startToken=A.endToken=s;
A.isArray=false;
if(s.type==n.numberLiteral){A.value=parseFloat(s.content);
}else{if(s.type==n.stringLiteral){A.value=s.content.replace(/^['"]/,"").replace(/['"]$/,"");
}else{if(s.type==n.booleanLiteral){A.value=(s.content=="true"||s.content=="True");
}else{if(s.type==n.nullLiteral){A.value=null;
}else{if(s.type==n.delimiter){return null;
}else{A.value=s.content;
}}}}}j();
return A;
};
var b=function(){var B=new CueCard.QueryNode(CueCard.QueryNode.TYPE_TERMINAL);
B.startToken=s;
B.isArray=true;
B.value=[];
if(s!=null&&s.type==n.delimiter&&s.content=="["){j();
}while(s!=null){z();
if(s==null||(s.type==n.delimiter&&s.content=="]")){break;
}var A=f(false);
if(A==null){break;
}B.value.push(A);
z();
if(s!=null&&s.type==n.delimiter&&s.content==","){j();
}}if(s!=null&&s.type==n.delimiter&&s.content=="]"){B.endToken=s;
j();
}if(B.endToken==null){B.endToken=r();
}return B;
};
var p=function(E){var E=new CueCard.QueryNode(CueCard.QueryNode.TYPE_NONTERMINAL);
E.startToken=s;
if(s!=null&&s.type==n.delimiter&&s.content=="{"){j();
}while(s!=null){z();
if(s==null){break;
}var C=null;
var A=null;
var B=null;
if(s.type==n.identifier){C=s.content;
A=s;
j();
z();
}else{if(s.type==n.stringLiteral){C=s.content.replace(/^['"]/,"").replace(/['"]$/,"");
A=s;
j();
z();
}else{A=u(s);
}}if(s!=null&&s.type==n.delimiter&&(s.content==":"||s.content==";")){j();
z();
}if(s!=null){B=f(false);
}if(C!=null||B!=null){var D=new CueCard.QueryNodeLink(C!=null?C:"",A);
D.value=B!=null?B:h();
E.links.push(D);
}z();
if(s==null||(s.type==n.delimiter&&(s.content=="}"||s.content=="]"))){break;
}if(s.type==n.delimiter&&s.content==","){j();
}}if(s!=null&&s.type==n.delimiter&&s.content=="}"){E.endToken=s;
j();
}if(E.endToken==null){E.endToken=r();
}return E;
};
var e=function(){var A=new CueCard.QueryNode(CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY);
A.startToken=s;
A.elements=[];
if(s!=null&&s.type==n.delimiter&&s.content=="["){j();
}while(s!=null){z();
if(s==null||(s.type==n.delimiter&&s.content=="]")){break;
}A.elements.push(p());
z();
if(s!=null&&s.type==n.delimiter&&s.content==","){j();
}}if(s!=null&&s.type==n.delimiter&&s.content=="]"){A.endToken=s;
j();
}if(A.endToken==null){A.endToken=r();
}return A;
};
var g=function(){var B=1;
var A;
while((A=i(B))!=null&&(A.type==n.whitespace||A.type==n.unrecognized)){B++;
}if(A!=null){if(A.type==n.delimiter&&A.content=="{"){return e();
}else{if(A.type==n.identifier||A.type==n.stringLiteral){B++;
while((A=i(B))!=null&&(A.type==n.whitespace||A.type==n.unrecognized)){B++;
}if(A!=null&&A.type==n.delimiter&&A.content==":"){return e();
}}}}return b();
};
var f=function(A){z();
if(s==null){return h();
}else{if(s.type==n.delimiter){if(s.content=="["){return g();
}else{if(s.content=="{"){return p();
}else{return h();
}}}else{if(A){return e();
}else{return d();
}}}};
var v=function(A){return c<A.start.line||(c==A.start.line&&t<=A.start.col);
};
var y=function(A){return c>A.start.line||(c==A.start.line&&t>=A.start.col);
};
var a=function(A){return c<A.end.line||(c==A.end.line&&t<=A.end.col);
};
var v=function(A){return c<A.start.line||(c==A.start.line&&t<=A.start.col);
};
var m=function(A){return A.startToken==A.endToken?(y(A.startToken)&&a(A.startToken)):(y(A.startToken)&&v(A.endToken));
};
var x=function(D,C){if(D.type==CueCard.QueryNode.TYPE_TERMINAL){if(D.isArray){for(var A=0;
A<D.value.length;
A++){var B=D.value[A];
if(v(B.startToken)){C.push({child:A,relative:"before",node:D});
return ;
}else{if(m(B)){C.push({child:A,relative:"inside",node:D});
x(B,C);
return ;
}}}C.push({child:D.value.length,relative:"before",node:D});
}else{C.push({token:D.startToken,node:D,offset:t-D.startToken.start.col});
}}else{if(D.type==CueCard.QueryNode.TYPE_NONTERMINAL_ARRAY){for(var A=0;
A<D.elements.length;
A++){var B=D.elements[A];
if(v(B.startToken)){C.push({child:A,relative:"before",node:D});
return ;
}else{if(m(B)){C.push({child:A,relative:"inside",node:D});
x(B,C);
return ;
}}}C.push({child:D.elements.length,relative:"before",node:D});
}else{if(D.type==CueCard.QueryNode.TYPE_NONTERMINAL){for(var A=0;
A<D.links.length;
A++){var E=D.links[A];
if(v(E.token)){C.push({child:A,relative:"before",node:D});
return ;
}else{if(a(E.token)){C.push({child:A,relative:"path",node:D,offset:t-E.token.start.col});
return ;
}else{if(!y(E.value.startToken)){C.push({child:A,relative:"space",node:D});
return ;
}else{if(a(E.value.endToken)){C.push({child:A,relative:"inside",node:D});
x(E.value,C);
return ;
}}}}}C.push({child:D.links.length,relative:"before",node:D});
}else{C.push({token:D.startToken,node:D});
}}}};
z();
var o={model:f(true),context:[]};
x(o.model,o.context);
return o;
};
CueCard.QueryTokenizer=function(D,C){this._text=D+" ";
this._maxIndex=D.length;
this._index=C;
this._line=0;
this._col=0;
this.next();
};
CueCard.QueryTokenizer.prototype.token=function(){return this._token;
};
CueCard.QueryTokenizer.prototype.index=function(){return this._index;
};
CueCard.QueryTokenizer._whitespaces=" \t\r\n";
CueCard.QueryTokenizer.prototype.next=function(){this._token=null;
if(this._index<this._maxIndex){var L=this._text.charAt(this._index);
var M=this._text.charAt(this._index+1);
var P=this;
function R(){P._index++;
P._col++;
}function N(){return new CueCard.TokenPos(P._index,P._line,P._col);
}function U(){var A=N();
R();
return A;
}function Q(C,D,B){var A=N();
P._pos=A;
P._token=new CueCard.Token(C,B||P._text.substring(D.offset,A.offset),D,A);
}function T(){var A=N();
while(P._index<P._maxIndex){var B=P._text.charAt(P._index);
if(CueCard.QueryTokenizer._whitespaces.indexOf(B)<0){break;
}if(B=="\n"){P._line++;
P._col=0;
}else{P._col++;
}P._index++;
}Q(CueCard.Token.Types.whitespace,A);
}function S(C){var A=N();
if(L=="u"){R();
}R();
var B="";
while(P._index<P._maxIndex){L=P._text.charAt(P._index);
if(L==C){R();
break;
}else{if(L=="\r"||L=="\n"){break;
}}if(L=="\\"){R();
B+=P._text.charAt(P._index);
}else{B+=L;
}R();
}Q(CueCard.Token.Types.stringLiteral,A,B);
}function V(){var B=N();
var A=1;
if(L=="+"){R();
}else{if(L=="-"){R();
A=-1;
}}while(P._index<P._maxIndex&&CueCard.QueryTokenizer._isDigit(P._text.charAt(P._index))){R();
}if(P._index<P._maxIndex&&P._text.charAt(P._index)=="."){R();
while(P._index<P._maxIndex&&CueCard.QueryTokenizer._isDigit(P._text.charAt(P._index))){R();
}}if(P._index<P._maxIndex&&P._text.charAt(P._index)=="e"){R();
L=P._text.charAt(P._index);
if(L=="+"||L=="-"){R();
}while(P._index<P._maxIndex&&CueCard.QueryTokenizer._isDigit(P._text.charAt(P._index))){R();
}}Q(CueCard.Token.Types.numberLiteral,B);
}function O(){var D=N();
while(P._index<P._maxIndex&&CueCard.QueryTokenizer._identifierPrefix.indexOf(P._text.charAt(P._index))>=0){R();
}var E=false;
if(P._index<P._maxIndex-2){var C=P._text.substr(P._index,2);
if(C==">="||C=="<="||C=="~="){R();
R();
E=true;
}}if(!E&&P._index<P._maxIndex-1){var C=P._text.substr(P._index,1);
if(C==">"||C=="<"){R();
E=true;
}}var A=N();
var B=P._text.substring(D.offset,A.offset);
P._pos=A;
if(B=="null"||B=="None"){P._token=new CueCard.Token(CueCard.Token.Types.nullLiteral,B,D,A);
}else{if(B=="true"||B=="True"||B=="false"||B=="False"){P._token=new CueCard.Token(CueCard.Token.Types.booleanLiteral,B,D,A);
}else{P._token=new CueCard.Token(CueCard.Token.Types.identifier,B,D,A);
}}}if(CueCard.QueryTokenizer._whitespaces.indexOf(L)>=0){T();
}else{if("[{}],:".indexOf(L)>=0){Q(CueCard.Token.Types.delimiter,U());
}else{if(L=='"'||L=="'"){S(L);
}else{if(L=="u"&&(M=='"'||M=="'")){S(M);
}else{if(L=="-"||L=="+"||CueCard.QueryTokenizer._isDigit(L)){V();
}else{if(L=="*"){Q(CueCard.Token.Types.identifier,U());
}else{if(CueCard.QueryTokenizer._identifierPrefix.indexOf(L)>=0){O();
}else{Q(CueCard.Token.Types.unrecognized,U());
}}}}}}}}return this._token;
};
CueCard.QueryTokenizer._isDigit=function(B){return"0123456789".indexOf(B)>=0;
};
CueCard.QueryTokenizer._identifierPrefix="#!/_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
CueCard.TokenPos=function(E,D,F){this.offset=E;
this.line=D;
this.col=F;
};
CueCard.Token=function(H,G,F,E){this.type=H;
this.content=G;
this.start=F;
this.end=E;
};
CueCard.Token.Types={unrecognized:-1,phantom:0,whitespace:1,delimiter:2,nullLiteral:3,numberLiteral:4,stringLiteral:5,booleanLiteral:6,identifier:7};
CueCard.JsonpQueue={pendingCallIDs:{},callInProgress:0};
CueCard.JsonpQueue.cancelAll=function(){CueCard.JsonpQueue.pendingCallIDs={};
};
CueCard.JsonpQueue.call=function(M,J,Q,L){if(CueCard.JsonpQueue.callInProgress==0){document.body.style.cursor="progress";
}CueCard.JsonpQueue.callInProgress++;
var R=new Date().getTime()+"x"+Math.floor(Math.random()*1000);
var O=document.createElement("script");
O.setAttribute("onerror","err"+R+"();");
M+=(M.indexOf("?")<0?"?":"&")+"callback=cb"+R;
O.setAttribute("src",M);
var K=function(){CueCard.JsonpQueue.callInProgress--;
if(CueCard.JsonpQueue.callInProgress==0){document.body.style.cursor="auto";
}if(!(L)){O.parentNode.removeChild(O);
}try{delete window["cb"+R];
delete window["err"+R];
}catch(A){window["cb"+R]=undefined;
window["err"+R]=undefined;
}if(R in CueCard.JsonpQueue.pendingCallIDs){delete CueCard.JsonpQueue.pendingCallIDs[R];
return true;
}else{return false;
}};
var N=function(A){if(K()){try{J(A);
}catch(B){}}};
var P=function(){if(K()){if(typeof Q=="function"){try{Q(M);
}catch(A){}}}};
window["cb"+R]=N;
window["err"+R]=P;
CueCard.JsonpQueue.pendingCallIDs[R]=true;
document.getElementsByTagName("head")[0].appendChild(O);
};
CueCard.JsonpQueue.queryOne=function(G,F,H,E){CueCard.JsonpQueue.queryOneEnvelope({"query":G},F,H,E);
};
CueCard.JsonpQueue.queryOneEnvelope=function(P,J,L,O){var K=CueCard.jsonize({"q1":P},{breakLines:false});
var M=CueCard.freebaseServiceUrl+"api/service/mqlread?queries="+encodeURIComponent(K);
var N=function(A){if(A.q1.code=="/api/status/error"){if(typeof L=="function"){L(A.q1);
}}else{J(A.q1);
}};
var I=function(){if(typeof L=="function"){L("Unknown");
}};
CueCard.JsonpQueue.call(M,N,I,O);
};
CueCard.StaticChoicesSuggestor=function(D,C){this._defaultSuggestions=D;
this._onCommit=C;
};
CueCard.StaticChoicesSuggestor.prototype.getSuggestions=function(H,G){H=H.toLowerCase();
var F=[];
for(var J=0;
J<this._defaultSuggestions.length;
J++){var I=this._defaultSuggestions[J];
if(H.length==0||I.label.toLowerCase().indexOf(H)>=0){F.push(I);
}}G(F);
};
CueCard.StaticChoicesSuggestor.prototype.commit=function(B){this._onCommit(B);
};
CueCard.SuggestionController=function(H,J,K,I){this._popup=H;
this._suggestor=K;
this._lastText=I;
this._selectedIndex=-1;
this._suggestions=[];
this._input=$('<input value="'+I+'" />');
this._suggestionContainer=$('<div class="cuecard-suggestion-container"></div>');
$(J).append($('<div class="cuecard-suggestion-input-container"></div>').append(this._input)).append(this._suggestionContainer);
var L=this;
this._onKeyUp=function(B){if(!B.shiftKey&&!B.metaKey&&!B.ctrlKey){if(B.keyCode==36||B.keyCode==38||B.keyCode==40){return L._cancelEvent(B);
}var A=L._input[0].value;
if(A!=L._lastText){L._lastText=A;
L._updateSuggestions();
}}};
this._onKeyDown=function(A){while(!A.shiftKey&&!A.metaKey&&!A.ctrlKey){if(A.keyCode==13||A.keyCode==9){L._commitSelectedSuggestion();
}else{if(A.keyCode==36){if(L._suggestions.length>0){L._selectSuggestion(0,true);
}}else{if(A.keyCode==38){if(L._selectedIndex>0){L._selectSuggestion(L._selectedIndex-1,true);
}}else{if(A.keyCode==40){if(L._selectedIndex<L._suggestions.length-1){L._selectSuggestion(L._selectedIndex+1,true);
}}else{break;
}}}}return L._cancelEvent(A);
}if("onKeyDown" in L._suggestor){return L._suggestor.onKeyDown(A,L._input[0].value);
}};
this._input.keyup(this._onKeyUp).keydown(this._onKeyDown);
var M=this._input[0];
if(M.setSelectionRange){M.focus();
M.setSelectionRange(I.length,I.length);
}else{if(M.createTextRange){var N=M.createTextRange();
N.collapse(true);
N.moveEnd("character",I.length);
N.moveStart("character",I.length);
N.select();
}}this._input[0].focus();
this._updateSuggestions();
};
CueCard.SuggestionController.prototype._updateSuggestions=function(){this._suggestionContainer.empty();
this._suggestionContainer.html('<div class="cuecard-suggestion-progress">Please wait...</div>');
this._selectedIndex=-1;
this._suggestions.length=0;
var B=this;
this._suggestor.getSuggestions(this._lastText,function(A){B._renderSuggestions(A,B._lastText);
});
};
CueCard.SuggestionController.prototype._renderSuggestions=function(G,H){var L=this._suggestionContainer;
L.empty();
var K=this;
var I=function(A,C){var B="elmt" in A?A.elmt:$('<a class="cuecard-suggestion-entry" href="javascript:{}">'+A.label+("hint" in A?(' <span class="cuecard-suggestion-hint">'+A.hint+"</span>"):"")+"</a>");
B.mouseover(function(D){K._selectSuggestion(C,false);
}).click(function(D){K._commitSelectedSuggestion();
}).appendTo(L);
};
this._suggestions=G;
for(var J=0;
J<G.length;
J++){I(G[J],J);
}if(this._suggestions.length>0){this._selectSuggestion(0,false);
}else{$('<div class="cuecard-suggestion-noEntryMessage">No suggestion available.<br/>Press Enter to keep what you have typed,<br/>ESC to discard it.</div>').appendTo(L);
}this._popup.reposition();
};
CueCard.SuggestionController.prototype._selectSuggestion=function(F,E){var D=this._suggestionContainer;
if(this._selectedIndex>=0){this._getSuggestion(this._selectedIndex).removeClass("cuecard-suggestion-selected");
}this._selectedIndex=F;
this._getSuggestion(this._selectedIndex).addClass("cuecard-suggestion-selected");
if(E){this._getSuggestion(this._selectedIndex)[0].scrollIntoView(false);
}};
CueCard.SuggestionController.prototype._commitSelectedSuggestion=function(){if(this._selectedIndex>=0){this._suggestor.commit(this._suggestions[this._selectedIndex]);
}else{this._suggestor.commit(this._input[0].value);
}};
CueCard.SuggestionController.prototype._getSuggestion=function(B){return $(this._suggestionContainer.children()[B]);
};
CueCard.SuggestionController.prototype._cancelEvent=function(B){B.returnValue=false;
B.cancelBubble=true;
if("preventDefault" in B){B.preventDefault();
}return false;
};
CueCard.TypeBasedTopicSuggestor=function(H,I,G,J,F){this._popup=H;
this._defaultSuggestions=I;
this._expectedTypes=G;
this._desiredProperty=J;
this._onCommit=F;
this._popup.elmt.addClass("cuecard-popup-container-wide");
};
CueCard.TypeBasedTopicSuggestor.prototype.getSuggestions=function(J,I){J=J.toLowerCase();
if(J.length==0){var N=[];
for(var K=0;
K<this._defaultSuggestions.length;
K++){N.push(this._defaultSuggestions[K]);
}I(N);
}else{var M=this;
var H=CueCard.UI.createBlockingContinuations(function(D,F){var E=[];
for(var A=0;
A<F.result.length;
A++){var C=F.result[A];
var B=null;
if("/common/topic/image" in C&&C["/common/topic/image"]!=null&&C["/common/topic/image"].length>0){B=CueCard.freebaseServiceUrl+"api/trans/image_thumb"+C["/common/topic/image"][0].id+"?mode=fillcrop&maxwidth=40&maxheight=40";
}E.push({result:C[M._desiredProperty],elmt:$('<a class="cuecard-suggestion-entry" href="javascript:{}"><table cellpadding="0" cellspacing="0"><tr valign="top"><td valign="top">'+(B==null?'<div class="cuecard-suggestion-thumbnail-empty"> </div>':('<img src="'+B+'" />'))+'</td><td valign="top">'+C.name+'<div class="cuecard-suggestion-id">'+C[M._desiredProperty]+"</div></td></tr></table></a>")});
}I(E);
});
this._popup.addPendingContinuation(H);
var L=CueCard.helper+"suggest-values-of-types?t="+encodeURIComponent(this._expectedTypes.join(","))+"&q="+encodeURIComponent(J);
CueCard.JsonpQueue.call(L,H.onDone,H.onError);
}};
CueCard.TypeBasedTopicSuggestor.prototype.commit=function(B){this._onCommit(B);
};
CueCard.TypeSuggestor=function(B){};
CueCard.TypeSuggestor.prototype.getSuggestions=function(B){};
CueCard.UI={};
CueCard.UI.reportError=function(D){try{console.log(D);
}catch(C){alert(D);
}};
CueCard.UI.createBlockingContinuations=function(D,C){return new CueCard.UI.Cont(D,C);
};
CueCard.UI.Cont=function(E,F){var D=this;
this._onDone=E;
this._onError=F||CueCard.UI.reportError;
this._progressUI=null;
this._canceled=false;
this._cleanedUp=false;
this.cleanUp=function(){if(!D._cleanedUp){D._cleanedUp=true;
if(D._progressUI!=null){D._progressUI.remove();
D._progressUI=null;
}}};
this.cancel=function(){if(!D._canceled){D._canceled=true;
D.cleanUp();
}};
this.onError=function(){D.cleanUp();
D._onError();
};
this.onDone=function(){var B=false;
if(!D._canceled){var C=[D];
for(var A=0;
A<arguments.length;
A++){C.push(arguments[A]);
}B=D._onDone.apply(null,C);
}if(!(B)){D.cleanUp();
}};
window.setTimeout(function(){if(!D._cleanedUp){D._progressUI=$('<div class="cuecard-progress">Working...</div>').appendTo($(document.body));
}},300);
};
CueCard.UI.Cont.prototype.isCanceled=function(){return this._canceled;
};
CueCard.UI.Cont.prototype.extend=function(D,C){this._onDone=D;
this._onError=C||this._onError;
return this;
};
CueCard.Utils={};
CueCard.Utils.getPaddingsMargins=function(E,D){if(E.getComputedStyle){var F=E.getComputedStyle(D,null);
return{paddingTop:F.getPropertyValue("padding-top"),marginTop:F.getPropertyValue("margin-top"),paddingLeft:F.getPropertyValue("padding-left"),marginLeft:F.getPropertyValue("margin-left")};
}else{var F=D.currentStyle;
return{paddingTop:F.paddingTop,marginTop:F.marginTop,paddingLeft:F.marginLeft,marginLeft:F.marginLeft};
}};
CueCard.XMetawebCosts={"tu":{meaning:"time/user",subsystem:"graphd"},"ts":{meaning:"time/system",subsystem:"graphd"},"tr":{meaning:"time/real",subsystem:"graphd"},"te":{meaning:"time/overall",subsystem:"graphd"},"pr":{meaning:"page reclaims",subsystem:"graphd"},"pf":{meaning:"page faults",subsystem:"graphd"},"dw":{meaning:"primitive data writes",subsystem:"graphd"},"dr":{meaning:"primitive data reads",subsystem:"graphd"},"in":{meaning:"index size reads",subsystem:"graphd"},"ir":{meaning:"index element reads",subsystem:"graphd"},"iw":{meaning:"index element write",subsystem:"graphd"},"va":{meaning:"value allocation",subsystem:"graphd"},"dt":{meaning:"total time spent in the session",subsystem:"client/me"},"mr":{meaning:"number of mql requests (independent of caches)",subsystem:"client/me"},"ch":{meaning:"cache/hit (memcache, not Squid)",subsystem:"client/me",important:true},"cm":{meaning:"cache/miss (memcache, not Squid)",subsystem:"client/me"},"cr":{meaning:"cache/read (memcache, not Squid)",subsystem:"client/me"},"cs":{meaning:"cache skip (browser shift+reload skips memcache)",subsystem:"client/me"},"lh":{meaning:"lojson-cache/hit",subsystem:"client/me"},"lm":{meaning:"lojson-cache/miss",subsystem:"client/me"},"lr":{meaning:"lojson-cache/read",subsystem:"client/me"},"nreqs":{meaning:"graph requests",subsystem:"client/me",important:true},"tf":{meaning:"time/formatted",subsystem:"client/me"},"tg":{meaning:"time/graph",subsystem:"client/me",important:true},"rt":{meaning:"relevance/time",subsystem:"client/me"},"cc":{meaning:"cpu time (utime + stime)",subsystem:"client/me"},"mcu":{meaning:"mql user time",subsystem:"client/me"},"mcs":{meaning:"mql system time",subsystem:"client/me"},"tm":{meaning:"mql real time",subsystem:"client/me",important:true},"utime":{meaning:"time in user mode (float)",subsystem:"client/me"},"stime":{meaning:"time in system mode (float)",subsystem:"client/me"},"maxrss":{meaning:"maximum resident set size",subsystem:"client/me"},"ixrss":{meaning:"shared memory size",subsystem:"client/me"},"idrss":{meaning:"unshared memory size",subsystem:"client/me"},"isrss":{meaning:"unshared stack size",subsystem:"client/me"},"minflt":{meaning:"page faults not requiring I/O",subsystem:"client/me"},"majflt":{meaning:"page faults requiring I/O",subsystem:"client/me"},"nswap":{meaning:"number of swap outs",subsystem:"client/me"},"inblock":{meaning:"block input operations",subsystem:"client/me"},"oublock":{meaning:"block output operations",subsystem:"client/me"},"msgsnd":{meaning:"messages sent",subsystem:"client/me"},"msgrcv":{meaning:"messages received",subsystem:"client/me"},"nsignals":{meaning:"signals received",subsystem:"client/me"},"nvcsw":{meaning:"voluntary context switches",subsystem:"client/me"},"nivcsw":{meaning:"involuntary context switches",subsystem:"client/me"},"br":{meaning:"number of blob requests",subsystem:"client/me"},"bctn":{meaning:"cdb thumbnail time - from blobclient POV",subsystem:"client/me"},"rt":{meaning:"relevance/time (FIX: same name, different semantics?)",subsystem:"gix"},"pt":{meaning:"postgres time",subsystem:"gix"},"qt":{meaning:"actual postgres query time",subsystem:"gix"},"ct":{meaning:"postgres connect time",subsystem:"gix"},"mt":{meaning:"MQL time",subsystem:"gix"},"tt":{meaning:"total time",subsystem:"other"},"mt":{meaning:"total MQL time: mql_output + mql_filter",subsystem:"other"},"mft":{meaning:"MQL filter time (total time, ie. not per invocation)",subsystem:"other"},"mfc":{meaning:"number of mql_filter invocations",subsystem:"other"},"sh":{meaning:"squid/hit",subsystem:"cache"},"st":{meaning:"squid/total time",subsystem:"cache"},"so":{meaning:"squid/origin server time",subsystem:"cache"}};
CueCard.urlPrefix = 'cuecard/';
