var Prototype={Version:'1.6.1',Browser:(function(){var ua=navigator.userAgent;var isOpera=Object.prototype.toString.call(window.opera)=='[object Opera]';return{IE:!!window.attachEvent&&!isOpera,Opera:isOpera,WebKit:ua.indexOf('AppleWebKit/')>-1,Gecko:ua.indexOf('Gecko')>-1&&ua.indexOf('KHTML')===-1,MobileSafari:/Apple.*Mobile.*Safari/.test(ua)}})(),BrowserFeatures:{XPath:!!document.evaluate,SelectorsAPI:!!document.querySelector,ElementExtensions:(function(){var constructor=window.Element||window.HTMLElement;return!!(constructor&&constructor.prototype);})(),SpecificElementExtensions:(function(){if(typeof window.HTMLDivElement!=='undefined') return true;var div=document.createElement('div');var form=document.createElement('form');var isSupported=false;if(div['__proto__']&&(div['__proto__']!==form['__proto__'])){isSupported=true;} div=form=null;return isSupported;})()},ScriptFragment:']*>([\\S\\s]*?)<\/script>',JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}};if(Prototype.Browser.MobileSafari) Prototype.BrowserFeatures.SpecificElementExtensions=false;var Abstract={};var Try={these:function(){var returnValue;for(var i=0,length=arguments.length;i0){if(match=source.match(pattern)){result+=source.slice(0,match.index);result+=String.interpret(replacement(match));source=source.slice(match.index+match[0].length);}else{result+=source,source='';}} return result;} function sub(pattern,replacement,count){replacement=prepareReplacement(replacement);count=Object.isUndefined(count)?1:count;return this.gsub(pattern,function(match){if(--count<0)return match[0];return replacement(match);});} function scan(pattern,iterator){this.gsub(pattern,iterator);return String(this);} function truncate(length,truncation){length=length||30;truncation=Object.isUndefined(truncation)?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:String(this);} function strip(){return this.replace(/^\s+/,'').replace(/\s+$/,'');} function stripTags(){return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi,'');} function stripScripts(){return this.replace(new RegExp(Prototype.ScriptFragment,'img'),'');} function extractScripts(){var matchAll=new RegExp(Prototype.ScriptFragment,'img');var matchOne=new RegExp(Prototype.ScriptFragment,'im');return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||['',''])[1];});} function evalScripts(){return this.extractScripts().map(function(script){return eval(script)});} function escapeHTML(){return this.replace(/&/g,'&').replace(//g,'>');} function unescapeHTML(){return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');} function toQueryParams(separator){var match=this.strip().match(/([^?#]*)(#.*)?$/);if(!match)return{};return match[1].split(separator||'&').inject({},function(hash,pair){if((pair=pair.split('='))[0]){var key=decodeURIComponent(pair.shift());var value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)value=decodeURIComponent(value);if(key in hash){if(!Object.isArray(hash[key]))hash[key]=[hash[key]];hash[key].push(value);} else hash[key]=value;} return hash;});} function toArray(){return this.split('');} function succ(){return this.slice(0,this.length-1)+ String.fromCharCode(this.charCodeAt(this.length-1)+1);} function times(count){return count<1?'':new Array(count+1).join(this);} function camelize(){var parts=this.split('-'),len=parts.length;if(len==1)return parts[0];var camelized=this.charAt(0)=='-'?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i-1;} function startsWith(pattern){return this.indexOf(pattern)===0;} function endsWith(pattern){var d=this.length-pattern.length;return d>=0&&this.lastIndexOf(pattern)===d;} function empty(){return this=='';} function blank(){return/^\s*$/.test(this);} function interpolate(object,pattern){return new Template(this,pattern).evaluate(object);} return{gsub:gsub,sub:sub,scan:scan,truncate:truncate,strip:String.prototype.trim?String.prototype.trim:strip,stripTags:stripTags,stripScripts:stripScripts,extractScripts:extractScripts,evalScripts:evalScripts,escapeHTML:escapeHTML,unescapeHTML:unescapeHTML,toQueryParams:toQueryParams,parseQuery:toQueryParams,toArray:toArray,succ:succ,times:times,camelize:camelize,capitalize:capitalize,underscore:underscore,dasherize:dasherize,inspect:inspect,toJSON:toJSON,unfilterJSON:unfilterJSON,isJSON:isJSON,evalJSON:evalJSON,include:include,startsWith:startsWith,endsWith:endsWith,empty:empty,blank:blank,interpolate:interpolate};})());var Template=Class.create({initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern;},evaluate:function(object){if(object&&Object.isFunction(object.toTemplateReplacements)) object=object.toTemplateReplacements();return this.template.gsub(this.pattern,function(match){if(object==null)return(match[1]+'');var before=match[1]||'';if(before=='\\')return match[2];var ctx=object,expr=match[3];var pattern=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;match=pattern.exec(expr);if(match==null)return before;while(match!=null){var comp=match[1].startsWith('[')?match[2].replace(/\\\\]/g,']'):match[1];ctx=ctx[comp];if(null==ctx||''==match[3])break;expr=expr.substring('['==match[3]?match[1].length:match[0].length);match=pattern.exec(expr);} return before+String.interpret(ctx);});}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable=(function(){function each(iterator,context){var index=0;try{this._each(function(value){iterator.call(context,value,index++);});}catch(e){if(e!=$break)throw e;} return this;} function eachSlice(number,iterator,context){var index=-number,slices=[],array=this.toArray();if(number<1)return array;while((index+=number)=result) result=value;});return result;} function min(iterator,context){iterator=iterator||Prototype.K;var result;this.each(function(value,index){value=iterator.call(context,value,index);if(result==null||valueb?1:0;}).pluck('value');} function toArray(){return this.map();} function zip(){var iterator=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last())) iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index));});} function size(){return this.toArray().length;} function inspect(){return'#';} return{each:each,eachSlice:eachSlice,all:all,every:all,any:any,some:any,collect:collect,map:collect,detect:detect,findAll:findAll,select:findAll,filter:findAll,grep:grep,include:include,member:include,inGroupsOf:inGroupsOf,inject:inject,invoke:invoke,max:max,min:min,partition:partition,pluck:pluck,reject:reject,sortBy:sortBy,toArray:toArray,entries:toArray,zip:zip,size:size,inspect:inspect,find:detect};})();function $A(iterable){if(!iterable)return[];if('toArray'in Object(iterable))return iterable.toArray();var length=iterable.length||0,results=new Array(length);while(length--)results[length]=iterable[length];return results;} function $w(string){if(!Object.isString(string))return[];string=string.strip();return string?string.split(/\s+/):[];} Array.from=$A;(function(){var arrayProto=Array.prototype,slice=arrayProto.slice,_each=arrayProto.forEach;function each(iterator){for(var i=0,length=this.length;i';} function toJSON(){return Object.toJSON(this.toObject());} function clone(){return new Hash(this);} return{initialize:initialize,_each:_each,set:set,get:get,unset:unset,toObject:toObject,toTemplateReplacements:toObject,keys:keys,values:values,index:index,merge:merge,update:update,toQueryString:toQueryString,inspect:inspect,toJSON:toJSON,clone:clone};})());Hash.from=$H;Object.extend(Number.prototype,(function(){function toColorPart(){return this.toPaddedString(2,16);} function succ(){return this+1;} function times(iterator,context){$R(0,this,true).each(iterator,context);return this;} function toPaddedString(length,radix){var string=this.toString(radix||10);return'0'.times(length-string.length)+string;} function toJSON(){return isFinite(this)?this.toString():'null';} function abs(){return Math.abs(this);} function round(){return Math.round(this);} function ceil(){return Math.ceil(this);} function floor(){return Math.floor(this);} return{toColorPart:toColorPart,succ:succ,times:times,toPaddedString:toPaddedString,toJSON:toJSON,abs:abs,round:round,ceil:ceil,floor:floor};})());function $R(start,end,exclusive){return new ObjectRange(start,end,exclusive);} var ObjectRange=Class.create(Enumerable,(function(){function initialize(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive;} function _each(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ();}} function include(value){if(value1&&!((readyState==4)&&this._complete)) this.respondToReadyState(this.transport.readyState);},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){headers['Content-type']=this.options.contentType+ (this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005) headers['Connection']='close';} if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(Object.isFunction(extras.push)) for(var i=0,length=extras.length;i=200&&status<300);},getStatus:function(){try{return this.transport.status||0;}catch(e){return 0}},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState],response=new Ajax.Response(this);if(state=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(response,response.headerJSON);}catch(e){this.dispatchException(e);} var contentType=response.getHeader('Content-type');if(this.options.evalJS=='force'||(this.options.evalJS&&this.isSameOrigin()&&contentType&&contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) this.evalResponse();} try{(this.options['on'+state]||Prototype.emptyFunction)(response,response.headerJSON);Ajax.Responders.dispatch('on'+state,this,response,response.headerJSON);}catch(e){this.dispatchException(e);} if(state=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction;}},isSameOrigin:function(){var m=this.url.match(/^\s*https?:\/\/[^\/]*/);return!m||(m[0]=='#{protocol}//#{domain}#{port}'.interpolate({protocol:location.protocol,domain:document.domain,port:location.port?':'+location.port:''}));},getHeader:function(name){try{return this.transport.getResponseHeader(name)||null;}catch(e){return null;}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON());}catch(e){this.dispatchException(e);}},dispatchException:function(exception){(this.options.onException||Prototype.emptyFunction)(this,exception);Ajax.Responders.dispatch('onException',this,exception);}});Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Response=Class.create({initialize:function(request){this.request=request;var transport=this.transport=request.transport,readyState=this.readyState=transport.readyState;if((readyState>2&&!Prototype.Browser.IE)||readyState==4){t his.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(transport.responseText);this.headerJSON=this._getHeaderJSON();} if(readyState==4){var xml=transport.responseXML;this.responseXML=Object.isUndefined(xml)?null:xml;this.responseJSON=this._getResponseJSON();}},status:0,statusText:'',getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||'';}catch(e){return''}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders();}catch(e){return null}},getResponseHeader:function(name){return this.transport.getResponseHeader(name);},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders();},_getHeaderJSON:function(){var json=this.getHeader('X-JSON');if(!json)return null;json=decodeURIComponent(escape(json));try{return json.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin());}catch(e){this.request.dispatchException(e);}},_getResponseJSON:function(){var options=this.request.options;if(!options.evalJSON||(options.evalJSON!='force'&&!(this.getHeader('Content-type')||'').include('application/json')) ||this.responseText.blank()) return null;try{return this.responseText.evalJSON(options.sanitizeJSON||!this.request.isSameOrigin());}catch(e){this.request.dispatchException(e);}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,container,url,options){this.container={success:(container.success||container),failure:(container.failure||(container.success?null:container))};options=Object.clone(options);var onComplete=options.onComplete;options.onComplete=(function(response,json){this.updateContent(response.responseText);if(Object.isFunction(onComplete))onComplete(response,json);}).bind(this);$super(url,options);},updateContent:function(responseText){var receiver=this.container[this.success()?'success':'failure'],options=this.options;if(!options.evalScripts)responseText=responseText.stripScripts();if(receiver=$(receiver)){if(options.insertion){if(Object.isString(options.insertion)){var insertion={};insertion[options.insertion]=responseText;receiver.insert(insertion);} else options.insertion(receiver,responseText);} else receiver.update(responseText);}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,container,url,options){$super(options);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=container;this.url=url;this.start();},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent();},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments);},updateComplete:function(response){if(this.options.decay){this.decay=(response.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=response.responseText;} this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency);},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options);}});function $(element){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i';delete attributes.name;return Element.writeAttribute(document.createElement(tagName),attributes);} if(!cache[tagName])cache[tagName]=Element.extend(document.createElement(tagName));return Element.writeAttribute(cache[tagName].cloneNode(false),attributes);};Object.extend(global.Element,element||{});if(element)global.Element.prototype=element.prototype;})(this);Element.cache={};Element.idCounter=1;Element.Methods={visible:function(element){return $(element).style.display!='none';},toggle:function(element){element=$(element);Element[Element.visible(element)?'hide':'show'](element);return element;},hide:function(element){element=$(element);element.style.display='none';return element;},show:function(element){element=$(element);element.style.display='';return element;},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element;},update:(function(){var SELECT_ELEMENT_INNERHTML_BUGGY=(function(){var el=document.createElement("select"),isBuggy=true;el.innerHTML="";if(el.options&&el.options[0]){isBuggy=el.options[0].nodeName.toUpperCase()!= ="OPTION";} el=null;return isBuggy;})();var TABLE_ELEMENT_INNERHTML_BUGGY=(function(){try{var el=document.createElement("table");if(el&&el.tBodies){el.innerHTML="test";var isBuggy=typeof el.tBodies[0]=="undefined";el=null;return isBuggy;}}catch(e){return true;}})();var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING=(function(){var s=document.createElement("script"),isBuggy=false;try{s.appendChild(document.createTextNode(""));isBuggy=!s.firstChild||s.firstChild&&s.firstChild.nodeType!==3;}catch(e){isBuggy=true;} s=null;return isBuggy;})();function update(element,content){element=$(element);if(content&&content.toElement) content=content.toElement();if(Object.isElement(content)) return element.update().insert(content);content=Object.toHTML(content);var tagName=element.tagName.toUpperCase();if(tagName==='SCRIPT'&&SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING){element.text=content;return element;} if(SELECT_ELEMENT_INNERHTML_BUGGY||TABLE_ELEMENT_INNERHTML_BUGGY){if(tagName in Element._insertionTranslations.tags){while(element.firstChild){element.removeChild(element.firstChild);} Element._getContentFromAnonymousElement(tagName,content.stripScripts()).each(function(node){element.appendChild(node)});} else{element.innerHTML=content.stripScripts();}} else{element.innerHTML=content.stripScripts();} content.evalScripts.bind(content).defer();return element;} return update;})(),replace:function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();else if(!Object.isElement(content)){content=Object.toHTML(content);var range=element.ownerDocument.createRange();range.selectNode(element);content.evalScripts.bind(content).defer();content=range.createContextualFragment(content.stripScripts());} element.parentNode.replaceChild(content,element);return element;},insert:function(element,insertions){element=$(element);if(Object.isString(insertions)||Object.isNumber(insertions)||Object.isElement(insertions)||(insertions&&(insertions.toElement||insertions.toHTML))) insertions={bottom:insertions};var content,insert,tagName,childNodes;for(var position in insertions){content=insertions[position];position=position.toLowerCase();insert=Element._insertionTranslations[position];if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){insert(element,content);continue;} content=Object.toHTML(content);tagName=((position=='before'||position=='after')?element.parentNode:element).tagName.toUpperCase();childNodes=Element._getContentFromAnonymousElement(tagName,content.stripScripts());if(position=='top'||position=='after')childNodes.reverse();childNodes.each(insert.curry(element));content.evalScripts.bind(content).defer();} return element;},wrap:function(element,wrapper,attributes){element=$(element);if(Object.isElement(wrapper)) $(wrapper).writeAttribute(attributes||{});else if(Object.isString(wrapper))wrapper=new Element(wrapper,attributes);else wrapper=new Element('div',wrapper);if(element.parentNode) element.parentNode.replaceChild(wrapper,element);wrapper.appendChild(element);return wrapper;},inspect:function(element){element=$(element);var result='<'+element.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(pair){var property=pair.first(),attribute=pair.last();var value=(element[property]||'').toString();if(value)result+=' '+attribute+'='+value.inspect(true);});return result+'>';},recursivelyCollect:function(element,property){element=$(element);var elements=[];while(element=element[property]) if(element.nodeType==1) elements.push(Element.extend(element));return elements;},ancestors:function(element){return Element.recursivelyCollect(element,'parentNode');},descendants:function(element){return Element.select(element,"*");},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element);},immediateDescendants:function(element){if(!(element=$(element).firstChild))return[];while(element&&element.nodeType!=1)element=element.nextSibling;if(element)return[element].concat($(element).nextSiblings());return[];},previousSiblings:function(element){return Element.recursivelyCollect(element,'previousSibling');},nextSiblings:function(element){return Element.recursivelyCollect(element,'nextSibling');},siblings:function(element){element=$(element);return Element.previousSiblings(element).reverse().concat(Element.nextSiblings(element));},match:function(element,selector){if(Object.isString(selector)) selector=new Selector(selector);return selector.match($(element));},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=Element.ancestors(element);return Object.isNumber(expression)?ancestors[expression]:Selector.findElement(ancestors,expression,index);},down:function(element,expression,index){element=$(element);if(arguments.length==1)return Element.firstDescendant(element);return Object.isNumber(expression)?Element.descendants(element)[expression]:Element.select(element,expression)[index||0];},previous:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(element));var previousSiblings=Element.previousSiblings(element);return Object.isNumber(expression)?previousSiblings[expression]:Selector.findElement(previousSiblings,expression,index);},next:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(e lement));var nextSiblings=Element.nextSiblings(element);return Object.isNumber(expression)?nextSiblings[expression]:Selector.findElement(nextSiblings,expression,index);},select:function(element){var args=Array.prototype.slice.call(arguments,1);return Selector.findChildElements(element,args);},adjacent:function(element){var args=Array.prototype.slice.call(arguments,1);return Selector.findChildElements(element.parentNode,args).without(element);},identify:function(element){element=$(element);var id=Element.readAttribute(element,'id');if(id)return id;do{id='anonymous_element_'+Element.idCounter++}while($(id));Element.writeAttribute(element,'id',id);return id;},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){var t=Element._attributeTranslations.read;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];if(name.include(':')){return(!element.attributes||!element.attributes[name])?null:element.attributes[name].value;}} return element.getAttribute(name);},writeAttribute:function(element,name,value){element=$(element);var attributes={},t=Element._attributeTranslations.write;if(typeof name=='object')attributes=name;else attributes[name]=Object.isUndefined(value)?true:value;for(var attr in attributes){name=t.names[attr]||attr;value=attributes[attr];if(t.values[attr])name=t.values[attr](element,value);if(value===false||value===null) element.removeAttribute(name);else if(value===true) element.setAttribute(name,name);else element.setAttribute(name,value);} return element;},getHeight:function(element){return Element.getDimensions(element).height;},getWidth:function(element){return Element.getDimensions(element).width;},classNames:function(element){return new Element.ClassNames(element);},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;return(elementClassName.length>0&&(elementClassName==className||new RegExp("(^|\\s)"+className+"(\\s|$)").test(elementClassName)));},addClassName:function(element,className){if(!(element=$(element)))return;if(!Element.hasClassName(element,className)) element.className+=(element.className?' ':'')+className;return element;},removeClassName:function(element,className){if(!(element=$(element)))return;element.className=element.className.replace(new RegExp("(^|\\s+)"+className+"(\\s+|$)"),' ').strip();return element;},toggleClassName:function(element,className){if(!(element=$(element)))return;return Element[Element.hasClassName(element,className)?'removeClassName':'addClassName'](element,className);},cleanWhitespace:function(element){element=$(element);var node=element.firstChild;while(node){var nextNode=node.nextSibling;if(node.nodeType==3&&!/\S/.test(node.nodeValue)) element.removeChild(node);node=nextNode;} return element;},empty:function(element){return $(element).innerHTML.blank();},descendantOf:function(element,ancestor){element=$(element),ancestor=$(ancestor);if(element.compareDocumentPosition) return(element.compareDocumentPosition(ancestor)&8)===8;if(ancestor.contains) return ancestor.contains(element)&&ancestor!==element;while(element=element.parentNode) if(element==ancestor)return true;return false;},scrollTo:function(element){element=$(element);var pos=Element.cumulativeOffset(element);window.scrollTo(pos[0],pos[1]);return element;},getStyle:function(element,style){element=$(element);style=style=='float'?'cssFloat':style.camelize();var value=element.style[style];if(!value||value=='auto'){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;} if(style=='opacity')return value?parseFloat(value):1.0;return value=='auto'?null:value;},getOpacity:function(element){return $(element).getStyle('opacity');},setStyle:function(element,styles){element=$(element);var elementStyle=element.style,match;if(Object.isString(styles)){element.style.cssText+=';'+styles;return styles.include('opacity')?element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]):element;} for(var property in styles) if(property=='opacity')element.setOpacity(styles[property]);else elementStyle[(property=='float'||property=='cssFloat')?(Object.isUndefined(elementStyle.styleFloat)?'cssFloat':'styleFloat'):property]=styles[property];return element;},setOpacity:function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;return element;},getDimensions:function(element){element=$(element);var display=Element.getStyle(element,'display');if(display!='none'&&display!=null) return{width:element.offsetWidth,height:element.offsetHeight};var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';if(originalPosition!='fixed') els.position='absolute';els.display='block';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,'position');if(pos=='static'||!pos){element._madePositioned=true;element.style.position='relative';if(Prototype.Browser.Opera){element.style.top=0;element.style.left=0;}} return element;},undoPositioned:function(element){element=$(element);if(element._madePositioned){element._madePositioned=undefined;element.style.position=element.style.top=element.style.left=element.style.bottom=element.style.right='';} return element;},makeClipping:function(element){element=$(element);if(element._overflow)return element;element._overflow=Element.getStyle(element,'overflow')||'auto';if(element._overflow!=='hidden') element.style.overflow='hidden';return element;},undoClipping:function(element){element=$(element);if(!element._overflow)return element;element.style.overflow=element._overflow=='auto'?'':element._overflow;element._overflow=null;return element;},cumulativeOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);return Element._returnOffset(valueL,valueT);},positionedOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(element.tagName.toUpperCase()=='BODY')break;var p=Element.getStyle(element,'position');if(p!=='static')break;}}while(element);return Element._returnOffset(valueL,valueT);},absolutize:function(element){element=$(element);if(Element.getStyle(element,'position')=='absolute')return element;var offsets=Element.positionedOffset(element);var top=offsets[1];var left=offsets[0];var width=element.clientWidth;va r height=element.clientHeight;element._originalLeft=left-parseFloat(element.style.left||0);element._originalTop=top-parseFloat(element.style.top||0);element._originalWidth=element.style.width;element._originalHeight=element.style.height;element.style.position='absolute';element.style.top=top+'px';element.style.left=left+'px';element.style.width=width+'px';element.style.height=height+'px';return element;},relativize:function(element){element=$(element);if(Element.getStyle(element,'position')=='relative')return element;element.style.position='relative';var top=parseFloat(element.style.top||0)-(element._originalTop||0);var left=parseFloat(element.style.left||0)-(element._originalLeft||0);element.style.top=top+'px';element.style.left=left+'px';element.style.height=element._originalHeight;element.style.width=element._originalWidth;return element;},cumulativeScrollOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode;}while(element); return Element._returnOffset(valueL,valueT);},getOffsetParent:function(element){if(element.offsetParent)return $(element.offsetParent);if(element==document.body)return $(element);while((element=element.parentNode)&&element!=document.body) if(Element.getStyle(element,'position')!='static') return $(element);return $(document.body);},viewportOffset:function(forElement){var valueT=0,valueL=0;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body&&Element.getStyle(element,'position')=='absolute')break;}while(element=element.offsetParent);element=forElement;do{if(!Prototype.Browser.Opera||(element.tagName&&(element.tagName.toUpperCase()=='BODY'))){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;}}while(element=element.parentNode);return Element._returnOffset(valueL,valueT);},clonePosition:function(element,source){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});source=$(source);var p=Element.viewportOffset(source);element=$(element);var delta=[0,0];var parent=null;if(Element.getStyle(element,'position')=='absolute'){parent=Element.getOffsetParent(element);delta=Element.viewportOffset(parent);} if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=document.body.offsetTop;} if(options.setLeft)element.style.left=(p[0]-delta[0]+options.offsetLeft)+'px';if(options.setTop)element.style.top=(p[1]-delta[1]+options.offsetTop)+'px';if(options.setWidth)element.style.width=source.offsetWidth+'px';if(options.setHeight)element.style.height=source.offsetHeight+'px';return element;}};Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:'class',htmlFor:'for'},values:{}}};if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(proceed,element,style){switch(style){case'left':case'top':case'right':case'bottom':if(proceed(element,'position')==='static')return null;case'height':case'width':if(!Element.visible(element))return null;var dim=parseInt(proceed(element,style),10);if(dim!==element['offset'+style.capitalize()]) return dim+'px';var properties;if(style==='height'){properties=['border-top-width','padding-top','padding-bottom','border-bottom-width'];} else{properties=['border-left-width','padding-left','padding-right','border-right-width'];} return properties.inject(dim,function(memo,property){var val=proceed(element,property);return val===null?memo:memo-parseInt(val,10);})+'px';default:return proceed(element,style);}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(proceed,element,attribute){if(attribute==='title')return element.title;return proceed(element,attribute);});} else if(Prototype.Browser.IE){Element.Methods.getOffsetParent=Element.Methods.getOffsetParent.wrap(function(proceed,element){element=$(element);try{element.offsetParent} catch(e){return $(document.body)} var position=element.getStyle('position');if(position!=='static')return proceed(element);element.setStyle({position:'relative'});var value=proceed(element);element.setStyle({position:position});return value;});$w('positionedOffset viewportOffset').each(function(method){Element.Methods[method]=Element.Methods[method].wrap(function(proceed,element){element=$(element);try{element.offsetParent} catch(e){return Element._returnOffset(0,0)} var position=element.getStyle('position');if(position!=='static')return proceed(element);var offsetParent=element.getOffsetParent();if(offsetParent&&offsetParent.getStyle('position')==='fixed') offsetParent.setStyle({zoom:1});element.setStyle({position:'relative'});var value=proceed(element);element.setStyle({position:position});return value;});});Element.Methods.cumulativeOffset=Element.Methods.cumulativeOffset.wrap(function(proceed,element){try{element.offsetParent} catch(e){return Element._returnOffset(0,0)} return proceed(element);});Element.Methods.getStyle=function(element,style){element=$(element);style=(style=='float'||style=='cssFloat')?'styleFloat':style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style=='opacity'){if(value=(element.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/)) if(value[1])return parseFloat(value[1])/100;return 1.0;} if(value=='auto'){if((style=='width'||style=='height')&&(element.getStyle('display')!='none')) return element['offset'+style.capitalize()]+'px';return null;} return value;};Element.Methods.setOpacity=function(element,value){function stripAlpha(filter){return filter.replace(/alpha\([^\)]*\)/gi,'');} element=$(element);var currentStyle=element.currentStyle;if((currentStyle&&!currentStyle.hasLayout)||(!currentStyle&&element.style.zoom=='normal')) element.style.zoom=1;var filter=element.getStyle('filter'),style=element.style;if(value==1||value===''){(filter=stripAlpha(filter))?style.filter=filter:style.removeAttribute('filter');return element;}else if(value<0.00001)value=0;style.filter=stripAlpha(filter)+'alpha(opacity='+(value*100)+')';return element;};Element._attributeTranslations=(function(){var classProp='className';var forProp='for';var el=document.createElement('div');el.setAttribute(classProp,'x');if(el.className!=='x'){el.setAttribute('class','x');if(el.className==='x'){classProp='class';}} el=null;el=document.createElement('label');el.setAttribute(forProp,'x');if(el.htmlFor!=='x'){el.setAttribute('htmlFor','x');if(el.htmlFor==='x'){forProp='htmlFor';}} el=null;return{read:{names:{'class':classProp,'className':classProp,'for':forProp,'htmlFor':forProp},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute);},_getAttr2:function(element,attribute){return element.getAttribute(attribute,2);},_getAttrNode:function(element,attribute){var node=element.getAttributeNode(attribute);return node?node.value:"";},_getEv:(function(){var el=document.createElement('div');el.onclick=Prototype.emptyFunction;var value=el.getAttribute('onclick');var f;if(String(value).indexOf('{')>-1){f=function(element,attribute){attribute=element.getAttribute(attribute);if(!attribute)return null;attribute=attribute.toString();attribute=attribute.split('{')[1];attribute=attribute.split('}')[0];return attribute.strip();};} else if(value===''){f=function(element,attribute){attribute=element.getAttribute(attribute);if(!attribute)return null;return attribute.strip();};} el=null;return f;})(),_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null;},style:function(element){return element.style.cssText.toLowerCase();},title:function(element){return element.title;}}}}})();Element._attributeTranslations.write={names:Object.extend({cellpadding:'cellPadding',cellspacing:'cellSpacing'},Element._attributeTranslations.read.names),values:{checked:function(element,value){element.checked=!!value;},style:function(element,value){element.style.cssText=value?value:'';}}};Element._attributeTranslations.has={};$w('colSpan rowSpan vAlign dateTime accessKey tabIndex '+'encType maxLength readOnly longDesc frameBorder').each(function(attr){Element._attributeTranslations.write.names[attr.toLowerCase()]=attr;Element._attributeTranslations.has[attr.toLowerCase()]=attr;});(function(v){Object.extend(v,{href:v._getAttr2,src:v._getAttr2,type:v._getAttr,action:v._getAttrNode,disabled:v._flag,checked:v._flag,readonly:v._flag,multiple:v._flag,onload:v._getEv,onunload:v._ getEv,onclick:v._getEv,ondblclick:v._getEv,onmousedown:v._getEv,onmouseup:v._getEv,onmouseover:v._getEv,onmousemove:v._getEv,onmouseout:v._getEv,onfocus:v._getEv,onblur:v._getEv,onkeypress:v._getEv,onkeydown:v._getEv,onkeyup:v._getEv,onsubmit:v._getEv,onreset:v._getEv,onselect:v._getEv,onchange:v._getEv});})(Element._attributeTranslations.read.values);if(Prototype.BrowserFeatures.ElementExtensions){(function(){function _descendants(element){var nodes=element.getElementsByTagName('*'),results=[];for(var i=0,node;node=nodes[i];i++) if(node.tagName!=="!") results.push(node);return results;} Element.Methods.down=function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();return Object.isNumber(expression)?_descendants(element)[expression]:Element.select(element,expression)[index||0];}})();}} else if(Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1)?0.999999:(value==='')?'':(value<0.00001)?0:value;return element;};} else if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;if(value==1) if(element.tagName.toUpperCase()=='IMG'&&element.width){element.width++;element.width--;}else try{var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){} return element;};Element.Methods.cumulativeOffset=function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body) if(Element.getStyle(element,'position')=='absolute')break;element=element.offsetParent;}while(element);return Element._returnOffset(valueL,valueT);};} if('outerHTML'in document.documentElement){Element.Methods.replace=function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){element.parentNode.replaceChild(content,element);return element;} content=Object.toHTML(content);var parent=element.parentNode,tagName=parent.tagName.toUpperCase();if(Element._insertionTranslations.tags[tagName]){var nextSibling=element.next();var fragments=Element._getContentFromAnonymousElement(tagName,content.stripScripts());parent.removeChild(element);if(nextSibling) fragments.each(function(node){parent.insertBefore(node,nextSibling)});else fragments.each(function(node){parent.appendChild(node)});} else element.outerHTML=content.stripScripts();content.evalScripts.bind(content).defer();return element;};} Element._returnOffset=function(l,t){var result=[l,t];result.left=l;result.top=t;return result;};Element._getContentFromAnonymousElement=function(tagName,html){var div=new Element('div'),t=Element._insertionTranslations.tags[tagName];if(t){div.innerHTML=t[0]+html+t[1];t[2].times(function(){div=div.firstChild});}else div.innerHTML=html;return $A(div.childNodes);};Element._insertionTranslations={before:function(element,node){element.parentNode.insertBefore(node,element);},top:function(element,node){element.insertBefore(node,element.firstChild);},bottom:function(element,node){element.appendChild(node);},after:function(element,node){element.parentNode.insertBefore(node,element.nextSibling);},tags:{TABLE:['','
',1],TBODY:['','
',2],TR:['','
',3],TD:['
','
',4],SELECT:['',1]}};(function(){var tags=Element._insertionTranslations.tags;Object.extend(tags,{THEAD:tags.TBODY,T FOOT:tags.TBODY,TH:tags.TD});})();Element.Methods.Simulated={hasAttribute:function(element,attribute){attribute=Element._attributeTranslations.has[attribute]||attribute;var node=$(element).getAttributeNode(attribute);return!!(node&&node.specified);}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);(function(div){if(!Prototype.BrowserFeatures.ElementExtensions&&div['__proto__']){window.HTMLElement={};window.HTMLElement.prototype=div['__proto__'];Prototype.BrowserFeatures.ElementExtensions=true;} div=null;})(document.createElement('div')) Element.extend=(function(){function checkDeficiency(tagName){if(typeof window.Element!='undefined'){var proto=window.Element.prototype;if(proto){var id='_'+(Math.random()+'').slice(2);var el=document.createElement(tagName);proto[id]='x';var isBuggy=(el[id]!=='x');delete proto[id];el=null;return isBuggy;}} return false;} function extendElementWith(element,methods){for(var property in methods){var value=methods[property];if(Object.isFunction(value)&&!(property in element)) element[property]=value.methodize();}} var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY=checkDeficiency('object');if(Prototype.BrowserFeatures.SpecificElementExtensions){if(HTMLOBJECTELEMENT_PROTOTYPE_BUGGY){return function(element){if(element&&typeof element._extendedByPrototype=='undefined'){var t=element.tagName;if(t&&(/^(?:object|applet|embed)$/i.test(t))){extendElementWith(element,Element.Methods);extendElementWith(element,Element.Methods.Simulated);extendElementWith(element,Element.Methods.ByTag[t.toUpperCase()]);}} return element;}} return Prototype.K;} var Methods={},ByTag=Element.Methods.ByTag;var extend=Object.extend(function(element){if(!element||typeof element._extendedByPrototype!='undefined'||element.nodeType!=1||element==window)return element;var methods=Object.clone(Methods),tagName=element.tagName.toUpperCase();if(ByTag[tagName])Object.extend(methods,ByTag[tagName]);extendElementWith(element,methods);element._extendedByPrototype=Prototype.emptyFunction;return element;},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(Methods,Element.Methods);Object.extend(Methods,Element.Methods.Simulated);}}});extend.refresh();return extend;})();Element.hasAttribute=function(element,attribute){if(element.hasAttribute)return element.hasAttribute(attribute);return Element.Methods.Simulated.hasAttribute(element,attribute);};Element.addMethods=function(methods){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!methods){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Me thods.ByTag,{"FORM":Object.clone(Form.Methods),"INPUT":Object.clone(Form.Element.Methods),"SELECT":Object.clone(Form.Element.Methods),"TEXTAREA":Object.clone(Form.Element.Methods)});} if(arguments.length==2){var tagName=methods;methods=arguments[1];} if(!tagName)Object.extend(Element.Methods,methods||{});else{if(Object.isArray(tagName))tagName.each(extend);else extend(tagName);} function extend(tagName){tagName=tagName.toUpperCase();if(!Element.Methods.ByTag[tagName]) Element.Methods.ByTag[tagName]={};Object.extend(Element.Methods.ByTag[tagName],methods);} function copy(methods,destination,onlyIfAbsent){onlyIfAbsent=onlyIfAbsent||false;for(var property in methods){var value=methods[property];if(!Object.isFunction(value))continue;if(!onlyIfAbsent||!(property in destination)) destination[property]=value.methodize();}} function findDOMClass(tagName){var klass;var trans={"OPTGROUP":"OptGroup","TEXTAREA":"TextArea","P":"Paragraph","FIELDSET":"FieldSet","UL":"UList","OL":"OList","DL":"DList","DIR":"Directory","H1":"Heading","H2":"Heading","H3":"Heading","H4":"Heading","H5":"Heading","H6":"Heading","Q":"Quote","INS":"Mod","DEL":"Mod","A":"Anchor","IMG":"Image","CAPTION":"TableCaption","COL":"TableCol","COLGROUP":"TableCol","THEAD":"TableSection","TFOOT":"TableSection","TBODY":"TableSection","TR":"TableRow","TH":"TableCell","TD":"TableCell","FRAMESET":"FrameSet","IFRAME":"IFrame"};if(trans[tagName])klass='HTML'+trans[tagName]+'Element';if(window[klass])return window[klass];klass='HTML'+tagName+'Element';if(window[klass])return window[klass];klass='HTML'+tagName.capitalize()+'Element';if(window[klass])return window[klass];var element=document.createElement(tagName);var proto=element['__proto__']||element.constructor.prototype;element=null;return proto;} var elementPrototype=window.HTMLElement?HTMLElement.prototype:Element.prototype;if(F.ElementExtensions){copy(Element.Methods,elementPrototype);copy(Element.Methods.Simulated,elementPrototype,true);} if(F.SpecificElementExtensions){for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(Object.isUndefined(klass))continue;copy(T[tag],klass.prototype);}} Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh)Element.extend.refresh();Element.cache={};};document.viewport={getDimensions:function(){return{width:this.getWidth(),height:this.getHeight()};},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop);}};(function(viewport){var B=Prototype.Browser,doc=document,element,property={};function getRootElement(){if(B.WebKit&&!doc.evaluate) return document;if(B.Opera&&window.parseFloat(window.opera.version())<9.5) return document.body;return document.documentElement;} function define(D){if(!element)element=getRootElement();property[D]='client'+D;viewport['get'+D]=function(){return element[property[D]]};return viewport['get'+D]();} viewport.getWidth=define.curry('Width');viewport.getHeight=define.curry('Height');})(document.viewport);Element.Storage={UID:1};Element.addMethods({getStorage:function(element){if(!(element=$(element)))return;var uid;if(element===window){uid=0;}else{if(typeof element._prototypeUID==="undefined") element._prototypeUID=[Element.Storage.UID++];uid=element._prototypeUID[0];} if(!Element.Storage[uid]) Element.Storage[uid]=$H();return Element.Storage[uid];},store:function(element,key,value){if(!(element=$(element)))return;if(arguments.length===2){Element.getStorage(element).update(key);}else{Element.getStorage(element).set(key,value);} return element;},retrieve:function(element,key,defaultValue){if(!(element=$(element)))return;var hash=Element.getStorage(element),value=hash.get(key);if(Object.isUndefined(value)){hash.set(key,defaultValue);value=defaultValue;} return value;},clone:function(element,deep){if(!(element=$(element)))return;var clone=element.cloneNode(deep);clone._prototypeUID=void 0;if(deep){var descendants=Element.select(clone,'*'),i=descendants.length;while(i--){descendants[i]._prototypeUID=void 0;}} return Element.extend(clone);}});var Selector=Class.create({initialize:function(expression){this.expression=expression.strip();if(this.shouldUseSelectorsAPI()){this.mode='selectorsAPI';}else if(this.shouldUseXPath()){this.mode='xpath';this.compileXPathMatcher();}else{this.mode="normal";this.compileMatcher();}},shouldUseXPath:(function(){var IS_DESCENDANT_SELECTOR_BUGGY=(function(){var isBuggy=false;if(document.evaluate&&window.XPathResult){var el=document.createElement('div');el.innerHTML='
';var xpath=".//*[local-name()='ul' or local-name()='UL']"+"//*[local-name()='li' or local-name()='LI']";var result=document.evaluate(xpath,el,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);isBuggy=(result.snapshotLength!==2);el=null;} return isBuggy;})();return function(){if(!Prototype.BrowserFeatures.XPath)return false;var e=this.expression;if(Prototype.Browser.WebKit&&(e.include("-of-type")||e.include(":empty"))) return false;if((/(\[[\w-]*?:|:checked)/).test(e)) return false;if(IS_DESCENDANT_SELECTOR_BUGGY)return false;return true;}})(),shouldUseSelectorsAPI:function(){if(!Prototype.BrowserFeatures.SelectorsAPI)return false;if(Selector.CASE_INSENSITIVE_CLASS_NAMES)return false;if(!Selector._div)Selector._div=new Element('div');try{Selector._div.querySelector(this.expression);}catch(e){return false;} return true;},compileMatcher:function(){var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m,len=ps.length,name;if(Selector._cache[e]){this.matcher=Selector._cache[e];return;} this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i=0;i";}});if(Prototype.BrowserFeatures.SelectorsAPI&&document.compatMode==='BackCompat'){Selector.CASE_INSENSITIVE_CLASS_NAMES=(function(){var div=document.createElement('div'),span=document.createElement('span');div.id="prototype_test_id";span.className='Test';div.appendChild(span);var isIgnored=(div.querySelector('#prototype_test_id .test')!==null);div=span=null;return isIgnored;})();} Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:'/following-sibling::*',tagName:function(m){if(m[1]=='*')return'';return"[local-name()='"+m[1].toLowerCase()+"' or local-name()='"+m[1].toUpperCase()+"']";},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:function(m){m[1]=m[1].toLowerCase();return new Template("[@#{1}]").evaluate(m);},attr:function(m){m[1]=m[1].toLowerCase();m[3]=m[5]||m[6];return new Template(Selector.xpath.operators[m[2]]).evaluate(m);},pseudo:function(m){var h=Selector.xpath.pseudos[m[1]];if(!h)return'';if(Object.isFunction(h))return h(m);return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);},operators:{'=':"[@#{1}='#{3}']",'!=':"[@#{1}!='#{3}']",'^=':"[starts-with(@#{1}, '#{3}')]",'$=':"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",'*=':"[contains(@#{1}, '#{3}')]",'~=':"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",'|=':"[contains(concat( '-', @#{1}, '-'), '-#{3}-')]"},pseudos:{'first-child':'[not(preceding-sibling::*)]','last-child':'[not(following-sibling::*)]','only-child':'[not(preceding-sibling::* or following-sibling::*)]','empty':"[count(*) = 0 and (count(text()) = 0)]",'checked':"[@checked]",'disabled':"[(@disabled) and (@type!='hidden')]",'enabled':"[not(@disabled) and (@type!='hidden')]",'not':function(m){var e=m[6],p=Selector.patterns,x=Selector.xpath,le,v,len=p.length,name;var exclusion=[];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i=0;i= 0)]";return new Template(predicate).evaluate({fragment:fragment,a:a,b:b});}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c); c = false;',className:'n = h.className(n, r, "#{1}", c); c = false;',id:'n = h.id(n, r, "#{1}", c); c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}", c); c = false;',attr:function(m){m[3]=(m[5]||m[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);},pseudo:function(m){if(m[6])m[6]=m[6].replace(/"/g,'\\"');return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:[{name:'laterSibling',re:/^\s*~\s*/},{name:'child',re :/^\s*>\s*/},{name:'adjacent',re:/^\s*\+\s*/},{name:'descendant',re:/^\s/},{name:'tagName',re:/^\s*(\*|[\w\-]+)(\b|$)?/},{name:'id',re:/^#([\w\-\*]+)(\b|$)/},{name:'className',re:/^\.([\w\-\*]+)(\b|$)/},{name:'pseudo',re:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/},{name:'attrPresence',re:/^\[((?:[\w-]+:)?[\w-]+)\]/},{name:'attr',re:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/}],assertions:{tagName:function(element,matches){return matches[1].toUpperCase()==element.tagName.toUpperCase();},className:function(element,matches){return Element.hasClassName(element,matches[1]);},id:function(element,matches){return element.id===matches[1];},attrPresence:function(element,matches){return Element.hasAttribute(element,matches[1]);},attr:function(element,matches){var nodeValue=Element.readAttribute(element,matches[1]);return nodeValue&&Selector.operators[matches[2]](nodeValue,matches[5]||matches[6]);}},handler s:{concat:function(a,b){for(var i=0,node;node=b[i];i++) a.push(node);return a;},mark:function(nodes){var _true=Prototype.emptyFunction;for(var i=0,node;node=nodes[i];i++) node._countedByPrototype=_true;return nodes;},unmark:(function(){var PROPERTIES_ATTRIBUTES_MAP=(function(){var el=document.createElement('div'),isBuggy=false,propName='_countedByPrototype',value='x' el[propName]=value;isBuggy=(el.getAttribute(propName)===value);el=null;return isBuggy;})();return PROPERTIES_ATTRIBUTES_MAP?function(nodes){for(var i=0,node;node=nodes[i];i++) node.removeAttribute('_countedByPrototype');return nodes;}:function(nodes){for(var i=0,node;node=nodes[i];i++) node._countedByPrototype=void 0;return nodes;}})(),index:function(parentNode,reverse,ofType){parentNode._countedByPrototype=Prototype.emptyFunction;if(reverse){for(var nodes=parentNode.childNodes,i=nodes.length-1,j=1;i>=0;i--){var node=nodes[i];if(node.nodeType==1&&(!ofType||node._countedByPrototype))node.nodeIndex=j++;}}else{for(var i=0,j=1,nodes=parentNode.childNodes;node=nodes[i];i++) if(node.nodeType==1&&(!ofType||node._countedByPrototype))node.nodeIndex=j++;}},unique:function(nodes){if(nodes.length==0)return nodes;var results=[],n;for(var i=0,l=nodes.length;i0?[b]:[];return $R(1,total).inject([],function(memo,i){if(0==(i-b)%a&&(i-b)/a>=0)memo.push(i);return memo;});},nth:function(nodes,formula,root,reverse,ofType){if(nodes.length==0)return[] ;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(nodes);for(var i=0,node;node=nodes[i];i++){if(!node.parentNode._countedByPrototype){h.index(node.parentNode,reverse,ofType);indexed.push(node.parentNode);}} if(formula.match(/^\d+$/)){formula=Number(formula);for(var i=0,node;node=nodes[i];i++) if(node.nodeIndex==formula)results.push(node);}else if(m=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(m[1]=="-")m[1]=-1;var a=m[1]?Number(m[1]):1;var b=m[2]?Number(m[2]):0;var indices=Selector.pseudos.getIndices(a,b,nodes.length);for(var i=0,node,l=indices.length;node=nodes[i];i++){for(var j=0;j+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){expressions.push(m[1].strip());});return expressions;},matchElements:function(elements,expression){var matches=$$(expression),h=Selector.handlers;h.mark(matches);for(var i=0,results=[],element;element=elements[i];i++) if(element._countedByPrototype)results.push(element);h.unmark(matches);return results;},findElement:function(elements,expression,index){if(Object.isNumber(expression)){index=expression;expression=false;} return Selector.matchElements(elements,expression||'*')[index||0];},findChildElements:function(element,expressions){expressions=Selector.split(expressions.join(','));var results=[],h=Selector.handlers;for(var i=0,l=expressions.length,selector;i1)?h.unique(results):results;}});if(Prototype.Browser.IE){Object.extend(Selector.handlers,{concat:function(a,b){for(var i=0,node;node=b[i];i++) if(node.tagName!=="!")a.push(node);return a;}});} function $$(){return Selector.findChildElements(document,$A(arguments));} var Form={reset:function(form){form=$(form);form.reset();return form;},serializeElements:function(elements,options){if(typeof options!='object')options={hash:!!options};else if(Object.isUndefined(options.hash))options.hash=true;var key,value,submitted=false,submit=options.submit;var data=elements.inject({},function(result,element){if(!element.disabled&&element.name){key=element.name;value=$(element).getValue();if(value!=null&&element.type!='file'&&(element.type!='submit'||(!submitted&&submit!==false&&(!submit||key==submit)&&(submitted=true)))){if(key in result){if(!Object.isArray(result[key]))result[key]=[result[key]];result[key].push(value);} else result[key]=value;}} return result;});return options.hash?data:Object.toQueryString(data);}};Form.Methods={serialize:function(form,options){return Form.serializeElements(Form.getElements(form),options);},getElements:function(form){var elements=$(form).getElementsByTagName('*'),element,arr=[],serializers=Form.Element.Serializers;for(var i=0;element=elements[i];i++){arr.push(element);} return arr.inject([],function(elements,child){if(serializers[child.tagName.toLowerCase()]) elements.push(Element.extend(child));return elements;})},getInputs:function(form,typeName,name){form=$(form);var inputs=form.getElementsByTagName('input');if(!typeName&&!name)return $A(inputs).map(Element.extend);for(var i=0,matchingInputs=[],length=inputs.length;i=0;}).sortBy(function(element){return element.tabIndex}).first();return firstByIndex?firstByIndex:elements.find(function(element){return/^(?:input|select|textarea)$/i.test(element.tagName);});},focusFirstElement:function(form){form=$(form);form.findFirstElement().activate();return form;},request:function(form,options){form=$(form),options=Object.clone(options||{});var params=options.parameters,action=form.readAttribute('action')||'';if(action.blank())action=window.location.href;options.parameters=form.serialize(true);if(params){if(Object.isString(params))para ms=params.toQueryParams();Object.extend(options.parameters,params);} if(form.hasAttribute('method')&&!options.method) options.method=form.method;return new Ajax.Request(action,options);}};Form.Element={focus:function(element){$(element).focus();return element;},select:function(element){$(element).select();return element;}};Form.Element.Methods={serialize:function(element){element=$(element);if(!element.disabled&&element.name){var value=element.getValue();if(value!=undefined){var pair={};pair[element.name]=value;return Object.toQueryString(pair);}} return'';},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](element);},setValue:function(element,value){element=$(element);var method=element.tagName.toLowerCase();Form.Element.Serializers[method](element,value);return element;},clear:function(element){$(element).value='';return element;},present:function(element){return $(element).value!='';},activate:function(element){element=$(element);try{element.focus();if(element.select&&(element.tagName.toLowerCase()!='input'||!(/^(?:button|reset|submit)$/i.test(element.type)))) element.select();}catch(e){} return element;},disable:function(element){element=$(element);element.disabled=true;return element;},enable:function(element){element=$(element);element.disabled=false;return element;}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(element,value){switch(element.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(element,value);default:return Form.Element.Serializers.textarea(element,value);}},inputSelector:function(element,value){if(Object.isUndefined(value))return element.checked?element.value:null;else element.checked=!!value;},textarea:function(element,value){if(Object.isUndefined(value))return element.value;else element.value=value;},select:function(element,value){if(Object.isUndefined(value)) return this[element.type=='select-one'?'selectOne':'selectMany'](element);else{var opt,currentValue,single=!Object.isArray(value);for(var i=0,length=element.length;i=0?this.optionValue(element.options[index]):null;},selectMany:function(element){var values,length=element.length;if(!length)return null;for(var i=0,values=[];i=this.offset[1]&&y=this.offset[0]&&x=this.offset[1]&&this.ycomp=this.offset[0]&&this.xcomp0;})._each(iterator);},set:function(className){this.element.className=className;},add:function(classNameToAdd){if(this.include(classNameToAdd))return;this.set($A(this).concat(classNameToAdd).join(' '));},remove:function(classNameToRemove){if(!this.include(classNameToRemove))return;this.set($A(this).without(classNameToRemove).join(' '));},toString:function(){return $A(this).join(' ');}};Object.extend(Element.ClassNames.prototype,Enumerable);GlkOte=function(){var game_interface=null;var windowport_id='windowport';var gameport_id='gameport';var generation=0;var disabled=false;var loading_visible=null;var windowdic=null;var current_metrics=null; var currently_focussed=false;var last_known_focus=0;var last_known_paging=0;var windows_paging_count=0;var resize_timer=null;var retry_timer=null;var is_ie7=false;var perform_paging=true;var detect_external_links=false;var regex_external_links=null;var NBSP="\xa0";var max_buffer_length=200;var terminator_key_names={escape:Event.KEY_ESC,func1:112,func2:113,func3:114,func4:115,func5:116,func6:117,func7:118,func8:119,func9:120,func10:121,func11:122,func12:123};var terminator_key_values={};function glkote_init(iface){if(!iface&&window.Game) iface=window.Game;if(!iface){glkote_error('No game interface object has been provided.');return;} if(!iface.accept){glkote_error('The game interface object must have an accept() function.');return;} game_interface=iface;if(!window.Prototype){glkote_error('The Prototype library has not been loaded.');return;} var version=Prototype.Version.split('.');if(version.length<2||(version[0]==1&&version[1]<6)){glkote_error('This version of the Prototype library is too old. (Version '+Prototype.Version+' found; 1.6.0 required.)');return;} for(var val in terminator_key_names){terminator_key_values[terminator_key_names[val]]=val;} if(Prototype.Browser.MobileSafari){perform_paging=false;} if(Prototype.Browser.IE){is_ie7=window.XMLHttpRequest!=null;} windowdic=new Hash();if(iface.windowport) windowport_id=iface.windowport;if(iface.gameport) gameport_id=iface.gameport;var el=$(windowport_id);if(!el){glkote_error('Cannot find windowport element #'+windowport_id+' in this document.');return;} el.update();if(!Prototype.Browser.MobileSafari) Event.observe(document,'keypress',evhan_doc_keypress);Event.observe(window,'resize',evhan_doc_resize);var res=measure_window();if(Object.isString(res)){glkote_error(res);return;} current_metrics=res;detect_external_links=iface.detect_external_links;if(detect_external_links){regex_external_links=iface.regex_external_links;if(!regex_external_links){if(detect_external_links=='search'){regex_external_links=RegExp('\\b((?:https?://)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?\u00ab\u00bb\u201c\u201d\u2018\u2019]))','i');} else{regex_external_links=RegExp('^https?:','i');}}} send_response('init',null,current_metrics);} function measure_window(){var metrics={};var el,linesize,winsize,line1size,line2size,spansize;el=$(gameport_id);if(!el) return'Cannot find gameport element #'+gameport_id+' in this document.';var portsize=el.getDimensions();metrics.width=portsize.width;metrics.height=portsize.height;el=$('layouttest_grid');if(!el) return'Cannot find layouttest_grid element for window measurement.';winsize=el.getDimensions();spansize=$('layouttest_gridspan').getDimensions();line1size=$('layouttest_gridline').getDimensions();line2size=$('layouttest_gridline2').getDimensions();metrics.gridcharheight=($('layouttest_gridline2').positionedOffset().top -$('layouttest_gridline').positionedOffset().top);metrics.gridcharwidth=(spansize.width/8);metrics.gridmarginx=winsize.width-spansize.width;metrics.gridmarginy=winsize.height-(line1size.height+line2size.height);el=$('layouttest_buffer');if(!el) return'Cannot find layouttest_grid element for window measurement.';winsize=el.getDimensions();spansize=$('layouttest_bufferspan').getDimensions();line1size=$('layouttest_bufferline').getDimensions();line2size=$('layouttest_bufferline2').getDimensions();metrics.buffercharheight=($('layouttest_bufferline2').positionedOffset().top -$('layouttest_bufferline').positionedOffset().top);metrics.buffercharwidth=(spansize.width/8);metrics.buffermarginx=winsize.width-spansize.width;metrics.buffermarginy=winsize.height-(line1size.height+line2size.height);metrics.outspacingx=0;metrics.outspacingy=0;metrics.inspacingx=0;metrics.inspacingy=0;if(game_interface.spacing!=undefined){metrics.outspacingx=game_interface.spacing;metrics.outspacingy=game_interface.spacing;metrics.inspacingx=game_interface.spacing;metrics.inspacingy=game_interface.spacing;} if(game_interface.outspacing!=undefined){metrics.outspacingx=game_interface.outspacing;metrics.outspacingy=game_interface.outspacing;} if(game_interface.inspacing!=undefined){metrics.inspacingx=game_interface.inspacing;metrics.inspacingy=game_interface.inspacing;} if(game_interface.inspacingx!=undefined) metrics.inspacingx=game_interface.inspacingx;if(game_interface.inspacingy!=undefined) metrics.inspacingy=game_interface.inspacingy;if(game_interface.outspacingx!=undefined) metrics.outspacingx=game_interface.outspacingx;if(game_interface.outspacingy!=undefined) metrics.outspacingy=game_interface.outspacingy;return metrics;} function glkote_update(arg){hide_loading();if(arg.type=='error'){glkote_error(arg.message);return;} if(arg.type=='pass'){return;} if(arg.type=='retry'){if(!retry_timer){glkote_log('Event has timed out; will retry...');show_loading();retry_timer=retry_update.delay(2);} else{glkote_log('Event has timed out, but a retry is already queued!');} return;} if(arg.type!='update'){glkote_log('Ignoring unknown message type '+arg.type+'.');return;} if(arg.gen==generation){glkote_log('Ignoring repeated generation number: '+generation);return;} if(arg.genrealbottom) newtopunseen=realbottom;if(win.topunseen=frameel.scrollHeight){win.needspaging=false;} else{win.needspaging=true;}} var moreel=$('win'+win.id+'_moreprompt');if(!win.needspaging){if(moreel) moreel.remove();} else{if(!moreel){moreel=new Element('div',{id:'win'+win.id+'_moreprompt','class':'MorePrompt'});insert_text(moreel,'More');var morex=win.coords.right+20;var morey=win.coords.bottom;moreel.setStyle({bottom:morey+'px',right:morex+'px'});$(windowport_id).insert(moreel);}}}}});readjust_paging_focus(false);disabled=false;if(arg.disable||arg.specialinput){disabled=true;windowdic.values().each(function(win){if(win.inputel){win.inputel.disabled=true;}});} var newinputwin=0;if(!disabled&&!windows_paging_count){windowdic.values().each(function(win){if(win.input){if(!newinputwin||win.id==last_known_focus) newinputwin=win.id;}});} if(newinputwin){var focusfunc=function(){var win=windowdic.get(newinputwin);if(win.inputel){win.inputel.focus();}};focusfunc.defer();}} function accept_windowset(arg){windowdic.values().each(function(win){win.inplace=false;});arg.map(accept_one_window);var closewins=windowdic.values().reject(function(win){return win.inplace;});closewins.map(close_one_window);} function accept_one_window(arg){var frameel,win;if(!arg){return;} win=windowdic.get(arg.id);if(win==null){win={id:arg.id,type:arg.type,rock:arg.rock};windowdic.set(arg.id,win);var typeclass;if(win.type=='grid') typeclass='GridWindow';if(win.type=='buffer') typeclass='BufferWindow';var rockclass='WindowRock_'+arg.rock;frameel=new Element('div',{id:'window'+arg.id,'class':'WindowFrame '+typeclass+' '+rockclass});frameel.winid=arg.id;Event.observe(frameel,'mousedown',function(ev){evhan_window_mousedown(ev,frameel);});if(perform_paging&&win.type=='buffer') frameel.onscroll=function(){evhan_window_scroll(frameel);};win.frameel=frameel;win.gridheight=0;win.gridwidth=0;win.input=null;win.inputel=null;win.terminators={};win.reqhyperlink=false;win.needscroll=false;win.needspaging=false;win.topunseen=0;win.coords={left:null,top:null,right:null,bottom:null};win.history=new Array();win.historypos=0;$(windowport_id).insert(frameel);} else{frameel=win.frameel;if(win.type!=arg.type) glkote_error('Window '+arg.id+' was created with type '+win.type+', but now is described as type '+arg.type);} win.inplace=true;if(win.type=='grid'){var ix;if(arg.gridheight>win.gridheight){for(ix=win.gridheight;ix0){var ix,obj;win.topunseen-=parals[totrim].offsetTop;if(win.topunseen<0) win.topunseen=0;for(ix=0;ixwin.input.gen){win.input=null;if(win.inputel){win.inputel.remove();win.inputel=null;}}}});} function accept_inputset(arg){var hasinput=new Hash();var hashyperlink=new Hash();arg.map(function(argi){if(argi.type) hasinput.set(argi.id,argi);if(argi.hyperlink) hashyperlink.set(argi.id,true);});windowdic.values().each(function(win){win.reqhyperlink=hashyperlink.get(win.id);var argi=hasinput.get(win.id);if(argi==null) return;win.input=argi;var maxlen=1;if(argi.type=='line') maxlen=argi.maxlen;var inputel=win.inputel;if(inputel==null){var classes='Input';if(argi.type=='line'){classes+=' LineInput';} else if(argi.type=='char'){classes+=' CharInput';} else{glkote_error('Window '+win.id+' has requested unrecognized input type '+argi.type+'.');} inputel=new Element('input',{id:'win'+win.id+'_input','class':classes,type:'text',maxlength:maxlen});if(Prototype.Browser.MobileSafari) inputel.writeAttribute('autocapitalize','off');if(argi.type=='line'){inputel.onkeypress=evhan_input_keypress;inputel.onkeydown=evhan_input_keydown;if(argi.initial) inputel.value=argi.initial;win.terminators={};if(argi.terminators){for(var ix=0;ixmaxwidth) width=maxwidth;inputel.setStyle({position:'absolute',left:xpos+'px',top:pos.top+'px',width:width+'px'});win.frameel.insert(inputel);} if(win.type=='buffer'){var cursel=$('win'+win.id+'_cursor');if(!cursel){cursel=new Element('span',{id:'win'+win.id+'_cursor','class':'InvisibleCursor'});insert_text(cursel,NBSP);win.frameel.insert(cursel);} var pos=cursel.positionedOffset();var width=win.frameel.getWidth()-(current_metrics.buffermarginx+pos.left+2);if(width<1) width=1;if(Prototype.Browser.Opera){inputel.setStyle({position:'relative',left:'0px',top:'0px',width:width+'px'});cursel.insert({top:inputel});} else{inputel.setStyle({position:'absolute',left:'0px',top:'0px',width:width+'px'});cursel.insert(inputel);}}});} function accept_specialinput(arg){if(arg.type=='fileref_prompt'){var replyfunc=function(ref){send_response('specialresponse',null,'fileref_prompt',ref);};try{var writable=(arg.filemode!='read');Dialog.open(writable,arg.filetype,arg.gameid,replyfunc);} catch(ex){GlkOte.log('Unable to open file dialog: '+ex);replyfunc.defer(null);}} else{glkote_error('Request for unknown special input type: '+arg.type);}} function last_line_top_offset(el){var ls=el.childElements();if(ls.length==0) return 0;return ls[ls.length-1].offsetTop;} function readjust_paging_focus(canfocus){windows_paging_count=0;var pageable_win=0;if(perform_paging){windowdic.values().each(function(win){if(win.needspaging){windows_paging_count+=1;if(!pageable_win||win.id==last_known_paging) pageable_win=win.id;}});} if(windows_paging_count){last_known_paging=pageable_win;} if(!windows_paging_count&&canfocus){var newinputwin=0;if(!disabled&&!windows_paging_count){windowdic.values().each(function(win){if(win.input){if(!newinputwin||win.id==last_known_focus) newinputwin=win.id;}});} if(newinputwin){var win=windowdic.get(newinputwin);if(win.inputel){win.inputel.focus();}}}} function glkote_get_interface(){return game_interface;} function glkote_log(msg){if(window.console&&console.log) console.log(msg);else if(window.opera&&opera.postError) opera.postError(msg);} function glkote_error(msg){var el=document.getElementById('errorcontent');remove_children(el);insert_text(el,msg);el=document.getElementById('errorpane');el.style.display='';hide_loading();} function glkote_extevent(val){send_response('external',null,val);} function retry_update(){retry_timer=null;glkote_log('Retrying update...');send_response('refresh',null,null);} function clear_error(){$('errorpane').hide();} function hide_loading(){if(loading_visible==false) return;loading_visible=false;var el=document.getElementById('loadingpane');if(el){el.style.display='none';}} function show_loading(){if(loading_visible==true) return;loading_visible=true;var el=document.getElementById('loadingpane');if(el){el.style.display='';}} function insert_text(el,val){var nod=document.createTextNode(val);el.appendChild(nod);} function remove_children(parent){var obj,ls;ls=parent.childNodes;while(ls.length>0){obj=ls.item(0);parent.removeChild(obj);}} function last_child_of(obj){var ls=obj.childElements();if(!ls||!ls.length) return null;return ls[ls.length-1];} function insert_text_detecting(el,val){if(!detect_external_links){var nod=document.createTextNode(val);el.appendChild(nod);return;} if(detect_external_links=='match'){if(regex_external_links.test(val)){var ael=new Element('a',{'href':val,'class':'External','target':'_blank'});var nod=document.createTextNode(val);ael.appendChild(nod);el.insert(ael);return;}} else if(detect_external_links=='search'){while(true){var match=regex_external_links.exec(val);if(!match) break;if(match.index>0){var prefix=val.substring(0,match.index);var nod=document.createTextNode(prefix);el.appendChild(nod);} var ael=new Element('a',{'href':match[0],'class':'External','target':'_blank'});var nod=document.createTextNode(match[0]);ael.appendChild(nod);el.insert(ael);val=val.substring(match.index+match[0].length);} if(!val.length) return;} var nod=document.createTextNode(val);el.appendChild(nod);} function inspect_method(){var keys=Object.keys(this);keys.sort();var els=keys.map(function(key){var val=this[key];if(val==inspect_method) val='[...]';return key+':'+val;},this);return'{'+els.join(', ')+'}';} function inspect_deep(res){var keys=Object.keys(res);keys.sort();var els=keys.map(function(key){var val=res[key];if(Object.isString(val)) val="'"+val+"'";else if(!Object.isNumber(val)) val=inspect_deep(val);return key+':'+val;},res);return'{'+els.join(', ')+'}';} function submit_line_input(win,inputel,termkey){var val=inputel.value;if(val&&val!=win.history.last()){win.history.push(val);if(win.history.length>20){win.history.shift();}} send_response('line',win,val,termkey);} function send_response(type,win,val,val2){if(disabled&&type!='specialresponse') return;var winid=0;if(win) winid=win.id;var res={type:type,gen:generation};if(type=='line'){res.window=win.id;res.value=val;if(val2) res.terminator=val2;} else if(type=='char'){res.window=win.id;res.value=val;} else if(type=='hyperlink'){res.window=win.id;res.value=val;} else if(type=='external'){res.value=val;} else if(type=='specialresponse'){res.response=val;res.value=val2;} else if(type=='init'||type=='arrange'){res.metrics=val;} if(!(type=='init'||type=='refresh'||type=='specialresponse')){windowdic.values().each(function(win){var savepartial=(type!='line'&&type!='char')||(win.id!=winid);if(savepartial&&win.input&&win.input.type=='line'&&win.inputel&&win.inputel.value){var partial=res.partial;if(!partial){partial={};res.partial=partial;};partial[win.id]=win.inputel.value;}});} game_interface.accept(res);} function evhan_doc_resize(ev){if(resize_timer!=null){window.clearTimeout(resize_timer);resize_timer=null;} resize_timer=doc_resize_real.delay(0.5);} function doc_resize_real(){resize_timer=null;if(disabled){resize_timer=doc_resize_real.delay(0.5);return;} current_metrics=measure_window();send_response('arrange',null,current_metrics);} function evhan_doc_keypress(ev){if(disabled){return;} var keycode=0;if(Prototype.Browser.IE){ev=Event.extend(window.event);if(ev)keycode=ev.keyCode;} else{if(ev)keycode=ev.which;} if(ev.target.tagName.toUpperCase()=='INPUT'){return;} if(ev.altKey||ev.metaKey||ev.ctrlKey){return;} if(Prototype.Browser.Opera){if(!keycode) return;if(keycode<32&&keycode!=13) return;} var win;if(windows_paging_count){win=windowdic.get(last_known_paging);if(win){if(!((keycode>=32&&keycode<=126)||keycode==13)){return;} ev.preventDefault();var frameel=win.frameel;frameel.scrollTop=win.topunseen-current_metrics.buffercharheight;var frameheight=frameel.getHeight();var realbottom=last_line_top_offset(frameel);var newtopunseen=frameel.scrollTop+frameheight;if(newtopunseen>realbottom) newtopunseen=realbottom;if(win.topunseen=frameel.scrollHeight){win.needspaging=false;var moreel=$('win'+win.id+'_moreprompt');if(moreel) moreel.remove();readjust_paging_focus(true);}} return;}} win=windowdic.get(last_known_focus);if(!win) return;if(!win.inputel) return;win.inputel.focus();if(win.input.type=='line'){if(keycode==13){submit_line_input(win,win.inputel,null);ev.preventDefault();return;} if(keycode){if(keycode>=32){var val=String.fromCharCode(keycode);win.inputel.value=win.inputel.value+val;} ev.preventDefault();return;}} else{var res=null;if(keycode==13) res='return';else if(keycode==Event.KEY_BACKSPACE) res='delete';else if(keycode) res=String.fromCharCode(keycode);if(res){send_response('char',win,res);} ev.preventDefault();return;}} function evhan_window_mousedown(ev,frameel){if(!frameel.winid) return;var win=windowdic.get(frameel.winid);if(!win) return;if(win.inputel){last_known_focus=win.id;if(Prototype.Browser.MobileSafari){ev.stop();win.inputel.focus();}} if(win.needspaging) last_known_paging=win.id;else if(win.inputel) last_known_paging=0;} function evhan_input_char_keydown(ev){var keycode=0;if(!ev){ev=Event.extend(window.event);} if(ev)keycode=ev.keyCode;if(!keycode)return true;var res=null;switch(keycode){case Event.KEY_LEFT:res='left';break;case Event.KEY_RIGHT:res='right';break;case Event.KEY_UP:res='up';break;case Event.KEY_DOWN:res='down';break;case Event.KEY_BACKSPACE:res='delete';break;case Event.KEY_ESC:res='escape';break;case Event.KEY_TAB:res='tab';break;case Event.KEY_PAGEUP:res='pageup';break;case Event.KEY_PAGEDOWN:res='pagedown';break;case Event.KEY_HOME:res='home';break;case Event.KEY_END:res='end';break;case 112:res='func1';break;case 113:res='func2';break;case 114:res='func3';break;case 115:res='func4';break;case 116:res='func5';break;case 117:res='func6';break;case 118:res='func7';break;case 119:res='func8';break;case 120:res='func9';break;case 121:res='func10';break;case 122:res='func11';break;case 123:res='func12';break;} if(res){if(!this.winid) return true;var win=windowdic.get(this.winid);if(!win||!win.input) return true;send_response('char',win,res);return false;} return true;} function evhan_input_char_keypress(ev){var keycode=0;if(!ev){ev=Event.extend(window.event);if(ev)keycode=ev.keyCode;} else{if(ev)keycode=ev.which;} if(!keycode)return false;if(keycode==10&&Prototype.Browser.MobileSafari){keycode=13;} var res;if(keycode==13) res='return';else res=String.fromCharCode(keycode);if(!this.winid) return true;var win=windowdic.get(this.winid);if(!win||!win.input) return true;send_response('char',win,res);return false;} function evhan_input_keydown(ev){var keycode=0;if(!ev){ev=Event.extend(window.event);} if(ev)keycode=ev.keyCode;if(!keycode)return true;if(keycode==Event.KEY_UP||keycode==Event.KEY_DOWN){if(!this.winid) return true;var win=windowdic.get(this.winid);if(!win||!win.input) return true;if(keycode==Event.KEY_UP&&win.historypos>0){win.historypos-=1;if(win.historyposrealbottom) newtopunseen=realbottom;if(win.topunseen=frameel.scrollHeight){win.needspaging=false;var moreel=$('win'+win.id+'_moreprompt');if(moreel) moreel.remove();readjust_paging_focus(true);return;}} function build_evhan_hyperlink(winid,linkval){return function(){var win=windowdic.get(winid);if(!win) return false;if(!win.reqhyperlink) return false;send_response('hyperlink',win,linkval);return false;};} return{version:'1.3.1',init:glkote_init,update:glkote_update,extevent:glkote_extevent,getinterface:glkote_get_interface,log:glkote_log,error:glkote_error};}();Dialog=function(){var dialog_el_id='dialog';var is_open=false;var dialog_callback=null;var will_save;var confirming;var editing;var editing_dirent;var cur_usage;var cur_usage_name;var cur_gameid;var cur_filelist;function dialog_open(tosave,usage,gameid,callback){if(is_open) throw'Dialog: dialog box is already open.';if(localStorage==null) throw'Dialog: your browser does not support local storage.';dialog_callback=callback;will_save=tosave;confirming=false;editing=false;editing_dirent=null;cur_usage=usage;cur_gameid=gameid;cur_usage_name=label_for_usage(cur_usage);var root_el_id='windowport';var iface=window.Game;if(window.GlkOte) iface=window.GlkOte.getinterface();if(iface&&iface.windowport) root_el_id=iface.windowport;var rootel=$(root_el_id);if(!rootel) throw'Dialog: unable to find root element #'+root_el_id+'.';var screen=$(dialog_el_id+'_screen');if(!screen){screen=new Element('div',{id:dialog_el_id+'_screen'});rootel.insert(screen);} var frame=$(dialog_el_id+'_frame');if(!frame){frame=new Element('div',{id:dialog_el_id+'_frame'});rootel.insert(frame);} var dia=$(dialog_el_id);if(dia) dia.remove();dia=new Element('div',{id:dialog_el_id});var form,el,row;form=new Element('form');form.observe('submit',(will_save?evhan_accept_save_button:evhan_accept_load_button));dia.insert(form);row=new Element('div',{'class':'DiaButtonsFloat'});el=new Element('button',{id:dialog_el_id+'_edit',type:'button'});insert_text(el,'Edit');el.observe('click',evhan_edit_button);row.insert(el);form.insert(row);row=new Element('div',{id:dialog_el_id+'_cap','class':'DiaCaption'});insert_text(row,'XXX');form.insert(row);if(will_save){row=new Element('div',{id:dialog_el_id+'_input','class':'DiaInput'});form.insert(row);el=new Element('input',{id:dialog_el_id+'_infield',type:'text',name:'filename'});row.insert(el);} row=new Element('div',{id:dialog_el_id+'_body','class':'DiaBody'});form.insert(row);row=new Element('div',{id:dialog_el_id+'_cap2','class':'DiaCaption'});row.hide();form.insert(row);row=new Element('div',{id:dialog_el_id+'_buttonrow','class':'DiaButtons'});{el=new Element('button',{id:dialog_el_id+'_cancel',type:'button'});insert_text(el,'Cancel');el.observe('click',evhan_cancel_button);row.insert(el);el=new Element('button',{id:dialog_el_id+'_delete',type:'button'});insert_text(el,'Delete');el.observe('click',evhan_delete_button);el.hide();row.insert(el);el=new Element('button',{id:dialog_el_id+'_display',type:'button'});insert_text(el,'Display');el.observe('click',evhan_display_button);el.hide();row.insert(el);el=new Element('button',{id:dialog_el_id+'_accept',type:'submit'});insert_text(el,(will_save?'Save':'Load'));el.observe('click',(will_save?evhan_accept_save_button:evhan_accept_load_button));row.insert(el);} form.insert(row);frame.insert(dia);is_open=true;evhan_storage_changed();var focusfunc;if(will_save){focusfunc=function(){var el=$(dialog_el_id+'_infield');if(el) el.focus();};} else{focusfunc=function(){var el=$(dialog_el_id+'_select');if(el) el.focus();};} focusfunc.defer();} function dialog_close(){var dia=$(dialog_el_id);if(dia) dia.remove();var frame=$(dialog_el_id+'_frame');if(frame) frame.remove();var screen=$(dialog_el_id+'_screen');if(screen) screen.remove();is_open=false;dialog_callback=null;cur_filelist=null;editing=false;editing_dirent=null;} function set_caption(msg,isupper){var elid=(isupper?dialog_el_id+'_cap':dialog_el_id+'_cap2');var el=$(elid);if(!el) return;if(!msg){el.hide();} else{remove_children(el);insert_text(el,msg);el.show();}} function label_for_usage(val){switch(val){case'data':return'data file';case'save':return'save file';case'transcript':return'transcript';case'command':return'command script';default:return'file';}} function usage_is_textual(val){return(val=='transcript'||val=='command');} function insert_text(el,val){var nod=document.createTextNode(val);el.appendChild(nod);} function remove_children(parent){var obj,ls;ls=parent.childNodes;while(ls.length>0){obj=ls.item(0);parent.removeChild(obj);}} function replace_text(el,val){remove_children(el);insert_text(el,val);} function evhan_select_change(){if(!is_open) return false;if(confirming) return false;var selel=$(dialog_el_id+'_select');if(!selel) return false;var pos=selel.selectedIndex;if(!cur_filelist||pos<0||pos>=cur_filelist.length) return false;var file=cur_filelist[pos];var fel=$(dialog_el_id+'_infield');if(!fel) return false;fel.value=file.dirent.filename;return false;} function evhan_select_change_editing(){if(!is_open) return false;if(!editing||editing_dirent) return false;var selel=$(dialog_el_id+'_select');if(!selel) return false;var pos=selel.selectedIndex;if(!cur_filelist||pos<0||pos>=cur_filelist.length) return false;var file=cur_filelist[pos];if(!file.dirent||!file_ref_exists(file.dirent)) return false;butel=$(dialog_el_id+'_delete');butel.disabled=false;butel=$(dialog_el_id+'_display');butel.disabled=!usage_is_textual(file.dirent.usage);} function evhan_accept_load_button(ev){ev.stop();if(!is_open) return false;if(editing) return false;var selel=$(dialog_el_id+'_select');if(!selel) return false;var pos=selel.selectedIndex;if(!cur_filelist||pos<0||pos>=cur_filelist.length) return false;var file=cur_filelist[pos];if(!file.dirent||!file_ref_exists(file.dirent)) return false;var callback=dialog_callback;dialog_close();if(callback) callback(file.dirent);return false;} function evhan_accept_save_button(ev){ev.stop();if(!is_open) return false;if(editing) return false;var fel=$(dialog_el_id+'_infield');if(!fel) return false;var filename=fel.value;filename=filename.strip();if(!filename) return false;var dirent=file_construct_ref(filename,cur_usage,cur_gameid);if(file_ref_exists(dirent)&&!confirming){confirming=true;set_caption('You already have a '+cur_usage_name+' "' +dirent.filename+'". Do you want to replace it?',false);fel.disabled=true;var butel=$(dialog_el_id+'_accept');replace_text(butel,'Replace');return false;} var callback=dialog_callback;dialog_close();if(callback) callback(dirent);return false;} function evhan_edit_button(ev){ev.stop();if(!is_open) return false;if(!editing){editing=true;editing_dirent=null;if(confirming){confirming=false;set_caption(null,false);var fel=$(dialog_el_id+'_infield');fel.disabled=false;var butel=$(dialog_el_id+'_accept');butel.disabled=false;replace_text(butel,'Save');} var fel=$(dialog_el_id+'_input');if(fel){fel.hide();} var butel=$(dialog_el_id+'_edit');replace_text(butel,'Done');butel=$(dialog_el_id+'_delete');butel.show();butel=$(dialog_el_id+'_display');butel.show();butel=$(dialog_el_id+'_accept');butel.hide();evhan_storage_changed();return false;} else if(!editing_dirent){editing=false;editing_dirent=null;var fel=$(dialog_el_id+'_input');if(fel){fel.show();} var butel=$(dialog_el_id+'_edit');replace_text(butel,'Edit');butel=$(dialog_el_id+'_delete');butel.hide();butel=$(dialog_el_id+'_display');butel.hide();butel=$(dialog_el_id+'_accept');butel.show();evhan_storage_changed();return false;} else{editing=true;editing_dirent=null;$(dialog_el_id+'_buttonrow').show();var butel=$(dialog_el_id+'_edit');replace_text(butel,'Done');evhan_storage_changed();return false;}} function evhan_delete_button(ev){ev.stop();if(!is_open) return false;if(!editing||editing_dirent) return false;var selel=$(dialog_el_id+'_select');if(!selel) return false;var pos=selel.selectedIndex;if(!cur_filelist||pos<0||pos>=cur_filelist.length) return false;var file=cur_filelist[pos];if(!file.dirent) return false;file_remove_ref(file.dirent);evhan_storage_changed();return false;} function evhan_display_button(ev){ev.stop();if(!is_open) return false;if(!editing||editing_dirent) return false;var selel=$(dialog_el_id+'_select');if(!selel) return false;var pos=selel.selectedIndex;if(!cur_filelist||pos<0||pos>=cur_filelist.length) return false;var file=cur_filelist[pos];if(!file.dirent||!file_ref_exists(file.dirent)) return false;$(dialog_el_id+'_buttonrow').hide();var butel=$(dialog_el_id+'_edit');replace_text(butel,'Close');editing_dirent=file.dirent;evhan_storage_changed();return false;} function evhan_cancel_button(ev){ev.stop();if(!is_open) return false;if(confirming){confirming=false;set_caption(null,false);var fel=$(dialog_el_id+'_infield');fel.disabled=false;var butel=$(dialog_el_id+'_accept');butel.disabled=false;replace_text(butel,'Save');return false;} var callback=dialog_callback;dialog_close();if(callback) callback(null);return false;} function evhan_storage_changed(ev){if(!is_open) return false;var el,bodyel,ls,lastusage;var changedkey=null;if(ev) changedkey=ev.key;bodyel=$(dialog_el_id+'_body');if(!bodyel) return false;if(editing&&editing_dirent){if(!file_ref_exists(editing_dirent)){editing_dirent=null;$(dialog_el_id+'_buttonrow').show();var butel=$(dialog_el_id+'_edit');replace_text(butel,'Done');}} if(editing&&editing_dirent){remove_children(bodyel);var dat=file_read(editing_dirent);dat=String.fromCharCode.apply(this,dat);var textel=new Element('div',{'class':'DiaDisplayText'});var nod=document.createTextNode(dat);textel.appendChild(nod);bodyel.insert(textel);set_caption('Displaying file contents...',true);return false;} if(editing){ls=files_list(null,cur_gameid);if(cur_gameid!=''){ls=ls.concat(files_list(null,''));} ls.sort(function(f1,f2){if(f1.dirent.usage!=f2.dirent.usage) return(f1.dirent.usage=0){localStorage.keys=localStorage.keys.without(key);localStorage.length=localStorage.keys.length;delete localStorage.data[key];}},key:function(index){return localStorage.keys[index];},clear:function(){localStorage.data={};localStorage.keys=[];localStorage.length=0;}}} Event.observe(window,'storage',evhan_storage_changed);return{open:dialog_open,file_construct_ref:file_construct_ref,file_ref_exists:file_ref_exists,file_remove_ref:file_remove_ref,file_write:file_write,file_read:file_read};}();Glk=function(){var VM=null;var has_exited=false;var ui_disabled=false;var ui_specialinput=null;var ui_specialcallback=null;var event_generation=0;var current_partial_inputs=null;var current_partial_outputs=null;function init(vm_options){VM=vm_options.vm;if(window.GiDispa) GiDispa.set_vm(VM);vm_options.accept=accept_ui_event;GlkOte.init(vm_options);} function accept_ui_event(obj){var box;if(ui_disabled){qlog("### ui is disabled, ignoring event");return;} if(obj.gen!=event_generation){GlkOte.log('Input event had wrong generation number: got '+obj.gen+', currently at '+event_generation);return;} event_generation+=1;current_partial_inputs=obj.partial;switch(obj.type){case'init':content_metrics=obj.metrics;VM.init();break;case'external':if(obj.value=='timer'){handle_timer_input();} break;case'hyperlink':handle_hyperlink_input(obj.window,obj.value);break;case'char':handle_char_input(obj.window,obj.value);break;case'line':handle_line_input(obj.window,obj.value,obj.terminator);break;case'arrange':content_metrics=obj.metrics;box={left:content_metrics.outspacingx,top:content_metrics.outspacingy,right:content_metrics.width-content_metrics.outspacingx,bottom:content_metrics.height-content_metrics.outspacingy};if(gli_rootwin) gli_window_rearrange(gli_rootwin,box);handle_arrange_input();break;case'specialresponse':if(obj.response=='fileref_prompt'){gli_fileref_create_by_prompt_callback(obj);} break;}} function handle_arrange_input(){if(!gli_selectref) return;gli_selectref.set_field(0,Const.evtype_Arrange);gli_selectref.set_field(1,null);gli_selectref.set_field(2,0);gli_selectref.set_field(3,0);if(window.GiDispa) GiDispa.prepare_resume(gli_selectref);gli_selectref=null;VM.resume();} function handle_timer_input(){if(!gli_selectref) return;gli_selectref.set_field(0,Const.evtype_Timer);gli_selectref.set_field(1,null);gli_selectref.set_field(2,0);gli_selectref.set_field(3,0);if(window.GiDispa) GiDispa.prepare_resume(gli_selectref);gli_selectref=null;VM.resume();} function handle_hyperlink_input(disprock,val){if(!gli_selectref) return;var win=null;for(win=gli_windowlist;win;win=win.next){if(win.disprock==disprock) break;} if(!win||!win.hyperlink_request) return;gli_selectref.set_field(0,Const.evtype_Hyperlink);gli_selectref.set_field(1,win);gli_selectref.set_field(2,val);gli_selectref.set_field(3,0);win.hyperlink_request=false;if(window.GiDispa) GiDispa.prepare_resume(gli_selectref);gli_selectref=null;VM.resume();} function handle_char_input(disprock,input){var charval;if(!gli_selectref) return;var win=null;for(win=gli_windowlist;win;win=win.next){if(win.disprock==disprock) break;} if(!win||!win.char_request) return;if(input.length==1){charval=input.charCodeAt(0);if(!win.char_request_uni) charval=charval&0xFF;} else{charval=KeystrokeNameMap[input];if(!charval) charval=Const.keycode_Unknown;} gli_selectref.set_field(0,Const.evtype_CharInput);gli_selectref.set_field(1,win);gli_selectref.set_field(2,charval);gli_selectref.set_field(3,0);win.char_request=false;win.char_request_uni=false;win.input_generation=null;if(window.GiDispa) GiDispa.prepare_resume(gli_selectref);gli_selectref=null;VM.resume();} function handle_line_input(disprock,input,termkey){var ix;if(!gli_selectref) return;var win=null;for(win=gli_windowlist;win;win=win.next){if(win.disprock==disprock) break;} if(!win||!win.line_request) return;if(input.length>win.linebuf.length) input=input.slice(0,win.linebuf.length);if(win.request_echo_line_input){ix=win.style;gli_set_style(win.str,Const.style_Input);gli_window_put_string(win,input);if(win.echostr) glk_put_jstring_stream(win.echostr,input);gli_set_style(win.str,ix);gli_window_put_string(win,"\n");if(win.echostr) glk_put_jstring_stream(win.echostr,"\n");} for(ix=0;ix>10),0xDC00+(val&0x3FF));}} function TrimArrayToBytes(arr){var ix,newarr;var len=arr.length;for(ix=0;ix=0x100) break;} if(ix==len){return arr;} newarr=Array(len);for(ix=0;ix=0x100) break;} if(ix==len){return String.fromCharCode.apply(this,arr);} newarr=Array(len);for(ix=0;ix=0x10000) break;} if(ix==len){return String.fromCharCode.apply(this,arr);} newarr=Array(len);for(ix=0;ix>10),0xDC00+(val&0x3FF));}} return newarr.join('');} function qlog(msg){if(window.console&&console.log) console.log(msg);else if(window.opera&&opera.postError) opera.postError(msg);} function RefBox(){this.value=undefined;this.set_value=function(val){this.value=val;} this.get_value=function(){return this.value;}} function RefStruct(numels){this.fields=[];this.push_field=function(val){this.fields.push(val);} this.set_field=function(pos,val){this.fields[pos]=val;} this.get_field=function(pos){return this.fields[pos];} this.get_fields=function(){return this.fields;}} var DidNotReturn={dummy:'Glk call has not yet returned'};function call_may_not_return(id){if(id==0x001||id==0x0C0||id==0x062) return true;else return false;} var strtype_File=1;var strtype_Window=2;var strtype_Memory=3;var strtype_Resource=4;var gli_windowlist=null;var gli_rootwin=null;var geometry_changed=true;var content_metrics=null;var gli_streamlist=null;var gli_filereflist=null;var gli_schannellist=null;var gli_currentstr=null;var gli_selectref=null;var gli_api_display_rocks=1;var gli_timer_interval=null;var gli_timer_id=null;var gli_timer_started=null;function gli_new_window(type,rock){var win={};win.type=type;win.rock=rock;win.disprock=undefined;win.parent=null;win.str=gli_stream_open_window(win);win.echostr=null;win.style=Const.style_Normal;win.hyperlink=0;win.input_generation=null;win.linebuf=null;win.char_request=false;win.line_request=false;win.char_request_uni=false;win.line_request_uni=false;win.hyperlink_request=false;win.echo_line_input=true;win.line_input_terminators=[];win.request_echo_line_input=null;win.prev=null;win.next=gli_windowlist;gli_windowlist=win;if(win.next) win.next.prev=win;if(window.GiDispa) GiDispa.class_register('window',win);else win.disprock=gli_api_display_rocks++;geometry_changed=true;return win;} function gli_delete_window(win){var prev,next;if(window.GiDispa) GiDispa.class_unregister('window',win);geometry_changed=true;win.echostr=null;if(win.str){gli_delete_stream(win.str);win.str=null;} prev=win.prev;next=win.next;win.prev=null;win.next=null;if(prev) prev.next=next;else gli_windowlist=next;if(next) next.prev=prev;win.parent=null;win.rock=null;win.disprock=null;} function gli_windows_unechostream(str){var win;for(win=gli_windowlist;win;win=win.next){if(win.echostr===str) win.echostr=null;}} function gli_window_put_string(win,val){var ix,ch;switch(win.type){case Const.wintype_TextBuffer:if(win.style!=win.accumstyle||win.hyperlink!=win.accumhyperlink) gli_window_buffer_deaccumulate(win);win.accum.push(val);break;case Const.wintype_TextGrid:for(ix=0;ix=win.gridwidth){win.cursorx=0;win.cursory++;} if(win.cursory<0) win.cursory=0;else if(win.cursory>=win.gridheight) break;if(ch=="\n"){win.cursory++;win.cursorx=0;continue;} lineobj=win.lines[win.cursory];lineobj.dirty=true;lineobj.chars[win.cursorx]=ch;lineobj.styles[win.cursorx]=win.style;lineobj.hyperlinks[win.cursorx]=win.hyperlink;win.cursorx++;} break;}} function gli_window_grid_canonicalize(win){if(win.cursorx<0) win.cursorx=0;else if(win.cursorx>=win.gridwidth){win.cursorx=0;win.cursory++;} if(win.cursory<0) win.cursory=0;else if(win.cursory>=win.gridheight) return true;return false;} function gli_window_buffer_deaccumulate(win){var conta=win.content;var stylename=StyleNameMap[win.accumstyle];var text,ls,ix,obj,arr;if(win.accum.length){text=win.accum.join('');ls=text.split('\n');for(ix=0;ixwin.gridheight){win.lines.length=win.gridheight;} else if(oldheightwin.gridwidth){lineobj.dirty=true;lineobj.chars.length=win.gridwidth;lineobj.styles.length=win.gridwidth;lineobj.hyperlinks.length=win.gridwidth;} else if(oldwidth=max){split=min;} else{split=Math.min(Math.max(split,min),max-splitwid);} win.pair_splitpos=split;win.pair_splitwidth=splitwid;if(win.pair_vertical){box1={left:win.bbox.left,right:win.pair_splitpos,top:win.bbox.top,bottom:win.bbox.bottom};box2={left:box1.right+win.pair_splitwidth,right:win.bbox.right,top:win.bbox.top,bottom:win.bbox.bottom};} else{box1={top:win.bbox.top,bottom:win.pair_splitpos,left:win.bbox.left,right:win.bbox.right};box2={top:box1.bottom+win.pair_splitwidth,bottom:win.bbox.bottom,left:win.bbox.left,right:win.bbox.right};} if(!win.pair_backward){ch1=win.child1;ch2=win.child2;} else{ch1=win.child2;ch2=win.child1;} gli_window_rearrange(ch1,box1);gli_window_rearrange(ch2,box2);break;}} function gli_new_stream(type,readable,writable,rock){var str={};str.type=type;str.rock=rock;str.disprock=undefined;str.unicode=false;str.ref=null;str.win=null;str.file=null;str.buf=null;str.bufpos=0;str.buflen=0;str.bufeof=0;str.timer_id=null;str.flush_func=null;str.readcount=0;str.writecount=0;str.readable=readable;str.writable=writable;str.prev=null;str.next=gli_streamlist;gli_streamlist=str;if(str.next) str.next.prev=str;if(window.GiDispa) GiDispa.class_register('stream',str);return str;} function gli_delete_stream(str){var prev,next;if(str===gli_currentstr){gli_currentstr=null;} gli_windows_unechostream(str);if(str.type==strtype_Memory){if(window.GiDispa) GiDispa.unretain_array(str.buf);} if(window.GiDispa) GiDispa.class_unregister('stream',str);prev=str.prev;next=str.next;str.prev=null;str.next=null;if(prev) prev.next=next;else gli_streamlist=next;if(next) next.prev=prev;str.buf=null;str.readable=false;str.writable=false;str.ref=null;str.win=null;str.file=null;str.rock=null;str.disprock=null;} function gli_stream_open_window(win){var str;str=gli_new_stream(strtype_Window,false,true,0);str.unicode=true;str.win=win;return str;} function gli_stream_dirty_file(str){if(str.timer_id===null){if(str.flush_func===null){str.flush_func=function(){gli_stream_flush_file(str);};} str.timer_id=setTimeout(str.flush_func,10000);}} function gli_stream_flush_file(str){str.timer_id=null;Dialog.file_write(str.ref,str.buf);} function gli_new_fileref(filename,usage,rock,ref){var fref={};fref.filename=filename;fref.rock=rock;fref.disprock=undefined;fref.textmode=((usage&Const.fileusage_TextMode)!=0);fref.filetype=(usage&Const.fileusage_TypeMask);fref.filetypename=FileTypeMap[fref.filetype];if(!fref.filetypename){fref.filetypename='xxx';} if(!ref){var gameid='';if(fref.filetype==Const.fileusage_SavedGame) gameid=VM.get_signature();ref=Dialog.file_construct_ref(fref.filename,fref.filetypename,gameid);} fref.ref=ref;fref.prev=null;fref.next=gli_filereflist;gli_filereflist=fref;if(fref.next) fref.next.prev=fref;if(window.GiDispa) GiDispa.class_register('fileref',fref);return fref;} function gli_delete_fileref(fref){var prev,next;if(window.GiDispa) GiDispa.class_unregister('fileref',fref);prev=fref.prev;next=fref.next;fref.prev=null;fref.next=null;if(prev) prev.next=next;else gli_filereflist=next;if(next) next.prev=prev;fref.filename=null;fref.ref=null;fref.rock=null;fref.disprock=null;} function gli_put_char(str,ch){if(!str||!str.writable) throw('gli_put_char: invalid stream');if(!str.unicode) ch=ch&0xFF;str.writecount+=1;switch(str.type){case strtype_File:gli_stream_dirty_file(str);case strtype_Memory:if(str.bufposstr.bufeof) str.bufeof=str.bufpos;} break;case strtype_Window:if(str.win.line_request) throw('gli_put_char: window has pending line request');gli_window_put_string(str.win,CharToString(ch));if(str.win.echostr) gli_put_char(str.win.echostr,ch);break;}} function gli_put_array(str,arr,allbytes){var ix,len,val;if(!str||!str.writable) throw('gli_put_array: invalid stream');if(!str.unicode&&!allbytes){arr=TrimArrayToBytes(arr);allbytes=true;} str.writecount+=arr.length;switch(str.type){case strtype_File:gli_stream_dirty_file(str);case strtype_Memory:len=arr.length;if(len>str.buflen-str.bufpos) len=str.buflen-str.bufpos;for(ix=0;ixstr.bufeof) str.bufeof=str.bufpos;break;case strtype_Window:if(str.win.line_request) throw('gli_put_array: window has pending line request');if(allbytes) val=String.fromCharCode.apply(this,arr);else val=UniArrayToString(arr);gli_window_put_string(str.win,val);if(str.win.echostr) gli_put_array(str.win.echostr,arr,allbytes);break;}} function gli_get_char(str,want_unicode){var ch;if(!str||!str.readable) return-1;switch(str.type){case strtype_Resource:if(str.unicode){if(str.isbinary){if(str.bufpos>=str.bufeof) return-1;ch=str.buf[str.bufpos];str.bufpos++;if(str.bufpos>=str.bufeof) return-1;ch=(ch<<8)|(str.buf[str.bufpos]&0xFF);str.bufpos++;if(str.bufpos>=str.bufeof) return-1;ch=(ch<<8)|(str.buf[str.bufpos]&0xFF);str.bufpos++;if(str.bufpos>=str.bufeof) return-1;ch=(ch<<8)|(str.buf[str.bufpos]&0xFF);str.bufpos++;} else{var val0,val1,val2,val3;if(str.bufpos>=str.bufeof) return-1;val0=str.buf[str.bufpos];str.bufpos++;if(val0<0x80){ch=val0;} else{if(str.bufpos>=str.bufeof) return-1;val1=str.buf[str.bufpos];str.bufpos++;if((val1&0xC0)!=0x80) return-1;if((val0&0xE0)==0xC0){ch=(val0&0x1F)<<6;ch|=(val1&0x3F);} else{if(str.bufpos>=str.bufeof) return-1;val2=str.buf[str.bufpos];str.bufpos++;if((val2&0xC0)!=0x80) return-1;if((val0&0xF0)==0xE0){ch=(((val0&0xF)<<12)&0x0000F000);ch|=(((val1&0x3F)<<6)&0x00000FC0);ch|=(((val2&0x3F))&0x0000003F);} else if((val0&0xF0)==0xF0){if(str.bufpos>=str.bufeof) return-1;val3=str.buf[str.bufpos];str.bufpos++;if((val3&0xC0)!=0x80) return-1;ch=(((val0&0x7)<<18)&0x1C0000);ch|=(((val1&0x3F)<<12)&0x03F000);ch|=(((val2&0x3F)<<6)&0x000FC0);ch|=(((val3&0x3F))&0x00003F);} else{return-1;}}}} str.readcount++;ch>>>=0;if(!want_unicode&&ch>=0x100) return 63;return ch;} case strtype_File:case strtype_Memory:if(str.bufpos=0x100) return 63;return ch;} else{return-1;} default:return-1;}} function gli_get_line(str,buf,want_unicode){if(!str||!str.readable) return 0;var len=buf.length;var gotnewline;switch(str.type){case strtype_Resource:if(str.unicode){if(len==0) return 0;len-=1;gotnewline=false;for(lx=0;lx=str.bufeof){len=0;} else{if(str.bufpos+len>str.bufeof){len=str.bufeof-str.bufpos;}} gotnewline=false;if(!want_unicode){for(lx=0;lx=0x100) ch=63;buf[lx]=ch;gotnewline=(ch==10);}} else{for(lx=0;lx=str.bufeof){len=0;} else{if(str.bufpos+len>str.bufeof){len=str.bufeof-str.bufpos;}} if(!want_unicode){for(lx=0;lx=0x100) ch=63;buf[lx]=ch;}} else{for(lx=0;lxstr.buflen-str.bufpos) len=str.buflen-str.bufpos;if(str.unicode||allbytes){for(ix=0;ixstr.bufeof) str.bufeof=str.bufpos;break;case strtype_Window:if(str.win.line_request) throw('glk_put_jstring: window has pending line request');gli_window_put_string(str.win,val);if(str.win.echostr) glk_put_jstring_stream(str.win.echostr,val,allbytes);break;}} function gli_set_style(str,val){if(!str||!str.writable) throw('gli_set_style: invalid stream');if(val>=Const.style_NUMSTYLES) val=0;if(str.type==strtype_Window){str.win.style=val;if(str.win.echostr) gli_set_style(str.win.echostr,val);}} function gli_set_hyperlink(str,val){if(!str||!str.writable) throw('gli_set_hyperlink: invalid stream');if(str.type==strtype_Window){str.win.hyperlink=val;if(str.win.echostr) gli_set_hyperlink(str.win.echostr,val);}} function gli_timer_callback(){if(ui_disabled){if(has_exited){GlkOte.log("### dropping timer event...");gli_timer_id=null;return;} else{GlkOte.log("### procrastinating timer event...");gli_timer_id=setTimeout(gli_timer_callback,500);return;}} gli_timer_id=setTimeout(gli_timer_callback,gli_timer_interval);gli_timer_started=Date.now();GlkOte.extevent('timer');} function glk_exit(){has_exited=true;ui_disabled=true;gli_selectref=null;return DidNotReturn;} function glk_tick(){} function glk_gestalt(sel,val){return glk_gestalt_ext(sel,val,null);} function glk_gestalt_ext(sel,val,arr){switch(sel){case 0:return 0x00000704;case 1:if(val<=Const.keycode_Left&&val>=Const.keycode_End) return 1;if(val>=0x100000000-Const.keycode_MAXVAL) return 0;if(val>0x10FFFF) return 0;if((val>=0&&val<32)||(val>=127&&val<160)) return 0;return 1;case 2:if(val>0x10FFFF) return 0;if((val>=0&&val<32)||(val>=127&&val<160)) return 0;return 1;case 3:if((val>0x10FFFF)||(val>=0&&val<32)||(val>=127&&val<160)){if(arr) arr[0]=1;return 0;} if(arr) arr[0]=1;return 2;case 4:return 0;case 5:return 1;case 6:return 0;case 7:return 0;case 8:return 0;case 9:return 0;case 10:return 0;case 11:return 1;case 12:if(val==3||val==4) return 1;else return 0;case 13:return 0;case 14:return 0;case 15:return 1;case 16:return 1;case 17:return 1;case 18:return 1;case 19:if(val==Const.keycode_Escape) return 1;if(val>=Const.keycode_Func12&&val<=Const.keycode_Func1) return 1;return 0;case 20:return 1;case 21:return 0;case 22:return 1;} return 0;} function glk_window_iterate(win,rockref){if(!win) win=gli_windowlist;else win=win.next;if(win){if(rockref) rockref.set_value(win.rock);return win;} if(rockref) rockref.set_value(0);return null;} function glk_window_get_rock(win){if(!win) throw('glk_window_get_rock: invalid window');return win.rock;} function glk_window_get_root(){return gli_rootwin;} function glk_window_open(splitwin,method,size,wintype,rock){var oldparent,box,val;var pairwin,newwin;if(!gli_rootwin){if(splitwin) throw('glk_window_open: splitwin must be null for first window');oldparent=null;box={left:content_metrics.outspacingx,top:content_metrics.outspacingy,right:content_metrics.width-content_metrics.outspacingx,bottom:content_metrics.height-content_metrics.outspacingy};} else{if(!splitwin) throw('glk_window_open: splitwin must not be null');val=(method&Const.winmethod_DivisionMask);if(val!=Const.winmethod_Fixed&&val!=Const.winmethod_Proportional) throw('glk_window_open: invalid method (not fixed or proportional)');val=(method&Const.winmethod_DirMask);if(val!=Const.winmethod_Above&&val!=Const.winmethod_Below&&val!=Const.winmethod_Left&&val!=Const.winmethod_Right) throw('glk_window_open: invalid method (bad direction)');box=splitwin.bbox;oldparent=splitwin.parent;if(oldparent&&oldparent.type!=Const.wintype_Pair) throw('glk_window_open: parent window is not Pair');} newwin=gli_new_window(wintype,rock);switch(newwin.type){case Const.wintype_TextBuffer:newwin.accum=[];newwin.accumstyle=null;newwin.accumhyperlink=0;newwin.content=[];newwin.clearcontent=false;break;case Const.wintype_TextGrid:newwin.gridwidth=0;newwin.gridheight=0;newwin.lines=[];newwin.cursorx=0;newwin.cursory=0;break;case Const.wintype_Blank:break;case Const.wintype_Pair:throw('glk_window_open: cannot open pair window directly') default:gli_delete_window(newwin);return null;} if(!splitwin){gli_rootwin=newwin;gli_window_rearrange(newwin,box);} else{pairwin=gli_new_window(Const.wintype_Pair,0);pairwin.pair_dir=method&Const.winmethod_DirMask;pairwin.pair_division=method&Const.winmethod_DivisionMask;pairwin.pair_key=newwin;pairwin.pair_keydamage=false;pairwin.pair_size=size;pairwin.pair_hasborder=((method&Const.winmethod_BorderMask)==Const.winmethod_Border);pairwin.pair_vertical=(pairwin.pair_dir==Const.winmethod_Left||pairwin.pair_dir==Const.winmethod_Right);pairwin.pair_backward=(pairwin.pair_dir==Const.winmethod_Left||pairwin.pair_dir==Const.winmethod_Above);pairwin.child1=splitwin;pairwin.child2=newwin;splitwin.parent=pairwin;newwin.parent=pairwin;pairwin.parent=oldparent;if(oldparent){if(oldparent.child1==splitwin) oldparent.child1=pairwin;else oldparent.child2=pairwin;} else{gli_rootwin=pairwin;} gli_window_rearrange(pairwin,box);} return newwin;} function glk_window_close(win,statsref){if(!win) throw('glk_window_close: invalid window');if(win===gli_rootwin||!win.parent){gli_rootwin=null;gli_stream_fill_result(win.str,statsref);gli_window_close(win,true);} else{var pairwin,grandparwin,sibwin,box,wx,keydamage_flag;pairwin=win.parent;if(win===pairwin.child1) sibwin=pairwin.child2;else if(win===pairwin.child2) sibwin=pairwin.child1;else throw('glk_window_close: window tree is corrupted');box=pairwin.bbox;grandparwin=pairwin.parent;if(!grandparwin){gli_rootwin=sibwin;sibwin.parent=null;} else{if(grandparwin.child1===pairwin) grandparwin.child1=sibwin;else grandparwin.child2=sibwin;sibwin.parent=grandparwin;} gli_stream_fill_result(win.str,statsref);gli_window_close(win,true);if(win===pairwin.child1){pairwin.child1=null;} else if(win===pairwin.child2){pairwin.child2=null;} gli_window_close(pairwin,false);keydamage_flag=false;for(wx=sibwin;wx;wx=wx.parent){if(wx.type==Const.wintype_Pair){if(wx.pair_keydamage){keydamage_flag=true;wx.pair_keydamage=false;}}} if(keydamage_flag){box=content_box;gli_window_rearrange(gli_rootwin,box);} else{gli_window_rearrange(sibwin,box);}}} function glk_window_get_size(win,widthref,heightref){if(!win) throw('glk_window_get_size: invalid window');var wid=0;var hgt=0;var boxwidth,boxheight;switch(win.type){case Const.wintype_TextGrid:boxwidth=win.bbox.right-win.bbox.left;boxheight=win.bbox.bottom-win.bbox.top;wid=Math.max(0,Math.floor((boxwidth-content_metrics.gridmarginx)/content_metrics.gridcharwidth));hgt=Math.max(0,Math.floor((boxheight-content_metrics.gridmarginy)/content_metrics.gridcharheight));break;case Const.wintype_TextBuffer:boxwidth=win.bbox.right-win.bbox.left;boxheight=win.bbox.bottom-win.bbox.top;wid=Math.max(0,Math.floor((boxwidth-content_metrics.buffermarginx)/content_metrics.buffercharwidth));hgt=Math.max(0,Math.floor((boxheight-content_metrics.buffermarginy)/content_metrics.buffercharheight));break;} if(widthref) widthref.set_value(wid);if(heightref) heightref.set_value(hgt);} function glk_window_set_arrangement(win,method,size,keywin){var wx,newdir,newvertical,newbackward;if(!win) throw('glk_window_set_arrangement: invalid window');if(win.type!=Const.wintype_Pair) throw('glk_window_set_arrangement: not a pair window');if(keywin){if(keywin.type==Const.wintype_Pair) throw('glk_window_set_arrangement: keywin cannot be a pair window');for(wx=keywin;wx;wx=wx.parent){if(wx==win) break;} if(!wx) throw('glk_window_set_arrangement: keywin must be a descendant');} newdir=method&Const.winmethod_DirMask;newvertical=(newdir==Const.winmethod_Left||newdir==Const.winmethod_Right);newbackward=(newdir==Const.winmethod_Left||newdir==Const.winmethod_Above);if(!keywin) keywin=win.pair_key;if(newvertical&&!win.pair_vertical) throw('glk_window_set_arrangement: split must stay horizontal');if(!newvertical&&win.pair_vertical) throw('glk_window_set_arrangement: split must stay vertical');if(keywin&&keywin.type==Const.wintype_Blank&&(method&Const.winmethod_DivisionMask)==Const.winmethod_Fixed) throw('glk_window_set_arrangement: a blank window cannot have a fixed size');if((newbackward&&!win.pair_backward)||(!newbackward&&win.pair_backward)){wx=win.child1;win.child1=win.child2;win.child2=wx;} win.pair_dir=newdir;win.pair_division=(method&Const.winmethod_DivisionMask);win.pair_key=keywin;win.pair_size=size;win.pair_hasborder=((method&Const.winmethod_BorderMask)==Const.winmethod_Border);win.pair_vertical=(win.pair_dir==Const.winmethod_Left||win.pair_dir==Const.winmethod_Right);win.pair_backward=(win.pair_dir==Const.winmethod_Left||win.pair_dir==Const.winmethod_Above);gli_window_rearrange(win,win.bbox);} function glk_window_get_arrangement(win,methodref,sizeref,keywinref){if(!win) throw('glk_window_get_arrangement: invalid window');if(win.type!=Const.wintype_Pair) throw('glk_window_get_arrangement: not a pair window');if(sizeref) sizeref.set_value(win.pair_size);if(keywinref) keywinref.set_value(win.pair_key);if(methodref) methodref.set_value(win.pair_dir|win.pair_division|(win.pair_hasborder?Const.winmethod_Border:Const.winmethod_NoBorder));} function glk_window_get_type(win){if(!win) throw('glk_window_get_type: invalid window');return win.type;} function glk_window_get_parent(win){if(!win) throw('glk_window_get_parent: invalid window');return win.parent;} function glk_window_clear(win){var ix,cx,lineobj;if(!win) throw('glk_window_clear: invalid window');if(win.line_request){throw('glk_window_clear: window has pending line request');} switch(win.type){case Const.wintype_TextBuffer:win.accum.length=0;win.accumstyle=null;win.accumhyperlink=0;win.content.length=0;win.clearcontent=true;break;case Const.wintype_TextGrid:win.cursorx=0;win.cursory=0;for(ix=0;ixstr.bufeof) pos=str.bufeof;str.bufpos=pos;}} function glk_stream_get_position(str){if(!str) throw('glk_stream_get_position: invalid stream');switch(str.type){case strtype_File:case strtype_Resource:case strtype_Memory:return str.bufpos;default:return 0;}} function glk_stream_set_current(str){gli_currentstr=str;} function glk_stream_get_current(){return gli_currentstr;} function glk_fileref_create_temp(usage,rock){var timestamp=new Date().getTime();var filename="_temp_"+timestamp+"_"+Math.random();filename=filename.replace('.','');fref=gli_new_fileref(filename,usage,rock,null);return fref;} function glk_fileref_create_by_name(usage,filename,rock){fref=gli_new_fileref(filename,usage,rock,null);return fref;} function glk_fileref_create_by_prompt(usage,fmode,rock){var modename;var filetype=(usage&Const.fileusage_TypeMask);var filetypename=FileTypeMap[filetype];if(!filetypename){filetypename='xxx';} switch(fmode){case Const.filemode_Write:modename='write';break;case Const.filemode_ReadWrite:modename='readwrite';break;case Const.filemode_WriteAppend:modename='writeappend';break;case Const.filemode_Read:default:modename='read';break;} var special={type:'fileref_prompt',filetype:filetypename,filemode:modename};var callback={usage:usage,rock:rock};if(filetype==Const.fileusage_SavedGame) special.gameid=VM.get_signature();ui_specialinput=special;ui_specialcallback=callback;gli_selectref=null;return DidNotReturn;} function gli_fileref_create_by_prompt_callback(obj){var ref=obj.value;var usage=ui_specialcallback.usage;var rock=ui_specialcallback.rock;var fref=null;if(ref){fref=gli_new_fileref(ref.filename,usage,rock,ref);} ui_specialinput=null;ui_specialcallback=null;if(window.GiDispa) GiDispa.prepare_resume(fref);VM.resume();} function glk_fileref_destroy(fref){if(!fref) throw('glk_fileref_destroy: invalid fileref');gli_delete_fileref(fref);} function glk_fileref_iterate(fref,rockref){if(!fref) fref=gli_filereflist;else fref=fref.next;if(fref){if(rockref) rockref.set_value(fref.rock);return fref;} if(rockref) rockref.set_value(0);return null;} function glk_fileref_get_rock(fref){if(!fref) throw('glk_fileref_get_rock: invalid fileref');return fref.rock;} function glk_fileref_delete_file(fref){if(!fref) throw('glk_fileref_delete_file: invalid fileref');Dialog.file_remove_ref(fref.ref);} function glk_fileref_does_file_exist(fref){if(!fref) throw('glk_fileref_does_file_exist: invalid fileref');if(Dialog.file_ref_exists(fref.ref)) return 1;else return 0;} function glk_fileref_create_from_fileref(usage,oldfref,rock){if(!oldfref) throw('glk_fileref_create_from_fileref: invalid fileref');var fref=gli_new_fileref(oldfref.filename,usage,rock,null);return fref;} function glk_put_char(ch){gli_put_char(gli_currentstr,ch&0xFF);} function glk_put_char_stream(str,ch){gli_put_char(str,ch&0xFF);} function glk_put_string(val){glk_put_jstring_stream(gli_currentstr,val,true);} function glk_put_string_stream(str,val){glk_put_jstring_stream(str,val,true);} function glk_put_buffer(arr){arr=TrimArrayToBytes(arr);gli_put_array(gli_currentstr,arr,true);} function glk_put_buffer_stream(str,arr){arr=TrimArrayToBytes(arr);gli_put_array(str,arr,true);} function glk_set_style(val){gli_set_style(gli_currentstr,val);} function glk_set_style_stream(str,val){gli_set_style(str,val);} function glk_get_char_stream(str){if(!str) throw('glk_get_char_stream: invalid stream');return gli_get_char(str,false);} function glk_get_line_stream(str,buf){if(!str) throw('glk_get_line_stream: invalid stream');return gli_get_line(str,buf,false);} function glk_get_buffer_stream(str,buf){if(!str) throw('glk_get_buffer_stream: invalid stream');return gli_get_buffer(str,buf,false);} function glk_char_to_lower(val){if(val>=0x41&&val<=0x5A) return val+0x20;if(val>=0xC0&&val<=0xDE&&val!=0xD7) return val+0x20;return val;} function glk_char_to_upper(val){if(val>=0x61&&val<=0x7A) return val-0x20;if(val>=0xE0&&val<=0xFE&&val!=0xF7) return val-0x20;return val;} function glk_stylehint_set(wintype,styl,hint,value){} function glk_stylehint_clear(wintype,styl,hint){} function glk_style_distinguish(win,styl1,styl2){return 0;} function glk_style_measure(win,styl,hint,resultref){if(resultref) resultref.set_value(0);return 0;} function glk_select(eventref){gli_selectref=eventref;return DidNotReturn;} function glk_select_poll(eventref){eventref.set_field(0,Const.evtype_None);eventref.set_field(1,null);eventref.set_field(2,0);eventref.set_field(3,0);if(gli_timer_interval&&!(gli_timer_id===null)){var now=Date.now();if(now-gli_timer_started>gli_timer_interval){clearTimeout(gli_timer_id);gli_timer_id=setTimeout(gli_timer_callback,gli_timer_interval);gli_timer_started=Date.now();eventref.set_field(0,Const.evtype_Timer);}}} function glk_request_line_event(win,buf,initlen){if(!win) throw('glk_request_line_event: invalid window');if(win.char_request||win.line_request) throw('glk_request_line_event: window already has keyboard request');if(win.type==Const.wintype_TextBuffer||win.type==Const.wintype_TextGrid){if(initlen){var ls=buf.slice(0,initlen);if(!current_partial_outputs) current_partial_outputs={};current_partial_outputs[win.disprock]=ByteArrayToString(ls);} win.line_request=true;win.line_request_uni=false;if(win.type==Const.wintype_TextBuffer) win.request_echo_line_input=win.echo_line_input;else win.request_echo_line_input=true;win.input_generation=event_generation;win.linebuf=buf;if(window.GiDispa) GiDispa.retain_array(buf);} else{throw('glk_request_line_event: window does not support keyboard input');}} function glk_cancel_line_event(win,eventref){if(!win) throw('glk_cancel_line_event: invalid window');if(!win.line_request){if(eventref){eventref.set_field(0,Const.evtype_None);eventref.set_field(1,null);eventref.set_field(2,0);eventref.set_field(3,0);} return;} var input="";var ix,val;if(current_partial_inputs){val=current_partial_inputs[win.disprock];if(val) input=val;} if(input.length>win.linebuf.length) input=input.slice(0,win.linebuf.length);if(win.request_echo_line_input){ix=win.style;gli_set_style(win.str,Const.style_Input);gli_window_put_string(win,input);if(win.echostr) glk_put_jstring_stream(win.echostr,input);gli_set_style(win.str,ix);gli_window_put_string(win,"\n");if(win.echostr) glk_put_jstring_stream(win.echostr,"\n");} for(ix=0;ix=pos) break;grpstart=ix;while(ix=2){for(jx=grpend-1;jx>grpstart;jx--){for(kx=grpstart;kxunicode_combin_table[arr[kx+1]]){tmp=arr[kx];arr[kx]=arr[kx+1];arr[kx+1]=tmp;}}}}} return pos;} function gli_buffer_canon_compose_uni(arr,numchars){var ix,jx,curch,newch,curclass,newclass,map,pos;if(numchars==0) return 0;pos=0;curch=arr[0];curclass=unicode_combin_table[curch];if(curclass) curclass=999;ix=1;jx=ix;while(true){if(jx>=numchars){arr[pos]=curch;pos=ix;break;} newch=arr[jx];newclass=unicode_combin_table[newch];map=unicode_compo_table[curch];if(map!==undefined&&map[newch]!==undefined&&(!curclass||(newclass&&curclass>>0);usec=Math.floor((now%1000)*1000);if(usec<0) usec=1000000+usec;timevalref.set_field(2,usec);} function glk_current_simple_time(factor){var now=new Date().getTime();return Math.floor(now/(factor*1000));} function glk_time_to_date_utc(timevalref,dateref){var now=timevalref.get_field(0)*4294967296000+timevalref.get_field(1)*1000+timevalref.get_field(2)/1000;var obj=new Date(now);dateref.set_field(0,obj.getUTCFullYear()) dateref.set_field(1,1+obj.getUTCMonth()) dateref.set_field(2,obj.getUTCDate()) dateref.set_field(3,obj.getUTCDay()) dateref.set_field(4,obj.getUTCHours()) dateref.set_field(5,obj.getUTCMinutes()) dateref.set_field(6,obj.getUTCSeconds()) dateref.set_field(7,1000*obj.getUTCMilliseconds())} function glk_time_to_date_local(timevalref,dateref){var now=timevalref.get_field(0)*4294967296000+timevalref.get_field(1)*1000+timevalref.get_field(2)/1000;var obj=new Date(now);dateref.set_field(0,obj.getFullYear()) dateref.set_field(1,1+obj.getMonth()) dateref.set_field(2,obj.getDate()) dateref.set_field(3,obj.getDay()) dateref.set_field(4,obj.getHours()) dateref.set_field(5,obj.getMinutes()) dateref.set_field(6,obj.getSeconds()) dateref.set_field(7,1000*obj.getMilliseconds())} function glk_simple_time_to_date_utc(time,factor,dateref){var now=time*(1000*factor);var obj=new Date(now);dateref.set_field(0,obj.getUTCFullYear()) dateref.set_field(1,1+obj.getUTCMonth()) dateref.set_field(2,obj.getUTCDate()) dateref.set_field(3,obj.getUTCDay()) dateref.set_field(4,obj.getUTCHours()) dateref.set_field(5,obj.getUTCMinutes()) dateref.set_field(6,obj.getUTCSeconds()) dateref.set_field(7,1000*obj.getUTCMilliseconds())} function glk_simple_time_to_date_local(time,factor,dateref){var now=time*(1000*factor);var obj=new Date(now);dateref.set_field(0,obj.getFullYear()) dateref.set_field(1,1+obj.getMonth()) dateref.set_field(2,obj.getDate()) dateref.set_field(3,obj.getDay()) dateref.set_field(4,obj.getHours()) dateref.set_field(5,obj.getMinutes()) dateref.set_field(6,obj.getSeconds()) dateref.set_field(7,1000*obj.getMilliseconds())} function glk_date_to_time_utc(dateref,timevalref){var obj=new Date(0);obj.setUTCFullYear(dateref.get_field(0));obj.setUTCMonth(dateref.get_field(1)-1);obj.setUTCDate(dateref.get_field(2));obj.setUTCHours(dateref.get_field(4));obj.setUTCMinutes(dateref.get_field(5));obj.setUTCSeconds(dateref.get_field(6));obj.setUTCMilliseconds(dateref.get_field(7)/1000);var now=obj.getTime();var usec;timevalref.set_field(0,Math.floor(now/4294967296000));timevalref.set_field(1,Math.floor(now/1000)>>>0);usec=Math.floor((now%1000)*1000);if(usec<0) usec=1000000+usec;timevalref.set_field(2,usec);} function glk_date_to_time_local(dateref,timevalref){var obj=new Date(dateref.get_field(0),dateref.get_field(1)-1,dateref.get_field(2),dateref.get_field(4),dateref.get_field(5),dateref.get_field(6),dateref.get_field(7)/1000);var now=obj.getTime();var usec;timevalref.set_field(0,Math.floor(now/4294967296000));timevalref.set_field(1,Math.floor(now/1000)>>>0);usec=Math.floor((now%1000)*1000);if(usec<0) usec=1000000+usec;timevalref.set_field(2,usec);} function glk_date_to_simple_time_utc(dateref,factor){var obj=new Date(0);obj.setUTCFullYear(dateref.get_field(0));obj.setUTCMonth(dateref.get_field(1)-1);obj.setUTCDate(dateref.get_field(2));obj.setUTCHours(dateref.get_field(4));obj.setUTCMinutes(dateref.get_field(5));obj.setUTCSeconds(dateref.get_field(6));obj.setUTCMilliseconds(dateref.get_field(7)/1000);var now=obj.getTime();return Math.floor(now/(factor*1000));} function glk_date_to_simple_time_local(dateref,factor){var obj=new Date(dateref.get_field(0),dateref.get_field(1)-1,dateref.get_field(2),dateref.get_field(4),dateref.get_field(5),dateref.get_field(6),dateref.get_field(7)/1000);var now=obj.getTime();return Math.floor(now/(factor*1000));} return{version:'1.3.1',init:init,update:update,fatal_error:fatal_error,byte_array_to_string:ByteArrayToString,uni_array_to_string:UniArrayToString,Const:Const,RefBox:RefBox,RefStruct:RefStruct,DidNotReturn:DidNotReturn,call_may_not_return:call_may_not_return,glk_put_jstring:glk_put_jstring,glk_put_jstring_stream:glk_put_jstring_stream,glk_exit:glk_exit,glk_tick:glk_tick,glk_gestalt:glk_gestalt,glk_gestalt_ext:glk_gestalt_ext,glk_window_iterate:glk_window_iterate,glk_window_get_rock:glk_window_get_rock,glk_window_get_root:glk_window_get_root,glk_window_open:glk_window_open,glk_window_close:glk_window_close,glk_window_get_size:glk_window_get_size,glk_window_set_arrangement:glk_window_set_arrangement,glk_window_get_arrangement:glk_window_get_arrangement,glk_window_get_type:glk_window_get_type,glk_window_get_parent:glk_window_get_parent,glk_window_clear:glk_window_clear,glk_window_move_cursor:glk_window_move_cursor,glk_window_get_stream:glk_window_get_stream,glk_window_set_echo_stream:glk_window_set_echo_stream, glk_window_get_echo_stream:glk_window_get_echo_stream,glk_set_window:glk_set_window,glk_window_get_sibling:glk_window_get_sibling,glk_stream_iterate:glk_stream_iterate,glk_stream_get_rock:glk_stream_get_rock,glk_stream_open_file:glk_stream_open_file,glk_stream_open_memory:glk_stream_open_memory,glk_stream_close:glk_stream_close,glk_stream_set_position:glk_stream_set_position,glk_stream_get_position:glk_stream_get_position,glk_stream_set_current:glk_stream_set_current,glk_stream_get_current:glk_stream_get_current,glk_fileref_create_temp:glk_fileref_create_temp,glk_fileref_create_by_name:glk_fileref_create_by_name,glk_fileref_create_by_prompt:glk_fileref_create_by_prompt,glk_fileref_destroy:glk_fileref_destroy,glk_fileref_iterate:glk_fileref_iterate,glk_fileref_get_rock:glk_fileref_get_rock,glk_fileref_delete_file:glk_fileref_delete_file,glk_fileref_does_file_exist:glk_fileref_does_file_exist,glk_fileref_create_from_fileref:glk_fileref_create_from_fileref,glk_put_char:glk_put_char,glk_put_char_stream:glk_put_c har_stream,glk_put_string:glk_put_string,glk_put_string_stream:glk_put_string_stream,glk_put_buffer:glk_put_buffer,glk_put_buffer_stream:glk_put_buffer_stream,glk_set_style:glk_set_style,glk_set_style_stream:glk_set_style_stream,glk_get_char_stream:glk_get_char_stream,glk_get_line_stream:glk_get_line_stream,glk_get_buffer_stream:glk_get_buffer_stream,glk_char_to_lower:glk_char_to_lower,glk_char_to_upper:glk_char_to_upper,glk_stylehint_set:glk_stylehint_set,glk_stylehint_clear:glk_stylehint_clear,glk_style_distinguish:glk_style_distinguish,glk_style_measure:glk_style_measure,glk_select:glk_select,glk_select_poll:glk_select_poll,glk_request_line_event:glk_request_line_event,glk_cancel_line_event:glk_cancel_line_event,glk_request_char_event:glk_request_char_event,glk_cancel_char_event:glk_cancel_char_event,glk_request_mouse_event:glk_request_mouse_event,glk_cancel_mouse_event:glk_cancel_mouse_event,glk_request_timer_events:glk_request_timer_events,glk_image_get_info:glk_image_get_info,glk_image_draw:glk_image_d raw,glk_image_draw_scaled:glk_image_draw_scaled,glk_window_flow_break:glk_window_flow_break,glk_window_erase_rect:glk_window_erase_rect,glk_window_fill_rect:glk_window_fill_rect,glk_window_set_background_color:glk_window_set_background_color,glk_schannel_iterate:glk_schannel_iterate,glk_schannel_get_rock:glk_schannel_get_rock,glk_schannel_create:glk_schannel_create,glk_schannel_destroy:glk_schannel_destroy,glk_schannel_play:glk_schannel_play,glk_schannel_play_ext:glk_schannel_play_ext,glk_schannel_stop:glk_schannel_stop,glk_schannel_set_volume:glk_schannel_set_volume,glk_schannel_create_ext:glk_schannel_create_ext,glk_schannel_play_multi:glk_schannel_play_multi,glk_schannel_pause:glk_schannel_pause,glk_schannel_unpause:glk_schannel_unpause,glk_schannel_set_volume_ext:glk_schannel_set_volume_ext,glk_sound_load_hint:glk_sound_load_hint,glk_set_hyperlink:glk_set_hyperlink,glk_set_hyperlink_stream:glk_set_hyperlink_stream,glk_request_hyperlink_event:glk_request_hyperlink_event,glk_cancel_hyperlink_event:glk_canc el_hyperlink_event,glk_buffer_to_lower_case_uni:glk_buffer_to_lower_case_uni,glk_buffer_to_upper_case_uni:glk_buffer_to_upper_case_uni,glk_buffer_to_title_case_uni:glk_buffer_to_title_case_uni,glk_buffer_canon_decompose_uni:glk_buffer_canon_decompose_uni,glk_buffer_canon_normalize_uni:glk_buffer_canon_normalize_uni,glk_put_char_uni:glk_put_char_uni,glk_put_string_uni:glk_put_string_uni,glk_put_buffer_uni:glk_put_buffer_uni,glk_put_char_stream_uni:glk_put_char_stream_uni,glk_put_string_stream_uni:glk_put_string_stream_uni,glk_put_buffer_stream_uni:glk_put_buffer_stream_uni,glk_get_char_stream_uni:glk_get_char_stream_uni,glk_get_buffer_stream_uni:glk_get_buffer_stream_uni,glk_get_line_stream_uni:glk_get_line_stream_uni,glk_stream_open_file_uni:glk_stream_open_file_uni,glk_stream_open_memory_uni:glk_stream_open_memory_uni,glk_request_char_event_uni:glk_request_char_event_uni,glk_request_line_event_uni:glk_request_line_event_uni,glk_set_echo_line_event:glk_set_echo_line_event,glk_set_terminators_line_event:glk_s et_terminators_line_event,glk_current_time:glk_current_time,glk_current_simple_time:glk_current_simple_time,glk_time_to_date_utc:glk_time_to_date_utc,glk_time_to_date_local:glk_time_to_date_local,glk_simple_time_to_date_utc:glk_simple_time_to_date_utc,glk_simple_time_to_date_local:glk_simple_time_to_date_local,glk_date_to_time_utc:glk_date_to_time_utc,glk_date_to_time_local:glk_date_to_time_local,glk_date_to_simple_time_utc:glk_date_to_simple_time_utc,glk_date_to_simple_time_local:glk_date_to_simple_time_local,glk_stream_open_resource:glk_stream_open_resource,glk_stream_open_resource_uni:glk_stream_open_resource_uni};}();