
(function(){var _mjt=window.mjt;var mjt=window.mjt={};mjt.noConflict=function(){window.mjt=_mjt;return mjt;};mjt.NAME='mjt';mjt.VERSION='0.9.2';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._browser_cache_buster={};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];if(typeof mjt.JsonP._browser_cache_buster[this.url]=='undefined'){mjt.JsonP._browser_cache_buster[this.url]=0;}
mjt.JsonP._browser_cache_buster[this.url]+=1;return this.install();}
return original.onready('ready',this).onerror('error',this);};mjt.JsonP.prototype._send_request=function(){var cache_buster='';if(typeof mjt.JsonP._browser_cache_buster[this.url]!='undefined'){cache_buster='&_='+mjt.JsonP._browser_cache_buster[this.url];}
var url=this.cburl+cache_buster;mjt.dynamic_script(undefined,url);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);}
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);return this.ready(o.result);};fb.FreebaseXhrTask.prototype.xhr_error=function(xhr,code,msg,info){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._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,compiler){var t0=(new Date()).getTime();if(typeof compiler=='undefined')
compiler=new mjt.TemplateCompiler();compiler.compile_top(top,'rawmain()');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;};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.output_prefix=null;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){this.scope=new mjt.Scope(this,null,'[toplevel]');this.scope.toplevel=true;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.output_prefix='<?xml version="1.0" encoding="utf-8" ?>\n';else if(mjtattrs['xml-pi']=='false'||mjtattrs['xml-pi']=='0')
this.output_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.output_prefix!=null)
this.markup(this.output_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);