
var ENV = {"platform":"classic","mode":"production"};
var SC=SC||{BUNDLE_INFO:{},LAZY_INSTANTIATION:{}};SC.json=JSON;SC.browser=(function(){var c=navigator.userAgent.toLowerCase();
var a=(c.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1];var b={version:a,safari:(/webkit/).test(c)?a:0,opera:(/opera/).test(c)?a:0,msie:(/msie/).test(c)&&!(/opera/).test(c)?a:0,mozilla:(/mozilla/).test(c)&&!(/(compatible|webkit)/).test(c)?a:0,mobileSafari:(/apple.*mobile.*safari/).test(c)?a:0,windows:!!(/(windows)/).test(c),mac:!!((/(macintosh)/).test(c)||(/(mac os x)/).test(c)),language:(navigator.language||navigator.browserLanguage).split("-",1)[0]};
b.current=b.msie?"msie":b.mozilla?"mozilla":b.safari?"safari":b.opera?"opera":"unknown";
return b})();SC.bundleDidLoad=function(a){var b=this.BUNDLE_INFO[a];if(!b){b=this.BUNDLE_INFO[a]={}
}b.loaded=true};SC.bundleIsLoaded=function(a){var b=this.BUNDLE_INFO[a];return b?!!b.loaded:false
};SC.loadBundle=function(){throw"SC.loadBundle(): SproutCore is not loaded."};SC.setupBodyClassNames=function(){var e=document.body;
if(!e){return}var c,a,f,b,g,d;c=SC.browser.current;a=SC.browser.windows?"windows":SC.browser.mac?"mac":"other-platform";
d=document.documentElement.style;f=(d.MozBoxShadow!==undefined)||(d.webkitBoxShadow!==undefined)||(d.oBoxShadow!==undefined)||(d.boxShadow!==undefined);
b=(d.MozBorderRadius!==undefined)||(d.webkitBorderRadius!==undefined)||(d.oBorderRadius!==undefined)||(d.borderRadius!==undefined);
g=e.className?e.className.split(" "):[];if(f){g.push("box-shadow")}if(b){g.push("border-rad")
}g.push(c);g.push(a);if(SC.browser.mobileSafari){g.push("mobile-safari")}e.className=g.join(" ")
};
"use modules false";"use loader false";if("undefined"===typeof tiki){var tiki=function(){var queue=[];
var factories={};var modules={};function _record(method,args){queue.push({m:method,a:args});
}var tiki={_modules:modules,_factories:factories,isBootstrap:true,queue:queue,register:function(){_record("register",arguments);
return this;},script:function(){_record("script",arguments);return this;},stylesheet:function(){_record("stylesheet",arguments);
return this;},module:function(moduleId,factory){factories[moduleId]=factory;_record("module",arguments);
return this;},require:function(moduleId){var ret,factory,info,idx,packagePart,modulePart;
ret=modules[moduleId];if(!ret){ret=modules[moduleId]={};info={id:moduleId};factory=factories[moduleId];
if(typeof factory!=="function"){throw (moduleId+" is not function");}factory.call(ret,tiki.require,ret,info);
}return ret;},destroy:function(){if(this.isDestroyed){return this;}this.isDestroyed=true;
modules=factories=queue=this.queue=null;return this;}};return tiki;}();}tiki.register("tiki",{"scripts":[{"url":"/static/tiki/en/0bc0db20a15cb1574e0e5deef1b477c14c43c8a3/javascript.js","id":"tiki:en/0bc0db20a15cb1574e0e5deef1b477c14c43c8a3/javascript.js"}]});
tiki.module("tiki:core",function(require,exports,module){var setupDisplayNames;"export setupDisplayNames";
"use factory_format function";var TMP_ARY=[];setupDisplayNames=function setupDisplayNames(obj,root){var a=TMP_ARY;
a[0]=root;var k,v;for(k in obj){if(!obj.hasOwnProperty(k)){continue;}v=obj[k];if("function"===typeof v){a[1]=k;
v.displayName=a.join(".");}}a.length=0;return obj;};exports.setupDisplayNames=setupDisplayNames;
});tiki.module("tiki:lib/loader",function(require,exports,module){var core=require("tiki:core");
var promise=require("tiki:lib/promise");var sandbox=require("tiki:lib/sandbox");var Loader,create,setup;
"import core as core";"import lib/promise as promise";"import lib/sandbox as sandbox";
"export package Loader";"export create setup";"use factory_format function";var SCRIPTS="scripts",CATALOG="catalog",MODULES="modules",STYLESHEETS="stylesheets",LOADS="loads";
var MODULE_WRAPPER=["(function(require, exports, module) {",null,"\n});\n//@ sourceURL=",null,"\n"];
var TIKI_ARY=["tiki/",null];var STRING="string";var globals={};var PROMISE_NAME=[];
function promiseName(type,key){PROMISE_NAME[0]=type;PROMISE_NAME[1]=key;return PROMISE_NAME.join("::");
}var object_keys=Object.keys;if(!object_keys){object_keys=function(obj){var k,ret=[];
for(k in obj){if(obj.hasOwnProperty(k)){ret.push(k);}}return ret;};}var inTikiCache={};
function inTiki(key){var ret=inTikiCache[key];if(ret){return ret;}return(inTikiCache[key]="tiki/"+key);
}Loader=function Loader(id,queue,env){this.id=id;this.scripts=[];this.packages=[];
this.stylesheets=[];this.modules=[];this.sandbox=sandbox.create(id,this,env);this.register("default",{});
this.register("tiki",{});var len=queue?queue.length:0,idx,action;for(idx=0;idx<len;
idx++){action=queue[idx];this[action.m].apply(this,action.a);}this._queue=queue;return this;
};Loader.prototype={scripts:null,stylesheets:null,packages:null,sandbox:null,modules:null,destroy:function(){},resolve:function resolve(moduleId,baseId){var path,len,idx,packageId,part,parts;
if(moduleId.match(/(^\.\.?\/)|(\/\.\.?\/)|(\/\.\.?\/?$)/)){if((idx=moduleId.indexOf(":"))>=0){packageId=moduleId.slice(0,idx);
moduleId=moduleId.slice(idx+1);path=[];}else{if(moduleId.match(/^\.\.?\//)){if(!baseId){throw ("base required to resolve relative: "+moduleId);
}idx=baseId.indexOf(":");packageId=baseId.slice(0,idx);baseId=baseId.slice(idx+1);
path=baseId.split("/");path.pop();}else{path=[];}}parts=moduleId.split("/");len=parts.length;
for(idx=0;idx<len;idx++){part=parts[idx];if(part===".."){if(path.length<1){throw"invalid path: "+moduleId;
}path.pop();}else{if(part!=="."){path.push(part);}}}moduleId=path.join("/");if(packageId){moduleId=packageId+":"+moduleId;
}}if(moduleId.indexOf(":")<0){if(baseId&&(idx=baseId.indexOf(":"))>0){packageId=baseId.slice(0,idx);
moduleId=packageId+":"+moduleId;}}return moduleId;},canonical:function canonical(moduleId,baseId){var ret=this.resolve(moduleId,baseId),factories=this._factories,catalog=this._catalog,packageId,idx;
if((idx=moduleId.indexOf(":"))<0){if(!catalog||(factories&&factories[ret])){return ret;
}if(catalog[moduleId]){return moduleId+":package";}else{if(catalog[inTiki(moduleId)]){return inTiki(moduleId)+":package";
}}}else{packageId=moduleId.slice(0,idx);if(catalog&&!catalog[packageId]&&catalog[inTiki(packageId)]){ret=inTiki(moduleId);
}}return ret;},evaluate:function evaluate(moduleText,moduleId){var ret;MODULE_WRAPPER[1]=moduleText;
MODULE_WRAPPER[3]=moduleId||"(unknown module)";ret=MODULE_WRAPPER.join("");ret=eval(ret);
MODULE_WRAPPER[1]=MODULE_WRAPPER[3]=null;return ret;},load:function load(moduleId,baseId){var factories=this._factories,factory,packagePart,idx,info,tmp;
moduleId=this.canonical(moduleId,baseId);if(!this.ready(moduleId)){throw (moduleId+" is not ready");
}factory=factories[moduleId];if(factory&&(STRING===typeof factory)){factory=this.evaluate(factory,moduleId);
factories[moduleId]=factory;}return factory;},global:function(moduleId){var depends,info,len,idx,factories,moduleId,exports,key,packageId,ARY;
moduleId=this.canonical(moduleId);if((idx=moduleId.indexOf(":"))<0){throw"package not found: "+moduleId;
}packageId=moduleId.slice(0,idx);ARY=moduleId.split(":");info=this._catalog[packageId];
if(!info){throw (packageId+" is not registered");}depends=info.depends;len=depends?depends.length:0;
if(len<=0){return this;}factories=this._factories;if(!factories){return this;}for(idx=0;
idx<len;idx++){packageId=depends[idx];if(globals[packageId]){continue;}globals[packageId]=true;
if(!this.ready(packageId)){throw ("cannot make "+packageId+" global because it is not ready");
}moduleId=this.canonical(packageId);if(!factories[moduleId]){continue;}exports=this.require(moduleId);
for(key in exports){if(!exports.hasOwnProperty(key)){continue;}window[key]=exports[key];
}}},register:function(name,desc){if(name.indexOf(":")>0){return this.module(name,desc);
}var catalog=this._catalog,key;if(!catalog){catalog=this._catalog={};}catalog[name]=desc;
var info=desc?desc.packages:null;if(info){for(key in info){if(!info.hasOwnProperty(key)||catalog[key]){continue;
}catalog[key]=info[key];}}if(!this._resolved(CATALOG,name)){this.packages.push(name);
}this._promiseFor(CATALOG,name).resolve(name);},script:function script(id){if(!this._resolved(SCRIPTS,id)){this.scripts.push(id);
}this._promiseFor(SCRIPTS,id).resolve(id);return this;},stylesheet:function stylesheet(id){if(!this._resolved(STYLESHEETS,id)){this.stylesheets.push(id);
}this._promiseFor(STYLESHEETS,id).resolve(id);return this;},module:function module(moduleId,factory){var factories=this._factories;
if(!factories){factories=this._factories={};}factories[moduleId]=factory;if(!this._resolved(MODULES,moduleId)){this.modules.push(moduleId);
}this._promiseFor(MODULES,moduleId).resolve(moduleId);},async:function(packageId){return this._async(packageId,null);
},_async:function(packageId,seen){var ret=this._promiseFor(LOADS,packageId);if(ret.status===promise.PENDING){if(this.ready(packageId)){ret.resolve();
}else{var loader=this;ret.action(function(pr){loader._promiseFor(CATALOG,packageId).then(pr,function(){loader._loadPackage(packageId,pr,seen||{});
pr.resolve();},function(reason){pr.cancel(reason);});loader._loadPackage(packageId,pr,seen||{});
}).run();}}return ret;},require:function require(moduleId,packageId){return this.sandbox.require(moduleId,packageId);
},ready:function ready(moduleId){return this._ready(moduleId,null);},_ready:function(moduleId,seen){if(seen){if(seen[moduleId]){return true;
}else{seen[moduleId]=true;}}var idx,packageId,info,items,loc,scriptId,styleId;idx=moduleId.indexOf(":");
if(idx>=0){packageId=moduleId.slice(0,idx);}else{packageId=moduleId;}if(!this._resolved(CATALOG,packageId)){return false;
}info=this._catalog[packageId];items=info.depends;loc=items?items.length:0;while(--loc>=0){if(!seen){seen={};
}if(!this._ready(items[loc],seen)){return false;}}items=info.stylesheets;loc=items?items.length:0;
while(--loc>=0){styleId=items[loc];if(STRING!==typeof styleId){styleId=styleId.id;
}if(!this._resolved(STYLESHEETS,styleId)){return false;}}items=info.scripts;loc=items?items.length:0;
while(--loc>=0){scriptId=items[loc];if(STRING!==typeof scriptId){scriptId=scriptId.id;
}if(!this._resolved(SCRIPTS,scriptId)){return false;}}if(moduleId!==packageId){if(!this._resolved(MODULES,moduleId)){return false;
}}return true;},main:function(moduleId,method){var r=this.require("system").ready;
if(!r){throw ("cannot register main because system.ready does not exist");}r.main(this,function(){this.async(moduleId).then(this,function(){this.require(moduleId)[method]();
});});return this;},_loadScript:function(scriptId){var id,url,pr;if(STRING!==typeof(scriptId)){id=scriptId.id;
url=scriptId.url;}else{id=url=scriptId;}pr=this._promiseFor(SCRIPTS,id);if(pr.status===promise.PENDING){var loader=this;
pr.action(function(pr){var body=document.body,el;if(!body){promise.cancel("no document to append script");
}el=document.createElement("script");el.setAttribute("src",url);body.appendChild(el);
body=el=null;});}return pr;},_loadStylesheet:function(styleId){var id,url,pr;if(STRING!==typeof(styleId)){id=styleId.id;
url=styleId.url;}else{id=url=styleId;}pr=this._promiseFor(STYLESHEETS,id);if(pr.status===promise.PENDING){var loader=this;
pr.action(function(pr){var body=document.body,el;if(!body){pr.cancel("no document to append stylesheet");
}el=document.createElement("link");el.setAttribute("rel","stylesheet");el.setAttribute("href",url);
body.appendChild(el);body=el=null;loader.stylesheet(id);});}return pr;},_loadPackage:function(packageId,pr,seen){if(seen){if(seen[packageId]){console.warn("detected cyclical reference to "+packageId+" seen="+object_keys(seen).join(", "));
return;}else{seen[packageId]=true;}}var info=this._catalog?this._catalog[packageId]:null,items,loc,item,ordered,next,prDepends;
if(!info){return this;}items=info.depends;loc=items?items.length:0;prDepends=promise.create(promiseName("load-package",packageId));
while(--loc>=0){prDepends.depends(this._async(items[loc],seen));}pr.depends(prDepends);
prDepends.resolve();items=info.scripts;loc=items?items.length:0;next=null;ordered=info.ordered!==false;
while(--loc>=0){item=this._loadScript(items[loc]);pr.depends(item);if(ordered){if(next){item.then(next,next.run,next.cancel);
}}else{item.run();}next=item;}if(next&&ordered){prDepends.then(next,next.run,next.cancel);
}items=info.stylesheets;loc=items?items.length:0;next=null;while(--loc>=0){item=this._loadStylesheet(items[loc]);
pr.depends(item);if(next){item.then(next,next.run,next.cancel);}next=item;}if(next){prDepends.then(next,next.run,next.cancel);
}},_promiseFor:function(promiseType,name1,name2){var promises=this._promises,sub1,sub2,ret,Q;
if(!promises){promises=this._promises={};}sub1=promises[promiseType];if(!sub1){sub1=promises[promiseType]={};
}if(name2===undefined){sub2=sub1;name2=name1;}else{sub2=sub1[name1];if(!sub2){sub2=sub1[name1]={};
}}ret=sub2[name2];if(!ret){ret=sub2[name2]=promise.create(promiseName(promiseType,name1));
}return ret;},_discoveredStylesheets:false,discoverStylesheets:function(){this._discoveredStylesheets=true;
if("undefined"===typeof document){return this;}var links=document.getElementsByTagName("link"),loc=links?links.length:0,link;
while(--loc>=0){link=links[loc];if(!link||(link.rel!=="stylesheet")){continue;}link=link.getAttribute("loadid")||link.getAttribute("LOADID");
if(link){this.stylesheet(link.toString());}link=link.href;if(link){this.stylesheet(link.toString());
}}link=link=loc=null;return this;},_resolved:function(promiseType,name1,name2){if((promiseType===STYLESHEETS)&&!this._discoveredStylesheets){this.discoverStylesheets();
}var ret=this._promises;if(ret){ret=ret[promiseType];}if(ret){ret=ret[name1];}if(ret&&name2){ret=ret[name2];
}return ret?(ret.status===promise.RESOLVED):false;},_inspectLoader:function(){var lines=[],modules=this.modules,key,names,len,idx,emitted=false;
lines.push("Loader<id="+this.id+">:");if(this.packages.length>0){lines.push("  packages: "+this.packages.join(","));
lines.push("");}if(this.scripts.length>0){lines.push("  scripts:");len=this.scripts.length;
for(idx=0;idx<len;idx++){lines.push("    "+this.scripts[idx]);}lines.push("");}if(this.stylesheets.length>0){lines.push("  stylesheets:");
len=this.scripts.length;for(idx=0;idx<len;idx++){lines.push("    "+this.scripts[idx]);
}lines.push("");}if(this.modules.length>0){lines.push("  modules: ");len=this.modules.length;
for(idx=0;idx<len;idx++){lines.push("    "+this.modules[idx]);}lines.push("");}return lines.join("\n");
},_inspectModule:function(moduleId){var lines=[],packageId=moduleId.slice(0,moduleId.indexOf(":")),tmp;
if(this._catalog&&!this._catalog[packageId]){tmp="tiki/"+packageId;if(this._catalog[tmp]){packageId=tmp;
moduleId="tiki/"+moduleId;}}lines.push(moduleId+" ("+(this.ready(moduleId)?"READY":"NOT READY")+"):");
lines.push(this._inspectPackage(packageId));return lines.join("\n");},_inspectPackage:function(packageId){if(this._catalog&&!this._catalog[packageId]){var tmp="tiki/"+packageId;
if(this._catalog[tmp]){packageId=tmp;}}var lines=[],info=this._catalog?this._catalog[packageId]:null,idx,len,item,parts;
lines.push(packageId+" ("+(this.ready(packageId)?"READY":"NOT READY")+"): "+(info?"":"Not in Catalog!"));
if(!info){return lines.join("\n");}len=info.depends?info.depends.length:0;if(len>0){parts=[];
for(idx=0;idx<len;idx++){item=info.depends[idx];parts.push(item+" ("+(this.ready(item)?"READY":"NOT READY")+")");
}lines.push("  depends: "+parts.join(", "));}len=info.scripts?info.scripts.length:0;
if(len>0){lines.push("\n  scripts:");for(idx=0;idx<len;idx++){item=info.scripts[idx];
if(STRING!==typeof item){item=item.id;}lines.push("    "+item+" ("+(this._resolved(SCRIPTS,item)?"READY":"NOT READY")+")");
}}len=info.stylesheets?info.stylesheets.length:0;if(len>0){lines.push("\n  stylesheets:");
for(idx=0;idx<len;idx++){item=info.stylesheets[idx];if(STRING!==typeof item){item=item.id;
}lines.push("    "+item+"("+(this._resolved(STYLESHEETS,item)?"READY":"NOT READY")+")");
}}return lines.join("\n");},inspect:function(id){if(arguments.length===0){return this._inspectLoader();
}else{if(id.indexOf(":")<0){return this._inspectPackage(id);}else{return this._inspectModule(id);
}}},toString:function(){return"Loader<id="+this.id+">";}};core.setupDisplayNames(Loader.prototype,"Loader");
setup=function setup(curLoader,env){if(curLoader&&!curLoader.isBootstrap){return curLoader;
}if(!env){env={};}if(!env.global&&("undefined"!==typeof window)){env.global=window;
}if(!env.document&&("undefined"!==typeof document)){env.document=document;}var queue=curLoader?curLoader.queue:null,id=curLoader?curLoader.id:"default",ret=new Loader(id,queue,env);
if(curLoader&&curLoader.destroy){curLoader.destroy();}return ret;};create=function create(id){return new Loader(id);
};exports.Loader=Loader;exports.create=create;exports.setup=setup;});tiki.module("tiki:lib/promise",function(require,exports,module){var core=require("tiki:core");
var Promise,create,RESOLVED,PENDING,CANCELLED,BUSY,BLOCKED;"import core as core";
"export package Promise";"export create RESOLVED PENDING CANCELLED BUSY BLOCKED";
"use factory_format function";var LOG_PROMISES=false;RESOLVED="resolved";PENDING="pending";
CANCELLED="cancelled";BUSY="busy";BLOCKED="blocked";var Promise=function(id){this.id=id;
return this;};Promise.prototype={status:PENDING,outstandingDependencies:0,hasAction:false,resolve:function(val){if(LOG_PROMISES){console.log(this.id+".resolve() dep="+this.outstandingDependencies+" status="+this.status);
}var st=this.status;if((st===RESOLVED)||(st===CANCELLED)){return this;}this._value=val;
if(this.outstandingDependencies>0){this.status=BLOCKED;}else{this.status=RESOLVED;
this.value=val;this._notify(RESOLVED,val);}return this;},cancel:function(reason){var st=this.status;
if((st===RESOLVED)||(st===CANCELLED)){return this;}this.status=CANCELLED;this.value=reason;
this._notify(CANCELLED,reason);return this;},then:function(target,resolveMethod,cancelMethod){var actions;
if(arguments.length<3&&("function"===typeof target)){cancelMethod=resolveMethod;resolveMethod=target;
target=this;}if(resolveMethod){this._register(RESOLVED,target,resolveMethod);}if(cancelMethod){this._register(CANCELLED,target,cancelMethod);
}return this;},run:function(){if(this.method&&this.status===PENDING){this.status=BUSY;
this.method.call(this.target||this,this);}return this;},reset:function(){var st=this.status;
if((st!==BUSY)||(st!==BLOCKED)){this.status=PENDING;}this.value=null;return this;
},action:function(target,method){if(arguments.length===1){method=target;target=this;
}this.target=target;this.method=method;this.hasAction=true;return this;},depends:function(pr){this.outstandingDependencies++;
if(LOG_PROMISES){console.log(this.id+".depends("+pr.id+") dep="+this.outstandingDependencies+" status="+this.status);
}pr.then(this,this._resolveDepends,this._cancelDepends);return this;},_resolveDepends:function(ignore,pr){this.outstandingDependencies--;
if(LOG_PROMISES){console.log("  "+this.id+"._resolveDepends("+pr.id+") dep="+this.outstandingDependencies);
}if(this.outstandingDependencies<=0&&(this.status===BLOCKED)){this.resolve(this.value);
}return this;},_cancelDepends:function(reason,pr){if(LOG_PROMISES){console.log("  "+this.id+"._cancelDepends("+pr.id+") dep="+this.outstandingDependencies);
}this.cancel(reason);return this;},_notify:function(status,arg){var act=this._actions,len,i;
act=act?act[status]:null;len=act?act.length:0;this._actions=null;for(i=0;i<len;i++){this._invoke(act[i].target,act[i].method,arg);
}},_invoke:function(target,method,arg){if(("string"===typeof method)&&target){method=target[method];
}if(!target){target=this;}method.call(target,arg,this);},_register:function(status,target,method){var cur=this.status,actions,f;
if((cur===RESOLVED)||(cur===CANCELLED)){if(cur===status){this._invoke(target,method,this.value);
}}else{actions=this._actions;if(!actions){actions=this._actions={};}f=actions[status];
if(!f){f=actions[status]=[];}f.push({target:target,method:method});}},toString:function(){return"Promise<id="+this.id+" status="+this.status+">";
}};core.setupDisplayNames(Promise.prototype,"Promise");create=function create(id){return new Promise(id);
};exports.Promise=Promise;exports.create=create;exports.RESOLVED=RESOLVED;exports.PENDING=PENDING;
exports.CANCELLED=CANCELLED;exports.BUSY=BUSY;exports.BLOCKED=BLOCKED;});tiki.module("tiki:lib/sandbox",function(require,exports,module){var Sandbox,create;
"export package Sandbox";"export create";"use factory_format function";Sandbox=function Sandbox(id,loader,env){var allExports={},modules=[],HASH={},sandbox=this;
this.id=id;this.modules=modules;this.loader=loader;function _clear(){var loc=arguments.length,moduleId;
if(loc>0){while(--loc>0){moduleId=arguments[loc];if(moduleId&&allExports[moduleId]){delete allExports[moduleId];
modules.splice(modules.indexOf(moduleId),1);}}}else{allExports={};modules.length=0;
}}_clear.displayName="Sandbox.clear";function _require(moduleId,packageId,curModuleId){var req,exports,moduleInfo,factory,idx;
if(packageId){idx=moduleId.indexOf(":");if(idx>=0){moduleId=moduleId.slice(0,idx);
}moduleId=packageId+":"+moduleId;}moduleId=loader.canonical(moduleId,curModuleId);
if(exp=allExports[moduleId]){return exp;}modules.push(moduleId);allExports[moduleId]=exports={};
req=function(m,p){return _require(m,p,moduleId);};req.displayName="Sandbox.require";
req.loader=loader;req.clear=_clear;req.env=env||{};req.sandbox=this;moduleInfo={id:moduleId};
var func=loader.load(moduleId);if(!func){throw"could not load function for "+moduleId;
}func.call(exports,req,exports,moduleInfo);return exports;}this.require=function(moduleId,packageId){return _require(moduleId,packageId);
};this.require.displayName="Sandbox.require";};Sandbox.prototype={};create=function create(id,loader,env){return new Sandbox(id,loader,env);
};exports.Sandbox=Sandbox;exports.create=create;});tiki.module("tiki:package",function(require,exports,module){var m;
m=require("tiki:lib/loader");exports.Loader=m.Loader;m=require("tiki:lib/promise");
exports.Promise=m.Promise;m=require("tiki:lib/sandbox");exports.Sandbox=m.Sandbox;
});"use modules false";"use loader false";tiki=tiki.require("tiki:lib/loader").setup(tiki,("undefined"===typeof ENV)?null:ENV);
tiki.script("tiki:en/0bc0db20a15cb1574e0e5deef1b477c14c43c8a3/javascript.js");tiki.register("tiki/platform/classic",{"depends":["tiki"],"packages":{"tiki":{}},"scripts":[{"url":"/static/tiki/platform/classic/en/9f6d82903c6accdda661e6d567f7d6f7fd335392/javascript.js","id":"tiki/platform/classic:en/9f6d82903c6accdda661e6d567f7d6f7fd335392/javascript.js"}]});
tiki.module("tiki/platform/classic:lib/console",function(require,exports,module){var console;
"export package console";"use factory_format function";var env=require.env;console=(env&&env.global)?env.global.console:null;
exports.console=console;});tiki.module("tiki/platform/classic:lib/event","var info = require('tiki/platform/classic:lib/info');var add,remove,event,ready,unload,NATIVE_EVENTS;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92006-2009 Sprout Systems, Inc. and contributors.\n//            Portions \u00a92008-2009 Apple Inc. All rights reserved.\n// License:   Licened under MIT license (see license.js)\n// ==========================================================================\n/*globals event exports add remove ready unload info NATIVE_EVENTS */\n\n\"import lib/info as info\";\n\"export add remove\";\n\"export package event ready unload NATIVE_EVENTS\";\n\n/**\n  @file\n  \n  Implements a low-level interface for registering interest in native events\n  delivered by the web browser.  If you are implementing this API for a non-\n  browser environment, add() and remove() may do nothing.\n  \n  ready() and unload() should still invoke the passed callback when the \n  JS environment is ready for the app to run and just before the app exits,\n  respectively.\n\n  ready() and unload() should both expect to be called exactly once (by the\n  system event module).  They may throw an error if called more than once.\n*/\n\n\nvar readyCalled  = false, \n    unloadCalled = false,\n    browser      = info.browser,\n    isReady      = false,\n    isUnloaded   = false,\n    ecache       = {};\n    \n\n// returns a handler function for the onready event depending on the browser.    \nfunction readyHandler(callback) {\n  var ret ;\n  \n  // opera - wait until all the stylesheets are made visible\n  if (browser.opera) {\n    ret = function() {\n      if (isReady) return;\n      \n      for (var i = 0; i < document.styleSheets.length; i++) {\n        if (document.styleSheets[i].disabled) {\n          setTimeout(ret, 0);\n          return;\n        }\n      }\n      \n      // and execute any waiting functions\n      isReady = true;\n      callback();\n    };\n    \n  // msie - wait until the doScroll event stops complaining..\n  } else if (browser.msie) {\n    ret = function() {\n      if (isReady) return;\n      try {\n        // If IE is used, use the trick by Diego Perini\n        // http://javascript.nwbox.com/IEContentLoaded/\n        document.documentElement.doScroll(\"left\");\n      } catch( error ) {\n        setTimeout(ret, 0);\n        return;\n      }\n\n      // and execute any waiting functions\n      isReady = true;\n      callback();\n    };\n    \n  // everyone else - just call\n  } else {\n    ret = function() {\n      console.log('ready!');\n      if (isReady) return ;\n      isReady = true;\n      callback();\n    };\n  }\n  \n  return ret ;\n  \n}\n\n/** \n  Invoke the  callback when the browser is ready to handle app code. \n  Throws an exception if it is called more than once.  Uses a built-in \n  listener.\n  \n  @param {Function} callback\n  @returns {void}\n*/\nready = function(callback) {\n  if (readyCalled) throw(\"Cannot call platform.ready() more than once\");\n  readyCalled = true;\n  \n  var handler = readyHandler(callback);\n  \n  // Mozilla, Opera (see further below for it) and webkit nightlies \n  // currently support this event.  Use the handy event callback\n  if (document.addEventListener) {\n    document.addEventListener( \"DOMContentLoaded\", handler, NO );\n  \n  // If IE is used and is not in a frame\n  // Continually check to see if the document is ready\n  } else if (browser.msie && (window === top)) handler();\n\n  // A fallback to window.onload, that will always work\n  add(window, 'load', handler);\n};\n\n\nfunction unloadHandler(callback) {\n  return function() {\n    if (isUnloaded) return ;\n    isUnloaded = true;\n    callback();\n  }; \n}\n\n/**\n  Invoke the callback just before the browser unloads the page.  Throws an \n  error if called more than once.\n  \n  @param {Function} callback\n  @returns {void}\n*/\nunload = function(callback) {\n  if (unloadCalled) throw(\"Cannot call platform.unload() more than once\");\n  unloadCalled = true;\n  add(window, 'unload', unloadHandler(callback));\n};\n\n// ..........................................................\n// EVENT LISTENERS\n// \n\n/**\n  Names of event types natively supported by this library.  Platforms without\n  native event support can return an empty hash.\n*/\nNATIVE_EVENTS = {};\n\n// TODO: make this correct per-browser\n// TODO: add touch events\nvar names = 'mousedown mouseup click dblclick mouseover mouseout selectstart keypress keydown keyup blur focus deactivate change select submit contextmenu dragstart error hashchange help load losecapture readystatechange resize scroll unload'.split(' '), loc = names.length;\nwhile(--loc>=0) NATIVE_EVENTS[names[loc]] = names[loc];\n\n\n// convert 'foo' => 'onfoo' using cache to avoid malloc\nfunction onStr(str) {\n    var ret = ecache[str];\n    if (!ret) ret = ecache[str] = ('on' + str); // avoid mallocs\n    return ret ;\n}\n\n/**\n  Adds a listener for the event.  No need to do any special buffering; just\n  add the listener in a platform-specific way.\n  \n  @param {Object} elem the target element if any.  otherwise use document\n  @param {String} eventType click, mousedown, etc\n  @param {Function} callback function to invoke\n  @returns {void}\n*/\nadd = function(elem, eventType, callback) {\n  if (!NATIVE_EVENTS[eventType]) return ; // ignore for native events\n  if (!elem) elem = require.env.document;\n  if (elem.addEventListener) elem.addEventListener(eventType, callback, NO);\n  else if (elem.attachEvent) elem.attachEvent(onStr(eventType), callback);      \n  else throw(\"cannot add listener to element: \" + elem);\n};\n\n/**\n  Removes a listener for the event.  No need to do any special buffering; just\n  remove the listener in a platform-specific way\n  \n  @param {Object} elem the target element if any. otherwise use document\n  @param {String} eventType click, mousedown, etc\n  @param {Function} func function to invoke\n  @returns {void}\n*/\nremove = function(elem, eventType, func) {\n  if (!NATIVE_EVENTS[eventType]) return ;\n  if (!elem) elem = require.env.document;\n  if (elem.removeEventListener) elem.removeEventListener(eventType, func, NO);\n  else if (elem.detachEvent) elem.detachEvent(onStr(eventType), func);\n  else throw(\"cannot remove listener from element: \" + elem);\n};\n\n// make this API visible as the events property on package\nevent = exports;\n;exports.add = add;\nexports.remove = remove;\nexports.event = event;\nexports.ready = ready;\nexports.unload = unload;\nexports.NATIVE_EVENTS = NATIVE_EVENTS;\n");
tiki.module("tiki/platform/classic:lib/info","var browser,userAgent,info;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n/*globals browser userAgent info exports */\n\n\"export browser userAgent\";\n\"export package info\";\n\n/**\n  @file\n\n  Export constants in this module that describe the capabilities of the target\n  platform.  The most important property you can define here is HTML\n*/\n\n\n// ..........................................................\n// BROWSER DESCRIPTION\n// \n\nuserAgent = navigator.userAgent.toLowerCase();\n\nvar version = (userAgent.match( /.+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)/ ) || [])[1];\n\nbrowser = {\n  \n  /** The current browser version */\n  version: version,\n  \n  /** non-zero if webkit-based browser */\n  safari: (/webkit/).test( userAgent ) ? version : 0,\n  \n  /** non-zero if this is an opera-based browser */\n  opera: (/opera/).test( userAgent ) ? version : 0,\n  \n  /** non-zero if this is IE */\n  msie: (/msie/).test( userAgent ) && !(/opera/).test( userAgent ) ? version : 0,\n  \n  /** non-zero if this is a miozilla based browser */\n  mozilla: (/mozilla/).test( userAgent ) && !(/(compatible|webkit)/).test( userAgent ) ? version : 0,\n  \n  /** non-zero if this is mobile safari */\n  mobileSafari: (/apple.*mobile.*safari/).test(userAgent) ? version : 0,\n  \n  /** non-zero if we are on windows */\n  windows: !!(/(windows)/).test(userAgent),\n  \n  /** non-zero if we are on a mac */\n  mac: !!((/(macintosh)/).test(userAgent) || (/(mac os x)/).test(userAgent)),\n  \n  language: (navigator.language || navigator.browserLanguage).split('-', 1)[0]\n};\n\nbrowser.isOpera = !!browser.opera;\nbrowser.isIe = browser.msie;\nbrowser.isIE = browser.msie;\nbrowser.isSafari = browser.safari;\nbrowser.isMobileSafari = browser.mobileSafari;\nbrowser.isMozilla = browser.mozilla;\nbrowser.isWindows = browser.windows;\nbrowser.isMac = browser.mac;\n\n/**\n  The current browser name.  This is useful for switch statements. \n*/\nbrowser.current = \n  browser.msie ? 'msie' : \n  browser.mozilla ? 'mozilla' : \n  browser.safari ? 'safari' : \n  browser.opera ? 'opera' : 'unknown' ;\n\n\n// make this module visible as \"info\"\ninfo = exports ;\n;exports.browser = browser;\nexports.userAgent = userAgent;\nexports.info = info;\n");
tiki.module("tiki/platform/classic:lib/timer",function(require,exports,module){var schedule,repeat,cancel,timer;
"export schedule repeat cancel";"export package timer";"use factory_format function";
schedule=function(after,callback,target){var ret,func;func=target?function(){callback.call(target,ret);
}:callback;ret=setTimeout(after,func);callback=null;return ret;};repeat=function(after,callback,target){var ret,func;
func=target?function(){callback.call(target,ret);}:callback;ret=setInterval(after,func);
callback=null;return ret;};cancel=function(timer,repeats){if(repeats===undefined){clearTimeout(timer);
clearInterval(timer);}else{if(repeats){clearInterval(timer);}else{clearTimeout(timer);
}}};timer=exports;exports.schedule=schedule;exports.repeat=repeat;exports.cancel=cancel;
exports.timer=timer;});tiki.module("tiki/platform/classic:package",function(require,exports,module){var m;
m=require("tiki/platform/classic:lib/console");exports.console=m.console;m=require("tiki/platform/classic:lib/event");
exports.event=m.event;exports.ready=m.ready;exports.unload=m.unload;exports.NATIVE_EVENTS=m.NATIVE_EVENTS;
m=require("tiki/platform/classic:lib/info");exports.info=m.info;m=require("tiki/platform/classic:lib/timer");
exports.timer=m.timer;});tiki.script("tiki/platform/classic:en/9f6d82903c6accdda661e6d567f7d6f7fd335392/javascript.js");
tiki.register("tiki/system",{"depends":["tiki","tiki/platform/classic"],"packages":{"tiki/platform/classic":{},"tiki":{}},"scripts":[{"url":"/static/tiki/system/en/2914de37845aac6a9ada3efb6531c59f9735086e/javascript.js","id":"tiki/system:en/2914de37845aac6a9ada3efb6531c59f9735086e/javascript.js"}]});
tiki.module("tiki/system:core","var T_ERROR,T_OBJECT,T_NULL,T_CLASS,T_HASH,T_FUNCTION,T_UNDEFINED,T_NUMBER,T_BOOL,T_ARRAY,T_STRING,T_BOOLEAN,YES,NO,isArray,typeOf,A,generateGuid,guidFor,mixin,setupDisplayNames;// ==========================================================================\n// Project:   SproutCore System Package\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n/*globals T_ERROR T_OBJECT T_NULL T_CLASS T_HASH T_FUNCTION T_NUMBER T_BOOL T_ARRAY T_UNDEFINED T_STRING YES NO isArray typeOf A generateGuid guidFor */\n\n\"export T_ERROR T_OBJECT T_NULL T_CLASS T_HASH T_FUNCTION T_UNDEFINED T_NUMBER T_BOOL T_ARRAY T_STRING T_BOOLEAN\";\n\"export YES NO isArray typeOf A generateGuid guidFor mixin setupDisplayNames\";\n\n// define standard type constants\nT_ERROR     = 'error';\nT_OBJECT    = 'object';\nT_NULL      = 'null';\nT_CLASS     = 'class';\nT_HASH      = 'hash';\nT_FUNCTION  = 'function';\nT_UNDEFINED = 'undefined';\nT_NUMBER    = 'number';\nT_BOOL      = 'boolean';\nT_ARRAY     = 'array';\nT_STRING    = 'string';\nT_BOOLEAN   = 'boolean';\n\nYES         = true;\nNO          = false; \n\n/**\n  Returns true if the passed item is an array.  Works regardless of source\n  of array.\n*/\nisArray = function(obj) {\n  if (obj && obj.isArray) return true; // fast path\n  if (!obj) return false;\n  if (T_UNDEFINED !== typeof obj.length) {\n    if ((typeof obj !== T_FUNCTION) && (typeof obj !== T_STRING) && (obj.constructor !== String)) return true;\n  }\n  // TODO: add proper check that works across windows...\n  return false ;  \n};\n\nArray.prototype.isArray = true ;\n  \n/**\n  Returns a consistant type for the passed item.\n\n  Use this instead of the built-in typeOf() to get the type of an item. \n  It will return the same result across all browsers and includes a bit \n  more detail.  Here is what will be returned:\n\n  | Return Value Constant | Meaning |\n  | SC.T_STRING | String primitive |\n  | SC.T_NUMBER | Number primitive |\n  | SC.T_BOOLEAN | Boolean primitive |\n  | SC.T_NULL | Null value |\n  | SC.T_UNDEFINED | Undefined value |\n  | SC.T_FUNCTION | A function |\n  | SC.T_ARRAY | An instance of Array |\n  | SC.T_CLASS | A SproutCore class (created using SC.Object.extend()) |\n  | SC.T_OBJECT | A SproutCore object instance |\n  | SC.T_HASH | A JavaScript object not inheriting from SC.Object |\n\n  @param item {Object} the item to check\n  @returns {String} the type\n*/  \ntypeOf = function typeOf(item) {\n  if (item === undefined) return T_UNDEFINED ;\n  if (item === null) return T_NULL ; \n  \n  var ret = typeof(item) ;\n  if (ret == \"object\") {\n    if (isArray(item)) ret = T_ARRAY ;\n    else if (item instanceof Function) {\n      ret = item.isClass ? T_CLASS : T_FUNCTION ;\n    } else if ((item instanceof Error) || item.isError) ret = T_ERROR;\n    else if (item.isObject) ret = T_OBJECT ;\n    else if (item.isClass) ret = T_CLASS;\n    else if (item.constructor === Object) ret = T_HASH;\n    else if (item.constructor === Number) ret = T_NUMBER;\n    else if (item.constructor === String) ret = T_STRING;\n    else ret = T_OBJECT;\n\n  } else if (ret === T_FUNCTION) ret = item.isClass ? T_CLASS : T_FUNCTION;\n  \n  return ret ;\n};\n  \n/**\n  Converts the passed object to an Array.  If the object appears to be \n  array-like, a new array will be cloned from it.  Otherwise, a new array\n  will be created with the item itself as the only item in the array.\n  \n  @param object {Object} any enumerable or array-like object.\n  @returns {Array} Array of items\n*/\nA = function A(obj) {\n  // null or undefined -- fast path\n  if ((obj === null) || (obj === undefined)) return [] ;\n  \n  // primitive -- fast path\n  if (obj.slice instanceof Function) {\n    // do we have a string?\n    if (typeof(obj) === 'string') return [obj] ;\n    else return obj.slice() ;\n  }\n  \n  // enumerable -- fast path\n  if (obj.toArray) return obj.toArray() ;\n  \n  // if not array-like, then just wrap in array.\n  if (!isArray(obj)) return [obj];\n  \n  // when all else fails, do a manual convert...\n  var ret = [], len = obj.length;\n  while(--len >= 0) ret[len] = obj[len];\n  return ret ;\n};\n  \nvar guidKey = \"_sc_guid_\" + new Date().getTime();\nvar _nextGUID = 0, _numberGuids = [], _stringGuids = [];\n\n/**\n  Generates a new guid, optionally saving the guid to the object that you\n  pass in.  You will rarely need to use this method.  Instead you should\n  call SC.guidFor(obj), which return an existing guid if available.\n\n  @param {Object} obj the object to assign the guid to\n  @returns {String} the guid\n*/\ngenerateGuid = function generateGuid(obj) { \n  var ret = (\"sc\" + (_nextGUID++)); \n  if (obj) obj[guidKey] = ret ;\n  return ret ;\n};\n\n/**\n  Returns a unique GUID for the object.  If the object does not yet have\n  a guid, one will be assigned to it.  You can call this on any object,\n  SC.Object-based or not, but be aware that it will add a _guid property.\n\n  You can also use this method on DOM Element objects.\n\n  @param obj {Object} any object, string, number, Element, or primitive\n  @returns {String} the unique guid for this instance.\n*/\nguidFor = function guidFor(obj) {\n  \n  // special cases where we don't want to add a key to object\n  if (obj === undefined) return \"(undefined)\" ;\n  if (obj === null) return '(null)' ;\n  if (obj === Object) return '(Object)';\n  if (obj === Array) return '(Array)';\n  \n  if (obj[guidKey]) return obj[guidKey] ;\n\n  switch(typeof obj) {\n    case T_NUMBER:\n      return (_numberGuids[obj] = _numberGuids[obj] || (\"nu\" + obj));\n    case T_STRING:\n      return (_stringGuids[obj] = _stringGuids[obj] || (\"st\" + obj));\n    case T_BOOL:\n      return obj ? \"(true)\" : \"(false)\" ;\n    default:\n      return generateGuid(obj);\n  }\n};\n\n/**\n  Mixin the passed properties onto the first parameter.  This is a convenient\n  way to add properties to an object.\n  \n  @param {Hash} t the target object to mixin to\n  @param {Hash..} one or more hashes to mix in\n  @returns {Hash} the first parameter\n*/\nmixin = function mixin(t) {\n  \n  // copy reference to target object\n  var len    = arguments.length,\n      target = arguments[0] || {},\n      idx, options, key, src, copy;\n\n  for (idx=1; idx < len; idx++ ) {\n    if (!(options = arguments[idx])) continue ;\n    for(key in options) {\n      if (!options.hasOwnProperty(key)) continue ;\n\n      src  = target[key];\n      copy = options[key] ;\n      if (target===copy) continue ; // prevent never-ending loop\n      if (copy !== undefined) target[key] = copy ;\n    }\n  }\n  \n  return target;\n};\n\nvar TMP_ARY = [];\n\n/**\n  Iterate over a property, setting display names on functions as needed. \n*/\nsetupDisplayNames = function setupDisplayNames(obj, root) {\n  var a = TMP_ARY;\n  a[0] = root;\n  \n  var k,v;\n  for(k in obj) {\n    if (!obj.hasOwnProperty(k)) continue ;\n    v = obj[k];\n    if ('function' === typeof v) {\n      a[1] = k;\n      v.displayName = a.join('.');\n    }\n  }\n  \n  a.length = 0;\n  return obj;\n};;exports.T_ERROR = T_ERROR;\nexports.T_OBJECT = T_OBJECT;\nexports.T_NULL = T_NULL;\nexports.T_CLASS = T_CLASS;\nexports.T_HASH = T_HASH;\nexports.T_FUNCTION = T_FUNCTION;\nexports.T_UNDEFINED = T_UNDEFINED;\nexports.T_NUMBER = T_NUMBER;\nexports.T_BOOL = T_BOOL;\nexports.T_ARRAY = T_ARRAY;\nexports.T_STRING = T_STRING;\nexports.T_BOOLEAN = T_BOOLEAN;\nexports.YES = YES;\nexports.NO = NO;\nexports.isArray = isArray;\nexports.typeOf = typeOf;\nexports.A = A;\nexports.generateGuid = generateGuid;\nexports.guidFor = guidFor;\nexports.mixin = mixin;\nexports.setupDisplayNames = setupDisplayNames;\n");
tiki.module("tiki/system:lib/event",'var $m__ = require(\'tiki/system:core\'), T_ERROR=$m__.T_ERROR,T_OBJECT=$m__.T_OBJECT,T_NULL=$m__.T_NULL,T_CLASS=$m__.T_CLASS,T_HASH=$m__.T_HASH,T_FUNCTION=$m__.T_FUNCTION,T_UNDEFINED=$m__.T_UNDEFINED,T_NUMBER=$m__.T_NUMBER,T_BOOL=$m__.T_BOOL,T_ARRAY=$m__.T_ARRAY,T_STRING=$m__.T_STRING,T_BOOLEAN=$m__.T_BOOLEAN,YES=$m__.YES,NO=$m__.NO,isArray=$m__.isArray,typeOf=$m__.typeOf,A=$m__.A,generateGuid=$m__.generateGuid,guidFor=$m__.guidFor,mixin=$m__.mixin,setupDisplayNames=$m__.setupDisplayNames;var $m__ = require(\'tiki/system:lib/invocation\'), Invocation=$m__.Invocation;var $m__ = require(\'tiki/system:lib/platform\'), PLATFORM=$m__.PLATFORM,PLATFORM_PACKAGE=$m__.PLATFORM_PACKAGE,info=$m__.info,env=$m__.env;var ready,unload;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n/*globals ready unload Invocation */\n\n"import core";\n"import lib/invocation";\n"import lib/platform";\n"export package ready unload";\n\nvar platform = require(PLATFORM_PACKAGE);\n\n// ..........................................................\n// READY HANDLER\n// \n\n// called when the document becomes ready.  work through the queue...\nfunction _ready() {\n  var queue = ready.queue, \n      mainQ = ready.mainQ,\n      len   = queue.length,\n      inv, idx;\n\n  ready.isReady = ready.scheduled = YES ;\n  ready.queue = []; // ok to alloc since it is usually only called once\n  ready.mainQ = [];\n  \n  for(idx=0;idx<len;idx++) {\n    inv = queue[idx];\n    inv.invoke();\n    inv.release(); // return to pool\n  }\n\n  // after calling ready handlers, invoke any main functions to start the app\n  len = mainQ.length;\n  for(idx=0;idx<len;idx++) {\n    inv = mainQ[idx];\n    inv.invoke();\n    inv.release(); // return to pool\n  }\n};\n\n/**\n  Call to register methods you want run when the system is ready for the app\n  to run.\n*/\nready = function(target, method, args) {\n  if (ready.isReady) {\n    Invocation.invoke(target, method, arguments, 2);\n    \n  } else {\n    if (!ready.scheduled && platform) platform.ready(_ready);\n    ready.scheduled = YES ;\n    ready.queue.push(Invocation.create(target, method, arguments, 2));\n  }\n  \n  return this ;\n};\n\nready.isReady = NO ;\nready.queue   = [] ;\nready.scheduled = NO ;\nready.mainQ   = [] ; // invocations for main. called after ready\n\nready.main = function(target, method, args) {\n  if (ready.isReady) {\n    Invocation.invoke(target, method, arguments, 2);\n    \n  } else {\n    if (!ready.scheduled && platform) platform.ready(_ready);\n    ready.scheduled = YES ;\n    ready.mainQ.push(Invocation.create(target, method, arguments, 2));\n  }\n  \n  return this ;\n};\n\n// ..........................................................\n// UNLOAD HANDLER\n// \n\nfunction _unload() {\n  var queue = unload.queue, \n      len   = queue.length,\n      inv, idx;\n\n  unload.isUnloaded = unload.scheduled = YES ;\n  unload.queue = [];\n  \n  for(idx=0;idx<len;idx++) {\n    inv = queue[idx];\n    inv.invoke();\n    inv.release(); // return to pool\n  }\n}\n\n/**\n  Call to register methods you want run when the system is about to unload.\n*/\nunload = function(target, method, args) {\n  if (unload.isUnloaded) {\n    Invocation.invoke(target, method, arguments, 2);\n    \n  } else {\n    if (!unload.scheduled && platform) platform.unload(_unload);\n    unload.scheduled = YES;\n    unload.queue.push(Invocation.create(target, method, arguments, 2));\n  }\n  \n  return this ;\n};\n\nunload.isUnloaded = NO;\nunload.queue      = [];\nunload.scheduled  = NO;\n;exports.ready = ready;\nexports.unload = unload;\n');
tiki.module("tiki/system:lib/global",'var global,reset;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n\n"export package global";\n"export reset";\n\n// exports a global object representing the current global.  you can reset \n// the global by importing this module directly.\n\n// if you have env.global, use that\nreset = function() {\n  global = require.env.global || {} ;\n};\n\nreset();\n;exports.global = global;\nexports.reset = reset;\n');
tiki.module("tiki/system:lib/invocation",'var $m__ = require(\'tiki/system:core\'), T_ERROR=$m__.T_ERROR,T_OBJECT=$m__.T_OBJECT,T_NULL=$m__.T_NULL,T_CLASS=$m__.T_CLASS,T_HASH=$m__.T_HASH,T_FUNCTION=$m__.T_FUNCTION,T_UNDEFINED=$m__.T_UNDEFINED,T_NUMBER=$m__.T_NUMBER,T_BOOL=$m__.T_BOOL,T_ARRAY=$m__.T_ARRAY,T_STRING=$m__.T_STRING,T_BOOLEAN=$m__.T_BOOLEAN,YES=$m__.YES,NO=$m__.NO,isArray=$m__.isArray,typeOf=$m__.typeOf,A=$m__.A,generateGuid=$m__.generateGuid,guidFor=$m__.guidFor,mixin=$m__.mixin,setupDisplayNames=$m__.setupDisplayNames;var $m__ = require(\'tiki/system:mixins/retainable\'), Retainable=$m__.Retainable;var Invocation;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n/*globals Invocation */\n\n"import core";\n"import mixins/retainable";\n"export package Invocation";\n\n/**\n  An Invocation captures a target, method and zero or more arguments to be \n  called at a later time.  Invocations are retainable so you can control when\n  they are destroyed.\n  \n  Note that if you pass a string to the method param, this string will not \n  be resolved to a function until you actually invoke it.  This means you can\n  potentially swap out the method between invocations.\n  \n  @since SproutCore 1.1\n*/\nInvocation = function Invocation(target, method, args) {\n  return this.init(target, method, args);\n};\n\nmixin(Invocation.prototype, Retainable, {\n  \n  constructor: Invocation,\n  \n  /**\n    Initializes the invocation.  This is called when you first create the \n    invocation.\n  */\n  init: function(target, method, args, ignore) {\n    if (args && (ignore !== undefined)) {\n      if (args.length>ignore) args = Array.prototype.slice.call(args, ignore);\n      else args = null; // nothing to curry\n    }\n    \n    this.inPool = NO; // for debug\n    this.target = target;\n    this.method = method;\n    this.args   = args;\n    return this ;\n  },\n  \n  /**\n    Destroys the invocation.  Called when the retain count hits zero.  This\n    will return the invocation to the pool.\n  */\n  destroy: function() {\n    // reset retainable\n    this.isDestroyed = NO;\n    this.retainCount = 1;\n    this.inPool      = YES;\n    this.target = this.method = this.args = null;\n    pool.push(this); // add back to pool\n    \n    return this ;\n  },\n  \n  /**\n    Invokes the method.  Any passed arguments will be curried onto existing\n    arguments.\n    \n    @returns {Object} return value of invoked method.\n  */\n  invoke: function() {\n    return Invocation.invoke(this.target, this.method, this.args, undefined, arguments);\n  }\n  \n});\n\nvar pool = [];\n\n/**\n  Creates a new invocation.  This method will use a memory pool if possible to\n  avoid allocing memory.\n  \n  @param {Object} target target to invoke\n  @param {Function|String} method function or name of method to invoke\n  @param {Array} args zero or more arguments.  optional\n  @param {Number} ignore if passed, ignores this many items from the args\n  @returns {Invocation} new instance\n*/\nInvocation.create = function(target, method, args, ignore) {\n  if (pool.length>0) return pool.pop().init(target,method,args,ignore);\n  else return new Invocation(target, method, args, ignore);\n};\n\n/**\n  Invokes the passed target, method, and arguments.  This is an optimized \n  version that may not actually create an invocation.\n*/\n/**\n  Invokes the invocation.  Return value of invocation is returned.  Any \n  additional arguments will be curried onto the end of any existing args.\n*/\nInvocation.invoke = function(target, method, args, ignore, extra) {\n\n  // normalize method\n  if (typeOf(method) === T_STRING) method = target[method];\n  if (!method) throw("Invocation: method " + this.method + " not defined");\n  \n  // normalize arguments - also curry any extra arguments\n  if ((ignore !== undefined) && args) {\n    if (args.length>ignore) args = Array.prototype.slice.call(args, ignore);\n    else args = null;\n  }\n  if (extra && extra.length>0) args = args ? args.concat(extra) : extra;\n  \n  // and finally invoke\n  return args ? method.apply(target, args) : method.call(target);\n};\n\n;exports.Invocation = Invocation;\n');
tiki.module("tiki/system:lib/logger","var core = require('tiki/system:core');var $m__ = require('tiki/system:lib/platform'), PLATFORM=$m__.PLATFORM,PLATFORM_PACKAGE=$m__.PLATFORM_PACKAGE,info=$m__.info,env=$m__.env;var Logger,console;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n/*globals Logger console core */\n\n\"import core as core\";\n\"import lib/platform\";\n\"export package Logger console\";\n\n/** \n  @file\n\n  Module defines generic functions that can be used to log output into a \n  string or file.\n  \n  The Logger class defined in this module implements the generic Logger API,\n  which includes warn(), info(), error(), debug() and log().  \n  \n  The console object logs this to a system-provided console (on browsers this\n  is equivalent to the system-provided console).\n\n  @since Tiki 1.0\n*/\n\n// get the platform console\nvar pconsole = require(PLATFORM_PACKAGE).console;\n\n/**\n  Logger class defines a standard logger.  If you attach a console, then the\n  logger will record its own results AND forward any output to the console \n  itself.  \n  \n  A default logger is usually created and exported as \"console\" that will \n  attach to the platform console.  You can create a new logger if you want as \n  well.\n\n  @since Tiki 1.0\n*/\nLogger = function Logger(id, console) {\n  this.id = id ;\n  this.console = console;\n  return this ;\n};\n\nvar COLON = ': ', NEWLINE = \"\\n\", TILDA = ' ~ ';\n\nLogger.prototype = {\n  \n  /**\n    Emits count number of lines (or 100 lines if not specified) as a single\n    string.\n    \n    @property {Number} count number of lines to display. optional\n    @returns {String} logged output\n  */\n  tail: function(count) {\n    var lines = this._lines,\n        len   = lines ? lines.length : 0,\n        idx, ret;\n\n    if (len===0) return '';\n\n    if (count === undefined) count = 100;\n    ret = [];\n    for(idx = Math.max(0, len - count); idx < len; idx++) {\n      \n      if (this.id) {\n        ret.push(this.id);\n        ret.push(TILDA);\n      }\n      if (lines[idx].kind) {\n        ret.push(lines[idx].kind);\n        ret.push(COLON);\n      }\n      ret.push(lines[idx].message);\n      ret.push(NEWLINE);      \n    }\n    \n    return ret.join(\"\");\n  },\n  \n  /**\n    Clears the log contents\n    \n    @returns {Logger} reciever\n  */\n  clear: function() {\n    this._lines = null;\n    return this ;\n  },\n  \n  /**\n    Adds a line to the log.  Pass the log type and message.\n    \n    @param {String} kind kind of log message.  should be WARN, DBEUG, or null\n    @param {String} message message to log\n    @returns {Logger} reciever\n  */\n  push: function(kind, message) {\n    var lines = this._lines;\n    if (!lines) lines = this._lines = [];\n    lines.push({ kind: kind, message: message });\n  },\n  \n  /**\n    Logs a debug statement.\n    \n    @param {String} msg one or more items to log\n    @returns {void} \n  */\n  debug: function(msg) {\n    this.push('DEBUG', core.A(arguments));\n    \n    var console = this.console;\n    if (console && console.debug) console.debug.apply(console, arguments);\n  },\n  \n  /**\n    Logs an info statement.\n    \n    @param {String} msg one or more items to log\n    @returns {void}\n  */\n  info: function(msg) {\n    this.push('INFO', core.A(arguments));\n    \n    var console = this.console;\n    if (console && console.info) console.info.apply(console, arguments);\n  },\n  \n  /**\n    Logs a warning\n    \n    @param {String} msg one or more items to log\n    @returns {void}\n  */\n  warn: function(msg) {\n    this.push('WARN', core.A(arguments));\n    \n    var console = this.console;\n    if (console && console.warn) console.warn.apply(console, arguments);\n  },\n  \n  /**\n    Logs an error.\n    \n    @param {String} msg one or mroe items to log\n    @returns {void}\n  */\n  error: function(msg) {\n    this.push('ERROR', core.A(arguments));\n    \n    var console = this.console;\n    if (console && console.error) console.error.apply(console, arguments);\n  },\n  \n  /**\n    Begins a group stack.\n  */\n  group: function(groupName) {\n    this.push('GROUP', groupName);\n    \n    var console = this.console;\n    if (console && console.group) console.group(groupName);\n  },\n  \n  /**\n    Ends a group stack\n  */\n  groupEnd: function(groupName) {\n    this.push('','');\n    \n    var console = this.console;\n    if (console && console.groupEnd) console.groupEnd(groupName);\n  },\n  \n  toString: function() {\n    var len = this._lines ? this._lines.length : 0;\n    return \"Logger<id=\" + this.id + \" size=\" + len + \">\";\n  }\n    \n};\nLogger.prototype.log = Logger.prototype.info;\n\nconsole = new Logger('console', pconsole);\n;exports.Logger = Logger;\nexports.console = console;\n");
tiki.module("tiki/system:lib/platform",function(require,exports,module){var PLATFORM,PLATFORM_PACKAGE,info,env;
"export package PLATFORM PLATFORM_PACKAGE info env";"use factory_format function";
PLATFORM_PACKAGE=null;PLATFORM=platform="unknown";env=require.env;if(env){platform=PLATFORM=env.PLATFORM||env.platform;
PLATFORM_PACKAGE=env.PLATFORM_PACKAGE||env.platformPackage;if(!PLATFORM_PACKAGE&&platform){PLATFORM_PACKAGE="platform/"+platform;
}}info=require(PLATFORM_PACKAGE).info;exports.PLATFORM=PLATFORM;exports.PLATFORM_PACKAGE=PLATFORM_PACKAGE;
exports.info=info;exports.env=env;});tiki.module("tiki/system:mixins/retainable",'var Retainable;// ==========================================================================\n// Project:   Tiki\n// Copyright: \u00a92009 Apple Inc.\n// ==========================================================================\n/*globals Retainable */\n\n\n"export package Retainable";\n\n/**\n  Makes an object retainable.  Retainable objects have a retain count you can\n  increment and decrement.  When the retain count reaches zero, the object is\n  destroyed (by calling destroy).  \n  \n  Use this mixin for objects that need to have their memory carefully \n  controlled (such as events).  This also allows you to write objects that\n  are pooled.\n  \n  @since SproutCore 1.1\n*/\nRetainable = {\n  \n  /**\n    Number of objects retaining this object.  When this reaches zero, the\n    object will be destroyed.\n  */\n  retainCount: 1,\n  \n  /**\n    Becomes true when the object is destroyed.\n  */\n  isDestroyed: false,\n  \n  /**\n    Call to retain the object\n    \n    @returns {Object} receiver\n  */\n  retain: function() {\n    this.retainCount++;\n    return this ;\n  },\n  \n  /** \n    Call to release the object.  May cause it to be destroyed.\n    \n    @returns {Object} receiver\n  */\n  release: function() {\n    if (--this.retainCount <= 0) this.__destroy();\n    return this;\n  },\n  \n  __destroy: function() {\n    if (!this.isDestroyed) {\n      this.isDestroyed = true;\n      if (this.destroy) this.destroy();\n    }\n  }\n  \n};\n\n\n;exports.Retainable = Retainable;\n');
tiki.module("tiki/system:package",function(require,exports,module){var m;m=require("tiki/system:lib/event");
exports.ready=m.ready;exports.unload=m.unload;m=require("tiki/system:lib/global");
exports.global=m.global;m=require("tiki/system:lib/invocation");exports.Invocation=m.Invocation;
m=require("tiki/system:lib/logger");exports.Logger=m.Logger;exports.console=m.console;
m=require("tiki/system:lib/platform");exports.PLATFORM=m.PLATFORM;exports.PLATFORM_PACKAGE=m.PLATFORM_PACKAGE;
exports.info=m.info;exports.env=m.env;m=require("tiki/system:mixins/retainable");
exports.Retainable=m.Retainable;});tiki.script("tiki/system:en/2914de37845aac6a9ada3efb6531c59f9735086e/javascript.js");
tiki.register("core_test",{"depends":["tiki","tiki/system"],"packages":{"tiki/system":{},"tiki":{}},"scripts":[{"url":"/static/core_test/en/e8c5b9533d139513ec785d2963756d97f3689319/javascript.js","id":"core_test:en/e8c5b9533d139513ec785d2963756d97f3689319/javascript.js"}]});
tiki.module("core_test:package",function(require,exports,module){var m;});tiki.script("core_test:en/e8c5b9533d139513ec785d2963756d97f3689319/javascript.js");
tiki.register("sproutcore/runtime",{"depends":["tiki/system"],"packages":{"tiki/system":{}},"scripts":[{"url":"/static/sproutcore/runtime/en/cca71b2c8ec71645c88d40a948f81436bff9a7f3/javascript.js","id":"sproutcore/runtime:en/cca71b2c8ec71645c88d40a948f81436bff9a7f3/javascript.js"}]});
/* @license
==========================================================================
SproutCore Costello -- Property Observing Library
Copyright ©2006-2009, Sprout Systems, Inc. and contributors.
Portions copyright ©2008-2009 Apple Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.

For more information about SproutCore, visit http://www.sproutcore.com

==========================================================================
@license */
"use modules false";
tiki.module("sproutcore/runtime:core",function(require,exports,module){var system=require("tiki/system:package");
var SC,SproutCore,YES,NO;"require license";"import tiki/system:package as system";
"export package SC SproutCore YES NO";YES=true;NO=false;var UNDEFINED="undefined";
if(UNDEFINED===typeof console){console=system.console;}if(UNDEFINED===typeof sc_require){sc_require=function(){};
}if(UNDEFINED===typeof sc_resource){sc_resource=function(){};}SC=SproutCore={};SC.global=function(key,value){system.global[key]=value;
return SC;};SC.global.remove=function(key){delete system.global[key];return SC;};
SC.global("SC",SC);SC.mixin=function(){var target=arguments[0]||{};var idx=1;var length=arguments.length;
var options;if(length===1){target=this||{};idx=0;}for(;idx<length;idx++){if(!(options=arguments[idx])){continue;
}for(var key in options){if(!options.hasOwnProperty(key)){continue;}var copy=options[key];
if(target===copy){continue;}if(copy!==undefined){target[key]=copy;}}}return target;
};SC.supplement=function(){var target=arguments[0]||{};var idx=1;var length=arguments.length;
var options;if(length===1){target=this||{};idx=0;}for(;idx<length;idx++){if(!(options=arguments[idx])){continue;
}for(var key in options){if(!options.hasOwnProperty(key)){continue;}var src=target[key];
var copy=options[key];if(target===copy){continue;}if(copy!==undefined&&src===undefined){target[key]=copy;
}}}return target;};SC.extend=SC.mixin;SC.mixin({T_ERROR:"error",T_OBJECT:"object",T_NULL:"null",T_CLASS:"class",T_HASH:"hash",T_FUNCTION:"function",T_UNDEFINED:"undefined",T_NUMBER:"number",T_BOOL:"boolean",T_ARRAY:"array",T_STRING:"string",typeOf:function(item){if(item===undefined){return SC.T_UNDEFINED;
}if(item===null){return SC.T_NULL;}var ret=typeof(item);if(ret=="object"){if(item instanceof Array){ret=SC.T_ARRAY;
}else{if(item instanceof Function){ret=item.isClass?SC.T_CLASS:SC.T_FUNCTION;}else{if(SC.Error&&(item instanceof SC.Error)){ret=SC.T_ERROR;
}else{if(item.isObject===true){ret=SC.T_OBJECT;}else{ret=SC.T_HASH;}}}}}else{if(ret===SC.T_FUNCTION){ret=(item.isClass)?SC.T_CLASS:SC.T_FUNCTION;
}}return ret;},none:function(obj){return obj===null||obj===undefined;},empty:function(obj){return obj===null||obj===undefined||obj==="";
},isArray:function(obj){if(obj&&obj.objectAt){return YES;}var len=(obj?obj.length:null),type=SC.typeOf(obj);
return !(SC.none(len)||(type===SC.T_FUNCTION)||(type===SC.T_STRING)||obj.setInterval);
},makeArray:function(obj){return SC.isArray(obj)?obj:SC.A(obj);},A:function(obj){if(SC.none(obj)){return[];
}if(obj.slice instanceof Function){if(typeof(obj)==="string"){return[obj];}else{return obj.slice();
}}if(obj.toArray){return obj.toArray();}if(!SC.isArray(obj)){return[obj];}var ret=[],len=obj.length;
while(--len>=0){ret[len]=obj[len];}return ret;},guidKey:"_sc_guid_"+new Date().getTime(),_nextGUID:0,_numberGuids:[],_stringGuids:{},_keyCache:{},guidFor:function(obj){if(obj===undefined){return"(undefined)";
}if(obj===null){return"(null)";}if(obj===Object){return"(Object)";}if(obj===Array){return"(Array)";
}var guidKey=this.guidKey;if(obj[guidKey]){return obj[guidKey];}switch(typeof obj){case SC.T_NUMBER:return(this._numberGuids[obj]=this._numberGuids[obj]||("nu"+obj));
case SC.T_STRING:return(this._stringGuids[obj]=this._stringGuids[obj]||("st"+obj));
case SC.T_BOOL:return(obj)?"(true)":"(false)";default:return SC.generateGuid(obj);
}},keyFor:function(prefix,key){var ret,pcache=this._keyCache[prefix];if(!pcache){pcache=this._keyCache[prefix]={};
}ret=pcache[key];if(!ret){ret=pcache[key]=prefix+"_"+key;}return ret;},generateGuid:function(obj){var ret=("sc"+(this._nextGUID++));
if(obj){obj[this.guidKey]=ret;}return ret;},hashFor:function(obj){return(obj&&obj.hash&&(typeof obj.hash===SC.T_FUNCTION))?obj.hash():this.guidFor(obj);
},isEqual:function(a,b){if(a===null){return b===null;}else{if(a===undefined){return b===undefined;
}else{return this.hashFor(a)===this.hashFor(b);}}},compare:function(v,w){var type1=SC.typeOf(v);
var type2=SC.typeOf(w);var type1Index=SC.ORDER_DEFINITION.indexOf(type1);var type2Index=SC.ORDER_DEFINITION.indexOf(type2);
if(type1Index<type2Index){return -1;}if(type1Index>type2Index){return 1;}switch(type1){case SC.T_BOOL:case SC.T_NUMBER:if(v<w){return -1;
}if(v>w){return 1;}return 0;case SC.T_STRING:if(v.localeCompare(w)<0){return -1;}if(v.localeCompare(w)>0){return 1;
}return 0;case SC.T_ARRAY:var l=Math.min(v.length,w.length);var r=0;var i=0;while(r===0&&i<l){r=arguments.callee(v[i],w[i]);
if(r!==0){return r;}i++;}if(v.length<w.length){return -1;}if(v.length>w.length){return 1;
}return 0;case SC.T_OBJECT:if(v.constructor.isComparable===YES){return v.constructor.compare(v,w);
}return 0;default:return 0;}},K:function(){return this;},EMPTY_ARRAY:[],EMPTY_HASH:{},EMPTY_RANGE:{start:0,length:0},beget:function(obj){if(SC.none(obj)){return null;
}var K=SC.K;K.prototype=obj;var ret=new K();K.prototype=null;if(SC.typeOf(obj.didBeget)===SC.T_FUNCTION){ret=obj.didBeget(ret);
}return ret;},copy:function(object){var ret=object;if(object&&object.isCopyable){return object.copy();
}switch(SC.typeOf(object)){case SC.T_ARRAY:if(object.clone&&SC.typeOf(object.clone)===SC.T_FUNCTION){ret=object.clone();
}else{ret=object.slice();}break;case SC.T_HASH:case SC.T_OBJECT:if(object.clone&&SC.typeOf(object.clone)===SC.T_FUNCTION){ret=object.clone();
}else{ret={};for(var key in object){ret[key]=object[key];}}}return ret;},merge:function(){var ret={},len=arguments.length,idx;
for(idx=0;idx<len;idx++){SC.mixin(ret,arguments[idx]);}return ret;},keys:function(obj){var ret=[];
for(var key in obj){ret.push(key);}return ret;},inspect:function(obj){var v,ret=[];
for(var key in obj){v=obj[key];if(v==="toString"){continue;}if(SC.typeOf(v)===SC.T_FUNCTION){v="function() { ... }";
}ret.push(key+": "+v);}return"{"+ret.join(" , ")+"}";},tupleForPropertyPath:function(path,root){if(SC.typeOf(path)===SC.T_ARRAY){return path;
}var key;var stopAt=path.indexOf("*");if(stopAt<0){stopAt=path.lastIndexOf(".");}key=(stopAt>=0)?path.slice(stopAt+1):path;
var obj=this.objectForPropertyPath(path,root,stopAt);return(obj&&key)?[obj,key]:null;
},objectForPropertyPath:function(path,root,stopAt){var loc,nextDotAt,key,max;if(!root){root=system.global;
}if(SC.typeOf(path)===SC.T_STRING){if(stopAt===undefined){stopAt=path.length;}loc=0;
while((root)&&(loc<stopAt)){nextDotAt=path.indexOf(".",loc);if((nextDotAt<0)||(nextDotAt>stopAt)){nextDotAt=stopAt;
}key=path.slice(loc,nextDotAt);root=root.get?root.get(key):root[key];loc=nextDotAt+1;
}if(loc<stopAt){root=undefined;}}else{loc=0;max=path.length;key=null;while((loc<max)&&root){key=path[loc++];
if(key){root=(root.get)?root.get(key):root[key];}}if(loc<max){root=undefined;}}return root;
},STRINGS:{},stringsFor:function(lang,strings){SC.mixin(SC.STRINGS,strings);return this;
}});SC.clone=SC.copy;SC.$A=SC.A;SC.didLoad=SC.K;SC.ORDER_DEFINITION=[SC.T_ERROR,SC.T_UNDEFINED,SC.T_NULL,SC.T_BOOL,SC.T_NUMBER,SC.T_STRING,SC.T_ARRAY,SC.T_HASH,SC.T_OBJECT,SC.T_FUNCTION,SC.T_CLASS];
SC.mixin(Function.prototype,{property:function(){this.dependentKeys=SC.$A(arguments);
var guid=SC.guidFor(this);this.cacheKey="__cache__"+guid;this.lastSetValueKey="__lastValue__"+guid;
this.isProperty=YES;return this;},cacheable:function(aFlag){this.isProperty=YES;if(!this.dependentKeys){this.dependentKeys=[];
}this.isCacheable=(aFlag===undefined)?YES:aFlag;return this;},idempotent:function(aFlag){this.isProperty=YES;
if(!this.dependentKeys){this.dependentKeys=[];}this.isVolatile=(aFlag===undefined)?YES:aFlag;
return this;},observes:function(propertyPaths){var loc=arguments.length,local=null,paths=null;
while(--loc>=0){var path=arguments[loc];if((path.indexOf(".")<0)&&(path.indexOf("*")<0)){if(!local){local=this.localPropertyPaths=[];
}local.push(path);}else{if(!paths){paths=this.propertyPaths=[];}paths.push(path);
}}return this;}});String.prototype.fmt=function(){var args=arguments;var idx=0;return this.replace(/%@([0-9]+)?/g,function(s,argIndex){argIndex=(argIndex)?parseInt(argIndex,0)-1:idx++;
s=args[argIndex];return((s===null)?"(null)":(s===undefined)?"":s).toString();});};
String.prototype.loc=function(){var str=SC.STRINGS[this]||this;return str.fmt.apply(str,arguments);
};String.prototype.w=function(){var ary=[],ary2=this.split(" "),len=ary2.length;for(var idx=0;
idx<len;++idx){var str=ary2[idx];if(str.length!==0){ary.push(str);}}return ary;};
exports.SC=SC;exports.SproutCore=SproutCore;exports.YES=YES;exports.NO=NO;});tiki.module("sproutcore/runtime:mixins/array",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:mixins/observable");require("sproutcore/runtime:mixins/enumerable");
require("sproutcore/runtime:system/range_observer");"import core";"import mixins/observable";
"import mixins/enumerable";"import system/range_observer";"export package";SC.OUT_OF_RANGE_EXCEPTION="Index out of range";
SC.Array={isSCArray:YES,replace:function(idx,amt,objects){throw"replace() must be implemented to support SC.Array";
},objectAt:function(idx){if(idx<0){return undefined;}if(idx>=this.get("length")){return undefined;
}return this.get(idx);},"[]":function(key,value){if(value!==undefined){this.replace(0,this.get("length"),value);
}return this;}.property(),insertAt:function(idx,object){if(idx>this.get("length")){throw SC.OUT_OF_RANGE_EXCEPTION;
}this.replace(idx,0,[object]);return this;},removeAt:function(start,length){var delta=0,empty=[];
if(typeof start===SC.T_NUMBER){if((start<0)||(start>=this.get("length"))){throw SC.OUT_OF_RANGE_EXCEPTION;
}if(length===undefined){this.replace(start,1,empty);return this;}else{start=SC.IndexSet.create(start,length);
}}this.beginPropertyChanges();start.forEachRange(function(start,length){start-=delta;
delta+=length;this.replace(start,length,empty);},this);this.endPropertyChanges();
return this;},removeObject:function(obj){var loc=this.get("length")||0;while(--loc>=0){var curObject=this.objectAt(loc);
if(curObject==obj){this.removeAt(loc);}}return this;},removeObjects:function(objects){this.beginPropertyChanges();
objects.forEach(function(obj){this.removeObject(obj);},this);this.endPropertyChanges();
return this;},pushObject:function(obj){this.insertAt(this.get("length"),obj);return obj;
},pushObjects:function(objects){this.beginPropertyChanges();objects.forEach(function(obj){this.pushObject(obj);
},this);this.endPropertyChanges();return this;},popObject:function(){var len=this.get("length");
if(len===0){return undefined;}var ret=this.objectAt(len-1);this.removeAt(len-1);return ret;
},shiftObject:function(){if(this.get("length")===0){return undefined;}var ret=this.objectAt(0);
this.removeAt(0);return ret;},unshiftObject:function(obj){this.insertAt(0,obj);return obj;
},unshiftObjects:function(objects){this.beginPropertyChanges();objects.forEach(function(obj){this.unshiftObject(obj);
},this);this.endPropertyChanges();return this;},isEqual:function(ary){if(!ary){return false;
}if(ary==this){return true;}var loc=ary.get("length");if(loc!=this.get("length")){return false;
}while(--loc>=0){if(!SC.isEqual(ary.objectAt(loc),this.objectAt(loc))){return false;
}}return true;},compact:function(){return this.without(null);},without:function(value){if(this.indexOf(value)<0){return this;
}var ret=[];this.forEach(function(k){if(k!==value){ret[ret.length]=k;}});return ret;
},uniq:function(){var ret=[];this.forEach(function(k){if(ret.indexOf(k)<0){ret[ret.length]=k;
}});return ret;},rangeObserverClass:SC.RangeObserver,addRangeObserver:function(indexes,target,method,context){var rangeob=this._array_rangeObservers;
if(!rangeob){rangeob=this._array_rangeObservers=SC.CoreSet.create();}if(this._array_oldLength===undefined){this._array_oldLength=this.get("length");
}var C=this.rangeObserverClass;var isDeep=NO;var ret=C.create(this,indexes,target,method,context,isDeep);
rangeob.add(ret);if(!this._array_isNotifyingRangeObservers){this._array_isNotifyingRangeObservers=YES;
this.addObserver("[]",this,this._array_notifyRangeObservers);}return ret;},updateRangeObserver:function(rangeObserver,indexes){return rangeObserver.update(this,indexes);
},removeRangeObserver:function(rangeObserver){var ret=rangeObserver.destroy(this);
var rangeob=this._array_rangeObservers;if(rangeob){rangeob.remove(rangeObserver);
}return ret;},enumerableContentDidChange:function(start,amt,delta){var rangeob=this._array_rangeObservers,oldlen=this._array_oldLength,newlen,length,changes;
this.beginPropertyChanges();this.notifyPropertyChange("length");if(rangeob&&rangeob.length>0){if(oldlen===undefined){oldlen=0;
}this._array_oldLength=newlen=this.get("length");if(start===undefined){start=0;}if(delta===undefined){delta=newlen-oldlen;
}if(delta!==0||amt===undefined){length=newlen-start;if(delta<0){length-=delta;}}else{length=amt;
}changes=this._array_rangeChanges;if(!changes){changes=this._array_rangeChanges=SC.IndexSet.create();
}changes.add(start,length);}this.notifyPropertyChange("[]");this.endPropertyChanges();
return this;},_array_notifyRangeObservers:function(){var rangeob=this._array_rangeObservers,changes=this._array_rangeChanges,len=rangeob?rangeob.length:0,idx,cur;
if(len>0&&changes&&changes.length>0){for(idx=0;idx<len;idx++){rangeob[idx].rangeDidChange(changes);
}changes.clear();}}};SC.mixin(Array.prototype,SC.Array);SC.Array=SC.mixin({},SC.Enumerable,SC.Array);
SC.Array.slice=function(beginIndex,endIndex){var ret=[];var length=this.get("length");
if(SC.none(beginIndex)){beginIndex=0;}if(SC.none(endIndex)||(endIndex>length)){endIndex=length;
}while(beginIndex<endIndex){ret[ret.length]=this.objectAt(beginIndex++);}return ret;
};SC.Array.indexOf=function(object,startAt){var idx,len=this.get("length");if(startAt===undefined){startAt=0;
}else{startAt=(startAt<0)?Math.ceil(startAt):Math.floor(startAt);}if(startAt<0){startAt+=len;
}for(idx=startAt;idx<len;idx++){if(this.objectAt(idx)===object){return idx;}}return -1;
};if(!Array.prototype.indexOf){Array.prototype.indexOf=SC.Array.indexOf;}SC.Array.lastIndexOf=function(object,startAt){var idx,len=this.get("length");
if(startAt===undefined){startAt=len-1;}else{startAt=(startAt<0)?Math.ceil(startAt):Math.floor(startAt);
}if(startAt<0){startAt+=len;}for(idx=startAt;idx>=0;idx--){if(this.objectAt(idx)===object){return idx;
}}return -1;};if(!Array.prototype.lastIndexOf){Array.prototype.lastIndexOf=SC.Array.lastIndexOf;
}(function(){SC.mixin(Array.prototype,{replace:function(idx,amt,objects){if(this.isFrozen){throw SC.FROZEN_ERROR;
}if(!objects||objects.length===0){this.splice(idx,amt);}else{var args=[idx,amt].concat(objects);
this.splice.apply(this,args);}var len=objects?(objects.get?objects.get("length"):objects.length):0;
this.enumerableContentDidChange(idx,amt,len-amt);return this;},unknownProperty:function(key,value){var ret=this.reducedProperty(key,value);
if((value!==undefined)&&ret===undefined){ret=this[key]=value;}return ret;}});var indexOf=Array.prototype.indexOf;
if(!indexOf||(indexOf===SC.Array.indexOf)){Array.prototype.indexOf=function(object,startAt){var idx,len=this.length;
if(startAt===undefined){startAt=0;}else{startAt=(startAt<0)?Math.ceil(startAt):Math.floor(startAt);
}if(startAt<0){startAt+=len;}for(idx=startAt;idx<len;idx++){if(this[idx]===object){return idx;
}}return -1;};}var lastIndexOf=Array.prototype.lastIndexOf;if(!lastIndexOf||(lastIndexOf===SC.Array.lastIndexOf)){Array.prototype.lastIndexOf=function(object,startAt){var idx,len=this.length;
if(startAt===undefined){startAt=len-1;}else{startAt=(startAt<0)?Math.ceil(startAt):Math.floor(startAt);
}if(startAt<0){startAt+=len;}for(idx=startAt;idx>=0;idx--){if(this[idx]===object){return idx;
}}return -1;};}})();});tiki.module("sproutcore/runtime:mixins/comparable",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";"export package";SC.Comparable={isComparable:YES,compare:function(a,b){throw"%@.compare() is not implemented".fmt(this.toString());
}};});tiki.module("sproutcore/runtime:mixins/copyable",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";"export package";SC.Copyable={isCopyable:YES,copy:function(){throw"%@.copy() is not implemented";
},frozenCopy:function(){var isFrozen=this.get?this.get("isFrozen"):this.isFrozen;
if(isFrozen===YES){return this;}else{if(isFrozen===undefined){throw"%@ does not support freezing".fmt(this);
}else{return this.copy().freeze();}}}};SC.mixin(Array.prototype,SC.Copyable);Array.prototype.copy=Array.prototype.slice;
});tiki.module("sproutcore/runtime:mixins/delegate_support",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";"export package";SC.DelegateSupport={delegateFor:function(methodName){var idx=1,len=arguments.length,ret;
while(idx<len){ret=arguments[idx];if(ret&&ret[methodName]!==undefined){return ret;
}idx++;}return(this[methodName]!==undefined)?this:null;},invokeDelegateMethod:function(delegate,methodName,args){args=SC.A(arguments);
args=args.slice(2,args.length);if(!delegate||!delegate[methodName]){delegate=this;
}var method=delegate[methodName];return method?method.apply(delegate,args):null;},getDelegateProperty:function(key,delegate){var idx=1,len=arguments.length,ret;
while(idx<len){ret=arguments[idx++];if(ret&&ret[key]!==undefined){return ret.get?ret.get(key):ret[key];
}}return(this[key]!==undefined)?this.get(key):undefined;}};});tiki.module("sproutcore/runtime:mixins/enumerable",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/enumerator");"import core";"import system/enumerator";
"export package";SC.Enumerable={isEnumerable:YES,nextObject:function(index,previousObject,context){return this.objectAt?this.objectAt(index):this[index];
},firstObject:function(){if(this.get("length")===0){return undefined;}if(this.objectAt){return this.objectAt(0);
}var context=SC.Enumerator._popContext(),ret;ret=this.nextObject(0,null,context);
context=SC.Enumerator._pushContext(context);return ret;}.property(),enumerator:function(){return SC.Enumerator.create(this);
},forEach:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(target===undefined){target=null;
}var last=null;var context=SC.Enumerator._popContext();for(var idx=0;idx<len;idx++){var next=this.nextObject(idx,last,context);
callback.call(target,next,idx,this);last=next;}last=null;context=SC.Enumerator._pushContext(context);
return this;},getEach:function(key){return this.map(function(next){return next?(next.get?next.get(key):next[key]):null;
},this);},setEach:function(key,value){this.forEach(function(next){if(next){if(next.set){next.set(key,value);
}else{next[key]=value;}}},this);return this;},map:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(target===undefined){target=null;
}var ret=[];var last=null;var context=SC.Enumerator._popContext();for(var idx=0;idx<len;
idx++){var next=this.nextObject(idx,last,context);ret[idx]=callback.call(target,next,idx,this);
last=next;}last=null;context=SC.Enumerator._pushContext(context);return ret;},mapProperty:function(key){return this.map(function(next){return next?(next.get?next.get(key):next[key]):null;
});},filter:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(target===undefined){target=null;
}var ret=[];var last=null;var context=SC.Enumerator._popContext();for(var idx=0;idx<len;
idx++){var next=this.nextObject(idx,last,context);if(callback.call(target,next,idx,this)){ret.push(next);
}last=next;}last=null;context=SC.Enumerator._pushContext(context);return ret;},sortProperty:function(key){var keys=(typeof key===SC.T_STRING)?arguments:key,len=keys.length,src;
if(this instanceof Array){src=this;}else{src=[];this.forEach(function(i){src.push(i);
});}if(!src){return[];}return src.sort(function(a,b){var idx,key,aValue,bValue,ret=0;
for(idx=0;ret===0&&idx<len;idx++){key=keys[idx];aValue=a?(a.get?a.get(key):a[key]):null;
bValue=b?(b.get?b.get(key):b[key]):null;ret=SC.compare(aValue,bValue);}return ret;
});},filterProperty:function(key,value){var len=this.get?this.get("length"):this.length;
var ret=[];var last=null;var context=SC.Enumerator._popContext();for(var idx=0;idx<len;
idx++){var next=this.nextObject(idx,last,context);var cur=next?(next.get?next.get(key):next[key]):null;
var matched=(value===undefined)?!!cur:SC.isEqual(cur,value);if(matched){ret.push(next);
}last=next;}last=null;context=SC.Enumerator._pushContext(context);return ret;},find:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(target===undefined){target=null;
}var last=null,next,found=NO,ret=null;var context=SC.Enumerator._popContext();for(var idx=0;
idx<len&&!found;idx++){next=this.nextObject(idx,last,context);if(found=callback.call(target,next,idx,this)){ret=next;
}last=next;}next=last=null;context=SC.Enumerator._pushContext(context);return ret;
},findProperty:function(key,value){var len=this.get?this.get("length"):this.length;
var found=NO,ret=null,last=null,next,cur;var context=SC.Enumerator._popContext();
for(var idx=0;idx<len&&!found;idx++){next=this.nextObject(idx,last,context);cur=next?(next.get?next.get(key):next[key]):null;
found=(value===undefined)?!!cur:SC.isEqual(cur,value);if(found){ret=next;}last=next;
}last=next=null;context=SC.Enumerator._pushContext(context);return ret;},every:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(target===undefined){target=null;
}var ret=YES;var last=null;var context=SC.Enumerator._popContext();for(var idx=0;
ret&&(idx<len);idx++){var next=this.nextObject(idx,last,context);if(!callback.call(target,next,idx,this)){ret=NO;
}last=next;}last=null;context=SC.Enumerator._pushContext(context);return ret;},everyProperty:function(key,value){var len=this.get?this.get("length"):this.length;
var ret=YES;var last=null;var context=SC.Enumerator._popContext();for(var idx=0;ret&&(idx<len);
idx++){var next=this.nextObject(idx,last,context);var cur=next?(next.get?next.get(key):next[key]):null;
ret=(value===undefined)?!!cur:SC.isEqual(cur,value);last=next;}last=null;context=SC.Enumerator._pushContext(context);
return ret;},some:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(target===undefined){target=null;
}var ret=NO;var last=null;var context=SC.Enumerator._popContext();for(var idx=0;(!ret)&&(idx<len);
idx++){var next=this.nextObject(idx,last,context);if(callback.call(target,next,idx,this)){ret=YES;
}last=next;}last=null;context=SC.Enumerator._pushContext(context);return ret;},someProperty:function(key,value){var len=this.get?this.get("length"):this.length;
var ret=NO;var last=null;var context=SC.Enumerator._popContext();for(var idx=0;!ret&&(idx<len);
idx++){var next=this.nextObject(idx,last,context);var cur=next?(next.get?next.get(key):next[key]):null;
ret=(value===undefined)?!!cur:SC.isEqual(cur,value);last=next;}last=null;context=SC.Enumerator._pushContext(context);
return ret;},reduce:function(callback,initialValue,reducerProperty){if(typeof callback!=="function"){throw new TypeError();
}var len=this.get?this.get("length"):this.length;if(len===0&&initialValue===undefined){throw new TypeError();
}var ret=initialValue;var last=null;var context=SC.Enumerator._popContext();for(var idx=0;
idx<len;idx++){var next=this.nextObject(idx,last,context);if(next!==null){if(ret===undefined){ret=next;
}else{ret=callback.call(null,ret,next,idx,this,reducerProperty);}}last=next;}last=null;
context=SC.Enumerator._pushContext(context);if(ret===undefined){throw new TypeError();
}return ret;},invoke:function(methodName){var len=this.get?this.get("length"):this.length;
if(len<=0){return[];}var idx;var args=[];var alen=arguments.length;if(alen>1){for(idx=1;
idx<alen;idx++){args.push(arguments[idx]);}}var ret=[];var last=null;var context=SC.Enumerator._popContext();
for(idx=0;idx<len;idx++){var next=this.nextObject(idx,last,context);var method=next?next[methodName]:null;
if(method){ret[idx]=method.apply(next,args);}last=next;}last=null;context=SC.Enumerator._pushContext(context);
return ret;},invokeWhile:function(targetValue,methodName){var len=this.get?this.get("length"):this.length;
if(len<=0){return null;}var idx;var args=[];var alen=arguments.length;if(alen>2){for(idx=2;
idx<alen;idx++){args.push(arguments[idx]);}}var ret=targetValue;var last=null;var context=SC.Enumerator._popContext();
for(idx=0;(ret===targetValue)&&(idx<len);idx++){var next=this.nextObject(idx,last,context);
var method=next?next[methodName]:null;if(method){ret=method.apply(next,args);}last=next;
}last=null;context=SC.Enumerator._pushContext(context);return ret;},toArray:function(){var ret=[];
this.forEach(function(o){ret.push(o);},this);return ret;}};SC._buildReducerFor=function(reducerKey,reducerProperty){return function(key,value){var reducer=this[reducerKey];
if(SC.typeOf(reducer)!==SC.T_FUNCTION){return this.unknownProperty?this.unknownProperty(key,value):null;
}else{var ret=SC.Enumerable.reduce.call(this,reducer,null,reducerProperty);return ret;
}}.property("[]");};SC.Reducers={"[]":function(key,value){return this;}.property(),enumerableContentDidChange:function(start,length){this.notifyPropertyChange("[]");
return this;},reducedProperty:function(key,value,generateProperty){if(!key||key.charAt(0)!=="@"){return undefined;
}var matches=key.match(/^@([^(]*)(\(([^)]*)\))?$/);if(!matches||matches.length<2){return undefined;
}var reducerKey=matches[1];var reducerProperty=matches[3];reducerKey="reduce"+reducerKey.slice(0,1).toUpperCase()+reducerKey.slice(1);
var reducer=this[reducerKey];if(SC.typeOf(reducer)!==SC.T_FUNCTION){return undefined;
}if(generateProperty===NO){return SC.Enumerable.reduce.call(this,reducer,null,reducerProperty);
}var func=SC._buildReducerFor(reducerKey,reducerProperty);var p=this.constructor.prototype;
if(p){p[key]=func;var props=p._properties||[];props.push(key);p._properties=props;
this.registerDependentKey(key,"[]");}return SC.Enumerable.reduce.call(this,reducer,null,reducerProperty);
},reduceMax:function(previousValue,item,index,e,reducerProperty){if(reducerProperty&&item){item=item.get?item.get(reducerProperty):item[reducerProperty];
}if(previousValue===null){return item;}return(item>previousValue)?item:previousValue;
},reduceMaxObject:function(previousItem,item,index,e,reducerProperty){var previousValue=previousItem,itemValue=item;
if(reducerProperty){if(item){itemValue=item.get?item.get(reducerProperty):item[reducerProperty];
}if(previousItem){previousValue=previousItem.get?previousItem.get(reducerProperty):previousItem[reducerProperty];
}}if(previousValue===null){return item;}return(itemValue>previousValue)?item:previousItem;
},reduceMin:function(previousValue,item,index,e,reducerProperty){if(reducerProperty&&item){item=item.get?item.get(reducerProperty):item[reducerProperty];
}if(previousValue===null){return item;}return(item<previousValue)?item:previousValue;
},reduceMinObject:function(previousItem,item,index,e,reducerProperty){var previousValue=previousItem,itemValue=item;
if(reducerProperty){if(item){itemValue=item.get?item.get(reducerProperty):item[reducerProperty];
}if(previousItem){previousValue=previousItem.get?previousItem.get(reducerProperty):previousItem[reducerProperty];
}}if(previousValue===null){return item;}return(itemValue<previousValue)?item:previousItem;
},reduceAverage:function(previousValue,item,index,e,reducerProperty){if(reducerProperty&&item){item=item.get?item.get(reducerProperty):item[reducerProperty];
}var ret=(previousValue||0)+item;var len=e.get?e.get("length"):e.length;if(index>=len-1){ret=ret/len;
}return ret;},reduceSum:function(previousValue,item,index,e,reducerProperty){if(reducerProperty&&item){item=item.get?item.get(reducerProperty):item[reducerProperty];
}return(previousValue===null)?item:previousValue+item;}};SC.mixin(SC.Enumerable,SC.Reducers);
SC.mixin(Array.prototype,SC.Reducers);Array.prototype.isEnumerable=YES;(function(){var alwaysMixin={nextObject:SC.Enumerable.nextObject,enumerator:SC.Enumerable.enumerator,firstObject:SC.Enumerable.firstObject,sortProperty:SC.Enumerable.sortProperty,mapProperty:function(key){var len=this.length;
var ret=[];for(var idx=0;idx<len;idx++){var next=this[idx];ret[idx]=next?(next.get?next.get(key):next[key]):null;
}return ret;},filterProperty:function(key,value){var len=this.length;var ret=[];for(var idx=0;
idx<len;idx++){var next=this[idx];var cur=next?(next.get?next.get(key):next[key]):null;
var matched=(value===undefined)?!!cur:SC.isEqual(cur,value);if(matched){ret.push(next);
}}return ret;},find:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(target===undefined){target=null;}var next,ret=null,found=NO;
for(var idx=0;idx<len&&!found;idx++){next=this[idx];if(found=callback.call(target,next,idx,this)){ret=next;
}}next=null;return ret;},findProperty:function(key,value){var len=this.length;var next,cur,found=NO,ret=null;
for(var idx=0;idx<len&&!found;idx++){cur=(next=this[idx])?(next.get?next.get(key):next[key]):null;
found=(value===undefined)?!!cur:SC.isEqual(cur,value);if(found){ret=next;}}next=null;
return ret;},everyProperty:function(key,value){var len=this.length;var ret=YES;for(var idx=0;
ret&&(idx<len);idx++){var next=this[idx];var cur=next?(next.get?next.get(key):next[key]):null;
ret=(value===undefined)?!!cur:SC.isEqual(cur,value);}return ret;},someProperty:function(key,value){var len=this.length;
var ret=NO;for(var idx=0;!ret&&(idx<len);idx++){var next=this[idx];var cur=next?(next.get?next.get(key):next[key]):null;
ret=(value===undefined)?!!cur:SC.isEqual(cur,value);}return ret;},invoke:function(methodName){var len=this.length;
if(len<=0){return[];}var idx;var args=[];var alen=arguments.length;if(alen>1){for(idx=1;
idx<alen;idx++){args.push(arguments[idx]);}}var ret=[];for(idx=0;idx<len;idx++){var next=this[idx];
var method=next?next[methodName]:null;if(method){ret[idx]=method.apply(next,args);
}}return ret;},invokeWhile:function(targetValue,methodName){var len=this.length;if(len<=0){return null;
}var idx;var args=[];var alen=arguments.length;if(alen>2){for(idx=2;idx<alen;idx++){args.push(arguments[idx]);
}}var ret=targetValue;for(idx=0;(ret===targetValue)&&(idx<len);idx++){var next=this[idx];
var method=next?next[methodName]:null;if(method){ret=method.apply(next,args);}}return ret;
},toArray:function(){var len=this.length;if(len<=0){return[];}var ret=[];for(var idx=0;
idx<len;idx++){var next=this[idx];ret.push(next);}return ret;},getEach:function(key){var ret=[];
var len=this.length;for(var idx=0;idx<len;idx++){var obj=this[idx];ret[idx]=obj?(obj.get?obj.get(key):obj[key]):null;
}return ret;},setEach:function(key,value){var len=this.length;for(var idx=0;idx<len;
idx++){var obj=this[idx];if(obj){if(obj.set){obj.set(key,value);}else{obj[key]=value;
}}}return this;}};var mixinIfMissing={forEach:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(target===undefined){target=null;}for(var idx=0;idx<len;idx++){var next=this[idx];
callback.call(target,next,idx,this);}return this;},map:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(target===undefined){target=null;}var ret=[];for(var idx=0;
idx<len;idx++){var next=this[idx];ret[idx]=callback.call(target,next,idx,this);}return ret;
},filter:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(target===undefined){target=null;}var ret=[];for(var idx=0;
idx<len;idx++){var next=this[idx];if(callback.call(target,next,idx,this)){ret.push(next);
}}return ret;},every:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(target===undefined){target=null;}var ret=YES;for(var idx=0;
ret&&(idx<len);idx++){var next=this[idx];if(!callback.call(target,next,idx,this)){ret=NO;
}}return ret;},some:function(callback,target){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(target===undefined){target=null;}var ret=NO;for(var idx=0;
(!ret)&&(idx<len);idx++){var next=this[idx];if(callback.call(target,next,idx,this)){ret=YES;
}}return ret;},reduce:function(callback,initialValue,reducerProperty){if(typeof callback!=="function"){throw new TypeError();
}var len=this.length;if(len===0&&initialValue===undefined){throw new TypeError();
}var ret=initialValue;for(var idx=0;idx<len;idx++){var next=this[idx];if(next!==null){if(ret===undefined){ret=next;
}else{ret=callback.call(null,ret,next,idx,this,reducerProperty);}}}if(ret===undefined){throw new TypeError();
}return ret;}};for(var key in mixinIfMissing){if(!mixinIfMissing.hasOwnProperty(key)){continue;
}if(!Array.prototype[key]||((typeof Prototype==="object")&&Prototype.Version.match(/^1\.6/))){Array.prototype[key]=mixinIfMissing[key];
}}SC.mixin(Array.prototype,alwaysMixin);})();});tiki.module("sproutcore/runtime:mixins/freezable",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";"export package";SC.FROZEN_ERROR=new Error("Cannot modify a frozen object");
SC.Freezable={isFreezable:YES,isFrozen:NO,freeze:function(){if(this.set){this.set("isFrozen",YES);
}else{this.isFrozen=YES;}return this;}};SC.mixin(Array.prototype,SC.Freezable);});
tiki.module("sproutcore/runtime:mixins/observable",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:private/observer_set");require("sproutcore/runtime:private/chain_observer");
"import core";"import private/observer_set";"import private/chain_observer";"export package";
var _inited=false;SC.LOG_OBSERVERS=NO;SC.Observable={isObservable:YES,automaticallyNotifiesObserversFor:function(key){return YES;
},get:function(key){var ret=this[key],cache;if(ret===undefined){return this.unknownProperty(key);
}else{if(ret&&ret.isProperty){if(ret.isCacheable){cache=this._kvo_cache;if(!cache){cache=this._kvo_cache={};
}return(cache[ret.cacheKey]!==undefined)?cache[ret.cacheKey]:(cache[ret.cacheKey]=ret.call(this,key));
}else{return ret.call(this,key);}}else{return ret;}}},set:function(key,value){var func=this[key],notify=this.automaticallyNotifiesObserversFor(key),ret=value,cachedep,cache,idx,dfunc;
if(this._kvo_cacheable&&(cache=this._kvo_cache)){cachedep=this._kvo_cachedep;if(!cachedep||(cachedep=cachedep[key])===undefined){cachedep=this._kvo_computeCachedDependentsFor(key);
}if(cachedep){idx=cachedep.length;while(--idx>=0){dfunc=cachedep[idx];cache[dfunc.cacheKey]=cache[dfunc.lastSetValueKey]=undefined;
}}}if(func&&func.isProperty){cache=this._kvo_cache;if(func.isVolatile||!cache||(cache[func.lastSetValueKey]!==value)){if(!cache){cache=this._kvo_cache={};
}cache[func.lastSetValueKey]=value;if(notify){this.propertyWillChange(key);}ret=func.call(this,key,value);
if(func.isCacheable){cache[func.cacheKey]=ret;}if(notify){this.propertyDidChange(key,ret,YES);
}}}else{if(func===undefined){if(notify){this.propertyWillChange(key);}this.unknownProperty(key,value);
if(notify){this.propertyDidChange(key,ret);}}else{if(this[key]!==value){if(notify){this.propertyWillChange(key);
}ret=this[key]=value;if(notify){this.propertyDidChange(key,ret);}}}}return this;},unknownProperty:function(key,value){if(!(value===undefined)){this[key]=value;
}return value;},beginPropertyChanges:function(){this._kvo_changeLevel=(this._kvo_changeLevel||0)+1;
return this;},endPropertyChanges:function(){this._kvo_changeLevel=(this._kvo_changeLevel||1)-1;
var level=this._kvo_changeLevel,changes=this._kvo_changes;if((level<=0)&&changes&&(changes.length>0)&&!SC.Observers.isObservingSuspended){this._notifyPropertyObservers();
}return this;},propertyWillChange:function(key){return this;},propertyDidChange:function(key,value,_keepCache){this._kvo_revision=(this._kvo_revision||0)+1;
var level=this._kvo_changeLevel||0,cachedep,idx,dfunc,cache,func,log=SC.LOG_OBSERVERS&&!(this.LOG_OBSERVING===NO);
if(this._kvo_cacheable&&(cache=this._kvo_cache)){if(!_keepCache){func=this[key];if(func&&func.isProperty){cache[func.cacheKey]=cache[func.lastSetValueKey]=undefined;
}}cachedep=this._kvo_cachedep;if(!cachedep||(cachedep=cachedep[key])===undefined){cachedep=this._kvo_computeCachedDependentsFor(key);
}if(cachedep){idx=cachedep.length;while(--idx>=0){dfunc=cachedep[idx];cache[dfunc.cacheKey]=cache[dfunc.lastSetValueKey]=undefined;
}}}var suspended=SC.Observers.isObservingSuspended;if((level>0)||suspended){var changes=this._kvo_changes;
if(!changes){changes=this._kvo_changes=SC.CoreSet.create();}changes.add(key);if(suspended){if(log){console.log("%@%@: will not notify observers because observing is suspended".fmt(SC.KVO_SPACES,this));
}SC.Observers.objectHasPendingChanges(this);}}else{this._notifyPropertyObservers(key);
}return this;},registerDependentKey:function(key,dependentKeys){var dependents=this._kvo_dependents,func=this[key],keys,idx,lim,dep,queue;
if(SC.typeOf(dependentKeys)===SC.T_ARRAY){keys=dependentKeys;lim=0;}else{keys=arguments;
lim=1;}idx=keys.length;if(!dependents){this._kvo_dependents=dependents={};}while(--idx>=lim){dep=keys[idx];
queue=dependents[dep];if(!queue){queue=dependents[dep]=[];}queue.push(key);}},_kvo_addCachedDependents:function(queue,keys,dependents,seen){var idx=keys.length,func,key,deps;
while(--idx>=0){key=keys[idx];seen.add(key);func=this[key];if(func&&(func instanceof Function)&&func.isProperty){if(func.isCacheable){queue.push(func);
}if((deps=dependents[key])&&deps.length>0){this._kvo_addCachedDependents(queue,deps,dependents,seen);
}}}},_kvo_computeCachedDependentsFor:function(key){var cached=this._kvo_cachedep,dependents=this._kvo_dependents,keys=dependents?dependents[key]:null,queue,seen;
if(!cached){cached=this._kvo_cachedep={};}if(!keys||keys.length===0){return cached[key]=null;
}queue=cached[key]=[];seen=SC._TMP_SEEN_SET=(SC._TMP_SEEN_SET||SC.CoreSet.create());
seen.add(key);this._kvo_addCachedDependents(queue,keys,dependents,seen);seen.clear();
if(queue.length===0){queue=cached[key]=null;}return queue;},_kvo_for:function(kvoKey,type){var ret=this[kvoKey];
if(!this._kvo_cloned){this._kvo_cloned={};}if(!ret){ret=this[kvoKey]=(type===undefined)?[]:type.create();
this._kvo_cloned[kvoKey]=YES;}else{if(!this._kvo_cloned[kvoKey]){ret=this[kvoKey]=ret.copy();
this._kvo_cloned[kvoKey]=YES;}}return ret;},addObserver:function(key,target,method,context){var kvoKey,chain,chains,observers;
if(method===undefined){method=target;target=this;}if(!target){target=this;}if(SC.typeOf(method)===SC.T_STRING){method=target[method];
}if(!method){throw"You must pass a method to addObserver()";}key=key.toString();if(key.indexOf(".")>=0){chain=SC._ChainObserver.createChain(this,key,target,method,context);
chain.masterTarget=target;chain.masterMethod=method;this._kvo_for(SC.keyFor("_kvo_chains",key)).push(chain);
}else{if((this[key]===undefined)&&(key.indexOf("@")===0)){this.get(key);}if(target===this){target=null;
}kvoKey=SC.keyFor("_kvo_observers",key);this._kvo_for(kvoKey,SC.ObserverSet).add(target,method,context);
this._kvo_for("_kvo_observed_keys",SC.CoreSet).add(key);}if(this.didAddObserver){this.didAddObserver(key,target,method);
}return this;},removeObserver:function(key,target,method){var kvoKey,chains,chain,observers,idx;
if(method===undefined){method=target;target=this;}if(!target){target=this;}if(SC.typeOf(method)===SC.T_STRING){method=target[method];
}if(!method){throw"You must pass a method to addObserver()";}key=key.toString();if(key.indexOf(".")>=0){kvoKey=SC.keyFor("_kvo_chains",key);
if(chains=this[kvoKey]){chains=this._kvo_for(kvoKey);idx=chains.length;while(--idx>=0){chain=chains[idx];
if(chain&&(chain.masterTarget===target)&&(chain.masterMethod===method)){chains[idx]=chain.destroyChain();
}}}}else{if(target===this){target=null;}kvoKey=SC.keyFor("_kvo_observers",key);if(observers=this[kvoKey]){observers=this._kvo_for(kvoKey);
observers.remove(target,method);if(observers.targets<=0){this._kvo_for("_kvo_observed_keys",SC.CoreSet).remove(key);
}}}if(this.didRemoveObserver){this.didRemoveObserver(key,target,method);}return this;
},hasObserverFor:function(key){SC.Observers.flush(this);var observers=this[SC.keyFor("_kvo_observers",key)],locals=this[SC.keyFor("_kvo_local",key)],members;
if(locals&&locals.length>0){return YES;}if(observers&&observers.getMembers().length>0){return YES;
}return NO;},initObservable:function(){if(this._observableInited){return;}this._observableInited=YES;
if(!_inited){_inited=YES;require("sproutcore/runtime:system/binding");require("sproutcore/runtime:private/observer_queue");
}var loc,keys,key,value,observer,propertyPaths,propertyPathsLength;if(keys=this._observers){var len=keys.length;
for(loc=0;loc<len;loc++){key=keys[loc];observer=this[key];propertyPaths=observer.propertyPaths;
propertyPathsLength=(propertyPaths)?propertyPaths.length:0;for(var ploc=0;ploc<propertyPathsLength;
ploc++){var path=propertyPaths[ploc];var dotIndex=path.indexOf(".");if(dotIndex<0){this.addObserver(path,this,observer);
}else{if(path.indexOf("*")===0){this.addObserver(path.slice(1),this,observer);}else{var root=null;
if(dotIndex===0){root=this;path=path.slice(1);}else{if(dotIndex===4&&path.slice(0,5)==="this."){root=this;
path=path.slice(5);}else{if(dotIndex<0&&path.length===4&&path==="this"){root=this;
path="";}}}SC.Observers.addObserver(path,this,observer,root);}}}}}this.bindings=[];
if(keys=this._bindings){for(loc=0;loc<keys.length;loc++){key=keys[loc];value=this[key];
var propertyKey=key.slice(0,-7);this[key]=this.bind(propertyKey,value);}}if(keys=this._properties){for(loc=0;
loc<keys.length;loc++){key=keys[loc];if(value=this[key]){if(value.isCacheable){this._kvo_cacheable=YES;
}if(value.dependentKeys&&(value.dependentKeys.length>0)){this.registerDependentKey(key,value.dependentKeys);
}}}}},observersForKey:function(key){var observers=this._kvo_for("_kvo_observers",key);
return observers.getMembers()||[];},_notifyPropertyObservers:function(key){if(!this._observableInited){this.initObservable();
}SC.Observers.flush(this);var log=SC.LOG_OBSERVERS&&!(this.LOG_OBSERVING===NO);var observers,changes,dependents,starObservers,idx,keys,rev;
var members,membersLength,member,memberLoc,target,method,loc,func;var context,spaces,cache;
if(log){spaces=SC.KVO_SPACES=(SC.KVO_SPACES||"")+"  ";console.log('%@%@: notifying observers after change to key "%@"'.fmt(spaces,this,key));
}starObservers=this["_kvo_observers_*"];this._kvo_changeLevel=(this._kvo_changeLevel||0)+1;
while(((changes=this._kvo_changes)&&(changes.length>0))||key){rev=++this.propertyRevision;
if(!changes){changes=SC.CoreSet.create();}this._kvo_changes=null;if(key==="*"){changes.add("*");
changes.addEach(this._kvo_for("_kvo_observed_keys",SC.CoreSet));}else{if(key){changes.add(key);
}}if(dependents=this._kvo_dependents){for(idx=0;idx<changes.length;idx++){key=changes[idx];
keys=dependents[key];if(keys&&(loc=keys.length)){if(log){console.log("%@...including dependent keys for %@: %@".fmt(spaces,key,keys));
}cache=this._kvo_cache;if(!cache){cache=this._kvo_cache={};}while(--loc>=0){changes.add(key=keys[loc]);
if(func=this[key]){this[func.cacheKey]=undefined;cache[func.cacheKey]=cache[func.lastSetValueKey]=undefined;
}}}}}while(changes.length>0){key=changes.pop();observers=this[SC.keyFor("_kvo_observers",key)];
if(observers){members=observers.getMembers();membersLength=members.length;for(memberLoc=0;
memberLoc<membersLength;memberLoc++){member=members[memberLoc];if(member[3]===rev){continue;
}target=member[0]||this;method=member[1];context=member[2];member[3]=rev;if(log){console.log('%@...firing observer on %@ for key "%@"'.fmt(spaces,target,key));
}if(context!==undefined){method.call(target,this,key,null,context,rev);}else{method.call(target,this,key,null,rev);
}}}members=this[SC.keyFor("_kvo_local",key)];if(members){membersLength=members.length;
for(memberLoc=0;memberLoc<membersLength;memberLoc++){member=members[memberLoc];method=this[member];
if(method){if(log){console.log('%@...firing local observer %@.%@ for key "%@"'.fmt(spaces,this,member,key));
}method.call(this,this,key,null,rev);}}}if(starObservers&&key!=="*"){members=starObservers.getMembers();
membersLength=members.length;for(memberLoc=0;memberLoc<membersLength;memberLoc++){member=members[memberLoc];
target=member[0]||this;method=member[1];context=member[2];if(log){console.log('%@...firing * observer on %@ for key "%@"'.fmt(spaces,target,key));
}if(context!==undefined){method.call(target,this,key,null,context,rev);}else{method.call(target,this,key,null,rev);
}}}if(this.propertyObserver){if(log){console.log('%@...firing %@.propertyObserver for key "%@"'.fmt(spaces,this,key));
}this.propertyObserver(this,key,null,rev);}}if(changes){changes.destroy();}key=null;
}this._kvo_changeLevel=(this._kvo_changeLevel||1)-1;if(log){SC.KVO_SPACES=spaces.slice(0,-2);
}return YES;},bind:function(toKey,target,method){var binding;if(method!==undefined){target=[target,method];
}var pathType=SC.typeOf(target);if(pathType===SC.T_STRING||pathType===SC.T_ARRAY){binding=this[toKey+"BindingDefault"]||SC.Binding;
binding=binding.beget().from(target);}else{binding=target;}binding=binding.to(toKey,this).connect();
this.bindings.push(binding);return binding;},didChangeFor:function(context){context=SC.hashFor(context);
var valueCache=this._kvo_didChange_valueCache;if(!valueCache){valueCache=this._kvo_didChange_valueCache={};
}var revisionCache=this._kvo_didChange_revisionCache;if(!revisionCache){revisionCache=this._kvo_didChange_revisionCache={};
}var seenValues=valueCache[context]||{};var seenRevisions=revisionCache[context]||{};
var ret=false;var currentRevision=this._kvo_revision||0;var idx=arguments.length;
while(--idx>=1){var key=arguments[idx];if(seenRevisions[key]!=currentRevision){var value=this.get(key);
if(seenValues[key]!==value){ret=true;seenValues[key]=value;}}seenRevisions[key]=currentRevision;
}valueCache[context]=seenValues;revisionCache[context]=seenRevisions;return ret;},setIfChanged:function(key,value){return(this.get(key)!==value)?this.set(key,value):this;
},getPath:function(path){var tuple=SC.tupleForPropertyPath(path,this);if(tuple===null||tuple[0]===null){return undefined;
}return tuple[0].get(tuple[1]);},setPath:function(path,value){if(path.indexOf(".")>=0){var tuple=SC.tupleForPropertyPath(path,this);
if(!tuple||!tuple[0]){return null;}tuple[0].set(tuple[1],value);}else{this.set(path,value);
}return this;},setPathIfChanged:function(path,value){if(path.indexOf(".")>=0){var tuple=SC.tupleForPropertyPath(path,this);
if(!tuple||!tuple[0]){return null;}if(tuple[0].get(tuple[1])!==value){tuple[0].set(tuple[1],value);
}}else{this.setIfChanged(path,value);}return this;},getEach:function(){var keys=SC.A(arguments);
var ret=[];for(var idx=0;idx<keys.length;idx++){ret[ret.length]=this.getPath(keys[idx]);
}return ret;},incrementProperty:function(key){this.set(key,(this.get(key)||0)+1);
return this.get(key);},decrementProperty:function(key){this.set(key,(this.get(key)||0)-1);
return this.get(key);},toggleProperty:function(key,value,alt){if(value===undefined){value=true;
}if(alt===undefined){alt=false;}value=(this.get(key)==value)?alt:value;this.set(key,value);
return this.get(key);},notifyPropertyChange:function(key,value){this.propertyWillChange(key);
this.propertyDidChange(key,value);return this;},allPropertiesDidChange:function(){this._kvo_cache=null;
this._notifyPropertyObservers("*");return this;},addProbe:function(key){this.addObserver(key,SC.logChange);
},removeProbe:function(key){this.removeObserver(key,SC.logChange);},logProperty:function(){var props=SC.$A(arguments);
for(var idx=0;idx<props.length;idx++){var prop=props[idx];console.log("%@:%@: ".fmt(SC.guidFor(this),prop),this.get(prop));
}},propertyRevision:1};SC.logChange=function logChange(target,key,value){console.log("CHANGE: %@[%@] => %@".fmt(target,key,target.get(key)));
};SC.mixin(Array.prototype,SC.Observable);});tiki.module("sproutcore/runtime:private/chain_observer",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";SC._ChainObserver=function(property){this.property=property;};SC._ChainObserver.createChain=function(rootObject,path,target,method,context){var parts=path.split("."),root=new SC._ChainObserver(parts[0]),tail=root,len=parts.length;
for(var idx=1;idx<len;idx++){tail=tail.next=new SC._ChainObserver(parts[idx]);}root.objectDidChange(rootObject);
tail.target=target;tail.method=method;tail.context=context;return root;};SC._ChainObserver.prototype={isChainObserver:true,object:null,property:null,next:null,target:null,method:null,objectDidChange:function(newObject){if(newObject===this.object){return;
}if(this.object&&this.object.removeObserver){this.object.removeObserver(this.property,this,this.propertyDidChange);
}this.object=newObject;if(this.object&&this.object.addObserver){this.object.addObserver(this.property,this,this.propertyDidChange);
}this.propertyDidChange();},propertyDidChange:function(){var object=this.object;var property=this.property;
var value=(object&&object.get)?object.get(property):null;if(this.next){this.next.objectDidChange(value);
}var target=this.target,method=this.method,context=this.context;if(target&&method){var rev=object?object.propertyRevision:null;
if(context){method.call(target,object,property,value,context,rev);}else{method.call(target,object,property,value,rev);
}}},destroyChain:function(){var obj=this.object;if(obj&&obj.removeObserver){obj.removeObserver(this.property,this,this.propertyDidChange);
}if(this.next){this.next.destroyChain();}this.next=this.target=this.method=this.object=this.context=null;
return null;}};});tiki.module("sproutcore/runtime:private/observer_queue",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/set");"import core";"import system/set";SC.Observers={queue:[],addObserver:function(propertyPath,target,method,pathRoot){var tuple;
if(SC.typeOf(propertyPath)===SC.T_STRING){tuple=SC.tupleForPropertyPath(propertyPath,pathRoot);
}else{tuple=propertyPath;}if(tuple){tuple[0].addObserver(tuple[1],target,method);
}else{this.queue.push([propertyPath,target,method,pathRoot]);}},removeObserver:function(propertyPath,target,method,pathRoot){var idx,queue,tuple,item;
tuple=SC.tupleForPropertyPath(propertyPath,pathRoot);if(tuple){tuple[0].removeObserver(tuple[1],target,method);
}idx=this.queue.length;queue=this.queue;while(--idx>=0){item=queue[idx];if((item[0]===propertyPath)&&(item[1]===target)&&(item[2]==method)&&(item[3]===pathRoot)){queue[idx]=null;
}}},addPendingRangeObserver:function(observer){var ro=this.rangeObservers;if(!ro){ro=this.rangeObservers=SC.CoreSet.create();
}ro.add(observer);return this;},_TMP_OUT:[],flush:function(object){var oldQueue=this.queue;
if(oldQueue&&oldQueue.length>0){var newQueue=(this.queue=[]);var idx=oldQueue.length;
while(--idx>=0){var item=oldQueue[idx];if(!item){continue;}var tuple=SC.tupleForPropertyPath(item[0],item[3]);
if(tuple){tuple[0].addObserver(tuple[1],item[1],item[2]);}else{newQueue.push(item);
}}}if(object._kvo_needsRangeObserver){var set=this.rangeObservers,len=set?set.get("length"):0,out=this._TMP_OUT,ro;
for(idx=0;idx<len;idx++){ro=set[idx];if(ro.setupPending(object)){out.push(ro);}}if(out.length>0){set.removeEach(out);
}out.length=0;object._kvo_needsRangeObserver=NO;}},isObservingSuspended:0,_pending:SC.CoreSet.create(),objectHasPendingChanges:function(obj){this._pending.add(obj);
},suspendPropertyObserving:function(){this.isObservingSuspended++;},resumePropertyObserving:function(){var pending;
if(--this.isObservingSuspended<=0){pending=this._pending;this._pending=SC.CoreSet.create();
var idx,len=pending.length;for(idx=0;idx<len;idx++){pending[idx]._notifyPropertyObservers();
}pending.clear();pending=null;}}};});tiki.module("sproutcore/runtime:private/observer_set",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";SC.ObserverSet={targets:0,_membersCacheIsValid:NO,add:function(target,method,context){var targetGuid=(target)?SC.guidFor(target):"__this__";
var methods=this[targetGuid];if(!methods){methods=this[targetGuid]=SC.CoreSet.create();
methods.target=target;methods.isTargetSet=YES;this.targets++;}methods.add(method);
if(context!==undefined){var contexts=methods.contexts;if(!context){contexts={};}contexts[SC.guidFor(method)]=context;
}this._membersCacheIsValid=NO;},remove:function(target,method){var targetGuid=(target)?SC.guidFor(target):"__this__";
var methods=this[targetGuid];if(!methods){return NO;}methods.remove(method);if(methods.length<=0){methods.target=null;
methods.isTargetSet=NO;methods.contexts=null;delete this[targetGuid];this.targets--;
}else{if(methods.contexts){delete methods.contexts[SC.guidFor(method)];}}this._membersCacheIsValid=NO;
return YES;},invokeMethods:function(){for(var key in this){if(!this.hasOwnProperty(key)){continue;
}var value=this[key];if(value&&value.isTargetSet){var idx=value.length;var target=value.target;
while(--idx>=0){value[idx].call(target);}}}},getMembers:function(){if(this._membersCacheIsValid){return this._members;
}if(!this._members){this._members=[];}else{this._members.length=0;}var ret=this._members;
for(var key in this){if(!this.hasOwnProperty(key)){continue;}var value=this[key];
if(value&&value.isTargetSet){var idx=value.length;var target=value.target;var contexts=value.contexts;
if(contexts){while(--idx>=0){var method=value[idx];ret.push([target,method,contexts[SC.guidFor(method)]]);
}}else{while(--idx>=0){ret.push([target,value[idx]]);}}}}this._membersCacheIsValid=YES;
return ret;},clone:function(){var oldSet,newSet,key,ret=SC.ObserverSet.create();for(key in this){if(!this.hasOwnProperty(key)){continue;
}oldSet=this[key];if(oldSet&&oldSet.isTargetSet){newSet=oldSet.clone();newSet.target=oldSet.target;
if(oldSet.contexts){newSet.contexts=SC.clone(oldSet.contexts);}ret[key]=newSet;}}ret.targets=this.targets;
ret._membersCacheIsValid=NO;return ret;},create:function(){return SC.beget(this);
}};SC.ObserverSet.slice=SC.ObserverSet.clone;});tiki.module("sproutcore/runtime:system/binding",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/set");"import core";"import system/set";"export package";
SC.LOG_BINDINGS=NO;SC.BENCHMARK_BINDING_NOTIFICATIONS=NO;SC.BENCHMARK_BINDING_SETUP=NO;
SC.MULTIPLE_PLACEHOLDER="@@MULT@@";SC.NULL_PLACEHOLDER="@@NULL@@";SC.EMPTY_PLACEHOLDER="@@EMPTY@@";
SC.Binding={beget:function(fromPath){var ret=SC.beget(this);ret.parentBinding=this;
if(fromPath!==undefined){ret=ret.from(fromPath);}return ret;},builder:function(){var binding=this;
var ret=function(fromProperty){return binding.beget().from(fromProperty);};ret.beget=function(){return binding.beget();
};return ret;},from:function(propertyPath,root){if(!propertyPath){return this;}var binding=(this===SC.Binding)?this.beget():this;
binding._fromPropertyPath=propertyPath;binding._fromRoot=root;binding._fromTuple=null;
return binding;},to:function(propertyPath,root){var binding=(this===SC.Binding)?this.beget():this;
binding._toPropertyPath=propertyPath;binding._toRoot=root;binding._toTuple=null;return binding;
},connect:function(){if(this.isConnected){return this;}this.isConnected=YES;this._connectionPending=YES;
this._syncOnConnect=YES;SC.Binding._connectQueue.add(this);return this;},_connect:function(){if(!this._connectionPending){return;
}this._connectionPending=NO;var path,root;var bench=SC.BENCHMARK_BINDING_SETUP;if(bench){SC.Benchmark.start("SC.Binding.connect()");
}path=this._fromPropertyPath;root=this._fromRoot;if(SC.typeOf(path)===SC.T_STRING){if(path.indexOf(".")===0){path=path.slice(1);
if(!root){root=this._toRoot;}}else{if(path.indexOf("*")===0){path=[this._fromRoot||this._toRoot,path.slice(1)];
root=null;}}}SC.Observers.addObserver(path,this,this.fromPropertyDidChange,root);
if(!this._oneWay){path=this._toPropertyPath;root=this._toRoot;SC.Observers.addObserver(path,this,this.toPropertyDidChange,root);
}if(bench){SC.Benchmark.end("SC.Binding.connect()");}if(this._syncOnConnect){this._syncOnConnect=NO;
if(bench){SC.Benchmark.start("SC.Binding.connect().sync");}this.sync();if(bench){SC.Benchmark.end("SC.Binding.connect().sync");
}}},disconnect:function(){if(!this.isConnected){return this;}if(this._connectionPending){this._connectionPending=NO;
}else{SC.Observers.removeObserver(this._fromPropertyPath,this,this.fromPropertyDidChange,this._fromRoot);
if(!this._oneWay){SC.Observers.removeObserver(this._toPropertyPath,this,this.toPropertyDidChange,this._toRoot);
}}this.isConnected=NO;return this;},fromPropertyDidChange:function(target,key){var v=target?target.get(key):null;
if(v!==this._bindingValue){this._setBindingValue(target,key);this._changePending=YES;
SC.Binding._changeQueue.add(this);}},toPropertyDidChange:function(target,key){if(this._oneWay){return;
}var v=target.get(key);if(v!==this._transformedBindingValue){this._setBindingValue(target,key);
this._changePending=YES;SC.Binding._changeQueue.add(this);}},_setBindingValue:function(source,key){this._bindingSource=source;
this._bindingKey=key;},_computeBindingValue:function(){var source=this._bindingSource,key=this._bindingKey,v;
if(!source){return;}this._bindingValue=v=source.getPath(key);var transforms=this._transforms;
if(transforms){var len=transforms.length;for(var idx=0;idx<len;idx++){var transform=transforms[idx];
v=transform(v,this);}}if(this._noError&&SC.typeOf(v)===SC.T_ERROR){v=null;}this._transformedBindingValue=v;
},_connectQueue:SC.CoreSet.create(),_alternateConnectQueue:SC.CoreSet.create(),_changeQueue:SC.CoreSet.create(),_alternateChangeQueue:SC.CoreSet.create(),_changePending:NO,flushPendingChanges:function(){if(this._isFlushing){return NO;
}this._isFlushing=YES;SC.Observers.suspendPropertyObserving();var didFlush=NO;var log=SC.LOG_BINDINGS;
var queue,binding;while((queue=this._connectQueue).length>0){this._connectQueue=this._alternateConnectQueue;
this._alternateConnectQueue=queue;while(binding=queue.pop()){binding._connect();}}while((queue=this._changeQueue).length>0){if(log){console.log("Begin: Trigger changed bindings");
}didFlush=YES;this._changeQueue=this._alternateChangeQueue;this._alternateChangeQueue=queue;
while(binding=queue.pop()){binding.applyBindingValue();}if(log){console.log("End: Trigger changed bindings");
}}this._isFlushing=NO;SC.Observers.resumePropertyObserving();return didFlush;},applyBindingValue:function(){this._changePending=NO;
this._computeBindingTargets();this._computeBindingValue();var v=this._bindingValue;
var tv=this._transformedBindingValue;var bench=SC.BENCHMARK_BINDING_NOTIFICATIONS;
var log=SC.LOG_BINDINGS;if(!this._oneWay&&this._fromTarget){if(log){console.log("%@: %@ -> %@".fmt(this,v,tv));
}if(bench){SC.Benchmark.start(this.toString()+"->");}this._fromTarget.setPathIfChanged(this._fromPropertyKey,v);
if(bench){SC.Benchmark.end(this.toString()+"->");}}if(this._toTarget){if(log){console.log("%@: %@ <- %@".fmt(this,v,tv));
}if(bench){SC.Benchmark.start(this.toString()+"<-");}this._toTarget.setPathIfChanged(this._toPropertyKey,tv);
if(bench){SC.Benchmark.start(this.toString()+"<-");}}},sync:function(){if(!this.isConnected){return this;
}if(this._connectionPending){this._syncOnConnect=YES;}else{this._computeBindingTargets();
var target=this._fromTarget;var key=this._fromPropertyKey;if(!target||!key){return this;
}var v=target.getPath(key);if(v!==this._bindingValue){this._setBindingValue(target,key);
this._changePending=YES;SC.Binding._changeQueue.add(this);}}return this;},_syncOnConnect:NO,_computeBindingTargets:function(){if(!this._fromTarget){var path,root,tuple;
path=this._fromPropertyPath;root=this._fromRoot;if(SC.typeOf(path)===SC.T_STRING){if(path.indexOf(".")===0){path=path.slice(1);
if(!root){root=this._toRoot;}}else{if(path.indexOf("*")===0){path=[root||this._toRoot,path.slice(1)];
root=null;}}}tuple=SC.tupleForPropertyPath(path,root);if(tuple){this._fromTarget=tuple[0];
this._fromPropertyKey=tuple[1];}}if(!this._toTarget){path=this._toPropertyPath;root=this._toRoot;
tuple=SC.tupleForPropertyPath(path,root);if(tuple){this._toTarget=tuple[0];this._toPropertyKey=tuple[1];
}}},oneWay:function(fromPath,aFlag){if((aFlag===undefined)&&(SC.typeOf(fromPath)===SC.T_BOOL)){aFlag=fromPath;
fromPath=null;}var binding=this.from(fromPath);if(binding===SC.Binding){binding=binding.beget();
}binding._oneWay=(aFlag===undefined)?YES:aFlag;return binding;},transform:function(transformFunc){var binding=(this===SC.Binding)?this.beget():this;
var t=binding._transforms;if(t&&(t===binding.parentBinding._transform)){t=binding._transforms=t.slice();
}if(!t){t=binding._transforms=[];}t.push(transformFunc);return binding;},resetTransforms:function(){var binding=(this===SC.Binding)?this.beget():this;
binding._transforms=null;return binding;},noError:function(fromPath,aFlag){if((aFlag===undefined)&&(SC.typeOf(fromPath)===SC.T_BOOL)){aFlag=fromPath;
fromPath=null;}var binding=this.from(fromPath);if(binding===SC.Binding){binding=binding.beget();
}binding._noError=(aFlag===undefined)?YES:aFlag;return binding;},single:function(fromPath,placeholder){if(placeholder===undefined){placeholder=SC.MULTIPLE_PLACEHOLDER;
}return this.from(fromPath).transform(function(value,isForward){if(value&&value.isEnumerable){var len=value.get("length");
value=(len>1)?placeholder:(len<=0)?null:value.firstObject();}return value;});},notEmpty:function(fromPath,placeholder){if(placeholder===undefined){placeholder=SC.EMPTY_PLACEHOLDER;
}return this.from(fromPath).transform(function(value,isForward){if(SC.none(value)||(value==="")||(SC.isArray(value)&&value.length===0)){value=placeholder;
}return value;});},notNull:function(fromPath,placeholder){if(placeholder===undefined){placeholder=SC.EMPTY_PLACEHOLDER;
}return this.from(fromPath).transform(function(value,isForward){if(SC.none(value)){value=placeholder;
}return value;});},multiple:function(fromPath){return this.from(fromPath).transform(function(value){if(!SC.isArray(value)){value=(value==null)?[]:[value];
}return value;});},bool:function(fromPath){return this.from(fromPath).transform(function(v){var t=SC.typeOf(v);
if(t===SC.T_ERROR){return v;}return(t==SC.T_ARRAY)?(v.length>0):(v==="")?NO:!!v;});
},not:function(fromPath){return this.from(fromPath).transform(function(v){var t=SC.typeOf(v);
if(t===SC.T_ERROR){return v;}return !((t==SC.T_ARRAY)?(v.length>0):(v==="")?NO:!!v);
});},isNull:function(fromPath){return this.from(fromPath).transform(function(v){var t=SC.typeOf(v);
return(t===SC.T_ERROR)?v:SC.none(v);});},toString:function(){var from=this._fromRoot?"<%@>:%@".fmt(this._fromRoot,this._fromPropertyPath):this._fromPropertyPath;
var to=this._toRoot?"<%@>:%@".fmt(this._toRoot,this._toPropertyPath):this._toPropertyPath;
var oneWay=this._oneWay?"[oneWay]":"";return"SC.Binding%@(%@ -> %@)%@".fmt(SC.guidFor(this),from,to,oneWay);
}};SC.binding=function(path,root){return SC.Binding.from(path,root);};});tiki.module("sproutcore/runtime:system/cookie",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/object");"import core";"import system/object";
"export package";SC.Cookie=SC.Object.extend({name:null,value:"",expires:null,path:null,domain:null,secure:NO,isCookie:YES,destroy:function(){this.set("expires",-1);
this.write();arguments.callee.base.apply(this,arguments);},write:function(){var name=this.get("name"),value=this.get("value"),expires=this.get("expires"),path=this.get("path"),domain=this.get("domain"),secure=this.get("secure");
var expiresOutput="";if(expires&&(SC.typeOf(expires)===SC.T_NUMBER||(SC.DateTime&&expires.get&&expires.get("milliseconds"))||SC.typeOf(expires.toUTCString)===SC.T_FUNCTION)){var date;
if(SC.typeOf(expires)===SC.T_NUMBER){date=new Date();date.setTime(date.getTime()+(expires*24*60*60*1000));
}else{if(SC.DateTime&&expires.get&&expires.get("milliseconds")){date=new Date(expires.get("milliseconds"));
}else{if(SC.typeOf(expires.toUTCString)===SC.T_FUNCTION){date=expires;}}}if(date){expiresOutput="; expires="+date.toUTCString();
}}var pathOutput=path?"; path="+path:"";var domainOutput=domain?"; domain="+domain:"";
var secureOutput=secure?"; secure":"";document.cookie=[name,"=",encodeURIComponent(value),expiresOutput,pathOutput,domainOutput,secureOutput].join("");
return this;}});SC.Cookie.mixin({find:function(name){if(document.cookie&&document.cookie!=""){var cookies=document.cookie.split(";");
for(var i=0;i<cookies.length;i++){var cookie=String(cookies[i]).trim();if(cookie.substring(0,name.length+1)===(name+"=")){return SC.Cookie.create({name:name,value:decodeURIComponent(cookie.substring(name.length+1))});
}}}return null;}});});tiki.module("sproutcore/runtime:system/enumerator",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";"export package";SC.Enumerator=function(enumerableObject){this.enumerable=enumerableObject;
this.reset();return this;};SC.Enumerator.prototype={nextObject:function(){var index=this._index;
var len=this._length;if(index>=len){return undefined;}var ret=this.enumerable.nextObject(index,this._previousObject,this._context);
this._previousObject=ret;this._index=index+1;if(index>=len){this._context=SC.Enumerator._pushContext(this._context);
}return ret;},reset:function(){var e=this.enumerable;if(!e){throw SC.$error("Enumerator has been destroyed");
}this._length=e.get?e.get("length"):e.length;var len=this._length;this._index=0;this._previousObject=null;
this._context=(len>0)?SC.Enumerator._popContext():null;},destroy:function(){this.enumerable=this._length=this._index=this._previousObject=this._context=null;
}};SC.Enumerator.create=function(enumerableObject){return new SC.Enumerator(enumerableObject);
};SC.Enumerator._popContext=function(){var ret=this._contextCache?this._contextCache.pop():null;
return ret||{};};SC.Enumerator._pushContext=function(context){this._contextCache=this._contextCache||[];
var cache=this._contextCache;cache.push(context);return null;};});tiki.module("sproutcore/runtime:system/error",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
"import core";"export package";SC.Error=SC.Object.extend({code:-1,message:"",errorValue:null,errorObject:function(){return this;
}.property().cacheable(),label:null,toString:function(){return"SC.Error:%@:%@ (%@)".fmt(SC.guidFor(this),this.get("message"),this.get("code"));
},isError:YES});SC.Error.desc=function(description,label,value,code){var opts={message:description};
if(label!==undefined){opts.label=label;}if(code!==undefined){opts.code=code;}if(value!==undefined){opts.errorValue=value;
}return this.create(opts);};SC.$error=function(description,label,value,c){return SC.Error.desc(description,label,value,c);
};SC.ok=function(ret){return(ret!==false)&&!(ret&&ret.isError);};SC.$ok=SC.ok;SC.val=function(obj){if(obj&&obj.isError){return obj.get?obj.get("errorValue"):null;
}else{return obj;}};SC.$val=SC.val;SC.Error.HAS_MULTIPLE_VALUES=-100;});tiki.module("sproutcore/runtime:system/index_set",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:mixins/enumerable");require("sproutcore/runtime:mixins/observable");
require("sproutcore/runtime:mixins/freezable");require("sproutcore/runtime:mixins/copyable");
"import core";"import mixins/enumerable";"import mixins/observable";"import mixins/freezable";
"import mixins/copyable";"export package";SC.IndexSet=SC.mixin({},SC.Enumerable,SC.Observable,SC.Freezable,SC.Copyable,{_sc_sliceContent:function(c){if(c.length<1000){return c.slice();
}var cur=0,ret=[],next=c[0];while(next!==0){ret[cur]=next;cur=(next<0)?(0-next):next;
next=c[cur];}ret[cur]=0;this._hint(0,cur,ret);return ret;},create:function(start,length){var ret=SC.beget(this);
ret.initObservable();if(start&&start.isIndexSet){ret._content=this._sc_sliceContent(start._content);
ret.max=start.max;ret.length=start.length;ret.source=start.source;}else{ret._content=[0];
if(start!==undefined){ret.add(start,length);}}return ret;},isIndexSet:YES,HINT_SIZE:256,length:0,max:0,min:function(){var content=this._content,cur=content[0];
return(cur===0)?-1:(cur>0)?0:Math.abs(cur);}.property("[]").cacheable(),firstObject:function(){return(this.get("length")>0)?this.get("min"):undefined;
}.property(),rangeStartForIndex:function(index){var content=this._content,max=this.get("max"),ret,next,accel;
if(index>=max){return max;}if(Math.abs(content[index])>index){return index;}accel=index-(index%SC.IndexSet.HINT_SIZE);
ret=content[accel];if(ret<0||ret>index){ret=accel;}next=Math.abs(content[ret]);while(next<index){ret=next;
next=Math.abs(content[ret]);}return ret;},isEqual:function(obj){if(obj===this){return YES;
}if(!obj||!obj.isIndexSet||(obj.max!==this.max)||(obj.length!==this.length)){return NO;
}var lcontent=this._content,rcontent=obj._content,cur=0,next=lcontent[cur];do{if(rcontent[cur]!==next){return NO;
}cur=Math.abs(next);next=lcontent[cur];}while(cur!==0);return YES;},indexBefore:function(index){if(index===0){return -1;
}index--;var content=this._content,max=this.get("max"),start=this.rangeStartForIndex(index);
if(!content){return null;}while((start===max)||(content[start]<0)){if(start===0){return -1;
}index=start-1;start=this.rangeStartForIndex(index);}return index;},indexAfter:function(index){var content=this._content,max=this.get("max"),start,next;
if(!content||(index>=max)){return -1;}index++;start=this.rangeStartForIndex(index);
next=content[start];while(next<0){if(next===0){return -1;}index=start=Math.abs(next);
next=content[start];}return index;},contains:function(start,length){var content,cur,next,rstart,rnext;
if(length===undefined){if(start===null||start===undefined){return NO;}if(typeof start===SC.T_NUMBER){length=1;
}else{if(start&&start.isIndexSet){if(start===this){return YES;}content=start._content;
cur=0;next=content[cur];while(next!==0){if((next>0)&&!this.contains(cur,next-cur)){return NO;
}cur=Math.abs(next);next=content[cur];}return YES;}else{length=start.length;start=start.start;
}}}rstart=this.rangeStartForIndex(start);rnext=this._content[rstart];return(rnext>0)&&(rstart<=start)&&(rnext>=(start+length));
},intersects:function(start,length){var content,cur,next,lim;if(length===undefined){if(typeof start===SC.T_NUMBER){length=1;
}else{if(start&&start.isIndexSet){if(start===this){return YES;}content=start._content;
cur=0;next=content[cur];while(next!==0){if((next>0)&&this.intersects(cur,next-cur)){return YES;
}cur=Math.abs(next);next=content[cur];}return NO;}else{length=start.length;start=start.start;
}}}cur=this.rangeStartForIndex(start);content=this._content;next=content[cur];lim=start+length;
while(cur<lim){if(next===0){return NO;}if((next>0)&&(next>start)){return YES;}cur=Math.abs(next);
next=content[cur];}return NO;},without:function(start,length){if(start===this){return SC.IndexSet.create();
}return this.clone().remove(start,length);},replace:function(start,length){if(length===undefined){if(typeof start===SC.T_NUMBER){length=1;
}else{if(start&&start.isIndexSet){this._content=this._sc_sliceContent(start._content);
this.beginPropertyChanges().set("max",start.max).set("length",start.length).set("source",start.source).enumerableContentDidChange().endPropertyChanges();
return this;}else{length=start.length;start=start.start;}}}var oldlen=this.length;
this._content.length=1;this._content[0]=0;this.length=this.max=0;return this.add(start,length);
},add:function(start,length){if(this.isFrozen){throw SC.FROZEN_ERROR;}var content,cur,next;
if(start&&start.isIndexSet){content=start._content;if(!content){return this;}cur=0;
next=content[0];while(next!==0){if(next>0){this.add(cur,next-cur);}cur=next<0?0-next:next;
next=content[cur];}return this;}else{if(length===undefined){if(start===null||start===undefined){return this;
}else{if(typeof start===SC.T_NUMBER){length=1;}else{length=start.length;start=start.start;
}}}else{if(length===null){length=1;}}}if(length<=0){return this;}var max=this.get("max"),oldmax=max,delta,value;
content=this._content;if(start===max){if(start>0){cur=this.rangeStartForIndex(start-1);
next=content[cur];if(next>0){delete content[max];content[cur]=max=start+length;start=cur;
}else{content[max]=max=start+length;}}else{content[start]=max=length;}content[max]=0;
this.set("max",max);this.set("length",this.length+length);length=max-start;}else{if(start>max){content[max]=0-start;
content[start]=start+length;content[start+length]=0;this.set("max",start+length);
this.set("length",this.length+length);length=start+length-max;start=max;}else{cur=this.rangeStartForIndex(start);
next=content[cur];max=start+length;delta=0;if((start>0)&&(cur===start)&&(next<=0)){cur=this.rangeStartForIndex(start-1);
next=content[cur];}if(next<0){content[cur]=0-start;if(Math.abs(next)>max){content[start]=0-max;
content[max]=next;}else{content[start]=next;}}else{start=cur;if(next>max){max=next;
}}cur=start;while(cur<max){value=content[cur];if(value===0){content[max]=0;next=max;
delta+=max-cur;}else{next=Math.abs(value);if(next>max){content[max]=value;next=max;
}if(value<0){delta+=next-cur;}}delete content[cur];cur=next;}if((cur=content[max])>0){delete content[max];
max=cur;}content[start]=max;if(max>oldmax){this.set("max",max);}this.set("length",this.get("length")+delta);
length=max-start;}}this._hint(start,length);if(delta!==0){this.enumerableContentDidChange();
}return this;},remove:function(start,length){if(this.isFrozen){throw SC.FROZEN_ERROR;
}if(length===undefined){if(start===null||start===undefined){return this;}else{if(typeof start===SC.T_NUMBER){length=1;
}else{if(start.isIndexSet){start.forEachRange(this.remove,this);return this;}else{length=start.length;
start=start.start;}}}}if(length<=0){return this;}var max=this.get("max"),oldmax=max,content=this._content,cur,next,delta,value,last;
if(start>=max){return this;}cur=this.rangeStartForIndex(start);next=content[cur];
last=start+length;delta=0;if((start>0)&&(cur===start)&&(next>0)){cur=this.rangeStartForIndex(start-1);
next=content[cur];}if(next>0){content[cur]=start;if(next>last){content[start]=last;
content[last]=next;}else{content[start]=next;}}else{start=cur;next=Math.abs(next);
if(next>last){last=next;}}cur=start;while(cur<last){value=content[cur];if(value===0){content[last]=0;
next=last;}else{next=Math.abs(value);if(next>last){content[last]=value;next=last;
}if(value>0){delta+=next-cur;}}delete content[cur];cur=next;}if((cur=content[last])<0){delete content[last];
last=Math.abs(cur);}if(content[last]===0){delete content[last];content[start]=0;this.set("max",start);
}else{content[start]=0-last;}this.set("length",this.get("length")-delta);length=last-start;
this._hint(start,length);if(delta!==0){this.enumerableContentDidChange();}return this;
},_hint:function(start,length,content){if(content===undefined){content=this._content;
}var skip=SC.IndexSet.HINT_SIZE,next=Math.abs(content[start]),loc=start-(start%skip)+skip,lim=start+length;
while(loc<lim){while((next!==0)&&(next<=loc)){start=next;next=Math.abs(content[start]);
}if(next===0){delete content[loc];}else{if(loc!==start){content[loc]=start;}}loc+=skip;
}},clear:function(){if(this.isFrozen){throw SC.FROZEN_ERROR;}var oldlen=this.length;
this._content.length=1;this._content[0]=0;this.set("length",0).set("max",0);if(oldlen>0){this.enumerableContentDidChange();
}},addEach:function(objects){if(this.isFrozen){throw SC.FROZEN_ERROR;}this.beginPropertyChanges();
var idx=objects.get("length");if(objects.isSCArray){while(--idx>=0){this.add(objects.objectAt(idx));
}}else{if(objects.isEnumerable){objects.forEach(function(idx){this.add(idx);},this);
}}this.endPropertyChanges();return this;},removeEach:function(objects){if(this.isFrozen){throw SC.FROZEN_ERROR;
}this.beginPropertyChanges();var idx=objects.get("length");if(objects.isSCArray){while(--idx>=0){this.remove(objects.objectAt(idx));
}}else{if(objects.isEnumerable){objects.forEach(function(idx){this.remove(idx);},this);
}}this.endPropertyChanges();return this;},clone:function(){return SC.IndexSet.create(this);
},inspect:function(){var content=this._content,len=content.length,idx=0,ret=[],item;
for(idx=0;idx<len;idx++){item=content[idx];if(item!==undefined){ret.push("%@:%@".fmt(idx,item));
}}return"SC.IndexSet<%@>".fmt(ret.join(" , "));},forEachRange:function(callback,target){var content=this._content,cur=0,next=content[cur],source=this.source;
if(target===undefined){target=null;}while(next!==0){if(next>0){callback.call(target,cur,next-cur,this,source);
}cur=Math.abs(next);next=content[cur];}return this;},forEachIn:function(start,length,callback,target){var content=this._content,cur=0,idx=0,lim=start+length,source=this.source,next=content[cur];
if(target===undefined){target=null;}while(next!==0){if(cur<start){cur=start;}while((cur<next)&&(cur<lim)){callback.call(target,cur++,idx++,this,source);
}if(cur>=lim){cur=next=0;}else{cur=Math.abs(next);next=content[cur];}}return this;
},lengthIn:function(start,length){var ret=0;if(length===undefined){if(start===null||start===undefined){return 0;
}else{if(typeof start===SC.T_NUMBER){length=1;}else{if(start.isIndexSet){start.forEachRange(function(start,length){ret+=this.lengthIn(start,length);
},this);return ret;}else{length=start.length;start=start.start;}}}}if(this.get("length")===0){return 0;
}var content=this._content,cur=0,next=content[cur],lim=start+length;while(cur<lim&&next!==0){if(next>0){ret+=(next>lim)?lim-cur:next-cur;
}cur=Math.abs(next);next=content[cur];}return ret;},source:null,indexOf:function(object,startAt){var source=this.source;
if(!source){throw"%@.indexOf() requires source".fmt(this);}var len=source.get("length"),content=this._content,cur=content[0]<0?Math.abs(content[0]):0,idx;
while(cur>=0&&cur<len){idx=source.indexOf(object,cur);if(idx<0){return -1;}if(this.contains(idx)){return idx;
}cur=idx+1;}return -1;},lastIndexOf:function(object,startAt){var source=this.source;
if(!source){throw"%@.lastIndexOf() requires source".fmt(this);}var len=source.get("length"),cur=this.max-1,idx;
if(cur>=len){cur=len-1;}while(cur>=0){idx=source.lastIndexOf(object,cur);if(idx<0){return -1;
}if(this.contains(idx)){return idx;}cur=idx+1;}return -1;},forEachObject:function(callback,target){var source=this.source;
if(!source){throw"%@.forEachObject() requires source".fmt(this);}var content=this._content,cur=0,idx=0,next=content[cur];
if(target===undefined){target=null;}while(next!==0){while(cur<next){callback.call(target,source.objectAt(cur),cur,source,this);
cur++;}cur=Math.abs(next);next=content[cur];}return this;},addObject:function(object,firstOnly){var source=this.source;
if(!source){throw"%@.addObject() requires source".fmt(this);}var len=source.get("length"),cur=0,idx;
while(cur>=0&&cur<len){idx=source.indexOf(object,cur);if(idx>=0){this.add(idx);if(firstOnly){return this;
}cur=idx++;}else{return this;}}return this;},addObjects:function(objects,firstOnly){objects.forEach(function(object){this.addObject(object,firstOnly);
},this);return this;},removeObject:function(object,firstOnly){var source=this.source;
if(!source){throw"%@.removeObject() requires source".fmt(this);}var len=source.get("length"),cur=0,idx;
while(cur>=0&&cur<len){idx=source.indexOf(object,cur);if(idx>=0){this.remove(idx);
if(firstOnly){return this;}cur=idx+1;}else{return this;}}return this;},removeObjects:function(objects,firstOnly){objects.forEach(function(object){this.removeObject(object,firstOnly);
},this);return this;},LOG_OBSERVING:NO,forEach:function(callback,target){var content=this._content,cur=0,idx=0,source=this.source,next=content[cur];
if(target===undefined){target=null;}while(next!==0){while(cur<next){callback.call(target,cur++,idx++,this,source);
}cur=Math.abs(next);next=content[cur];}return this;},nextObject:function(ignore,idx,context){var content=this._content,next=context.next,max=this.get("max");
if(idx===null){idx=next=0;}else{if(idx>=max){delete context.next;return null;}else{idx++;
}}if(idx===next){do{idx=Math.abs(next);next=content[idx];}while(next<0);context.next=next;
}return idx;},toString:function(){var str=[];this.forEachRange(function(start,length){str.push(length===1?start:"%@..%@".fmt(start,start+length-1));
},this);return"SC.IndexSet<%@>".fmt(str.join(","));},max:0});SC.IndexSet.slice=SC.IndexSet.copy=SC.IndexSet.clone;
SC.IndexSet.EMPTY=SC.IndexSet.create().freeze();});tiki.module("sproutcore/runtime:system/logger",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/object");"import core";"import system/object";
"export package";SC.LOGGER_LOG_DELIMITER=", ";SC.LOGGER_LOG_ERROR="ERROR: ";SC.LOGGER_LOG_INFO="INFO: ";
SC.LOGGER_LOG_WARN="WARNING: ";SC.Logger=SC.Object.create({exists:function(){return typeof(this.get("reporter"))!=="undefined"&&this.get("reporter")!=null;
}.property("reporter").cacheable(),fallBackOnAlert:NO,fallBackOnLog:YES,format:YES,reporter:console,log:function(){var reporter=this.get("reporter");
if(this.get("exists")&&typeof(reporter.log)==="function"){if(this.get("format")){reporter.log(this._argumentsToString.apply(this,arguments));
}else{reporter.log.apply(reporter,arguments);}return true;}else{if(this.fallBackOnAlert){var s=this.get("format")?this._argumentsToString.apply(this,arguments):arguments;
if(this.get("exists")&&typeof(reporter.alert)==="function"){reporter.alert(s);}else{alert(s);
}return true;}}return false;},dir:function(){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.dir)==="function"){reporter.dir.apply(reporter,arguments);
return true;}return(this.fallBackOnLog)?this.log.apply(this,arguments):false;},dirxml:function(){var reporter=this.get("reporter");
if(this.get("exists")&&typeof(reporter.dirxml)==="function"){reporter.dirxml.apply(reporter,arguments);
return true;}return(this.fallBackOnLog)?this.log.apply(this,arguments):false;},error:function(){var reporter=this.get("reporter");
if(this.get("exists")&&typeof(reporter.error)==="function"){reporter.error.apply(reporter,arguments);
return true;}else{if(this.fallBackOnLog){var a=this._argumentsToArray(arguments);
if(typeof(a.unshift)==="function"){a.unshift(SC.LOGGER_LOG_ERROR);}return this.log.apply(this,a);
}}return false;},group:function(s){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.group)==="function"){reporter.group(s);
return true;}return false;},groupEnd:function(){var reporter=this.get("reporter");
if(this.get("exists")&&typeof(reporter.groupEnd)==="function"){reporter.groupEnd();
return true;}return false;},info:function(){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.info)==="function"){reporter.info.apply(reporter,arguments);
return true;}else{if(this.fallBackOnLog){var a=this._argumentsToArray(arguments);
if(typeof(a.unshift)==="function"){a.unshift(SC.LOGGER_LOG_INFO);}return this.log.apply(this,a);
}}return false;},profile:function(){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.profile)==="function"){reporter.profile();
return true;}return false;},profileEnd:function(){var reporter=this.get("reporter");
if(this.get("exists")&&typeof(reporter.profileEnd)==="function"){reporter.profileEnd();
return true;}return false;},time:function(name){var reporter=this.get("reporter");
if(this.get("exists")&&typeof(reporter.time)==="function"){reporter.time(name);return true;
}return false;},timeEnd:function(name){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.timeEnd)==="function"){reporter.timeEnd(name);
return true;}return false;},trace:function(){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.trace)==="function"){reporter.trace();
return true;}return false;},warn:function(){var reporter=this.get("reporter");if(this.get("exists")&&typeof(reporter.warn)==="function"){reporter.warn.apply(reporter,arguments);
return true;}else{if(this.fallBackOnLog){var a=this._argumentsToArray(arguments);
if(typeof(a.unshift)==="function"){a.unshift(SC.LOGGER_LOG_WARN);}return this.log.apply(this,a);
}}return false;},_argumentsToArray:function(arguments){if(!arguments){return[];}var a=[];
for(var i=0;i<arguments.length;i++){a[i]=arguments[i];}return a;},_argumentsToString:function(){var s="";
for(var i=0;i<arguments.length-1;i++){s+=arguments[i]+SC.LOGGER_LOG_DELIMITER;}s+=arguments[arguments.length-1];
return s;}});});tiki.module("sproutcore/runtime:system/object",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:mixins/observable");require("sproutcore/runtime:system/set");
"import core";"import mixins/observable";"import system/set";"export package";SC.BENCHMARK_OBJECTS=NO;
SC._object_extend=function _object_extend(base,ext){if(!ext){throw"SC.Object.extend expects a non-null value.  Did you forget to 'sc_require' something?  Or were you passing a Protocol to extend() as if it were a mixin?";
}base._kvo_cloned=null;var key,idx,len,cur,cprops=base.concatenatedProperties,K=SC.K;
var p1,p2;idx=(cprops)?cprops.length:0;var concats=(idx>0)?{}:null;while(--idx>=0){key=cprops[idx];
p1=base[key];p2=ext[key];if(p1){if(!(p1 instanceof Array)){p1=SC.$A(p1);}concats[key]=(p2)?p1.concat(p2):p2;
}else{if(!(p2 instanceof Array)){p2=SC.$A(p2);}concats[key]=p2;}}var bindings=base._bindings,clonedBindings=NO;
var observers=base._observers,clonedObservers=NO;var properties=base._properties,clonedProperties=NO;
var paths,pathLoc,local;var outlets=base.outlets,clonedOutlets=NO;if(ext.outlets){outlets=(outlets||SC.EMPTY_ARRAY).concat(ext.outlets);
clonedOutlets=YES;}for(key in ext){if(key==="_kvo_cloned"){continue;}if(!ext.hasOwnProperty(key)){continue;
}var value=(concats.hasOwnProperty(key)?concats[key]:null)||ext[key];if(key.slice(-7)==="Binding"){if(!clonedBindings){bindings=(bindings||SC.EMPTY_ARRAY).slice();
clonedBindings=YES;}if(bindings===null){bindings=(base._bindings||SC.EMPTY_ARRAY).slice();
}bindings[bindings.length]=key;}else{if(value&&(value instanceof Function)){if(!value.superclass&&(value!==(cur=base[key]))){value.superclass=value.base=cur||K;
}if(value.propertyPaths){if(!clonedObservers){observers=(observers||SC.EMPTY_ARRAY).slice();
clonedObservers=YES;}observers[observers.length]=key;}else{if(paths=value.localPropertyPaths){pathLoc=paths.length;
while(--pathLoc>=0){local=base._kvo_for(SC.keyFor("_kvo_local",paths[pathLoc]),SC.Set);
local.add(key);base._kvo_for("_kvo_observed_keys",SC.CoreSet).add(paths[pathLoc]);
}}else{if(value.dependentKeys){if(!clonedProperties){properties=(properties||SC.EMPTY_ARRAY).slice();
clonedProperties=YES;}properties[properties.length]=key;}else{if(value.autoconfiguredOutlet){if(!clonedOutlets){outlets=(outlets||SC.EMPTY_ARRAY).slice();
clonedOutlets=YES;}outlets[outlets.length]=key;}}}}}}base[key]=value;}if(ext.hasOwnProperty("toString")){key="toString";
value=(concats.hasOwnProperty(key)?concats[key]:null)||ext[key];if(!value.superclass&&(value!==(cur=base[key]))){value.superclass=value.base=cur||K;
}base[key]=value;}base._bindings=bindings||[];base._observers=observers||[];base._properties=properties||[];
base.outlets=outlets||[];return base;};SC.Object=function(props){return this._object_init(props);
};SC.mixin(SC.Object,{mixin:function(props){var len=arguments.length,loc;for(loc=0;
loc<len;loc++){SC.mixin(this,arguments[loc]);}return this;},superclass:null,extend:function(props){var bench=SC.BENCHMARK_OBJECTS;
if(bench){SC.Benchmark.start("SC.Object.extend");}var prop,ret=function(props){return this._object_init(props);
};for(prop in this){if(!this.hasOwnProperty(prop)){continue;}ret[prop]=this[prop];
}if(this.hasOwnProperty("toString")){ret.toString=this.toString;}ret.superclass=this;
SC.generateGuid(ret);ret.subclasses=SC.Set.create();this.subclasses.add(ret);var base=(ret.prototype=SC.beget(this.prototype));
var idx,len=arguments.length;for(idx=0;idx<len;idx++){SC._object_extend(base,arguments[idx]);
}base.constructor=ret;if(bench){SC.Benchmark.end("SC.Object.extend");}return ret;
},create:function(props){var C=this;return new C(arguments);},isClass:YES,subclasses:SC.Set.create(),toString:function(){return SC._object_className(this);
},subclassOf:function(scClass){if(this===scClass){return NO;}var t=this;while(t=t.superclass){if(t===scClass){return YES;
}}return NO;},hasSubclass:function(scClass){return(scClass&&scClass.subclassOf)?scClass.subclassOf(this):NO;
},kindOf:function(scClass){return(this===scClass)||this.subclassOf(scClass);}});SC.Object.prototype={_kvo_enabled:YES,_object_init:function(extensions){var idx,len=(extensions)?extensions.length:0;
for(idx=0;idx<len;idx++){SC._object_extend(this,extensions[idx]);}SC.generateGuid(this);
this.init();var inits=this.initMixin;len=(inits)?inits.length:0;for(idx=0;idx<len;
idx++){inits[idx].call(this);}return this;},mixin:function(){var idx,len=arguments.length;
for(idx=0;idx<len;idx++){SC.mixin(this,arguments[idx]);}for(idx=0;idx<len;idx++){var init=arguments[idx].initMixin;
if(init){init.call(this);}}return this;},init:function(){this.initObservable();return this;
},isDestroyed:NO,destroy:function(){if(this.get("isDestroyed")){return this;}this.set("isDestroyed",YES);
var idx,inits=this.destroyMixin,len=(inits)?inits.length:0;for(idx=0;idx<len;idx++){inits[idx].call(this);
}return this;},isObject:true,respondsTo:function(methodName){return !!(SC.typeOf(this[methodName])===SC.T_FUNCTION);
},tryToPerform:function(methodName,arg1,arg2){return this.respondsTo(methodName)&&(this[methodName](arg1,arg2)!==NO);
},superclass:function(args){var caller=arguments.callee.caller;if(!caller){throw"superclass cannot determine the caller method";
}return caller.superclass?caller.superclass.apply(this,arguments):null;},instanceOf:function(scClass){return this.constructor===scClass;
},kindOf:function(scClass){return this.constructor.kindOf(scClass);},toString:function(){if(!this._object_toString){var klassName=SC._object_className(this.constructor);
var string="%@:%@".fmt(klassName,SC.guidFor(this));if(klassName){this._object_toString=string;
}else{return string;}}return this._object_toString;},awake:function(key){this.outlets.forEach(function(key){this.get(key);
},this);this.bindings.invoke("sync");},invokeOnce:function(method){SC.RunLoop.currentRunLoop.invokeOnce(this,method);
return this;},invokeLast:function(method){SC.RunLoop.currentRunLoop.invokeLast(this,method);
return this;},concatenatedProperties:["concatenatedProperties","initMixin","destroyMixin"]};
SC.Object.prototype.constructor=SC.Object;SC.mixin(SC.Object.prototype,SC.Observable);
function findClassNames(){if(SC._object_foundObjectClassNames){return;}SC._object_foundObjectClassNames=true;
var seen=[];var searchObject=function(root,object,levels){levels--;if(seen.indexOf(object)>=0){return;
}seen.push(object);for(var key in object){if(key=="__scope__"){continue;}if(key=="superclass"){continue;
}if(!key.match(/^[A-Z0-9]/)){continue;}var path=(root)?[root,key].join("."):key;var value=object[key];
switch(SC.typeOf(value)){case SC.T_CLASS:if(!value._object_className){value._object_className=path;
}if(levels>=0){searchObject(path,value,levels);}break;case SC.T_OBJECT:if(levels>=0){searchObject(path,value,levels);
}break;case SC.T_HASH:if(((root)||(path==="SC"))&&(levels>=0)){searchObject(path,value,levels);
}break;default:break;}}};searchObject(null,require("system:package").global,2);}SC.instanceOf=function(scObject,scClass){return !!(scObject&&scObject.constructor===scClass);
};SC.kindOf=function(scObject,scClass){if(scObject&&!scObject.isClass){scObject=scObject.constructor;
}return !!(scObject&&scObject.kindOf&&scObject.kindOf(scClass));};SC._object_className=function(obj){if(!SC.isReady){return"";
}if(!obj._object_className){findClassNames();}if(obj._object_className){return obj._object_className;
}var ret=obj;while(ret&&!ret._object_className){ret=ret.superclass;}return(ret&&ret._object_className)?ret._object_className:"Anonymous";
};});tiki.module("sproutcore/runtime:system/range_observer",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:private/observer_queue");require("sproutcore/runtime:system/index_set");
"import core";"import private/observer_queue";"import system/index_set";"export package";
SC.RangeObserver={isRangeObserver:YES,toString:function(){var base=this.indexes?this.indexes.toString():"SC.IndexSet<..>";
return base.replace("IndexSet","RangeObserver(%@)".fmt(SC.guidFor(this)));},create:function(source,indexSet,target,method,context,isDeep){var ret=SC.beget(this);
ret.source=source;ret.indexes=indexSet?indexSet.frozenCopy():null;ret.target=target;
ret.method=method;ret.context=context;ret.isDeep=isDeep||NO;ret.beginObserving();
return ret;},extend:function(attrs){var ret=SC.beget(this),args=arguments,len=args.length,idx;
for(idx=0;idx<len;idx++){SC.mixin(ret,args[idx]);}return ret;},destroy:function(source){this.endObserving();
return this;},update:function(source,indexSet){if(this.indexes&&this.indexes.isEqual(indexSet)){return this;
}this.indexes=indexSet?indexSet.frozenCopy():null;this.endObserving().beginObserving();
return this;},beginObserving:function(){if(!this.isDeep){return this;}var observing=this.observing;
if(!observing){observing=this.observing=SC.CoreSet.create();}var func=this._beginObservingForEach;
if(!func){func=this._beginObservingForEach=function(idx){var obj=this.source.objectAt(idx);
if(obj&&obj.addObserver){observing.push(obj);obj._kvo_needsRangeObserver=YES;}};}this.indexes.forEach(func,this);
this.isObserving=NO;SC.Observers.addPendingRangeObserver(this);return this;},setupPending:function(object){var observing=this.observing;
if(this.isObserving||!observing||(observing.get("length")===0)){return YES;}if(observing.contains(object)){this.isObserving=YES;
var func=this._setupPendingForEach;if(!func){var source=this.source,method=this.objectPropertyDidChange;
func=this._setupPendingForEach=function(idx){var obj=this.source.objectAt(idx),guid=SC.guidFor(obj),key;
if(obj&&obj.addObserver){observing.push(obj);obj.addObserver("*",this,method);key=this[guid];
if(key===undefined||key===null){this[guid]=idx;}else{if(key.isIndexSet){key.add(idx);
}else{key=this[guid]=SC.IndexSet.create(key).add(idx);}}}};}this.indexes.forEach(func,this);
return YES;}else{return NO;}},endObserving:function(){if(!this.isDeep){return this;
}var observing=this.observing;if(this.isObserving){var meth=this.objectPropertyDidChange,source=this.source,idx,lim,obj;
if(observing){lim=observing.length;for(idx=0;idx<lim;idx++){obj=observing[idx];obj.removeObserver("*",this,meth);
this[SC.guidFor(obj)]=null;}observing.length=0;}this.isObserving=NO;}if(observing){observing.clear();
}return this;},rangeDidChange:function(changes){var indexes=this.indexes;if(!changes||!indexes||indexes.intersects(changes)){this.endObserving();
this.method.call(this.target,this.source,null,"[]",changes,this.context);this.beginObserving();
}return this;},objectPropertyDidChange:function(object,key,value,rev){var context=this.context,method=this.method,guid=SC.guidFor(object),index=this[guid];
if(index&&!index.isIndexSet){index=this[guid]=SC.IndexSet.create(index).freeze();
}if(context){method.call(this.target,this.source,object,key,index,context,rev);}else{method.call(this.target,this.source,object,key,index,rev);
}}};});tiki.module("sproutcore/runtime:system/run_loop",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:private/observer_set");require("sproutcore/runtime:system/object");
"import core";"import private/observer_set";"import system/object";"export package";
SC.RunLoop=SC.Object.extend({beginRunLoop:function(){this._start=new Date().getTime();
if(SC.LOG_BINDINGS||SC.LOG_OBSERVERS){console.log("-- SC.RunLoop.beginRunLoop at %@".fmt(this._start));
}return this;},endRunLoop:function(){var didChange;if(SC.LOG_BINDINGS||SC.LOG_OBSERVERS){console.log("-- SC.RunLoop.endRunLoop ~ flushing application queues");
}do{didChange=this.flushApplicationQueues();if(!didChange){didChange=this._flushinvokeLastQueue();
}}while(didChange);this._start=null;if(SC.LOG_BINDINGS||SC.LOG_OBSERVERS){console.log("-- SC.RunLoop.endRunLoop ~ End");
}return this;},invokeOnce:function(target,method){if(method===undefined){method=target;
target=this;}if(SC.typeOf(method)===SC.T_STRING){method=target[method];}if(!this._invokeQueue){this._invokeQueue=SC.ObserverSet.create();
}this._invokeQueue.add(target,method);return this;},invokeLast:function(target,method){if(method===undefined){method=target;
target=this;}if(SC.typeOf(method)===SC.T_STRING){method=target[method];}if(!this._invokeLastQueue){this._invokeLastQueue=SC.ObserverSet.create();
}this._invokeLastQueue.add(target,method);return this;},flushApplicationQueues:function(){var hadContent=NO;
var queue=this._invokeQueue;if(queue&&queue.targets>0){this._invokeQueue=null;hadContent=YES;
queue.invokeMethods();}return SC.Binding.flushPendingChanges()||hadContent;},_flushinvokeLastQueue:function(){var queue=this._invokeLastQueue,hadContent=NO;
if(queue&&queue.targets>0){this._invokeLastQueue=null;hadContent=YES;if(hadContent){queue.invokeMethods();
}}return hadContent;}});SC.RunLoop.currentRunLoop=null;SC.RunLoop.runLoopClass=SC.RunLoop;
SC.RunLoop.begin=function(){var runLoop=this.currentRunLoop;if(!runLoop){runLoop=this.currentRunLoop=this.runLoopClass.create();
}runLoop.beginRunLoop();return this;};SC.RunLoop.end=function(){var runLoop=this.currentRunLoop;
if(!runLoop){throw"SC.RunLoop.end() called outside of a runloop!";}runLoop.endRunLoop();
return this;};SC.run=function(callback,target){SC.RunLoop.begin();callback.call(target);
SC.RunLoop.end();};});tiki.module("sproutcore/runtime:system/selection_set",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/object");require("sproutcore/runtime:mixins/enumerable");
require("sproutcore/runtime:mixins/copyable");require("sproutcore/runtime:mixins/freezable");
require("sproutcore/runtime:system/set");require("sproutcore/runtime:system/index_set");
"import core";"import system/object";"import mixins/enumerable";"import mixins/copyable";
"import mixins/freezable";"import system/set";"import system/index_set";"export package";
SC.SelectionSet=SC.Object.extend(SC.Enumerable,SC.Freezable,SC.Copyable,{isSelectionSet:YES,length:function(){var ret=0,sets=this._sets,objects=this._objects;
if(objects){ret+=objects.get("length");}if(sets){sets.forEach(function(s){ret+=s.get("length");
});}return ret;}.property().cacheable(),sources:function(){var ret=[],sets=this._sets,len=sets?sets.length:0,idx,set,source;
for(idx=0;idx<len;idx++){set=sets[idx];if(set&&set.get("length")>0&&set.source){ret.push(set.source);
}}return ret;}.property().cacheable(),indexSetForSource:function(source){if(!source||!source.isSCArray){return null;
}var cache=this._indexSetCache,objects=this._objects,ret,idx;if(!cache){cache=this._indexSetCache={};
}ret=cache[SC.guidFor(source)];if(ret&&ret._sourceRevision&&(ret._sourceRevision!==source.propertyRevision)){ret=null;
}if(!ret){ret=this._indexSetForSource(source,NO);if(ret&&ret.get("length")===0){ret=null;
}if(objects){if(ret){ret=ret.copy();}objects.forEach(function(o){if((idx=source.indexOf(o))>=0){if(!ret){ret=SC.IndexSet.create();
}ret.add(idx);}},this);}if(ret){ret=cache[SC.guidFor(source)]=ret.frozenCopy();ret._sourceRevision=source.propertyRevision;
}}return ret;},_indexSetForSource:function(source,canCreate){if(canCreate===undefined){canCreate=YES;
}var guid=SC.guidFor(source),index=this[guid],sets=this._sets,len=sets?sets.length:0,ret=null;
if(index>=len){index=null;}if(SC.none(index)){if(canCreate&&!this.isFrozen){this.propertyWillChange("sources");
if(!sets){sets=this._sets=[];}ret=sets[len]=SC.IndexSet.create();ret.source=source;
this[guid]=len;this.propertyDidChange("sources");}}else{ret=sets?sets[index]:null;
}return ret;},add:function(source,start,length){if(this.isFrozen){throw SC.FROZEN_ERROR;
}var sets,len,idx,set,oldlen,newlen,setlen,objects;if(start===undefined&&length===undefined){if(!source){throw"Must pass params to SC.SelectionSet.add()";
}if(source.isIndexSet){return this.add(source.source,source);}if(source.isSelectionSet){sets=source._sets;
objects=source._objects;len=sets?sets.length:0;this.beginPropertyChanges();for(idx=0;
idx<len;idx++){set=sets[idx];if(set&&set.get("length")>0){this.add(set.source,set);
}}if(objects){this.addObjects(objects);}this.endPropertyChanges();return this;}}set=this._indexSetForSource(source,YES);
oldlen=this.get("length");setlen=set.get("length");newlen=oldlen-setlen;set.add(start,length);
this._indexSetCache=null;newlen+=set.get("length");if(newlen!==oldlen){this.propertyDidChange("length");
this.enumerableContentDidChange();if(setlen===0){this.notifyPropertyChange("sources");
}}return this;},remove:function(source,start,length){if(this.isFrozen){throw SC.FROZEN_ERROR;
}var sets,len,idx,set,oldlen,newlen,setlen,objects;if(start===undefined&&length===undefined){if(!source){throw"Must pass params to SC.SelectionSet.remove()";
}if(source.isIndexSet){return this.remove(source.source,source);}if(source.isSelectionSet){sets=source._sets;
objects=source._objects;len=sets?sets.length:0;this.beginPropertyChanges();for(idx=0;
idx<len;idx++){set=sets[idx];if(set&&set.get("length")>0){this.remove(set.source,set);
}}if(objects){this.removeObjects(objects);}this.endPropertyChanges();return this;
}}set=this._indexSetForSource(source,YES);oldlen=this.get("length");newlen=oldlen-set.get("length");
if(set&&(objects=this._objects)){if(length!==undefined){start=SC.IndexSet.create(start,length);
length=undefined;}objects.forEach(function(object){idx=source.indexOf(object);if(start.contains(idx)){objects.remove(object);
newlen--;}},this);}set.remove(start,length);setlen=set.get("length");newlen+=setlen;
this._indexSetCache=null;if(newlen!==oldlen){this.propertyDidChange("length");this.enumerableContentDidChange();
if(setlen===0){this.notifyPropertyChange("sources");}}return this;},contains:function(source,start,length){if(start===undefined&&length===undefined){return this.containsObject(source);
}var set=this.indexSetForSource(source);if(!set){return NO;}return set.contains(start,length);
},intersects:function(source,start,length){var set=this.indexSetForSource(source,NO);
if(!set){return NO;}return set.intersects(start,length);},_TMP_ARY:[],addObject:function(object){var ary=this._TMP_ARY,ret;
ary[0]=object;ret=this.addObjects(ary);ary.length=0;return ret;},addObjects:function(objects){var cur=this._objects,oldlen,newlen;
if(!cur){cur=this._objects=SC.CoreSet.create();}oldlen=cur.get("length");cur.addEach(objects);
newlen=cur.get("length");this._indexSetCache=null;if(newlen!==oldlen){this.propertyDidChange("length");
this.enumerableContentDidChange();}return this;},removeObject:function(object){var ary=this._TMP_ARY,ret;
ary[0]=object;ret=this.removeObjects(ary);ary.length=0;return ret;},removeObjects:function(objects){var cur=this._objects,oldlen,newlen,sets;
if(!cur){return this;}oldlen=cur.get("length");cur.removeEach(objects);newlen=cur.get("length");
if(sets=this._sets){sets.forEach(function(set){oldlen+=set.get("length");set.removeObjects(objects);
newlen+=set.get("length");},this);}this._indexSetCache=null;if(newlen!==oldlen){this.propertyDidChange("length");
this.enumerableContentDidChange();}return this;},containsObject:function(object){var objects=this._objects;
if(objects&&objects.contains(object)){return YES;}var sets=this._sets,len=sets?sets.length:0,idx,set;
for(idx=0;idx<len;idx++){set=sets[idx];if(set&&set.indexOf(object)>=0){return YES;
}}return NO;},constrain:function(source){var set,len,max,objects;this.beginPropertyChanges();
this.get("sources").forEach(function(cur){if(cur===source){return;}var set=this._indexSetForSource(source,NO);
if(set){this.remove(source,set);}},this);set=this._indexSetForSource(source,NO);if(set&&((max=set.get("max"))>(len=source.get("length")))){this.remove(source,len,max-len);
}if(objects=this._objects){objects.forEach(function(cur){if(source.indexOf(cur)<0){this.removeObject(cur);
}},this);}this.endPropertyChanges();return this;},isEqual:function(obj){var left,right,idx,len,sources,source;
if(!obj||!obj.isSelectionSet){return NO;}if(obj===this){return YES;}if((this._sets===obj._sets)&&(this._objects===obj._objects)){return YES;
}if(this.get("length")!==obj.get("length")){return NO;}left=this._objects;right=obj._objects;
if(left||right){if((left?left.get("length"):0)!==(right?right.get("length"):0)){return NO;
}if(left&&!left.isEqual(right)){return NO;}}sources=this.get("sources");len=sources.get("length");
for(idx=0;idx<len;idx++){source=sources.objectAt(idx);left=this._indexSetForSource(source,NO);
right=this._indexSetForSource(source,NO);if(!!right!==!!left){return NO;}if(left&&!left.isEqual(right)){return NO;
}}return YES;},clear:function(){if(this.isFrozen){throw SC.FROZEN_ERROR;}if(this._sets){this._sets.length=0;
}if(this._objects){this._objects=null;}this._indexSetCache=null;this.propertyDidChange("length");
this.enumerableContentDidChange();this.notifyPropertyChange("sources");return this;
},copy:function(){var ret=this.constructor.create(),sets=this._sets,len=sets?sets.length:0,idx,set;
if(sets&&len>0){sets=ret._sets=sets.slice();for(idx=0;idx<len;idx++){if(!(set=sets[idx])){continue;
}set=sets[idx]=set.copy();ret[SC.guidFor(set.source)]=idx;}}if(this._objects){ret._objects=this._objects.copy();
}return ret;},freeze:function(){if(this.isFrozen){return this;}var sets=this._sets,loc=sets?sets.length:0,set;
while(--loc>=0){if(set=sets[loc]){set.freeze();}}if(this._objects){this._objects.freeze();
}return arguments.callee.base.apply(this,arguments);},toString:function(){var sets=this._sets||[];
sets=sets.map(function(set){return set.toString().replace("SC.IndexSet",SC.guidFor(set.source));
},this);if(this._objects){sets.push(this._objects.toString());}return"SC.SelectionSet:%@<%@>".fmt(SC.guidFor(this),sets.join(","));
},firstObject:function(){var sets=this._sets,objects=this._objects;if(sets&&sets.get("length")>0){var set=sets?sets[0]:null,src=set?set.source:null,idx=set?set.firstObject():-1;
if(src&&idx>=0){return src.objectAt(idx);}}return objects?objects.firstObject():undefined;
}.property(),nextObject:function(count,lastObject,context){var objects,ret;if(count===0){objects=context.objects=[];
this.forEach(function(o){objects.push(o);},this);context.max=objects.length;}objects=context.objects;
ret=objects[count];if(count+1>=context.max){context.objects=context.max=null;}return ret;
},forEach:function(callback,target){var sets=this._sets,objects=this._objects,len=sets?sets.length:0,set,idx;
for(idx=0;idx<len;idx++){set=sets[idx];if(set){set.forEachObject(callback,target);
}}if(objects){objects.forEach(callback,target);}return this;}});SC.SelectionSet.prototype.clone=SC.SelectionSet.prototype.copy;
SC.SelectionSet.EMPTY=SC.SelectionSet.create().freeze();});tiki.module("sproutcore/runtime:system/set",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:mixins/enumerable");require("sproutcore/runtime:mixins/copyable");
require("sproutcore/runtime:mixins/freezable");require("sproutcore/runtime:mixins/observable");
"import core";"import mixins/enumerable";"import mixins/copyable";"import mixins/freezable";
"import mixins/observable";"export package";SC.Set=SC.mixin({},SC.Enumerable,SC.Observable,SC.Freezable,{create:function(items){var ret,idx,pool=SC.Set._pool,isObservable=this.isObservable;
if(!isObservable&&items===undefined&&pool.length>0){ret=pool.pop();}else{ret=SC.beget(this);
if(isObservable){ret.initObservable();}if(items&&items.isEnumerable&&items.get("length")>0){ret.isObservable=NO;
if(items.isSCArray){idx=items.get?items.get("length"):items.length;while(--idx>=0){ret.add(items.objectAt(idx));
}}else{if(items.isSet){idx=items.length;while(--idx>=0){ret.add(items[idx]);}}else{items.forEach(function(i){ret.add(i);
},this);}}ret.isObservable=isObservable;}}return ret;},isSet:YES,length:0,firstObject:function(){return(this.length>0)?this[0]:undefined;
}.property(),clear:function(){if(this.isFrozen){throw SC.FROZEN_ERROR;}this.length=0;
return this;},contains:function(obj){if(obj===null){return NO;}var idx=this[SC.hashFor(obj)];
return(!SC.none(idx)&&(idx<this.length)&&(this[idx]===obj));},isEqual:function(obj){if(!obj||!obj.isSet||(obj.get("length")!==this.get("length"))){return NO;
}var loc=this.get("length");while(--loc>=0){if(!obj.contains(this[loc])){return NO;
}}return YES;},add:function(obj){if(this.isFrozen){throw SC.FROZEN_ERROR;}if(obj===null||obj===undefined){return this;
}var guid=SC.hashFor(obj);var idx=this[guid];var len=this.length;if((idx===null||idx===undefined)||(idx>=len)||(this[idx]!==obj)){this[len]=obj;
this[guid]=len;this.length=len+1;}if(this.isObservable){this.enumerableContentDidChange();
}return this;},addEach:function(objects){if(this.isFrozen){throw SC.FROZEN_ERROR;
}if(!objects||!objects.isEnumerable){throw"%@.addEach must pass enumerable".fmt(this);
}var idx,isObservable=this.isObservable;if(isObservable){this.beginPropertyChanges();
}if(objects.isSCArray){idx=objects.get("length");while(--idx>=0){this.add(objects.objectAt(idx));
}}else{if(objects.isSet){idx=objects.length;while(--idx>=0){this.add(objects[idx]);
}}else{objects.forEach(function(i){this.add(i);},this);}}if(isObservable){this.endPropertyChanges();
}return this;},remove:function(obj){if(this.isFrozen){throw SC.FROZEN_ERROR;}if(SC.none(obj)){return this;
}var guid=SC.hashFor(obj);var idx=this[guid];var len=this.length;if(SC.none(idx)||(idx>=len)||(this[idx]!==obj)){return this;
}delete this[guid];if(idx<(len-1)){obj=this[idx]=this[len-1];this[SC.hashFor(obj)]=idx;
}this.length=len-1;if(this.isObservable){this.enumerableContentDidChange();}return this;
},pop:function(){if(this.isFrozen){throw SC.FROZEN_ERROR;}var obj=(this.length>0)?this[this.length-1]:null;
if(obj){this.remove(obj);}return obj;},removeEach:function(objects){if(this.isFrozen){throw SC.FROZEN_ERROR;
}if(!objects||!objects.isEnumerable){throw"%@.addEach must pass enumerable".fmt(this);
}var idx,isObservable=this.isObservable;if(isObservable){this.beginPropertyChanges();
}if(objects.isSCArray){idx=objects.get("length");while(--idx>=0){this.remove(objects.objectAt(idx));
}}else{if(objects.isSet){idx=objects.length;while(--idx>=0){this.remove(objects[idx]);
}}else{objects.forEach(function(i){this.remove(i);},this);}}if(isObservable){this.endPropertyChanges();
}return this;},copy:function(){return this.constructor.create(this);},destroy:function(){this.isFrozen=NO;
if(!this.isObservable){SC.Set._pool.push(this.clear());}return this;},forEach:function(iterator,target){var len=this.length;
if(!target){target=this;}for(var idx=0;idx<len;idx++){iterator.call(target,this[idx],idx,this);
}return this;},toString:function(){var len=this.length,idx,ary=[];for(idx=0;idx<len;
idx++){ary[idx]=this[idx];}return"SC.Set<%@>".fmt(ary.join(","));},_pool:[],isObservable:YES});
SC.Set.constructor=SC.Set;SC.Set.clone=SC.Set.copy;SC.Set.push=SC.Set.unshift=SC.Set.add;
SC.Set.shift=SC.Set.pop;SC.Set.addObject=SC.Set.add;SC.Set.removeObject=SC.Set.remove;
SC.Set._pool=[];SC.CoreSet=SC.beget(SC.Set);SC.CoreSet.isObservable=NO;SC.CoreSet.constructor=SC.CoreSet;
});tiki.module("sproutcore/runtime:system/sparse_array",function(require,exports,module){var $m__=require("sproutcore/runtime:core"),SC=$m__.SC,SproutCore=$m__.SproutCore,YES=$m__.YES,NO=$m__.NO;
require("sproutcore/runtime:system/index_set");require("sproutcore/runtime:system/object");
require("sproutcore/runtime:mixins/enumerable");require("sproutcore/runtime:mixins/array");
require("sproutcore/runtime:mixins/delegate_support");"import core";"import system/index_set";
"import system/object";"import mixins/enumerable";"import mixins/array";"import mixins/delegate_support";
"export package";SC.SparseArray=SC.Object.extend(SC.Enumerable,SC.Array,SC.DelegateSupport,{_requestingLength:0,_requestingIndex:0,length:function(){var del=this.delegate;
if(del&&SC.none(this._length)&&del.sparseArrayDidRequestLength){this._requestingLength++;
del.sparseArrayDidRequestLength(this);this._requestingLength--;}return this._length||0;
}.property().cacheable(),provideLength:function(length){if(SC.none(length)){this._sa_content=null;
}if(length!==this._length){this._length=length;if(this._requestingLength<=0){this.enumerableContentDidChange();
}}return this;},rangeWindowSize:1,requestedRangeIndex:[],objectAt:function(idx){var content=this._sa_content,ret;
if(!content){content=this._sa_content=[];}if((ret=content[idx])===undefined){this.requestIndex(idx);
ret=content[idx];}return ret;},definedIndexes:function(indexes){var ret=SC.IndexSet.create(),content=this._sa_content,idx,len;
if(!content){return ret.freeze();}if(indexes){indexes.forEach(function(idx){if(content[idx]!==undefined){ret.add(idx);
}});}else{len=content.length;for(idx=0;idx<len;idx++){if(content[idx]!==undefined){ret.add(idx);
}}}return ret.freeze();},_TMP_RANGE:{},requestIndex:function(idx){var del=this.delegate;
if(!del){return this;}var len=this.get("rangeWindowSize"),start=idx;if(len>1){start=start-Math.floor(start%len);
}if(len<1){len=1;}this._requestingIndex++;if(del.sparseArrayDidRequestRange){var range=this._TMP_RANGE;
if(this.wasRangeRequested(start)===-1){range.start=start;range.length=len;del.sparseArrayDidRequestRange(this,range);
this.requestedRangeIndex.push(start);}}else{if(del.sparseArrayDidRequestIndex){while(--len>=0){del.sparseArrayDidRequestIndex(this,start+len);
}}}this._requestingIndex--;return this;},wasRangeRequested:function(rangeStart){var i,ilen;
for(i=0,ilen=this.requestedRangeIndex.length;i<ilen;i++){if(this.requestedRangeIndex[i]===rangeStart){return i;
}}return -1;},rangeRequestCompleted:function(start){var i=this.wasRangeRequested(start);
if(i>=0){this.requestedRangeIndex.removeAt(i,1);return YES;}return NO;},provideObjectsInRange:function(range,array){var content=this._sa_content;
if(!content){content=this._sa_content=[];}var start=range.start,len=range.length;
while(--len>=0){content[start+len]=array[len];}if(this._requestingIndex<=0){this.enumerableContentDidChange();
}return this;},_TMP_PROVIDE_ARRAY:[],_TMP_PROVIDE_RANGE:{length:1},provideObjectAtIndex:function(index,object){var array=this._TMP_PROVIDE_ARRAY,range=this._TMP_PROVIDE_RANGE;
array[0]=object;range.start=index;return this.provideObjectsInRange(range,array);
},objectsDidChangeInRange:function(range){var content=this._sa_content;if(content){if(range.start===0&&SC.maxRange(range)>=content.length){this._sa_content=null;
}else{var start=range.start,loc=Math.min(start+range.length,content.length);while(--loc>=start){content[loc]=undefined;
}}}this.enumerableContentDidChange(range);return this;},indexOf:function(obj){var del=this.delegate;
if(del&&del.sparseArrayDidRequestIndexOf){return del.sparseArrayDidRequestIndexOf(this,obj);
}else{var content=this._sa_content;if(!content){content=this._sa_content=[];}return content.indexOf(obj);
}},replace:function(idx,amt,objects){objects=objects||[];var del=this.delegate;if(del){if(!del.sparseArrayShouldReplace||!del.sparseArrayShouldReplace(this,idx,amt,objects)){return this;
}}var content=this._sa_content;if(!content){content=this._sa_content=[];}content.replace(idx,amt,objects);
var len=objects?(objects.get?objects.get("length"):objects.length):0;var delta=len-amt;
if(!SC.none(this._length)){this.propertyWillChange("length");this._length+=delta;
this.propertyDidChange("length");}this.enumerableContentDidChange(idx,amt,delta);
return this;},reset:function(){this._sa_content=null;this._length=null;this.enumerableContentDidChange();
this.invokeDelegateMethod(this.delegate,"sparseArrayDidReset",this);return this;}});
SC.SparseArray.array=function(len){return this.create({_length:len||0});};});tiki.module("sproutcore/runtime:package",function(require,exports,module){var m;
m=require("sproutcore/runtime:core");exports.SC=m.SC;exports.SproutCore=m.SproutCore;
exports.YES=m.YES;exports.NO=m.NO;require("sproutcore/runtime:mixins/array");require("sproutcore/runtime:mixins/comparable");
require("sproutcore/runtime:mixins/copyable");require("sproutcore/runtime:mixins/delegate_support");
require("sproutcore/runtime:mixins/enumerable");require("sproutcore/runtime:mixins/freezable");
require("sproutcore/runtime:mixins/observable");require("sproutcore/runtime:system/binding");
require("sproutcore/runtime:system/cookie");require("sproutcore/runtime:system/enumerator");
require("sproutcore/runtime:system/error");require("sproutcore/runtime:system/index_set");
require("sproutcore/runtime:system/logger");require("sproutcore/runtime:system/object");
require("sproutcore/runtime:system/range_observer");require("sproutcore/runtime:system/run_loop");
require("sproutcore/runtime:system/selection_set");require("sproutcore/runtime:system/set");
require("sproutcore/runtime:system/sparse_array");});tiki.script("sproutcore/runtime:en/cca71b2c8ec71645c88d40a948f81436bff9a7f3/javascript.js");
tiki.register("sproutcore/datastore",{"depends":["sproutcore/runtime"],"packages":{"sproutcore/runtime":{}},"scripts":[{"url":"/static/sproutcore/datastore/en/b3d882bb66846ea67e40aafb234e0da54bf57b3e/javascript.js","id":"sproutcore/datastore:en/b3d882bb66846ea67e40aafb234e0da54bf57b3e/javascript.js"}]});
tiki.global("sproutcore/datastore");tiki.script("sproutcore/datastore:en/b3d882bb66846ea67e40aafb234e0da54bf57b3e/javascript.js");
tiki.register("sproutcore/foundation",{"depends":["sproutcore/runtime"],"packages":{"sproutcore/runtime":{}},"scripts":[{"url":"/static/sproutcore/foundation/en/668e188bd44c10fb9ca18d37e89878e7aac1402d/javascript.js","id":"sproutcore/foundation:en/668e188bd44c10fb9ca18d37e89878e7aac1402d/javascript.js"}]});
tiki.global("sproutcore/foundation");SC.Locale=SC.Object.extend({init:function(){if(!this.language){SC.Locale._assignLocales();
}if(!this.hasStrings){var langs=this._deprecatedLanguageCodes||[];langs.push(this.language);
var idx=langs.length;var strings=null;while(!strings&&--idx>=0){strings=String[langs[idx]];
}if(strings){this.hasStrings=YES;this.strings=strings;}}},hasStrings:NO,strings:{},toString:function(){if(!this.language){SC.Locale._assignLocales();
}return"SC.Locale["+this.language+"]"+SC.guidFor(this);},locWithDefault:function(string,def){return this.strings[string]||def||string;
}});SC.Locale.mixin({useAutodetectedLanguage:NO,preferredLanguage:null,createCurrentLocale:function(){var autodetect=(String.useAutodetectedLanguage!==undefined)?String.useAutodetectedLanguage:this.useAutodetectedLanguage;
var preferred=(String.preferredLanguage!==undefined)?String.preferredLanguage:this.preferredLanguage;
var lang=((autodetect)?SC.browser.language:null)||preferred||SC.browser.language||"en";
lang=SC.Locale.normalizeLanguage(lang);var klass=this.localeClassFor(lang);if(lang!=this.currentLanguage){this.currentLanguage=lang;
this.currentLocale=klass.create();}return this.currentLocale;},localeClassFor:function(lang){lang=SC.Locale.normalizeLanguage(lang);
var parent,klass=this.locales[lang];if(!klass&&((parent=lang.split("-")[0])!==lang)&&(klass=this.locales[parent])){klass=this.locales[lang]=klass.extend();
}if(!klass){klass=this.locales[lang]=this.locales.en.extend();}return klass;},define:function(localeName,options){var locale;
if(options===undefined&&(SC.typeOf(localeName)!==SC.T_STRING)){locale=this;options=localeName;
}else{locale=SC.Locale.localeClassFor(localeName);}SC.mixin(locale.prototype,options);
return locale;},options:function(){return this.prototype;},addStrings:function(stringsHash){var strings=this.prototype.strings;
if(strings){if(!this.prototype.hasOwnProperty("strings")){this.prototype.strings=SC.clone(strings);
}}else{strings=this.prototype.strings={};}if(stringsHash){this.prototype.strings=SC.mixin(strings,stringsHash);
}this.prototype.hasStrings=YES;return this;},_map:{english:"en",french:"fr",german:"de",japanese:"ja",jp:"ja",spanish:"es"},normalizeLanguage:function(languageCode){if(!languageCode){return"en";
}return SC.Locale._map[languageCode.toLowerCase()]||languageCode;},_assignLocales:function(){for(var key in this.locales){this.locales[key].prototype.language=key;
}},toString:function(){if(!this.prototype.language){SC.Locale._assignLocales();}return"SC.Locale["+this.prototype.language+"]";
},extend:function(){var ret=SC.Object.extend.apply(this,arguments);ret.addStrings=SC.Locale.addStrings;
ret.define=SC.Locale.define;ret.options=SC.Locale.options;ret.toString=SC.Locale.toString;
return ret;}});SC.Locale.locales={en:SC.Locale.extend({_deprecatedLanguageCodes:["English"]}),fr:SC.Locale.extend({_deprecatedLanguageCodes:["French"]}),de:SC.Locale.extend({_deprecatedLanguageCodes:["German"]}),ja:SC.Locale.extend({_deprecatedLanguageCodes:["Japanese","jp"]}),es:SC.Locale.extend({_deprecatedLanguageCodes:["Spanish"]})};
SC.stringsFor=function(languageCode,strings){var locale=SC.Locale.localeClassFor(languageCode);
locale.addStrings(strings);return this;};sc_require("system/locale");SC.stringsFor("English",{"_SC.DateTime.dayNames":"Sunday Monday Tuesday Wednesday Thursday Friday Saturday","_SC.DateTime.abbreviatedDayNames":"Sun Mon Tue Wed Thu Fri Sat","_SC.DateTime.monthNames":"January February March April May June July August September October November December","_SC.DateTime.abbreviatedMonthNames":"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"});
SC.DROP_ON=1;SC.DROP_BEFORE=2;SC.DROP_AFTER=4;SC.DROP_ANY=7;SC.mixin({data:function(elem,name,data){elem=(elem===window)?"@window":elem;
var hash=SC.hashFor(elem);var cache=SC._data_cache;if(!cache){SC._data_cache=cache={};
}var elemCache=cache[hash];if(name&&!elemCache){cache[hash]=elemCache={};}if(elemCache&&(data!==undefined)){elemCache[name]=data;
}return(name)?elemCache[name]:elemCache;},removeData:function(elem,name){elem=(elem===window)?"@window":elem;
var hash=SC.hashFor(elem);var cache=SC._data_cache;if(!cache){return undefined;}var elemCache=cache[hash];
if(!elemCache){return undefined;}var ret=(name)?elemCache[name]:elemCache;if(name){delete elemCache[name];
}else{delete cache[hash];}return ret;}});SC.mixin(Function.prototype,{invokeLater:function(target,interval){if(interval===undefined){interval=1;
}var f=this;if(arguments.length>2){var args=SC.$A(arguments).slice(2,arguments.length);
args.unshift(target);var that=this,func=f;f=function(){return func.apply(that,args.slice(1));
};}return SC.Timer.schedule({target:target,action:f,interval:interval});}});SC.Controller=SC.Object.extend({isEditable:YES});
SC.mixin(SC.Object.prototype,{invokeLater:function(methodName,interval){if(interval===undefined){interval=1;
}var f=methodName,args,func;if(arguments.length>2){args=SC.$A(arguments).slice(2);
if(SC.typeOf(f)===SC.T_STRING){f=this[methodName];}func=f;f=function(){return func.apply(this,args);
};}return SC.Timer.schedule({target:this,action:f,interval:interval});},invokeWith:function(pathName,target,method){if(method===undefined){method=target;
target=this;}if(!target){target=this;}if(SC.typeOf(method)===SC.T_STRING){method=target[method];
}var v=this.getPath(pathName);method.call(target,v,this);return this;}});SC.RunLoop=SC.RunLoop.extend({startTime:function(){if(!this._start){this._start=Date.now();
}return this._start;}.property(),endRunLoop:function(){this.fireExpiredTimers();var ret=arguments.callee.base.apply(this,arguments);
this.scheduleNextTimeout();return ret;},scheduleTimer:function(timer,runTime){this._timerQueue=timer.removeFromTimerQueue(this._timerQueue);
this._timerQueue=timer.scheduleInTimerQueue(this._timerQueue,runTime);return this;
},cancelTimer:function(timer){this._timerQueue=timer.removeFromTimerQueue(this._timerQueue);
return this;},TIMER_ARRAY:[],fireExpiredTimers:function(){if(!this._timerQueue||this._firing){return NO;
}var now=this.get("startTime");this._firing=YES;var timers=this.TIMER_ARRAY;this._timerQueue=this._timerQueue.collectExpiredTimers(timers,now);
var idx,len=timers.length;for(idx=0;idx<len;idx++){timers[idx].fire();}var didFire=timers.length>0;
timers.length=0;this._firing=NO;return didFire;},scheduleNextTimeout:function(){var timer=this._timerQueue;
var ret=NO;if(!timer){if(this._timeout){clearTimeout(this._timeout);}}else{var nextTimeoutAt=timer._timerQueueRunTime;
if(this._timeoutAt!==nextTimeoutAt){if(this._timeout){clearTimeout(this._timeout);
}var delay=Math.max(0,nextTimeoutAt-Date.now());this._timeout=setTimeout(this._timeoutDidFire,delay);
this._timeoutAt=nextTimeoutAt;}ret=YES;}return ret;},_timeoutDidFire:function(){var rl=SC.RunLoop.currentRunLoop;
rl._timeout=rl._timeoutAt=null;SC.RunLoop.begin().end();}});SC.RunLoop.currentRunLoop=SC.RunLoop.create();
/* @license

Portions of this software are copyright Yahoo, Inc, used under the following license:

Software License Agreement (BSD License)
Copyright (c) 2009, Yahoo! Inc.
All rights reserved.
Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Sources of Intellectual Property Included in the YUI Library
Where not otherwise indicated, all YUI content is authored by Yahoo! engineers and consists of Yahoo!-owned intellectual property. YUI is issued by Yahoo! under the BSD license above. In some specific instances, YUI will incorporate work done by developers outside of Yahoo! with their express permission.

*/
SC.BRANCH_OPEN=17;
SC.BRANCH_CLOSED=18;SC.LEAF_NODE=32;SC.CollectionContent={isCollectionContent:YES,contentIndexIsSelected:function(view,content,idx){var sel=view.get("selection");
return sel?sel.contains(content,idx):NO;},contentIndexIsEnabled:function(view,content,idx){return view.get("isEnabled");
},contentGroupIndexes:function(view,content){return null;},contentIndexIsGroup:function(view,content,idx){return NO;
},contentIndexOutlineLevel:function(view,content,idx){return -1;},contentIndexDisclosureState:function(view,content,idx){return SC.LEAF_NODE;
},contentIndexExpand:function(view,content,idx){console.log("contentIndexExpand(%@, %@, %@)".fmt(view,content,idx));
},contentIndexCollapse:function(view,content,idx){console.log("contentIndexCollapse(%@, %@, %@)".fmt(view,content,idx));
}};SC.ContentDisplay={concatenatedProperties:"contentDisplayProperties",displayProperties:["content"],contentDisplayProperties:[],_display_contentDidChange:function(target,key,value){if((value=this.get("content"))!=this._display_content){var f=this._display_contentPropertyDidChange;
var content=this._display_content;if(content){if(SC.isArray(content)){content.invoke("removeObserver","*",this,f);
}else{if(content.removeObserver){content.removeObserver("*",this,f);}}}content=this._display_content=value;
if(content){if(SC.isArray(content)){content.invoke("addObserver","*",this,f);}else{if(content.addObserver){content.addObserver("*",this,f);
}}}this.allPropertiesDidChange();this.endPropertyChanges();}}.observes("content"),_display_contentPropertyDidChange:function(target,key,value,propertyRevision){if(key==="*"){this.displayDidChange();
}else{var ary=this.get("contentDisplayProperties");if(ary&&ary.indexOf(key)>=0){this.displayDidChange();
}}}};sc_require("system/locale");SC.STRING_TITLEIZE_REGEXP=(/([\s|\-|\_|\n])([^\s|\-|\_|\n]?)/g);
SC.String={loc:function(){if(!SC.Locale.currentLocale){SC.Locale.createCurrentLocale();
}var str=SC.Locale.currentLocale.locWithDefault(this)||this;return str.fmt.apply(str,arguments);
},locWithDefault:function(def){if(!SC.Locale.currentLocale){SC.Locale.createCurrentLocale();
}var str=SC.Locale.currentLocale.locWithDefault(def)||this;var args=SC.$A(arguments);
args.shift();return str.fmt.apply(str,args);},capitalize:function(){return this.charAt(0).toUpperCase()+this.slice(1);
},capitalizeEach:function(){return this.replace(SC.STRING_TITLEIZE_REGEXP,function(str,sep,character){return(character)?(sep+character.toUpperCase()):sep;
}).capitalize();},titleize:function(){var ret=this.replace(/([a-z])([A-Z])/g,"$1_$2");
return ret.replace(SC.STRING_TITLEIZE_REGEXP,function(str,separater,character){return(character)?(" "+character.toUpperCase()):" ";
}).capitalize();},camelize:function(){var ret=this.replace(SC.STRING_TITLEIZE_REGEXP,function(str,separater,character){return(character)?character.toUpperCase():"";
});var first=ret.charAt(0),lower=first.toLowerCase();return(first!==lower)?(lower+ret.slice(1)):ret;
},classify:function(){var ret=this.replace(SC.STRING_TITLEIZE_REGEXP,function(str,separater,character){return(character)?character.toUpperCase():"";
});var first=ret.charAt(0),upper=first.toUpperCase();return(first!==upper)?(upper+ret.slice(1)):ret;
},decamelize:function(){return this.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();
},dasherize:function(){return this.decamelize().replace(/[ _]/g,"-");},humanize:function(){return this.decamelize().replace(/[\-_]/g," ");
},removeDiacritics:function(){var diacriticMappingTable=SC.diacriticMappingTable;
if(!diacriticMappingTable){SC.diacriticMappingTable={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Ā":"A","Ă":"A","Ą":"A","Ǎ":"A","Ǟ":"A","Ǡ":"A","Ǻ":"A","Ȁ":"A","Ȃ":"A","Ȧ":"A","Ḁ":"A","Ạ":"A","Ả":"A","Ấ":"A","Ầ":"A","Ẩ":"A","Ẫ":"A","Ậ":"A","Ắ":"A","Ằ":"A","Ẳ":"A","Ẵ":"A","Ặ":"A","Å":"A","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ç":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ḉ":"C","Ď":"D","Ḋ":"D","Ḍ":"D","Ḏ":"D","Ḑ":"D","Ḓ":"D","È":"E","É":"E","Ê":"E","Ë":"E","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ȩ":"E","Ḕ":"E","Ḗ":"E","Ḙ":"E","Ḛ":"E","Ḝ":"E","Ẹ":"E","Ẻ":"E","Ẽ":"E","Ế":"E","Ề":"E","Ể":"E","Ễ":"E","Ệ":"E","Ḟ":"F","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","Ǧ":"G","Ǵ":"G","Ḡ":"G","Ĥ":"H","Ȟ":"H","Ḣ":"H","Ḥ":"H","Ḧ":"H","Ḩ":"H","Ḫ":"H","Ì":"I","Í":"I","Î":"I","Ï":"I","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ḭ":"I","Ḯ":"I","Ỉ":"I","Ị":"I","Ĵ":"J","Ķ":"K","Ǩ":"K","Ḱ":"K","Ḳ":"K","Ḵ":"K","Ĺ":"L","Ļ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ḻ":"L","Ḽ":"L","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ñ":"N","Ń":"N","Ņ":"N","Ň":"N","Ǹ":"N","Ṅ":"N","Ṇ":"N","Ṉ":"N","Ṋ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ō":"O","Ŏ":"O","Ő":"O","Ơ":"O","Ǒ":"O","Ǫ":"O","Ǭ":"O","Ȍ":"O","Ȏ":"O","Ȫ":"O","Ȭ":"O","Ȯ":"O","Ȱ":"O","Ṍ":"O","Ṏ":"O","Ṑ":"O","Ṓ":"O","Ọ":"O","Ỏ":"O","Ố":"O","Ồ":"O","Ổ":"O","Ỗ":"O","Ộ":"O","Ớ":"O","Ờ":"O","Ở":"O","Ỡ":"O","Ợ":"O","Ṕ":"P","Ṗ":"P","Ŕ":"R","Ŗ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṙ":"R","Ṛ":"R","Ṝ":"R","Ṟ":"R","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","Ș":"S","Ṡ":"S","Ṣ":"S","Ṥ":"S","Ṧ":"S","Ṩ":"S","Ţ":"T","Ť":"T","Ț":"T","Ṫ":"T","Ṭ":"T","Ṯ":"T","Ṱ":"T","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","Ư":"U","Ǔ":"U","Ǖ":"U","Ǘ":"U","Ǚ":"U","Ǜ":"U","Ȕ":"U","Ȗ":"U","Ṳ":"U","Ṵ":"U","Ṷ":"U","Ṹ":"U","Ṻ":"U","Ụ":"U","Ủ":"U","Ứ":"U","Ừ":"U","Ử":"U","Ữ":"U","Ự":"U","Ṽ":"V","Ṿ":"V","Ŵ":"W","Ẁ":"W","Ẃ":"W","Ẅ":"W","Ẇ":"W","Ẉ":"W","Ẋ":"X","Ẍ":"X","Ý":"Y","Ŷ":"Y","Ÿ":"Y","Ȳ":"Y","Ẏ":"Y","Ỳ":"Y","Ỵ":"Y","Ỷ":"Y","Ỹ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","Ẑ":"Z","Ẓ":"Z","Ẕ":"Z","`":"`","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","ā":"a","ă":"a","ą":"a","ǎ":"a","ǟ":"a","ǡ":"a","ǻ":"a","ȁ":"a","ȃ":"a","ȧ":"a","ḁ":"a","ạ":"a","ả":"a","ấ":"a","ầ":"a","ẩ":"a","ẫ":"a","ậ":"a","ắ":"a","ằ":"a","ẳ":"a","ẵ":"a","ặ":"a","ḃ":"b","ḅ":"b","ḇ":"b","ç":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ḉ":"c","ď":"d","ḋ":"d","ḍ":"d","ḏ":"d","ḑ":"d","ḓ":"d","è":"e","é":"e","ê":"e","ë":"e","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","ȅ":"e","ȇ":"e","ȩ":"e","ḕ":"e","ḗ":"e","ḙ":"e","ḛ":"e","ḝ":"e","ẹ":"e","ẻ":"e","ẽ":"e","ế":"e","ề":"e","ể":"e","ễ":"e","ệ":"e","ḟ":"f","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","ǧ":"g","ǵ":"g","ḡ":"g","ĥ":"h","ȟ":"h","ḣ":"h","ḥ":"h","ḧ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ì":"i","í":"i","î":"i","ï":"i","ĩ":"i","ī":"i","ĭ":"i","į":"i","ǐ":"i","ȉ":"i","ȋ":"i","ḭ":"i","ḯ":"i","ỉ":"i","ị":"i","ĵ":"j","ǰ":"j","ķ":"k","ǩ":"k","ḱ":"k","ḳ":"k","ḵ":"k","ĺ":"l","ļ":"l","ľ":"l","ḷ":"l","ḹ":"l","ḻ":"l","ḽ":"l","ḿ":"m","ṁ":"m","ṃ":"m","ñ":"n","ń":"n","ņ":"n","ň":"n","ǹ":"n","ṅ":"n","ṇ":"n","ṉ":"n","ṋ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ō":"o","ŏ":"o","ő":"o","ơ":"o","ǒ":"o","ǫ":"o","ǭ":"o","ȍ":"o","ȏ":"o","ȫ":"o","ȭ":"o","ȯ":"o","ȱ":"o","ṍ":"o","ṏ":"o","ṑ":"o","ṓ":"o","ọ":"o","ỏ":"o","ố":"o","ồ":"o","ổ":"o","ỗ":"o","ộ":"o","ớ":"o","ờ":"o","ở":"o","ỡ":"o","ợ":"o","ṕ":"p","ṗ":"p","ŕ":"r","ŗ":"r","ř":"r","ȑ":"r","ȓ":"r","ṙ":"r","ṛ":"r","ṝ":"r","ṟ":"r","ś":"s","ŝ":"s","ş":"s","š":"s","ș":"s","ṡ":"s","ṣ":"s","ṥ":"s","ṧ":"s","ṩ":"s","ţ":"t","ť":"t","ț":"t","ṫ":"t","ṭ":"t","ṯ":"t","ṱ":"t","ẗ":"t","ù":"u","ú":"u","û":"u","ü":"u","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","ư":"u","ǔ":"u","ǖ":"u","ǘ":"u","ǚ":"u","ǜ":"u","ȕ":"u","ȗ":"u","ṳ":"u","ṵ":"u","ṷ":"u","ṹ":"u","ṻ":"u","ụ":"u","ủ":"u","ứ":"u","ừ":"u","ử":"u","ữ":"u","ự":"u","ṽ":"v","ṿ":"v","ŵ":"w","ẁ":"w","ẃ":"w","ẅ":"w","ẇ":"w","ẉ":"w","ẘ":"w","ẋ":"x","ẍ":"x","ý":"y","ÿ":"y","ŷ":"y","ȳ":"y","ẏ":"y","ẙ":"y","ỳ":"y","ỵ":"y","ỷ":"y","ỹ":"y","ź":"z","ż":"z","ž":"z","ẑ":"z","ẓ":"z","ẕ":"z"};
diacriticMappingTable=SC.diacriticMappingTable;}var original,replacement;var ret="";
var length=this.length;for(var i=0;i<=length;++i){original=this.charAt(i);replacement=diacriticMappingTable[original];
if(replacement){ret+=replacement;}else{ret+=original;}}return ret;},trim:function(){return this.replace(/^\s+|\s+$/g,"");
},trimLeft:function(){return this.replace(/^\s+/g,"");},trimRight:function(){return this.replace(/\s+$/g,"");
}};SC.String.strip=SC.String.trim;SC.supplement(String.prototype,SC.String);String.prototype.loc=SC.String.loc;
SC.String.fmt=String.prototype.fmt;sc_require("mixins/string");SC.MIXED_STATE="__MIXED__";
SC.HUGE_CONTROL_SIZE="sc-huge-size";SC.LARGE_CONTROL_SIZE="sc-large-size";SC.REGULAR_CONTROL_SIZE="sc-regular-size";
SC.SMALL_CONTROL_SIZE="sc-small-size";SC.TINY_CONTROL_SIZE="sc-tiny-size";SC.Control={initMixin:function(){this._control_contentDidChange();
},isSelected:NO,isSelectedBindingDefault:SC.Binding.oneWay().bool(),isActive:NO,isActiveBindingDefault:SC.Binding.oneWay().bool(),value:null,content:null,contentValueKey:null,contentPropertyDidChange:function(target,key){return this.updatePropertyFromContent("value",key,"contentValueKey");
},updatePropertyFromContent:function(prop,key,contentKey,content){var all=key==="*";
if(contentKey===undefined){contentKey="content%@Key".fmt(prop.capitalize());}if(content===undefined){content=this.get("content");
}contentKey=this[contentKey]?this.get(contentKey):this.getDelegateProperty(contentKey,this.displayDelegate);
if(contentKey&&(all||key===contentKey)){var v=(content)?(content.get?content.get(contentKey):content[contentKey]):null;
this.set(prop,v);}return this;},updateContentWithValueObserver:function(){var key=this.contentValueKey?this.get("contentValueKey"):this.getDelegateProperty("contentValueKey",this.displayDelegate);
var content=this.get("content");if(!key||!content){return;}var value=this.get("value");
if(typeof content.setIfChanged===SC.T_FUNCTION){content.setIfChanged(key,value);}else{if(content[key]!==value){content[key]=value;
}}}.observes("value"),fieldKey:null,fieldLabel:null,errorLabel:function(){var ret,fk,def;
if(ret=this.get("fieldLabel")){return ret;}fk=this.get("fieldKey")||this.constructor.toString();
def=(fk||"").humanize().capitalize();return"ErrorLabel.%@".fmt(fk).locWithDefault("FieldKey.%@".fmt(fk).locWithDefault(def));
}.property("fieldLabel","fieldKey").cacheable(),controlSize:SC.REGULAR_CONTROL_SIZE,displayProperties:"isEnabled isSelected isActive controlSize".w(),_CONTROL_TMP_CLASSNAMES:{},renderMixin:function(context,firstTime){var sel=this.get("isSelected"),disabled=!this.get("isEnabled");
var names=this._CONTROL_TMP_CLASSNAMES;names.mixed=sel===SC.MIXED_STATE;names.sel=sel&&(sel!==SC.MIXED_STATE);
names.active=this.get("isActive");context.setClass(names).addClass(this.get("controlSize"));
if(!firstTime&&this.$input){this.$input().attr("disabled",disabled);}},_control_content:null,_control_contentDidChange:function(){var content=this.get("content");
if(this._control_content===content){return;}var f=this.contentPropertyDidChange;var old=this._control_content;
if(old&&old.removeObserver){old.removeObserver("*",this,f);}this._control_content=content;
if(content&&content.addObserver){content.addObserver("*",this,f);}this.contentPropertyDidChange(content,"*");
}.observes("content")};SC.Editable={isEditable:NO,isEditing:NO,beginEditing:function(){if(!this.get("isEditable")){return NO;
}if(this.get("isEditing")){return YES;}this.set("isEditing",YES);this.becomeFirstResponder();
return YES;},discardEditing:function(){return !this.get("isEditing");},commitEditing:function(){if(!this.get("isEditing")){return YES;
}this.set("isEditing",NO);this.resignFirstResponder();return YES;}};SC.SelectionSupport={hasSelectionSupport:YES,allowsSelection:YES,allowsMultipleSelection:YES,allowsEmptySelection:YES,firstSelectableObject:function(){return this.get("firstObject");
}.property(),selection:function(key,value){var old=this._scsel_selection,oldlen=old?old.get("length"):0,content,empty,len;
if((value===undefined)||!this.get("allowsSelection")){value=old;}len=(value&&value.isEnumerable)?value.get("length"):0;
if((len>1)&&!this.get("allowsMultipleSelection")){if(oldlen>1){value=SC.SelectionSet.create().addObject(old.get("firstObject")).freeze();
len=1;}else{value=old;len=oldlen;}}if((len===0)&&!this.get("allowsEmptySelection")){if(oldlen===0){value=this.get("firstSelectableObject");
if(value){value=SC.SelectionSet.create().addObject(value).freeze();}else{value=SC.SelectionSet.EMPTY;
}len=value.get("length");}else{value=old;len=oldlen;}}if(len===0){value=SC.SelectionSet.EMPTY;
}value=value.frozenCopy();this._scsel_selection=value;return value;}.property("arrangedObjects","allowsEmptySelection","allowsMultipleSelection","allowsSelection").cacheable(),hasSelection:function(){var sel=this.get("selection");
return !!sel&&(sel.get("length")>0);}.property("selection").cacheable(),selectObjects:function(objects,extend){if(!objects||objects.get("length")===0){if(!extend){this.set("selection",SC.SelectionSet.EMPTY);
}return this;}var sel=this.get("selection");if(extend&&sel){sel=sel.copy();}else{sel=SC.SelectionSet.create();
}sel.addObjects(objects).freeze();this.set("selection",sel);return this;},selectObject:function(object,extend){if(object===null){if(!extend){this.set("selection",null);
}return this;}else{return this.selectObjects([object],extend);}},deselectObjects:function(objects){if(!objects||objects.get("length")===0){return this;
}var sel=this.get("selection");if(!sel||sel.get("length")===0){return this;}sel=sel.copy().removeObjects(objects).freeze();
this.set("selection",sel.freeze());return this;},deselectObject:function(object){if(!object){return this;
}else{return this.deselectObjects([object]);}},updateSelectionAfterContentChange:function(){var content=this.get("arrangedObjects"),sel=this.get("selection"),ret=sel,indexes,len,max;
if(ret&&content&&ret.get("sources").indexOf(content)>=0){indexes=ret.indexSetForSource(content);
len=content.get("length");max=indexes?indexes.get("max"):0;if(max>len){ret=ret.copy().remove(content,len,max-len).freeze();
this.set("selection",ret);}}if(ret===sel){len=sel?sel.get("length"):0;max=content?content.get("length"):0;
if((len===0)&&!this.get("allowsEmptySelection")&&max>0){this.notifyPropertyChange("selection");
}}return this;}};SC.StaticLayout={hasStaticLayout:YES,useStaticLayout:NO,renderMixin:function(context,firstTime){context.setClass("sc-static-layout",this.get("useStaticLayout"));
},clippingFrame:null,parentViewDidResize:null,beginLiveResize:null,endLiveResize:null,viewDidResize:null};
SC.TreeItemContent={isTreeItemContent:YES,treeItemChildren:null,treeItemIsExpanded:YES,treeItemIsGrouped:NO,treeItemDisclosureState:function(parent,idx){return this.get("treeItemIsExpanded")?SC.BRANCH_OPEN:SC.BRANCH_CLOSED;
},treeItemCollapse:function(parent,idx){this.setIfChanged("treeItemIsExpanded",NO);
},treeItemExpand:function(parent,idx){this.setIfChanged("treeItemIsExpanded",YES);
},treeItemBranchIndexes:function(parent,index){var children=this.get("treeItemChildren"),ret,lim,idx,item;
if(!children){return null;}ret=SC.IndexSet.create();lim=children.get("length");for(idx=0;
idx<lim;idx++){if(!(item=children.objectAt(idx))){continue;}if(!item.get("treeItemChildren")){continue;
}if(item.treeItemDisclosureState(this,idx)!==SC.LEAF_NODE){ret.add(idx);}}return ret.get("length")>0?ret:null;
}};SC.Validatable={initMixin:function(){this._validatable_validatorDidChange();},validator:null,errorLabel:null,isValid:function(){return SC.typeOf(this.get("value"))!==SC.T_ERROR;
}.property("value"),ownerForm:null,performValidate:function(partialChange){var ret=SC.VALIDATE_OK;
if(this._validator){var form=this.get("ownerForm");if(partialChange){ret=this._validator.validatePartial(form,this);
if((ret==SC.VALIDATE_NO_CHANGE)&&(this._validator.validateChange(form,this)==SC.VALIDATE_OK)){ret=SC.VALIDATE_OK;
}}else{ret=this._validator.validateChange(form,this);}}return ret;},performValidateSubmit:function(){return this._validator?this._validator.validateSubmit(this.get("ownerForm"),this):SC.VALIDATE_OK;
},performValidateKeyDown:function(evt){var charStr=evt.getCharString();if(!charStr){return YES;
}return this._validator?this._validator.validateKeyDown(this.get("ownerForm"),this,charStr):YES;
},validatorObject:function(){return this._validator;}.property(),validateSubmit:function(){return this.performValidateSubmit();
},objectForFieldValue:function(fieldValue,partialChange){return this._validator?this._validator.objectForFieldValue(fieldValue,this.get("ownerForm"),this):fieldValue;
},fieldValueForObject:function(object){return this._validator?this._validator.fieldValueForObject(object,this.get("ownerForm"),this):object;
},_validatable_displayObserver:function(){this.displayDidChange();}.observes("isValid"),updateLayerMixin:function(context){context.setClass("invalid",!this.get("isValid"));
},_validatable_validatorDidChange:function(){var form=this.get("ownerForm");var val=SC.Validator.findFor(form,this,this.get("validator"));
if(val!=this._validator){this.propertyWillChange("validatorObject");if(this._validator){this._validator.detachFrom(form,this);
}this._validator=val;if(this._validator){this._validator.attachTo(form,this);}this.propertyDidChange("validatorObject");
}}.observes("validator","ownerForm")};SC.browser=(function(){var userAgent=navigator.userAgent.toLowerCase();
var version=(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1];var browser={version:version,safari:(/webkit/).test(userAgent)?version:0,opera:(/opera/).test(userAgent)?version:0,msie:(/msie/).test(userAgent)&&!(/opera/).test(userAgent)?version:0,mozilla:(/mozilla/).test(userAgent)&&!(/(compatible|webkit)/).test(userAgent)?version:0,mobileSafari:(/apple.*mobile.*safari/).test(userAgent)?version:0,windows:!!(/(windows)/).test(userAgent),mac:!!((/(macintosh)/).test(userAgent)||(/(mac os x)/).test(userAgent)),language:(navigator.language||navigator.browserLanguage).split("-",1)[0]};
SC.extend(browser,{isOpera:!!browser.opera,isIe:!!browser.msie,isIE:!!browser.msie,isSafari:!!browser.safari,isMobileSafari:!!browser.mobileSafari,isMozilla:!!browser.mozilla,isWindows:!!browser.windows,isMac:!!browser.mac,current:browser.msie?"msie":browser.mozilla?"mozilla":browser.safari?"safari":browser.opera?"opera":"unknown"});
return browser;})();SC.Builder=function(props){return SC.Builder.create(props);};
SC.Builder.create=function create(props){var fn=SC.mixin(SC.beget(this.fn),props||{});
if(props.hasOwnProperty("toString")){fn.toString=props.toString;}var construct=function(){var ret=SC.beget(fn);
ret.defaultClass=this;ret.constructor=construct;return ret.init.apply(ret,arguments);
};construct.fn=construct.prototype=fn;construct.extend=SC.Builder.create;construct.mixin=SC.Builder.mixin;
return construct;};SC.Builder.mixin=function(){var len=arguments.length,idx;for(idx=0;
idx<len;idx++){SC.mixin(this,arguments[idx]);}return this;};SC.Builder.fn={init:function(content){if(content!==undefined){if(SC.typeOf(content)===SC.T_ARRAY){var loc=content.length;
while(--loc>=0){this[loc]=content.objectAt?content.objectAt(loc):content[loc];}this.length=content.length;
}else{this[0]=content;this.length=1;}}return this;},size:function(){return this.length;
},pushStack:function(){var ret=this.constructor.apply(this,arguments);ret.prevObject=this;
return ret;},end:function(){return this.prevObject||this.constructor();},toString:function(){return"%@$(%@)".fmt(this.defaultClass.toString(),SC.A(this).invoke("toString").join(","));
},mixin:SC.Builder.mixin};(function(){var enumerable=SC.Enumerable,fn=SC.Builder.fn,key,value;
for(key in enumerable){if(!enumerable.hasOwnProperty(key)){continue;}value=Array.prototype[key]||enumerable[key];
fn[key]=value;}})();sc_require("system/builder");SC.CoreQuery=(function(){var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;
var styleFloat=SC.browser.msie?"styleFloat":"cssFloat";var chars=(SC.browser.safari&&parseInt(SC.browser.version,0)<417)?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)";
var quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)");var singleClass=new RegExp("^([#.]?)("+chars+"*)");
var quickSplit=new RegExp("([#.]?)("+chars+"*)","g");var LEFT_RIGHT=["Left","Right"];
var TOP_BOTTOM=["Top","Bottom"];var CSS_DISPLAY_PROPS={position:"absolute",visibility:"hidden",display:"block"};
var getWH=function getWH(elem,name,which){var val=name=="width"?elem.offsetWidth:elem.offsetHeight;
var padding=0,border=0,loc=which.length,dim;while(--loc>=0){dim=which[loc];padding+=parseFloat(CQ.curCSS(elem,"padding"+dim,true))||0;
border+=parseFloat(CQ.curCSS(elem,"border"+dim+"Width",true))||0;}val-=Math.round(padding+border);
return val;};var expando=SC.guidKey,uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};
var styleIsBorked=function styleIsBorked(elem){if(!SC.browser.safari){return false;
}var ret=defaultView.getComputedStyle(elem,null);return !ret||ret.getPropertyValue("color")=="";
};function num(elem,prop){return elem[0]&&parseInt(CQ.curCSS(elem[0],prop,true),10)||0;
}var CoreQuery,CQ;CQ=CoreQuery=SC.Builder.create({jquery:"SC.CoreQuery",init:function(selector,context){selector=selector||document;
if(selector.nodeType){this[0]=selector;this.length=1;return this;}else{if(typeof selector==="string"){var match=quickExpr.exec(selector);
if(match&&(match[1]||!context)){if(match[1]){selector=CQ.clean([match[1]],context);
}else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3]){return CQ().find(selector);
}return CQ(elem);}selector=[];}}else{return CQ(context).find(selector);}}else{if(SC.typeOf(selector)===SC.T_FUNCTION){return SC.ready(selector);
}}}return this.setArray(CQ.makeArray(selector));},size:function(){return this.length;
},get:function(num){return num===undefined?CQ.makeArray(this):this[num];},find:function(selector){var elems=CQ.map(this,function(elem){return CQ.find(selector,elem);
});return this.pushStack(elems);},filter:function(selector){return this.pushStack((SC.typeOf(selector)===SC.T_FUNCTION)&&CQ.grep(this,function(elem,i){return selector.call(elem,i);
})||CQ.multiFilter(selector,this));},not:function(selector){if(typeof selector==="string"){if(isSimple.test(selector)){return this.pushStack(CQ.multiFilter(selector,this,true));
}else{selector=CQ.multiFilter(selector,this);}}var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;
return this.filter(function(){return isArrayLike?CQ.inArray(this,selector)<0:this!=selector;
});},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);
return this;},map:function(callback){return this.pushStack(CQ.map(this,function(elem,i){return callback.call(elem,i,elem);
}));},each:function(callback,args){return CQ.each(this,callback,args);},index:function(elem){if(elem&&elem.jquery){elem=elem[0];
}return Array.prototype.indexOf.call(this,elem);},eq:function(i){return this.slice(i,+i+1);
},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));
},add:function(selector){return this.pushStack(CQ.merge(this.get(),typeof selector==="string"?CQ(selector):CQ.makeArray(selector)).uniq());
},attr:function(name,value,type){var options=name;if(typeof name==="string"){if(value===undefined){return this[0]&&CQ[type||"attr"](this[0],name);
}else{options={};options[name]=value;}}return this.each(function(i){for(name in options){CQ.attr((type)?this.style:this,name,CQ.prop(this,options[name],type,i,name));
}});},html:function(value){return value===undefined?(this[0]?this[0].innerHTML.replace(/ CQ\d+="(?:\d+|null)"/g,""):null):this.empty().append(value);
},andSelf:function(){return this.add(this.prevObject);},is:function(selector){return !!selector&&CQ.multiFilter(selector,this).length>0;
},hasClass:function(className){return Array.prototype.every.call(this,function(elem){return(elem.nodeType!=1)||CQ.className.has(elem,className);
});},val:function(value){if(value===undefined){var elem=this[0];if(elem){if(CQ.nodeName(elem,"option")){return(elem.attributes.value||{}).specified?elem.value:elem.text;
}if(CQ.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";
if(index<0){return null;}var i,max=one?index+1:options.length;for(i=one?index:0;i<max;
i++){var option=options[i];if(option.selected){value=CQ(option).val();if(one){return value;
}values.push(value);}}return values;}return(elem.value||"").replace(/\r/g,"");}return undefined;
}else{if(typeof value==="number"){value+="";}this.each(function(){if(this.nodeType!=1){return;
}if(SC.typeOf(value)===SC.T_ARRAY&&(/radio|checkbox/).test(this.type)){this.checked=(CQ.inArray(this.value,value)>=0||CQ.inArray(this.name,value)>=0);
}else{if(CQ.nodeName(this,"select")){var values=CQ.makeArray(value);CQ("option",this).each(function(){this.selected=(CQ.inArray(this.value,values)>=0||CQ.inArray(this.text,values)>=0);
});if(!values.length){this.selectedIndex=-1;}}else{this.value=value;}}});}return this;
},clone:function(){var ret=this.map(function(){if(SC.browser.msie&&!CQ.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");
container.appendChild(clone);return CQ.clean([container.innerHTML])[0];}else{return this.cloneNode(true);
}});var clone=ret.find("*").andSelf().each(function(){if(this[SC.guidKey]!==undefined){this[SC.guidKey]=null;
}});return ret;},css:function(key,value){if((key=="width"||key=="height")&&parseFloat(value,0)<0){value=undefined;
}return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!=="object"&&text!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));
}var ret="";CQ.each(text||this,function(){CQ.each(this.childNodes,function(){if(this.nodeType!=8){ret+=this.nodeType!=1?this.nodeValue:CQ.fn.text([this]);
}});});return ret;},show:function(){var isVisible=SC.$.isVisible;this.each(function(){if(!isVisible(this)){this.style.display=this.oldblock||"";
if(CQ.css(this,"display")=="none"){var elem=CQ("<"+this.tagName+"/>");CQ("body").append(elem);
this.style.display=elem.css("display");if(this.style.display==="none"){this.style.display="block";
}elem.remove();elem=null;}}});return this;},hide:function(){var isVisible=SC.$.isVisible;
this.each(function(){if(isVisible(this)){this.oldblock=this.oldblock||CQ.css(this,"display");
this.style.display="none";}});return this;},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;
return this.each(function(){if(!elems){elems=CQ.clean(args,this.ownerDocument);if(reverse){elems.reverse();
}}var obj=this;if(table&&CQ.nodeName(this,"table")&&CQ.nodeName(elems[0],"tr")){obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));
}CQ.each(elems,function(){var elem=clone?CQ(this).clone(true)[0]:this;callback.call(obj,elem);
});});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1){this.appendChild(elem);
}});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1){this.insertBefore(elem,this.firstChild);
}});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);
});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);
});},replaceWith:function(value){return this.after(value).remove();},removeData:function(key){return this.each(function(){SC.removeData(this,key);
});}});CoreQuery.mixin({nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();
},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;
i++){var value=callback(elems[i],i);if(value!=null){ret[ret.length]=value;}}return ret.concat.apply([],ret);
},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length===undefined){for(name in object){if(callback.apply(object[name],args)===false){break;
}}}else{for(;i<length;){if(callback.apply(object[i++],args)===false){break;}}}}else{if(length===undefined){for(name in object){if(callback.call(object[name],name,object[name])===false){break;
}}}else{for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}}return object;
},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;
},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=="undefined"){context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;
}CQ.each(elems,function(i,elem){if(typeof elem==="number"){elem+="";}if(!elem){return;
}if(typeof elem==="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";
});var tags=elem.replace(/^\s+/,"").substring(0,10).toLowerCase(),div=context.createElement("div");
var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||SC.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];
div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--){div=div.lastChild;}if(SC.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];
for(var j=tbody.length-1;j>=0;--j){if(CQ.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length){tbody[j].parentNode.removeChild(tbody[j]);
}}if(/^\s/.test(elem)){div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);
}}elem=CQ.makeArray(div.childNodes);}if(elem.length===0&&(!CQ.nodeName(elem,"form")&&!CQ.nodeName(elem,"select"))){return;
}if(elem[0]===undefined||CQ.nodeName(elem,"form")||elem.options){ret.push(elem);}else{ret=CQ.merge(ret,elem);
}});return ret;},find:function(t,context){if(typeof t!="string"){return[t];}if(t.indexOf(",")>=0){var ret=t.split(",").map(function(sel){return CQ.find(sel,context);
});return ret.concat.apply([],ret).uniq();}if(context&&context.nodeType!=1&&context.nodeType!=9){return[];
}context=context||document;var ret=[context],nodeName,inFindMode=YES;var parts=t.match(quickSplit),len=parts.length,m;
for(var idx=0;idx<len;idx++){t=parts[idx];if(t===" "||t===""){inFindMode=YES;}else{if(inFindMode){m=singleClass.exec(t);
if((m[1]==="")&&(idx<(len-1))&&(parts[idx+1].charAt(0)==="#")){t=parts[idx+1];parts[idx+1]=parts[idx];
m=singleClass.exec(t);}var next=[],retlen=ret.length,retidx,cur,val=m[2],found;for(retidx=0;
retidx<retlen;retidx++){cur=ret[retidx];switch(m[1]){case"":if(!val){val="*";}if(val=="*"&&cur.nodeName.toLowerCase()=="object"){val="param";
}next=CQ.merge(next,cur.getElementsByTagName(val));break;case"#":if(cur===document){found=document.getElementById(val);
if(SC.browser.msie&&found&&found.getAttribute("id")!==val){found=NO;}else{if(found){next.push(found);
}found=YES;}}else{found=NO;}if(!found){found=cur.getElementsByTagName("*");found=Array.prototype.find.call(found,function(el){return el.getAttribute&&(el.getAttribute("id")===val);
});if(found){next.push(found);}}break;case".":if(cur.getElementsByClassName){next=CQ.merge(next,cur.getElementsByClassName(val));
}else{next=CQ.merge(next,CQ.classFilter(cur.getElementsByTagName("*"),val));}break;
default:}}delete ret;ret=next;inFindMode=NO;}else{ret=CQ.filter(t,ret);}}}if(ret&&ret[0]==context){ret.shift();
}return ret.uniq();},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;
r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass){tmp.push(r[i]);
}}return tmp;},filter:function(t,r,not){var m=singleClass.exec(t),val=m[2],kind=m[1],filter;
if(kind==="."){return CQ.classFilter(CQ.makeArray(r),val,not);}else{if(kind==="#"){filter=function(el){var ret=el&&el.getAttribute&&(el.getAttribute("id")===val);
return(not)?!ret:ret;};}else{filter=function(el){var ret=CQ.nodeName(el,val);return(not)?!ret:ret;
};}return Array.prototype.filter.call(CQ.makeArray(r),filter);}},multiFilter:function(expr,elems,not){expr=(expr.indexOf(","))?expr.split(","):[expr];
var loc=expr.length,cur,ret=[];while(--loc>=0){cur=CQ.filter(expr[loc].trim(),elems,not);
ret=not?elems=cur:CQ.merge(cur,ret);}return ret;},merge:function(first,second){var i=0,elem,pos=first.length;
if(SC.browser.msie){while(elem=second[i++]){if(elem.nodeType!=8){first[pos++]=elem;
}}}else{while(elem=second[i++]){first[pos++]=elem;}}return first;},makeArray:function(array){var ret=[];
if(array!=null){var i=array.length;if(i==null||typeof array==="string"||array.setInterval){ret[0]=array;
}else{while(i){ret[--i]=array[i];}}}return ret;},inArray:function(elem,array){return(array.indexOf)?array.indexOf(elem):Array.prototype.indexOf.call(array,elem);
},boxModel:!SC.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan"},prop:function(elem,value,type,i,name){if(SC.typeOf(value)===SC.T_FUNCTION){value=value.call(elem,i);
}return value&&(typeof value==="number")&&type=="curCSS"&&!exclude.test(name)?value+"px":value;
},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;
i++){if(!inv!=!callback(elems[i],i)){ret.push(elems[i]);}}return ret;},className:{add:function(elem,classNames){var has=CQ.className.has;
CQ.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!has(elem.className,className)){elem.className+=(elem.className?" ":"")+className;
}});},remove:function(elem,classNames){if(elem.nodeType==1){elem.className=classNames!==undefined?CQ.grep(elem.className.split(/\s+/),function(className){return !CQ.className.has(classNames,className);
}).join(" "):"";}},has:function(elem,className){return elem&&CQ.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;
}},swap:function(elem,options,callback,direction,arg){var old={};for(var name in options){old[name]=elem.style[name];
elem.style[name]=options[name];}var ret=callback(elem,direction,arg);for(var name in options){elem.style[name]=old[name];
}return ret;},css:function(elem,name,force){if(name=="width"||name=="height"){var val,which=(name=="width")?LEFT_RIGHT:TOP_BOTTOM,props=CSS_DISPLAY_PROPS;
val=SC.$.isVisible(elem)?getWH(elem,name,which):CQ.swap(elem,props,getWH,name,which);
return Math.max(0,val);}return CQ.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;
if(name=="opacity"&&SC.browser.msie){ret=CQ.attr(style,"opacity");return ret==""?"1":ret;
}if(SC.browser.opera&&name==="display"){var save=style.outline;style.outline="0 solid black";
style.outline=save;}var isFloat=name.match(/float/i);if(isFloat){name=styleFloat;
}if(!force&&style&&style[name]){ret=style[name];}else{if(defaultView.getComputedStyle){if(isFloat){name="float";
}name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);
if(computedStyle&&!styleIsBorked(elem,defaultView)){ret=computedStyle.getPropertyValue(name);
}else{var swap=[],stack=[],a=elem,i=0,swLen,stLen;for(;a&&styleIsBorked(a);a=a.parentNode){stack.unshift(a);
}for(stLen=stack.length;i<stLen;i++){if(styleIsBorked(stack[i])){swap[i]=stack[i].style.display;
stack[i].style.display="block";}}ret=(name=="display"&&swap[stack.length-1]!=null)?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";
for(i=0,swLen=swap.length;i<swLen;i++){if(swap[i]!=null){stack[i].style.display=swap[i];
}}}if(name=="opacity"&&ret==""){ret="1";}}else{if(elem.currentStyle){ret=elem.currentStyle[name]||elem.currentStyle[name.camelize()];
if(!(/^\d+(px)?$/i).test(ret)&&(/^\d/).test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;
elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";
style.left=left;elem.runtimeStyle.left=rsLeft;}}}}return ret;},dir:function(elem,dir){var matched=[],cur=elem[dir];
while(cur&&cur!=document){if(cur.nodeType==1){matched.push(cur);}cur=cur[dir];}return matched;
},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir]){if(cur.nodeType==1&&++num==result){break;
}}return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem){r.push(n);
}}return r;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8){return undefined;
}var notxml=!CQ.isXMLDoc(elem),set=value!==undefined,msie=SC.browser.msie;name=notxml&&CQ.props[name]||name;
if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&elem.parentNode){elem.parentNode.selectedIndex;
}if(name in elem&&notxml&&!special){if(set){if(name=="type"&&CQ.nodeName(elem,"input")&&elem.parentNode){throw"type property can't be changed";
}elem[name]=value;}if(CQ.nodeName(elem,"form")&&elem.getAttributeNode(name)){return elem.getAttributeNode(name).nodeValue;
}if(name=="tabIndex"){var attributeNode=elem.getAttributeNode("tabIndex");return attributeNode&&attributeNode.specified?attributeNode.value:elem.nodeName.match(/(button|input|object|select|textarea)/i)?0:elem.nodeName.match(/^(a|area)$/i)&&elem.href?0:undefined;
}return elem[name];}if(msie&&notxml&&name==="style"){return CQ.attr(elem.style,"cssText",value);
}if(set){elem.setAttribute(name,""+value);}var attr=(msie&&notxml&&special)?elem.getAttribute(name,2):elem.getAttribute(name);
return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;
elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value,0)+""=="NaN"?"":"alpha(opacity="+value*100+")");
}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+"":"";
}name=name.camelize();if(set){elem[name]=value;}return elem[name];}});CQ.fn.init.prototype=CQ.fn;
CQ.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return CQ.dir(elem,"parentNode");
},next:function(elem){return CQ.nth(elem,2,"nextSibling");},prev:function(elem){return CQ.nth(elem,2,"previousSibling");
},nextAll:function(elem){return CQ.dir(elem,"nextSibling");},prevAll:function(elem){return CQ.dir(elem,"previousSibling");
},siblings:function(elem){return CQ.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return CQ.sibling(elem.firstChild);
},contents:function(elem){return CQ.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:CQ.makeArray(elem.childNodes);
}},function(name,fn){CQ.fn[name]=function(selector){var ret=CQ.map(this,fn);if(selector&&typeof selector=="string"){ret=CQ.multiFilter(selector,ret);
}return this.pushStack(ret.uniq());};});CQ.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){CQ.fn[name]=function(){var args=arguments;
return this.each(function(){for(var i=0,length=args.length;i<length;i++){CQ(args[i])[original](this);
}});};});CQ.each({removeAttr:function(name){CQ.attr(this,name,"");if(this.nodeType==1){this.removeAttribute(name);
}},addClass:function(classNames){CQ.className.add(this,classNames);},removeClass:function(classNames){CQ.className.remove(this,classNames);
},toggleClass:function(classNames){CQ.className[CQ.className.has(this,classNames)?"remove":"add"](this,classNames);
},remove:function(selector){if(!selector||CQ.filter(selector,[this]).length){if(this.parentNode){this.parentNode.removeChild(this);
}}},empty:function(){while(this.firstChild){this.removeChild(this.firstChild);}}},function(name,fn){CQ.fn[name]=function(){return this.each(fn,arguments);
};});CQ.each(["Height","Width"],function(i,name){var type=name.toLowerCase();CQ.fn[type]=function(size){if(this[0]===window){if(SC.browser.opera){ret=document.body["client"+name];
}else{if(SC.browser.safari){ret=window["inner"+name];}else{if(document.compatMode){ret=documentElement["client"+name];
}else{ret=document.body["client"+name];}}}}else{if(this[0]===document){ret=Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name]));
}else{if(size==undefined){return this.length?CQ.css(this[0],type):null;}else{return this.css(type,(typeof size==="string")?size:size+"px");
}}}return ret;};var tl=i?"Left":"Top",br=i?"Right":"Bottom";CQ.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);
};CQ.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);
};});CoreQuery.fn.offset=function(){var left=0,top=0,elem=this[0],br=SC.browser,results;
if(!elem){return undefined;}function border(elem){add(CQ.curCSS(elem,"borderLeftWidth",true),CQ.curCSS(elem,"borderTopWidth",true));
}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=br.safari&&parseInt(br.version,0)<522&&!(/adobeair/i).test(br.userAgent),css=CQ.curCSS,fixed=CQ.css(elem,"position")=="fixed";
if(!(br.mozilla&&elem==document.body)&&elem.getBoundingClientRect){var box=elem.getBoundingClientRect();
add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));
add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);
while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(br.mozilla&&!(/^t(able|d|h)$/i).test(offsetParent.tagName)||br.safari&&!safari2){border(offsetParent);
}if(!fixed&&css(offsetParent,"position")=="fixed"){fixed=true;}offsetChild=(/^body$/i).test(offsetParent.tagName)?offsetChild:offsetParent;
offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!(/^body|html$/i).test(parent.tagName)){if(!(/^inline|table.*$/i).test(css(parent,"display"))){add(-parent.scrollLeft,-parent.scrollTop);
}if(br.mozilla&&css(parent,"overflow")!="visible"){border(parent);}parent=parent.parentNode;
}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(br.mozilla&&css(offsetChild,"position")!="absolute")){add(-doc.body.offsetLeft,-doc.body.offsetTop);
}if(fixed){add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));
}}results={top:top,left:left};return results;};CoreQuery.fn.mixin({position:function(){var left=0,top=0,results;
if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();
offset.top-=num(this,"marginTop");offset.left-=num(this,"marginLeft");parentOffset.top+=num(offsetParent,"borderTopWidth");
parentOffset.left+=num(offsetParent,"borderLeftWidth");results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};
}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent||document.body;
while(offsetParent&&(!(/^body|html$/i).test(offsetParent.tagName)&&CQ.css(offsetParent,"position")=="static")){offsetParent=offsetParent.offsetParent;
}return CQ(offsetParent);}});CQ.each(["Left","Top"],function(i,name){var method="scroll"+name;
CQ.fn[method]=function(val){if(!this[0]){return;}return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:CQ(window).scrollLeft(),i?val:CQ(window).scrollTop()):this[method]=val;
}):this[0]==window||this[0]==document?self[i?"pageYOffset":"pageXOffset"]||CQ.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];
};});return CoreQuery;}());SC.$=(typeof jQuery=="undefined")?SC.CoreQuery:jQuery;
SC.mixin(SC.$.fn,{isCoreQuery:YES,toString:function(){var values=[];var len=this.length,idx=0;
for(idx=0;idx<len;idx++){values[idx]="%@: %@".fmt(idx,(this[idx])?this[idx].toString():"(null)");
}return"<$:%@>(%@)".fmt(SC.guidFor(this),values.join(" , "));},isVisible:function(){return Array.prototype.every.call(this,function(elem){return SC.$.isVisible(elem);
});},first:function(){return this.pushStack([this[0]]);},last:function(){return this.pushStack([this[this.length-1]]);
},view:function(){return this.map(function(){var ret=null,guidKey=SC.viewKey,dom=this,value;
while(!ret&&dom&&(dom!==document)){if(value=dom.getAttribute("id")){ret=SC.View.views[value];
}dom=dom.parentNode;}dom=null;return ret;});},setClass:function(className,shouldAdd){if(SC.none(className)){return this;
}var isHash=SC.typeOf(className)!==SC.T_STRING;var fix=this._fixupClass,key;this.each(function(){if(this.nodeType!==1){return;
}var classNames=this.className.split(/\s+/),didChange=NO;if(isHash){for(var key in className){if(!className.hasOwnProperty(key)){continue;
}didChange=fix(classNames,key,className[key])||didChange;}}else{didChange=fix(classNames,className,shouldAdd);
}if(didChange){this.className=classNames.join(" ");}});return this;},_fixupClass:function(classNames,name,shouldAdd){var indexOf=classNames.indexOf(name);
if(shouldAdd){if(indexOf<0){classNames.push(name);return YES;}}else{if(indexOf>=0){classNames[indexOf]=null;
return YES;}}return NO;},within:function(el){el=SC.$(el);var ret,elCur,myCur,idx,len=el.length;
var loc=this.length;while(!ret&&(--loc>=0)){myCur=this[loc];for(idx=0;!ret&&(idx<len);
idx++){elCur=el[idx];while(elCur&&(elCur!==myCur)){elCur=elCur.parentNode;}ret=elCur===myCur;
}}myCur=elCur=null;return ret;}});(function(){var original={};var wrappers={find:function(callback,target){return(target!==undefined)?SC.Enumerable.find.call(this,callback,target):original.find.call(this,callback);
},filter:function(callback,target){return(target!==undefined)?this.pushStack(SC.Enumerable.filter.call(this,callback,target)):original.filter.call(this,callback);
},filterProperty:function(key,value){return this.pushStack(SC.Enumerable.filterProperty.call(this,key,value));
},indexOf:SC.$.index,map:function(callback,target){return(target!==undefined)?SC.Enumerable.map.call(this,callback,target):original.map.call(this,callback);
}};var isCoreQuery=SC.$.jquery==="SC.CoreQuery";var fn=SC.$.fn,enumerable=isCoreQuery?wrappers:SC.Enumerable;
for(var key in enumerable){if(!enumerable.hasOwnProperty(key)){continue;}var value=enumerable[key];
if(key in wrappers){original[key]=fn[key];value=wrappers[key];}fn[key]=value;}})();
SC.mixin(SC.$,{isVisible:function(elem){var CQ=SC.$;return("hidden"!=elem.type)&&(CQ.css(elem,"display")!="none")&&(CQ.css(elem,"visibility")!="hidden");
}});sc_require("system/core_query");SC.Event=function(originalEvent){if(originalEvent){this.originalEvent=originalEvent;
var props=SC.Event._props,len=props.length,idx=len,key;while(--idx>=0){key=props[idx];
this[key]=originalEvent[key];}}this.timeStamp=this.timeStamp||Date.now();if(!this.target){this.target=this.srcElement||document;
}if(this.target.nodeType===3){this.target=this.target.parentNode;}if(!this.relatedTarget&&this.fromElement){this.relatedTarget=(this.fromElement===this.target)?this.toElement:this.fromElement;
}if(SC.none(this.pageX)&&!SC.none(this.clientX)){var doc=document.documentElement,body=document.body;
this.pageX=this.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);
this.pageY=this.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);
}if(!this.which&&((this.charCode||originalEvent.charCode===0)?this.charCode:this.keyCode)){this.which=this.charCode||this.keyCode;
}if(!this.metaKey&&this.ctrlKey){this.metaKey=this.ctrlKey;}if(!this.which&&this.button){this.which=((this.button&1)?1:((this.button&2)?3:((this.button&4)?2:0)));
}if(SC.browser.safari&&originalEvent.wheelDelta!==undefined){this.wheelDelta=this.wheelDeltaY=0-(originalEvent.wheelDeltaY||originalEvent.wheelDelta);
this.wheelDeltaX=0-(originalEvent.wheelDeltaX||0);}else{if(!SC.none(originalEvent.detail)){var detail=Math.floor(originalEvent.detail*2);
if(originalEvent.axis&&(originalEvent.axis===originalEvent.HORIZONTAL_AXIS)){this.wheelDeltaX=detail;
this.wheelDeltaY=this.wheelDelta=0;}else{this.wheelDeltaY=this.wheelDelta=detail;
this.wheelDeltaX=0;}}else{this.wheelDelta=this.wheelDeltaY=SC.browser.msie?0-originalEvent.wheelDelta:originalEvent.wheelDelta;
this.wheelDeltaX=0;}}return this;};SC.mixin(SC.Event,{create:function(e){return new SC.Event(e);
},add:function(elem,eventType,target,method,context){if(elem&&elem.isCoreQuery){if(elem.length>0){elem.forEach(function(e){this.add(e,eventType,target,method,context);
},this);return this;}else{elem=elem.get(0);}}if(!elem){return this;}if(elem.nodeType==3||elem.nodeType==8){return SC.Event;
}if(SC.browser.msie&&elem.setInterval){elem=window;}if(SC.typeOf(target)===SC.T_FUNCTION){context=method;
method=target;target=null;}else{if(target&&SC.typeOf(method)===SC.T_STRING){method=target[method];
}}var events=SC.data(elem,"events")||SC.data(elem,"events",{}),handlers=events[eventType];
if(!handlers){handlers=events[eventType]={};this._addEventListener(elem,eventType);
}handlers[SC.guidFor(method)]=[target,method,context];SC.Event._global[eventType]=YES;
elem=events=handlers=null;return this;},remove:function(elem,eventType,target,method){if(elem&&elem.isCoreQuery){if(elem.length>0){elem.forEach(function(e){this.remove(e,eventType,target,method);
},this);return this;}else{elem=elem.get(0);}}if(!elem){return this;}if(elem.nodeType==3||elem.nodeType==8){return SC.Event;
}if(SC.browser.msie&&elem.setInterval){elem=window;}var handlers,key,events=SC.data(elem,"events");
if(!events){return this;}if(eventType===undefined){for(eventType in events){this.remove(elem,eventType);
}}else{if(handlers=events[eventType]){var cleanupHandlers=NO;if(target||method){if(SC.typeOf(target)===SC.T_FUNCTION){method=target;
target=null;}else{if(SC.typeOf(method)===SC.T_STRING){method=target[method];}}delete handlers[SC.guidFor(method)];
key=null;for(key in handlers){break;}if(key===null){cleanupHandlers=YES;}}else{cleanupHandlers=YES;
}if(cleanupHandlers){delete events[eventType];this._removeEventListener(elem,eventType);
}key=null;for(key in events){break;}if(!key){SC.removeData(elem,"events");delete this._elements[SC.guidFor(elem)];
}}}elem=events=handlers=null;return this;},NO_BUBBLE:["blur","focus","change"],simulateEvent:function(elem,eventType,attrs){var ret=SC.Event.create({type:eventType,target:elem,preventDefault:function(){this.cancelled=YES;
},stopPropagation:function(){this.bubbles=NO;},allowDefault:function(){this.hasCustomEventHandling=YES;
},timeStamp:Date.now(),bubbles:(this.NO_BUBBLE.indexOf(eventType)<0),cancelled:NO,normalized:YES});
if(attrs){SC.mixin(ret,attrs);}return ret;},trigger:function(elem,eventType,args,donative){if(elem&&elem.isCoreQuery){if(elem.length>0){elem.forEach(function(e){this.trigger(e,eventType,args,donative);
},this);return this;}else{elem=elem.get(0);}}if(!elem){return this;}if(elem.nodeType==3||elem.nodeType==8){return undefined;
}args=SC.A(args);var ret,fn=SC.typeOf(elem[eventType]||null)===SC.T_FUNCTION,event,current,onfoo;
event=args[0];if(!event||!event.preventDefault){event=this.simulateEvent(elem,eventType);
args.unshift(event);}event.type=eventType;current=elem;do{ret=SC.Event.handle.apply(current,args);
current=(current===document)?null:(current.parentNode||document);}while(!ret&&event.bubbles&&current);
current=null;onfoo=elem["on"+eventType];isClick=SC.CoreQuery.nodeName(elem,"a")&&eventType==="click";
if((!fn||isClick)&&onfoo&&onfoo.apply(elem,args)===NO){ret=NO;}if(fn&&donative!==NO&&ret!==NO&&!isClick){this.triggered=YES;
try{elem[eventType]();}catch(e){}}this.triggered=NO;return ret;},handle:function(event){if((typeof SC==="undefined")||SC.Event.triggered){return YES;
}var val,ret,namespace,all,handlers,args,key,handler,method,target;args=SC.A(arguments);
args[0]=event=SC.Event.normalizeEvent(event||window.event);handlers=(SC.data(this,"events")||{})[event.type];
if(!handlers){return NO;}for(key in handlers){handler=handlers[key];method=handler[1];
event.handler=method;event.data=event.context=handler[2];target=handler[0]||this;
ret=method.apply(target,args);if(val!==NO){val=ret;}if(ret===NO){event.preventDefault();
event.stopPropagation();}}return val;},unload:function(){var key,elements=this._elements;
for(key in elements){this.remove(elements[key]);}for(key in elements){delete elements[key];
}delete this._elements;},special:{ready:{setup:function(){SC._bindReady();return;
},teardown:function(){return;}},mouseenter:{setup:function(){if(SC.browser.msie){return NO;
}SC.Event.add(this,"mouseover",SC.Event.special.mouseover.handler);return YES;},teardown:function(){if(SC.browser.msie){return NO;
}SC.Event.remove(this,"mouseover",SC.Event.special.mouseover.handler);return YES;
},handler:function(event){if(SC.Event._withinElement(event,this)){return YES;}event.type="mouseenter";
return SC.Event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(SC.browser.msie){return NO;
}SC.Event.add(this,"mouseout",SC.Event.special.mouseleave.handler);return YES;},teardown:function(){if(SC.browser.msie){return NO;
}SC.Event.remove(this,"mouseout",SC.Event.special.mouseleave.handler);return YES;
},handler:function(event){if(SC.Event._withinElement(event,this)){return YES;}event.type="mouseleave";
return SC.Event.handle.apply(this,arguments);}}},KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,_withinElement:function(event,elem){var parent=event.relatedTarget;
while(parent&&parent!=elem){try{parent=parent.parentNode;}catch(error){parent=elem;
}}return parent===elem;},_addEventListener:function(elem,eventType){var listener,special=this.special[eventType];
if(!special||special.setup.call(elem)===NO){var guid=SC.guidFor(elem);this._elements[guid]=elem;
listener=SC.data(elem,"listener")||SC.data(elem,"listener",function(){return SC.Event.handle.apply(SC.Event._elements[guid],arguments);
});if(elem.addEventListener){elem.addEventListener(eventType,listener,NO);}else{if(elem.attachEvent){elem.attachEvent("on"+eventType,listener);
}}}elem=special=listener=null;},_removeEventListener:function(elem,eventType){var listener,special=SC.Event.special[eventType];
if(!special||(special.teardown.call(elem)===NO)){listener=SC.data(elem,"listener");
if(listener){if(elem.removeEventListener){elem.removeEventListener(eventType,listener,NO);
}else{if(elem.detachEvent){elem.detachEvent("on"+eventType,listener);}}}}elem=special=listener=null;
},_elements:{},normalizeEvent:function(event){if(event==window.event){return SC.Event.create(event);
}else{return event.normalized?event:SC.Event.create(event);}},_global:{},_props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view which touches targetTouches changedTouches".split(" ")});
SC.Event.prototype={hasCustomEventHandling:NO,allowDefault:function(){this.hasCustomEventHandling=YES;
return this;},preventDefault:function(){var evt=this.originalEvent;if(evt){if(evt.preventDefault){evt.preventDefault();
}evt.returnValue=NO;}this.hasCustomEventHandling=YES;return this;},stopPropagation:function(){var evt=this.originalEvent;
if(evt){if(evt.stopPropagation){evt.stopPropagation();}evt.cancelBubble=YES;}this.hasCustomEventHandling=YES;
return this;},stop:function(){return this.preventDefault().stopPropagation();},normalized:YES,getCharString:function(){return(this.charCode>0)?String.fromCharCode(this.which):null;
},commandCodes:function(){var code=this.keyCode,ret=null,key=null,modifiers="",lowercase;
if(code){ret=SC.FUNCTION_KEYS[code];if(!ret&&(this.altKey||this.ctrlKey||this.metaKey)){ret=SC.PRINTABLE_KEYS[code];
}if(ret){if(this.altKey){modifiers+="alt_";}if(this.ctrlKey||this.metaKey){modifiers+="ctrl_";
}if(this.shiftKey){modifiers+="shift_";}}}if(!ret){code=this.which;key=ret=String.fromCharCode(code);
lowercase=ret.toLowerCase();if(this.metaKey){modifiers="meta_";ret=lowercase;}else{ret=null;
}}if(ret){ret=modifiers+ret;}return[ret,key];}};SC.Event.observe=SC.Event.add;SC.Event.stopObserving=SC.Event.remove;
SC.Event.fire=SC.Event.trigger;SC.Event.add(window,"unload",SC.Event.prototype,SC.Event.unload);
SC.MODIFIER_KEYS={16:"shift",17:"ctrl",18:"alt"};SC.FUNCTION_KEYS={8:"backspace",9:"tab",13:"return",19:"pause",27:"escape",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",44:"printscreen",45:"insert",46:"delete",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12",144:"numlock",145:"scrolllock"};
SC.PRINTABLE_KEYS={32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:'"'};
SC.SYSTEM_CURSOR="default";SC.AUTO_CURSOR=SC.DEFAULT_CURSOR="auto";SC.CROSSHAIR_CURSOR="crosshair";
SC.HAND_CURSOR=SC.POINTER_CURSOR="pointer";SC.MOVE_CURSOR="move";SC.E_RESIZE_CURSOR="e-resize";
SC.NE_RESIZE_CURSOR="ne-resize";SC.NW_RESIZE_CURSOR="nw-resize";SC.N_RESIZE_CURSOR="n-resize";
SC.SE_RESIZE_CURSOR="se-resize";SC.SW_RESIZE_CURSOR="sw-resize";SC.S_RESIZE_CURSOR="s-resize";
SC.W_RESIZE_CURSOR="w-resize";SC.IBEAM_CURSOR=SC.TEXT_CURSOR="text";SC.WAIT_CURSOR="wait";
SC.HELP_CURSOR="help";SC.Cursor=SC.Object.extend({init:function(){arguments.callee.base.apply(this,arguments);
var cursorStyle=this.get("cursorStyle")||SC.DEFAULT_CURSOR,ss=this.constructor.sharedStyleSheet();
if(ss.insertRule){ss.insertRule(".%@ {cursor: %@;}".fmt(SC.guidFor(this),cursorStyle),ss.cssRules?ss.cssRules.length:0);
}else{if(ss.addRule){ss.addRule("."+SC.guidFor(this),"cursor: "+cursorStyle);}}this.cursorStyle=cursorStyle;
this.className=SC.guidFor(this);return this;},className:null,cursorStyle:SC.DEFAULT_CURSOR,cursorStyleDidChange:function(){var cursorStyle,rule,selector,ss,rules,idx,len;
cursorStyle=this.get("cursorStyle")||SC.DEFAULT_CURSOR;rule=this._rule;if(rule){rule.style.cursor=cursorStyle;
return;}selector="."+this.get("className");ss=this.constructor.sharedStyleSheet();
rules=(ss.cssRules?ss.cssRules:ss.rules)||[];for(idx=0,len=rules.length;idx<len;++idx){rule=rules[idx];
if(rule.selectorText===selector){this._rule=rule;rule.style.cursor=cursorStyle;break;
}}}.observes("cursorStyle")});SC.Cursor.sharedStyleSheet=function(){var head,ss=this._styleSheet;
if(!ss){ss=document.createElement("style");ss.type="text/css";head=document.getElementsByTagName("head")[0];
if(!head){head=document.documentElement;}head.appendChild(ss);ss=document.styleSheets[document.styleSheets.length-1];
this._styleSheet=ss;}return ss;};SC.Responder=SC.Object.extend({isResponder:YES,pane:null,responderContext:null,nextResponder:null,isFirstResponder:NO,hasFirstResponder:NO,acceptsFirstResponder:YES,becomeFirstResponder:function(){var pane=this.get("pane")||this.get("responderContext")||this.pane();
if(pane&&this.get("acceptsFirstResponder")){if(pane.get("firstResponder")!==this){pane.makeFirstResponder(this);
}}return this;},resignFirstResponder:function(){var pane=this.get("pane")||this.get("responderContext");
if(pane&&(pane.get("firstResponder")===this)){pane.makeFirstResponder(null);}return YES;
},willLoseFirstResponder:function(responder){},didBecomeFirstResponder:function(responder){}});
sc_require("system/browser");sc_require("system/event");sc_require("system/cursor");
sc_require("system/responder");sc_require("mixins/string");SC.viewKey=SC.guidKey+"_view";
SC.LAYOUT_HORIZONTAL="sc-layout-horizontal";SC.LAYOUT_VERTICAL="sc-layout-vertical";
SC._VIEW_DEFAULT_DIMS="marginTop marginLeft".w();SC.ANCHOR_TOP={top:0};SC.ANCHOR_LEFT={left:0};
SC.ANCHOR_TOP_LEFT={top:0,left:0};SC.ANCHOR_BOTTOM={bottom:0};SC.ANCHOR_RIGHT={right:0};
SC.ANCHOR_BOTTOM_RIGHT={bottom:0,right:0};SC.FULL_WIDTH={left:0,right:0};SC.FULL_HEIGHT={top:0,bottom:0};
SC.ANCHOR_CENTER={centerX:0,centerY:0};SC.LAYOUT_AUTO="auto";SC.EMPTY_CHILD_VIEWS_ARRAY=[];
SC.EMPTY_CHILD_VIEWS_ARRAY.needsClone=YES;SC.View=SC.Responder.extend(SC.DelegateSupport,{concatenatedProperties:"outlets displayProperties layoutProperties classNames renderMixin didCreateLayerMixin willDestroyLayerMixin".w(),pane:function(){var view=this;
while(view&&!view.isPane){view=view.get("parentView");}return view;}.property("parentView").cacheable(),page:null,splitView:function(){var view=this;
while(view&&!view.isSplitView){view=view.get("parentView");}return view;}.property("parentView").cacheable(),parentView:null,backgroundColor:null,isEnabled:YES,isEnabledBindingDefault:SC.Binding.oneWay().bool(),isEnabledInPane:function(){var ret=this.get("isEnabled"),pv;
if(ret&&(pv=this.get("parentView"))){ret=pv.get("isEnabledInPane");}return ret;}.property("parentView","isEnabled"),isVisible:YES,isVisibleBindingDefault:SC.Binding.bool(),isVisibleInWindow:NO,recomputeIsVisibleInWindow:function(parentViewIsVisible){var last=this.get("isVisibleInWindow");
var cur=this.get("isVisible"),parentView;if(cur){cur=(parentViewIsVisible===undefined)?((parentView=this.get("parentView"))?parentView.get("isVisibleInWindow"):NO):parentViewIsVisible;
}if(last!==cur){this.set("isVisibleInWindow",cur);this._needsVisibiltyChange=YES;
var childViews=this.get("childViews"),len=childViews.length,idx;for(idx=0;idx<len;
idx++){childViews[idx].recomputeIsVisibleInWindow(cur);}if(cur){if(this.parentViewDidResize){this.parentViewDidResize();
}if(this.get("childViewsNeedLayout")){this.invokeOnce(this.layoutChildViewsIfNeeded);
}}this.set("layerNeedsUpdate",YES);if(!cur&&this.get("isFirstResponder")){this.resignFirstResponder();
}}return this;}.observes("isVisible"),childViews:SC.EMPTY_CHILD_VIEWS_ARRAY,insertBefore:function(view,beforeView){view.beginPropertyChanges();
if(view.get("parentView")){view.removeFromParent();}if(this.willAddChild){this.willAddChild(view,beforeView);
}if(view.willAddToParent){view.willAddToParent(this,beforeView);}view.set("parentView",this);
var idx,childViews=this.get("childViews");if(childViews.needsClone){this.set(childViews=[]);
}idx=(beforeView)?childViews.indexOf(beforeView):childViews.length;if(idx<0){idx=childViews.length;
}childViews.insertAt(idx,view);view.parentViewDidChange();view.layoutDidChange();
if(this.didAddChild){this.didAddChild(view,beforeView);}if(view.didAddToParent){view.didAddToParent(this,beforeView);
}view.endPropertyChanges();return this;},removeChild:function(view){if(!view){return this;
}if(view.parentView!==this){throw"%@.removeChild(%@) must belong to parent".fmt(this,view);
}if(view.willRemoveFromParent){view.willRemoveFromParent();}if(this.willRemoveChild){this.willRemoveChild(view);
}view.set("parentView",null);var childViews=this.get("childViews");var idx=childViews.indexOf(view);
if(idx>=0){childViews.removeAt(idx);}view.parentViewDidChange();if(this.didRemoveChild){this.didRemoveChild(view);
}if(view.didRemoveFromParent){view.didRemoveFromParent(this);}return this;},removeAllChildren:function(){var childViews=this.get("childViews"),view;
while(view=childViews.objectAt(childViews.get("length")-1)){this.removeChild(view);
}return this;},removeFromParent:function(){var parent=this.get("parentView");if(parent){parent.removeChild(this);
}return this;},replaceChild:function(view,oldView){view.beginPropertyChanges();oldView.beginPropertyChanges();
this.beginPropertyChanges();this.insertBefore(view,oldView).removeChild(oldView);
this.endPropertyChanges();oldView.endPropertyChanges();view.endPropertyChanges();
return this;},replaceAllChildren:function(views){var len=views.get("length"),idx;
this.beginPropertyChanges();this.destroyLayer().removeAllChildren();for(idx=0;idx<len;
idx++){this.appendChild(views.objectAt(idx));}this.replaceLayer();this.endPropertyChanges();
return this;},appendChild:function(view){return this.insertBefore(view,null);},parentViewDidChange:function(){this.recomputeIsVisibleInWindow();
this.set("layerLocationNeedsUpdate",YES);this.invokeOnce(this.updateLayerLocationIfNeeded);
this._invalidatePaneCacheForSelfAndAllChildViews();return this;}.observes("isVisible"),_invalidatePaneCacheForSelfAndAllChildViews:function(){this.notifyPropertyChange("pane");
var childViews=this.get("childViews");var len=childViews.length;for(var idx=0;idx<len;
++idx){var childView=childViews[idx];if(childView._invalidatePaneCacheForSelfAndAllChildViews){childView._invalidatePaneCacheForSelfAndAllChildViews();
}}},layer:function(key,value){if(value!==undefined){this._view_layer=value;}else{value=this._view_layer;
if(!value){var parent=this.get("parentView");if(parent){parent=parent.get("layer");
}if(parent){this._view_layer=value=this.findLayerInParentLayer(parent);}parent=null;
}}return value;}.property("isVisibleInWindow").cacheable(),$:function(sel){var ret,layer=this.get("layer");
ret=!layer?SC.$([]):(sel===undefined)?SC.$(layer):SC.$(sel,layer);layer=null;return ret;
},containerLayer:function(){return this.get("layer");}.property("layer").cacheable(),layerId:function(){return SC.guidFor(this);
}.property().cacheable(),findLayerInParentLayer:function(parentLayer){var layerId=this.get("layerId");
var node,i,ilen,found,elem;if(parentLayer.getElementById){elem=parentLayer.getElementById(layerId);
}else{elem=document.getElementById(layerId);}if(SC.browser.msie&&elem&&elem.id!==layerId){elem=null;
}if(!elem&&parentLayer.querySelector){}if(!elem){elem=parentLayer.firstChild;var q=[];
q.push(parentLayer);while(q.length!==0){node=q[0];q.shift();if(node.id===layerId){found=true;
elem=node;break;}for(i=0,ilen=node.childNodes.length;i<ilen;i++){q.push(node.childNodes[i]);
}}if(!found){elem=null;}}return elem;},displayDidChange:function(){this.set("layerNeedsUpdate",YES);
return this;},layerNeedsUpdate:NO,_view_layerNeedsUpdateDidChange:function(){if(this.get("layerNeedsUpdate")){this.invokeOnce(this.updateLayerIfNeeded);
}}.observes("layerNeedsUpdate"),updateLayerIfNeeded:function(){var viz=this.get("isVisibleInWindow");
if((viz||this._needsVisibiltyChange)&&this.get("layerNeedsUpdate")){this._needsVisibiltyChange=NO;
if(this.get("layer")){this.beginPropertyChanges();this.set("layerNeedsUpdate",NO);
this.updateLayer();this.endPropertyChanges();}}else{this.set("layerNeedsUpdate",NO);
}return this;},updateLayer:function(){var context=this.renderContext(this.get("layer"));
this.prepareContext(context,NO);context.update();if(this.didUpdateLayer){this.didUpdateLayer();
}if(this.designer&&this.designer.viewDidUpdateLayer){this.designer.viewDidUpdateLayer();
}return this;},renderContext:function(tagNameOrElement){return SC.RenderContext(tagNameOrElement);
},createLayer:function(){if(this.get("layer")){return this;}var context=this.renderContext(this.get("tagName"));
this.prepareContext(context,YES);this.set("layer",context.element());this._notifyDidCreateLayer();
return this;},_notifyDidCreateLayer:function(){if(this.didCreateLayer){this.didCreateLayer();
}var mixins=this.didCreateLayerMixin,len,idx;if(mixins){len=mixins.length;for(idx=0;
idx<len;++idx){mixins[idx].call(this);}}var childViews=this.get("childViews");len=childViews.length;
for(idx=0;idx<len;++idx){if(!childViews[idx]){continue;}childViews[idx]._notifyDidCreateLayer();
}},destroyLayer:function(){var layer=this.get("layer");if(layer){this._notifyWillDestroyLayer();
if(layer.parentNode){layer.parentNode.removeChild(layer);}layer=null;}return this;
},replaceLayer:function(){this.destroyLayer();this.set("layerLocationNeedsUpdate",YES);
this.invokeOnce(this.updateLayerLocationIfNeeded);},_notifyWillDestroyLayer:function(){if(this.willDestroyLayer){this.willDestroyLayer();
}var mixins=this.willDestroyLayerMixin,len,idx;if(mixins){len=mixins.length;for(idx=0;
idx<len;++idx){mixins[idx].call(this);}}var childViews=this.get("childViews");len=childViews.length;
for(idx=0;idx<len;++idx){childViews[idx]._notifyWillDestroyLayer();}this.set("layer",null);
},prepareContext:function(context,firstTime){var mixins,len,idx,layerId,bgcolor,cursor;
if(firstTime){layerId=this.layerId?this.get("layerId"):SC.guidFor(this);context.id(layerId).classNames(this.get("classNames"),YES);
this.renderLayout(context,firstTime);}else{context.resetClassNames();context.classNames(this.get("classNames"),YES);
}if(this.get("isTextSelectable")){context.addClass("allow-select");}if(!this.get("isEnabled")){context.addClass("disabled");
}if(!this.get("isVisible")){context.addClass("hidden");}if(this.get("isFirstResponder")){context.addClass("focus");
}bgcolor=this.get("backgroundColor");if(bgcolor){context.addStyle("backgroundColor",bgcolor);
}cursor=this.get("cursor");if(cursor){context.addClass(cursor.get("className"));}this.beginPropertyChanges();
this.set("layerNeedsUpdate",NO);this.render(context,firstTime);if(mixins=this.renderMixin){len=mixins.length;
for(idx=0;idx<len;++idx){mixins[idx].call(this,context,firstTime);}}this.endPropertyChanges();
},renderChildViews:function(context,firstTime){var cv=this.get("childViews"),len=cv.length,idx,view;
for(idx=0;idx<len;++idx){view=cv[idx];if(!view){continue;}context=context.begin(view.get("tagName"));
view.prepareContext(context,firstTime);context=context.end();}return context;},render:function(context,firstTime){if(firstTime){this.renderChildViews(context,firstTime);
}},tagName:"div",classNames:["sc-view"],toolTip:null,isTextSelectable:NO,displayProperties:["isFirstResponder","isVisible"],cursor:null,layerLocationNeedsUpdate:NO,updateLayerLocationIfNeeded:function(force){if(this.get("layerLocationNeedsUpdate")){this.set("layerLocationNeedsUpdate",NO);
this.updateLayerLocation();}return this;},updateLayerLocation:function(){var node=this.get("layer");
var parentView=this.get("parentView");var parentNode=parentView?parentView.get("containerLayer"):null;
if(node&&node.parentNode&&node.parentNode!==parentNode){node.parentNode.removeChild(node);
}if(!parentView){if(node&&node.parentNode){node.parentNode.removeChild(node);}}else{if(!parentNode){if(node){if(node.parentNode){node.parentNode.removeChild(node);
}this.destroyLayer();}}else{if(!node){this.createLayer();node=this.get("layer");}var siblings=parentView.get("childViews");
var nextView=siblings.objectAt(siblings.indexOf(this)+1);var nextNode=(nextView)?nextView.get("layer"):null;
if(nextView&&(!nextNode||nextNode.parentNode!==parentNode)){nextView.updateLayerLocationIfNeeded();
nextNode=nextView.get("layer");}if((node.parentNode!==parentNode)||(node.nextSibling!==nextNode)){parentNode.insertBefore(node,nextNode);
if(this.parentViewDidResize){this.parentViewDidResize();}}}}parentNode=parentView=node=null;
return this;},nextResponder:function(){return this.get("parentView");}.property("parentView").cacheable(),acceptsFirstResponder:NO,isKeyResponder:NO,willLoseKeyResponderTo:function(responder){},willBecomeKeyResponderFrom:function(responder){},didLoseKeyResponderTo:function(responder){},didBecomeKeyResponderFrom:function(responder){},interpretKeyEvents:function(event){var codes=event.commandCodes(),cmd=codes[0],chr=codes[1],ret;
if(!cmd&&!chr){return null;}if(cmd){var methodName=SC.MODIFIED_KEY_BINDINGS[cmd]||SC.BASE_KEY_BINDINGS[cmd.match(/[^_]+$/)[0]];
if(methodName){var target=this,pane=this.get("pane"),handler=null;while(target&&!(handler=target.tryToPerform(methodName,event))){target=(target===pane)?null:target.get("nextResponder");
}return handler;}}if(chr&&this.respondsTo("insertText")){ret=this.insertText(chr,event);
return ret?(ret===YES?this:ret):null;}return null;},insertText:function(chr){return NO;
},performKeyEquivalent:function(keystring,evt){var ret=NO,childViews=this.get("childViews"),len=childViews.length,idx=-1;
while(!ret&&(++idx<len)){ret=childViews[idx].performKeyEquivalent(keystring,evt);
}return ret;},nextKeyView:null,nextValidKeyView:function(){var seen=SC.CoreSet.create(),ret=this._computeNextValidKeyView(seen);
seen.destroy();return ret;}.property("nextKeyView"),_computeNextValidKeyView:function(seen){var ret=this.get("nextKeyView"),pv,cv,idx;
seen.add(this);if(!ret){pv=this.get("parentView");cv=pv?pv.get("childViews"):null;
idx=cv?cv.indexOf(this):-1;if(idx<0){ret=null;}else{if(idx+1>=cv.get("length")){ret=cv.objectAt(0);
}else{ret=cv.objectAt(idx+1);}}}if(ret&&!ret.get("acceptsFirstResponder")){if(seen.contains(ret)){ret=null;
}else{ret=ret._computeNextValidKeyView(seen);}}return ret;},previousKeyView:null,previousValidKeyView:function(){var seen=SC.CoreSet.create(),ret=this._computePreviousValidKeyView(seen);
seen.destroy();return ret;}.property("previousKeyView"),_computePreviousValidKeyView:function(seen){var ret=this.get("previousKeyView"),pv,cv,idx;
seen.add(this);if(!ret){pv=this.get("parentView");cv=pv?pv.get("childViews"):null;
idx=cv?cv.indexOf(this):-1;if(idx<0){ret=null;}else{if(idx>0){ret=cv.objectAt(idx-1);
}else{ret=cv.objectAt(cv.get("length")-1);}}}if(ret&&!ret.get("acceptsFirstResponder")){if(seen.contains(ret)){ret=null;
}else{ret=ret._computePreviousValidKeyView(seen);}}return ret;},init:function(){var parentView,path,root,idx,len,lp,dp;
arguments.callee.base.apply(this,arguments);if(!this.get("isMaterialized")){SC.View.views[this.get("layerId")]=this;
}var childViews=this.get("childViews");this.childViews=childViews?childViews.slice():[];
this.createChildViews();dp=this.get("displayProperties");idx=dp.length;while(--idx>=0){this.addObserver(dp[idx],this,this.displayDidChange);
}if(this.get("isDropTarget")){SC.Drag.addDropTarget(this);}if(this.get("isScrollable")){SC.Drag.addScrollableView(this);
}},awake:function(){arguments.callee.base.apply(this,arguments);var childViews=this.get("childViews"),len=childViews.length,idx;
for(idx=0;idx<len;++idx){if(!childViews[idx]){continue;}childViews[idx].awake();}},destroy:function(){if(this.get("isDestroyed")){return this;
}arguments.callee.base.apply(this,arguments);this.removeFromParent();this._destroy();
if(this.get("isDropTarget")){SC.Drag.removeDropTarget(this);}if(this.get("isScrollable")){SC.Drag.removeScrollableView(this);
}return this;},_destroy:function(){if(this.get("isDestroyed")){return this;}this.destroyLayer();
var childViews=this.get("childViews"),len=childViews.length,idx;if(len){childViews=childViews.slice();
for(idx=0;idx<len;++idx){childViews[idx]._destroy();}}delete SC.View.views[this.get("layerId")];
delete this._CQ;delete this.page;this.set("isDestroyed",YES);return this;},createChildViews:function(){var childViews=this.get("childViews"),len=childViews.length,idx,key,views,view;
this.beginPropertyChanges();for(idx=0;idx<len;++idx){if(key=(view=childViews[idx])){if(typeof key===SC.T_STRING){view=this[key];
}else{key=null;}if(!view){console.error("No view with name "+key+" has been found in "+this.toString());
continue;}if(view.isClass){view=this.createChildView(view);if(key){this[key]=view;
}}}childViews[idx]=view;}this.endPropertyChanges();return this;},createChildView:function(view,attrs){if(!attrs){attrs={};
}attrs.owner=attrs.parentView=this;attrs.isVisibleInWindow=this.get("isVisibleInWindow");
if(!attrs.page){attrs.page=this.page;}view=view.create(attrs);return view;},adjust:function(key,value){var layout=SC.clone(this.get("layout")),didChange=NO,cur;
if(key===undefined){return this;}if(SC.typeOf(key)===SC.T_STRING){cur=layout[key];
if(SC.none(value)){if(cur!==undefined){didChange=YES;}delete layout[key];}else{if(cur!==value){didChange=YES;
}layout[key]=value;}}else{var hash=key;for(key in hash){if(!hash.hasOwnProperty(key)){continue;
}value=hash[key];cur=layout[key];if(value===null){if(cur!==undefined){didChange=YES;
}delete layout[key];}else{if(value!==undefined){if(cur!==value){didChange=YES;}layout[key]=value;
}}}}if(didChange){this.set("layout",layout);}return this;},layout:{top:0,left:0,bottom:0,right:0},convertFrameToView:function(frame,targetView){var myX=0,myY=0,targetX=0,targetY=0,view=this,f;
if(this.get("useStaticLayout")){throw"convertFrameToView is not available with static layout";
}while(view){f=view.get("frame");myX+=f.x;myY+=f.y;view=view.get("layoutView");}if(targetView){view=targetView;
while(view){f=view.get("frame");targetX+=f.x;targetY+=f.y;view=view.get("layoutView");
}}myX=frame.x+myX-targetX;myY=frame.y+myY-targetY;return{x:myX,y:myY,width:frame.width,height:frame.height};
},convertFrameFromView:function(frame,targetView){var myX=0,myY=0,targetX=0,targetY=0,view=this,next,f;
if(this.get("useStaticLayout")){throw"convertFrameToView is not available with static layout";
}while(view&&view.get("frame")){f=view.get("frame");myX+=f.x;myY+=f.y;view=view.get("parentView");
}if(targetView){view=targetView;while(view){f=view.get("frame");targetX+=f.x;targetY+=f.y;
view=view.get("parentView");}}myX=frame.x-myX+targetX;myY=frame.y-myY+targetY;return{x:myX,y:myY,width:frame.width,height:frame.height};
},scrollToVisible:function(){var pv=this.get("parentView");while(pv&&!pv.get("isScrollable")){pv=pv.get("parentView");
}if(pv){pv.scrollToVisible();return pv.scrollToVisible(this);}else{return NO;}},frame:function(){return this.computeFrameWithParentFrame(null);
}.property("layout","useStaticLayout").cacheable(),computeFrameWithParentFrame:function(pdim){var layout=this.get("layout");
var f={},error,layer,AUTO=SC.LAYOUT_AUTO;var stLayout=this.get("useStaticLayout");
if(layout.width!==undefined&&layout.width===SC.LAYOUT_AUTO&&stLayout!==undefined&&!stLayout){error=SC.Error.desc("%@.layout() you cannot use width:auto if staticLayout is disabled".fmt(this),"%@".fmt(this),-1);
console.error(error.toString());throw error;}if(layout.height!==undefined&&layout.height===SC.LAYOUT_AUTO&&stLayout!==undefined&&!stLayout){error=SC.Error.desc("%@.layout() you cannot use height:auto if staticLayout is disabled".fmt(this),"%@".fmt(this),-1);
console.error(error.toString());throw error;}if(stLayout){return null;}if(!SC.none(layout.left)){f.x=Math.floor(layout.left);
if(layout.width!==undefined){if(layout.width===AUTO){f.width=AUTO;}else{f.width=Math.floor(layout.width);
}}else{if(!pdim){pdim=this.computeParentDimensions(layout);}f.width=Math.floor(pdim.width-f.x-(layout.right||0));
}}else{if(!SC.none(layout.right)){if(!pdim){pdim=this.computeParentDimensions(layout);
}if(SC.none(layout.width)){f.width=pdim.width-layout.right;f.x=0;}else{if(layout.width===AUTO){f.width=AUTO;
}else{f.width=Math.floor(layout.width||0);}f.x=Math.floor(pdim.width-layout.right-f.width);
}}else{if(!SC.none(layout.centerX)){if(!pdim){pdim=this.computeParentDimensions(layout);
}if(layout.width===AUTO){f.width=AUTO;}else{f.width=Math.floor(layout.width||0);}f.x=Math.floor((pdim.width-f.width)/2+layout.centerX);
}else{f.x=0;if(SC.none(layout.width)){if(!pdim){pdim=this.computeParentDimensions(layout);
}f.width=Math.floor(pdim.width);}else{if(layout.width===AUTO){f.width=AUTO;}else{f.width=Math.floor(layout.width||0);
}}}}}if(!SC.none(layout.top)){f.y=Math.floor(layout.top);if(layout.height!==undefined){if(layout.height===AUTO){f.height=AUTO;
}else{f.height=Math.floor(layout.height);}}else{if(!pdim){pdim=this.computeParentDimensions(layout);
}f.height=Math.floor(pdim.height-f.y-(layout.bottom||0));}}else{if(!SC.none(layout.bottom)){if(!pdim){pdim=this.computeParentDimensions(layout);
}if(SC.none(layout.height)){f.height=pdim.height-layout.bottom;f.y=0;}else{if(layout.height===AUTO){f.height=AUTO;
}else{f.height=Math.floor(layout.height||0);}f.y=Math.floor(pdim.height-layout.bottom-f.height);
}}else{if(!SC.none(layout.centerY)){if(!pdim){pdim=this.computeParentDimensions(layout);
}if(layout.height===AUTO){f.height=AUTO;}else{f.height=Math.floor(layout.height||0);
}f.y=Math.floor((pdim.height-f.height)/2+layout.centerY);}else{f.y=0;if(SC.none(layout.height)){if(!pdim){pdim=this.computeParentDimensions(layout);
}f.height=Math.floor(pdim.height);}else{if(layout.height===AUTO){f.height=AUTO;}else{f.height=Math.floor(layout.height||0);
}}}}}if(f.height===AUTO||f.width===AUTO){layer=this.get("layer");if(f.height===AUTO){f.height=layer?layer.clientHeight:0;
}if(f.width===AUTO){f.width=layer?layer.clientWidth:0;}}if(!SC.none(layout.maxHeight)&&(f.height>layout.maxHeight)){f.height=layout.maxHeight;
}if(!SC.none(layout.minHeight)&&(f.height<layout.minHeight)){f.height=layout.minHeight;
}if(!SC.none(layout.maxWidth)&&(f.width>layout.maxWidth)){f.width=layout.maxWidth;
}if(!SC.none(layout.minWidth)&&(f.width<layout.minWidth)){f.width=layout.minWidth;
}if(f.height<0){f.height=0;}if(f.width<0){f.width=0;}return f;},computeParentDimensions:function(frame){var ret,pv=this.get("parentView"),pf=(pv)?pv.get("frame"):null;
if(pf){ret={width:pf.width,height:pf.height};}else{var f=frame;ret={width:(f.left||0)+(f.width||0)+(f.right||0),height:(f.top||0)+(f.height||0)+(f.bottom||0)};
}return ret;},clippingFrame:function(){var pv=this.get("parentView"),f=this.get("frame"),ret=f;
if(pv){pv=pv.get("clippingFrame");ret=SC.intersectRects(pv,f);}ret.x-=f.x;ret.y-=f.y;
return ret;}.property("parentView","frame").cacheable(),_sc_view_clippingFrameDidChange:function(){var cvs=this.get("childViews"),len=cvs.length,idx,cv;
for(idx=0;idx<len;++idx){cv=cvs[idx];if(!cv.hasStaticLayout){cv.notifyPropertyChange("clippingFrame");
}}}.observes("clippingFrame"),parentViewDidResize:function(){var layout=this.get("layout");
var isFixed=((layout.left!==undefined)&&(layout.top!==undefined)&&(layout.width!==undefined)&&(layout.height!==undefined));
if(!isFixed){this.notifyPropertyChange("frame");this.viewDidResize();}},viewDidResize:function(){var cv=this.childViews,len=cv.length,idx,view;
for(idx=0;idx<len;++idx){view=cv[idx];if(view.parentViewDidResize){view.parentViewDidResize();
}}}.observes("layout"),beginLiveResize:function(){if(this.willBeginLiveResize){this.willBeginLiveResize();
}var ary=this.get("childViews"),len=ary.length,idx,view;for(idx=0;idx<len;++idx){view=ary[idx];
if(view.beginLiveResize){view.beginLiveResize();}}return this;},endLiveResize:function(){var ary=this.get("childViews"),len=ary.length,idx,view;
for(idx=len-1;idx>=0;--idx){view=ary[idx];if(view.endLiveResize){view.endLiveResize();
}}if(this.didEndLiveResize){this.didEndLiveResize();}return this;},layoutStyle:function(){var layout=this.get("layout"),ret={},pdim=null,error,AUTO=SC.LAYOUT_AUTO;
var stLayout=this.get("useStaticLayout");if(layout.width!==undefined&&layout.width===SC.LAYOUT_AUTO&&!stLayout){error=SC.Error.desc("%@.layout() you cannot use width:auto if  staticLayout is disabled".fmt(this),"%@".fmt(this),-1);
console.error(error.toString());throw error;}if(layout.height!==undefined&&layout.height===SC.LAYOUT_AUTO&&!stLayout){error=SC.Error.desc("%@.layout() you cannot use height:auto if  staticLayout is disabled".fmt(this),"%@".fmt(this),-1);
console.error(error.toString());throw error;}if(!SC.none(layout.left)){ret.left=Math.floor(layout.left);
if(layout.width!==undefined){if(layout.width===SC.LAYOUT_AUTO){ret.width=SC.LAYOUT_AUTO;
}else{ret.width=Math.floor(layout.width);}ret.right=null;}else{ret.width=null;ret.right=Math.floor(layout.right||0);
}ret.marginLeft=0;}else{if(!SC.none(layout.right)){ret.right=Math.floor(layout.right);
ret.marginLeft=0;if(SC.none(layout.width)){ret.left=0;ret.width=null;}else{ret.left=null;
if(layout.width===SC.LAYOUT_AUTO){ret.width=SC.LAYOUT_AUTO;}else{ret.width=Math.floor(layout.width||0);
}}}else{if(!SC.none(layout.centerX)){ret.left="50%";ret.width=Math.floor(layout.width||0);
ret.marginLeft=Math.floor(layout.centerX-ret.width/2);ret.right=null;}else{if(!SC.none(layout.width)){ret.left=0;
ret.right=null;if(layout.width===SC.LAYOUT_AUTO){ret.width=SC.LAYOUT_AUTO;}else{ret.width=Math.floor(layout.width);
}ret.marginLeft=0;}else{ret.left=0;ret.right=0;ret.width=null;ret.marginLeft=0;}}}}ret.minWidth=(layout.minWidth===undefined)?null:layout.minWidth;
ret.maxWidth=(layout.maxWidth===undefined)?null:layout.maxWidth;if(!SC.none(layout.top)){ret.top=Math.floor(layout.top);
if(layout.height!==undefined){if(layout.height===SC.LAYOUT_AUTO){ret.height=SC.LAYOUT_AUTO;
}else{ret.height=Math.floor(layout.height);}ret.bottom=null;}else{ret.height=null;
ret.bottom=Math.floor(layout.bottom||0);}ret.marginTop=0;}else{if(!SC.none(layout.bottom)){ret.marginTop=0;
ret.bottom=Math.floor(layout.bottom);if(SC.none(layout.height)){ret.top=0;ret.height=null;
}else{ret.top=null;if(layout.height===SC.LAYOUT_AUTO){ret.height=SC.LAYOUT_AUTO;}else{ret.height=Math.floor(layout.height||0);
}}}else{if(!SC.none(layout.centerY)){ret.top="50%";ret.height=Math.floor(layout.height||0);
ret.marginTop=Math.floor(layout.centerY-ret.height/2);ret.bottom=null;}else{if(!SC.none(layout.height)){ret.top=0;
ret.bottom=null;if(layout.height===SC.LAYOUT_AUTO){ret.height=SC.LAYOUT_AUTO;}else{ret.height=Math.floor(layout.height||0);
}ret.marginTop=0;}else{ret.top=0;ret.bottom=0;ret.height=null;ret.marginTop=0;}}}}ret.minHeight=(layout.minHeight===undefined)?null:layout.minHeight;
ret.maxHeight=(layout.maxHeight===undefined)?null:layout.maxHeight;ret.zIndex=SC.none(layout.zIndex)?null:layout.zIndex.toString();
ret.backgroundPosition=SC.none(layout.backgroundPosition)?null:layout.backgroundPosition.toString();
var dims=SC._VIEW_DEFAULT_DIMS,loc=dims.length,x;while(--loc>=0){x=dims[loc];if(ret[x]===0){ret[x]=null;
}}for(var key in ret){var value=ret[key];if(typeof value===SC.T_NUMBER){ret[key]=(value+"px");
}}return ret;}.property().cacheable(),layoutView:function(){return this.get("parentView");
}.property("parentView").cacheable(),layoutDidChange:function(){this.beginPropertyChanges();
if(this.frame){this.notifyPropertyChange("frame");}this.notifyPropertyChange("layoutStyle");
this.endPropertyChanges();var layoutView=this.get("layoutView");if(layoutView){layoutView.set("childViewsNeedLayout",YES);
layoutView.layoutDidChangeFor(this);if(layoutView.get("childViewsNeedLayout")){layoutView.invokeOnce(layoutView.layoutChildViewsIfNeeded);
}}return this;}.observes("layout"),childViewsNeedLayout:NO,layoutDidChangeFor:function(childView){var set=this._needLayoutViews;
if(!set){set=this._needLayoutViews=SC.CoreSet.create();}set.add(childView);},layoutChildViewsIfNeeded:function(isVisible){if(!isVisible){isVisible=this.get("isVisibleInWindow");
}if(isVisible&&this.get("childViewsNeedLayout")){this.set("childViewsNeedLayout",NO);
this.layoutChildViews();}return this;},layoutChildViews:function(){var set=this._needLayoutViews,len=set?set.length:0,idx;
var view,context,layer;for(idx=0;idx<len;idx++){view=set[idx];view.updateLayout();
}view=context=layer=null;set.clear();},updateLayout:function(){var layer=this.get("layer"),context;
if(layer){context=this.renderContext(layer);this.renderLayout(context);context.update();
}layer=null;return this;},renderLayout:function(context,firstTime){context.addStyle(this.get("layoutStyle"));
},isView:YES,selectStart:function(evt){return this.get("isTextSelectable");}});SC.View.mixin({isViewClass:YES,design:function(){if(this.isDesign){return this;
}var ret=this.extend.apply(this,arguments);ret.isDesign=YES;if(SC.ViewDesigner){SC.ViewDesigner.didLoadDesign(ret,this,SC.A(arguments));
}return ret;},layout:function(layout){this.prototype.layout=layout;return this;},convertLayoutToAnchoredLayout:function(layout,parentFrame){var ret={top:0,left:0,width:parentFrame.width,height:parentFrame.height};
if(!SC.none(layout.left)){ret.left=Math.floor(layout.left);if(layout.width!==undefined){if(layout.width===SC.LAYOUT_AUTO){ret.width=SC.LAYOUT_AUTO;
}else{ret.width=Math.floor(layout.width);}}else{ret.width=parentFrame.width-ret.left-Math.floor(layout.right||0);
}}else{if(!SC.none(layout.right)){if(SC.none(layout.width)){ret.left=0;ret.width=parentFrame.width-Math.floor(layout.right||0);
}else{if(layout.width===SC.LAYOUT_AUTO){ret.width=SC.LAYOUT_AUTO;}else{ret.width=layout.width;
ret.left=parentFrame.width-(layout.width+layout.right);}}}else{if(!SC.none(layout.centerX)){ret.width=Math.floor(layout.width||0);
ret.left=Math.floor((parentFrame.width-ret.width)/2)+layout.centerX;}else{if(!SC.none(layout.width)){ret.left=0;
if(layout.width===SC.LAYOUT_AUTO){ret.width=SC.LAYOUT_AUTO;}else{ret.width=Math.floor(layout.width);
}}else{ret.left=0;ret.width=0;}}}}if(layout.minWidth!==undefined){ret.minWidth=layout.minWidth;
}if(layout.maxWidth!==undefined){ret.maxWidth=layout.maxWidth;}if(!SC.none(layout.top)){ret.top=Math.floor(layout.top);
if(layout.height!==undefined){if(layout.height===SC.LAYOUT_AUTO){ret.height=SC.LAYOUT_AUTO;
}else{ret.height=Math.floor(layout.height);}}else{ret.height=parentFrame.height-ret.top-Math.floor(layout.bottom||0);
}}else{if(!SC.none(layout.bottom)){if(SC.none(layout.height)){ret.top=0;ret.height=parentFrame.height-Math.floor(layout.bottom||0);
}else{if(layout.height===SC.LAYOUT_AUTO){ret.height=SC.LAYOUT_AUTO;}else{ret.height=layout.height;
ret.top=parentFrame.height-(layout.height+layout.bottom);}}}else{if(!SC.none(layout.centerY)){ret.height=Math.floor(layout.height||0);
ret.top=Math.floor((parentFrame.height-ret.height)/2)+layout.centerY;}else{if(!SC.none(layout.height)){ret.top=0;
if(layout.height===SC.LAYOUT_AUTO){ret.height=SC.LAYOUT_AUTO;}else{ret.height=Math.floor(layout.height);
}}else{ret.top=0;ret.height=0;}}}}if(layout.minHeight!==undefined){ret.minHeight=layout.minHeight;
}if(layout.maxHeight!==undefined){ret.maxHeight=layout.maxHeight;}return ret;},convertLayoutToCustomLayout:function(layout,layoutParams,parentFrame){},classNames:function(sc){sc=(this.prototype.classNames||[]).concat(sc);
this.prototype.classNames=sc;return this;},tagName:function(tg){this.prototype.tagName=tg;
return this;},childView:function(cv){var childViews=this.prototype.childViews||[];
if(childViews===this.superclass.prototype.childViews){childViews=childViews.slice();
}childViews.push(cv);this.prototype.childViews=childViews;return this;},bind:function(keyName,path){var p=this.prototype,s=this.superclass.prototype;
var bindings=p._bindings;if(!bindings||bindings===s._bindings){bindings=p._bindings=(bindings||[]).slice();
}keyName=keyName+"Binding";p[keyName]=path;bindings.push(keyName);return this;},prop:function(keyName,value){this.prototype[keyName]=value;
return this;},localization:function(attrs,rootElement){if(rootElement){attrs.rootElement=SC.$(rootElement).get(0);
}return attrs;},viewFor:function(element,attrs){var args=SC.$A(arguments);if(SC.none(element)){args.shift();
}else{args[0]={rootElement:SC.$(element).get(0)};}var ret=this.create.apply(this,arguments);
args=args[0]=null;return ret;},create:function(){var C=this,ret=new C(arguments);
if(SC.ViewDesigner){SC.ViewDesigner.didCreateView(ret,SC.$A(arguments));}return ret;
},loc:function(loc){var childLocs=loc.childViews;delete loc.childViews;this.applyLocalizedAttributes(loc);
if(SC.ViewDesigner){SC.ViewDesigner.didLoadLocalization(this,SC.$A(arguments));}var childViews=this.prototype.childViews,idx=childViews.length;
while(--idx>=0){var viewClass=childViews[idx];loc=childLocs[idx];if(loc&&viewClass&&viewClass.loc){viewClass.loc(loc);
}}return this;},applyLocalizedAttributes:function(loc){SC.mixin(this.prototype,loc);
},views:{}});SC.outlet=function(path){return function(key){return(this[key]=SC.objectForPropertyPath(path,this));
}.property();};SC.View.unload=function(){var views=SC.View.views;if(views){for(var key in views){if(!views.hasOwnProperty(key)){continue;
}delete views[key];}}};SC.Event.add(window,"unload",SC.View,SC.View.unload);sc_require("views/view");
SC.Pane=SC.View.extend({isPane:YES,page:null,rootResponder:null,currentWindowSize:null,computeParentDimensions:function(frame){var wframe=this.get("currentWindowSize");
var wDim={x:0,y:0,width:1000,height:1000};if(wframe){wDim.width=wframe.width;wDim.height=wframe.height;
}else{if(SC.RootResponder.responder){var wSize=SC.RootResponder.responder.get("currentWindowSize");
if(wSize){wDim.width=wSize.width;wDim.height=wSize.height;}}else{if(window.innerHeight){wDim.width=window.innerWidth;
wDim.height=window.innerHeight;}else{if(document.documentElement&&document.documentElement.clientHeight){wDim.width=document.documentElement.clientWidth;
wDim.height=document.documentElement.clientHeight;}else{if(document.body){wDim.width=document.body.clientWidth;
wDim.height=document.body.clientHeight;}}}this.windowSizeDidChange(null,wDim);}}return wDim;
},frame:function(){return this.computeFrameWithParentFrame(null);}.property(),windowSizeDidChange:function(oldSize,newSize){this.set("currentWindowSize",newSize);
this.parentViewDidResize();return this;},sendEvent:function(action,evt,target){var handler;
if(!target){target=this.get("firstResponder");}while(target&&!target.tryToPerform(action,evt)){target=(target===this)?null:target.get("nextResponder");
}if(!target&&(target=this.get("defaultResponder"))){if(typeof target===SC.T_STRING){target=SC.objectForPropertyPath(target);
}if(!target){target=null;}else{if(target.isResponderContext){target=target.sendAction(action,this,evt);
}else{target=target.tryToPerform(action,evt)?target:null;}}}return evt.mouseHandler||target;
},performKeyEquivalent:function(keystring,evt){var ret=arguments.callee.base.apply(this,arguments);
if(!ret){var defaultResponder=this.get("defaultResponder");if(defaultResponder){if(defaultResponder.performKeyEquivalent){ret=defaultResponder.performKeyEquivalent(keystring,evt);
}if(!ret){ret=defaultResponder.tryToPerform(keystring,evt);}}}return ret;},defaultResponder:null,nextResponder:function(){return null;
}.property().cacheable(),firstResponder:null,acceptsKeyPane:YES,isKeyPane:NO,becomeKeyPane:function(){if(this.get("isKeyPane")){return this;
}if(this.rootResponder){this.rootResponder.makeKeyPane(this);}return this;},resignKeyPane:function(){if(!this.get("isKeyPane")){return this;
}if(this.rootResponder){this.rootResponder.makeKeyPane(null);}return this;},makeFirstResponder:function(view){var current=this.get("firstResponder"),isKeyPane=this.get("isKeyPane");
if(current===view){return this;}if(current){current.willLoseFirstResponder(current);
}if(isKeyPane){if(current){current.willLoseKeyResponderTo(view);}if(view){view.willBecomeKeyResponderFrom(current);
}}if(current){current.beginPropertyChanges().set("isFirstResponder",NO).set("isKeyResponder",NO).endPropertyChanges();
}this.set("firstResponder",view);if(view){view.beginPropertyChanges().set("isFirstResponder",YES).set("isKeyResponder",isKeyPane).endPropertyChanges();
}if(isKeyPane){if(view){view.didBecomeKeyResponderFrom(current);}if(current){current.didLoseKeyResponderTo(view);
}}if(view){view.didBecomeFirstResponder(view);}return this;},_forwardKeyChange:function(shouldForward,methodName,pane,isKey){var keyView,responder,newKeyView;
if(shouldForward&&(responder=this.get("firstResponder"))){newKeyView=(pane)?pane.get("firstResponder"):null;
keyView=this.get("firstResponder");if(keyView){keyView[methodName](newKeyView);}if((isKey!==undefined)&&responder){responder.set("isKeyResponder",isKey);
}}},willLoseKeyPaneTo:function(pane){this._forwardKeyChange(this.get("isKeyPane"),"willLoseKeyResponderTo",pane,NO);
return this;},willBecomeKeyPaneFrom:function(pane){this._forwardKeyChange(!this.get("isKeyPane"),"willBecomeKeyResponderFrom",pane,YES);
return this;},didLoseKeyPaneTo:function(pane){var isKeyPane=this.get("isKeyPane");
this.set("isKeyPane",NO);this._forwardKeyChange(isKeyPane,"didLoseKeyResponderTo",pane);
return this;},didBecomeKeyPaneFrom:function(pane){var isKeyPane=this.get("isKeyPane");
this.set("isKeyPane",YES);this._forwardKeyChange(!isKeyPane,"didBecomeKeyResponderFrom",pane,YES);
return this;},isMainPane:NO,focusFrom:function(pane){},blurTo:function(pane){},blurMainTo:function(pane){this.set("isMainPane",NO);
},focusMainFrom:function(pane){this.set("isMainPane",YES);},append:function(){return this.appendTo(document.body);
},remove:function(){if(!this.get("isVisibleInWindow")){return this;}if(!this.get("isPaneAttached")){return this;
}var dom=this.get("layer");if(dom.parentNode){dom.parentNode.removeChild(dom);}dom=null;
this.resignKeyPane();var rootResponder=this.rootResponder;if(this.get("isMainPane")){rootResponder.makeMainPane(null);
}rootResponder.panes.remove(this);this.rootResponder=null;this.set("isPaneAttached",NO);
this.parentViewDidChange();return this;},appendTo:function(elem){var layer=this.get("layer");
if(!layer){layer=this.createLayer().get("layer");}if(this.get("isPaneAttached")&&(layer.parentNode===elem)){return this;
}elem.insertBefore(layer,null);elem=layer=null;return this.paneDidAttach();},prependTo:function(elem){if(this.get("isPaneAttached")){return this;
}var layer=this.get("layer");if(!layer){layer=this.createLayer().get("layer");}if(this.get("isPaneAttached")&&(layer.parentNode===elem)){return this;
}elem.insertBefore(layer,elem.firstChild);elem=layer=null;return this.paneDidAttach();
},before:function(elem){if(this.get("isPaneAttached")){return this;}var layer=this.get("layer");
if(!layer){layer=this.createLayer().get("layer");}var parent=elem.parentNode;if(this.get("isPaneAttached")&&(layer.parentNode===parent)){return this;
}parent.insertBefore(layer,elem);parent=elem=layer=null;return this.paneDidAttach();
},after:function(elem){var layer=this.get("layer");if(!layer){layer=this.createLayer().get("layer");
}var parent=elem.parentNode;if(this.get("isPaneAttached")&&(layer.parentNode===parent)){return this;
}parent.insertBefore(layer,elem.nextSibling);parent=elem=layer=null;return this.paneDidAttach();
},removeFromParent:function(){},paneDidAttach:function(){var responder=(this.rootResponder=SC.RootResponder.responder);
responder.panes.add(this);this.set("currentWindowSize",responder.computeWindowSize());
this.set("isPaneAttached",YES);this.parentViewDidChange();return this;},isPaneAttached:NO,recomputeIsVisibleInWindow:function(parentViewIsVisible){var last=this.get("isVisibleInWindow");
var cur=this.get("isPaneAttached")&&this.get("isVisible");if(last!==cur){this.set("isVisibleInWindow",cur);
if(cur&&this.get("layerNeedsUpdate")){this.updateLayerIfNeeded();}if(cur&&this.get("childViewsNeedLayout")){this.layoutChildViewsIfNeeded();
}var childViews=this.get("childViews"),len=childViews.length,idx;for(idx=0;idx<len;
idx++){childViews[idx].recomputeIsVisibleInWindow(cur);}if(!cur&&this.get("isFirstResponder")){this.resignFirstResponder();
}}if(cur){if(this.parentViewDidResize){this.parentViewDidResize();}if(this.get("childViewsNeedLayout")){this.invokeOnce(this.layoutChildViewsIfNeeded);
}}return this;},updateLayerLocation:function(){return this;},init:function(){var hasLayer=!!this.get("layer");
arguments.callee.base.apply(this,arguments);if(hasLayer){this.paneDidAttach();}},classNames:"sc-pane".w()});
sc_require("mixins/tree_item_content");sc_require("mixins/collection_content");SC.TreeItemObserver=SC.Object.extend(SC.Array,SC.CollectionContent,{item:null,delegate:null,parentObserver:null,parentItem:function(){var p=this.get("parentObserver");
return p?p.get("item"):null;}.property("parentObserver").cacheable(),index:null,outlineLevel:0,children:null,disclosureState:SC.BRANCH_OPEN,branchIndexes:function(){var item=this.get("item"),len,pitem,idx,children,ret;
if(!item){return SC.IndexSet.EMPTY;}else{if(item.isTreeItemContent){pitem=this.get("parentItem");
idx=this.get("index");return item.treeItemBranchIndexes(pitem,idx);}else{children=this.get("children");
if(!children){return null;}ret=SC.IndexSet.create();len=children.get("length");pitem=item;
for(idx=0;idx<len;idx++){if(!(item=children.objectAt(idx))){continue;}if(!this._computeChildren(item,pitem,idx)){continue;
}if(this._computeDisclosureState(item,pitem,idx)!==SC.LEAF_NODE){ret.add(idx);}}return ret.get("length")>0?ret:null;
}}}.property("children").cacheable(),isHeaderVisible:function(){return !!this.get("parentObserver");
}.property("parentObserver").cacheable(),length:0,objectAt:function(index){var len=this.get("length"),item=this.get("item"),cache=this._objectAtCache,cur=index,loc=0,indexes,children;
if(index>=len){return undefined;}if(this.get("isHeaderVisible")){if(index===0){return item;
}else{cur--;}}item=null;if(!cache){cache=this._objectAtCache=[];}if((item=cache[index])!==undefined){return item;
}children=this.get("children");if(!children){return undefined;}if(indexes=this.get("branchIndexes")){indexes.forEach(function(i){if(item||(i>cur)){return;
}var observer=this.branchObserverAt(i),len;if(!observer){return;}len=observer.get("length");
if(i+len>cur){item=observer.objectAt(cur-i);cur=-1;}else{cur-=len-1;}},this);}if(cur>=0){item=children.objectAt(cur);
}cache[index]=item;return item;},replace:function(start,amt,objects,operation){var cur=start,observer=null,indexes,len,max;
if(operation===undefined){operation=SC.DROP_BEFORE;}if(this.get("isHeaderVisible")){cur--;
}if(cur<0){throw"Tree Item cannot replace itself";}if(indexes=this.get("branchIndexes")){indexes.forEach(function(i){if(observer||(i>=cur)){return;
}if(!(observer=this.branchObserverAt(i))){return;}len=observer.get("length");if((i+len===cur)&&operation===SC.DROP_AFTER){cur-=i;
}else{if(i+len>cur){cur-=i;}else{cur-=len-1;observer=null;}}},this);}if(observer){observer.replace(cur,amt,objects,operation);
return this;}max=cur+amt;if(amt>1&&indexes){indexes.forEachIn(cur,indexes.get("max")-cur,function(i){if(i>max){return;
}if(!(observer=this.branchObserverAt(i))){return;}len=observer.get("length");max-=len-1;
},this);}amt=max-cur;var children=this.get("children");if(!children){throw"cannot replace() tree item with no children";
}if((amt<0)||(max>children.get("length"))){throw"replace() range must lie within a single tree item";
}children.replace(cur,amt,objects,operation);return this;},observerContentDidChange:function(start,amt,delta){this.invalidateBranchObserversAt(start);
this._objectAtCache=this._outlineLevelCache=null;this._disclosureStateCache=null;
this._contentGroupIndexes=NO;this.notifyPropertyChange("branchIndexes");var oldlen=this.get("length"),newlen=this._computeLength(),parent=this.get("parentObserver"),set;
if(oldlen!==newlen){this.set("length",newlen);}if(!this._notifyParent){return this;
}if(parent){set=SC.IndexSet.create(this.get("index"));parent._childrenRangeDidChange(parent.get("children"),null,"[]",set);
}else{if(oldlen===newlen){amt=this.expandChildIndex(start+amt);start=this.expandChildIndex(start);
amt=amt-start;delta=0;}else{start=this.expandChildIndex(start);amt=newlen-start;delta=newlen-oldlen;
}this.enumerableContentDidChange(start,amt,delta);}},expandChildIndex:function(index){var ret=index;
if(this.get("isHeaderVisible")){index++;}var branches=this.get("branchIndexes");if(!branches||branches.get("length")===0){return ret;
}branches.forEachIn(0,index,function(idx){ret+=this.branchObserverAt(idx).get("length")-1;
},this);return ret;},_contentGroupIndexes:NO,contentGroupIndexes:function(view,content){if(content!==this){return null;
}var ret=this._contentGroupIndexes;if(ret!==NO){return ret;}if(this.get("parentObserver")){return null;
}var item=this.get("item"),group,indexes,len,cur,loc,children;if(item&&item.isTreeItemContent){group=item.get("treeItemIsGrouped");
}else{group=!!this.delegate.get("treeItemIsGrouped");}if(group){ret=SC.IndexSet.create();
indexes=this.get("branchIndexes");children=this.get("children");len=children?children.get("length"):0;
cur=loc=0;if(indexes){indexes.forEach(function(i){ret.add(cur,(i+1)-loc);cur+=(i+1)-loc;
loc=i+1;var observer=this.branchObserverAt(i);if(observer){cur+=observer.get("length")-1;
}},this);}if(loc<len){ret.add(cur,len-loc);}}else{ret=null;}this._contentGroupIndexes=ret;
return ret;},contentIndexIsGroup:function(view,content,idx){var indexes=this.contentGroupIndexes(view,content);
return indexes?indexes.contains(idx):NO;},contentIndexOutlineLevel:function(view,content,index){if(content!==this){return -1;
}var cache=this._outlineLevelCache;if(cache&&(cache[index]!==undefined)){return cache[index];
}if(!cache){cache=this._outlineLevelCache=[];}var len=this.get("length"),cur=index,loc=0,ret=null,indexes,children,observer;
if(index>=len){return -1;}if(this.get("isHeaderVisible")){if(index===0){return cache[0]=this.get("outlineLevel")-1;
}else{cur--;}}if(indexes=this.get("branchIndexes")){indexes.forEach(function(i){if((ret!==null)||(i>cur)){return;
}var observer=this.branchObserverAt(i),len;if(!observer){return;}len=observer.get("length");
if(i+len>cur){ret=observer.contentIndexOutlineLevel(view,observer,cur-i);cur=-1;}else{cur-=len-1;
}},this);}if(cur>=0){ret=this.get("outlineLevel");}cache[index]=ret;return ret;},contentIndexDisclosureState:function(view,content,index){if(content!==this){return -1;
}var cache=this._disclosureStateCache;if(cache&&(cache[index]!==undefined)){return cache[index];
}if(!cache){cache=this._disclosureStateCache=[];}var len=this.get("length"),cur=index,loc=0,ret=null,indexes,children,observer;
if(index>=len){return SC.LEAF_NODE;}if(this.get("isHeaderVisible")){if(index===0){return cache[0]=this.get("disclosureState");
}else{cur--;}}if(indexes=this.get("branchIndexes")){indexes.forEach(function(i){if((ret!==null)||(i>cur)){return;
}var observer=this.branchObserverAt(i),len;if(!observer){return;}len=observer.get("length");
if(i+len>cur){ret=observer.contentIndexDisclosureState(view,observer,cur-i);cur=-1;
}else{cur-=len-1;}},this);}if(cur>=0){ret=SC.LEAF_NODE;}cache[index]=ret;return ret;
},contentIndexExpand:function(view,content,idx){var indexes,cur=idx,children,item;
if(content!==this){return;}if(this.get("isHeaderVisible")){if(idx===0){this._expand(this.get("item"));
return;}else{cur--;}}if(indexes=this.get("branchIndexes")){indexes.forEach(function(i){if(i>=cur){return;
}var observer=this.branchObserverAt(i),len;if(!observer){return;}len=observer.get("length");
if(i+len>cur){observer.contentIndexExpand(view,observer,cur-i);cur=-1;}else{cur-=len-1;
}},this);}if(cur>=0){children=this.get("children");item=children?children.objectAt(cur):null;
if(item){this._expand(item,this.get("item"),cur);}}},contentIndexCollapse:function(view,content,idx){var indexes,children,item,cur=idx;
if(content!==this){return;}if(this.get("isHeaderVisible")){if(idx===0){this._collapse(this.get("item"));
return;}else{cur--;}}if(indexes=this.get("branchIndexes")){indexes.forEach(function(i){if(i>=cur){return;
}var observer=this.branchObserverAt(i),len;if(!observer){return;}len=observer.get("length");
if(i+len>cur){observer.contentIndexCollapse(view,observer,cur-i);cur=-1;}else{cur-=len-1;
}},this);}if(cur>=0){children=this.get("children");item=children?children.objectAt(cur):null;
if(item){this._collapse(item,this.get("item"),cur);}}},branchObserverAt:function(index){var byIndex=this._branchObserversByIndex,indexes=this._branchObserverIndexes,ret,parent,pitem,item,children,guid,del;
if(!byIndex){byIndex=this._branchObserversByIndex=[];}if(!indexes){indexes=this._branchObserverIndexes=SC.IndexSet.create();
}if(ret=byIndex[index]){return ret;}children=this.get("children");item=children?children.objectAt(index):null;
if(!item){return null;}byIndex[index]=ret=SC.TreeItemObserver.create({item:item,delegate:this.get("delegate"),parentObserver:this,index:index,outlineLevel:this.get("outlineLevel")+1});
indexes.add(index);return ret;},invalidateBranchObserversAt:function(index){var byIndex=this._branchObserversByIndex,indexes=this._branchObserverIndexes;
if(!byIndex||byIndex.length<=index){return this;}if(index<0){index=0;}indexes.forEachIn(index,indexes.get("max")-index,function(i){var observer=byIndex[i];
if(observer){observer.destroy();}},this);byIndex.length=index;return this;},init:function(){arguments.callee.base.apply(this,arguments);
var item=this.get("item");if(!item){throw"SC.TreeItemObserver.item cannot be null";
}item.addObserver("*",this,this._itemPropertyDidChange);this._itemPropertyDidChange(item,"*");
this._notifyParent=YES;},destroy:function(){this.invalidateBranchObserversAt(0);this._objectAtCache=null;
var item=this.get("item");if(item){item.removeObserver("*",this,this._itemPropertyDidChange);
}var children=this._children,ro=this._childrenRangeObserver;if(children&&ro){children.removeRangeObserver(ro);
}arguments.callee.base.apply(this,arguments);},_itemPropertyDidChange:function(target,key){var children=this.get("children"),state=this.get("disclosureState"),item=this.get("item"),next;
this.beginPropertyChanges();next=this._computeDisclosureState(item);if(state!==next){this.set("disclosureState",next);
}next=this._computeChildren(item);if(children!==next){this.set("children",next);}this.endPropertyChanges();
},_childrenDidChange:function(){var state=this.get("disclosureState"),cur=state===SC.BRANCH_OPEN?this.get("children"):null,last=this._children,ro=this._childrenRangeObserver;
if(last===cur){return this;}if(ro){last.removeRangeObserver(ro);}if(cur){this._childrenRangeObserver=cur.addRangeObserver(null,this,this._childrenRangeDidChange);
}else{this._childrenRangeObserver=null;}this._children=cur;this._childrenRangeDidChange(cur,null,"[]",null);
}.observes("children","disclosureState"),_childrenRangeDidChange:function(array,objects,key,indexes){var children=this.get("children"),len=children?children.get("length"):0,min=indexes?indexes.get("min"):0,max=indexes?indexes.get("max"):len,old=this._childrenLen||0;
this._childrenLen=len;this.observerContentDidChange(min,max-min,len-old);},_computeDisclosureState:function(item,pitem,index){var key,del;
if(!item||!this._computeChildren(item)){return SC.LEAF_NODE;}else{if(item.isTreeItemContent){if(pitem===undefined){pitem=this.get("parentItem");
}if(index===undefined){index=this.get("index");}return item.treeItemDisclosureState(pitem,index);
}else{key=this._treeItemIsExpandedKey;if(!key){del=this.get("delegate");key=del?del.get("treeItemIsExpandedKey"):"treeItemIsExpanded";
this._treeItemIsExpandedKey=key;}return item.get(key)?SC.BRANCH_OPEN:SC.BRANCH_CLOSED;
}}},_collapse:function(item,pitem,index){var key,del;if(!item||!this._computeChildren(item)){return this;
}else{if(item.isTreeItemContent){if(pitem===undefined){pitem=this.get("parentItem");
}if(index===undefined){index=this.get("index");}item.treeItemCollapse(pitem,index);
}else{key=this._treeItemIsExpandedKey;if(!key){del=this.get("delegate");key=del?del.get("treeItemIsExpandedKey"):"treeItemIsExpanded";
this._treeItemIsExpandedKey=key;}item.setIfChanged(key,NO);}}return this;},_expand:function(item,pitem,index){var key,del;
if(!item||!this._computeChildren(item)){return this;}else{if(item.isTreeItemContent){if(pitem===undefined){pitem=this.get("parentItem");
}if(index===undefined){index=this.get("index");}item.treeItemExpand(pitem,index);
}else{key=this._treeItemIsExpandedKey;if(!key){del=this.get("delegate");key=del?del.get("treeItemIsExpandedKey"):"treeItemIsExpanded";
this._treeItemIsExpandedKey=key;}item.setIfChanged(key,YES);}}return this;},_computeChildren:function(item){var del,key;
if(!item){return null;}else{if(item.isTreeItemContent){return item.get("treeItemChildren");
}else{key=this._treeItemChildrenKey;if(!key){del=this.get("delegate");key=del?del.get("treeItemChildrenKey"):"treeItemChildren";
this._treeItemChildrenKey=key;}return item.get(key);}}},_computeLength:function(){var ret=this.get("isHeaderVisible")?1:0,state=this.get("disclosureState"),children=this.get("children"),indexes;
if((state===SC.BRANCH_OPEN)&&children){ret+=children.get("length");if(indexes=this.get("branchIndexes")){indexes.forEach(function(idx){var observer=this.branchObserverAt(idx);
ret+=observer.get("length")-1;},this);}}return ret;}});sc_require("system/responder");
SC.ResponderContext=SC.Responder.extend({isResponderContext:YES,trace:NO,defaultResponder:null,nextResponder:function(){return this.get("defaultResponder");
}.property("defaultResponder").cacheable(),firstResponder:null,nextResponderFor:function(responder){var next=responder.get("nextResponder");
if(typeof next===SC.T_STRING){next=SC.objectForPropertyPath(next,this);}else{if(!next&&(responder!==this)){next=this;
}}return next;},responderNameFor:function(responder){if(!responder){return"(No Responder)";
}else{if(responder._scrc_name){return responder._scrc_name;}}var n=this.NAMESPACE;
this._findResponderNamesFor(this,3,n?[this.NAMESPACE]:[]);return responder._scrc_name||responder.toString();
},_findResponderNamesFor:function(responder,level,path){var key,value;for(key in responder){if(key==="nextResponder"){continue;
}value=responder[key];if(value&&value.isResponder){if(value._scrc_name){continue;
}path.push(key);value._scrc_name=path.join(".");if(level>0){this._findResponderNamesFor(value,level-1,path);
}path.pop();}}},makeFirstResponder:function(responder){var current=this.get("firstResponder"),last=this.get("nextResponder"),trace=this.get("trace"),common;
if(this._locked){if(trace){console.log("%@: AFTER ACTION: makeFirstResponder => %@".fmt(this,this.responderNameFor(responder)));
}this._pendingResponder=responder;return;}if(trace){console.log("%@: makeFirstResponder => %@".fmt(this,this.responderNameFor(responder)));
}this._locked=YES;this._pendingResponder=null;common=responder?this.nextResponderFor(responder):null;
while(common){if(common.get("hasFirstResponder")){break;}common=(common===last)?null:this.nextResponderFor(common);
}if(!common){common=last;}this._notifyWillLoseFirstResponder(current,current,common);
if(current){current.set("isFirstResponder",NO);}this.set("firstResponder",responder);
if(responder){responder.set("isFirstResponder",YES);}this._notifyDidBecomeFirstResponder(responder,responder,common);
this._locked=NO;if(this._pendingResponder){this.makeFirstResponder(this._pendingResponder);
this._pendingResponder=null;}return this;},_notifyWillLoseFirstResponder:function(responder,cur,root){if(cur===root){return;
}cur.willLoseFirstResponder(responder);cur.set("hasFirstResponder",NO);var next=this.nextResponderFor(cur);
if(next){this._notifyWillLoseFirstResponder(responder,next,root);}},_notifyDidBecomeFirstResponder:function(responder,cur,root){if(cur===root){return;
}var next=this.nextResponderFor(cur);if(next){this._notifyDidBecomeFirstResponder(responder,next,root);
}cur.set("hasFirstResponder",YES);cur.didBecomeFirstResponder(responder);},sendAction:function(action,sender,context){var working=this.get("firstResponder"),last=this.get("nextResponder"),trace=this.get("trace"),handled=NO,responder;
this._locked=YES;if(trace){console.log("%@: begin action '%@' (%@, %@)".fmt(this,action,sender,context));
}while(!handled&&working){if(working.tryToPerform){handled=working.tryToPerform(action,sender,context);
}if(!handled){working=(working===last)?null:this.nextResponderFor(working);}}if(trace){if(!handled){console.log("%@:  action '%@' NOT HANDLED".fmt(this,action));
}else{console.log("%@: action '%@' handled by %@".fmt(this,action,this.responderNameFor(working)));
}}this._locked=NO;if(responder=this._pendingResponder){this._pendingResponder=null;
this.makeFirstResponder(responder);}return working;}});sc_require("system/responder_context");
SC.Application=SC.ResponderContext.extend({});sc_require("core");SC.Benchmark={verbose:NO,enabled:YES,stats:{},globalStartTime:null,start:function(key,parentKey,time,topLevelOnly){if(!this.enabled){return;
}var start=(time||Date.now()),stat;if(parentKey){stat=this._subStatFor(key,parentKey);
}else{stat=this._statFor(key);}if(topLevelOnly&&stat._starts.length>0){stat._starts.push("ignore");
}else{stat._starts.push(start);}stat._times.push({start:start,_subStats:{}});return key;
},end:function(key,parentKey,time){var stat;if(!this.enabled){return;}if(parentKey){stat=this._subStatFor(key,parentKey);
}else{stat=this._statFor(key);}var start=stat._starts.pop();if(!start){console.log('SC.Benchmark "%@" ended without a matching start.  No information was saved.'.fmt(key));
return;}if(start=="ignore"){return;}var end=(time||Date.now());var dur=end-start;
stat._times[stat._times.length-1].end=end;stat._times[stat._times.length-1].dur=dur;
stat.amt+=dur;stat.runs++;if(this.verbose){this.log(key);}},setGlobalStartTime:function(time){this.globalStartTime=time;
},bench:function(func,key,reps){if(!key){key="bench%@".fmt(this._benchCount++);}if(!reps){reps=1;
}var ret;while(--reps>=0){var timeKey=SC.Benchmark.start(key);ret=func();SC.Benchmark.end(timeKey);
}return ret;},install:function(object,method,topLevelOnly){object["b__"+method]=object[method];
var __func=object["b__"+method];object[method]=function(){var key="%@(%@)".fmt(method,$A(arguments).join(", "));
SC.Benchmark.start(key,topLevelOnly);var ret=__func.apply(this,arguments);SC.Benchmark.end(key);
return ret;};},restore:function(object,method){object[method]=object["b__"+method];
},report:function(key){if(key){return this._genReport(key);}var ret=[];for(var k in this.stats){if(!this.stats.hasOwnProperty(k)){continue;
}ret.push(this._genReport(k));}return ret.join("\n");},timelineReport:function(appName){appName=(appName)?"SproutCore Application":appName;
var ret=[appName,"User-Agent: %@".fmt(navigator.userAgent),"Report Generated: %@ (%@)".fmt(new Date().toString(),Date.now()),""];
var chart=this._compileChartData(true);for(var i=0;i<chart.length;i++){if(chart[i][4]){ret.push(this._timelineGenSubReport(chart[i]));
}else{ret.push(this._timelineGenReport(chart[i]));}}return ret.join("\n");},timelineChart:function(appName){var i=0;
this.hideChart();var chart=this._compileChartData(false);var chartLen=chart.length;
if(chartLen===0){return;}var gStart=this.globalStartTime?this.globalStartTime:chart[0][1];
var maxDur=chart[chartLen-1][2]-gStart;var maxHeight=50+chartLen*30;var incr=Math.ceil(maxDur/200)+1;
var maxWidth=incr*50;var graph=document.createElement("div");graph.className="sc-benchmark-graph";
document.body.appendChild(graph);var title=document.createElement("div");title.innerHTML=((appName)?appName:"SproutCore Application")+(" - Total Captured Time: "+maxDur+" ms - Points Captured: "+chartLen)+' [<a href="javascript:SC.Benchmark.hideChart();">Hide Chart</a>]';
title.className="sc-benchmark-title";graph.appendChild(title);var topBox=document.createElement("div");
topBox.className="sc-benchmark-top";topBox.style.width=maxWidth+"px";graph.appendChild(topBox);
for(i=0;i<incr;i++){var tick=document.createElement("div");tick.className="sc-benchmark-tick";
tick.style.left=(i*50)+"px";tick.style.height=maxHeight+"px";var tickLabel=document.createElement("div");
tickLabel.className="sc-benchmark-tick-label";tickLabel.style.left=(i*50)+"px";tickLabel.innerHTML=i*200+" ms";
graph.appendChild(tick);graph.appendChild(tickLabel);}for(i=0;i<chartLen;i++){var row=document.createElement("div");
row.style.top=(75+(i*30))+"px";row.style.width=maxWidth+"px";row.className=(i%2===0)?"sc-benchmark-row even":"sc-benchmark-row";
graph.appendChild(row);var div=document.createElement("div");var start=chart[i][1];
var end=chart[i][2];var duration=chart[i][3];div.innerHTML="&nbsp;"+(chart[i][0]+" <span class='sc-benchmark-emphasis'>"+duration+"ms</span>");
div.className="sc-benchmark-bar";div.style.cssText="left:"+(((start-gStart)/4))+"px; width: "+((duration/4))+"px; top: "+(53+(i*30))+"px;";
div.title="start: "+(start-gStart)+" ms, end: "+(end-gStart)+" ms, duration: "+duration+" ms";
graph.appendChild(div);}this._graph=graph;},hideChart:function(){if(this._graph){try{document.body.removeChild(this._graph);
}catch(e){}}},log:function(key){console.log(this.report(key));},startProfile:function(key){if(!this.enabled){return;
}if(console&&console.profile){console.profile(key);}},endProfile:function(key){if(!this.enabled){return;
}if(console&&console.profileEnd){console.profileEnd(key);}},_compileChartData:function(showSub){var chart=[],dispKey;
for(var key in this.stats){var stat=this.stats[key];for(var i=0;i<stat._times.length;
i++){var st=stat._times[i];dispKey=(stat._times.length>1)?(i+1)+" - "+key:key;chart.push([dispKey,st.start,st.end,st.dur,false]);
if(showSub){var subStats=st._subStats;for(var k in subStats){var subStat=subStats[k];
for(var j=0;j<subStat._times.length;j++){var s=subStat._times[j];dispKey=(subStat._times.length>1)?(j+1)+" - "+k:k;
chart.push([dispKey,s.start,s.end,s.dur,true]);}}}}}chart.sort(function(a,b){if(a[1]<b[1]){return -1;
}else{if(a[1]==b[1]){if(a[3]&&!b[3]){return -1;}if(!a[3]&&b[3]){return 1;}return 0;
}}return 1;});return chart;},_genReport:function(key){var stat=this._statFor(key);
var avg=(stat.runs>0)?(Math.floor(stat.amt*1000/stat.runs)/1000):0;return"BENCH %@ msec: %@ (%@x)".fmt(avg,(stat.name||key),stat.runs);
},_timelineGenReport:function(val){if(this.globalStartTime){return"BENCH start: %@ msec, duration: %@ msec,  %@".fmt((val[1]-this.globalStartTime),val[3],val[0]);
}else{return"BENCH duration: %@ msec, %@".fmt(val[3],val[0]);}},_timelineGenSubReport:function(val){if(this.globalStartTime){return"   CHECKPOINT BENCH start: %@ msec, duration: %@ msec,  %@".fmt((val[1]-this.globalStartTime),val[3],val[0]);
}else{return"   CHECKPOINT BENCH duration: %@ msec, %@".fmt(val[3],val[0]);}},_subStatFor:function(key,parentKey){var parentTimeLen=this.stats[parentKey]._times.length;
if(parentTimeLen===0){return;}var parentSubStats=this.stats[parentKey]._times[this.stats[parentKey]._times.length-1]._subStats;
var ret=parentSubStats[key];if(!ret){parentSubStats[key]={runs:0,amt:0,name:key,_starts:[],_times:[]};
ret=parentSubStats[key];}return ret;},_statFor:function(key){var ret=this.stats[key];
if(!ret){ret=this.stats[key]={runs:0,amt:0,name:key,_starts:[],_times:[]};ret=this.stats[key];
}return ret;},reset:function(){this.stats={};},_bench:function(func,name){SC.Benchmark.bench(func,name,1);
},_benchCount:1};SC.Benchmark=SC.Benchmark;SC.mixin({logBundleLoading:NO,bundleIsLoaded:function(bundleName){var bundleInfo=SC.BUNDLE_INFO[bundleName];
return bundleInfo?!!bundleInfo.loaded:NO;},_scb_bundleDidLoad:function(bundleName,target,method,args){var m=method,t=target;
if(SC.typeOf(target)===SC.T_STRING){t=SC.objectForPropertyPath(target);}if(SC.typeOf(method)===SC.T_STRING){m=SC.objectForPropertyPath(method,t);
}if(!m){if(SC.LAZY_INSTANTIATION[bundleName]){var lazyInfo=SC.LAZY_INSTANTIATION[bundleName];
if(SC.logBundleLoading){console.log("SC.loadBundle(): Bundle '%@' is marked for lazy instantiation, instantiating it now…".fmt(bundleName));
}for(var i=0,iLen=lazyInfo.length;i<iLen;i++){try{lazyInfo[i]();}catch(e){console.log("SC.loadBundle(): Failted to lazily instatiate entry for  '%@'".fmt(bundleName));
}}delete SC.LAZY_INSTANTIATION[bundleName];if(SC.typeOf(target)===SC.T_STRING){t=SC.objectForPropertyPath(target);
}if(SC.typeOf(method)===SC.T_STRING){m=SC.objectForPropertyPath(method,t);}if(!method){throw"SC.loadBundle(): could not find callback for lazily instantiated bundle '%@'".fmt(bundleName);
}}else{throw"SC.loadBundle(): could not find callback for '%@'".fmt(bundleName);}}if(!args){args=[];
}args.push(bundleName);var needsRunLoop=!!SC.RunLoop.currentRunLoop;if(needsRunLoop){SC.RunLoop.begin();
}m.apply(t,args);if(needsRunLoop){SC.RunLoop.end();}},tryToLoadBundle:function(bundleName,target,method,args){var m,t;
if(SC.typeOf(target)===SC.T_STRING){t=SC.objectForPropertyPath(target);}if(SC.typeOf(method)===SC.T_STRING){m=SC.objectForPropertyPath(method,t);
}if(m||SC.LAZY_INSTANTIATION[bundleName]){if(SC.logBundleLoading){console.log("SC.loadBundle(): Bundle '%@' found through other means, will attempt to load…".fmt(bundleName));
}SC.BUNDLE_INFO[bundleName]={loaded:YES};return SC.BUNDLE_INFO[bundleName];}return NO;
},loadBundle:function(bundleName,target,method){var idx,len;if(method===undefined&&SC.typeOf(target)===SC.T_FUNCTION){method=target;
target=null;}var bundleInfo=SC.BUNDLE_INFO[bundleName],callbacks,targets;var args=SC.A(arguments).slice(3);
if(SC.logBundleLoading){console.log("SC.loadBundle(): Attempting to load '%@'".fmt(bundleName));
}if(!bundleInfo){if(SC.logBundleLoading){console.log("SC.loadBundle(): Attemping to load %@ without SC.BUNDLE_INFO entry… could be loaded through other means.".fmt(bundleName));
}bundleInfo=this.tryToLoadBundle(bundleName,target,method,args);}if(!bundleInfo){throw"SC.loadBundle(): could not find bundle '%@'".fmt(bundleName);
}else{if(bundleInfo.loaded){if(SC.logBundleLoading){console.log("SC.loadBundle(): Bundle '%@' already loaded, skipping.".fmt(bundleName));
}if(method){if(SC.isReady){SC._scb_bundleDidLoad(bundleName,target,method,args);}else{SC.ready(SC,function(){SC._scb_bundleDidLoad(bundleName,target,method,args);
});}}}else{if(SC.logBundleLoading){console.log("SC.loadBundle(): Bundle '%@' is not loaded, loading now.".fmt(bundleName));
}callbacks=bundleInfo.callbacks||[];if(method){callbacks.push(function(){SC._scb_bundleDidLoad(bundleName,target,method,args);
});bundleInfo.callbacks=callbacks;}if(!bundleInfo.loading){var requires=bundleInfo.requires||[];
var dependenciesMet=YES;for(idx=0,len=requires.length;idx<len;++idx){var targetName=requires[idx];
var targetInfo=SC.BUNDLE_INFO[targetName];if(!targetInfo){throw"SC.loadBundle(): could not find required bundle '%@' for bundle '%@'".fmt(targetName,bundleName);
}else{if(targetInfo.loading){dependenciesMet=NO;break;}else{if(targetInfo.loaded){continue;
}else{dependenciesMet=NO;var dependents=targetInfo.dependents;if(!dependents){targetInfo.dependents=dependents=[];
}dependents.push(bundleName);if(SC.logBundleLoading){console.log("SC.loadBundle(): '%@' depends on '%@', loading dependency…".fmt(bundleName,targetName));
}SC.loadBundle(targetName);break;}}}}if(dependenciesMet){var styles,scripts,url,el,head,body;
head=document.getElementsByTagName("head")[0];if(!head){head=document.documentElement;
}styles=bundleInfo.styles||[];for(idx=0,len=styles.length;idx<len;++idx){url=styles[idx];
if(url.length>0){el=document.createElement("link");el.setAttribute("href",url);el.setAttribute("rel","stylesheet");
el.setAttribute("type","text/css");head.appendChild(el);}}var jsBundleLoadQueue=this._jsBundleLoadQueue;
if(!jsBundleLoadQueue){this._jsBundleLoadQueue=jsBundleLoadQueue={};}jsBundleLoadQueue[bundleName]=[];
var q=jsBundleLoadQueue[bundleName];scripts=bundleInfo.scripts||[];for(idx=0,len=scripts.length;
idx<len;++idx){url=scripts[idx];if(url.length>0){q.push(url);}}bundleInfo.loading=YES;
this.scriptDidLoad(bundleName);}}}}},scriptDidLoad:function(bundleName){var jsBundleLoadQueue=this._jsBundleLoadQueue;
if(jsBundleLoadQueue){var q=jsBundleLoadQueue[bundleName];if(q){var url=q.shift();
if(SC.logBundleLoading){console.log("SC.scriptDidLoad(): Loading next file in '%@' -> '%@'".fmt(bundleName,url));
}var el=document.createElement("script");el.setAttribute("type","text/javascript");
el.setAttribute("src",url);document.body.appendChild(el);}}},bundleDidLoad:function(bundleName){var bundleInfo=SC.BUNDLE_INFO[bundleName],callbacks,targets;
if(!bundleInfo){bundleInfo=SC.BUNDLE_INFO[bundleName]={loaded:YES};return;}if(bundleInfo.loaded&&SC.logBundleLoading){console.log("SC.bundleDidLoad() called more than once for bundle '%@'. Skipping.".fmt(bundleName));
return;}delete bundleInfo.loading;bundleInfo.loaded=YES;if(SC.isReady){SC._invokeCallbacksForBundle(bundleName);
}else{SC.ready(SC,function(){SC._invokeCallbacksForBundle(bundleName);});}var dependents=bundleInfo.dependents||[];
for(var idx=0,len=dependents.length;idx<len;++idx){if(SC.logBundleLoading){console.log("SC.loadBundle(): Bundle '%@' has completed loading, loading '%@' that depended on it.".fmt(bundleName,dependents[idx]));
}SC.loadBundle(dependents[idx]);}},_invokeCallbacksForBundle:function(bundleName){var bundleInfo=SC.BUNDLE_INFO[bundleName],callbacks;
if(!bundleInfo){return;}if(SC.logBundleLoading){console.log("SC.loadBundle(): Bundle '%@' has completed loading, invoking callbacks.".fmt(bundleName));
}callbacks=bundleInfo.callbacks||[];SC.RunLoop.begin();for(var idx=0,len=callbacks.length;
idx<len;++idx){callbacks[idx]();}SC.RunLoop.end();}});sc_require("system/locale");
SC.IMAGE_ABORTED_ERROR=SC.$error("SC.Image.AbortedError","Image",-100);SC.IMAGE_FAILED_ERROR=SC.$error("SC.Image.FailedError","Image",-101);
SC.imageCache=SC.Object.create({loadLimit:4,activeRequests:0,loadImage:function(url,target,method,isBackgroundFlag){var type=SC.typeOf(target);
if(SC.none(method)&&SC.typeOf(target)===SC.T_FUNCTION){target=null;method=target;
}if(SC.typeOf(method)===SC.T_STRING){method=target[method];}if(SC.none(isBackgroundFlag)){isBackgroundFlag=SC.none(target)&&SC.none(method);
}var entry=this._imageEntryFor(url);if(entry.status===this.IMAGE_LOADED){if(method){method.call(target||entry.image,entry.url,entry.image);
}}else{if(target||method){this._addCallback(entry,target,method);}entry.retainCount++;
this._scheduleImageEntry(entry,isBackgroundFlag);}},releaseImage:function(url,target,method){var entry=this._imageEntryFor(url,NO);
if(!entry){return this;}if(--entry.retainCount<=0){this._deleteEntry(entry);}else{if(target||method){var type=SC.typeOf(target);
if(SC.none(method)&&SC.typeOf(target)===SC.T_FUNCTION){target=null;method=target;
}if(SC.typeOf(method)===SC.T_STRING){method=target[method];}this._removeCallback(entry,target,method);
}}},reloadImage:function(url){var entry=this._imageEntryFor(url,NO);if(entry&&entry.status===this.IMAGE_LOADED){entry.status=this.IMAGE_WAITING;
}},loadNextImage:function(){var entry=null,queue;if(this.get("activeRequests")>=this.get("loadLimit")){return;
}queue=this._foregroundQueue;while(queue.length>0&&!entry){entry=queue.shift();}if(!entry){queue=this._backgroundQueue;
while(queue.length>0&&!entry){entry=queue.shift();}}this.set("isLoading",!!entry);
if(entry){var img=entry.image;img.onabort=this._imageDidAbort;img.onerror=this._imageDidError;
img.onload=this._imageDidLoad;img.src=entry.url;this._loading.push(entry);this.incrementProperty("activeRequests");
this.loadNextImage();}},_imageEntryFor:function(url,createIfNeeded){if(createIfNeeded===undefined){createIfNeeded=YES;
}var entry=this._images[url];if(!entry&&createIfNeeded){var img=new Image();entry=this._images[url]={url:url,status:this.IMAGE_WAITING,callbacks:[],retainCount:0,image:img};
img.entry=entry;}return entry;},_deleteEntry:function(entry){this._unscheduleEntry(entry);
delete this._images[entry.url];},_addCallback:function(entry,target,method){var callbacks=entry.callbacks;
var handler=callbacks.find(function(x){return x[0]===target&&x[1]===method;},this);
if(!handler){callbacks.push([target,method]);}callbacks=null;return this;},_removeCallback:function(entry,target,method){var callbacks=entry.callbacks;
callbacks.forEach(function(x,idx){if(x[0]===target&&x[1]===method){callbacks[idx]=null;
}},this);callbacks=null;return this;},_scheduleImageEntry:function(entry,isBackgroundFlag){var background=this._backgroundQueue;
var foreground=this._foregroundQueue;if(entry.status===this.IMAGE_LOADED){return this;
}if((entry.status===this.IMAGE_QUEUE)&&!isBackgroundFlag&&entry.isBackground){background[background.indexOf(entry)]=null;
entry.status=this.IMAGE_WAITING;}if(entry.status!==this.IMAGE_QUEUE){var queue=(isBackgroundFlag)?background:foreground;
queue.push(entry);entry.status=this.IMAGE_QUEUE;entry.isBackground=isBackgroundFlag;
}if(!this.isLoading){this.invokeLater(this.loadNextImage,100);}this.set("isLoading",YES);
return this;},_unscheduleImageEntry:function(entry){if(entry.status!==this.IMAGE_QUEUE){return this;
}var queue=entry.isBackground?this._backgroundQueue:this._foregroundQueue;queue[queue.indexOf(entry)]=null;
if(this._loading.indexOf(entry)>=0){queue.image.abort();this.imageStatusDidChange(entry,this.ABORTED);
}return this;},_imageDidAbort:function(){SC.imageCache.imageStatusDidChange(this.entry,SC.imageCache.ABORTED);
},_imageDidError:function(){SC.imageCache.imageStatusDidChange(this.entry,SC.imageCache.ERROR);
},_imageDidLoad:function(){SC.imageCache.imageStatusDidChange(this.entry,SC.imageCache.LOADED);
},imageStatusDidChange:function(entry,status){if(!entry){return;}var url=entry.url;
var value;switch(status){case this.LOADED:value=entry.image;break;case this.ABORTED:value=SC.IMAGE_ABORTED_ERROR;
break;case this.ERROR:value=SC.IMAGE_FAILED_ERROR;break;default:value=SC.IMAGE_FAILED_ERROR;
break;}entry.callbacks.forEach(function(x){var target=x[0],method=x[1];method.call(target,url,value);
},this);entry.callbacks=[];entry.status=(status===this.LOADED)?this.IMAGE_LOADED:this.IMAGE_WAITING;
var image=entry.image;if(image){image.onload=image.onerror=image.onabort=null;if(status!==this.LOADED){entry.image=null;
}}this._loading[this._loading.indexOf(entry)]=null;if(this._loading.length>this.loadLimit*2){this._loading=this._loading.compact();
}this.decrementProperty("activeRequests");this.loadNextImage();},init:function(){arguments.callee.base.apply(this,arguments);
this._images={};this._loading=[];this._foregroundQueue=[];this._backgroundQueue=[];
},IMAGE_LOADED:"loaded",IMAGE_QUEUED:"queued",IMAGE_WAITING:"waiting",ABORTED:"aborted",ERROR:"error",LOADED:"loaded"});
SC.Page=SC.Object.extend({owner:null,get:function(key){var value=this[key];if(value&&value.isClass){this[key]=value=value.create({page:this});
if(!this.get("inDesignMode")){value.awake();}return value;}else{return arguments.callee.base.apply(this,arguments);
}},awake:function(){for(var key in this){if(!this.hasOwnProperty(key)){continue;}var value=this[key];
if(value&&value.isViewClass){this[key]=value=value.create({page:this});}}return this;
},getIfConfigured:function(key){var ret=this[key];return(ret&&ret.isViewClass)?null:this.get(key);
},loc:function(locs){for(var key in locs){if(!locs.hasOwnProperty(key)){continue;
}var view=this[key];if(!view||!view.isViewClass){continue;}view.loc(locs[key]);}return this;
}});SC.Page.design=SC.Page.create;SC.Page.localization=function(attrs){return attrs;
};sc_require("system/event");SC.mixin({_isReadyBound:NO,_bindReady:function(){if(this._isReadyBound){return;
}this._isReadyBound=YES;tiki.require("system").ready(this,this._didBecomeReady);},_readyQueue:[],_afterReadyQueue:[],isReady:NO,_didBecomeReady:function(){if(SC.isReady){return;
}if(typeof SC.mapDisplayNames===SC.T_FUNCTION){SC.mapDisplayNames();}SC.Locale.createCurrentLocale();
if(document&&document.getElementsByTagName){var body=document.getElementsByTagName("body")[0];
if(body){var className=body.className;var language=SC.Locale.currentLanguage.toLowerCase();
body.className=(className&&className.length>0)?[className,language].join(" "):language;
}}SC.Benchmark.start("ready");SC.RunLoop.begin();var handler,ary,idx,len;do{ary=SC._readyQueue;
SC._readyQueue=[];for(idx=0,len=ary.length;idx<len;idx++){handler=ary[idx];var target=handler[0]||document;
var method=handler[1];if(method){method.call(target);}}}while(SC._readyQueue.length>0);
SC.isReady=YES;SC._readyQueue=null;SC.Event.trigger("ready",null,document,NO);if(SC.removeLoading){SC.$("#loading").remove();
}if((SC.mode===SC.APP_MODE)&&(typeof main!="undefined")&&(main instanceof Function)&&!SC.suppressMain){main();
}if(SC.routes&&SC.routes.ping){SC.routes.ping();}SC.RunLoop.end();SC.Benchmark.end("ready");
SC.Benchmark.log();},ready:function(target,method){var queue=this._readyQueue;if(method===undefined){method=target;
target=null;}else{if(SC.typeOf(method)===SC.T_STRING){method=target[method];}}if(!method){return this;
}if(this.isReady){return method.call(target||document);}queue.push([target,method]);
return this;}});SC._bindReady();SC.removeLoading=YES;SC.APP_MODE="APP_MODE";SC.TEST_MODE="TEST_MODE";
SC.mode=SC.APP_MODE;sc_require("system/builder");SC.MODE_REPLACE="replace";SC.MODE_APPEND="append";
SC.MODE_PREPEND="prepend";SC.RenderContext=SC.Builder.create({SELF_CLOSING:SC.CoreSet.create().addEach("area base basefront br hr input img link meta".w()),init:function(tagNameOrElement,prevContext){if(tagNameOrElement===undefined){tagNameOrElement="div";
}if(prevContext){this.prevObject=prevContext;this.strings=prevContext.strings;this.offset=prevContext.length+prevContext.offset;
}if(!this.strings){this.strings=[];}this.needsContent=YES;if(SC.typeOf(tagNameOrElement)===SC.T_STRING){this._tagName=tagNameOrElement.toLowerCase();
this._needsTag=YES;var c=this;while(c){c.length++;c=c.prevObject;}this.strings.push(null);
this._selfClosing=this.SELF_CLOSING.contains(this._tagName);}else{this._elem=tagNameOrElement;
this._needsTag=NO;this.length=0;this.needsContent=NO;}return this;},strings:null,offset:0,length:0,updateMode:SC.MODE_REPLACE,needsContent:NO,get:function(idx){var strings=this.strings||[];
return(idx===undefined)?strings.slice(this.offset,this.length):strings[idx+this.offset];
},push:function(line){var strings=this.strings,len=arguments.length;if(!strings){this.strings=strings=[];
}if(len>1){strings.push.apply(strings,arguments);}else{strings.push(line);}var c=this;
while(c){c.length+=len;c=c.prevObject;}this.needsContent=YES;return this;},text:function(line){var len=arguments.length,idx=0;
for(idx=0;idx<len;idx++){this.push(SC.RenderContext.escapeHTML(arguments[idx]));}return this;
},join:function(joinChar){if(this._needsTag){this.end();}var strings=this.strings;
return strings?strings.join(joinChar||""):"";},begin:function(tagNameOrElement){return SC.RenderContext(tagNameOrElement,this);
},element:function(){if(this._elem){return this._elem;}var ret,child;if(!SC.RenderContext.factory){SC.RenderContext.factory=document.createElement("div");
}SC.RenderContext.factory.innerHTML=this.join();if(SC.RenderContext.factory.innerHTML.length>0){child=SC.RenderContext.factory.firstChild.cloneNode(true);
SC.RenderContext.factory.innerHTML="";}else{child=null;}return child;},remove:function(elementId){if(!elementId){return;
}var el,elem=this._elem;if(!elem||!elem.removeChild){return;}el=document.getElementById(elementId);
if(el){el=elem.removeChild(el);el=null;}},update:function(){var elem=this._elem,mode=this.updateMode,key,value,styles,factory,cur,next,before;
if(!elem){return;}if(this.length>0){if(mode===SC.MODE_REPLACE){elem.innerHTML=this.join();
}else{factory=elem.cloneNode(false);factory.innerHTML=this.join();before=(mode===SC.MODE_APPEND)?null:elem.firstChild;
cur=factory.firstChild;while(cur){next=cur.nextSibling;elem.insertBefore(cur,next);
cur=next;}cur=next=factory=before=null;}}if(this._attrsDidChange&&(value=this._attrs)){for(key in value){if(!value.hasOwnProperty(key)){continue;
}if(value[key]===null){elem.removeAttribute(key);}else{SC.$(elem).attr(key,value[key]);
}}}if(this._classNamesDidChange&&(value=this._classNames)){SC.$(elem).attr("class",value.join(" "));
}if(this._idDidChange&&(value=this._id)){SC.$(elem).attr("id",value);}if(this._stylesDidChange&&(styles=this._styles)){var pair=this._STYLE_PAIR_ARRAY,joined=this._JOIN_ARRAY;
for(key in styles){if(!styles.hasOwnProperty(key)){continue;}value=styles[key];if(value===null){continue;
}if(typeof value===SC.T_NUMBER){value=value.toString()+"px";}pair[0]=key.dasherize();
pair[1]=value;joined.push(pair.join(": "));}SC.$(elem).attr("style",joined.join("; "));
joined.length=0;}elem=this._elem=null;return this.prevObject||this;},_DEFAULT_ATTRS:{},_TAG_ARRAY:[],_JOIN_ARRAY:[],_STYLE_PAIR_ARRAY:[],end:function(){var tag=this._TAG_ARRAY,pair,joined,key;
var attrs=this._attrs,className=this._classNames;var id=this._id,styles=this._styles;
tag[0]="<";tag[1]=this._tagName;if(attrs||className||styles||id){if(!attrs){attrs=this._DEFAULT_ATTRS;
}if(id){attrs.id=id;}if(className){attrs["class"]=className.join(" ");}if(styles){joined=this._JOIN_ARRAY;
pair=this._STYLE_PAIR_ARRAY;for(key in styles){if(!styles.hasOwnProperty(key)){continue;
}pair[0]=key.dasherize();pair[1]=styles[key];if(pair[1]===null){continue;}if(typeof pair[1]===SC.T_NUMBER){pair[1]="%@px".fmt(pair[1]);
}joined.push(pair.join(": "));}attrs.style=joined.join("; ");joined.length=0;}tag.push(" ");
for(key in attrs){if(!attrs.hasOwnProperty(key)){continue;}if(attrs[key]===null){continue;
}tag.push(key);tag.push('="');tag.push(attrs[key]);tag.push('" ');}if(attrs===this._DEFAULT_ATTRS){delete attrs.style;
delete attrs["class"];delete attrs.id;}}var strings=this.strings;var selfClosing=(this._selfClosing===NO)?NO:(this.length===1);
tag.push(selfClosing?" />":">");strings[this.offset]=tag.join("");tag.length=0;if(!selfClosing){tag[0]="</";
tag[1]=this._tagName;tag[2]=">";strings.push(tag.join(""));var c=this;while(c){c.length++;
c=c.prevObject;}tag.length=0;}this._elem=null;return this.prevObject||this;},tag:function(tagName,opts){return this.begin(tagName,opts).end();
},tagName:function(tagName){if(tagName===undefined){if(!this._tagName&&this._elem){this._tagName=this._elem.tagName;
}return this._tagName;}else{this._tagName=tagName;this._tagNameDidChange=YES;return this;
}},id:function(idName){if(idName===undefined){if(!this._id&&this._elem){this._id=this._elem.id;
}return this._id;}else{this._id=idName;this._idDidChange=YES;return this;}},classNames:function(classNames,cloneOnModify){if(classNames===undefined){if(!this._classNames&&this._elem){this._classNames=(SC.$(this._elem).attr("class")||"").split(" ");
}if(this._cloneClassNames){this._classNames=(this._classNames||[]).slice();this._cloneClassNames=NO;
}if(!this._classNames){this._classNames=[];}return this._classNames;}else{this._classNames=classNames;
this._cloneClassNames=cloneOnModify||NO;this._classNamesDidChange=YES;return this;
}},hasClass:function(className){return this.classNames().indexOf(className)>=0;},addClass:function(className){var classNames=this.classNames();
if(classNames.indexOf(className)<0){classNames.push(className);this._classNamesDidChange=YES;
}return this;},removeClass:function(className){var classNames=this._classNames,idx;
if(!classNames&&this._elem){classNames=this._classNames=(SC.$(this._elem).attr("class")||"").split(" ");
}if(classNames&&(idx=classNames.indexOf(className))>=0){if(this._cloneClassNames){classNames=this._classNames=classNames.slice();
this._cloneClassNames=NO;}classNames[idx]=null;this._classNamesDidChange=YES;}return this;
},resetClassNames:function(){this._classNames=[];this._classNamesDidChange=YES;return this;
},setClass:function(className,shouldAdd){var classNames,idx,key,didChange;if(shouldAdd!==undefined){return shouldAdd?this.addClass(className):this.removeClass(className);
}else{classNames=this._classNames;if(!classNames&&this._elem){classNames=this._classNames=(SC.$(this._elem).attr("class")||"").split(" ");
}if(!classNames){classNames=this._classNames=[];}if(this._cloneClassNames){classNames=this._classNames=classNames.slice();
this._cloneClassNames=NO;}didChange=NO;for(key in className){if(!className.hasOwnProperty(key)){continue;
}idx=classNames.indexOf(key);if(className[key]){if(idx<0){classNames.push(key);didChange=YES;
}}else{if(idx>=0){classNames[idx]=null;didChange=YES;}}}if(didChange){this._classNamesDidChange=YES;
}}return this;},_STYLE_REGEX:/\s*([^:\s]+)\s*:\s*([^;]+)\s*;?/g,styles:function(styles,cloneOnModify){var attr,regex,match;
if(styles===undefined){if(!this._styles&&this._elem){attr=SC.$(this._elem).attr("style");
if(attr&&(attr=attr.toString()).length>0){if(SC.browser.msie){attr=attr.toLowerCase();
}styles={};regex=this._STYLE_REGEX;regex.lastIndex=0;while(match=regex.exec(attr)){styles[match[1].camelize()]=match[2];
}this._styles=styles;this._cloneStyles=NO;}else{this._styles={};}}else{if(!this._styles){this._styles={};
}else{if(this._cloneStyles){this._styles=SC.beget(this._styles);this._cloneStyles=NO;
}}}return this._styles;}else{this._styles=styles;this._cloneStyles=cloneOnModify||NO;
this._stylesDidChange=YES;return this;}},addStyle:function(nameOrStyles,value){var key,didChange=NO,styles=this.styles();
if(typeof nameOrStyles===SC.T_STRING){if(value===undefined){return styles[nameOrStyles];
}else{if(styles[nameOrStyles]!==value){styles[nameOrStyles]=value;this._stylesDidChange=YES;
}}}else{for(key in nameOrStyles){if(!nameOrStyles.hasOwnProperty(key)){continue;}value=nameOrStyles[key];
if(styles[key]!==value){styles[key]=value;didChange=YES;}}if(didChange){this._stylesDidChange=YES;
}}return this;},removeStyle:function(styleName){if(!this._styles&&!this._elem){return this;
}var styles=this.styles();if(styles[styleName]){styles[styleName]=null;this._stylesDidChange=YES;
}},attr:function(nameOrAttrs,value){var key,attrs=this._attrs,didChange=NO;if(!attrs){this._attrs=attrs={};
}if(typeof nameOrAttrs===SC.T_STRING){if(value===undefined){return attrs[nameOrAttrs];
}else{if(attrs[nameOrAttrs]!==value){attrs[nameOrAttrs]=value;this._attrsDidChange=YES;
}}}else{for(key in nameOrAttrs){if(!nameOrAttrs.hasOwnProperty(key)){continue;}value=nameOrAttrs[key];
if(attrs[key]!==value){attrs[key]=value;didChange=YES;}}if(didChange){this._attrsDidChange=YES;
}}return this;}});SC.RenderContext.fn.html=SC.RenderContext.fn.push;SC.RenderContext.fn.css=SC.RenderContext.fn.addStyle;
if(!SC.browser.isSafari||parseInt(SC.browser.version,10)<526){SC.RenderContext._safari3=YES;
}SC.RenderContext.escapeHTML=function(text){var elem,node,ret;if(SC.none(text)){return text;
}elem=this.escapeHTMLElement;if(!elem){elem=this.escapeHTMLElement=document.createElement("div");
}node=this.escapeTextNode;if(!node){node=this.escapeTextNode=document.createTextNode("");
elem.appendChild(node);}node.data=text;ret=elem.innerHTML;if(SC.RenderContext._safari3){ret=ret.replace(/>/g,"&gt;");
}node=elem=null;return ret;};SC.Response=SC.Object.extend({isError:NO,errorValue:function(){return this;
}.property().cacheable(),errorObject:null,request:null,originalRequest:function(){var ret=this.get("request");
while(ret.get("source")){ret=ret.get("source");}return ret;}.property("request").cacheable(),type:function(){return this.getPath("request.type");
}.property("request").cacheable(),address:function(){return this.getPath("request.address");
}.property("request").cacheable(),isJSON:function(){return this.getPath("request.isJSON")||NO;
}.property("request").cacheable(),isXML:function(){return this.getPath("request.isXML")||NO;
}.property("request").cacheable(),listeners:function(){return this.getPath("request.listeners");
}.property("request").cacheable(),status:-100,headers:null,encodedBody:null,body:function(){var ret=this.get("encodedBody");
if(ret&&this.get("isJSON")){try{ret=SC.json.decode(ret);}catch(e){return SC.Error.create({message:e.name+": "+e.message,label:"Response",errorValue:this});
}}return ret;}.property("encodedBody").cacheable(),response:function(){return this.get("body");
}.property("body").cacheable(),isCancelled:NO,fire:function(){var req=this.get("request"),source=req?req.get("source"):null;
if(source&&source.willSend){source.willSend(req,this);}req.freeze();if(!this.get("isCancelled")){this.invokeTransport();
}if(!this.get("isCancelled")&&source&&source.didSend){source.didSend(req,this);}},invokeTransport:function(){this.receive(function(proceed){this.set("status",200);
},this);},receive:function(callback,context){var req=this.get("request");var source=req?req.get("source"):null;
if(source&&source.willReceive){source.willReceive(req,this);}callback.call(context,!this.get("isCancelled"));
if(!this.get("isCancelled")&&source&&source.didReceive){source.didReceive(req,this);
}if(!this.get("isCancelled")){this.notify();}SC.Request.manager.transportDidClose(this);
return this;},cancel:function(){if(!this.get("isCancelled")){this.set("isCancelled",YES);
this.cancelTransport();SC.Request.manager.transportDidClose(this);}},cancelTransport:function(){},_notifyListener:function(listeners,status){var info=listeners[status],params,target,action;
if(!info){return NO;}params=(info.params||[]).copy();params.unshift(this);target=info.target;
action=info.action;if(SC.typeOf(action)===SC.T_STRING){action=target[action];}return action.apply(target,params);
},notify:function(){var listeners=this.get("listeners"),status=this.get("status"),baseStat=Math.floor(status/100)*100,handled=NO;
if(!listeners){return this;}SC.RunLoop.begin();handled=this._notifyListener(listeners,status);
if(!handled){handled=this._notifyListener(listeners,baseStat);}if(!handled){handled=this._notifyListener(listeners,0);
}SC.RunLoop.end();return this;},toString:function(){var ret=arguments.callee.base.apply(this,arguments);
return"%@<%@ %@, status=%@".fmt(ret,this.get("type"),this.get("address"),this.get("status"));
}});SC.XHRResponse=SC.Response.extend({headers:function(){var xhr=this.get("rawRequest"),str=xhr?xhr.getAllResponseHeaders():null,ret={};
if(!str){return ret;}str.split("\n").forEach(function(header){var idx=header.indexOf(":"),key,value;
if(idx>=0){key=header.slice(0,idx);value=header.slice(idx+1).trim();ret[key]=value;
}},this);return ret;}.property("status").cacheable(),header:function(key){var xhr=this.get("rawRequest");
return xhr?xhr.getResponseHeader(key):null;},encodedBody:function(){var xhr=this.get("rawRequest"),ret;
if(!xhr){ret=null;}else{if(this.get("isXML")){ret=xhr.responseXML;}else{ret=xhr.responseText;
}}return ret;}.property("status").cacheable(),cancelTransport:function(){var rawRequest=this.get("rawRequest");
if(rawRequest){rawRequest.abort();}this.set("rawRequest",null);},invokeTransport:function(){var rawRequest,transport,handleReadyStateChange,async,headers;
function tryThese(){for(var i=0;i<arguments.length;i++){try{var item=arguments[i]();
return item;}catch(e){}}return NO;}rawRequest=tryThese(function(){return new XMLHttpRequest();
},function(){return new ActiveXObject("Msxml2.XMLHTTP");},function(){return new ActiveXObject("Microsoft.XMLHTTP");
});this.set("rawRequest",rawRequest);async=!!this.getPath("request.isAsynchronous");
if(async){if(!SC.browser.msie){SC.Event.add(rawRequest,"readystatechange",this,this.finishRequest,rawRequest);
}else{transport=this;handleReadyStateChange=function(){if(!transport){return null;
}var ret=transport.finishRequest();if(ret){transport=null;}return ret;};rawRequest.onreadystatechange=handleReadyStateChange;
}}rawRequest.open(this.get("type"),this.get("address"),async);headers=this.getPath("request.headers");
for(var headerKey in headers){rawRequest.setRequestHeader(headerKey,headers[headerKey]);
}rawRequest.send(this.getPath("request.encodedBody"));if(!async){this.finishRequest();
}return rawRequest;},finishRequest:function(evt){var rawRequest=this.get("rawRequest"),readyState=rawRequest.readyState,error,status,msg;
if(readyState===4){this.receive(function(proceed){if(!proceed){return;}status=-1;
try{status=rawRequest.status||0;}catch(e){}if((status<200)||(status>=300)){msg=rawRequest.statusText;
error=SC.$error(msg||"HTTP Request failed","Request",status);error.set("errorValue",this);
this.set("isError",YES);this.set("errorObject",error);}this.set("status",status);
},this);rawRequest.onreadystatechange=function(){};return YES;}return NO;}});sc_require("system/response");
SC.Request=SC.Object.extend(SC.Copyable,SC.Freezable,{isAsynchronous:YES,isJSON:NO,isXML:NO,headers:function(){var ret=this._headers;
if(!ret){ret=this._headers={};}return ret;}.property().cacheable(),responseClass:SC.XHRResponse,source:null,address:null,type:"GET",body:null,encodedBody:function(){var ret=this.get("body");
if(ret&&this.get("isJSON")){ret=SC.json.encode(ret);}return ret;}.property("isJSON","isXML","body").cacheable(),willSend:function(request,response){},didSend:function(request,response){},willReceive:function(request,response){},didReceive:function(request,response){},COPY_KEYS:"isAsynchronous isJSON isXML address type body responseClass willSend didSend willReceive didReceive".w(),copy:function(){var ret={},keys=this.COPY_KEYS,loc=keys.length,key,listeners,headers;
while(--loc>=0){key=keys[loc];if(this.hasOwnProperty(key)){ret[key]=this.get(key);
}}if(this.hasOwnProperty("listeners")){ret.listeners=SC.copy(this.get("listeners"));
}if(this.hasOwnProperty("_headers")){ret._headers=SC.copy(this._headers);}ret.source=this.get("source")||this;
return this.constructor.create(ret);},header:function(key,value){var headers;if(SC.typeOf(key)===SC.T_STRING){headers=this._headers;
if(arguments.length===1){return headers?headers[key]:null;}else{this.propertyWillChange("headers");
if(!headers){headers=this._headers={};}headers[key]=value;this.propertyDidChange("headers");
return this;}}else{if(value===undefined){headers=key;this.beginPropertyChanges();
for(key in headers){if(!headers.hasOwnProperty(key)){continue;}this.header(key,headers[key]);
}this.endPropertyChanges();return this;}}return this;},json:function(flag){if(flag===undefined){flag=YES;
}if(flag){this.set("isXML",NO);}return this.set("isJSON",flag);},xml:function(flag){if(flag===undefined){flag=YES;
}if(flag){this.set("isJSON",NO);}return this.set("isXML",flag);},_prep:function(){var hasContentType=!!this.header("Content-Type");
if(this.get("isJSON")&&!hasContentType){this.header("Content-Type","application/json");
}else{if(this.get("isXML")&&!hasContentType){this.header("Content-Type","text/xml");
}}return this;},send:function(body){if(body){this.set("body",body);}return SC.Request.manager.sendRequest(this.copy()._prep());
},resend:function(){var req=this.get("source")?this:this.copy()._prep();return SC.Request.manager.sendRequest(req);
},notify:function(status,target,action,params){var hasStatus=YES,params;if(SC.typeOf(status)!==SC.T_NUMBER){params=SC.A(arguments).slice(2);
action=target;target=status;status=0;hasStatus=NO;}else{params=SC.A(arguments).slice(3);
}var listeners=this.get("listeners");if(!listeners){this.set("listeners",listeners={});
}listeners[status]={target:target,action:action,params:params};return this;}});SC.Request.mixin({getUrl:function(address){return this.create().set("address",address).set("type","GET");
},postUrl:function(address,body){var req=this.create().set("address",address).set("type","POST");
if(body){req.set("body",body);}return req;},deleteUrl:function(address){return this.create().set("address",address).set("type","DELETE");
},putUrl:function(address,body){var req=this.create().set("address",address).set("type","PUT");
if(body){req.set("body",body);}return req;}});SC.Request.manager=SC.Object.create(SC.DelegateSupport,{maxRequests:6,inflight:[],pending:[],sendRequest:function(request){if(!request){return null;
}var response=request.get("responseClass").create({request:request});this.get("pending").pushObject(response);
this.fireRequestIfNeeded();return response;},cancel:function(response){var pending=this.get("pending"),inflight=this.get("inflight"),idx;
if(pending.indexOf(response)>=0){this.propertyWillChange("pending");pending.removeObject(response);
this.propertyDidChange("pending");return YES;}else{if(inflight.indexOf(response)>=0){response.cancel();
inflight.removeObject(response);this.fireRequestIfNeeded();return YES;}else{return NO;
}}},cancelAll:function(){if(this.get("pending").length||this.get("inflight").length){this.set("pending",[]);
this.get("inflight").forEach(function(r){r.cancel();});this.set("inflight",[]);return YES;
}else{return NO;}},fireRequestIfNeeded:function(){var pending=this.get("pending"),inflight=this.get("inflight"),max=this.get("maxRequests"),next;
if((pending.length>0)&&(inflight.length<max)){next=pending.shiftObject();inflight.pushObject(next);
next.fire();}},transportDidClose:function(response){this.get("inflight").removeObject(response);
this.fireRequestIfNeeded();}});sc_require("system/ready");SC.RootResponder=SC.Object.extend({panes:null,init:function(){arguments.callee.base.apply(this,arguments);
this.panes=SC.Set.create();},mainPane:null,makeMainPane:function(pane){var currentMain=this.get("mainPane");
if(currentMain===pane){return this;}this.beginPropertyChanges();if(this.get("keyPane")===currentMain){this.makeKeyPane(pane);
}this.set("mainPane",pane);if(currentMain){currentMain.blurMainTo(pane);}if(pane){pane.focusMainFrom(currentMain);
}this.endPropertyChanges();return this;},keyPane:null,previousKeyPanes:[],makeKeyPane:function(pane){var newKeyPane,previousKeyPane,previousKeyPanes;
if(pane){if(!pane.get("acceptsKeyPane")){return this;}else{previousKeyPane=this.get("keyPane");
if(previousKeyPane===pane){return this;}else{if(previousKeyPane){previousKeyPanes=this.get("previousKeyPanes");
previousKeyPanes.push(previousKeyPane);}newKeyPane=pane;}}}else{previousKeyPane=this.get("keyPane");
previousKeyPanes=this.get("previousKeyPanes");newKeyPane=null;while(previousKeyPanes.length>0){var candidate=previousKeyPanes.pop();
if(candidate.get("isPaneAttached")&&candidate.get("acceptsKeyPane")){newKeyPane=candidate;
break;}}}if(!newKeyPane){var mainPane=this.get("mainPane");if(mainPane&&mainPane.get("acceptsKeyPane")){newKeyPane=mainPane;
}}if(previousKeyPane){previousKeyPane.willLoseKeyPaneTo(newKeyPane);}if(newKeyPane){newKeyPane.willBecomeKeyPaneFrom(previousKeyPane);
}this.set("keyPane",newKeyPane);if(newKeyPane){newKeyPane.didBecomeKeyPaneFrom(previousKeyPane);
}if(previousKeyPane){previousKeyPane.didLoseKeyPaneTo(newKeyPane);}return this;},computeWindowSize:function(){return{width:640,height:480};
},defaultResponder:null,sendAction:function(action,target,sender,pane,context){target=this.targetForAction(action,target,sender,pane);
if(target&&target.isResponderContext){return !!target.sendAction(action,sender,context);
}else{return target&&target.tryToPerform(action,sender);}},_responderFor:function(target,methodName){var defaultResponder=target?target.get("defaultResponder"):null;
if(target){target=target.get("firstResponder")||target;do{if(target.respondsTo(methodName)){return target;
}}while(target=target.get("nextResponder"));}if(typeof defaultResponder===SC.T_STRING){defaultResponder=SC.objectForPropertyPath(defaultResponder);
}if(!defaultResponder){return null;}else{if(defaultResponder.isResponderContext){return defaultResponder;
}else{if(defaultResponder.respondsTo(methodName)){return defaultResponder;}else{return null;
}}}},targetForAction:function(methodName,target,sender,pane){if(!methodName||(SC.typeOf(methodName)!==SC.T_STRING)){return null;
}if(target){if(SC.typeOf(target)===SC.T_STRING){target=SC.objectForPropertyPath(target);
}if(target){if(target.respondsTo&&!target.respondsTo(methodName)){target=null;}else{if(SC.typeOf(target[methodName])!==SC.T_FUNCTION){target=null;
}}}return target;}if(pane){return this._responderFor(pane,methodName);}var keyPane=this.get("keyPane"),mainPane=this.get("mainPane");
if(keyPane&&(keyPane!==pane)){target=this._responderFor(keyPane,methodName);}if(!target&&mainPane&&(mainPane!==keyPane)){target=this._responderFor(mainPane,methodName);
}if(!target&&(target=this.get("defaultResponder"))){if(SC.typeOf(target)===SC.T_STRING){target=SC.objectForPropertyPath(target);
if(target){this.set("defaultResponder",target);}}if(target){if(target.respondsTo&&!target.respondsTo(methodName)){target=null;
}else{if(SC.typeOf(target[methodName])!==SC.T_FUNCTION){target=null;}}}}return target;
},targetViewForEvent:function(evt){return evt.target?SC.$(evt.target).view()[0]:null;
},sendEvent:function(action,evt,target){var pane,ret;SC.RunLoop.begin();if(target){pane=target.get("pane");
}else{pane=this.get("keyPane")||this.get("mainPane");}ret=(pane)?pane.sendEvent(action,evt,target):null;
SC.RunLoop.end();return ret;},listenFor:function(keyNames,target){keyNames.forEach(function(keyName){var method=this[keyName];
if(method){SC.Event.add(target,keyName,this,method);}},this);target=null;return this;
},setup:function(){}});SC.ready(SC.RootResponder,SC.RootResponder.ready=function(){var r;
r=SC.RootResponder.responder=SC.RootResponder.create();r.setup();});SC.routes=SC.Object.create({location:function(key,value){if(value!==undefined){if(value===null){value="";
}if(typeof(value)=="object"){var parts=value.route?value.route.split("&"):[""];var route=parts.shift();
var params={};parts.forEach(function(p){var bits=p.split("=");params[bits[0]]=bits[1];
});for(key in value){if(!value.hasOwnProperty(key)){continue;}if(key!="route"){params[key]=encodeURIComponent(""+value[key]);
}}parts=[route];for(key in params){if(!params.hasOwnProperty(key)){continue;}parts.push([key,params[key]].join("="));
}value=parts.join("&");}if(this._location!=value){this._location=value;this._setWindowLocation(value);
}}return this._location;}.property(),ping:function(){if(!this._didSetupHistory){this._didSetupHistory=true;
this._setupHistory();}this._checkWindowLocation();},add:function(route,target,method){if(method===undefined&&SC.typeOf(target)===SC.T_FUNCTION){method=target;
target=null;}else{if(SC.typeOf(method)===SC.T_STRING){method=target[method];}}var parts=route.split("/");
if(!this._routes){this._routes=SC.routes._Route.create();}this._routes.addRoute(parts,target,method);
return this;},gotoRoute:function(route){var params={},parts,routeHandler,target,method;
this._lastRoute=route;parts=route.split("&");if(parts&&parts.length>0){route=parts.shift();
parts.forEach(function(part){var param=part.split("=");if(param&&param.length>1){params[param[0]]=decodeURIComponent(param[1]);
}});}else{route="";}parts=route.split("/");if(!this._routes){this._routes=SC.routes._Route.create();
}routeHandler=this._routes.functionForRoute(parts,params);if(routeHandler){target=routeHandler._target;
method=routeHandler._method;if(method){method.call(target,params);}}},init:function(){arguments.callee.base.call(this);
if(SC.browser.isSafari&&parseInt(SC.browser.version,0)<417){SC.mixin(this,this.browserFuncs.safari);
}else{if(SC.browser.isIE){SC.mixin(this,this.browserFuncs.ie);}else{if(SC.browser.isMozilla){SC.mixin(this,this.browserFuncs.firefox);
}}}this._didSetupHistory=false;},invokeCheckWindowLocation:function(after){var f=this.__checkWindowLocation,that=this;
if(!f){f=this.__checkWindowLocation=function(){that._checkWindowLocation();};}setTimeout(f,after);
},browserFuncs:{safari:{_setupHistory:function(){var cloc=location.hash;cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";
this._cloc=cloc;this._backStack=[];this._backStack.length=history.length;this._backStack.push(cloc);
this._forwardStack=[];this.invokeCheckWindowLocation(1000);},_checkWindowLocation:function(){var historyDidChange=(history.length-this._lastLength)!==0;
var delta=(historyDidChange)?(history.length-this._backStack.length):0;this._lastLength=history.length;
if(historyDidChange){console.log("historyDidChange");}if(delta){if(delta<0){this._forwardStack.push(this._cloc);
for(var i=0;i<Math.abs(delta+1);i++){this._forwardStack.push(this._backStack.pop());
}this._cloc=this._backStack.pop();}else{this._backStack.push(this._cloc);for(i=0;
i<(delta-1);i++){this._backStack.push(this._forwardStack.pop());}this._cloc=this._forwardStack.pop();
}}else{if(historyDidChange&&this._locationDidChange){this.gotoRoute(this._cloc);this._locationDidChange=false;
}}var cloc=this._cloc;var loc=this.get("location");if(cloc!=loc){this.set("location",(cloc)?cloc:"");
this.gotoRoute(cloc);}this.invokeCheckWindowLocation(50);},_setWindowLocation:function(loc){var cloc=this._cloc;
if(cloc!=loc){this._backStack.push(this._cloc);this._forwardStack.length=0;this._cloc=loc;
location.hash=(loc&&loc.length>0)?loc:"";this._locationDidChange=true;}}},ie:{_setupHistory:function(){this.invokeCheckWindowLocation(1000);
},_checkWindowLocation:function(){var loc=this.get("location");var cloc=location.hash;
cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";if(cloc!=loc){this.set("location",(cloc)?cloc:"");
}this.invokeCheckWindowLocation(100);},_setWindowLocation:function(loc){var cloc=location.hash;
cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";if(cloc!=loc){location.hash=(loc&&loc.length>0)?loc:"#";
}this.gotoRoute(loc);}},firefox:{_checkWindowLocation:function(){var loc=this.get("location");
var cloc=location.hash;cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";if(cloc!=loc){SC.RunLoop.begin();
this.set("location",(cloc)?cloc:"");SC.RunLoop.end();}this.invokeCheckWindowLocation(150);
},_setWindowLocation:function(loc){var cloc=location.hash;cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";
if(cloc!=loc){location.hash=(loc&&loc.length>0)?loc:"#";}this.gotoRoute(loc);}}},_setupHistory:function(){var that=this;
this.invokeCheckWindowLocation(1000);},_checkWindowLocation:function(){var loc=this.get("location");
var cloc=decodeURI(location.hash);cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";
if(cloc!==loc){SC.RunLoop.begin();this.set("location",(cloc)?cloc:"");SC.RunLoop.end();
}this.invokeCheckWindowLocation(150);},_setWindowLocation:function(loc){var cloc=location.hash;
cloc=(cloc&&cloc.length>0)?cloc.slice(1,cloc.length):"";if(cloc!=loc){location.hash=(loc&&loc.length>0)?encodeURI(loc):"#";
}this.gotoRoute(loc);},_routes:null,_Route:SC.Object.extend({_target:null,_method:null,_static:null,_dynamic:null,_wildcard:null,addRoute:function(parts,target,method){if(!parts||parts.length===0){this._target=target;
this._method=method;}else{var part=parts.shift();var nextRoute=null;switch(part.slice(0,1)){case":":part=part.slice(1,part.length);
var routes=this._dynamic[part]||[];nextRoute=SC.routes._Route.create();routes.push(nextRoute);
this._dynamic[part]=routes;break;case"*":part=part.slice(1,part.length);this._wildcard=part;
this._target=target;this._method=method;break;default:routes=this._static[part]||[];
nextRoute=SC.routes._Route.create();routes.push(nextRoute);this._static[part]=routes;
}if(nextRoute){nextRoute.addRoute(parts,target,method);}}},functionForRoute:function(parts,params){if(!parts||parts.length===0){return this;
}else{var part=parts.shift(),ret=null,routes,nextRoute,loc,routesLen;routes=this._static[part];
if(routes){for(loc=0,routesLen=routes.length;(loc<routesLen)&&(ret===null);loc++){var clone=parts.slice();
ret=routes[loc].functionForRoute(clone,params);}}if(ret===null){for(var key in this._dynamic){routes=this._dynamic[key];
if(routes){for(loc=0,routesLen=routes.length;(loc<routesLen)&&(ret===null);loc++){clone=parts.slice();
ret=routes[loc].functionForRoute(clone,params);if(ret&&params){params[key]=part;}}}if(ret){break;
}}}if((ret===null)&&this._wildcard){parts.unshift(part);if(params){params[this._wildcard]=parts.join("/");
}ret=this;}return ret;}},init:function(){arguments.callee.base.call(this);this._static={};
this._dynamic={};}})});SC.TextSelection=SC.Object.extend(SC.Copyable,SC.Freezable,{start:-1,end:-1,length:function(){var start=this.get("start");
var end=this.get("end");if((start)===-1||(end===-1)){return -1;}else{return end-start;
}}.property("start","end").cacheable(),init:function(){arguments.callee.base.apply(this,arguments);
this.freeze();},copy:function(){return SC.TextSelection.create({start:this.get("start"),end:this.get("end")});
},toString:function(){var length=this.get("length");if(length&&length>0){if(length===1){return"[%@ character selected: {%@, %@}]".fmt(length,this.get("start"),this.get("end"));
}else{return"[%@ characters selected: {%@, %@}]".fmt(length,this.get("start"),this.get("end"));
}}else{return"[no text selected; caret at %@]".fmt(this.get("start"));}}});SC.time=function(timeoffset){var ret=SC.beget(fn);
ret.value=timeOffset;return ret;};(function(){var date=new Date();SC.mixin(SC.time,{month:function(offset,newMonth){date.setTime(offset);
if(newMonth===undefined){return date.getMonth();}date.setMonth(newMonth);return date.getTime();
},utc:function(offset){date.setTime(offset);return offset+(date.getTimezoneOffset()*60*1000);
},local:function(offset){date.setTime(offset);return offset-(date.getTimezoneOffset()*60*1000);
},parse:function(string){},format:function(offset){}});})();SC.time.fmt=SC.time.format;
SC.time.fn={done:function(){return this.value;}};"month day year".split(" ").forEach(function(key){SC.time.fn[key]=function(newTime){if(newTime===undefined){return SC.time[key](this.value);
}else{this.value=SC.time[key](this.value,newTime);return this;}};});var MONTH_NAMES=new Array("January","February","March","April","May","June","July","August","September","October","November","December","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var DAY_NAMES=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sun","Mon","Tue","Wed","Thu","Fri","Sat");
function LZ(x){return(x<0||x>9?"":"0")+x;}SC.Locale.define("en",{longMonthNames:"January February March April May".split(" "),shortMonthNames:[],shortDateFormat:"dd/mm/yy",longDateFormat:""});
SC.mixin(Date,{now:function(){return new Date().getTime();},isDate:function(val,format){var date=Date.getDateFromFormat(val,format);
if(date==0){return false;}return true;},compareDates:function(date1,dateformat1,date2,dateformat2){var d1=Date.getDateFromFormat(date1,dateformat1);
var d2=Date.getDateFromFormat(date2,dateformat2);if(d1==0||d2==0){return -1;}else{if(d1>d2){return 1;
}}return 0;},getDateFromFormat:function(val,format){val=val+"";format=format+"";var i_val=0;
var i_format=0;var c="";var token="";var token2="";var x,y;var now=new Date();var year=now.getFullYear();
var month=now.getMonth()+1;var date=1;var hh=now.getHours();var mm=now.getMinutes();
var ss=now.getSeconds();var ampm="";var locale=SC.Locale.currentLocale;while(i_format<format.length){c=format.charAt(i_format);
token="";while((format.charAt(i_format)==c)&&(i_format<format.length)){token+=format.charAt(i_format++);
}if(token=="yyyy"||token=="yy"||token=="y"){if(token=="yyyy"){x=4;y=4;}if(token=="yy"){x=2;
y=2;}if(token=="y"){x=2;y=4;}year=Date._getInt(val,i_val,x,y);if(year==null){return 0;
}i_val+=year.length;if(year.length==2){if(year>70){year=1900+(year-0);}else{year=2000+(year-0);
}}}else{if(token=="MMM"||token=="NNN"){month=0;for(var i=0;i<MONTH_NAMES.length;i++){var month_name=MONTH_NAMES[i];
if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){if(token=="MMM"||(token=="NNN"&&i>11)){month=i+1;
if(month>12){month-=12;}i_val+=month_name.length;break;}}}if((month<1)||(month>12)){return 0;
}}else{if(token=="EE"||token=="E"){for(var i=0;i<DAY_NAMES.length;i++){var day_name=DAY_NAMES[i];
if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){i_val+=day_name.length;
break;}}}else{if(token=="MM"||token=="M"){month=Date._getInt(val,i_val,token.length,2);
if(month==null||(month<1)||(month>12)){return 0;}i_val+=month.length;}else{if(token=="dd"||token=="d"){date=Date._getInt(val,i_val,token.length,2);
if(date==null||(date<1)||(date>31)){return 0;}i_val+=date.length;}else{if(token=="hh"||token=="h"){hh=Date._getInt(val,i_val,token.length,2);
if(hh==null||(hh<1)||(hh>12)){return 0;}i_val+=hh.length;}else{if(token=="HH"||token=="H"){hh=Date._getInt(val,i_val,token.length,2);
if(hh==null||(hh<0)||(hh>23)){return 0;}i_val+=hh.length;}else{if(token=="KK"||token=="K"){hh=Date._getInt(val,i_val,token.length,2);
if(hh==null||(hh<0)||(hh>11)){return 0;}i_val+=hh.length;}else{if(token=="kk"||token=="k"){hh=Date._getInt(val,i_val,token.length,2);
if(hh==null||(hh<1)||(hh>24)){return 0;}i_val+=hh.length;hh--;}else{if(token=="mm"||token=="m"){mm=Date._getInt(val,i_val,token.length,2);
if(mm==null||(mm<0)||(mm>59)){return 0;}i_val+=mm.length;}else{if(token=="ss"||token=="s"){ss=Date._getInt(val,i_val,token.length,2);
if(ss==null||(ss<0)||(ss>59)){return 0;}i_val+=ss.length;}else{if(token=="a"){if(val.substring(i_val,i_val+2).toLowerCase()=="am"){ampm="AM";
}else{if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){ampm="PM";}else{return 0;
}}i_val+=2;}else{if(val.substring(i_val,i_val+token.length)!=token){return 0;}else{i_val+=token.length;
}}}}}}}}}}}}}}if(i_val!=val.length){return 0;}if(month==2){if(((year%4==0)&&(year%100!=0))||(year%400==0)){if(date>29){return 0;
}}else{if(date>28){return 0;}}}if((month==4)||(month==6)||(month==9)||(month==11)){if(date>30){return 0;
}}if(hh<12&&ampm=="PM"){hh=hh-0+12;}else{if(hh>11&&ampm=="AM"){hh-=12;}}var newdate=new Date(year,month-1,date,hh,mm,ss);
return newdate.getTime();},parseDate:function(val){var preferEuro=(arguments.length==2)?arguments[1]:false;
generalFormats=new Array("E NNN dd HH:mm:ss UTC yyyy","y-M-d","y-M-d","MMM d, y","MMM d,y","y-MMM-d","d-MMM-y","MMM d","d MMM y","d.MMM.y","y MMM d","y.MMM.d");
monthFirst=new Array("M/d/y","M-d-y","M.d.y","MMM-d","M/d","M-d");dateFirst=new Array("d/M/y","d-M-y","d.M.y","d-MMM","d/M","d-M");
var checkList=new Array("generalFormats",preferEuro?"dateFirst":"monthFirst",preferEuro?"monthFirst":"dateFirst");
var d=null;d=0;var now=new Date().getTime();switch(val.toLowerCase()){case"yesterday".loc():d=now-(24*60*60*1000);
break;case"today".loc():case"now".loc():d=now;break;case"tomorrow".loc():d=now+(24*60*60*1000);
break;}if(d>0){return new Date(d);}for(var i=0;i<checkList.length;i++){var l=window[checkList[i]];
for(var j=0;j<l.length;j++){d=Date.getDateFromFormat(val,l[j]);if(d==0){d=Date.getDateFromFormat(val,l[j]+" H:m:s");
}if(d==0){d=Date.getDateFromFormat(val,l[j]+" h:m:s a");}if(d!=0){return new Date(d);
}}}return null;},_isInteger:function(val){var digits="1234567890";for(var i=0;i<val.length;
i++){if(digits.indexOf(val.charAt(i))==-1){return false;}}return true;},_getInt:function(str,i,minlength,maxlength){for(var x=maxlength;
x>=minlength;x--){var token=str.substring(i,i+x);if(token.length<minlength){return null;
}if(Date._isInteger(token)){return token;}}return null;}});SC.mixin(Date.prototype,{format:function(format){format=format+"";
var date=this;var result="";var i_format=0;var c="";var token="";var y=date.getFullYear()+"";
var M=date.getMonth()+1;var d=date.getDate();var E=date.getDay();var H=date.getHours();
var m=date.getMinutes();var s=date.getSeconds();var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
var value=new Object();if(y.length<4){y=""+(y-0+1900);}value["y"]=""+y;value["yyyy"]=y;
value["yy"]=y.substring(2,4);value["M"]=M;value["MM"]=LZ(M);value["MMM"]=MONTH_NAMES[M-1];
value["NNN"]=MONTH_NAMES[M+11];value["d"]=d;value["dd"]=LZ(d);value["E"]=DAY_NAMES[E+7];
value["EE"]=DAY_NAMES[E];value["H"]=H;value["HH"]=LZ(H);if(H==0){value["h"]=12;}else{if(H>12){value["h"]=H-12;
}else{value["h"]=H;}}value["hh"]=LZ(value["h"]);if(H>11){value["K"]=H-12;}else{value["K"]=H;
}value["k"]=H+1;value["KK"]=LZ(value["K"]);value["kk"]=LZ(value["k"]);if(H>11){value["a"]="PM";
}else{value["a"]="AM";}value["m"]=m;value["mm"]=LZ(m);value["s"]=s;value["ss"]=LZ(s);
while(i_format<format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c)&&(i_format<format.length)){token+=format.charAt(i_format++);
}if(value[token]!=null){result=result+value[token];}else{result=result+token;}}return result;
},utcFormat:function(){return(new Date(this.getTime()+(this.getTimezoneOffset()*60*1000))).format("E NNN dd HH:mm:ss UTC yyyy");
}});SC.Timer=SC.Object.extend({target:null,action:null,isPooled:NO,interval:0,startTime:null,repeats:NO,until:null,isPaused:NO,isScheduled:NO,isValid:YES,lastFireTime:0,fireTime:function(){if(!this.get("isValid")){return -1;
}var start=this.get("startTime");if(!start||start===0){return -1;}var interval=this.get("interval"),last=this.get("lastFireTime");
if(last<start){last=start;}var next;if(this.get("repeats")){if(interval===0){next=last;
}else{next=start+(Math.floor((last-start)/interval)+1)*interval;}}else{next=start+interval;
}var until=this.get("until");if(until&&until>0&&next>until){next=until;}return next;
}.property("interval","startTime","repeats","until","isValid","lastFireTime").cacheable(),schedule:function(){if(!this.get("isValid")){return this;
}this.beginPropertyChanges();if(!this.startTime){this.set("startTime",SC.RunLoop.currentRunLoop.get("startTime"));
}var next=this.get("fireTime"),last=this.get("lastFireTime");if(next>=last){this.set("isScheduled",YES);
SC.RunLoop.currentRunLoop.scheduleTimer(this,next);}this.endPropertyChanges();return this;
},invalidate:function(){this.beginPropertyChanges();this.set("isValid",NO);SC.RunLoop.currentRunLoop.cancelTimer(this);
this.action=this.target=null;this.endPropertyChanges();if(this.get("isPooled")){SC.Timer.returnTimerToPool(this);
}return this;},fire:function(){var last=Date.now();this.set("lastFireTime",last);
var next=this.get("fireTime");if(!this.get("isPaused")){this.performAction();}if(next>last){this.schedule();
}else{this.invalidate();}},performAction:function(){var typeOfAction=SC.typeOf(this.action);
if(typeOfAction==SC.T_FUNCTION){this.action.call((this.target||this),this);}else{if(typeOfAction===SC.T_STRING){if(this.action.indexOf(".")>=0){var path=this.action.split(".");
var property=path.pop();var target=SC.objectForPropertyPath(path,window);var action=target.get?target.get(property):target[property];
if(action&&SC.typeOf(action)==SC.T_FUNCTION){action.call(target,this);}else{throw"%@: Timer could not find a function at %@".fmt(this,this.action);
}}else{SC.RootResponder.responder.sendAction(this.action,this.target,this);}}}},init:function(){arguments.callee.base.apply(this,arguments);
if(this.startTime instanceof Date){this.startTime=this.startTime.getTime();}if(this.until instanceof Date){this.until=this.until.getTime();
}},RESET_DEFAULTS:{target:null,action:null,isPooled:NO,isPaused:NO,isScheduled:NO,isValid:YES,interval:0,repeats:NO,until:null,startTime:null,lastFireTime:0},reset:function(props){if(!props){props=SC.EMPTY_HASH;
}this.propertyWillChange("fireTime");var defaults=this.RESET_DEFAULTS;for(var key in defaults){if(!defaults.hasOwnProperty(key)){continue;
}this[key]=SC.none(props[key])?defaults[key]:props[key];}this.propertyDidChange("fireTime");
return this;},removeFromTimerQueue:function(timerQueueRoot){var prev=this._timerQueuePrevious,next=this._timerQueueNext;
if(!prev&&!next&&timerQueueRoot!==this){return timerQueueRoot;}if(prev){prev._timerQueueNext=next;
}if(next){next._timerQueuePrevious=prev;}this._timerQueuePrevious=this._timerQueueNext=null;
return(timerQueueRoot===this)?next:timerQueueRoot;},scheduleInTimerQueue:function(timerQueueRoot,runTime){this._timerQueueRunTime=runTime;
var beforeNode=timerQueueRoot;var afterNode=null;while(beforeNode&&beforeNode._timerQueueRunTime<runTime){afterNode=beforeNode;
beforeNode=beforeNode._timerQueueNext;}if(afterNode){afterNode._timerQueueNext=this;
this._timerQueuePrevious=afterNode;}if(beforeNode){beforeNode._timerQueuePrevious=this;
this._timerQueueNext=beforeNode;}return(beforeNode===timerQueueRoot)?this:timerQueueRoot;
},collectExpiredTimers:function(timers,now){if(this._timerQueueRunTime>now){return this;
}timers.push(this);var next=this._timerQueueNext;this._timerQueueNext=null;if(next){next._timerQueuePrevious=null;
}return next?next.collectExpiredTimers(timers,now):null;}});SC.Timer.schedule=function(props){var timer;
if(!props||SC.none(props.isPooled)||props.isPooled){timer=this.timerFromPool(props);
}else{timer=this.create(props);}return timer.schedule();};SC.Timer.timerFromPool=function(props){var timers=this._timerPool;
if(!timers){timers=this._timerPool=[];}var timer=timers.pop();if(!timer){timer=this.create();
}return timer.reset(props);};SC.Timer.returnTimerToPool=function(timer){if(!this._timerPool){this._timerPool=[];
}this._timerPool.push(timer);return this;};SC.UserDefaults=SC.Object.extend({userDomain:null,appDomain:null,_defaults:null,defaults:function(newDefaults){this._defaults=newDefaults;
this.allPropertiesDidChange();},readDefault:function(keyName){var ret=undefined;keyName=this._normalizeKeyName(keyName);
var userKeyName=this._userKeyName(keyName);if(this._written){ret=this._written[userKeyName];
}var localStorage=window.localStorage;if(!localStorage&&window.globalStorage){localStorage=window.globalStorage[window.location.hostname];
}if(localStorage){ret=localStorage[["SC.UserDefaults",userKeyName].join("@")];if(!SC.none(ret)){try{ret=SC.json.decode(ret);
}catch(e){ret=undefined;}}else{ret=undefined;}}var del=this.delegate;if(del&&del.userDefaultsNeedsDefault){ret=del.userDefaultsNeedsDefault(this,keyName,userKeyName);
}if((ret===undefined)&&this._defaults){ret=this._defaults[userKeyName]||this._defaults[keyName];
}return ret;},writeDefault:function(keyName,value){keyName=this._normalizeKeyName(keyName);
var userKeyName=this._userKeyName(keyName);var written=this._written;if(!written){written=this._written={};
}written[userKeyName]=value;var localStorage=window.localStorage;if(!localStorage&&window.globalStorage){localStorage=window.globalStorage[window.location.hostname];
}if(localStorage){localStorage[["SC.UserDefaults",userKeyName].join("@")]=SC.json.encode(value);
}var del=this.delegate;if(del&&del.userDefaultsDidChange){del.userDefaultsDidChange(this,keyName,value,userKeyName);
}return this;},resetDefault:function(keyName){var fullKeyName=this._normalizeKeyName(keyName);
var userKeyName=this._userKeyName(fullKeyName);this.propertyWillChange(keyName);this.propertyWillChange(fullKeyName);
var written=this._written;if(written){delete written[userKeyName];}var localStorage=window.localStorage;
if(!localStorage&&window.globalStorage){localStorage=window.globalStorage[window.location.hostname];
}if(localStorage){delete localStorage[["SC.UserDefaults",userKeyName].join("@")];
}this.propertyDidChange(keyName);this.propertyDidChange(fullKeyName);return this;
},unknownProperty:function(key,value){if(value===undefined){return this.readDefault(key);
}else{this.writeDefault(key,value);return value;}},_normalizeKeyName:function(keyName){if(keyName.indexOf(":")<0){var domain=this.get("appDomain")||"app";
keyName=[domain,keyName].join(":");}return keyName;},_userKeyName:function(keyName){var user=this.get("userDomain")||"(anonymous)";
return[user,keyName].join("@");},_domainDidChange:function(){var didChange=NO;if(this.get("userDomain")!==this._scud_userDomain){this._scud_userDomain=this.get("userDomain");
didChange=YES;}if(this.get("appDomain")!==this._scud_appDomain){this._scud_appDomain=this.get("appDomain");
didChange=YES;}if(didChange){this.allPropertiesDidChange();}}.observes("userDomain","appDomain"),init:function(){arguments.callee.base.apply(this,arguments);
this._scud_userDomain=this.get("userDomain");this._scud_appDomain=this.get("appDomain");
}});SC.userDefaults=SC.UserDefaults.create();sc_require("system/browser");SC.mixin({_downloadFrames:0,_copy_computed_props:["maxWidth","maxHeight","paddingLeft","paddingRight","paddingTop","paddingBottom","fontFamily","fontSize","fontStyle","fontWeight","fontVariant","lineHeight","whiteSpace"],download:function(path){var tempDLIFrame=document.createElement("iframe");
var frameId="DownloadFrame_"+this._downloadFrames;SC.$(tempDLIFrame).attr("id",frameId);
tempDLIFrame.style.border="10px";tempDLIFrame.style.width="0px";tempDLIFrame.style.height="0px";
tempDLIFrame.style.position="absolute";tempDLIFrame.style.top="-10000px";tempDLIFrame.style.left="-10000px";
if(!SC.browser.isSafari){SC.$(tempDLIFrame).attr("src",path);}document.getElementsByTagName("body")[0].appendChild(tempDLIFrame);
if(SC.browser.isSafari){SC.$(tempDLIFrame).attr("src",path);}this._downloadFrames=this._downloadFrames+1;
if(!SC.browser.isSafari){var r=function(){document.body.removeChild(document.getElementById(frameId));
frameId=null;};var t=r.invokeLater(null,2000);}tempDLIFrame=null;},normalizeURL:function(url){if(url.slice(0,1)=="/"){url=window.location.protocol+"//"+window.location.host+url;
}else{if((url.slice(0,5)=="http:")||(url.slice(0,6)=="https:")){}else{url=window.location.href+"/"+url;
}}return url;},minX:function(frame){return frame.x||0;},maxX:function(frame){return(frame.x||0)+(frame.width||0);
},midX:function(frame){return(frame.x||0)+((frame.width||0)/2);},minY:function(frame){return frame.y||0;
},maxY:function(frame){return(frame.y||0)+(frame.height||0);},midY:function(frame){return(frame.y||0)+((frame.height||0)/2);
},centerX:function(innerFrame,outerFrame){return(outerFrame.width-innerFrame.width)/2;
},centerY:function(innerFrame,outerFrame){return(outerFrame.height-innerFrame.height)/2;
},pointInRect:function(point,f){return(point.x>=SC.minX(f))&&(point.y>=SC.minY(f))&&(point.x<=SC.maxX(f))&&(point.y<=SC.maxY(f));
},rectsEqual:function(r1,r2,delta){if(!r1||!r2){return(r1==r2);}if(!delta&&delta!==0){delta=0.1;
}if((r1.y!=r2.y)&&(Math.abs(r1.y-r2.y)>delta)){return NO;}if((r1.x!=r2.x)&&(Math.abs(r1.x-r2.x)>delta)){return NO;
}if((r1.width!=r2.width)&&(Math.abs(r1.width-r2.width)>delta)){return NO;}if((r1.height!=r2.height)&&(Math.abs(r1.height-r2.height)>delta)){return NO;
}return YES;},intersectRects:function(r1,r2){var ret={x:Math.max(SC.minX(r1),SC.minX(r2)),y:Math.max(SC.minY(r1),SC.minY(r2)),width:Math.min(SC.maxX(r1),SC.maxX(r2)),height:Math.min(SC.maxY(r1),SC.maxY(r2))};
ret.width=Math.max(0,ret.width-ret.x);ret.height=Math.max(0,ret.height-ret.y);return ret;
},unionRects:function(r1,r2){var ret={x:Math.min(SC.minX(r1),SC.minX(r2)),y:Math.min(SC.minY(r1),SC.minY(r2)),width:Math.max(SC.maxX(r1),SC.maxX(r2)),height:Math.max(SC.maxY(r1),SC.maxX(r2))};
ret.width=Math.max(0,ret.width-ret.x);ret.height=Math.max(0,ret.height-ret.y);return ret;
},cloneRect:function(r){return{x:r.x,y:r.y,width:r.width,height:r.height};},stringFromRect:function(r){return"{%@, %@, %@, %@}".fmt(r.x,r.y,r.width,r.height);
},stringFromLayout:function(layout){var keys=["maxHeight","maxWidth","minHeight","minWidth","centerY","centerX","width","height","bottom","right","top","left"];
var keyValues=[];var i=keys.length;while(--i>=0){var key=keys[i];if(layout.hasOwnProperty(key)){keyValues.push(key+":"+layout[key]);
}}return"{"+keyValues.join(", ")+"}";},heightForString:function(str,width,style,classNames){var elem=this._heightCalcElement,classes,height;
classes=(classNames&&SC.typeOf(classNames)===SC.T_ARRAY)?classNames.join(" "):"";
if(!width){width=100;}if(!elem){elem=this._heightCalcElement=document.createElement("div");
document.body.insertBefore(elem,null);}style="%@; width: %@px; left: %@px; position: absolute".fmt(style,width,(-1*width));
SC.$(elem).attr("style",style);if(classes!==""){SC.$(elem).attr("class",classes);
}elem.innerHTML=str;height=elem.clientHeight;elem=null;return height;},metricsForString:function(string,exampleElement,classNames){var element=this._metricsCalculationElement,width,height,classes,styles,style;
classes=SC.A(classNames).join(" ");if(!element){element=this._metricsCalculationElement=document.createElement("div");
document.body.insertBefore(element,null);}if(SC.typeOf(exampleElement)!=SC.T_STRING){var computed=null;
if(document.defaultView&&document.defaultView.getComputedStyle){computed=document.defaultView.getComputedStyle(exampleElement,null);
}else{computed=exampleElement.currentStyle;}style=computed.cssText;if(!style||style.trim()===""){var props=this._copy_computed_props;
for(var i=0;i<props.length;i++){var prop=props[i],val=computed[prop];element.style[prop]=val;
}var cs=element.style;if(cs.font===""){var font="";if(cs.fontStyle){font+=cs.fontStyle+" ";
}if(cs.fontVariant){font+=cs.fontVariant+" ";}if(cs.fontWeight){font+=cs.fontWeight+" ";
}if(cs.fontSize){font+=cs.fontSize;}else{font+="10px";}if(cs.lineHeight){font+="/"+cs.lineHeight;
}font+=" ";if(cs.fontFamily){font+=cs.fontFamily;}else{cs+="sans-serif";}element.style.font=font;
}SC.mixin(element.style,{left:"0px",top:"0px",position:"absolute",bottom:"auto",right:"auto",width:"auto",height:"auto"});
}else{element.setAttribute("style",style+"; position:absolute; left: 0px; top: 0px; bottom: auto; right: auto; width: auto; height: auto;");
}computed=null;}else{style=exampleElement;element.setAttribute("style",style+"; position:absolute; left: 0px; top: 0px; bottom: auto; right: auto; width: auto; height: auto;");
}if(typeof element.innerText!="undefined"){element.innerText=string;}else{element.textContent=string;
}element.className=classes;var result={width:element.clientWidth,height:element.clientHeight};
element.innerHTML="";element.className="";element.setAttribute("style","");element=null;
return result;},viewportOffset:function(el){if(el.getBoundingClientRect){var boundingRect=el.getBoundingClientRect();
return{x:boundingRect.left,y:boundingRect.top};}var valueL=0;var valueT=0;var element=el;
var isFirefox3=SC.browser.mozilla>=3;while(element){valueT+=(element.offsetTop||0);
if(!isFirefox3||(element!==el)){valueT+=(element.clientTop||0);}valueL+=(element.offsetLeft||0);
if(!isFirefox3||(element!==el)){valueL+=(element.clientLeft||0);}if(SC.browser.mozilla){var overflow=SC.$(element).attr("overflow");
if(overflow!=="visible"){var left=parseInt(SC.$(element).attr("borderLeftWidth"),0)||0;
var top=parseInt(SC.$(element).attr("borderTopWidth"),0)||0;if(el!==element){left*=2;
top*=2;}valueL+=left;valueT+=top;}var offsetParent=element.offsetParent;if((SC.browser.mozilla>=3)&&offsetParent){valueT-=offsetParent.clientTop;
valueL-=offsetParent.clientLeft;}}if(element.offsetParent==document.body&&SC.$(element).attr("position")=="absolute"){break;
}element=element.offsetParent;}element=el;while(element){if(!SC.browser.isOpera||element.tagName=="BODY"){valueT-=element.scrollTop||0;
valueL-=element.scrollLeft||0;}element=element.parentNode;}return{x:valueL,y:valueT};
},ZERO_POINT:{x:0,y:0},ZERO_RANGE:{start:0,length:0},RANGE_NOT_FOUND:{start:0,length:-1},valueInRange:function(value,range){return(value>=0)&&(value>=range.start)&&(value<(range.start+range.length));
},minRange:function(range){return range.start;},maxRange:function(range){return(range.length<0)?-1:(range.start+range.length);
},unionRanges:function(r1,r2){if((r1==null)||(r1.length<0)){return r2;}if((r2==null)||(r2.length<0)){return r1;
}var min=Math.min(r1.start,r2.start);var max=Math.max(SC.maxRange(r1),SC.maxRange(r2));
return{start:min,length:max-min};},intersectRanges:function(r1,r2){if((r1==null)||(r2==null)){return SC.RANGE_NOT_FOUND;
}if((r1.length<0)||(r2.length<0)){return SC.RANGE_NOT_FOUND;}var min=Math.max(SC.minRange(r1),SC.minRange(r2));
var max=Math.min(SC.maxRange(r1),SC.maxRange(r2));if(max<min){return SC.RANGE_NOT_FOUND;
}return{start:min,length:max-min};},subtractRanges:function(r1,r2){if((r1==null)||(r2==null)){return SC.RANGE_NOT_FOUND;
}if((r1.length<0)||(r2.length<0)){return SC.RANGE_NOT_FOUND;}var max=Math.max(SC.minRange(r1),SC.minRange(r2));
var min=Math.min(SC.maxRange(r1),SC.maxRange(r2));if(max<min){return SC.RANGE_NOT_FOUND;
}return{start:min,length:max-min};},cloneRange:function(r){return{start:r.start,length:r.length};
},rangesEqual:function(r1,r2){if(r1===r2){return true;}if(r1==null){return r2.length<0;
}if(r2==null){return r1.length<0;}return(r1.start==r2.start)&&(r1.length==r2.length);
},convertHsvToHex:function(h,s,v){var r=0;var g=0;var b=0;if(v>0){var i=(h==1)?0:Math.floor(h*6);
var f=(h==1)?0:(h*6)-i;var p=v*(1-s);var q=v*(1-(s*f));var t=v*(1-(s*(1-f)));var rgb=[[v,t,p],[q,v,p],[p,v,t],[p,q,v],[t,p,v],[v,p,q]];
r=Math.round(255*rgb[i][0]);g=Math.round(255*rgb[i][1]);b=Math.round(255*rgb[i][2]);
}return this.parseColor("rgb("+r+","+g+","+b+")");},convertHexToHsv:function(hex){var rgb=this.expandColor(hex);
var max=Math.max(Math.max(rgb[0],rgb[1]),rgb[2]);var min=Math.min(Math.min(rgb[0],rgb[1]),rgb[2]);
var h=(max==min)?0:((max==rgb[0])?((rgb[1]-rgb[2])/(max-min)/6):((max==rgb[1])?((rgb[2]-rgb[0])/(max-min)/6+1/3):((rgb[0]-rgb[1])/(max-min)/6+2/3)));
h=(h<0)?(h+1):((h>1)?(h-1):h);var s=(max==0)?0:(1-min/max);var v=max/255;return[h,s,v];
},PARSE_COLOR_RGBRE:/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i,PARSE_COLOR_HEXRE:/^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,expandColor:function(color){var hexColor,red,green,blue;
hexColor=this.parseColor(color);if(hexColor){red=parseInt(hexColor.slice(1,3),16);
green=parseInt(hexColor.slice(3,5),16);blue=parseInt(hexColor.slice(5,7),16);return[red,green,blue];
}},parseColor:function(string){var i=0,color="#",match;if(match=this.PARSE_COLOR_RGBRE.exec(string)){var part;
for(i=1;i<=3;i++){part=Math.max(0,Math.min(255,parseInt(match[i],0)));color+=this.toColorPart(part);
}return color;}if(match=this.PARSE_COLOR_HEXRE.exec(string)){if(match[1].length==3){for(i=0;
i<3;i++){color+=match[1].charAt(i)+match[1].charAt(i);}return color;}return"#"+match[1];
}return false;},toColorPart:function(number){if(number>255){number=255;}var digits=number.toString(16);
if(number<16){return"0"+digits;}return digits;},getStyle:function(oElm,strCssRule){var strValue="";
if(document.defaultView&&document.defaultView.getComputedStyle){strValue=document.defaultView.getComputedStyle(oElm,"").getPropertyValue(strCssRule);
}else{if(oElm.currentStyle){strCssRule=strCssRule.replace(/\-(\w)/g,function(strMatch,p1){return p1.toUpperCase();
});strValue=oElm.currentStyle[strCssRule];}}return strValue;}});sc_require("views/view");
SC.ContainerView=SC.View.extend({classNames:["sc-container-view"],nowShowing:null,contentView:null,contentViewBindingDefault:SC.Binding.single(),replaceContent:function(newContent){this.removeAllChildren();
if(newContent){this.appendChild(newContent);}},createChildViews:function(){var view=this.get("contentView");
if(view){view=this.contentView=this.createChildView(view);this.childViews=[view];
}},awake:function(){arguments.callee.base.apply(this,arguments);var nowShowing=this.get("nowShowing");
if(nowShowing&&nowShowing.length>0){this.nowShowingDidChange();}},nowShowingDidChange:function(){var nowShowing=this.get("nowShowing");
var content=null;if(SC.typeOf(nowShowing)===SC.T_STRING){if(nowShowing===SC.CONTENT_SET_DIRECTLY){return;
}if(nowShowing&&nowShowing.length>0){if(nowShowing.indexOf(".")>0){content=SC.objectForPropertyPath(nowShowing,null);
}else{content=SC.objectForPropertyPath(nowShowing,this.get("page"));}}}else{content=nowShowing;
}if(content&&!(content instanceof SC.View)){content=null;}this.set("contentView",content);
}.observes("nowShowing"),contentViewDidChange:function(){this.replaceContent(this.get("contentView"));
}.observes("contentView")});sc_require("views/view");sc_require("mixins/control");
sc_require("mixins/validatable");SC.FieldView=SC.View.extend(SC.Control,SC.Validatable,{isTextArea:NO,followSafariTabFocusBehavior:NO,_field_isMouseDown:NO,fieldValue:function(){var value=this.get("value");
if(SC.typeOf(value)===SC.T_ERROR){value=value.get("value");}return this.fieldValueForObject(value);
}.property("value","validator").cacheable(),$input:function(){if(this.get("isTextArea")){return this.$("textarea").andSelf().filter("textarea");
}else{return this.$("input").andSelf().filter("input");}},setFieldValue:function(newValue){if(SC.none(newValue)){newValue="";
}var input=this.$input();if(input.val()!==newValue){input.val(newValue);}return this;
},getFieldValue:function(){return this.$input().val();},_field_fieldValueDidChange:function(evt){SC.RunLoop.begin();
this.fieldValueDidChange(NO);SC.RunLoop.end();},fieldValueDidChange:function(partialChange){var fieldValue=this.getFieldValue();
var value=this.objectForFieldValue(fieldValue,partialChange);this.setIfChanged("value",value);
},_field_valueDidChange:function(){this.setFieldValue(this.get("fieldValue"));}.observes("value"),didCreateLayer:function(){this.setFieldValue(this.get("fieldValue"));
SC.Event.add(this.$input(),"change",this,this._field_fieldValueDidChange);},willDestroyLayer:function(){SC.Event.remove(this.$input(),"change",this,this._field_fieldValueDidChange);
},updateLayer:function(){arguments.callee.base.apply(this,arguments);},mouseDown:function(evt){this._field_isMouseDown=YES;
evt.allowDefault();return YES;},mouseOut:function(evt){if(this._field_isMouseDown){this.set("isActive",NO);
}evt.allowDefault();return YES;},mouseOver:function(evt){this.set("isActive",this._field_isMouseDown);
evt.allowDefault();return YES;},mouseUp:function(evt){if(this._field_isMouseDown){this.set("isActive",NO);
}this._field_isMouseDown=NO;evt.allowDefault();return YES;},keyDown:function(evt){if(evt.which===9){var view=evt.shiftKey?this.get("previousValidKeyView"):this.get("nextValidKeyView");
view.becomeFirstResponder();return YES;}if(this.performValidateKeyDown(evt)){this._isKeyDown=YES;
evt.allowDefault();}else{evt.stop();}return YES;},acceptsFirstResponder:function(){if(!this.get("followSafariTabFocusBehavior")){return this.get("isEnabled");
}return NO;}.property("isEnabled"),willBecomeKeyResponderFrom:function(keyView){if(!this._isFocused){this._isFocused=YES;
this.becomeFirstResponder();if(this.get("isVisibleInWindow")){this.$input().get(0).focus();
}}},willLoseKeyResponderTo:function(responder){if(this._isFocused){this._isFocused=NO;
}},_field_setFieldValue:function(newValue){this.propertyWillChange("fieldValue");
if(this.fieldValueForObject){newValue=this.fieldValueForObject(newValue);}var ret=this.setFieldValue(newValue);
this.propertyDidChange("fieldValue");return ret;},_field_getFieldValue:function(){var ret=this.getFieldValue();
if(this.objectForFieldValue){ret=this.objectForFieldValue(ret);}return ret;}});sc_require("views/view");
sc_require("mixins/control");SC.IMAGE_STATE_NONE="none";SC.IMAGE_STATE_LOADING="loading";
SC.IMAGE_STATE_LOADED="loaded";SC.IMAGE_STATE_FAILED="failed";SC.IMAGE_STATE_SPRITE="sprite";
SC.BLANK_IMAGE_DATAURL="data:image/gif;base64,R0lGODlhAQABAJAAAP///wAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==";
SC.BLANK_IMAGE_URL=SC.browser.msie&&SC.browser.msie<8?"/static/sproutcore/foundation/en/668e188bd44c10fb9ca18d37e89878e7aac1402d/blank.gif":SC.BLANK_IMAGE_DATAURL;
SC.ImageView=SC.View.extend(SC.Control,{classNames:"sc-image-view",tagName:"img",status:SC.IMAGE_STATE_NONE,value:null,useImageCache:YES,canLoadInBackground:NO,localize:YES,displayProperties:"status toolTip".w(),render:function(context,firstTime){var status=this.get("status"),value=this.get("value");
if(status===SC.IMAGE_STATE_NONE&&value){this._image_valueDidChange();}status=this.get("status");
var src=(status===SC.IMAGE_STATE_LOADED)?value:SC.BLANK_IMAGE_URL;if(status===SC.IMAGE_STATE_SPRITE){context.addClass(value);
}context.attr("src",src);var toolTip=this.get("toolTip");if(SC.typeOf(toolTip)===SC.T_STRING){if(this.get("localize")){toolTip=toolTip.loc();
}context.attr("title",toolTip);context.attr("alt",toolTip);}},_image_valueDidChange:function(){var value=this.get("value"),isUrl;
if(value&&value.isEnumerable){value=value.firstObject();}isUrl=SC.ImageView.valueIsUrl(value);
if(isUrl&&this.get("useImageCache")){var isBackground=this.get("isVisibleInWindow")||this.get("canLoadInBackground");
this._loadingUrl=value;SC.imageCache.loadImage(value,this,this.imageDidLoad,isBackground);
if(this._loadingUrl){this.set("status",SC.IMAGE_STATE_LOADING);}}else{this._loadingUrl=null;
this.set("status",(isUrl)?SC.IMAGE_STATE_LOADED:SC.IMAGE_STATE_SPRITE);this.displayDidChange();
}}.observes("value"),imageDidLoad:function(url,imageOrError){if(url===this._loadingUrl){this._loadingUrl=null;
}if(this.get("value")===url){this.set("status",SC.$ok(imageOrError)?SC.IMAGE_STATE_LOADED:SC.IMAGE_STATE_FAILED);
this.displayDidChange();}}});SC.ImageView.valueIsUrl=function(value){return value?value.indexOf("/")>=0:NO;
};sc_require("views/view");sc_require("mixins/control");SC.ALIGN_LEFT="left";SC.ALIGN_RIGHT="right";
SC.ALIGN_CENTER="center";SC.REGULAR_WEIGHT="normal";SC.BOLD_WEIGHT="bold";SC.LabelView=SC.View.extend(SC.Control,{classNames:["sc-label-view"],fontWeight:SC.REGULAR_WEIGHT,escapeHTML:true,escapeHTMLBindingDefault:SC.Binding.oneWay().bool(),localize:false,localizeBindingDefault:SC.Binding.oneWay().bool(),formatter:null,value:"",hint:null,exampleInlineTextFieldView:SC.InlineTextFieldView,icon:null,textAlign:SC.ALIGN_LEFT,isInlineEditorMultiline:NO,displayValue:function(){var value=this.get("value");
var formatter=this.getDelegateProperty("formatter",this.displayDelegate);if(formatter){var formattedValue=(SC.typeOf(formatter)===SC.T_FUNCTION)?formatter(value,this):formatter.fieldValueForObject(value,this);
if(!SC.none(formattedValue)){value=formattedValue;}}if(SC.typeOf(value)===SC.T_ARRAY){var ary=[];
for(var idx=0;idx<value.get("length");idx++){var x=value.objectAt(idx);if(!SC.none(x)&&x.toString){x=x.toString();
}ary.push(x);}value=ary.join(",");}if(!SC.none(value)&&value.toString){value=value.toString();
}if(value&&this.getDelegateProperty("localize",this.displayDelegate)){value=value.loc();
}if(this.get("escapeHTML")){value=SC.RenderContext.escapeHTML(value);}return value;
}.property("value","localize","formatter","escapeHTML").cacheable(),isEditable:NO,isEditableBindingDefault:SC.Binding.bool(),isEditing:NO,validator:null,doubleClick:function(evt){return this.beginEditing();
},beginEditing:function(){if(this.get("isEditing")){return YES;}if(!this.get("isEditable")){return NO;
}var el=this.$();var value=this.get("value")||"";var f=SC.viewportOffset(el[0]);var frameTemp=this.convertFrameFromView(this.get("frame"),null);
f.width=frameTemp.width;f.height=frameTemp.height;SC.InlineTextFieldView.beginEditing({frame:f,delegate:this,exampleElement:el,value:value,multiline:this.get("isInlineEditorMultiline"),isCollection:NO,validator:this.get("validator"),exampleInlineTextFieldView:this.get("exampleInlineTextFieldView")});
},discardEditing:function(){if(!this.get("isEditing")){return YES;}return SC.InlineTextFieldView.discardEditing();
},commitEditing:function(){if(!this.get("isEditing")){return YES;}return SC.InlineTextFieldView.commitEditing();
},inlineEditorWillBeginEditing:function(inlineEditor){this.set("isEditing",YES);},inlineEditorDidBeginEditing:function(inlineEditor){this._oldOpacity=this.$().css("opacity");
this.$().css("opacity",0);},inlineEditorShouldEndEditing:function(inlineEditor,finalValue){return YES;
},inlineEditorDidEndEditing:function(inlineEditor,finalValue){this.setIfChanged("value",finalValue);
this.$().css("opacity",this._oldOpacity);this._oldOpacity=null;this.set("isEditing",NO);
},displayProperties:"displayValue textAlign fontWeight icon".w(),_TEMPORARY_CLASS_HASH:{},render:function(context,firstTime){var value=this.get("displayValue"),icon=this.get("icon"),hint=this.get("hint");
if(icon){var url=(icon.indexOf("/")>=0)?icon:SC.BLANK_IMAGE_URL;var className=(url===icon)?"":icon;
icon='<img src="%@" alt="" class="icon %@" />'.fmt(url,className);context.push(icon);
}if(hint&&(!value||value==="")){context.push('<span class="sc-hint">',hint,"</span>");
}else{context.push(value);}context.addStyle("text-align",this.get("textAlign")).addStyle("font-weight",this.get("fontWeight"));
var classes=this._TEMPORARY_CLASS_HASH;classes.icon=!!this.get("icon");context.setClass(classes);
if(this.get("isEditing")){context.addStyle("opacity",0);}}});sc_require("views/field");
sc_require("system/text_selection");sc_require("mixins/static_layout");SC.TextFieldView=SC.FieldView.extend(SC.StaticLayout,SC.Editable,{tagName:"label",classNames:["sc-text-field-view"],isPassword:NO,isTextArea:NO,hint:null,isEditing:NO,leftAccessoryView:null,rightAccessoryView:null,_isFocused:NO,isEditable:function(){return this.get("isEnabled");
}.property("isEnabled").cacheable(),selection:function(key,value){var element=this.$input().get(0);
var range,start,end;if(value===undefined){if(element){start=null;end=null;if(!element.value){start=end=0;
}else{if("selectionStart" in element){start=element.selectionStart;}if("selectionEnd" in element){end=element.selectionEnd;
}if(start===null||end===null){var selection=document.selection;if(selection){var type=selection.type;
if(type&&(type==="None"||type==="Text")){range=selection.createRange();if(!this.get("isTextArea")){var length=range.text.length;
start=Math.abs(range.moveStart("character",0-(element.value.length+1)));end=start+length;
}else{var dummyRange=range.duplicate();dummyRange.moveToElementText(element);dummyRange.setEndPoint("EndToStart",range);
start=dummyRange.text.length;end=start+range.text.length;}}}}}return SC.TextSelection.create({start:start,end:end});
}else{return null;}}else{if(!value||!value.kindOf||!value.kindOf(SC.TextSelection)){throw"When setting the selection, you must specify an SC.TextSelection instance.";
}if(element){var setStart,setEnd;if("selectionStart" in element){element.selectionStart=value.get("start");
setStart=YES;}if("selectionEnd" in element){element.selectionEnd=value.get("end");
setEnd=YES;}if(!setStart||!setEnd){range=element.createTextRange();start=value.get("start");
range.move("character",start);range.moveEnd("character",value.get("end")-start);range.select();
}}}}.property("fieldValue").cacheable(),displayProperties:"hint fieldValue isEditing leftAccessoryView rightAccessoryView isTextArea".w(),createChildViews:function(){this.accessoryViewObserver();
},accessoryViewObserver:function(){var classNames;var viewProperties=["leftAccessoryView","rightAccessoryView"];
var len=viewProperties.length;for(var i=0;i<len;i++){var viewProperty=viewProperties[i];
var previousView=this["_"+viewProperty];var accessoryView=this.get(viewProperty);
if(!(previousView&&accessoryView&&(previousView===accessoryView))){if(previousView){classNames=previousView.get("classNames");
classNames=classNames.without("sc-text-field-accessory-view");previousView.set("classNames",classNames);
this.removeChild(previousView);previousView=null;this["_"+viewProperty]=null;}if(accessoryView){if(accessoryView.isClass){accessoryView=accessoryView.create({layoutView:this});
}classNames=accessoryView.get("classNames");var className="sc-text-field-accessory-view";
if(classNames.indexOf(className)<0){classNames.push(className);}this.appendChild(accessoryView);
this["_"+viewProperty]=accessoryView;}}}}.observes("leftAccessoryView","rightAccessoryView"),layoutChildViewsIfNeeded:function(isVisible){if(!isVisible){isVisible=this.get("isVisibleInWindow");
}if(isVisible&&this.get("childViewsNeedLayout")){var rightAccessoryView=this.get("rightAccessoryView");
if(rightAccessoryView&&rightAccessoryView.get){var layout=rightAccessoryView.get("layout");
if(layout){layout.left=null;if(!layout.right){layout.right=0;}rightAccessoryView.adjust({layout:layout});
}}}arguments.callee.base.apply(this,arguments);},render:function(context,firstTime){arguments.callee.base.apply(this,arguments);
var disabled=this.get("isEnabled")?"":'disabled="disabled"';var name=SC.guidFor(this);
var type=this.get("isPassword")?"password":"text";if(this.get("isTextArea")){context.addClass("text-area");
}var v=this.get("fieldValue");if(SC.none(v)){v="";}context.setClass("not-empty",v.length>0);
var accessoryViewWidths=this._getAccessoryViewWidths();var leftAdjustment=accessoryViewWidths["left"];
var rightAdjustment=accessoryViewWidths["right"];if(leftAdjustment){leftAdjustment+="px";
}if(rightAdjustment){rightAdjustment+="px";}this._renderField(context,firstTime,v,leftAdjustment,rightAdjustment);
if(SC.browser.mozilla){this.invokeLast(this._applyFirefoxCursorFix);}},_forceRenderFirstTime:NO,_renderFieldLikeFirstTime:function(){this.set("_forceRenderFirstTime",YES);
}.observes("isTextArea"),_renderField:function(context,firstTime,value,leftAdjustment,rightAdjustment){var hint=this.get("hint");
if(firstTime||this._forceRenderFirstTime){this._forceRenderFirstTime=NO;var disabled=this.get("isEnabled")?"":'disabled="disabled"';
var name=this.get("layerId");context.push('<span class="border"></span>');var adjustmentStyle="";
if(leftAdjustment||rightAdjustment){adjustmentStyle='style="';if(leftAdjustment){adjustmentStyle+="left: "+leftAdjustment+"; ";
}if(rightAdjustment){adjustmentStyle+="right: "+rightAdjustment+";";}adjustmentStyle+='"';
}context.push('<span class="padding" %@>'.fmt(adjustmentStyle));context.push('<span class="sc-hint">',hint,"</span>");
if(this.get("isTextArea")){context.push('<textarea name="%@" %@>%@</textarea></span>'.fmt(name,disabled,value));
}else{var type=this.get("isPassword")?"password":"text";context.push('<input type="%@" name="%@" %@ value="%@"/></span>'.fmt(type,name,disabled,value));
}}else{var hintElements=this.$(".sc-hint");if(hint!==this._textField_currentHint){this._textField_currentHint=hint;
hintElements.text(hint);}var element=this.$input()[0];if(element){if(!this.get("isEnabled")){element.disabled="true";
}else{element.disabled=null;}var paddingElement=element.parentNode;if(leftAdjustment){if(paddingElement.style.left!==leftAdjustment){paddingElement.style.left=leftAdjustment;
}}else{paddingElement.style.left=null;}if(rightAdjustment){if(paddingElement.style.right!==rightAdjustment){paddingElement.style.right=rightAdjustment;
}}else{paddingElement.style.right=null;}}}},_getAccessoryViewWidths:function(){var widths={};
var accessoryViewPositions=["left","right"];var numberOfAccessoryViewPositions=accessoryViewPositions.length;
for(var i=0;i<numberOfAccessoryViewPositions;i++){var position=accessoryViewPositions[i];
var accessoryView=this.get(position+"AccessoryView");if(accessoryView&&accessoryView.get){var frame=accessoryView.get("frame");
if(frame){var width=frame.width;if(width){var layout=accessoryView.get("layout");
if(layout){var offset=layout[position];width+=offset;}widths[position]=width;}}}}return widths;
},didCreateLayer:function(){arguments.callee.base.apply(this,arguments);var input=this.$input();
SC.Event.add(input,"focus",this,this._textField_fieldDidFocus);SC.Event.add(input,"blur",this,this._textField_fieldDidBlur);
SC.Event.add(input,"select",this,this._textField_selectionDidChange);if(SC.browser.mozilla){this._cacheInputElement=this.$input();
this._cachePaddingElement=this.$(".padding");}},willDestroyLayer:function(){arguments.callee.base.apply(this,arguments);
var input=this.$input();SC.Event.remove(input,"focus",this,this._textField_fieldDidFocus);
SC.Event.remove(input,"blur",this,this._textField_fieldDidBlur);SC.Event.remove(input,"select",this,this._textField_selectionDidChange);
},_textField_fieldDidFocus:function(evt){SC.RunLoop.begin();this.fieldDidFocus();
SC.RunLoop.end();},_textField_fieldDidBlur:function(evt){SC.RunLoop.begin();this.fieldDidBlur();
SC.RunLoop.end();},fieldDidFocus:function(evt){this.beginEditing();},fieldDidBlur:function(){this.commitEditing();
},_topOffsetForFirefoxCursorFix:3,_applyFirefoxCursorFix:function(){if(SC.browser.mozilla){var top,left,width,height,p,layer,element,textfield;
element=this._cacheInputElement;textfield=this._cachePaddingElement;if(textfield&&textfield[0]){layer=textfield[0];
p=SC.$(layer).offset();if(element[0].tagName.toLowerCase()==="input"){top=p.top+this._topOffsetForFirefoxCursorFix;
}else{top=p.top;}left=p.left;width=layer.offsetWidth;height=layer.offsetHeight;var style="position: fixed; top: %@px; left: %@px; width: %@px; height: %@px;".fmt(top,left,width,height);
if(!this._prevStyle||this._prevStyle!=style){element.attr("style",style);}this._prevStyle=style;
}}return this;},_textField_selectionDidChange:function(){this.notifyPropertyChange("selection");
},willBecomeKeyResponderFrom:function(keyView){if(this.get("isVisibleInWindow")){this.$input()[0].focus();
if(!this._txtFieldMouseDown){if(SC.browser.mozilla){this.invokeOnce(this._selectRootElement);
}else{if(SC.browser.safari){this.invokeLater(this._selectRootElement,1);}else{this._selectRootElement();
}}}}},willLoseKeyResponderTo:function(responder){},_selectRootElement:function(){this.$input()[0].select();
},didLoseKeyResponderTo:function(keyView){this.$input()[0].blur();},parentViewDidResize:function(){if(SC.browser.mozilla){this.invokeLast(this._applyFirefoxCursorFix);
}arguments.callee.base.apply(this,arguments);},keyDown:function(evt){if((evt.which===13)&&!this.get("isTextArea")){return NO;
}if(evt.which===27){return NO;}if(evt.which===9&&!this.get("isTextArea")){var view=evt.shiftKey?this.get("previousValidKeyView"):this.get("nextValidKeyView");
view.becomeFirstResponder();return YES;}if(evt.which===8){evt.dontForceDeleteKey=YES;
}if(this.performValidateKeyDown(evt)){this._isKeyDown=YES;evt.allowDefault();}else{evt.stop();
}return YES;},keyUp:function(evt){this.notifyPropertyChange("selection");if(this._isKeyDown){this.invokeLater(this.fieldValueDidChange,1,YES);
}this._isKeyDown=NO;evt.allowDefault();return YES;},mouseDown:function(evt){this._txtFieldMouseDown=YES;
if(!this.get("isEnabled")){evt.stop();return YES;}else{if((this.value&&this.value.length===0)||!this.value){return YES;
}else{if(SC.browser.mozilla){this.$input()[0].focus();}return arguments.callee.base.apply(this,arguments);
}}},mouseUp:function(evt){this._txtFieldMouseDown=NO;this.notifyPropertyChange("selection");
if(!this.get("isEnabled")){evt.stop();return YES;}else{if((this.value&&this.value.length===0)||!this.value){this.$input()[0].focus();
return YES;}else{return arguments.callee.base.apply(this,arguments);}}},selectStart:function(evt){return YES;
}});sc_require("panes/pane");SC.MainPane=SC.Pane.extend({layout:{left:0,right:0,top:0,bottom:0},paneDidAttach:function(){var ret=arguments.callee.base.apply(this,arguments);
var responder=this.rootResponder;responder.makeMainPane(this);if(!responder.get("keyRootView")){responder.makeKeyPane(this);
}return ret;},acceptsKeyPane:YES,classNames:["sc-main"]});tiki.script("sproutcore/foundation:en/668e188bd44c10fb9ca18d37e89878e7aac1402d/javascript.js");
tiki.register("sproutcore/desktop",{"depends":["sproutcore/runtime","sproutcore/datastore","sproutcore/foundation"],"packages":{"sproutcore/runtime":{},"sproutcore/foundation":{},"sproutcore/datastore":{}},"scripts":[{"url":"/static/sproutcore/desktop/en/0a67032b44fccf8f11160e96135230830ba8b945/javascript.js","id":"sproutcore/desktop:en/0a67032b44fccf8f11160e96135230830ba8b945/javascript.js"}]});
tiki.global("sproutcore/desktop");SC.stringsFor("English",{"Invalid.CreditCard(%@)":"%@ is not a valid credit card number","Invalid.Email(%@)":"%@ is not a valid email address","Invalid.NotEmpty(%@)":"%@ must not be empty","Invalid.Password":"Your passwords do not match.  Please try typing them again.","Invalid.General(%@)":"%@ is invalid.  Please try again.","Invalid.Number(%@)":"%@ is not a number."});
SC.allowsBackspaceToPreviousPage=NO;SC.BORDER_BEZEL="sc-bezel-border";SC.BORDER_BLACK="sc-black-border";
SC.BORDER_GRAY="sc-gray-border";SC.BORDER_TOP="sc-top-border";SC.BORDER_BOTTOM="sc-bottom-border";
SC.BORDER_NONE=null;SC.Border={borderStyle:SC.BORDER_GRAY,_BORDER_REGEXP:(/-border$/),renderMixin:function(context,firstTime){var style=this.get("borderStyle");
if(style){if(this._BORDER_REGEXP.exec(style)){context.addClass(style);}else{content.addStyle("border","1px %@ solid".fmt(style));
}}}};SC.Scrollable={isScrollable:true,verticalLineScroll:20,horizontalLineScroll:20,verticalPageScroll:function(){return this.get("innerFrame").height;
}.property("innerFrame"),horizontalPageScroll:function(){return this.get("innerFrame").width;
}.property("innerFrame"),hasVerticalScroller:function(){return this.get("scrollFrame").height>this.get("innerFrame").height;
}.property("scrollFrame"),hasHorizontalScroller:function(){return this.get("scrollFrame").width>this.get("innerFrame").width;
}.property("scrollFrame"),scrollBy:function(amount){var sf=this.get("scrollFrame");
var f=this.get("innerFrame");if(!this.get("hasVerticalScroller")){amount.y=0;}if(sf.height<=f.height){amount.y=0;
}if(!this.get("hasHorizontalScroller")){amount.x=0;}if(sf.width<=f.width){amount.x=0;
}var newSf={x:sf.x-(amount.x||0),y:sf.y-(amount.y||0)};this.set("scrollFrame",newSf);
newSf=this.get("scrollFrame");return{x:newSf.x-sf.x,y:newSf.y-sf.y};},scrollTo:function(x,y){this.set("scrollFrame",{x:0-x,y:0-y});
},scrollToVisible:function(view){var f=this.get("innerFrame");var sf=this.get("scrollFrame");
var vf=this.convertFrameFromView(view.get("frame"),view);vf.x-=(f.x+sf.x);vf.y-=(f.y+sf.y);
var vo={x:0-sf.x,y:0-sf.y,width:f.width,height:f.height};vo.y-=Math.max(0,SC.minY(vo)-SC.minY(vf));
vo.x-=Math.max(0,SC.minX(vo)-SC.minX(vf));vo.y+=Math.max(0,SC.maxY(vf)-SC.maxY(vo));
vo.x+=Math.max(0,SC.maxX(vf)-SC.maxX(vo));this.scrollTo(vo.x,vo.y);},scrollDownLine:function(lines){if(lines===undefined){lines=1;
}return this.scrollBy({y:this.get("verticalLineScroll")*lines}).y;},scrollUpLine:function(lines){if(lines===undefined){lines=1;
}return 0-this.scrollBy({y:0-this.get("verticalLineScroll")*lines}).y;},scrollRightLine:function(lines){if(lines===undefined){lines=1;
}return this.scrollTo({y:this.get("horizontalLineScroll")*lines}).x;},scrollLeftLine:function(lines){if(lines===undefined){lines=1;
}return 0-this.scrollTo({y:0-this.get("horizontalLineScroll")*lines}).x;},scrollDownPage:function(pages){if(pages===undefined){pages=1;
}return this.scrollBy({y:this.get("verticalPageScroll")*pages}).y;},scrollUpPage:function(pages){if(pages===undefined){pages=1;
}return 0-this.scrollBy({y:0-this.get("verticalPageScroll")*pages}).y;},scrollRightPage:function(pages){if(pages===undefined){pages=1;
}return this.scrollTo({y:this.get("horizontalPageScroll")*pages}).x;},scrollLeftPage:function(pages){if(pages===undefined){pages=1;
}return 0-this.scrollTo({y:0-this.get("horizontalPageScroll")*pages}).x;}};SC.DRAG_LINK=4;
SC.DRAG_COPY=1;SC.DRAG_MOVE=2;SC.DRAG_NONE=0;SC.DRAG_ANY=7;SC.DRAG_AUTOSCROLL_ZONE_THICKNESS=20;
SC.Drag=SC.Object.extend({source:null,ghostView:null,ghostActsLikeCursor:NO,dragView:null,ghost:YES,slideBack:YES,mouseDownEvent:null,ghostOffset:{x:0,y:0},location:{},dataTypes:function(){if(this.dataSource){return this.dataSource.get("dragDataTypes")||[];
}var hash=this.data;if(hash){var ret=[];for(var key in hash){if(hash.hasOwnProperty(key)){ret.push(key);
}}return ret;}var source=this.get("source");if(source&&source.dragDataTypes){return source.get("dragDataTypes")||[];
}return[];}.property().cacheable(),hasDataType:function(dataType){return(this.get("dataTypes").indexOf(dataType)>=0);
},dataForType:function(dataType){if(this.dataSource){return this.dataSource.dragDataForType(this,dataType);
}else{if(this.data){return this.data[dataType];}else{var source=this.get("source");
if(source&&SC.typeOf(source.dragDataForType)==SC.T_FUNCTION){return source.dragDataForType(this,dataType);
}else{return null;}}}},dataSource:null,data:null,allowedDragOperations:SC.DRAG_ANY,_dragInProgress:YES,startDrag:function(){this._createGhostView();
var evt=this.event;var loc={x:evt.pageX,y:evt.pageY};this.set("location",loc);var dv=this.dragView;
var pane=dv.get("pane");var pv=dv.get("parentView");var clippingFrame=dv.get("clippingFrame");
var f=pv?pv.convertFrameToView(dv.get("frame"),null):dv.get("frame");var pf=pane?pane.get("frame"):{x:0,y:0};
dv.adjust({top:f.y+pf.y,left:f.x+pf.x,width:f.width,height:f.height});var dvf=dv.get("frame");
var origin=f;if(this.ghostActsLikeCursor){this.ghostOffset={x:14,y:14};}else{this.ghostOffset={x:(loc.x-origin.x),y:(loc.y-origin.y)};
}if(!this._ghostViewHidden){this._positionGhostView(evt);}this.ghostView.rootResponder.dragDidStart(this);
var source=this.source;if(source&&source.dragDidBegin){source.dragDidBegin(this,loc);
}var ary=this._dropTargets();for(var idx=0,len=ary.length;idx<len;idx++){ary[idx].tryToPerform("dragStarted",this,evt);
}},mouseDragged:function(evt){var scrolled=this._autoscroll(evt);var loc=this.get("location");
if(!scrolled&&(evt.pageX==loc.x)&&(evt.pageY==loc.y)){return;}loc={x:evt.pageX,y:evt.pageY};
this.set("location",loc);var source=this.source;var last=this._lastTarget;var target=this._findDropTarget(evt);
var op=SC.DRAG_NONE;while(target&&(target!=last)&&(op==SC.DRAG_NONE)){if(target&&source&&source.dragSourceOperationMaskFor){op=source.dragSourceOperationMaskFor(this,target);
}else{op=SC.DRAG_ANY;}if((op!=SC.DRAG_NONE)&&target&&target.computeDragOperations){op=op&target.computeDragOperations(this,evt,op);
}else{op=SC.DRAG_NONE;}this.allowedDragOperations=op;if(op==SC.DRAG_NONE){target=this._findNextDropTarget(target);
}}if(target!=last){if(last&&last.dragExited){last.dragExited(this,evt);}if(target){if(target.dragEntered){target.dragEntered(this,evt);
}if(target.dragUpdated){target.dragUpdated(this,evt);}}this._lastTarget=target;}else{if(target&&target.dragUpdated){target.dragUpdated(this,evt);
}}if(source&&source.dragDidMove){source.dragDidMove(this,loc);}if(!this._ghostViewHidden){this._positionGhostView(evt);
}},mouseUp:function(evt){var loc={x:evt.pageX,y:evt.pageY},target=this._lastTarget,op=this.allowedDragOperations;
this.set("location",loc);try{if(target&&target.acceptDragOperation&&target.acceptDragOperation(this,op)){op=target.performDragOperation?target.performDragOperation(this,op):SC.DRAG_NONE;
}else{op=SC.DRAG_NONE;}}catch(e){console.error("Exception in SC.Drag.mouseUp(acceptDragOperation|performDragOperation): %@".fmt(e));
}try{if(target&&target.dragExited){target.dragExited(this,evt);}}catch(ex){console.error("Exception in SC.Drag.mouseUp(target.dragExited): %@".fmt(ex));
}var ary=this._dropTargets();for(var idx=0,len=ary.length;idx<len;idx++){try{ary[idx].tryToPerform("dragEnded",this,evt);
}catch(ex2){console.error("Exception in SC.Drag.mouseUp(dragEnded on %@): %@".fmt(ary[idx],ex2));
}}this._destroyGhostView();var source=this.source;if(source&&source.dragDidEnd){source.dragDidEnd(this,loc,op);
}this._lastTarget=null;this._dragInProgress=NO;},_createGhostView:function(){var that=this,frame=this.dragView.get("frame"),view;
view=this.ghostView=SC.Pane.create({classNames:["sc-ghost-view"],layout:{top:frame.y,left:frame.x,width:frame.width,height:frame.height},owner:this,didCreateLayer:function(){if(that.dragView){var layer=that.dragView.get("layer");
if(layer){this.get("layer").appendChild(layer.cloneNode(true));}}}});view.append();
},_positionGhostView:function(evt){var loc=this.get("location");loc.x-=this.ghostOffset.x;
loc.y-=this.ghostOffset.y;var gV=this.ghostView;if(gV){gV.adjust({top:loc.y,left:loc.x});
gV.invokeOnce("updateLayout");}},_ghostViewHidden:NO,hideGhostView:function(){if(this.ghostView&&!this._ghostViewHidden){this.ghostView.remove();
this._ghostViewHidden=YES;}},unhideGhostView:function(){if(this._ghostViewHidden){this._ghostViewHidden=NO;
this._createGhostView();}},_destroyGhostView:function(){if(this.ghostView){this.ghostView.remove();
this.ghostView=null;this._ghostViewHidden=NO;}},_dropTargets:function(){if(this._cachedDropTargets){return this._cachedDropTargets;
}var ret=[];var hash=SC.Drag._dropTargets;for(var key in hash){if(hash.hasOwnProperty(key)){ret.push(hash[key]);
}}var depth={};var dropTargets=SC.Drag._dropTargets;var getDepthFor=function(x){if(!x){return 0;
}var guid=SC.guidFor(x);var ret=depth[guid];if(!ret){ret=1;while(x=x.get("parentView")){if(dropTargets[SC.guidFor(x)]!==undefined){ret++;
}}depth[guid]=ret;}return ret;};ret.sort(function(a,b){if(a===b){return 0;}a=getDepthFor(a);
b=getDepthFor(b);return(a>b)?-1:1;});this._cachedDropTargets=ret;return ret;},_findDropTarget:function(evt){var loc={x:evt.pageX,y:evt.pageY};
var target,frame;var ary=this._dropTargets();for(var idx=0,len=ary.length;idx<len;
idx++){target=ary[idx];if(!target.get("isVisibleInWindow")){continue;}frame=target.convertFrameToView(target.get("clippingFrame"),null);
if(SC.pointInRect(loc,frame)){return target;}}return null;},_findNextDropTarget:function(target){var dropTargets=SC.Drag._dropTargets;
while(target=target.get("parentView")){if(dropTargets[SC.guidFor(target)]){return target;
}}return null;},_autoscroll:function(evt){if(!evt){evt=this._lastAutoscrollEvent;
}if(!this._dragInProgress){return NO;}var loc=evt?{x:evt.pageX,y:evt.pageY}:this.get("location"),view=this._findScrollableView(loc),scrollableView=null,vscroll,hscroll,min,max,edge,container,f;
while(view&&!scrollableView){vscroll=view.get("canScrollVertical")?1:0;hscroll=view.get("canScrollHorizontal")?1:0;
if(vscroll||hscroll){container=view.get("containerView");if(container){f=view.convertFrameToView(container.get("frame"),null);
}else{vscroll=hscroll=0;}}if(vscroll){max=SC.maxY(f);min=max-SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;
if(loc.y>=min&&loc.y<=max){vscroll=1;}else{min=SC.minY(f);max=min+SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;
if(loc.y>=min&&loc.y<=max){vscroll=-1;}else{vscroll=0;}}}if(hscroll){max=SC.maxX(f);
min=max-SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;if(loc.x>=min&&loc.x<=max){hscroll=1;}else{min=SC.minX(f);
max=min+SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;if(loc.x>=min&&loc.x<=max){hscroll=-1;}else{hscroll=0;
}}}if(vscroll||hscroll){scrollableView=view;}else{view=this._findNextScrollableView(view);
}}if(scrollableView&&(this._lastScrollableView===scrollableView)){if((Date.now()-this._hotzoneStartTime)>100){this._horizontalScrollAmount*=1.05;
this._verticalScrollAmount*=1.05;}}else{this._lastScrollableView=scrollableView;this._horizontalScrollAmount=15;
this._verticalScrollAmount=15;this._hotzoneStartTime=(scrollableView)?Date.now():null;
hscroll=vscroll=0;}if(scrollableView&&(hscroll||vscroll)){var scroll={x:hscroll*this._horizontalScrollAmount,y:vscroll*this._verticalScrollAmount};
scrollableView.scrollBy(scroll);}if(scrollableView){if(evt){this._lastAutoscrollEvent={pageX:evt.pageX,pageY:evt.pageY};
}this.invokeLater(this._autoscroll,100,null);return YES;}else{this._lastAutoscrollEvent=null;
return NO;}},_scrollableViews:function(){if(this._cachedScrollableView){return this._cachedScrollableView;
}var ret=[];var hash=SC.Drag._scrollableViews;for(var key in hash){if(hash.hasOwnProperty(key)){ret.push(hash[key]);
}}ret=ret.sort(function(a,b){var view=a;while(view=view.get("parentView")){if(b==view){return -1;
}}return 1;});this._cachedScrollableView=ret;return ret;},_findScrollableView:function(loc){var ary=this._scrollableViews(),len=ary?ary.length:0,target,frame,idx;
for(idx=0;idx<len;idx++){target=ary[idx];if(!target.get("isVisibleInWindow")){continue;
}frame=target.convertFrameToView(target.get("clippingFrame"),null);if(SC.pointInRect(loc,frame)){return target;
}}return null;},_findNextScrollableView:function(view){var scrollableViews=SC.Drag._scrollableViews;
while(view=view.get("parentView")){if(scrollableViews[SC.guidFor(view)]){return view;
}}return null;}});SC.Drag.mixin({start:function(ops){var ret=this.create(ops);ret.startDrag();
return ret;},_dropTargets:{},_scrollableViews:{},addDropTarget:function(target){this._dropTargets[SC.guidFor(target)]=target;
},removeDropTarget:function(target){delete this._dropTargets[SC.guidFor(target)];
},addScrollableView:function(target){this._scrollableViews[SC.guidFor(target)]=target;
},removeScrollableView:function(target){delete this._scrollableViews[SC.guidFor(target)];
}});SC.MODIFIED_KEY_BINDINGS={"ctrl_.":"cancel","shift_tab":"insertBacktab","shift_left":"moveLeftAndModifySelection","shift_right":"moveRightAndModifySelection","shift_up":"moveUpAndModifySelection","shift_down":"moveDownAndModifySelection","alt_left":"moveLeftAndModifySelection","alt_right":"moveRightAndModifySelection","alt_up":"moveUpAndModifySelection","alt_down":"moveDownAndModifySelection","ctrl_a":"selectAll"};
SC.BASE_KEY_BINDINGS={"escape":"cancel","backspace":"deleteBackward","delete":"deleteForward","return":"insertNewline","tab":"insertTab","left":"moveLeft","right":"moveRight","up":"moveUp","down":"moveDown","home":"moveToBeginningOfDocument","end":"moveToEndOfDocument","pagedown":"pageDown","pageup":"pageUp"};
SC.CAPTURE_BACKSPACE_KEY=NO;SC.PANEL_ORDER_LAYER=4096;SC.PALETTE_ORDER_LAYER=8192;
SC.POPUP_ORDER_LAYER=12288;SC.RootResponder=SC.RootResponder.extend({platform:"desktop",focusedPane:function(){var views=this.get("orderedPanes");
return views[views.length-1];}.property("orderedPanes"),orderedPanes:null,orderBefore:function(pane,beforePane){var currentFocus=this.get("focusedPane"),panes=this.get("orderedPanes").without(pane),len,idx,currentOrder,newFocus;
var orderLayer=pane.get("orderLayer");if(beforePane){len=panes.length;idx=panes.indexOf(beforePane);
currentOrder=beforePane.get("orderLayer");if(currentOrder<orderLayer){while((beforePane.get("orderLayer")<orderLayer)&&(++idx<len)){beforePane=panes[idx];
}if(idx>=len){beforePane=null;}}else{if(currentOrder>orderLayer){while((beforePane.get("orderLayer")>orderLayer)&&(--idx>=0)){beforePane=panes[idx];
}beforePane=(idx<0)?panes[0]:panes[idx+1];}}}else{idx=panes.length;while((--idx>=0)&&!beforePane){beforePane=panes[idx];
if(beforePane.get("orderLayer")>orderLayer){beforePane=null;}}if(idx<0){beforePane=panes[0];
}else{beforePane=panes[idx+1];}}if(beforePane){idx=panes.indexOf(beforePane);panes.insertAt(idx,pane);
}else{panes.push(pane);}this.set("orderedPanes",panes);newFocus=this.get("focusedPane");
if(newFocus!==currentFocus){if(currentFocus){currentFocus.blurTo(newFocus);}if(newFocus){newFocus.focusFrom(currentFocus);
}}return this;},orderOut:function(pane){var currentFocus=this.get("focusedPane"),currentKey=this.get("keyPane");
var panes=this.get("orderedPanes").without(pane);this.set("orderedPanes",panes);if(currentFocus===pane){var newFocus=this.get("focusedPane");
if(currentFocus){currentFocus.blurTo(newFocus);}if(newFocus){newFocus.focusFrom(currentFocus);
}if(currentKey===pane){this.makeKeyPane(newFocus);}}else{if(currentKey===pane){this.makeKeyPane(null);
}}return this;},init:function(){arguments.callee.base.apply(this,arguments);this.orderedPanes=[];
},setup:function(){this.listenFor("keydown keyup mousedown mouseup click dblclick mouseout mouseover mousemove selectstart".w(),document).listenFor("resize focus blur".w(),window);
if(this.keypress){if(SC.CAPTURE_BACKSPACE_KEY&&SC.browser.mozilla){var responder=this;
document.onkeypress=function(e){e=SC.Event.normalizeEvent(e);return responder.keypress.call(responder,e);
};SC.Event.add(window,"unload",this,function(){document.onkeypress=null;});}else{SC.Event.add(document,"keypress",this,this.keypress);
}}"drag selectstart".w().forEach(function(keyName){var method=this[keyName];if(method){if(SC.browser.msie){var responder=this;
document.body["on"+keyName]=function(e){return method.call(responder,SC.Event.normalizeEvent(event||window.event));
};SC.Event.add(window,"unload",this,function(){document.body["on"+keyName]=null;});
}else{SC.Event.add(document,keyName,this,method);}}},this);var mousewheel=SC.browser.mozilla?"DOMMouseScroll":"mousewheel";
SC.Event.add(document,mousewheel,this,this.mousewheel);this.set("currentWindowSize",this.computeWindowSize());
this.focus();},attemptKeyEquivalent:function(evt){var ret=null;var keystring=evt.commandCodes()[0];
if(!keystring){return NO;}var keyPane=this.get("keyPane"),mainPane=this.get("mainPane"),mainMenu=this.get("mainMenu");
if(keyPane){ret=keyPane.performKeyEquivalent(keystring,evt);}if(!ret&&mainPane&&(mainPane!==keyPane)){ret=mainPane.performKeyEquivalent(keystring,evt);
}if(!ret&&mainMenu){ret=mainMenu.performKeyEquivalent(keystring,evt);}return ret;
},currentWindowSize:null,computeWindowSize:function(){var size;if(window.innerHeight){size={width:window.innerWidth,height:window.innerHeight};
}else{if(document.documentElement&&document.documentElement.clientHeight){size={width:document.documentElement.clientWidth,height:document.documentElement.clientHeight};
}else{if(document.body){size={width:document.body.clientWidth,height:document.body.clientHeight};
}}}return size;},resize:function(){this._resize();return YES;},_resize:function(){var newSize=this.computeWindowSize(),oldSize=this.get("currentWindowSize");
this.set("currentWindowSize",newSize);if(!SC.rectsEqual(newSize,oldSize)){if(this.panes){SC.RunLoop.begin();
this.panes.invoke("windowSizeDidChange",oldSize,newSize);SC.RunLoop.end();}}},hasFocus:NO,focus:function(){if(!this.get("hasFocus")){SC.$("body").addClass("sc-focus").removeClass("sc-blur");
SC.RunLoop.begin();this.set("hasFocus",YES);SC.RunLoop.end();}return YES;},blur:function(){if(this.get("hasFocus")){SC.$("body").addClass("sc-blur").removeClass("sc-focus");
SC.RunLoop.begin();this.set("hasFocus",NO);SC.RunLoop.end();}return YES;},dragDidStart:function(drag){this._mouseDownView=drag;
this._drag=drag;},_lastModifiers:null,_handleModifierChanges:function(evt){var m;
m=this._lastModifiers=(this._lastModifiers||{alt:false,ctrl:false,shift:false});var changed=false;
if(evt.altKey!==m.alt){m.alt=evt.altKey;changed=true;}if(evt.ctrlKey!==m.ctrl){m.ctrl=evt.ctrlKey;
changed=true;}if(evt.shiftKey!==m.shift){m.shift=evt.shiftKey;changed=true;}evt.modifiers=m;
return(changed)?(this.sendEvent("flagsChanged",evt)?evt.hasCustomEventHandling:YES):YES;
},_isFunctionOrNonPrintableKey:function(evt){return !!(evt.altKey||evt.ctrlKey||evt.metaKey||((evt.charCode!==evt.which)&&SC.FUNCTION_KEYS[evt.which]));
},_isModifierKey:function(evt){return !!SC.MODIFIER_KEYS[evt.charCode];},keydown:function(evt){if(!evt.kindOf){this._ffevt=null;
}else{evt=this._ffevt;}if(SC.none(evt)){return YES;}if(SC.browser.mozilla&&(evt.which===8)){return true;
}var ret=this._handleModifierChanges(evt),target=evt.target||evt.srcElement,forceBlock=(evt.which===8)&&!SC.allowsBackspaceToPreviousPage&&(target===document.body);
if(this._isModifierKey(evt)){return(forceBlock?NO:ret);}ret=YES;if(this._isFunctionOrNonPrintableKey(evt)){if(SC.browser.mozilla&&evt.keyCode>=37&&evt.keyCode<=40){this._ffevt=evt;
SC.RunLoop.begin();this.invokeLater(this.keydown,100);SC.RunLoop.end();}ret=this.sendEvent("keyDown",evt);
if(!ret){ret=!this.attemptKeyEquivalent(evt);}else{ret=evt.hasCustomEventHandling;
if(ret){forceBlock=NO;}}}return forceBlock?NO:ret;},keypress:function(evt){var ret;
if(SC.browser.mozilla&&(evt.which===8)){ret=this.sendEvent("keyDown",evt);return ret?(SC.allowsBackspaceToPreviousPage||evt.hasCustomEventHandling):YES;
}else{if(evt.charCode!==undefined&&evt.charCode===0){return YES;}return this.sendEvent("keyDown",evt)?evt.hasCustomEventHandling:YES;
}},keyup:function(evt){if(this._ffevt){this._ffevt=null;}var ret=this._handleModifierChanges(evt);
if(this._isModifierKey(evt)){return ret;}return this.sendEvent("keyUp",evt)?evt.hasCustomEventHandling:YES;
},mousedown:function(evt){try{this.focus();if(SC.browser.msie){this._lastMouseDownX=evt.clientX;
this._lastMouseDownY=evt.clientY;}this._clickCount+=1;if(!this._lastMouseUpAt||((Date.now()-this._lastMouseUpAt)>200)){this._clickCount=1;
}evt.clickCount=this._clickCount;var fr,view=this.targetViewForEvent(evt);if(view){fr=view.get("pane").get("firstResponder");
}if(fr&&fr.kindOf(SC.InlineTextFieldView)&&fr!==view){fr.resignFirstResponder();}view=this._mouseDownView=this.sendEvent("mouseDown",evt,view);
if(view&&view.respondsTo("mouseDragged")){this._mouseCanDrag=YES;}}catch(e){console.warn("Exception during mousedown: %@".fmt(e));
this._mouseDownView=null;this._mouseCanDrag=NO;throw e;}return view?evt.hasCustomEventHandling:YES;
},mouseup:function(evt){try{if(this._drag){this._drag.tryToPerform("mouseUp",evt);
this._drag=null;}var handler=null,view=this._mouseDownView;this._lastMouseUpAt=Date.now();
evt.clickCount=this._clickCount;if(view){handler=this.sendEvent("mouseUp",evt,view);
if(!handler&&(this._clickCount===2)){handler=this.sendEvent("doubleClick",evt,view);
}if(!handler){handler=this.sendEvent("click",evt,view);}}if(!handler){view=this.targetViewForEvent(evt);
if(this._clickCount===2){handler=this.sendEvent("doubleClick",evt,view);}if(!handler){handler=this.sendEvent("click",evt,view);
}}this._mouseCanDrag=NO;this._mouseDownView=null;}catch(e){this._drag=null;this._mouseCanDrag=NO;
this._mouseDownView=null;throw e;}return(handler)?evt.hasCustomEventHandling:YES;
},dblclick:function(evt){if(SC.browser.isIE){this._clickCount=2;this.mouseup(evt);
}},mousewheel:function(evt){try{var view=this.targetViewForEvent(evt),handler=this.sendEvent("mouseWheel",evt,view);
}catch(e){throw e;}return(handler)?evt.hasCustomEventHandling:YES;},_lastHovered:null,mousemove:function(evt){if(SC.browser.msie){if(this._lastMoveX===evt.clientX&&this._lastMoveY===evt.clientY){return;
}else{this._lastMoveX=evt.clientX;this._lastMoveY=evt.clientY;}}SC.RunLoop.begin();
try{this.focus();if(this._drag){if(SC.browser.msie){if(this._lastMouseDownX!==evt.clientX&&this._lastMouseDownY!==evt.clientY){this._drag.tryToPerform("mouseDragged",evt);
}}else{this._drag.tryToPerform("mouseDragged",evt);}}else{var lh=this._lastHovered||[],nh=[],exited,loc,len,view=this.targetViewForEvent(evt);
while(view&&(view!==this)){if(lh.indexOf(view)!==-1){view.tryToPerform("mouseMoved",evt);
nh.push(view);}else{view.tryToPerform("mouseEntered",evt);nh.push(view);}view=view.get("nextResponder");
}for(loc=0,len=lh.length;loc<len;loc++){view=lh[loc];exited=view.respondsTo("mouseExited");
if(exited&&!(nh.indexOf(view)!==-1)){view.tryToPerform("mouseExited",evt);}}this._lastHovered=nh;
if(this._mouseDownView){if(SC.browser.msie){if(this._lastMouseDownX!==evt.clientX&&this._lastMouseDownY!==evt.clientY){this._mouseDownView.tryToPerform("mouseDragged",evt);
}}else{this._mouseDownView.tryToPerform("mouseDragged",evt);}}}}catch(e){throw e;
}SC.RunLoop.end();},_mouseCanDrag:YES,selectstart:function(evt){var result=this.sendEvent("selectStart",evt,this.targetViewForEvent(evt));
return(result!==null?YES:NO)&&(this._mouseCanDrag?NO:YES);},drag:function(){return false;
}});sc_require("core");SC.UndoManager=SC.Object.extend({undoActionName:function(){return this.undoStack?this.undoStack.name:null;
}.property("undoStack"),redoActionName:function(){return this.redoStack?this.redoStack.name:null;
}.property("redoStack"),canUndo:function(){return this.undoStack!=null;}.property("undoStack"),canRedo:function(){return this.redoStack!=null;
}.property("redoStack"),undo:function(){this._undoOrRedo("undoStack","isUndoing");
},redo:function(){this._undoOrRedo("redoStack","isRedoing");},isUndoing:false,isRedoing:false,groupingLevel:0,registerUndo:function(func,name){this.beginUndoGroup(name);
this._activeGroup.actions.push(func);this.endUndoGroup(name);},beginUndoGroup:function(name){if(this._activeGroup){this.groupingLevel++;
}else{var stack=this.isUndoing?"redoStack":"undoStack";this._activeGroup={name:name,actions:[],prev:this.get(stack)};
this.set(stack,this._activeGroup);this.groupingLevel=1;}},endUndoGroup:function(name){if(!this._activeGroup){raise("endUndoGroup() called outside group.");
}if(this.groupingLevel>1){this.groupingLevel--;}else{this._activeGroup=null;this.groupingLevel=0;
}this.propertyDidChange(this.isUndoing?"redoStack":"undoStack");},setActionName:function(name){if(!this._activeGroup){raise("setActionName() called outside group.");
}this._activeGroup.name=name;},_activeGroup:null,undoStack:null,redoStack:null,_undoOrRedo:function(stack,state){if(this._activeGroup){return false;
}if(this.get(stack)==null){return true;}this.set(state,true);var group=this.get(stack);
this.set(stack,group.prev);var action;var useGroup=group.actions.length>1;if(useGroup){this.beginUndoGroup(group.name);
}while(action=group.actions.pop()){action();}if(useGroup){this.endUndoGroup(group.name);
}this.set(state,false);}});SC.NATURAL_SCROLLER_THICKNESS=16;SC.ScrollerView=SC.View.extend({classNames:["sc-scroller-view"],scrollerThickness:SC.NATURAL_SCROLLER_THICKNESS,value:function(key,val){if(val!==undefined){if(val>=0){this._value=val;
}}else{var value=this._value||0;return Math.min(value,this.get("maximum"));}}.property("maximum").cacheable(),maximum:0,isEnabled:YES,layoutDirection:SC.LAYOUT_VERTICAL,ownerScrollValueKey:function(){var key=null;
switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:key="verticalScrollOffset";
break;case SC.LAYOUT_HORIZONTAL:key="horizontalScrollOffset";break;default:key=null;
}return key;}.property("layoutDirection").cacheable(),displayProperties:"maximum isEnabled layoutDirection".w(),render:function(context,firstTime){var max=this.get("maximum");
switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:context.addClass("sc-vertical");
if(firstTime){context.push('<div class="sc-inner" style="height: %@px;">&nbsp;</div>'.fmt(max));
}else{this.$("div")[0].style.height=max+"px";}break;case SC.LAYOUT_HORIZONTAL:context.addClass("sc-horizontal");
if(firstTime){context.push('<div class="sc-inner" style="width: %@px;">&nbsp;</div>'.fmt(max));
}else{this.$("div")[0].style.width=max+"px";}break;default:throw"You must set a layoutDirection for your scroller class.";
}context.setClass("disabled",!this.get("isEnabled"));},didCreateLayer:function(){var callback=this._sc_scroller_scrollDidChange;
SC.Event.add(this.$(),"scroll",this,callback);var amt=this.get("value");var layer=this.get("layer");
switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:layer.scrollTop=amt;break;
case SC.LAYOUT_HORIZONTAL:layer.scrollLeft=amt;break;}},willDestroyLayer:function(){var callback=this._sc_scroller_scrollDidChange;
SC.Event.remove(this.$(),"scroll",this,callback);},_sc_scroller_armScrollTimer:function(){if(!this._sc_scrollTimer){SC.RunLoop.begin();
var method=this._sc_scroller_scrollDidChange;this._sc_scrollTimer=this.invokeLater(method,50);
SC.RunLoop.end();}},_sc_scroller_scrollDidChange:function(){var now=Date.now(),last=this._sc_lastScroll;
if(last&&(now-last)<50){return this._sc_scroller_armScrollTimer();}this._sc_scrollTimer=null;
this._sc_lastScroll=now;SC.RunLoop.begin();if(!this.get("isEnabled")){return;}var layer=this.get("layer"),scroll=0;
switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:this._sc_scrollValue=scroll=layer.scrollTop;
break;case SC.LAYOUT_HORIZONTAL:this._sc_scrollValue=scroll=layer.scrollLeft;break;
}this.set("value",scroll);SC.RunLoop.end();},_sc_scroller_valueDidChange:function(){var v=this.get("value");
if(v!==this._sc_scrollValue){var layer=this.get("layer");if(layer){switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:layer.scrollTop=v;
break;case SC.LAYOUT_HORIZONTAL:layer.scrollLeft=v;break;}}}}.observes("value")});
sc_require("views/scroller");sc_require("mixins/border");SC.ScrollView=SC.View.extend(SC.Border,{classNames:["sc-scroll-view"],isScrollable:YES,contentView:null,horizontalScrollOffset:0,verticalScrollOffset:0,maximumHorizontalScrollOffset:function(){if(!this.get("canScrollHorizontal")){return 0;
}var view=this.get("contentView");var contentWidth=view?view.get("frame").width:0;
if(view.calculatedWidth&&view.calculatedWidth!==0){contentWidth=view.calculatedWidth;
}var containerWidth=this.get("containerView").get("frame").width;return Math.max(0,contentWidth-containerWidth);
}.property(),maximumVerticalScrollOffset:function(){if(!this.get("canScrollVertical")){return 0;
}var view=this.get("contentView");var contentHeight=(view&&view.get("frame"))?view.get("frame").height:0;
if(view.calculatedHeight&&view.calculatedHeight!==0){contentHeight=view.calculatedHeight;
}var containerHeight=this.get("containerView").get("frame").height;return Math.max(0,contentHeight-containerHeight);
}.property(),verticalLineScroll:20,horizontalLineScroll:20,verticalPageScroll:function(){return this.get("frame").height;
}.property("frame"),horizontalPageScroll:function(){return this.get("frame").width;
}.property("frame"),hasHorizontalScroller:YES,horizontalScrollerView:SC.ScrollerView,isHorizontalScrollerVisible:YES,canScrollHorizontal:function(){return !!(this.get("hasHorizontalScroller")&&this.get("horizontalScrollerView")&&this.get("isHorizontalScrollerVisible"));
}.property("isHorizontalScrollerVisible").cacheable(),autohidesHorizontalScroller:YES,hasVerticalScroller:YES,verticalScrollerView:SC.ScrollerView,isVerticalScrollerVisible:YES,canScrollVertical:function(){return !!(this.get("hasVerticalScroller")&&this.get("verticalScrollerView")&&this.get("isVerticalScrollerVisible"));
}.property("isVerticalScrollerVisible").cacheable(),autohidesVerticalScroller:YES,verticalScrollerBottom:0,containerView:SC.ContainerView,scrollTo:function(x,y){if(y===undefined&&SC.typeOf(x)===SC.T_HASH){y=x.y;
x=x.x;}if(!SC.none(x)){x=Math.max(0,Math.min(this.get("maximumHorizontalScrollOffset"),x));
this.set("horizontalScrollOffset",x);}if(!SC.none(y)){y=Math.max(0,Math.min(this.get("maximumVerticalScrollOffset"),y));
this.set("verticalScrollOffset",y);}return this;},scrollBy:function(x,y){if(y===undefined&&SC.typeOf(x)===SC.T_HASH){y=x.y;
x=x.x;}x=(x)?this.get("horizontalScrollOffset")+x:null;y=(y)?this.get("verticalScrollOffset")+y:null;
return this.scrollTo(x,y);},scrollToVisible:function(view){if(arguments.length===0){return arguments.callee.base.apply(this,arguments);
}var contentView=this.get("contentView");if(!contentView){return NO;}var vf=view.get("frame");
if(!vf){return NO;}vf=contentView.convertFrameFromView(vf,view.get("parentView"));
var vo=SC.cloneRect(this.get("containerView").get("frame"));vo.x=this.get("horizontalScrollOffset");
vo.y=this.get("verticalScrollOffset");var origX=vo.x,origY=vo.y;vo.y-=Math.max(0,SC.minY(vo)-SC.minY(vf));
vo.x-=Math.max(0,SC.minX(vo)-SC.minX(vf));vo.y+=Math.max(0,SC.maxY(vf)-SC.maxY(vo));
vo.x+=Math.max(0,SC.maxX(vf)-SC.maxX(vo));if((origX!==vo.x)||(origY!==vo.y)){this.scrollTo(vo.x,vo.y);
return YES;}else{return NO;}},scrollDownLine:function(lines){if(lines===undefined){lines=1;
}return this.scrollBy(null,this.get("verticalLineScroll")*lines);},scrollUpLine:function(lines){if(lines===undefined){lines=1;
}return this.scrollBy(null,0-this.get("verticalLineScroll")*lines);},scrollRightLine:function(lines){if(lines===undefined){lines=1;
}return this.scrollTo(this.get("horizontalLineScroll")*lines,null);},scrollLeftLine:function(lines){if(lines===undefined){lines=1;
}return this.scrollTo(0-this.get("horizontalLineScroll")*lines,null);},scrollDownPage:function(pages){if(pages===undefined){pages=1;
}return this.scrollBy(null,this.get("verticalPageScroll")*pages);},scrollUpPage:function(pages){if(pages===undefined){pages=1;
}return this.scrollBy(null,0-(this.get("verticalPageScroll")*pages));},scrollRightPage:function(pages){if(pages===undefined){pages=1;
}return this.scrollBy(this.get("horizontalPageScroll")*pages,null);},scrollLeftPage:function(pages){if(pages===undefined){pages=1;
}return this.scrollBy(0-(this.get("horizontalPageScroll")*pages),null);},tile:function(){var hscroll=this.get("hasHorizontalScroller")?this.get("horizontalScrollerView"):null;
var hasHorizontal=hscroll&&this.get("isHorizontalScrollerVisible");var vscroll=this.get("hasVerticalScroller")?this.get("verticalScrollerView"):null;
var hasVertical=vscroll&&this.get("isVerticalScrollerVisible");var clip=this.get("containerView");
var clipLayout={left:0,top:0};var t;var ht=((hasHorizontal)?hscroll.get("scrollerThickness"):0);
var vt=(hasVertical)?vscroll.get("scrollerThickness"):0;if(hasHorizontal){hscroll.set("layout",{left:0,bottom:0,right:vt-1,height:ht});
clipLayout.bottom=ht-1;}else{clipLayout.bottom=0;}if(hscroll){hscroll.set("isVisible",hasHorizontal);
}if(hasVertical){ht=ht+this.get("verticalScrollerBottom");vscroll.set("layout",{top:0,bottom:ht,right:0,width:vt});
clipLayout.right=vt-1;}else{clipLayout.right=0;}if(vscroll){vscroll.set("isVisible",hasVertical);
}clip.set("layout",clipLayout);},scrollerVisibilityDidChange:function(){this.tile();
}.observes("isVerticalScrollerVisible","isHorizontalScrollerVisible"),_scroll_wheelDeltaX:0,_scroll_wheelDeltaY:0,mouseWheel:function(evt){this._scroll_wheelDeltaX+=evt.wheelDeltaX;
this._scroll_wheelDeltaY+=evt.wheelDeltaY;this.invokeLater(this._scroll_mouseWheel,10);
return this.get("canScrollHorizontal")||this.get("canScrollVertical");},_scroll_mouseWheel:function(){this.scrollBy(this._scroll_wheelDeltaX,this._scroll_wheelDeltaY);
this._scroll_wheelDeltaX=this._scroll_wheelDeltaY=0;},createChildViews:function(){var childViews=[],view;
if(SC.none(view=this.containerView)){view=SC.ContainerView;}childViews.push(this.containerView=this.createChildView(view,{contentView:this.contentView}));
this.contentView=this.containerView.get("contentView");if(view=this.horizontalScrollerView){if(this.get("hasHorizontalScroller")){view=this.horizontalScrollerView=this.createChildView(view,{layoutDirection:SC.LAYOUT_HORIZONTAL,valueBinding:"*owner.horizontalScrollOffset"});
childViews.push(view);}else{this.horizontalScrollerView=null;}}if(view=this.verticalScrollerView){if(this.get("hasVerticalScroller")){view=this.verticalScrollerView=this.createChildView(view,{layoutDirection:SC.LAYOUT_VERTICAL,valueBinding:"*owner.verticalScrollOffset"});
childViews.push(view);}else{this.verticalScrollerView=null;}}this.childViews=childViews;
this.contentViewDidChange();this.tile();},init:function(){arguments.callee.base.apply(this,arguments);
this._scroll_contentView=this.get("contentView");var contentView=this._scroll_contentView;
if(contentView){contentView.addObserver("frame",this,this.contentViewFrameDidChange);
}if(this.get("isVisibleInWindow")){this._scsv_registerAutoscroll();}},_scsv_registerAutoscroll:function(){if(this.get("isVisibleInWindow")){SC.Drag.addScrollableView(this);
}else{SC.Drag.removeScrollableView(this);}}.observes("isVisibleInWindow"),contentViewDidChange:function(){var newView=this.get("contentView"),oldView=this._scroll_contentView;
var f=this.contentViewFrameDidChange;if(newView!==oldView){if(oldView){oldView.removeObserver("frame",this,f);
}this._scroll_contentView=newView;if(newView){newView.addObserver("frame",this,f);
}this.containerView.set("contentView",newView);this.contentViewFrameDidChange();}}.observes("contentView"),oldMaxHOffset:0,oldMaxVOffset:0,contentViewFrameDidChange:function(){var view=this.get("contentView"),f=(view)?view.get("frame"):null,width=(f)?f.width:0,height=(f)?f.height:0,dim=this.get("frame");
this._scroll_contentWidth=width;this._scroll_contentHeight=height;if(this.get("hasHorizontalScroller")&&(view=this.get("horizontalScrollerView"))){width-=1;
if(this.get("autohidesHorizontalScroller")){this.set("isHorizontalScrollerVisible",width>dim.width);
}view.setIfChanged("maximum",width);}if(this.get("hasVerticalScroller")&&(view=this.get("verticalScrollerView"))){height-=1;
if(this.get("autohidesVerticalScroller")){this.set("isVerticalScrollerVisible",height>dim.height);
}height-=this.get("verticalScrollerBottom");view.setIfChanged("maximum",height);}if(!this.get("isVerticalScrollerVisible")&&(this.get("verticalScrollOffset")!==0)&&this.get("autohidesVerticalScroller")){this.set("verticalScrollOffset",0);
}if(!this.get("isHorizontalScrollerVisible")&&(this.get("horizontalScrollOffset")!==0)&&this.get("autohidesHorizontalScroller")){this.set("horizontalScrollOffset",0);
}var mxVOffSet=this.get("maximumVerticalScrollOffset"),vOffSet=this.get("verticalScrollOffset"),mxHOffSet=this.get("maximumHorizontalScrollOffset"),hOffSet=this.get("horizontalScrollOffset");
var forceHeight=mxVOffSet<vOffSet;var forceWidth=mxHOffSet<hOffSet;if(forceHeight||forceWidth){this.forceDimensionsRecalculation(forceWidth,forceHeight,vOffSet,hOffSet);
}},_scroll_horizontalScrollOffsetDidChange:function(){var offset=this.get("horizontalScrollOffset");
offset=Math.max(0,Math.min(this.get("maximumHorizontalScrollOffset"),offset));var contentView=this.get("contentView");
if(contentView){contentView.adjust("left",0-offset);}}.observes("horizontalScrollOffset"),_scroll_verticalScrollOffsetDidChange:function(){var offset=this.get("verticalScrollOffset");
offset=Math.max(0,Math.min(this.get("maximumVerticalScrollOffset"),offset));var contentView=this.get("contentView");
var containerView=this.get("containerView");if(contentView){contentView.adjust("top",0-offset);
}}.observes("verticalScrollOffset"),forceDimensionsRecalculation:function(forceWidth,forceHeight,vOffSet,hOffSet){var oldScrollHOffset=hOffSet;
var oldScrollVOffset=vOffSet;this.scrollTo(0,0);if(forceWidth&&forceHeight){this.scrollTo(this.get("maximumHorizontalScrollOffset"),this.get("maximumVerticalScrollOffset"));
}if(forceWidth&&!forceHeight){this.scrollTo(this.get("maximumHorizontalScrollOffset"),oldScrollVOffset);
}if(!forceWidth&&forceHeight){this.scrollTo(oldScrollHOffset,this.get("maximumVerticalScrollOffset"));
}}});tiki.script("sproutcore/desktop:en/0a67032b44fccf8f11160e96135230830ba8b945/javascript.js");
tiki.register("sproutcore",{"depends":["sproutcore/desktop"],"packages":{"sproutcore/desktop":{}},"scripts":[{"url":"/static/sproutcore/en/95f7b4c6a721469760d266a255fa6c3b793250e6/javascript.js","id":"sproutcore:en/95f7b4c6a721469760d266a255fa6c3b793250e6/javascript.js"}]});
tiki.global("sproutcore");
/* @license
==========================================================================
SproutCore -- JavaScript Application Framework
copyright 2006-2008, Sprout Systems, Inc. and contributors.

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.

For more information about SproutCore, visit http://www.sproutcore.com


==========================================================================
@license */
tiki.script("sproutcore:en/95f7b4c6a721469760d266a255fa6c3b793250e6/javascript.js");
tiki.register("sproutcore/empty_theme",{"scripts":[{"url":"/static/sproutcore/empty_theme/en/21c3b7b16d7ef39d60d2651975590828812f3ad9/javascript.js","id":"sproutcore/empty_theme:en/21c3b7b16d7ef39d60d2651975590828812f3ad9/javascript.js"}]});
tiki.global("sproutcore/empty_theme");tiki.script("sproutcore/empty_theme:en/21c3b7b16d7ef39d60d2651975590828812f3ad9/javascript.js");
tiki.register("sproutcore/standard_theme",{"depends":["sproutcore/empty_theme"],"packages":{"sproutcore/empty_theme":{}},"scripts":[{"url":"/static/sproutcore/standard_theme/en/4448cf3c8117a1e50376695dc8ea12138b0f9099/javascript.js","id":"sproutcore/standard_theme:en/4448cf3c8117a1e50376695dc8ea12138b0f9099/javascript.js"}]});
tiki.global("sproutcore/standard_theme");tiki.script("sproutcore/standard_theme:en/4448cf3c8117a1e50376695dc8ea12138b0f9099/javascript.js");
tiki.register("bespin",{"depends":["tiki","tiki/system","core_test","sproutcore","sproutcore/empty_theme","sproutcore/standard_theme"],"packages":{"sproutcore/empty_theme":{},"core_test":{},"sproutcore/standard_theme":{},"tiki/system":{},"sproutcore":{},"tiki":{}},"scripts":[{"url":"/static/bespin/en/163e0975202cdb540ae3a5016e0151448aed01e0/javascript.js","id":"bespin:en/163e0975202cdb540ae3a5016e0151448aed01e0/javascript.js"}]});
tiki.module("bespin:actions",function(require,exports,module){var bespin=require("package");
var SC=require("sproutcore/runtime:package").SC;var cursor=require("cursor");var clipboard=require("util/clipboard");
bespin.get("settings").addSetting({name:"tabmode",type:"boolean",defaultValue:false});
bespin.get("settings").addSetting({name:"closepairs",type:"boolean",defaultValue:false});
exports.Actions=SC.Object.extend({editor:null,ignoreRepaints:false,currentEditItem:undefined,editDepth:0,beginEdit:function(name){if(this.editDepth==0){this.currentEditItem=exports.ActionHistoryItem.create({name:name,editor:this.editor});
this.currentEditItem.begin();}this.editDepth++;},endEdit:function(){if(this.editDepth<=0){return;
}this.editDepth--;if(this.editDepth==0){this.currentEditItem.end();this.editor.historyManager.add(this.currentEditItem);
this.currentEditItem=undefined;}},handleCursorSelection:function(args){if(args.event.shiftKey){if(!this.editor.selection){this.editor.setSelection({startPos:cursor.copyPos(args.pos)});
}this.editor.setSelection({startPos:this.editor.selection.startPos,endPos:cursor.copyPos(this.editor.cursorManager.getCursorPosition())});
}else{this.editor.setSelection(undefined);}},moveCursor:function(moveType,args){var posData=this.editor.cursorManager[moveType](args);
this.handleCursorSelection(args);this.repaint();args.pos=posData.newPos;return args;
},moveCursorLeft:function(args){return this.moveCursor("moveLeft",args);},moveCursorRight:function(args){return this.moveCursor("moveRight",args);
},moveCursorUp:function(args){return this.moveCursor("moveUp",args);},moveCursorDown:function(args){return this.moveCursor("moveDown",args);
},moveToLineStart:function(args){return this.moveCursor("moveToLineStart",args);},moveToLineEnd:function(args){return this.moveCursor("moveToLineEnd",args);
},moveToFileTop:function(args){return this.moveCursor("moveToTop",args);},moveToFileBottom:function(args){return this.moveCursor("moveToBottom",args);
},movePageUp:function(args){return this.moveCursor("movePageUp",args);},movePageDown:function(args){return this.moveCursor("movePageDown",args);
},moveWordLeft:function(args){return this.moveCursor("smartMoveLeft",args);},moveWordRight:function(args){return this.moveCursor("smartMoveRight",args);
},deleteWordLeft:function(args){this.beginEdit("deleteWordLeft");this.deleteChunk({endPos:args.pos,pos:this.moveCursor("smartMoveLeft",args).pos});
this.endEdit();return args;},deleteWordRight:function(args){this.beginEdit("deleteWordRight");
this.deleteChunk({pos:args.pos,endPos:this.moveCursor("smartMoveRight",args).pos});
this.endEdit();return args;},applyState:function(state){if(this.testHistory.length==0){return;
}else{if(state<0){state=-1;}else{if(state>=this.testHistory.length){return;}}}this.testHistoryPosition=state;
var item=this.testHistory[Math.max(0,this.testHistoryPosition)];var modelState=item.after;
var editorState=item.uiAfter;if(state<0){modelState=item.before;editorState=item.uiBefore;
}this.editor.model.applyState(modelState);this.editor.setState(editorState);},undo:function(){this.editor.historyManager.undo();
},redo:function(){this.editor.historyManager.redo();},selectAll:function(args){if(this.editor.model.isEmpty()){return;
}args.startPos={row:0,col:0};args.endPos={row:this.editor.model.getRowCount()-1,col:this.editor.editorView.getRowScreenLength(this.editor.model.getRowCount()-1)};
this.select(args);},select:function(args){if(args.startPos){this.editor.setSelection({startPos:args.startPos,endPos:args.endPos});
this.editor.cursorManager.moveCursor(args.endPos);}else{this.editor.setSelection(undefined);
}},insertTab:function(args){if(this.editor.readonly){return;}var settings=bespin.get("settings");
if(this.editor.getSelection()&&!args.undoInsertTab){this.indent(args);return;}var tab=args.tab;
var tablength=this.editor.cursorManager.getCharacterLength("\t");if(!tab||!tablength){if(settings.values.tabmode){tab="\t";
}else{tab="";var tabSizeCount=tablength;while(tabSizeCount-->0){tab+=" ";}tablength=tab.length;
}}this.beginEdit("insertTab");delete this.editor.selection;this.editor.model.insertCharacters(this.editor.cursorManager.getModelPosition({row:args.pos.row,col:args.pos.col}),tab);
this.editor.cursorManager.moveCursor({row:args.pos.row,col:args.pos.col+tablength});
this.repaint();this.endEdit();},indent:function(args){this.beginEdit("indent");var settings=bespin.get("settings");
var selection=this.editor.getSelection();var unsetSelection=false;if(selection===undefined){unsetSelection=true;
var cursorPos=this.editor.getCursorPos();var modelPos=this.editor.getModelPos();selection={startPos:{row:cursorPos.row,col:0},endPos:{row:cursorPos.row,col:this.editor.model.getRowMetadata(cursorPos.row).lineLength},startModelPos:{row:modelPos.row,col:0},endModelPos:{row:modelPos.row,col:this.editor.model.getRowMetadata(modelPos.row).lineLengthWithoutTabExpansion}};
this.editor.setSelection(selection);}var startRow=selection.startPos.row;var endRow=selection.endPos.row;
var endRowLength=this.editor.cursorManager.getStringLength(this.editor.model.getRowArray(endRow).join(""));
var cursorRowLength=this.editor.cursorManager.getStringLength(this.editor.model.getRowArray(args.pos.row).join(""));
var charsToInsert;var tab="";if(settings.values.tabmode){tab="\t";}else{var tabsize=this.editor.getTabSize();
while(tabsize-->0){tab+=" ";}}for(var y=startRow;y<=endRow;y++){if(tab!="\t"){charsToInsert=this.editor.cursorManager.getLeadingWhitespace(y);
charsToInsert=this.editor.cursorManager.getNextTablevelRight(charsToInsert)-charsToInsert;
charsToInsert=tab.substring(0,charsToInsert);}else{charsToInsert="\t";}this.editor.model.insertCharacters(this.editor.cursorManager.getModelPosition({row:y,col:0}),charsToInsert);
}var delta=this.editor.cursorManager.getStringLength(this.editor.model.getRowArray(args.pos.row).join(""))-cursorRowLength;
selection.endPos.col+=this.editor.cursorManager.getStringLength(this.editor.model.getRowArray(endRow).join(""))-endRowLength;
this.editor.setSelection(selection);this.editor.cursorManager.moveCursor({col:args.pos.col+delta});
if(unsetSelection){this.editor.setSelection(undefined);}this.repaint();this.endEdit();
},unindent:function(args){this.beginEdit("unindent");var selection=this.editor.getSelection();
var unsetSelection=false;if(selection===undefined){unsetSelection=true;var cursorPos=this.editor.getCursorPos();
var modelPos=this.editor.getModelPos();selection={startPos:{row:cursorPos.row,col:0},endPos:{row:cursorPos.row,col:this.editor.model.getRowMetadata(cursorPos.row).lineLength},startModelPos:{row:modelPos.row,col:0},endModelPos:{row:modelPos.row,col:this.editor.model.getRowMetadata(modelPos.row).lineLengthWithoutTabExpansion}};
this.editor.setSelection(selection);}var startRow=selection.startPos.row;var endRow=selection.endPos.row;
var endRowLength=this.editor.cursorManager.getStringLength(this.editor.model.getRowArray(endRow).join(""));
var row=false;var charsToDelete;var charsWidth;for(var y=startRow;y<=endRow;y++){row=this.editor.model.getRowArray(y);
if(row.length>0&&row[0]=="\t"){charsToDelete=1;charsWidth=this.editor.getTabSize();
}else{var leadingWhitespaceLength=this.editor.cursorManager.getLeadingWhitespace(y);
charsToDelete=this.editor.cursorManager.getContinuousSpaceCount(0,this.editor.getTabSize(),y);
charsWidth=charsToDelete;}if(charsToDelete){this.editor.model.deleteCharacters(this.editor.cursorManager.getModelPosition({row:y,col:0}),charsToDelete);
}if(y==startRow){selection.startPos.col=Math.max(0,selection.startPos.col-charsWidth);
}if(y==endRow){if(!row){row=this.editor.model.getRowArray(y);}var delta=endRowLength-this.editor.cursorManager.getStringLength(row.join(""));
selection.endPos.col=Math.max(0,selection.endPos.col-delta);args.pos.col=Math.max(0,args.pos.col-delta);
}}this.editor.setSelection(selection);this.editor.cursorManager.moveCursor({col:args.pos.col});
if(unsetSelection){this.editor.setSelection(undefined);}this.repaint();this.endEdit();
},cutSelection:function(args){if(this.editor.readonly){return;}this.beginEdit("cut");
this.copySelection(args);this.deleteSelection(args);this.endEdit();},copySelection:function(args){var selectionObject=this.editor.getSelection();
if(selectionObject){var selectionText=this.editor.model.getChunk(selectionObject);
if(selectionText){clipboard.manual.copy(selectionText);}}},pasteFromClipboard:function(args){if(this.editor.readonly){return;
}var data=(args.clipboard)?args.clipboard:clipboard.manual.data();if(data===undefined){return;
}args.chunk=data;this.beginEdit("paste");this.insertChunk(args);this.endEdit();},insertChunk:function(args){if(this.editor.readonly){return;
}this.beginEdit("insertChunk");if(this.editor.selection){this.deleteSelection();}var pos=cursor.copyPos(this.editor.cursorManager.getCursorPosition());
pos=this.editor.model.insertChunk(this.editor.cursorManager.getModelPosition(pos),args.chunk);
pos=this.editor.cursorManager.getCursorPosition(pos);this.editor.cursorManager.moveCursor(pos);
this.repaint();this.endEdit();return pos;},deleteChunk:function(args){if(this.editor.readonly){return;
}this.beginEdit("deleteChunk");var startPos=(args.startPos!=undefined)?args.startPos:cursor.copyPos(args.pos);
var selection=this.editor.getSelection({startPos:startPos,endPos:args.endPos});var chunk=this.editor.model.deleteChunk(selection);
this.editor.cursorManager.moveCursor(selection.startPos);this.editor.setSelection(undefined);
this.repaint();this.endEdit();return selection.startPos;},joinLine:function(args){if(this.editor.readonly){return;
}this.beginEdit("joinLine");if(args.joinDirection=="up"){if(args.pos.row==0){return;
}var newcol=this.editor.editorView.getRowScreenLength(args.pos.row-1);this.editor.model.joinRow(args.pos.row-1);
this.editor.cursorManager.moveCursor({row:args.pos.row-1,col:newcol});}else{if(args.pos.row>=this.editor.model.getRowCount()-1){return;
}this.editor.model.joinRow(args.pos.row);}this.endEdit();this.repaint();},killLine:function(args){if(this.editor.readonly){return;
}this.beginEdit("killLine");this.editor.setSelection({startPos:{row:args.pos.row,col:0},endPos:{row:args.pos.row+1,col:0}});
this.cutSelection(args);this.endEdit();},deleteSelection:function(args){if(this.editor.readonly){return;
}var selection=this.editor.getSelection();return this.deleteChunk({startPos:selection.startPos,endPos:selection.endPos,clearSelection:true});
},backspace:function(args){if(this.editor.readonly){return;}this.beginEdit("backspace");
if(this.editor.selection){this.deleteSelection(args);}else{if(args.pos.col>0){var settings=bespin.get("settings");
if(settings.values.smartmove){var tabsize=this.editor.getTabSize();var freeSpaces=this.editor.cursorManager.getContinuousSpaceCount(args.pos.col,this.editor.cursorManager.getNextTablevelLeft(args.pos.col));
if(freeSpaces==tabsize){var pos=args.pos;this.editor.selection={startPos:{row:pos.row,col:pos.col-tabsize},endPos:{row:pos.row,col:pos.col}};
this.deleteSelection(args);this.endEdit();return;}}this.editor.cursorManager.moveCursor({col:Math.max(0,args.pos.col-1)});
args.pos.col-=1;this.deleteCharacter(args);}else{args.joinDirection="up";this.joinLine(args);
}}this.endEdit();},deleteKey:function(args){if(this.editor.readonly){return;}this.beginEdit("deleteKey");
if(this.editor.selection){this.deleteSelection(args);}else{if(args.pos.col<this.editor.editorView.getRowScreenLength(args.pos.row)){var settings=bespin.get("settings");
if(settings.values.smartmove){var tabsize=this.editor.getTabSize();var freeSpaces=this.editor.cursorManager.getContinuousSpaceCount(args.pos.col,this.editor.cursorManager.getNextTablevelRight(args.pos.col));
if(freeSpaces==tabsize){var pos=args.pos;this.editor.selection={startPos:{row:pos.row,col:pos.col},endPos:{row:pos.row,col:pos.col+tabsize}};
this.deleteSelection(args);this.endEdit();return;}}this.deleteCharacter(args);}else{args.joinDirection="down";
this.joinLine(args);}}this.endEdit();},deleteCharacter:function(args){if(this.editor.readonly){return;
}if(args.pos.col<this.editor.editorView.getRowScreenLength(args.pos.row)){this.beginEdit("deleteCharacter");
var modelPos=this.editor.cursorManager.getModelPosition(args.pos);var length=1;var deleted=this.editor.model.deleteCharacters(modelPos,length);
this.repaint();this.endEdit();}},newline:function(args){if(this.editor.readonly){return;
}var settings=bespin.get("settings");var autoindent;if(settings.values.autoindent){autoindent=bespin.util.leadingWhitespace(this.editor.model.getRowArray(args.pos.row));
}else{autoindent=[];}args.chunk="\n"+autoindent.join("");this.insertChunk(args);},newlineBelow:function(args){this.newline(this.moveToLineEnd(args));
},insertCharacter:function(args){if(this.editor.readonly){return;}this.beginEdit("insertCharacter");
var pos=args.pos;if(this.editor.selection){pos=this.deleteSelection(args);}this.editor.model.insertCharacters(this.editor.cursorManager.getModelPosition(pos),args.newchar);
this.editor.cursorManager.moveRight(true);var settings=bespin.get("settings");if(settings.values.closepairs){switch(args.newchar){case"(":this.editor.model.insertCharacters(this.editor.cursorManager.getModelPosition(),")");
break;case"[":this.editor.model.insertCharacters(this.editor.cursorManager.getModelPosition(),"]");
break;case"{":this.editor.model.insertCharacters(this.editor.cursorManager.getModelPosition(),"}");
break;case"<":break;case'"':break;case"'":break;}}this.repaint();this.endEdit();},moveCursorRowToCenter:function(args){var saveCursorRow=this.editor.getCursorPos().row;
var halfRows=Math.floor(this.editor.ui.visibleRows/2);if(saveCursorRow>(this.editor.ui.firstVisibleRow+halfRows)){this.editor.cursorManager.moveCursor({row:this.editor.getCursorPos().row+halfRows});
}else{this.editor.cursorManager.moveCursor({row:this.editor.getCursorPos().row-halfRows});
}this.editor.editorView.ensureCursorVisible();this.editor.cursorManager.moveCursor({row:saveCursorRow});
},getOppositeCase:function(stringCase){if(!stringCase){return undefined;}switch(stringCase){case"u":return"l";
case"l":return"u";}},selectionChangeCase:function(args){if(this.editor.readonly){return;
}if(this.editor.selection){this.beginEdit("selectionChangeCase");if(!args.selectionObject){args.selectionObject=this.editor.getSelection();
}var selection=this.editor.model.getChunk(args.selectionObject);var stringArray=selection.split("\n");
for(var i in stringArray){switch(args.stringCase){case"l":stringArray[i]=stringArray[i].toLowerCase();
break;case"u":stringArray[i]=stringArray[i].toUpperCase();break;}}var outText=stringArray.join("\n");
this.editor.model.deleteChunk(args.selectionObject);this.editor.model.insertChunk(args.selectionObject.startModelPos,outText);
this.select(args.selectionObject);this.endEdit();}},startSearch:function(str,displayType,shiftKey){if(str==""){this.editor.ui.setSearchString(false);
this.editor.paint(true);document.getElementById("searchresult").style.display="none";
return false;}if(str==this.editor.ui.searchString&&displayType=="toolbar"){if(!shiftKey){this.findNext();
}else{this.findPrev();}document.getElementById("searchresult").style.display="block";
return;}this.editor.ui.setSearchString(str);var count=this.editor.model.getCountOfString(str);
if(count!=0){var pos=cursor.copyPos(this.editor.cursorManager.getCursorPosition());
if(!this.editor.ui.actions.findNext(null,true)){this.editor.cursorManager.moveCursor({col:0,row:0});
this.editor.ui.actions.findNext();}}var msg;switch(displayType){case"commandLine":msg="Found "+count+" match";
if(count>1){msg+="es";}msg+=" for your search for <em>"+str+"</em>";bespin.get("commandLine").showHint(msg);
break;case"searchwindow":var filesearch=bespin.get("filesearch");if(filesearch){filesearch.setMatchesCount(count);
}break;case"toolbar":msg=+count+" Match";if(count>1){msg+="es";}document.getElementById("searchfeedback").innerHTML=msg;
document.getElementById("searchresult").style.display="block";break;}this.editor.paint(true);
},findNext:function(event,canBeSamePosition){if(!this.editor.ui.searchString){return;
}var pos=cursor.copyPos(this.editor.cursorManager.getModelPosition());var sel=this.editor.getSelection();
if(canBeSamePosition&&sel!==undefined){pos.col-=sel.endModelPos.col-sel.startModelPos.col+1;
}var found=this.editor.model.findNext(pos.row,pos.col,this.editor.ui.searchString);
if(!found){found=this.editor.model.findNext(0,0,this.editor.ui.searchString);}if(found){this.editor.setSelection({startPos:this.editor.cursorManager.getCursorPosition(found.startPos),endPos:this.editor.cursorManager.getCursorPosition(found.endPos)});
this.editor.cursorManager.moveCursor(this.editor.cursorManager.getCursorPosition(found.endPos));
this.editor.editorView.ensureCursorVisible(true);this.repaint();return true;}else{return false;
}},findPrev:function(){if(!this.editor.ui.searchString){return;}var pos=this.editor.cursorManager.getModelPosition();
var found=this.editor.model.findPrev(pos.row,pos.col,this.editor.ui.searchString);
if(!found){var lastRow=this.editor.model.getRowCount()-1;found=this.editor.model.findPrev(lastRow,this.editor.model.getRowArray(lastRow).length-1,this.editor.ui.searchString);
}if(found){this.editor.setSelection({startPos:this.editor.cursorManager.getCursorPosition(found.startPos),endPos:this.editor.cursorManager.getCursorPosition(found.endPos)});
this.editor.cursorManager.moveCursor(this.editor.cursorManager.getCursorPosition(found.endPos));
this.editor.editorView.ensureCursorVisible(true);this.repaint();return true;}else{return false;
}},escape:function(){bespin.publish("ui:escape");if(this.editor.ui.searchString){this.editor.ui.setSearchString(false);
}},toggleQuickopen:function(){var quickopen=bespin.get("quickopen");if(quickopen){quickopen.toggle();
}},togglePieMenu:function(){bespin.getComponent("piemenu",function(piemenu){piemenu.toggle();
});},focusCommandline:function(){bespin.getComponent("popup",function(popup){popup.show("output","Command Line");
});},focusFileBrowser:function(){bespin.getComponent("popup",function(popup){popup.show("files","File Explorer");
});},repaint:function(){if(!this.ignoreRepaints){this.editor.editorView.ensureCursorVisible();
this.editor.paint();}},replace:function(args){this.beginEdit("replace");this.editor.model.replace(args.search,args.replace);
this.repaint();this.endEdit();},gotoLine:function(){bespin.getComponent("commandLine",function(cli){cli.setCommandText("goto ");
bespin.getComponent("popup",function(popup){popup.show("output");});});},cmdFilesearch:function(){bespin.getComponent("commandLine",function(cli){cli.setCommandText("search ");
bespin.getComponent("popup",function(popup){popup.show("output");});});},previousFile:function(){bespin.get("editSession").goToPreviousFile();
},nextFile:function(){bespin.get("editSession").goToNextFile();}});exports.ActionHistoryItem=SC.Object.extend({begin:function(editor,model){this.startIndex=this.editor.historyManager.getCurrent();
if(editor){this.editorBefore=editor;}else{this.editorBefore=this.editor.getState();
}if(model){this.modelBefore=model;}else{this.modelBefore=this.editor.model.getState();
}},end:function(editor,model){this.editor.historyManager.truncate(this.startIndex);
if(editor){this.editorAfter=editor;}else{this.editorAfter=this.editor.getState();
}if(model){this.modelAfter=model;}else{this.modelAfter=this.editor.model.getState();
}},undo:function(){this.editor.model.applyState(this.modelBefore);this.editor.setState(this.editorBefore);
this.editor.editorView.ensureCursorVisible();this.editor.paint();},redo:function(){this.editor.model.applyState(this.modelAfter);
this.editor.setState(this.editorAfter);this.editor.editorView.ensureCursorVisible();
this.editor.paint();}});});tiki.module("bespin:boot",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var embed=tiki.require("bespin:embed");SC.ready(function(){var nodes=document.querySelectorAll(".bespin");
for(var i=0;i<nodes.length;i++){var node=nodes[i];var options=node.getAttribute("data-bespinoptions");
var bespin=embed.useBespin(node,JSON.parse(options));node.bespin=bespin;}if(window.onBespinLoad){window.onBespinLoad();
}});window.onload=SC.didLoad;});tiki.module("bespin:builtins",function(require,exports,module){exports.metadata={"Base Syntax":{"provides":[{"ep":"extensionpoint","name":"syntax.engine","description":"Syntax highlighting engines"},{"ep":"syntax.engine","name":"simple","pointer":"bespin/syntax/simple:Model"},{"ep":"extensionpoint","name":"syntax.simple.highlighter","description":"Highlighter code for the simple syntax highlighter."},{"ep":"syntax.simple.highlighter","name":"JavaScript","extensions":["js","json","javascript","ecmascript","jsm","java"],"pointer":"bespin/syntax/simple/javascript:JavaScript"},{"ep":"syntax.simple.highlighter","name":"C","extensions":["c","h"],"pointer":"bespin/syntax/simple/c:C"},{"ep":"syntax.simple.highlighter","name":"CSharp","extensions":["cs"],"pointer":"bespin/syntax/simple/csharp:CSharp"},{"ep":"syntax.simple.highlighter","name":"CSS","extensions":["css"],"pointer":"bespin/syntax/simple/css:CSS"},{"ep":"syntax.simple.highlighter","name":"HTML","extensions":["html","htm","xml","xhtml","shtml"],"pointer":"bespin/syntax/simple/html:HTML"},{"ep":"syntax.simple.highlighter","name":"PHP","extensions":["php","php3","php4","php5"],"pointer":"bespin/syntax/simple/php:PHP"},{"ep":"syntax.simple.highlighter","name":"Python","extensions":["py","python"],"pointer":"bespin/syntax/simple/python:Python"},{"ep":"syntax.simple.highlighter","name":"Ruby","extensions":["rb","ruby"],"pointer":"bespin/syntax/simple/ruby:Ruby"}]},"bespin":{"provides":[{"ep":"extensionpoint","name":"startup","description":"A function that should be called at startup. This should be used sparingly, as these plugins will be eagerly loaded at the beginning. All that's needed for this extension point is a pointer to a function that takes no arguments.","activate":"plugins#startupHandler"},{"ep":"extensionpoint","name":"factory","description":"Provides a factory for singleton components. Each extension needs to provide a name, a pointer and an action. The action can be 'call' (if the pointer refers to a function), 'create' (if the pointer refers to an SC.Object), 'new' (if the pointer refers to a traditional JS object) or 'value' (if the pointer refers to the object itself that is the component).","indexOn":"name"},{"action":"call","pointer":"util/container#dummyFactory","name":"files","ep":"factory"},{"action":"create","pointer":"util/hub#Hub","name":"hub","ep":"factory"},{"action":"create","pointer":"settings#InMemorySettings","name":"settings","ep":"factory"},{"action":"call","pointer":"util/container#dummyFactory","name":"commandLine","ep":"factory"},{"action":"call","pointer":"util/container#dummyFactory","name":"parser","ep":"factory"},{"action":"create","pointer":"editor/controller#EditorController","name":"editor","ep":"factory"},{"action":"call","pointer":"util/container#dummyFactory","name":"editSession","ep":"factory"},{"action":"create","pointer":"cursor#CursorManager","name":"cursorManager","ep":"factory"}]}};
});tiki.module("bespin:command",function(require,exports,module){var bespin=require("package");
var SC=require("sproutcore/runtime:package").SC;var TokenObject=require("util/tokenobject").TokenObject;
exports.Store=SC.Object.extend({commands:{},aliases:{},command:null,parent:null,init:function(){if(this.parent){this.containerCommand=this.command;
this.command.takes=["*"];this.command.subcommands=this;this.parent.addCommand(this.command);
}},addCommand:function(command){if(!command){return;}command.parent=this;this.commands[command.name]=command;
if(command.takes&&Array.isArray(command.takes)){command=this.normalizeTakes(command);
}if(command.withKey){bespin.getComponent("editor",function(editor){editor.bindCommand(command.name,command.withKey);
});}if(command.aliases){command.aliases.forEach(function(alias){this.aliases[alias]=command.name;
},this);}command.getFullCommandName=function(){var name=this.name;if(this.parent){name=this.parent.getFullCommandName()+" "+name;
}return name.trim();};if(!command.findCompletions){command.findCompletions=function(query,callback){query.hint=this.completeText;
callback(query);};}},removeCommand:function(command){if(!command){return;}delete this.commands[command.name];
},getFullCommandName:function(){var name=this.containerCommand?this.containerCommand.name:"";
if(this.parent){name=this.parent.getFullCommandName()+" "+name;}return name.trim();
},filterOptionsByPrefix:function(options,prefix){return options.filter(function(option){return option.substr(0,prefix.length)===prefix;
});},findCommand:function(value){var parts=value.trim().split(/\s+/);var first=parts.shift();
var command=this.commands[first]||this.commands[this.aliases[first]];if(!command){if(parts.length>0){return null;
}else{return this;}}if(command.subcommands){return command.subcommands.findCommand(parts.join(" "));
}else{return command;}},findCompletions:function(query,callback){if(query.action.length>1){query.error="No matches";
callback(query);return;}var typed=query.action[0];if(typed.length==0&&this.parent==null){callback(query);
return;}var matches=[];for(var command in this.commands){if(command.indexOf(typed)==0){matches.push(command);
}}for(var alias in this.aliases){if(alias.indexOf(typed)==0){matches.push(alias);
}}if(matches.length==1){var newValue=matches[0];command=this.commands[newValue]||this.commands[this.aliases[newValue]];
if(this.commandTakesArgs(command)){newValue=newValue+" ";}query.autofill=query.prefix+newValue;
query.hint=command.preview;}else{if(matches.length==0){query.error="No matches";}else{matches.sort(function(a,b){return a.localeCompare(b);
});query.options=matches;}}callback(query);return;},commandTakesArgs:function(command){return command.takes!=undefined;
},getArgs:function(fromUser,command){if(!command.takes){return undefined;}var args;
var userString=fromUser.join(" ");if(command.takes["*"]){args=new TokenObject({input:userString});
args.rawinput=userString;args.varargs=args.pieces;}else{if(command.takes&&command.takes.order.length<2){args=userString;
}else{args=new TokenObject({input:userString,options:{params:command.takes.order.join(" ")}});
args.rawinput=userString;}}return args;},normalizeTakes:function(command){var takes=command.takes;
command.takes={order:takes};takes.forEach(function(item){command.takes[item]={"short":item[0]};
});return command;},getHelp:function(prefix,options){var commands=[];var command,name;
if(this.commands[prefix]){command=this.commands[prefix];commands.push(command.description?command.description:command.preview);
}else{var showHidden=false;var subcmdprefix="";if(this.containerCommand){subcmdprefix=" for "+this.containerCommand.name;
}if(prefix){if(prefix=="hidden"){prefix="";showHidden=true;}commands.push("<h2>Commands starting with '"+prefix+"':</h2>");
}else{commands.push("<h2>Available Commands:</h2>");}var tobesorted=[];for(name in this.commands){tobesorted.push(name);
}var sorted=tobesorted.sort();commands.push("<table>");for(var i=0;i<sorted.length;
i++){name=sorted[i];command=this.commands[name];if(!showHidden&&command.hidden){continue;
}if(prefix&&name.indexOf(prefix)!=0){continue;}var args=(command.takes)?" ["+command.takes.order.join("] [")+"]":"";
commands.push("<tr>");commands.push("<th>"+name+"</th>");commands.push("<td>"+command.preview+"</td>");
commands.push("<td>"+args+"</td>");commands.push("</tr>");}commands.push("</table>");
}var output=commands.join("");if(options&&options.prefix){output=options.prefix+"<br/>"+output;
}if(options&&options.suffix){output=output+"<br/>"+options.suffix;}return output;
}});exports.store=new exports.Store();exports.executeExtensionCommand=function(){var args=arguments;
var self=this;this.load(function(execute){execute.apply(self,args);});};bespin.subscribe("extension:loaded:bespin.command",function(ext){ext.execute=exports.command.executeExtensionCommand;
exports.store.addCommand(ext);});bespin.subscribe("extension:removed:bespin.command",function(ext){exports.store.removeCommand(ext);
});exports.store.addCommand({name:"help",takes:["search"],preview:"show commands",description:"The <u>help</u> gives you access to the various commands in the Bespin system.<br/><br/>You can narrow the search of a command by adding an optional search params.<br/><br/>If you pass in the magic <em>hidden</em> parameter, you will find subtle hidden commands.<br/><br/>Finally, pass in the full name of a command and you can get the full description, which you just did to see this!",completeText:"optionally, narrow down the search",execute:function(instruction,extra){var output=this.parent.getHelp(extra,{prefix:"<h2>Welcome to Bespin - Code in the Cloud</h2><ul>"+"<li><a href='http://labs.mozilla.com/projects/bespin' target='_blank'>Home Page</a>"+"<li><a href='https://wiki.mozilla.org/Labs/Bespin' target='_blank'>Wiki</a>"+"<li><a href='https://wiki.mozilla.org/Labs/Bespin/UserGuide' target='_blank'>User Guide</a>"+"<li><a href='https://wiki.mozilla.org/Labs/Bespin/Tips' target='_blank'>Tips and Tricks</a>"+"<li><a href='https://wiki.mozilla.org/Labs/Bespin/FAQ' target='_blank'>FAQ</a>"+"<li><a href='https://wiki.mozilla.org/Labs/Bespin/DeveloperGuide' target='_blank'>Developers Guide</a>"+"</ul>",suffix:"For more information, see the <a href='https://wiki.mozilla.org/Labs/Bespin'>Bespin Wiki</a>."});
instruction.addOutput(output);}});});tiki.module("bespin:cursor",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var bespin=require("package");exports.CursorManager=SC.Object.extend({init:function(){this.position={row:0,col:0};
this.virtualCol=0;arguments.callee.base.apply(this,arguments);},requires:{editor:"editor",settings:"settings",hub:"hub"},afterContainerInit:function(){this.settings.addSetting({name:"strictlines",type:"boolean",defaultValue:false});
this.settings.addSetting({name:"smartmove",type:"boolean",defaultValue:true});this.hub.subscribe("settings:set:strictlines",function(setting){if(setting.value){var oldPos=exports.copyPos(this.position);
this.checkPastEndOfLine(oldPos);}}.bind(this));},getCursorPosition:function(modelPos){if(modelPos==undefined){return this.position;
}var pos=exports.copyPos(modelPos);var line=[];if(this.editor.model.hasRow(pos.row)){line=this.editor.model.getRowArray(pos.row);
}var tabsize=this.editor.getTabSize();if(line.indexOf("\t")!=-1){var tabs=0,nottabs=0;
for(var i=0;i<modelPos.col;i++){if(line[i]=="\t"){pos.col+=tabsize-1-(nottabs%tabsize);
tabs++;nottabs=0;}else{nottabs++;tabs=0;}}}return pos;},getModelPosition:function(pos){pos=(pos!=undefined)?pos:this.position;
var modelPos=exports.copyPos(pos);var line=[];if(this.editor.model.hasRow(pos.row)){line=this.editor.model.getRowArray(pos.row);
}var tabsize=this.editor.getTabSize();if(line.indexOf("\t")!=-1){var current_pos=0;
for(var i=0;i<modelPos.col;i++){var new_pos=current_pos;if(line[i]=="\t"){new_pos=Math.floor((current_pos+tabsize)/tabsize)*tabsize;
}else{new_pos+=1;}if(new_pos>modelPos.col){break;}current_pos=new_pos;}modelPos.col=i;
}return modelPos;},getCharacterLength:function(character,column){if(character.length>1){return;
}if(column==undefined){column=this.position.col;}if(character=="\t"){var tabsize=this.editor.getTabSize();
return tabsize-(column%tabsize);}else{return 1;}},getStringLength:function(str){if(!str||str.length==0){return 0;
}var count=0;str=str.split("");for(var x=0;x<str.length;x++){count+=this.getCharacterLength(str[x],count);
}return count;},getLeadingWhitespace:function(rowIndex){var row=this.editor.model.getRowArray(rowIndex).join("");
var match=/^(\s+).*/.exec(row);return(match&&match.length==2?this.getStringLength(match[1]):0);
},getContinuousSpaceCount:function(from,to,rowIndex){rowIndex=rowIndex||this.position.row;
var row=this.editor.model.getRowArray(rowIndex);var delta=(from<to?1:-1);var length=row.length;
from=from+(delta==1?0:-1);to=to+(delta==1?0:-1);from=this.getModelPosition({col:from,row:rowIndex}).col;
to=this.getModelPosition({col:to,row:rowIndex}).col;if(this.settings.values.strictlines){from=Math.min(from,length);
to=Math.min(to,length);}var count=0;for(var x=from;x!=to;x+=delta){if(x<length){if(row[x]!=" "){break;
}}count++;}return count;},getNextTablevelLeft:function(col){var tabsize=this.editor.getTabSize();
col=col||this.position.col;col--;return Math.floor(col/tabsize)*tabsize;},getNextTablevelRight:function(col){var tabsize=this.editor.getTabSize();
col=col||this.position.col;col++;return Math.ceil(col/tabsize)*tabsize;},moveToLineStart:function(){var oldPos=exports.copyPos(this.position);
var leadingWhitespaceLength=this.getLeadingWhitespace(oldPos.row);if(this.position.col==0){this.moveCursor({col:leadingWhitespaceLength});
}else{if(this.position.col==leadingWhitespaceLength){this.moveCursor({col:0});}else{if(leadingWhitespaceLength!=this.editor.editorView.getRowScreenLength(this.editor.cursorManager.getCursorPosition().row)){this.moveCursor({col:leadingWhitespaceLength});
}else{this.moveCursor({col:0});}}}return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},moveToLineEnd:function(){var oldPos=exports.copyPos(this.position);this.moveCursor({col:this.editor.editorView.getRowScreenLength(oldPos.row)});
return{oldPos:oldPos,newPos:exports.copyPos(this.position)};},moveToTop:function(){var oldPos=exports.copyPos(this.position);
this.editor.cursorManager.moveCursor({row:0,col:0});return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},moveToBottom:function(){var oldPos=exports.copyPos(this.position);var row=this.editor.model.getRowCount()-1;
this.editor.cursorManager.moveCursor({row:row,col:this.editor.editorView.getRowScreenLength(row)});
return{oldPos:oldPos,newPos:exports.copyPos(this.position)};},moveUp:function(){var oldPos=exports.copyPos(this.position);
this.moveCursor({row:oldPos.row-1,col:Math.max(oldPos.col,this.virtualCol)});this.checkPastEndOfLine(oldPos);
return{oldPos:oldPos,newPos:exports.copyPos(this.position)};},moveDown:function(){var oldPos=exports.copyPos(this.position);
this.moveCursor({row:Math.max(0,oldPos.row+1),col:Math.max(oldPos.col,this.virtualCol)});
this.checkPastEndOfLine(oldPos);return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},moveLeft:function(args){var oldPos=exports.copyPos(this.position);var shiftKey=(args.event?args.event.shiftKey:false);
if(!this.editor.getSelection()||shiftKey){if(this.settings.values.smartmove){var freeSpaces=this.getContinuousSpaceCount(oldPos.col,this.getNextTablevelLeft());
if(freeSpaces==this.editor.getTabSize()){this.moveCursor({col:oldPos.col-freeSpaces});
return{oldPos:oldPos,newPos:exports.copyPos(this.position)};}}if(this.settings.values.strictlines&&this.position.col==0){this.moveUp();
if(oldPos.row>0){this.moveToLineEnd();}}else{this.moveCursor({row:oldPos.row,col:Math.max(0,oldPos.col-1)});
}}else{this.moveCursor(this.editor.getSelection().startPos);}return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},moveRight:function(args){var oldPos=exports.copyPos(this.position);var shiftKey=(args.event?args.event.shiftKey:false);
if(!this.editor.getSelection()||shiftKey){if(this.settings.values.smartmove&&args!=true){var freeSpaces=this.getContinuousSpaceCount(oldPos.col,this.getNextTablevelRight());
if(freeSpaces==this.editor.getTabSize()){this.moveCursor({col:oldPos.col+freeSpaces});
return{oldPos:oldPos,newPos:exports.copyPos(this.position)};}}if(this.settings.values.strictlines&&(this.position.col>=this.editor.editorView.getRowScreenLength(this.position.row))){this.moveDown();
if(oldPos.row<this.editor.model.getRowCount()-1){this.moveCursor({col:0});}}else{this.moveCursor({col:this.position.col+1});
}}else{this.moveCursor(this.editor.getSelection().endPos);}return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},movePageUp:function(){var oldPos=exports.copyPos(this.position);this.moveCursor({row:Math.max(this.editor.editorView.firstVisibleRow-this.editor.editorView.visibleRows,0)});
this.checkPastEndOfLine(oldPos);return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},movePageDown:function(){var oldPos=exports.copyPos(this.position);this.moveCursor({row:Math.min(this.position.row+this.editor.editorView.visibleRows,this.editor.model.getRowCount()-1)});
this.checkPastEndOfLine(oldPos);return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},checkPastEndOfLine:function(oldPos){var isStrictLines=this.settings.values.strictlines;
var maxCol=this.editor.editorView.getRowScreenLength(this.position.row);if(isStrictLines&&this.position.col>maxCol){this.moveToLineEnd();
this.virtualCol=Math.max(oldPos.col,this.virtualCol);}},smartMoveLeft:function(){var oldPos=exports.copyPos(this.position);
var row=this.editor.editorView.getRowString(oldPos.row);var c,charCode;if(this.position.col==0){this.moveUp();
this.moveToLineEnd();}else{if(row.length<this.position.col){this.moveToLineEnd();
}var newcol=this.position.col;var wasSpaces=false;while(newcol>0){newcol--;c=row.charAt(newcol);
charCode=c.charCodeAt(0);if(charCode==32){wasSpaces=true;}else{newcol++;break;}}if(!wasSpaces){while(newcol>0){newcol--;
c=row.charAt(newcol);charCode=c.charCodeAt(0);if((charCode<65)||(charCode>122)){if(newcol!=this.position.col-1){newcol++;
}break;}}}this.moveCursor({col:newcol});}return{oldPos:oldPos,newPos:exports.copyPos(this.position)};
},smartMoveRight:function(){var oldPos=exports.copyPos(this.position);var row=this.editor.editorView.getRowString(oldPos.row);
if(row.length<=this.position.col){this.moveDown();this.moveToLineStart();}else{var c,charCode;
var newcol=this.position.col;var wasSpaces=false;while(newcol<row.length){c=row[newcol];
charCode=c.charCodeAt(0);if(charCode==32){wasSpaces=true;newcol++;}else{break;}}if(!wasSpaces){while(newcol<row.length){newcol++;
if(row.length==newcol){this.moveToLineEnd();newcol=-1;break;}c=row[newcol];charCode=c.charCodeAt(0);
if((charCode<65)||(charCode>122)){break;}}}if(newcol!=-1){this.moveCursor({col:newcol});
}}return{oldPos:oldPos,newPos:exports.copyPos(this.position)};},moveCursor:function(newpos){if(!newpos){return;
}if(newpos.col===undefined){newpos.col=this.position.col;}if(newpos.row===undefined){newpos.row=this.position.row;
}this.virtualCol=0;var oldpos=this.position;var row=Math.min(newpos.row,this.editor.model.getRowCount()-1);
if(row<0){row=0;}var invalid=this.isInvalidCursorPosition(row,newpos.col);if(invalid){if(oldpos.row!=newpos.row){newpos.col=invalid.right;
}else{if(oldpos.col<newpos.col){newpos.col=invalid.right;}else{if(oldpos.col>newpos.col){newpos.col=invalid.left;
}else{newpos.col=invalid.right;}}}}this.position={row:row,col:newpos.col};var editorView=this.editor.editorView;
editorView.showCursor=true;editorView.toggleCursorAllowed=false;editorView.cursorDidMove(this,this.position);
},isInvalidCursorPosition:function(row,col){var rowArray=this.editor.model.getRowArray(row);
var curCol=0;for(var i=0;i<rowArray.length;i++){if(rowArray[i].charCodeAt(0)==9){var toInsert=this.editor.getTabSize()-(curCol%this.editor.getTabSize());
if((col>curCol)&&(col<(curCol+toInsert))){return{left:curCol,right:curCol+toInsert,half:toInsert/2};
}curCol+=toInsert-1;}curCol++;}return undefined;}});exports.buildArgs=function(oldPos){return{pos:exports.copyPos(oldPos||bespin.get("editor").getCursorPos())};
};exports.changePos=function(args,pos){return{pos:exports.copyPos(pos||bespin.get("editor").getCursorPos())};
};exports.copyPos=function(oldPos){if(!oldPos){return oldPos;}return{row:oldPos.row,col:oldPos.col};
};exports.posEquals=function(pos1,pos2){if(pos1==pos2){return true;}if(!pos1||!pos2){return false;
}return(pos1.col==pos2.col)&&(pos1.row==pos2.row);};});tiki.module("bespin:editor",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var bespin=require("bespin:package");var util=require("util/util");var keys=require("util/keys");
var canvas=require("util/canvas");var cookie=require("util/cookie");var mousewheelevent=require("util/mousewheelevent");
var clipboard=require("util/clipboard");var editorEvents=require("events");var syntax=require("syntax");
var cursor=require("cursor");var actions=require("actions");var model=require("model");
var history=require("history");});tiki.module("bespin:editor/controller",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var util=require("util/util");var canvas=require("util/canvas");var cookie=require("util/cookie");
var keys=require("util/keys");var editorEvents=require("events");var cursor=require("cursor");
var model=require("model");var history=require("history");var view=require("editor/views/editor");
var scroll=require("editor/views/scroll");exports.EditorController=SC.Object.extend({containerBinding:".editorView.layer",requires:{ioc:"ioc",settings:"settings",commandLine:"commandLine",session:"editSession",cursorManager:"cursorManager",files:"files",settings:"settings",hub:"hub"},afterContainerSetup:function(){this.settings.addSetting({name:"tabsize",type:"number",defaultValue:4});
this.settings.addSetting({name:"trimonsave",type:"boolean",defaultValue:false});this.settings.addSetting({name:"language",type:"text",defaultValue:"auto"});
this.hub.subscribe("editor:openfile:opensuccess",function(event){var project=event.project||session.project;
var fileType=util.path.fileType(event.file.name);if(fileType){this.hub.publish("settings:language",{language:fileType});
}var mapName=project+"/"+event.file.name;if(this.specialFileMap[mapName]){this.hub.publish("settings:language",{language:this.specialFileMap[mapName]});
}}.bind(this));this.specialFileMap={"BespinSettings/config":"js"};this.hub.subscribe("editor:openfile:opensuccess",function(event){var project=event.project||session.project;
var filename=event.file.name;try{var name="viewData_"+project+"_"+filename.split("/").join("_");
var data=cookie.get(name);if(data){this.resetView(JSON.parse(data));}else{this.basicView();
}}catch(ex){console.log("Error setting in the view: ",ex);}}.bind(this));this.debugMode=false;
this.model=model.DocumentModel.create({editor:this});this.ui=scroll.BespinScrollView.create({contentView:view.EditorView.extend({editor:this,content:this.model})});
this.editorView=this.ui.contentView;this.theme=require("theme")["default"];this.editorKeyListener=exports.DefaultEditorKeyListener.create();
this.ioc.inject(this.editorKeyListener);this.historyManager=history.HistoryManager.create({editor:this});
editorEvents.subscribe();this.editorView.installKeyListener(this.editorKeyListener);
arguments.callee.base.apply(this,arguments);},getContent:function(){return this.model.getDocument();
},setContent:function(content){return this.model.insertDocument(content);},setLineNumber:function(linenum){this.moveAndCenter(linenum);
},setSetting:function(key,value){this.settings.values[key]=value;},onchange:function(callback){this.hub.subscribe("editor:document:changed",callback);
},executeCommand:function(command){try{this.commandLine.executeCommand(command);}catch(e){}},getSelection:function(selection){selection=(selection!=undefined)?selection:this.selection;
if(!selection){return undefined;}var startPos=selection.startPos;var endPos=selection.endPos;
if((endPos.row<startPos.row)||((endPos.row==startPos.row)&&(endPos.col<startPos.col))){var foo=startPos;
startPos=endPos;endPos=foo;}return{startPos:cursor.copyPos(startPos),endPos:cursor.copyPos(endPos),startModelPos:this.getModelPos(startPos),endModelPos:this.getModelPos(endPos)};
},getCursorPos:function(modelPos){return this.cursorManager.getCursorPosition(modelPos);
},getModelPos:function(pos){return this.cursorManager.getModelPosition(pos);},computeLayout:function(){var layout={left:0,top:0,width:this.ui.clientWidth,height:this.ui.clientHeight};
var container=this.ui;while(container!==null){if(!isNaN(container.offsetLeft)){layout.left+=container.offsetLeft;
}if(!isNaN(container.offsetTop)){layout.top+=container.offsetTop;}container=container.parentNode;
}return layout;},moveCursor:function(pos){this.cursorManager.moveCursor(pos);},resetView:function(data){this.cursorManager.moveCursor(data.cursor);
this.setSelection(data.selection);this.ui.horizontalScrollOffset=0;this.ui.verticalScrollOffset=0;
},basicView:function(){this.cursorManager.moveCursor({row:0,col:0});this.setSelection(undefined);
this.ui.horizontalScrollOffset=0;this.ui.verticalScrollOffset=0;},getCurrentView:function(){return{cursor:this.getCursorPos(),offset:{x:this.horizontalScrollOffset,y:this.verticalScrollOffset},selection:this.selection};
},getState:function(){return{cursor:this.getCursorPos(),selection:this.getSelection()};
},setState:function(data){this.cursorManager.moveCursor(data.cursor);this.setSelection(data.selection);
this.editorView.ensureCursorVisible();this.paint(false);},defaultTabSize:4,getTabSize:function(){var size=this.defaultTabSize;
var tabsize=this.settings.values.tabsize;if(tabsize>0){size=tabsize;}return size;
},getSelectionAsText:function(){var selectionText="";var selectionObject=this.getSelection();
if(selectionObject){selectionText=this.model.getChunk(selectionObject);}return selectionText;
},setSelection:function(selection){this.selection=selection;},paint:function(fullRefresh){SC.RunLoop.begin();
this.editorView.set("layerNeedsUpdate",true);SC.RunLoop.end();},changeKeyListener:function(newKeyListener){this.editorView.installKeyListener(newKeyListener);
this.editorKeyListener=newKeyListener;},setFocus:function(focus){this.editorView.setFocus(focus);
},setReadOnly:function(readonly){this.readonly=readonly;},dispose:function(){this.ui.dispose();
},bindKey:function(action,keySpec,selectable){console.warn("Use of editor.bindKey(",action,keySpec,selectable,") seems doomed to fail");
var keyObj=keys.fillArguments(keySpec);var key=keyObj.key;var modifiers=keyObj.modifiers;
if(!key){return;}var keyCode=keys.toKeyCode(key);var actionDescription="Execute command: '"+action+"'";
action=this.editorView.actions[action]||function(){this.commandLine.executeCommand(command,true);
};if(keyCode&&action){if(selectable){this.editorKeyListener.bindKeyStringSelectable(modifiers,keyCode,action,actionDescription);
}else{this.editorKeyListener.bindKeyString(modifiers,keyCode,action,actionDescription);
}}},bindCommand:function(command,keySpec){var keyObj=keys.fillArguments(keySpec);
var keyCode=keys.toKeyCode(keyObj.key);var action=function(){this.commandLine.executeCommand(command,true);
};var actionDescription="Execute command: '"+command+"'";this.editorKeyListener.bindKeyString(keyObj.modifiers,keyCode,action,actionDescription);
},moveAndCenter:function(row){if(!row){return;}var linenum=row-1;this.cursorManager.moveCursor({row:linenum,col:0});
if((linenum<this.editorView.firstVisibleRow)||(linenum>=this.editorView.firstVisibleRow+this.editorView.visibleRows)){this.editorView.actions.moveCursorRowToCenter();
}},newFile:function(project,path,content){project=project||this.session.project;path=path||"new.txt";
var self=this;var onSuccess=function(){if(!this.settings.values.collaborate){self.model.insertDocument(content||"");
self.cursorManager.moveCursor({row:0,col:0});self.setFocus(true);}this.hub.publish("editor:openfile:opensuccess",{project:project,file:{name:path,content:content||"",timestamp:new Date().getTime()}});
this.hub.publish("editor:dirty");};this.files.newFile(project,path,onSuccess);},saveFile:function(project,filename,onSuccess,onFailure){project=project||this.session.project;
filename=filename||this.session.path;var name="viewData_"+project+"_"+filename.split("/").join("_");
var value=JSON.stringify(this.getCurrentView());cookie.set(name,value,{expires:7});
var file={name:filename,content:this.model.getDocument(),timestamp:new Date().getTime()};
var newOnSuccess=function(){document.title=filename+" - editing with Bespin";this.commandLine.showHint("Saved file: "+file.name);
this.hub.publish("editor:clean");if(util.isFunction(onSuccess)){onSuccess();}};var newOnFailure=function(xhr){this.commandLine.showHint("Save failed: "+xhr.responseText);
if(util.isFunction(onFailure)){onFailure();}};if(this.settings.values.trimonsave){this.commandLine.executeCommand("trim",true);
}this.file.saveFile(project,file,newOnSuccess,newOnFailure);},openFile:function(project,filename,options){var onFailure,onSuccess;
var self=this;project=project||this.session.project;filename=filename||this.session.path;
options=options||{};var fromFileHistory=options.fromFileHistory||false;if(this.session.checkSameFile(project,filename)&&!options.reload){if(options.line){this.commandLine.executeCommand("goto "+options.line,true);
}return;}if(this.dirty&&!this.session.shouldCollaborate()){onFailure=function(xhr){this.commandLine.showHint("Trying to save current file. Failed: "+xhr.responseText);
};onSuccess=function(){self.openFile(project,filename,options);};this.saveFile(null,null,onSuccess,onFailure);
return;}if(options.force){this.file.whenFileDoesNotExist(project,filename,{execute:function(){self.newFile(project,filename,options.content||"");
},elseFailed:function(){options.force=false;self.openFile(project,filename,options);
}});return;}onFailure=function(){this.hub.publish("editor:openfile:openfail",{project:project,filename:filename});
};onSuccess=function(file){if(!file){onFailure();return;}if(file.content!==undefined){self.model.insertDocument(file.content);
self.cursorManager.moveCursor({row:0,col:0});self.setFocus(true);}this.session.setProjectPath(project,filename);
if(options.line){this.commandLine.executeCommand("goto "+options.line,true);}self._addHistoryItem(project,filename,fromFileHistory);
this.hub.publish("editor:openfile:opensuccess",{project:project,file:file});document.title=file+" - editing with Bespin";
this.hub.publish("url:change",{project:project,path:file});this.session.project=project;
this.session.path=file;};this.hub.publish("editor:openfile:openbefore",{project:project,filename:filename});
this.file.editFile(project,filename,onSuccess,onFailure);},_addHistoryItem:function(project,filename,fromFileHistory){var lastUsed=this.settings.values.lastused;
if(!lastUsed){lastUsed=[];}var newItem={project:project,filename:filename};if(!fromFileHistory){this.session.addFileToHistory(newItem);
}var cleanLastUsed=[];lastUsed.forEach(function(item){if(item.project!=newItem.project||item.filename!=newItem.filename){cleanLastUsed.unshift(item);
}});cleanLastUsed.unshift(newItem);lastUsed=cleanLastUsed;if(lastUsed.length>10){lastUsed=lastUsed.slice(0,10);
}this.settings.values.lastused=lastUsed;}});exports.DefaultEditorKeyListener=SC.Object.extend({skipKeypress:false,defaultKeyMap:{},keyMapDescriptions:{},requires:{editor:"editor",hub:"hub"},init:function(){this.keyMap=this.defaultKeyMap;
},bindKey:function(keyCode,metaKey,ctrlKey,altKey,shiftKey,action,name){var key=[keyCode,metaKey,ctrlKey,altKey,shiftKey].toString();
if(typeof action=="string"){this.defaultKeyMap[key]=function(){var toFire=this._toFire(action);
this.hub.publish(toFire.name,toFire.args);}.bind(this);}else{this.defaultKeyMap[key]=action.bind(this.editor.editorView.actions);
}if(name){this.keyMapDescriptions[key]=name;}},_toFire:function(eventString){var event={};
if(eventString.indexOf(";")<0){event.name=eventString;}else{var pieces=eventString.split(";");
event.name=pieces[0];event.args=util.queryToObject(pieces[1],",");}return event;},bindKeyForPlatform:function(keysForPlatforms,action,name,isSelectable){var platform=util.getOS();
var platformKeys=keysForPlatforms[platform]||keysForPlatforms.WINDOWS;if(!platformKeys){return;
}var args=keys.fillArguments(platformKeys);var bindFunction=(isSelectable)?"bindKeyStringSelectable":"bindKeyString";
this[bindFunction](args.modifiers,keys.toKeyCode(args.key),action,name);},bindKeyString:function(modifiers,keyCode,action,name){var ctrlKey=(modifiers.toUpperCase().indexOf("CTRL")!=-1);
var altKey=(modifiers.toUpperCase().indexOf("ALT")!=-1);var metaKey=(modifiers.toUpperCase().indexOf("META")!=-1)||(modifiers.toUpperCase().indexOf("APPLE")!=-1);
var shiftKey=(modifiers.toUpperCase().indexOf("SHIFT")!=-1);if(modifiers.toUpperCase().indexOf("CMD")!=-1){if(util.isMac){metaKey=true;
}else{ctrlKey=true;}}return this.bindKey(keyCode,metaKey,ctrlKey,altKey,shiftKey,action,name);
},bindKeyStringSelectable:function(modifiers,keyCode,action,name){this.bindKeyString(modifiers,keyCode,action,name);
this.bindKeyString("SHIFT "+modifiers,keyCode,action);},getPrintableChar:function(e){if(e.charCode>255){return false;
}if(e.charCode<32){return false;}if((e.altKey||e.metaKey||e.ctrlKey)&&(e.charCode>65&&e.charCode<123)){return false;
}return String.fromCharCode(e.charCode);},onkeydown:function(e){if(!this.editor.editorView.hasFocus()){console.log("ignoring keyboard event, we don't have focus",e);
return;}var args={event:e,pos:cursor.copyPos(this.editor.cursorManager.getCursorPosition())};
this.skipKeypress=false;this.returnValue=false;var action=this.keyMap[[e.keyCode,e.metaKey,e.ctrlKey,e.altKey,e.shiftKey]];
var hasAction=false;if(util.isFunction(action)){hasAction=true;try{action(args);}catch(ex){console.log("Action caused an error! ",ex);
}this.lastAction=action;}if(e.metaKey||e.ctrlKey||e.altKey){this.skipKeypress=true;
this.returnValue=true;}if(hasAction||!keys.passThroughToBrowser(e)){util.stopEvent(e);
}},onkeypress:function(e){if(!this.editor.editorView.hasFocus()){console.log("ignoring keyboard event, we don't have focus",e);
return;}if((e.metaKey||e.ctrlKey)&&e.charCode>=48&&e.charCode<=57){return;}var charToPrint=this.getPrintableChar(e);
if(charToPrint){this.skipKeypress=false;}else{if(this.skipKeypress){if(!keys.passThroughToBrowser(e)){util.stopEvent(e);
}return this.returnValue;}}var args={event:e,pos:cursor.copyPos(this.editor.cursorManager.getCursorPosition())};
var actions=this.editor.editorView.actions;if(charToPrint){args.newchar=String.fromCharCode(e.charCode);
actions.insertCharacter(args);}else{var action=this.keyMap[[e.keyCode,e.metaKey,e.ctrlKey,e.altKey,e.shiftKey]];
if(this.lastAction==action){delete this.lastAction;}else{if(typeof action=="function"){action(args);
}}}util.stopEvent(e);}});});tiki.module("bespin:editor/mixins/canvas",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
exports.Canvas={tagName:"canvas",layerFrame:function(){return this.get("frame");}.property("frame").cacheable(),layoutStyle:function(){var layerFrame=this.get("layerFrame");
return{left:"%@px".fmt(layerFrame.x),top:"%@px".fmt(layerFrame.y)};}.property("layerFrame").cacheable(),renderLayout:function(context,firstTime){arguments.callee.base.apply(this,arguments);
var layerFrame=this.get("layerFrame");if(firstTime){context.attr("width",layerFrame.width);
context.attr("height",layerFrame.height);return;}var canvas=this.$()[0];if(canvas.width!==layerFrame.width){canvas.width=layerFrame.width;
}if(canvas.height!==layerFrame.height){canvas.height=layerFrame.height;}},drawRect:function(context,visibleFrame){},render:function(context,firstTime){var layerFrame=this.get("layerFrame");
if(firstTime){context.attr("width",""+layerFrame.width);context.attr("height",""+layerFrame.height);
context.push("canvas tag not supported by your browser");return;}var visibleFrame=SC.cloneRect(this.get("clippingFrame"));
visibleFrame.width=layerFrame.width;visibleFrame.height=layerFrame.height;var canvas=this.$()[0];
var drawingContext=canvas.getContext("2d");drawingContext.save();var frame=this.get("frame");
drawingContext.translate(frame.x-layerFrame.x,frame.y-layerFrame.y);this.drawRect(drawingContext,visibleFrame);
drawingContext.restore();},getCharacterWidth:function(font){var canvas=this.$()[0];
if(SC.none(canvas)){return null;}var context=canvas.getContext("2d");context.save();
context.font=font;var width=context.measureText("M").width;context.restore();return width;
},guessLineHeight:function(font){var canvas=this.$()[0];if(SC.none(canvas)){return null;
}var context=canvas.getContext("2d");context.save();context.font=font;var height=Math.floor(context.measureText("m").width*2.8);
context.restore();return height;},_bespin_canvas_layerFrameDidChange:function(){this.updateLayout();
}.observes("layerFrame")};});tiki.module("bespin:editor/views/editor",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var bespin=require("package");var syntax=require("syntax");var actions=require("actions");
var keys=require("util/keys");var clipboard=require("util/clipboard");var cursor=require("cursor");
var scroller=require("editor/views/scroller");var canvas=require("editor/mixins/canvas");
var pluginCatalog=require("plugins").catalog;var SelectionHelper=SC.Object.extend({editor:null,getRowSelectionPositions:function(rowIndex){var startCol;
var endCol;var selection=this.editor.getSelection();if(!selection){return undefined;
}if((selection.endPos.row<rowIndex)||(selection.startPos.row>rowIndex)){return undefined;
}startCol=(selection.startPos.row<rowIndex)?0:selection.startPos.col;endCol=(selection.endPos.row>rowIndex)?-1:selection.endPos.col;
return{startCol:startCol,endCol:endCol};}});bespin.get("settings").addSetting({name:"tabarrow",type:"boolean",defaultValue:true});
exports.EditorView=SC.View.extend(canvas.Canvas,{classNames:"sc-canvas-view",displayProperties:["value","shouldAutoResize"],rowLengthCache:[],searchString:null,toggleCursorFullRepaintCounter:0,toggleCursorFrequency:250,toggleCursorAllowed:true,LINE_HEIGHT:23,BOTTOM_SCROLL_AFFORDANCE:30,LINE_INSETS:{top:0,left:5,right:0,bottom:6},FALLBACK_CHARACTER_WIDTH:10,showCursor:true,hasFocus:false,onInitActions:[],inited:false,lastLineCount:0,lastCursorPos:null,padding:{bottom:0,right:0},hasPadding:true,layerFrame:function(){var parentView=this.get("parentView");
var parentFrame=parentView.get("frame");return{x:0,y:0,width:parentFrame.width,height:parentFrame.height};
}.property(),init:function(){var settings=bespin.get("settings");var ep=pluginCatalog.getExtensionPoint("syntax.engine");
this.syntaxModel=syntax.Model.create();if(ep.extensions.length>0){ep.extensions[0].load(function(model){this.syntaxModel=model.create();
}.bind(this));}this.selectionHelper=SelectionHelper.create({editor:this.editor});
this.actions=actions.Actions.create({editor:this.editor});var wheelEventName=(window.onmousewheel?"onmousewheel":"DOMMouseScroll");
setTimeout(function(){this.toggleCursor();}.bind(this),this.toggleCursorFrequency);
arguments.callee.base.apply(this,arguments);},render:function(context,firstTime){arguments.callee.base.apply(this,arguments);
if(!firstTime){return;}context.attr("moz-opaque","true");context.attr("tabindex","1");
},didCreateLayer:function(){var canvas=this.$()[0];SC.Event.add(canvas,"blur",this,function(ev){this.focus=true;
return true;});SC.Event.add(canvas,"focus",this,function(ev){this.focus=true;return true;
});var editorWrapper=EditorWrapper.create({editor:this.editor,ui:this});clipboard.setup(editorWrapper);
this.onInitActions.forEach(function(action){action();});this.set("rowCount",this.get("content").getRowCount());
this.inited=true;},onInit:function(action){if(this.inited){action();return;}this.onInitActions.push(action);
},convertClientPointToCursorPoint:function(pos){var settings=bespin.get("settings");
var x,y;var content=this.get("content");var charWidth=this.get("charWidth");var lineHeight=this.get("lineHeight");
if(pos.y<0){y=0;}else{if(pos.y>=(lineHeight*content.getRowCount())){y=content.getRowCount()-1;
}else{var ty=pos.y;y=Math.floor(ty/lineHeight);}}if(pos.x<=this.LINE_INSETS.left){x=-1;
}else{var tx=pos.x-this.LINE_INSETS.left;x=Math.round(tx/charWidth);if(settings.values.strictlines){var maxcol=this.getRowScreenLength(y);
if(x>=maxcol){x=this.getRowScreenLength(y);}}}return{row:y,col:x};},absoluteCoordinatesForEvent:function(ev){return this.convertFrameFromView({x:ev.clientX,y:ev.clientY});
},setSelection:function(e){var content=this.get("content");var absolutePoint=this.absoluteCoordinatesForEvent(e);
var clientY=absolutePoint.y,clientX=absolutePoint.x;if(!this.selectMouseDownPos){return;
}var down=cursor.copyPos(this.selectMouseDownPos);var point={x:clientX,y:clientY};
var up=this.convertClientPointToCursorPoint(point);if(down.col==-1){down.col=0;var lineMarker=bespin.get("parser").getLineMarkers()[down.row+1];
if(lineMarker){bespin.get("commandLine").showHint(lineMarker.msg);}}if(up.col==-1){up.col=0;
}var modelstart=this.editor.getModelPos(down);var modelend=this.editor.getModelPos(up);
var backwards=false;if(modelend.row<modelstart.row||(modelend.row==modelstart.row&&modelend.col<modelstart.col)){backwards=true;
var temp=modelstart;modelstart=modelend;modelend=temp;}if(!content.hasRow(modelstart.row)){modelstart.row=content.getRowCount()-1;
}if(!content.hasRow(modelend.row)){modelend.row=content.getRowCount()-1;}var detail=this.selectMouseDetail;
var startPos,endPos;if(detail==1){if(cursor.posEquals(modelstart,modelend)){this.editor.setSelection(undefined);
}else{this.editor.setSelection({startPos:this.editor.getCursorPos(backwards?modelend:modelstart),endPos:this.editor.getCursorPos(backwards?modelstart:modelend)});
}this.editor.moveCursor(this.editor.getCursorPos(backwards?modelstart:modelend));
}else{if(detail==2){var row=content.rows[modelstart.row];var cursorAt=row[modelstart.col];
var isDelimiter=function(item){var delimiters=["="," ","\t",">","<",".","(",")","{","}",":",'"',"'",";"];
if(delimiters.indexOf(item)>-1){return true;}return false;};var comparator;if(!cursorAt){this.editor.setSelection({startPos:this.editor.getCursorPos({row:modelstart.row,col:0}),endPos:this.editor.getCursorPos({row:modelstart.row,col:row.length})});
}else{if(isDelimiter(cursorAt.charAt(0))){comparator=function(letter){if(isDelimiter(letter)){return false;
}return true;};startPos=content.findBefore(modelstart.row,modelstart.col,comparator);
endPos=content.findAfter(modelend.row,modelend.col,comparator);this.editor.setSelection({startPos:this.editor.getCursorPos(backwards?endPos:startPos),endPos:this.editor.getCursorPos(backwards?startPos:endPos)});
this.editor.moveCursor(this.editor.getCursorPos(backwards?startPos:endPos));}else{comparator=function(letter){if(isDelimiter(letter)){return true;
}return false;};startPos=content.findBefore(modelstart.row,modelstart.col,comparator);
endPos=content.findAfter(modelend.row,modelend.col,comparator);this.editor.setSelection({startPos:this.editor.getCursorPos(backwards?endPos:startPos),endPos:this.editor.getCursorPos(backwards?startPos:endPos)});
this.editor.moveCursor(this.editor.getCursorPos(backwards?startPos:endPos));}}}else{if(detail>2){startPos={row:modelstart.row,col:0};
endPos={row:modelend.row,col:0};if(this.editor.model.hasRow(endPos.row+1)){endPos.row=endPos.row+1;
}else{endPos.col=this.editor.model.getRowArray(endPos.row).length;}startPos=this.editor.getCursorPos(startPos);
endPos=this.editor.getCursorPos(endPos);this.editor.setSelection({startPos:backwards?endPos:startPos,endPos:backwards?startPos:endPos});
this.editor.moveCursor(backwards?startPos:endPos);}}}this.editor.paint();},toggleCursor:function(){if(this.toggleCursorAllowed){this.showCursor=!this.showCursor;
}else{this.toggleCursorAllowed=true;}this.toggleCursorFullRepaintCounter++;if(this.toggleCursorFullRepaintCounter>0){this.toggleCursorFullRepaintCounter=0;
this.editor.paint(true);}else{this.editor.paint();}setTimeout(function(){this.toggleCursor();
}.bind(this),this.toggleCursorFrequency);},ensureCursorVisible:function(softEnsure){},handleFocus:function(e){var content=this.get("content");
content.clear();content.insertCharacters({row:0,col:0},e.type);return true;},mouseDragged:function(e){if(this.selectMouseDownPos){this.setSelection(e);
}return true;},mouseDown:function(e){var absolutePoint=this.absoluteCoordinatesForEvent(e);
var clientY=absolutePoint.y,clientX=absolutePoint.x;this.selectMouseDetail=e.detail;
if(e.shiftKey){this.selectMouseDownPos=(this.editor.selection)?this.editor.selection.startPos:this.editor.getCursorPos();
this.setSelection(e);}else{point={x:clientX,y:clientY};this.selectMouseDownPos=this.convertClientPointToCursorPoint(point);
}var canvas=this.$()[0];canvas.focus();return true;},mouseUp:function(e){if(this.selectMouseDownPos){this.setSelection(e);
this.selectMouseDownPos=undefined;this.selectMouseDetail=undefined;return false;}return true;
},setFocus:function(focus){this.onInit(function(){if(this.focus!=focus){var canvas=this.$()[0];
if(focus){canvas.focus();}else{canvas.blur();}this.focus=focus;}}.bind(this));},hasFocus:function(focus){return this.focus;
},_getFocusElement:function(){var canvas=this.$()[0];return canvas;},installKeyListener:function(listener){this.onInit(function(){this.realInstallKeyListener(listener);
}.bind(this));},realInstallKeyListener:function(listener){var canvas=this.$()[0];
var scope=canvas;if(this.oldkeydown){SC.Event.remove(scope,"keydown",this,this.oldkeydown);
}if(this.oldkeypress){SC.Event.remove(scope,"keypress",this,this.oldkeypress);}this.oldkeydown=function(ev){listener.onkeydown(ev);
return true;};this.oldkeypress=function(ev){listener.onkeypress(ev);return true;};
SC.Event.add(scope,"keydown",this,this.oldkeydown);SC.Event.add(scope,"keypress",this,this.oldkeypress);
var Key=keys.Key;listener.bindKeyStringSelectable("",keys.Key.LEFT_ARROW,this.actions.moveCursorLeft,"Move Cursor Left");
listener.bindKeyStringSelectable("",keys.Key.RIGHT_ARROW,this.actions.moveCursorRight,"Move Cursor Right");
listener.bindKeyStringSelectable("",keys.Key.UP_ARROW,this.actions.moveCursorUp,"Move Cursor Up");
listener.bindKeyStringSelectable("",keys.Key.DOWN_ARROW,this.actions.moveCursorDown,"Move Cursor Down");
listener.bindKeyForPlatform({MAC:"ALT LEFT_ARROW",WINDOWS:"CTRL LEFT_ARROW"},this.actions.moveWordLeft,"Move Word Left",true);
listener.bindKeyForPlatform({MAC:"ALT RIGHT_ARROW",WINDOWS:"CTRL RIGHT_ARROW"},this.actions.moveWordRight,"Move Word Right",true);
listener.bindKeyStringSelectable("",keys.Key.HOME,this.actions.moveToLineStart,"Move to start of line");
listener.bindKeyForPlatform({MAC:"APPLE LEFT_ARROW",WINDOWS:"ALT LEFT_ARROW"},this.actions.moveToLineStart,"Move to start of line",true);
listener.bindKeyStringSelectable("",keys.Key.END,this.actions.moveToLineEnd,"Move to end of line");
listener.bindKeyForPlatform({MAC:"APPLE RIGHT_ARROW",WINDOWS:"ALT RIGHT_ARROW"},this.actions.moveToLineEnd,"Move to end of line",true);
listener.bindKeyString("CTRL",keys.Key.K,this.actions.killLine,"Kill entire line");
listener.bindKeyString("CMD",keys.Key.L,this.actions.gotoLine,"Goto Line");listener.bindKeyString("CTRL",keys.Key.L,this.actions.moveCursorRowToCenter,"Move cursor to center of page");
listener.bindKeyStringSelectable("",keys.Key.BACKSPACE,this.actions.backspace,"Backspace");
listener.bindKeyStringSelectable("CTRL",keys.Key.BACKSPACE,this.actions.deleteWordLeft,"Delete a word to the left");
listener.bindKeyString("",keys.Key.DELETE,this.actions.deleteKey,"Delete");listener.bindKeyString("CTRL",keys.Key.DELETE,this.actions.deleteWordRight,"Delete a word to the right");
listener.bindKeyString("",keys.Key.ENTER,this.actions.newline,"Insert newline");listener.bindKeyString("CMD",keys.Key.ENTER,this.actions.newlineBelow,"Insert newline at end of current line");
listener.bindKeyString("",keys.Key.TAB,this.actions.insertTab,"Indent / insert tab");
listener.bindKeyString("SHIFT",keys.Key.TAB,this.actions.unindent,"Unindent");listener.bindKeyString("CMD",keys.Key.SQUARE_BRACKET_CLOSE,this.actions.indent,"Indent");
listener.bindKeyString("CMD",keys.Key.SQUARE_BRACKET_OPEN,this.actions.unindent,"Unindent");
listener.bindKeyString("",keys.Key.ESCAPE,this.actions.escape,"Clear fields and dialogs");
listener.bindKeyString("CMD",keys.Key.A,this.actions.selectAll,"Select All");listener.bindKeyString("CMD",keys.Key.I,this.actions.toggleQuickopen,"Toggle Quickopen");
listener.bindKeyString("CMD",keys.Key.J,this.actions.focusCommandline,"Open Command line");
listener.bindKeyString("CMD",keys.Key.O,this.actions.focusFileBrowser,"Open File Browser");
listener.bindKeyString("CMD",keys.Key.F,this.actions.cmdFilesearch,"Search in this file");
listener.bindKeyString("CMD",keys.Key.G,this.actions.findNext,"Find Next");listener.bindKeyString("SHIFT CMD",keys.Key.G,this.actions.findPrev,"Find Previous");
listener.bindKeyString("CTRL",keys.Key.M,this.actions.togglePieMenu,"Open Pie Menu");
listener.bindKeyString("CMD",keys.Key.Z,this.actions.undo,"Undo");listener.bindKeyString("SHIFT CMD",keys.Key.Z,this.actions.redo,"Redo");
listener.bindKeyString("CMD",keys.Key.Y,this.actions.redo,"Redo");listener.bindKeyStringSelectable("CMD",keys.Key.UP_ARROW,this.actions.moveToFileTop,"Move to top of file");
listener.bindKeyStringSelectable("CMD",keys.Key.DOWN_ARROW,this.actions.moveToFileBottom,"Move to bottom of file");
listener.bindKeyStringSelectable("CMD",keys.Key.HOME,this.actions.moveToFileTop,"Move to top of file");
listener.bindKeyStringSelectable("CMD",keys.Key.END,this.actions.moveToFileBottom,"Move to bottom of file");
listener.bindKeyStringSelectable("",keys.Key.PAGE_UP,this.actions.movePageUp,"Move a page up");
listener.bindKeyStringSelectable("",keys.Key.PAGE_DOWN,this.actions.movePageDown,"Move a page down");
listener.bindKeyStringSelectable("ALT",keys.Key.UP_ARROW,this.actions.movePageUp,"Move up a block");
listener.bindKeyStringSelectable("ALT",keys.Key.DOWN_ARROW,this.actions.movePageDown,"Move down a block");
listener.bindKeyString("CMD ALT",keys.Key.LEFT_ARROW,this.actions.previousFile);listener.bindKeyString("CMD ALT",keys.Key.RIGHT_ARROW,this.actions.nextFile);
},getHeight:function(){return this.get("lineHeight")*this.get("content").getRowCount()+this.get("padding").bottom;
},charWidth:function(){return this.getCharacterWidth(this.editor.theme.editorTextFont);
}.property(),lineHeight:function(key,value){var theme=this.editor.theme;var userLineHeight=theme.lineHeight;
return !SC.none(userLineHeight)?userLineHeight:this.guessLineHeight(theme.editorTextFont);
}.property().cacheable(),textWidth:function(key,value){return this.get("charWidth")*(this.getMaxCols(0,this.get("content").getRowCount()-1)+1);
}.property("content","charWidth"),layout:function(key,value){var origin=this._origin;
if(!SC.none(value)){origin.left=value.left;origin.top=value.top;}var canvas=this.$()[0];
if(SC.none(canvas)){return{left:origin.left,top:origin.top,width:32,height:32};}return{left:origin.left,top:origin.top,width:this.LINE_INSETS.left+this.get("textWidth")+this.get("padding").right,height:this.get("lineHeight")*this.get("content").getRowCount()+this.get("padding").bottom};
}.property("canvas","content","lineHeight","padding","textWidth"),_origin:{top:0,left:0},resetCanvas:function(){},fillText:function(ctx,text,x,y){ctx.fillText(text,x,y);
},fillTextWithTransparency:function(ctx,text,x,y){ctx.globalAlpha=0.3;ctx.fillText(text,x,y);
ctx.globalAlpha=1;},_firstPaint:false,drawRect:function(ctx,visibleFrame){var content=this.get("content");
if(!this._firstPaint){this.propertyWillChange("layout");this.propertyDidChange("layout",this.get("layout"));
}fullRefresh=true;var ed=this.editor;var c=this.$()[0];var theme=ed.theme;var x,y;
var cy;var currentLine;var Rect=scroller.Rect;var refreshCanvas=fullRefresh;if(!refreshCanvas){refreshCanvas=(this.selectMouseDownPos);
}if(!refreshCanvas){refreshCanvas=(this.lastLineCount!=content.getRowCount());}this.lastLineCount=content.getRowCount();
var cwidth=c.width;var cheight=c.height;var lineHeight=this.get("lineHeight");var firstVisibleRow=Math.floor(visibleFrame.y/lineHeight);
var visibleRows=Math.ceil(visibleFrame.height/lineHeight);var lastLineToRender=Math.min(firstVisibleRow+visibleRows,content.getRowCount()-1);
var virtualheight=this.getHeight();var virtualwidth=this.LINE_INSETS.left+this.get("textWidth");
if(this.editor.debugMode&&bespin.get("editSession")){bespin.getComponent("breakpoints",function(bpmanager){var points=bpmanager.getBreakpoints(bespin.get("editSession").project,bespin.get("editSession").path);
points.forEach(function(point){breakpoints[point.lineNumber]=point;});});}if(!refreshCanvas){var dirty=content.getDirtyRows();
if((this.lastCursorPos)&&(this.lastCursorPos.row!=ed.cursorManager.getCursorPosition().row)){dirty[this.lastCursorPos.row]=true;
}dirty[ed.cursorManager.getCursorPosition().row]=true;}this.lastCursorPos=cursor.copyPos(ed.cursorManager.getCursorPosition());
ctx.save();if(refreshCanvas){ctx.fillStyle=theme.backgroundStyle;ctx.fillRect(visibleFrame.x,visibleFrame.y,visibleFrame.width,visibleFrame.height);
}ctx.save();var charWidth=this.get("charWidth");var firstColumn=0;var lastColumn=firstColumn+Math.ceil(cwidth/charWidth);
y=lineHeight*firstVisibleRow;var cc;var ce;var ri;var regionlen;var tx,tw,tsel;var settings=bespin.get("settings");
var searchStringLength=(this.searchString?this.searchString.length:-1);for(currentLine=firstVisibleRow;
currentLine<=lastLineToRender;currentLine++){x=0;if(!refreshCanvas){if(!dirty[currentLine]){y+=lineHeight;
continue;}ctx.save();ctx.beginPath();ctx.rect(x,y,cwidth,lineHeight);ctx.closePath();
ctx.clip();if((currentLine%2)==1){ctx.fillStyle=theme.backgroundStyle;ctx.fillRect(x,y,cwidth,lineHeight);
}}if(settings.values.highlightline&&currentLine==ed.cursorManager.getCursorPosition().row){ctx.fillStyle=theme.highlightCurrentLineColor;
ctx.fillRect(x,y,cwidth,lineHeight);}else{if((currentLine%2)===0){ctx.fillStyle=theme.zebraStripeColor;
ctx.fillRect(x,y,cwidth,lineHeight);}}x+=this.LINE_INSETS.left;cy=y+(lineHeight-this.LINE_INSETS.bottom);
var selections=this.selectionHelper.getRowSelectionPositions(currentLine);if(selections){tx=x+(selections.startCol*charWidth);
tw=(selections.endCol==-1)?(lastColumn-firstColumn)*charWidth:(selections.endCol-selections.startCol)*charWidth;
ctx.fillStyle=theme.editorSelectedTextBackground;ctx.fillRect(tx,y,tw,lineHeight);
}var lineMetadata=content.getRowMetadata(currentLine);var lineText=lineMetadata.lineText;
var searchIndices=lineMetadata.searchIndices;var lineInfo=this.syntaxModel.getSyntaxStylesPerLine(lineText,currentLine,this.editor.language);
var readOnlyAwareFill=ed.readonly?this.fillTextWithTransparency:this.fillText;for(ri=0;
ri<lineInfo.regions.length;ri++){var styleInfo=lineInfo.regions[ri];for(var style in styleInfo){if(!styleInfo.hasOwnProperty(style)){continue;
}var thisLine="";var styleArray=styleInfo[style];var currentColumn=0;for(var si=0;
si<styleArray.length;si++){var range=styleArray[si];for(;currentColumn<range.start;
currentColumn++){thisLine+=" ";}thisLine+=lineInfo.text.substring(range.start,range.stop);
currentColumn=range.stop;}ctx.fillStyle=this.editor.theme[style]||"white";ctx.font=this.editor.theme.editorTextFont;
readOnlyAwareFill(ctx,thisLine,x,cy);}}if(searchIndices){if(selections){tsel={startCol:0,endCol:lineText.length};
if(selections.startCol!=-1){tsel.startCol=selections.startCol;}if(selections.endCol!=-1){tsel.endCol=selections.endCol;
}}else{tsel=false;}for(var i=0;i<searchIndices.length;i++){var index=ed.cursorManager.getCursorPosition({col:searchIndices[i],row:currentLine}).col;
tx=x+index*charWidth;ctx.fillStyle=this.editor.theme.searchHighlight;ctx.fillRect(tx,y,searchStringLength*charWidth,lineHeight);
if(tsel){var indexStart=index;var indexEnd=index+searchStringLength;if(tsel.startCol<indexEnd&&tsel.endCol>indexStart){indexStart=Math.max(indexStart,tsel.startCol);
indexEnd=Math.min(indexEnd,tsel.endCol);ctx.fillStyle=this.editor.theme.searchHighlightSelected;
ctx.fillRect(x+indexStart*charWidth,y,(indexEnd-indexStart)*charWidth,lineHeight);
}}ctx.fillStyle=this.editor.theme.editorTextColor||"white";ctx.fillText(lineText.substring(index,index+searchStringLength),tx,cy);
}}if(settings.values.tabarrow||settings.values.tabshowspace){if(lineMetadata.tabExpansions.length>0){for(i=0;
i<lineMetadata.tabExpansions.length;i++){var expansion=lineMetadata.tabExpansions[i];
var lx=x+(expansion.start*charWidth);var showTabSpace=settings.values.tabshowspace;
if(showTabSpace){var sw=(expansion.end-expansion.start)*charWidth;ctx.fillStyle=this.editor.theme.tabSpace||"white";
ctx.fillRect(lx,y,sw,lineHeight);}var showTabNib=settings.values.tabarrow;if(showTabNib){cy=y+(lineHeight/2);
var cx=lx+(charWidth/2);tw=4;var th=6;tx=parseInt(cx-(tw/2),10);var ty=parseInt(cy-(th/2),10);
ctx.globalAlpha=0.3;ctx.beginPath();ctx.fillStyle=this.editor.theme.plain||"white";
ctx.moveTo(tx,ty);ctx.lineTo(tx,ty+th);ctx.lineTo(tx+tw,ty+parseInt(th/2,10));ctx.closePath();
ctx.fill();ctx.globalAlpha=1;}}}}y+=lineHeight;}if(this.focus){if(this.showCursor){if(ed.theme.cursorType=="underline"){x=this.LINE_INSETS.left+ed.cursorManager.getCursorPosition().col*charWidth;
y=(ed.getCursorPos().row*lineHeight)+(lineHeight-5);ctx.fillStyle=ed.theme.cursorStyle;
ctx.fillRect(x,y,charWidth,3);}else{x=this.LINE_INSETS.left+ed.cursorManager.getCursorPosition().col*charWidth;
y=(ed.cursorManager.getCursorPosition().row*lineHeight);ctx.fillStyle=ed.theme.cursorStyle;
ctx.fillRect(x,y,1,lineHeight);}}}else{x=this.LINE_INSETS.left+ed.cursorManager.getCursorPosition().col*charWidth;
y=(ed.cursorManager.getCursorPosition().row*lineHeight);ctx.fillStyle=ed.theme.unfocusedCursorFillStyle;
ctx.strokeStyle=ed.theme.unfocusedCursorStrokeStyle;ctx.fillRect(x,y,charWidth,lineHeight);
ctx.strokeRect(x,y,charWidth,lineHeight);}var session=bespin.get("editSession");if(session){var userEntries=session.getUserEntries();
if(userEntries){userEntries.forEach(function(userEntry){if(!userEntry.clientData.isMe){x=this.LINE_INSETS.left+userEntry.clientData.cursor.start.col*charWidth;
y=userEntry.clientData.cursor.start.row*lineHeight;ctx.fillStyle="#ee8c00";ctx.fillRect(x,y,1,lineHeight);
var prevFont=ctx.font;ctx.font="6pt Monaco, Lucida Console, monospace";ctx.fillText(userEntry.handle,x+3,y+lineHeight+4);
ctx.font=prevFont;}}.bind(this));}}if(this.changes){this.changes.forEach(function(change){ctx.strokeStyle="#211A16";
ctx.beginPath();x=this.LINE_INSETS.left+180*charWidth;y=change.start.row*lineHeight;
ctx.moveTo(x,y);x=this.LINE_INSETS.left+change.start.col*charWidth;ctx.lineTo(x,y);
y+=lineHeight;ctx.lineTo(x,y);x=this.LINE_INSETS.left;ctx.lineTo(x,y);y=(change.end.row+1)*lineHeight;
ctx.lineTo(x,y);x=this.LINE_INSETS.left+change.end.col*charWidth;ctx.lineTo(x,y);
y=change.end.row*lineHeight;ctx.lineTo(x,y);x=this.LINE_INSETS.left+180*charWidth;
ctx.lineTo(x,y);y=change.start.row*lineHeight;ctx.lineTo(x,y);ctx.stroke();}.bind(this));
}ctx.restore();ctx.restore();},getRowString:function(row){var content=this.get("content");
return content.getRowMetadata(row).lineText;},getRowScreenLength:function(row){return this.getRowString(row).length;
},getMaxCols:function(firstRow,lastRow){var cols=0;for(var i=firstRow;i<=lastRow;
i++){cols=Math.max(cols,this.getRowScreenLength(i));}return cols;},setSearchString:function(str){var content=this.get("content");
if(str&&str!==""){this.searchString=str;}else{delete this.searchString;}content.searchStringChanged(this.searchString);
this.editor.paint(true);},setChanges:function(changes){this.changes=changes;console.log("changes=",this.changes);
},rowCount:0,_scrollToFrameVisible:function(frame){var clippingFrame=this.get("clippingFrame");
var padding=this.get("padding");var preferredFrame={x:clippingFrame.x,y:clippingFrame.y,width:clippingFrame.width-padding.right,height:clippingFrame.height-padding.bottom};
var targetX;var frameRight=frame.x+frame.width;if(frame.x<preferredFrame.x){targetX=frame.x;
}else{if(frameRight>=preferredFrame.x+preferredFrame.width){targetX=frameRight-preferredFrame.width;
}else{targetX=preferredFrame.x;}}var targetY;var frameBottom=frame.y+frame.height;
if(frame.y<preferredFrame.y){targetY=frame.y;}else{if(frameBottom>=preferredFrame.y+preferredFrame.height){targetY=frameBottom-preferredFrame.height;
}else{targetY=preferredFrame.y;}}if(targetX===preferredFrame.x&&targetY===preferredFrame.y){return false;
}var scrollable=this;do{scrollable=scrollable.get("parentView");if(scrollable===null){return false;
}}while(scrollable.get("isScrollable")!==true);scrollable.scrollToVisible();return scrollable.scrollTo(targetX,targetY);
},_scrollToCharVisible:function(pos){var charWidth=this.get("charWidth");var lineHeight=this.get("lineHeight");
return this._scrollToFrameVisible({x:pos.col===0?0:this.LINE_INSETS.left+pos.col*charWidth,y:pos.row*lineHeight,width:charWidth,height:lineHeight});
},_scrollToCursorVisible:function(){var cursorPos=this.editor.cursorManager.getCursorPosition();
return this._scrollToCharVisible(cursorPos);},_updateRowCount:function(){this.set("rowCount",this.get("content").getRowCount());
},cursorDidMove:function(sender,newPosition){SC.RunLoop.begin();this.propertyWillChange("layout");
this.propertyDidChange("layout",this.get("layout"));this._scrollToCursorVisible();
this._updateRowCount();SC.RunLoop.end();},textStorageEdited:function(sender){SC.RunLoop.begin();
this.notifyPropertyChange("layout",this.get("layout"));this._updateRowCount();SC.RunLoop.end();
},dispose:function(){},_bespin_editorView_parentViewFrameDidChange:function(){this.propertyWillChange("layerFrame");
this.propertyDidChange("layerFrame",this.get("layerFrame"));}.observes("*parentView.frame")});
bespin.subscribe("settings:set:cursorblink",function(event){var ms=parseInt(event.value,10);
if(ms){var editor=bespin.get("editor");editor.ui.toggleCursorFrequency=ms;}});bespin.subscribe("settings:set:fontsize",function(event){var editor=bespin.get("editor");
var fontsize=parseInt(event.value,10);editor.theme.editorTextFont=editor.theme.editorTextFont.replace(/[0-9]{1,}pt/,fontsize+"pt");
editor.theme.lineNumberFont=editor.theme.lineNumberFont.replace(/[0-9]{1,}pt/,fontsize+"pt");
});bespin.get("settings").addSetting({name:"fontsize",type:"number",defaultValue:10});
bespin.subscribe("settings:set:theme",function(event){var editor=bespin.get("editor");
var settings=bespin.get("settings");var files=bespin.get("files");var theme=event.value;
var checkSetAndExit=function(){var themeSettings=themes[theme];if(themeSettings){if(themeSettings!=editor.theme){editor.theme=themeSettings;
}return true;}return false;};if(theme){if(checkSetAndExit()){return true;}try{var req=require;
req.call(window,"themes."+theme);if(checkSetAndExit()){return true;}}catch(e){console.log("Unable to load theme: "+theme,e);
}var onSuccess=function(file){try{eval(file.content);}catch(e){console.log("Error with theme loading: ",e);
}if(!checkSetAndExit()){bespin.get("commandLine").addErrorOutput("Sorry old chap. No theme called '"+theme+"'. Fancy making it?");
}};var onFailure=function(){bespin.get("commandLine").addErrorOutput("Sorry old chap. No theme called '"+theme+"'. Fancy making it?");
};files.loadContents(files.userSettingsProject,"/themes/"+theme+".js",onSuccess,onFailure);
}return false;});var EditorWrapper=SC.Object.extend({editor:null,ui:null,focus:function(){this.ui.setFocus(true);
},hasFocus:function(){return this.ui.hasFocus();},getFocusElement:function(){return this.ui._getFocusElement();
},removeSelection:function(){var selectionObject=this.editor.getSelection();var text=null;
if(selectionObject){text=this.editor.model.getChunk(selectionObject);if(text&&text!==""){this.ui.actions.beginEdit("cut");
this.ui.actions.deleteSelection(selectionObject);this.ui.actions.endEdit();}}return text;
},getSelection:function(){return this.editor.getSelectionAsText();},replaceSelection:function(text){var args=cursor.buildArgs();
args.chunk=text;if(args.chunk){this.ui.actions.beginEdit("paste");this.ui.actions.insertChunk(args);
this.ui.actions.endEdit();}},installEditorOnly:function(){this.editor.bindKey("copySelection","CMD C");
this.editor.bindKey("pasteFromClipboard","CMD V");this.editor.bindKey("cutSelection","CMD X");
}});});tiki.module("bespin:editor/views/gutter",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var canvas=require("editor/mixins/canvas");var GUTTER_INSETS={left:5,right:10,bottom:6};
var LINE_INSETS={bottom:6};exports.GutterView=SC.View.extend(canvas.Canvas,{classNames:"sc-gutter-view",tagName:"canvas",editorView:null,rowCount:0,theme:{gutterStyle:"#4c4a41",lineNumberColor:"#e5c138",lineNumberFont:"10pt Monaco, Lucida Console, monospace",editorTextFont:"10pt Monaco, Lucida Console, monospace"},layout:function(key,value){var origin=this._origin;
if(!SC.none(value)){origin.left=value.left;origin.top=value.top;}var canvas=this.$()[0];
if(SC.none(canvas)){return{left:origin.left,top:origin.top,width:0,height:0};}var rowCount=this.get("rowCount");
return{left:origin.left,top:origin.top,width:GUTTER_INSETS.left+rowCount.toString().length*this.get("_charWidth")+GUTTER_INSETS.right,height:rowCount*this.get("_lineHeight")};
}.property("_charWidth","_lineHeight","rowCount"),_origin:{left:0,top:0},layerFrame:function(){return{x:0,y:0,width:this.get("layout").width,height:this.get("parentView").get("frame").height};
}.property("layout","parentView"),_charWidth:function(){return this.getCharacterWidth(this.get("theme").editorTextFont);
}.property("theme").cacheable(),_lineHeight:function(){var theme=this.get("theme");
var userLineHeight=theme.lineHeight;return !SC.none(userLineHeight)?userLineHeight:this.guessLineHeight(theme.editorTextFont);
}.property("theme").cacheable(),drawRect:function(ctx,visibleFrame){var theme=this.get("theme");
ctx.fillStyle=theme.gutterStyle;ctx.fillRect(0,visibleFrame.y,visibleFrame.width,visibleFrame.height);
var lineHeight=this.get("_lineHeight");var firstVisibleRow=Math.floor(visibleFrame.y/lineHeight);
var lastLineToRender=Math.min(this.get("rowCount")-1,Math.ceil((visibleFrame.y+visibleFrame.height)/lineHeight));
for(var currentLine=firstVisibleRow;currentLine<=lastLineToRender;currentLine++){ctx.fillStyle=theme.lineNumberColor;
ctx.font=theme.lineNumberFont;ctx.fillText(""+(currentLine+1),GUTTER_INSETS.left,(currentLine+1)*lineHeight-LINE_INSETS.bottom);
}},_bespin_gutterView_parentViewFrameDidChange:function(){this.propertyWillChange("layerFrame");
this.propertyDidChange("layerFrame",this.get("layerFrame"));}.observes("*parentView.frame"),_bespin_gutterView_rowCountDidChange:function(){this.updateLayout();
this.set("layerNeedsUpdate",true);}.observes("rowCount"),_bespin_gutterView_frameDidChange:function(){this.set("layerNeedsUpdate",true);
}.observes("frame")});});tiki.module("bespin:editor/views/scroll",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var gutter=require("editor/views/gutter");var scroller=require("editor/views/scroller");
exports.BespinScrollView=SC.ScrollView.extend({_gutterViewInstantiated:false,gutterView:gutter.GutterView,hasHorizontalScroller:true,autohidesHorizontalScroller:false,horizontalScrollerView:scroller.BespinScrollerView,hasVerticalScroller:true,autohidesVerticalScroller:false,verticalScrollerView:scroller.BespinScrollerView,horizontalScrollerThickness:24,verticalScrollerThickness:24,tile:function(){var gutterView=this.get("gutterView");
if(this._gutterViewInstantiated===false){this._gutterViewInstantiated=true;var thisBespinScrollView=this;
gutterView=this.createChildView(gutterView,{rowCountBinding:"*parentView.contentView.rowCount",didCreateLayer:function(){thisBespinScrollView.tile();
this.set("layerNeedsUpdate",true);}});this.childViews.push(gutterView);this.set("gutterView",gutterView);
gutterView.addObserver("frame",this,this.tile);return;}var gutterFrame=gutterView.get("frame");
this.get("containerView").set("layout",{left:gutterFrame.width,bottom:0,top:0,right:0});
var hScroller=this.get("horizontalScrollerView");var vScroller=this.get("verticalScrollerView");
var hScrollerVisible=this.get("isHorizontalScrollerVisible");var vScrollerVisible=this.get("isVerticalScrollerVisible");
var hScrollerThickness=this.get("horizontalScrollerThickness");var vScrollerThickness=this.get("verticalScrollerThickness");
if(hScrollerVisible){hScroller=this.get("horizontalScrollerView");hScroller.set("scrollerThickness",hScrollerThickness);
hScroller.set("padding",{top:0,bottom:6,left:6,right:6+vScrollerThickness});hScroller.set("layout",{left:gutterFrame.width,bottom:0,right:0,height:hScrollerThickness});
}if(vScrollerVisible){vScroller=this.get("verticalScrollerView");vScroller.set("scrollerThickness",vScrollerThickness);
vScroller.set("padding",{left:0,right:6,top:6,bottom:6+hScrollerThickness});vScroller.set("layout",{top:0,right:0,bottom:0,width:vScrollerThickness});
}var contentView=this.get("contentView");if(contentView.get("hasPadding")===true){this.get("contentView").set("padding",{bottom:hScrollerThickness+6,right:vScrollerThickness+6});
}},_bespin_BespinScrollView_verticalScrollOffsetDidChange:function(){this.get("gutterView").adjust({left:0,top:-Math.min(this.get("verticalScrollOffset"),this.get("maximumVerticalScrollOffset"))});
}.observes("verticalScrollOffset")});});tiki.module("bespin:editor/views/scroller",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var canvas=require("editor/mixins/canvas");var NIB_ARROW_PADDING_BEFORE=3;var NIB_ARROW_PADDING_AFTER=5;
var NIB_LENGTH=15;var NIB_PADDING=8;exports.BespinScrollerView=SC.View.extend(canvas.Canvas,{classNames:["bespin-scroller-view"],_mouseDownScreenPoint:null,_mouseDownValue:null,_isMouseOver:false,_value:0,_bespinScrollerView_valueDidChange:function(){this.set("layerNeedsUpdate",true);
}.observes("value"),_bespinScrollerView_maximumDidChange:function(){this.set("layerNeedsUpdate",true);
}.observes("maximum"),theme:{backgroundStyle:"#2A211C",partialNibStyle:"rgba(100, 100, 100, 0.3)",partialNibArrowStyle:"rgba(255, 255, 255, 0.3)",partialNibStrokeStyle:"rgba(150, 150, 150, 0.3)",fullNibStyle:"rgb(100, 100, 100)",fullNibArrowStyle:"rgb(255, 255, 255)",fullNibStrokeStyle:"rgb(150, 150, 150)",scrollTrackFillStyle:"rgba(50, 50, 50, 0.8)",scrollTrackStrokeStyle:"rgb(150, 150, 150)",scrollBarFillStyle:"rgba(0, 0, 0, %a)",scrollBarFillGradientTopStart:"rgba(90, 90, 90, %a)",scrollBarFillGradientTopStop:"rgba(40, 40, 40, %a)",scrollBarFillGradientBottomStart:"rgba(22, 22, 22, %a)",scrollBarFillGradientBottomStop:"rgba(44, 44, 44, %a)"},scrollerThickness:SC.NATURAL_SCROLLER_THICKNESS,minimumHandleSize:20,lineHeight:15,layoutDirection:SC.LAYOUT_VERTICAL,isEnabled:true,ownerScrollValueKey:function(){switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:return"verticalScrollOffset";
case SC.LAYOUT_HORIZONTAL:return"horizontalScrollOffset";default:return null;}}.property("layoutDirection").cacheable(),padding:{left:0,bottom:0,top:0,right:0},_clientFrame:function(){var frame=this.get("frame"),padding=this.get("padding");
return{x:padding.left,y:padding.top,width:frame.width-(padding.left+padding.right),height:frame.height-(padding.top+padding.bottom)};
}.property("frame","padding").cacheable(),_clientThickness:function(){var padding=this.get("padding");
var scrollerThickness=this.get("scrollerThickness");switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:return scrollerThickness-(padding.left+padding.right);
case SC.LAYOUT_HORIZONTAL:return scrollerThickness-(padding.top+padding.bottom);default:console.assert(false,"unknown layout direction");
return null;}}.property("layoutDirection","padding","scrollerThickness").cacheable(),_gutterFrame:function(){var clientFrame=this.get("_clientFrame");
var thickness=this.get("_clientThickness");switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:return{x:clientFrame.x,y:clientFrame.y+NIB_LENGTH,width:thickness,height:Math.max(0,clientFrame.height-2*NIB_LENGTH)};
case SC.LAYOUT_HORIZONTAL:return{x:clientFrame.x+NIB_LENGTH,y:clientFrame.y,width:Math.max(0,clientFrame.width-2*NIB_LENGTH),height:thickness};
default:console.assert(false,"unknown layout direction");return null;}}.property("_clientFrame","_clientThickness","layoutDirection").cacheable(),_gutterLength:function(){var gutterFrame=this.get("_gutterFrame");
var gutterLength;switch(this.get("layoutDirection")){case SC.LAYOUT_HORIZONTAL:gutterLength=gutterFrame.width;
break;case SC.LAYOUT_VERTICAL:gutterLength=gutterFrame.height;break;default:console.assert(false,"unknown layout direction");
break;}return gutterLength;}.property("_gutterFrame","layoutDirection").cacheable(),_frameLength:function(){var frame=this.get("frame");
switch(this.get("layoutDirection")){case SC.LAYOUT_HORIZONTAL:return frame.width;
case SC.LAYOUT_VERTICAL:return frame.height;default:console.assert(false,"unknown layout direction");
return null;}}.property("frame","layoutDirection").cacheable(),_clientLength:function(){var clientFrame=this.get("_clientFrame");
switch(this.get("layoutDirection")){case SC.LAYOUT_HORIZONTAL:return clientFrame.width;
case SC.LAYOUT_VERTICAL:return clientFrame.height;default:console.assert(false,"unknown layout direction");
return null;}}.property("_clientFrame","layoutDirection").cacheable(),_handleFrame:function(){var value=this.get("value");
var maximum=this.get("maximum");var frame=this.get("frame");var clientFrame=this.get("_clientFrame");
var gutterFrame=this.get("_gutterFrame");var clientThickness=this.get("_clientThickness");
switch(this.get("layoutDirection")){case SC.LAYOUT_VERTICAL:return{x:clientFrame.x,y:clientFrame.y+NIB_LENGTH+value*gutterFrame.height/maximum,width:clientThickness,height:Math.min(frame.height,maximum)*gutterFrame.height/maximum};
case SC.LAYOUT_HORIZONTAL:return{x:clientFrame.x+NIB_LENGTH+value*gutterFrame.width/maximum,y:clientFrame.y,width:Math.min(frame.width,maximum)*gutterFrame.width/maximum,height:clientThickness};
default:console.assert(false,"unknown layout direction");return null;}}.property("_clientFrame","_clientThickness","_gutterFrame","maximum","value").cacheable(),maximumValue:function(){return Math.max(this.get("maximum")-this.get("_frameLength"),0);
}.property("_frameLength","maximum").cacheable(),value:function(key,value){var maximumValue=this.get("maximumValue");
if(value!==undefined){if(value<0){value=0;}else{if(value>maximumValue){value=maximumValue;
}}this._value=value;return value;}return Math.min(this._value||0,maximumValue);}.property("maximumValue").cacheable(),maximum:0,_segmentForMouseEvent:function(evt){var point=this.convertFrameFromView({x:evt.pageX,y:evt.pageY});
var clientFrame=this.get("_clientFrame");if(!SC.pointInRect(point,clientFrame)){return null;
}var layoutDirection=this.get("layoutDirection");switch(layoutDirection){case SC.LAYOUT_HORIZONTAL:if(point.x<NIB_LENGTH){return"nib-start";
}else{if(point.x>=clientFrame.width-NIB_LENGTH){return"nib-end";}}break;case SC.LAYOUT_VERTICAL:if(point.y<NIB_LENGTH){return"nib-start";
}else{if(point.y>=clientFrame.height-NIB_LENGTH){return"nib-end";}}break;default:console.assert(false,"unknown layout direction");
break;}var handleFrame=this.get("_handleFrame");if(SC.pointInRect(point,handleFrame)){return"handle";
}switch(layoutDirection){case SC.LAYOUT_HORIZONTAL:if(point.x<handleFrame.x){return"gutter-before";
}else{if(point.x>=handleFrame.x+handleFrame.width){return"gutter-after";}}break;case SC.LAYOUT_VERTICAL:if(point.y<handleFrame.y){return"gutter-before";
}else{if(point.y>=handleFrame.y+handleFrame.height){return"gutter-after";}}break;
default:console.assert(false,"unknown layout direction");break;}console.assert(false,"_segmentForMouseEvent: point ",point," outside view with handle frame ",handleFrame," and client frame ",clientFrame);
return null;},mouseEntered:function(evt){SC.RunLoop.begin();this._isMouseOver=true;
this.set("layerNeedsUpdate",true);SC.RunLoop.end();},mouseExited:function(evt){SC.RunLoop.begin();
this._isMouseOver=false;this._mouseDownScreenPoint=null;this.set("layerNeedsUpdate",true);
SC.RunLoop.end();},mouseWheel:function(evt){SC.RunLoop.begin();var delta;switch(this.get("layoutDirection")){case SC.LAYOUT_HORIZONTAL:delta=evt.wheelDeltaX;
break;case SC.LAYOUT_VERTICAL:delta=evt.wheelDeltaY;break;default:console.assert(false,"unknown layout direction");
return;}this.set("value",this.get("value")+2*delta);SC.RunLoop.end();},mouseDown:function(evt){SC.RunLoop.begin();
var value=this.get("value");var gutterLength=this.get("_gutterLength");switch(this._segmentForMouseEvent(evt)){case"nib-start":this.set("value",value-this.get("lineHeight"));
break;case"nib-end":this.set("value",value+this.get("lineHeight"));break;case"gutter-before":this.set("value",value-gutterLength);
break;case"gutter-after":this.set("value",value+gutterLength);break;case"handle":switch(this.get("layoutDirection")){case SC.LAYOUT_HORIZONTAL:this._mouseDownScreenPoint=evt.clientX;
break;case SC.LAYOUT_VERTICAL:this._mouseDownScreenPoint=evt.clientY;break;default:console.assert(false,"unknown layout direction");
break;}default:console.assert("_segmentForMouseEvent returned an unknown value");
break;}SC.RunLoop.end();},mouseUp:function(evt){this._mouseDownScreenPoint=null;this._mouseDownValue=null;
},mouseMoved:function(evt){SC.RunLoop.begin();if(this._mouseDownScreenPoint!==null){var eventDistance;
switch(this.get("layoutDirection")){case SC.LAYOUT_HORIZONTAL:eventDistance=evt.clientX;
break;case SC.LAYOUT_VERTICAL:eventDistance=evt.clientY;break;default:console.assert(false,"unknown layout direction");
break;}var eventDelta=eventDistance-this._mouseDownScreenPoint;var maximum=this.get("maximum");
var gutterLength=this.get("_gutterLength");this.set("value",this.get("value")+eventDelta*maximum/gutterLength);
this._mouseDownScreenPoint=eventDistance;}SC.RunLoop.end();},_drawNib:function(ctx){var theme=this.get("theme");
var fillStyle,arrowStyle,strokeStyle;if(this._isMouseOver){fillStyle=theme.fullNibStyle;
arrowStyle=theme.fullNibArrowStyle;strokeStyle=theme.fullNibStrokeStyle;}else{fillStyle=theme.partialNibStyle;
arrowStyle=theme.partialNibArrowStyle;strokeStyle=theme.partialNibStrokeStyle;}var midpoint=Math.floor(NIB_LENGTH/2);
ctx.fillStyle=fillStyle;ctx.beginPath();ctx.arc(0,0,Math.floor(NIB_LENGTH/2),0,Math.PI*2,true);
ctx.closePath();ctx.fill();ctx.strokeStyle=strokeStyle;ctx.stroke();ctx.fillStyle=arrowStyle;
ctx.beginPath();ctx.moveTo(0,-midpoint+NIB_ARROW_PADDING_BEFORE);ctx.lineTo(-midpoint+NIB_ARROW_PADDING_BEFORE,midpoint-NIB_ARROW_PADDING_AFTER);
ctx.lineTo(midpoint-NIB_ARROW_PADDING_BEFORE,midpoint-NIB_ARROW_PADDING_AFTER);ctx.closePath();
ctx.fill();},_drawNibs:function(ctx){var isMouseOver=this._isMouseOver;var thickness=this.get("_clientThickness");
var value=this.get("value");if(isMouseOver||value!==0){ctx.save();ctx.translate(NIB_PADDING,thickness/2);
ctx.rotate(Math.PI*1.5);ctx.moveTo(0,0);this._drawNib(ctx);ctx.restore();}if(isMouseOver||value!==this.get("maximumValue")){ctx.save();
ctx.translate(this.get("_clientLength")-NIB_PADDING,thickness/2);ctx.rotate(Math.PI*0.5);
ctx.moveTo(0,0);this._drawNib(ctx);ctx.restore();}},drawRect:function(ctx,visibleFrame){var alpha=(ctx.globalAlpha)?ctx.globalAlpha:1;
var theme=this.get("theme");var frame=this.get("frame");ctx.clearRect(0,0,frame.width,frame.height);
ctx.save();var padding=this.get("padding");ctx.translate(padding.left,padding.top);
var handleFrame=this.get("_handleFrame");var gutterLength=this.get("_gutterLength");
var thickness=this.get("_clientThickness");var halfThickness=thickness/2;var layoutDirection=this.get("layoutDirection");
var handleDistance,handleLength;switch(layoutDirection){case SC.LAYOUT_VERTICAL:handleDistance=handleFrame.y-padding.top;
handleLength=handleFrame.height;ctx.translate(thickness+1,0);ctx.rotate(Math.PI*0.5);
break;case SC.LAYOUT_HORIZONTAL:handleDistance=handleFrame.x-padding.left;handleLength=handleFrame.width;
break;default:console.assert(false,"unknown layout direction");break;}if(this.get("isEnabled")===false||gutterLength<=handleLength){return;
}if(this._isMouseOver===false){ctx.globalAlpha=0.3;}else{var clientLength=this.get("_clientLength");
ctx.fillStyle=theme.scrollTrackFillStyle;ctx.fillRect(NIB_PADDING+0.5,0.5,clientLength-2*NIB_PADDING,thickness-1);
ctx.strokeStyle=theme.scrollTrackStrokeStyle;ctx.strokeRect(NIB_PADDING+0.5,0.5,clientLength-2*NIB_PADDING,thickness-1);
}var buildHandlePath=function(){ctx.beginPath();ctx.arc(handleDistance+halfThickness+0.5,halfThickness,halfThickness-0.5,Math.PI/2,3*Math.PI/2,false);
ctx.arc(handleDistance+handleLength-halfThickness-0.5,halfThickness,halfThickness-0.5,3*Math.PI/2,Math.PI/2,false);
ctx.lineTo(handleDistance+halfThickness+0.5,thickness-0.5);ctx.closePath();};buildHandlePath();
var gradient=ctx.createLinearGradient(handleDistance,0,handleDistance,thickness);
gradient.addColorStop(0,theme.scrollBarFillGradientTopStart.replace(/%a/,alpha));
gradient.addColorStop(0.4,theme.scrollBarFillGradientTopStop.replace(/%a/,alpha));
gradient.addColorStop(0.41,theme.scrollBarFillStyle.replace(/%a/,alpha));gradient.addColorStop(0.8,theme.scrollBarFillGradientBottomStart.replace(/%a/,alpha));
gradient.addColorStop(1,theme.scrollBarFillGradientBottomStop.replace(/%a/,alpha));
ctx.fillStyle=gradient;ctx.fill();ctx.save();ctx.clip();ctx.fillStyle=theme.scrollBarFillStyle.replace(/%a/,alpha);
ctx.beginPath();ctx.moveTo(handleDistance+halfThickness*0.4,halfThickness*0.6);ctx.lineTo(handleDistance+halfThickness*0.9,thickness*0.4);
ctx.lineTo(handleDistance,thickness*0.4);ctx.closePath();ctx.fill();ctx.beginPath();
ctx.moveTo(handleDistance+handleLength-(halfThickness*0.4),0+(halfThickness*0.6));
ctx.lineTo(handleDistance+handleLength-(halfThickness*0.9),0+(thickness*0.4));ctx.lineTo(handleDistance+handleLength,0+(thickness*0.4));
ctx.closePath();ctx.fill();ctx.restore();ctx.save();buildHandlePath();ctx.strokeStyle=theme.scrollTrackStrokeStyle;
ctx.stroke();ctx.restore();if(this._isMouseOver===false){ctx.globalAlpha=1;}this._drawNibs(ctx);
ctx.restore();}});});tiki.module("bespin:embed",function(require,exports,module){require("util/globals");
var SC=require("sproutcore/runtime:package").SC;var bespin=require("package");var containerMod=require("util/container");
var util=require("util/util");var computeLayout=function(element){var layout={top:0,left:0,width:element.clientWidth,height:element.clientHeight};
while(!SC.none(element)){layout.top+=element.offsetTop+element.clientTop;layout.left+=element.offsetLeft+element.clientLeft;
element=element.offsetParent;}return layout;};exports.useBespin=function(element,options){options=options||{};
if(util.isString(element)){element=document.getElementById(element);}if(!element){throw new Error("useBespin requires a element parameter to attach to");
}var content=element.innerHTML;var editor;window.editor=undefined;var container=containerMod.Container.create();
bespin.container=container;SC.run(function(){container.register("container",element);
editor=container.get("editor");var editorPane=SC.Pane.create({layout:computeLayout(element),layoutStyle:function(){var layout=this.get("layout");
var style={width:""+layout.width+"px",height:""+layout.height+"px"};return style;
}.property("layout")});editorPane.appendChild(editor.ui,null);SC.$(element).css("position","relative");
element.innerHTML="";editorPane.appendTo(element);editor.element=element;editor.pane=editorPane;
if(options.initialContent){content=options.initialContent;}editor.model.insertDocument(content);
if(options.settings){for(var key in options.settings){if(options.settings.hasOwnProperty(key)){editor.setSetting(key,options.settings[key]);
}}}if(options.stealFocus){editor.setFocus(true);}if(options.lineNumber){editor.setLineNumber(options.lineNumber);
}if(SC.none(options.dontHookWindowResizeEvent)||!options.dontHookWindowResizeEvent){var handler=function(){exports.dimensionsChanged(editor);
};if(!SC.none(window.addEventListener)){window.addEventListener("resize",handler,false);
}else{if(!SC.none(window.attachEvent)){window.addEventListener("onresize",handler);
}}}});return editor;};exports.dimensionsChanged=function(editor){SC.RunLoop.begin();
var pane=editor.pane;var oldLayout=pane.get("layout");var newLayout=computeLayout(editor.element);
if(!SC.rectsEqual(oldLayout,newLayout)){pane.adjust(newLayout);pane.updateLayout();
}SC.RunLoop.end();};});tiki.module("bespin:events",function(require,exports,module){var bespin=require("package");
var util=require("util/util");exports.subscribe=function(){bespin.subscribe("url:change",function(event){var hashArguments=util.queryToObject(location.hash.substring(1));
hashArguments.project=event.project;hashArguments.path=event.path;var pairs=[];for(var name in hashArguments){var value=hashArguments[name];
pairs.push(name+"="+value);}window.location.hash=pairs.join("&");});bespin.subscribe("url:changed",function(event){bespin.get("editor").openFile(null,event.now.get("path"));
});bespin.subscribe("cmdline:focus",function(event){bespin.get("editor").setFocus(false);
});bespin.subscribe("cmdline:blur",function(event){bespin.get("editor").setFocus(true);
});bespin.subscribe("editor:document:changed",function(event){bespin.publish("editor:dirty");
});bespin.subscribe("editor:dirty",function(event){bespin.get("editor").dirty=true;
});bespin.subscribe("editor:clean",function(event){bespin.get("editor").dirty=false;
});};});tiki.module("bespin:history",function(require,exports,module){var bespin=require("package");
var SC=require("sproutcore/runtime:package").SC;exports.HistoryManager=SC.Object.extend({history:[],historyPosition:-1,disableAdding:false,clear:function(){this.history=[];
this.historyPosition=-1;this.disableAdding=false;},getRange:function(start,end){},replaceRange:function(start,end,withWhat){this.history.splice(start,end-start+1,withWhat);
},truncate:function(keepUntil){this.history.length=keepUntil+1;this.historyPosition=Math.min(this.historyPosition,this.history.length-1);
},getCurrent:function(){return this.historyPosition;},undo:function(){if(this.historyPosition<0){return;
}var current=this.history[this.historyPosition];this.disableAdding=true;try{current.undo();
}catch(e){console.error("There was an error in an undo action: ");console.error(e);
}this.disableAdding=false;this.historyPosition--;},redo:function(){if(this.historyPosition>=this.history.length-1){return;
}var next=this.history[this.historyPosition+1];this.disableAdding=true;try{next.redo();
}catch(e){console.error("There was an error in an undo action: ");console.error(e);
}this.disableAdding=false;this.historyPosition++;},add:function(item){if(this.disableAdding){return;
}this.history.length=this.historyPosition+1;this.history.push(item);this.historyPosition++;
},canUndo:function(){return this.historyPosition>-1;},canRedo:function(){return this.historyPosition<this.history.length-1;
}});bespin.subscribe("editor:openfile:opensuccess",function(){bespin.get("editor").historyManager.clear();
});});tiki.module("bespin:model",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var bespin=require("package");var util=require("util/util");var cursor=require("cursor");
exports.DocumentModel=SC.Object.extend({editor:null,layoutManager:function(){return this.editor.editorView;
}.property(),init:function(){this.clear();},addHistoryItem:function(func,data){this.history.length=this.historyIndex+1;
this.history.push({func:func,data:data});this.historyIndex++;},performHistoryItem:function(item){var func=item.func;
var data=item.data;switch(func){case"deleteCharacters":this.deleteCharacters(data.pos,data.characters.length,true);
break;case"insertCharacters":this.insertCharacters(data.pos,data.characters,true);
break;case"deleteChunk":this.deleteChunk(data.selection,data.chunk,true);break;case"insertChunk":this.insertChunk(data.selection.startModelPos,data.chunk,true);
break;case"joinRow":this.joinRow(data.selection.startModelPos.row,true);break;case"replaceRow":this.replaceRow(data.row,item.undo?data.oldline:data.newline,true);
break;}},unperformHistoryItem:function(item){var func=item.func;var data=item.data;
switch(func){case"deleteCharacters":func="insertCharacters";break;case"insertCharacters":func="deleteCharacters";
break;case"deleteChunk":func="insertChunk";break;case"insertChunk":func="deleteChunk";
break;case"joinRow":func="insertChunk";break;}this.performHistoryItem({func:func,data:data,undo:true});
},applyState:function(state){if(state>=this.history.length||state<-1){return;}else{if(state==this.historyIndex){return;
}}var i,historyItem;if(state>this.historyIndex){for(i=this.historyIndex+1;i<=state;
i++){historyItem=this.history[i];this.performHistoryItem(historyItem);}}else{for(i=this.historyIndex;
i>state;i--){historyItem=this.history[i];this.unperformHistoryItem(historyItem);}}this.historyIndex=state;
},getState:function(){return this.historyIndex;},isEmpty:function(){if(this.rows.length>1){return false;
}if(this.rows.length==1&&this.rows[0].length>0){return false;}return true;},getDirtyRows:function(){var dr=(this.dirtyRows)?this.dirtyRows:[];
this.dirtyRows=null;return dr;},setRowDirty:function(row){if(!this.dirtyRows){this.dirtyRows=new Array(this.rows.length);
}this.dirtyRows[row]=true;},isRowDirty:function(row){if(!this.dirtyRows){return true;
}return this.dirtyRows[row];},setRowArray:function(rowIndex,row){if(!Array.isArray(row)){row=row.split("");
}this.rows[rowIndex]=row;},getRowArray:function(rowIndex){while(this.rows.length<=rowIndex){this.rows.push([]);
}return this.rows[rowIndex];},hasRow:function(rowIndex){return(this.rows[rowIndex]);
},insertCharacters:function(modelPos,string,noHistory){var row=this.getRowArray(modelPos.row);
while(row.length<modelPos.col){row.push(" ");}var newrow=(modelPos.col>0)?row.splice(0,modelPos.col):[];
newrow=newrow.concat(string.split(""));this.rows[modelPos.row]=newrow.concat(row);
this.setRowDirty(modelPos.row);if(!noHistory){this.addHistoryItem("insertCharacters",{pos:cursor.copyPos(modelPos),characters:string});
}this._sendTextEditedNotification();},getDocument:function(){var file=[];for(var x=0;
x<this.getRowCount();x++){file[x]=this.getRowArray(x).join("");}return file.join("\n");
},insertDocument:function(content){this.clear();var rows=content.split("\n");for(var x=0;
x<rows.length;x++){this.insertCharacters({row:x,col:0},rows[x],true);}},changeEachRow:function(changeFunction){for(var x=0;
x<this.getRowCount();x++){var row=this.getRowArray(x);row=changeFunction(row);this.setRowArray(x,row);
}},replace:function(search,replace){var regex=new RegExp(search,"g");for(var x=0;
x<this.getRowCount();x++){var line=this.getRowArray(x).join("");var newline=line.replace(regex,replace);
if(newline!=line){this.replaceRow(x,newline);}}},replaceRow:function(row,newline,noHistory){var oldline=this.getRowArray(row).join("");
this.rows[row]=newline.split("");if(!noHistory){this.addHistoryItem("replaceRow",{row:row,oldline:oldline,newline:newline});
}},deleteCharacters:function(modelPos,length,noHistory){var row=this.getRowArray(modelPos.row);
var diff=(modelPos.col+length-1)-row.length;if(diff>0){length-=diff;}if(length>0){this.setRowDirty(modelPos.row);
this.editor.editorView.syntaxModel.invalidateCache(modelPos.row);var deleted=row.splice(modelPos.col,length).join("");
if(!noHistory){this.addHistoryItem("deleteCharacters",{pos:cursor.copyPos(modelPos),characters:deleted});
}return deleted;}return"";},clear:function(){this.rows=[];this.cacheRowMetadata=[];
this.history=[];this.historyIndex=-1;},deleteRows:function(row,count){var diff=(row+count-1)-this.rows.length;
if(diff>0){count-=diff;}if(count>0){this.rows.splice(row,count);this.cacheRowMetadata.splice(row,count);
}},splitRow:function(modelPos){this.editor.editorView.syntaxModel.invalidateCache(modelPos.row);
this.setRowDirty(modelPos.row);var row=this.getRowArray(modelPos.row);var newRow=[];
if(modelPos.col<row.length){newRow=newRow.concat(row.splice(modelPos.col));}if(modelPos.row==(this.rows.length-1)){this.rows.push(newRow);
}else{var newRows=this.rows.splice(0,modelPos.row+1);newRows.push(newRow);newRows=newRows.concat(this.rows);
this.rows=newRows;var newCacheRowMetadata=this.cacheRowMetadata.splice(0,modelPos.row+1);
newCacheRowMetadata.push(undefined);this.cacheRowMetadata=newCacheRowMetadata.concat(this.cacheRowMetadata);
}},joinRow:function(rowIndex,noHistory){this.editor.editorView.syntaxModel.invalidateCache(rowIndex);
this.setRowDirty(rowIndex);if(rowIndex>=this.rows.length-1){return;}var row=this.getRowArray(rowIndex);
var nextrow=this.rows[rowIndex+1];var rowLength=row.length;this.rows[rowIndex]=row.concat(nextrow);
this.rows.splice(rowIndex+1,1);this.cacheRowMetadata.splice(rowIndex+1,1);if(!noHistory){var pos={row:rowIndex,col:rowLength};
this.addHistoryItem("joinRow",{selection:{startModelPos:pos,endModelPos:pos},chunk:"\n"});
}},getRowCount:function(){return this.rows.length;},getChunk:function(selection){var startModelPos=selection.startModelPos;
var endModelPos=selection.endModelPos;var startModelCol,endModelCol;var chunk="";
startModelCol=startModelPos.col;var row=this.getRowArray(startModelPos.row);endModelCol=(endModelPos.row==startModelPos.row)?endModelPos.col:row.length;
if(endModelCol>row.length){endModelCol=row.length;}chunk+=row.join("").substring(startModelCol,endModelCol);
for(var i=startModelPos.row+1;i<endModelPos.row;i++){chunk+="\n";chunk+=this.getRowArray(i).join("");
}if(startModelPos.row!=endModelPos.row){startModelCol=0;endModelCol=endModelPos.col;
row=this.getRowArray(endModelPos.row);if(endModelCol>row.length){endModelCol=row.length;
}chunk+="\n"+row.join("").substring(startModelCol,endModelCol);}return chunk;},deleteChunk:function(selection,noHistory){var chunk=this.getChunk(selection);
var startModelPos=selection.startModelPos;var endModelPos=selection.endModelPos;this.editor.editorView.syntaxModel.invalidateCache(startModelPos.row);
var startModelCol,endModelCol;startModelCol=startModelPos.col;var row=this.getRowArray(startModelPos.row);
endModelCol=(endModelPos.row==startModelPos.row)?endModelPos.col:row.length;if(endModelCol>row.length){endModelCol=row.length;
}var pos={row:startModelPos.row,col:startModelCol};this.deleteCharacters(pos,endModelCol-startModelCol,true);
if(startModelPos.row!=endModelPos.row){startModelCol=0;endModelCol=endModelPos.col;
row=this.getRowArray(endModelPos.row);if(endModelCol>row.length){endModelCol=row.length;
}pos={row:endModelPos.row,col:startModelCol};this.deleteCharacters(pos,endModelCol-startModelCol,true);
}if((endModelPos.row-startModelPos.row)>1){this.deleteRows(startModelPos.row+1,endModelPos.row-startModelPos.row-1);
}if(endModelPos.row!=startModelPos.row){this.joinRow(startModelPos.row,true);}if(!noHistory){this.addHistoryItem("deleteChunk",{selection:{startModelPos:cursor.copyPos(selection.startModelPos),endModelPos:cursor.copyPos(selection.endModelPos)},chunk:chunk});
}return chunk;},insertChunk:function(modelPos,chunk,noHistory){this.editor.editorView.syntaxModel.invalidateCache(modelPos.row);
var lines=chunk.split("\n");var cModelPos=cursor.copyPos(modelPos);for(var i=0;i<lines.length;
i++){this.insertCharacters(cModelPos,lines[i],true);cModelPos.col=cModelPos.col+lines[i].length;
if(i<lines.length-1){this.splitRow(cModelPos);cModelPos.col=0;cModelPos.row=cModelPos.row+1;
}}if(!noHistory){this.addHistoryItem("insertChunk",{selection:{startModelPos:cursor.copyPos(modelPos),endModelPos:cursor.copyPos(cModelPos)},chunk:chunk});
}return cModelPos;},getStringIndicesInRow:function(row,str){str=str.toLowerCase();
row=this.getRowArray(row).join("").toLowerCase();if(row.indexOf(str)==-1){return false;
}var result=[];var start=0;var index=row.indexOf(str);do{result.push(index);index=row.indexOf(str,index+1);
}while(index!=-1);return result;},getCountOfString:function(str){var count=0;var line;
var match;for(var x=0;x<this.getRowCount();x++){match=this.getStringIndicesInRow(x,str);
if(match){count+=match.length;}}return count;},searchStringChanged:function(str){for(var row=0;
row<this.cacheRowMetadata.length;row++){if(this.cacheRowMetadata[row]){if(str){this.cacheRowMetadata[row].searchIndices=this.getStringIndicesInRow(row,str);
}else{this.cacheRowMetadata[row].searchIndices=false;}}}},findPrev:function(row,col,str){var indices;
var strLen=str.length;for(var x=row;x>-1;x--){indices=this.getStringIndicesInRow(x,str);
if(!indices){continue;}for(var y=indices.length-1;y>-1;y--){if(indices[y]<(col-strLen)||row!=x){return{startPos:{col:indices[y],row:x},endPos:{col:indices[y]+strLen,row:x}};
}}}return false;},findNext:function(row,col,str){var indices;for(var x=row;x<this.getRowCount();
x++){indices=this.getStringIndicesInRow(x,str);if(!indices){continue;}for(var y=0;
y<indices.length;y++){if(indices[y]>col||row!=x){return{startPos:{col:indices[y],row:x},endPos:{col:indices[y]+str.length,row:x}};
}}}return false;},findBefore:function(row,col,comparator){var line=this.getRowArray(row);
if(!util.isFunction(comparator)){comparator=function(letter){if(letter.charAt(0)==" "){return true;
}var letterCode=letter.charCodeAt(0);return(letterCode<48)||(letterCode>122);};}if(col>=line.length){col=Math.max(line.length-1,0);
}while(col>0){var letter=line[col];if(!letter){continue;}if(comparator(letter)){col++;
break;}col--;}return{row:row,col:col};},findAfter:function(row,col,comparator){var line=this.getRowArray(row);
if(!util.isFunction(comparator)){comparator=function(letter){if(letter.charAt(0)==" "){return true;
}var letterCode=letter.charCodeAt(0);return(letterCode<48)||(letterCode>122);};}while(col<line.length){col++;
var letter=line[col];if(!letter){continue;}if(comparator(letter)){break;}}return{row:row,col:col};
},getRowMetadata:function(row){if(!this.isRowDirty(row)&&this.cacheRowMetadata[row]){return this.cacheRowMetadata[row];
}var meta={tabExpansions:[]};var rowArray=this.editor.model.getRowArray(row);var lineText=rowArray.join("");
var tabsize=this.editor.getTabSize();meta.lineTextWithoutTabExpansion=lineText;meta.lineLengthWithoutTabExpansion=rowArray.length;
for(var ti=0;ti<lineText.length;ti++){if(lineText.charCodeAt(ti)==9){var toInsert=tabsize-(ti%tabsize);
var spacer="";for(var si=1;si<toInsert;si++){spacer+=" ";}var left=(ti==0)?"":lineText.substring(0,ti);
var right=(ti<lineText.length-1)?lineText.substring(ti+1):"";lineText=left+" "+spacer+right;
meta.tabExpansions.push({start:left.length,end:left.length+spacer.length+1});ti+=toInsert-1;
}}meta.lineText=lineText;meta.lineLength=meta.lineText.length;if(this.editor.editorView.searchString){meta.searchIndices=this.getStringIndicesInRow(row,this.editor.editorView.searchString);
}else{meta.searchIndices=false;}this.cacheRowMetadata[row]=meta;return meta;},_sendTextEditedNotification:function(){var layoutManager=this.get("layoutManager");
if(!SC.none(layoutManager)){layoutManager.textStorageEdited(this);}}});});tiki.module("bespin:package",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
require("util/globals");SC.mixin(exports,{versionNumber:"tip",versionCodename:"DEVELOPMENT MODE",apiVersion:"dev"});
exports.displayVersion=function(el){el=document.getElementById(el)||document.getElementById("version");
if(!el){return;}el.innerHTML='<a href="https://wiki.mozilla.org/Labs/Bespin/ReleaseNotes" title="Read the release notes">Version <span class="versionnumber">'+this.versionNumber+'</span> "'+this.versionCodename+'"</a>';
};var containerMod=require("util/container");exports._container=containerMod.Container.create();
exports.register=exports._container.register.bind(exports._container);exports.unregister=exports._container.unregister.bind(exports._container);
exports.get=exports._container.get.bind(exports._container);exports.getComponent=exports._container.getComponent.bind(exports._container);
var hub=exports._container.get("hub");exports.publish=hub.publish.bind(hub);exports.subscribe=hub.subscribe.bind(hub);
exports.unsubscribe=hub.unsubscribe.bind(hub);exports.fireAfter=hub.fireAfter.bind(hub);
exports.BaseController=SC.Object.extend({init:function(){arguments.callee.base.apply(this,arguments);
exports._container.inject(this);}});});tiki.module("bespin:plugins",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var builtins=require("builtins");var r=require;exports.Extension=SC.Object.extend({load:function(callback,property){property=property||"pointer";
var parts=this.get(property).split("#");var self=this;tiki.async(this._pluginName).then(function(){var fullName;
if(parts[0]){fullName=self._pluginName+":"+parts[0];}else{fullName=self._pluginName;
}SC.run(function(){var module=r(fullName);if(callback){if(parts[1]){callback(module[parts[1]]);
}else{callback(module);}}});});}});exports.ExtensionPoint=SC.Object.extend({init:function(){this.extensions=[];
this.handlers=[];},addExtension:function(extension){this.extensions.push(extension);
},getByKey:function(key){var indexOn=this.get("indexOn");if(!indexOn){return undefined;
}for(var i=0;i<this.extensions.length;i++){if(this.extensions[i][indexOn]==key){return this.extensions[i];
}}return undefined;},active:function(extension){this.handlers.forEach(function(handler){if(handler.activate){handler.load(function(activate){activate(extension);
},"activate");}});}});exports.Plugin=SC.Object.extend({activate:function(){var provides=this.provides;
self=this;this.provides.forEach(function(extension){var ep=self.get("catalog").getExtensionPoint(extension.ep);
ep.active(extension);});}});exports.Catalog=SC.Object.extend({init:function(){this.points={};
this.plugins={};var ep=this.getExtensionPoint("extensionpoint");ep.set("indexOn","name");
this.load(builtins.metadata);},getExtensionPoint:function(name){if(this.points[name]===undefined){this.points[name]=exports.ExtensionPoint.create({name:name,catalog:this});
}return this.points[name];},getExtensions:function(name){var ep=this.points[name];
if(ep===undefined){return[];}return ep.extensions;},getExtensionByKey:function(name,key){var ep=this.points[name];
if(ep===undefined){return undefined;}return ep.getByKey(key);},registerExtensionPoint:function(extension){var ep=this.getExtensionPoint(extension.name);
ep.handlers.push(extension);if(extension.indexOn){ep.set("indexOn",extension.indexOn);
}},load:function(metadata){for(var name in metadata){var md=metadata[name];if(md.active===undefined){md.active=true;
}md.catalog=this;if(md.provides){var provides=md.provides;for(var i=0;i<provides.length;
i++){var extension=exports.Extension.create(provides[i]);extension._pluginName=name;
provides[i]=extension;var epname=extension.ep;if(epname=="extensionpoint"){this.registerExtensionPoint(extension);
}var ep=this.getExtensionPoint(extension.ep);ep.addExtension(extension);}}else{md.provides=[];
}var plugin=exports.Plugin.create(md);if(plugin.active){plugin.activate();}this.plugins[name]=plugin;
}}});exports.catalog=exports.Catalog.create();exports.startupHandler=function(ep){ep.load(function(func){func();
});};});tiki.module("bespin:settings",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var util=require("util/util");exports.InMemorySettings=SC.Object.extend({values:{},_settings:{},requires:{hub:"hub"},init:function(){setTimeout(function(){this._loadInitialValues();
}.bind(this),10);},resetValue:function(key){var setting=this._settings[key];if(setting){this.values[key]=setting.defaultValue;
}else{delete this.values[key];}},list:function(){var reply=[];for(var prop in this.values){if(this.values.hasOwnProperty(prop)){reply.push({"key":prop,"value":this.values[prop]});
}}return reply;},addSetting:function(setting){if(!setting.name){throw"Settings need 'name' members";
}if(!this._types[setting.type]){throw"setting.type should be one of [number|boolean|string]";
}if(!setting.defaultValue===undefined){throw"Settings need 'defaultValue' members";
}if(!this._types[setting.type].validator(setting.defaultValue)){throw"Default value "+setting.defaultValue+" is not a valid "+setting.type;
}this._settings[setting.name]=setting;this.values["_"+setting.name]=setting.defaultValue;
this.values.__defineSetter__(setting.name,function(value){this.values["_"+setting.name]=value;
this._changeValue(setting.name,value);hub.publish("settings:set:"+setting.name,{value:value});
}.bind(this));this.values.__defineGetter__(setting.name,function(value){this.values["_"+setting.name]=value;
}.bind(this));},_types:{number:{validator:function(value){return typeof value=="number";
},toString:function(value){return""+value;},fromString:function(value){return 0+value;
}},"boolean":{validator:function(value){return typeof value=="boolean";},toString:function(value){return""+value;
},fromString:function(value){return !!value;}},text:{validator:function(value){return typeof value=="string";
},toString:function(value){return value;},fromString:function(value){return value;
}},object:{validator:function(value){return typeof value=="object";},toString:function(value){return JSON.stringify(value);
},fromString:function(value){return JSON.parse(value);}}},_changeValue:function(key,value){},_loadInitialValues:function(){this._loadDefaultValues();
},_loadDefaultValues:function(){this._loadFromObject(this._defaultValues());},_loadFromObject:function(data){for(var key in data){if(data.hasOwnProperty(key)){var value=data[key];
var setting=this._settings[key];if(setting){value=this._types[setting.type].fromString(value);
}this.values[key]=value;}}},_saveToObject:function(){var reply={};for(var key in this.values){if(this.values.hasOwnProperty(key)){var value=this.values[key];
var setting=this._settings[key];if(setting){reply[key]=this._types[setting.type].toString(value);
}else{reply[key]=""+value;}}}return reply;},_defaultValues:function(){var defaultValues={};
for(var name in this._settings){if(this._settings.hasOwnProperty(name)){var setting=this._settings[name];
defaultValues[setting.name]=setting.defaultValue;}}return defaultValues;}});exports.CookieSettings=exports.InMemorySettings.extend({_loadInitialValues:function(){this._loadDefaultValues();
var data=cookie.get("settings");this._loadFromObject(JSON.parse(data));},_changeValue:function(key,value){var data=JSON.stringify(this._saveToObject());
cookie.set("settings",data);}});exports.ServerSettings=exports.InMemorySettings.extend({requires:{files:"files"},_loadInitialValues:function(){this._loadDefaultValues();
var onLoad=function(file){file.content.split(/\n/).forEach(function(setting){if(setting.match(/^\s*#/)){return;
}if(setting.match(/\S+\s+\S+/)){var pieces=setting.split(/\s+/);this.values[pieces[0].trim()]=pieces[1].trim();
}});};this.files.loadContents(this.files.userSettingsProject,"settings",onLoad);},_changeValue:function(key,value){var content="";
for(var key in this.values){if(this.values.hasOwnProperty(key)){content+=key+" "+this.values[key]+"\n";
}}this.files.saveFile(this.files.userSettingsProject,{name:"settings",content:content,timestamp:new Date().getTime()});
}});});tiki.module("bespin:syntax",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var bespin=require("package");bespin.get("settings").addSetting({name:"syntaxengine",type:"text",defaultValue:"simple"});
exports.Model=SC.Object.extend({language:"",lineCache:[],invalidateCache:function(lineNumber){delete this.lineCache[lineNumber];
},invalidateEntireCache:function(){this.lineCache=[];},addToCache:function(lineNumber,line){this.lineCache[lineNumber]=line;
},getFromCache:function(lineNumber){return this.lineCache[lineNumber];},mergeSyntaxResults:function(regions){var base=0;
for(var i=0;i<regions.length;i++){var region=region[i];}},getSyntaxStylesPerLine:function(lineText,lineNumber,language){return{text:lineText,regions:[{plain:[{start:0,stop:lineText.length}]}]};
},getSyntaxStyles:function(rows,firstLineToRender,lastLineToRender,language){var syntaxResults={};
for(var i=firstLineToRender;i<=lastLineToRender;i++){syntaxResults[i]=this.getSyntaxStylesPerLine(rows[i],i,language);
}return syntaxResults;}});var current,model;var engines={};exports.Resolver={setEngine:function(name){var engine=engines[name];
if(name==current){return this;}if(engine){current=name;if(model){delete model;}if(engine.worker){}else{model=new engines[name].Model();
model.workerEnabled=false;}}else{console.log("no such engine: ",name);}return this;
},getModel:function(){return model;}};});tiki.module("bespin:theme",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
exports.coffee={backgroundStyle:"#2A211C",gutterStyle:"#4c4a41",lineNumberColor:"#e5c138",lineNumberFont:"10pt Monaco, Lucida Console, monospace",lineMarkerErrorColor:"#CC4444",lineMarkerWarningColor:"#B8860B",lineMarkerMessageColor:"green",zebraStripeColor:"#2A211C",highlightCurrentLineColor:"#3a312b",editorTextFont:"10pt Monaco, Lucida Console, monospace",editorTextColor:"rgb(230, 230, 230)",editorSelectedTextColor:"rgb(240, 240, 240)",editorSelectedTextBackground:"#526DA5",cursorStyle:"#879aff",cursorType:"ibeam",unfocusedCursorStrokeStyle:"#FF0033",unfocusedCursorFillStyle:"#73171E",partialNibStyle:"rgba(100, 100, 100, 0.3)",partialNibArrowStyle:"rgba(255, 255, 255, 0.3)",partialNibStrokeStyle:"rgba(150, 150, 150, 0.3)",fullNibStyle:"rgb(100, 100, 100)",fullNibArrowStyle:"rgb(255, 255, 255)",fullNibStrokeStyle:"rgb(150, 150, 150)",scrollTrackFillStyle:"rgba(50, 50, 50, 0.8)",scrollTrackStrokeStyle:"rgb(150, 150, 150)",scrollBarFillStyle:"rgba(0, 0, 0, %a)",scrollBarFillGradientTopStart:"rgba(90, 90, 90, %a)",scrollBarFillGradientTopStop:"rgba(40, 40, 40, %a)",scrollBarFillGradientBottomStart:"rgba(22, 22, 22, %a)",scrollBarFillGradientBottomStop:"rgba(44, 44, 44, %a)",tabSpace:"#392A25",searchHighlight:"#B55C00",searchHighlightSelected:"#FF9A00",plain:"#bdae9d",keyword:"#42a8ed",string:"#039a0a",comment:"#666666","c-comment":"#666666",punctuation:"#888888",attribute:"#BF9464",test:"rgb(255,0,0)",cdata:"#bdae9d","attribute-value":"#039a0a",tag:"#46a8ed",color:"#c4646b","tag-name":"#46a8ed",value:"#039a0a",important:"#990000",sizes:"#990000",cssclass:"#BF9464",cssid:"#46a8ed",atom:"#aa4444",variable:"#00cccc",variabledef:"#4422cc",localvariable:"#cc2277",property:"#66bb33",operator:"#88bbff",error:"#FF0000",processing:"#999999",entity:"#AA2222",text:"#00BB00","compile-time-constant":"#776088","predefined-constant":"#33CC33","reserved-language-construct":"#00FF00","predefined-function":"#22FF22","predefined-class":"#22FF22",literal:"#DD4411",identifier:"#22FF22",func:"#2200FF",type:"#8822FF",decorator:"#2222FF"};
exports.coffeezebra={};SC.mixin(exports.coffeezebra,exports.coffee);exports.coffeezebra.zebraStripeColor="#FFFFFF";
exports["default"]=exports.coffee;});tiki.module("bespin:util/bootstrap_worker",function(require,exports,module){var NATIVE_JSON=this.JSON?true:false;
var __GLOBAL__=this;if(!__GLOBAL__.console){__GLOBAL__.console={log:function(msg){postMessage("log="+msg);
}};}var loadDone=function(){if(theObject.initialize){theObject.initialize();}};var internalMessageIdentifier="__IMPORT_SCRIPT__";
var SCRIPT_COUNT=0;var LOADED_SCRIPTS=0;var EMULATE_LOAD=false;if(typeof google!="undefined"&&google.gears&&google.gears.workerPool){var wp=google.gears.workerPool;
wp.onmessage=function(a,b,message){var sender=message.sender;postMessage=function(data){wp.sendMessage(data,sender);
};onmessage({data:message.body});};__GLOBAL__.importScripts=function(){var global=this;
var src="";var i=0;var load=function(url,callback){var request=google.gears.factory.create("beta.httprequest");
request.open("GET",url);request.onreadystatechange=function(){if(request.readyState==4){if(request.status>=200&&request.status<400){var res=request.responseText;
src+=res+"\n";callback();}else{throw new Error("Error fetching script "+url+". Response code: "+request.status+" Response text: "+request.responseText);
}}};request.send();};var urls=Array.prototype.splice.call(arguments,0);var loader=function(){var url=urls.shift();
if(url){load(url,loader);}else{try{global.eval(src);}catch(e){console.log("Error evaluating source ",e);
}loadDone();}};loader();};}if(typeof importScripts=="undefined"){EMULATE_LOAD=true;
var loadCounter=0;__GLOBAL__.importScripts=function(){for(var i=0;i<arguments.length;
++i){var script=arguments[i];postMessage(internalMessageIdentifier+"["+(SCRIPT_COUNT++)+", '"+script+"']");
++loadCounter;}};var loaded=[];var nextLoad=0;__GLOBAL__.__evalScriptFromImport=function(index,source){loaded[index]=source;
for(var i=nextLoad;i<loaded.length;++i){if(loaded[i]){nextLoad=i+1;try{__GLOBAL__.eval(loaded[i]);
}catch(e){console.log("Error evaluating script from import: ",e);}if(loadCounter==i){loadDone();
}}else{break;}}};}if(!NATIVE_JSON){origPostMessage=postMessage;postMessage=function(data){if(typeof data!="string"){data=JSON.stringify(data);
}origPostMessage(data);};}onmessage=function(event){var body=event.data;var dataIsString=false;
if(typeof body=="string"){if(body.indexOf("// YOUcannotGuessMe")==0){if(EMULATE_LOAD){__GLOBAL__.__evalScriptFromImport(SCRIPT_COUNT++,body);
}else{try{__GLOBAL__.eval(body);}catch(e){console.log("Unable to evaluate onmessage() "+e);
}loadDone();}return;}else{if(body.indexOf("__IMPORT_SCRIPT__")==0){var source=body.substr("__IMPORT_SCRIPT__".length);
var match=source.match(/^\/\/(\d+)/);if(match){var index=parseInt(match[1],10);__evalScriptFromImport(index,source);
}return;}else{dataIsString=true;try{body=JSON.parse(body);}catch(e){throw e+""+body;
}}}}if(body.event){bespin.receive(body);return;}var method=body.method;var o=theObject;
var ret=o[body.method].apply(o,body.paras);var data={method:body.method,returnValue:ret,callIndex:body.callIndex};
postMessage(data);};var eventIndex=0;var eventCallbacks=[];bespin={subscribe:function(name,callback){postMessage({type:"subscribe",name:name,index:eventIndex});
eventCallbacks[eventIndex]=function(){callback.apply(this,arguments);};eventIndex++;
},publish:function(name,event){postMessage({type:"publish",name:name,event:event});
},receive:function(info){eventCallbacks[info.index](info.event);}};if(!this.JSON){JSON=function(){function f(n){return n<10?"0"+n:n;
}Date.prototype.toJSON=function(){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z";
};var m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};
function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case"string":return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];
if(c){return c;}c=a.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16);
})+'"':'"'+value+'"';case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);
case"object":if(!value){return"null";}if(typeof value.toJSON==="function"){return stringify(value.toJSON());
}a=[];if(typeof value.length==="number"&&!(value.propertyIsEnumerable("length"))){l=value.length;
for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||"null");}return"["+a.join(",")+"]";
}if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==="string"){v=stringify(value[k],whitelist);
if(v){a.push(stringify(k)+":"+v);}}}}else{for(k in value){if(typeof k==="string"){v=stringify(value[k],whitelist);
if(v){a.push(stringify(k)+":"+v);}}}}return"{"+a.join(",")+"}";}}return{stringify:stringify,parse:function(text,filter){var j;
function walk(k,v){var i,n;if(v&&typeof v==="object"){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);
if(n!==undefined){v[i]=n;}else{delete v[i];}}}}return filter(k,v);}if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");
return typeof filter==="function"?walk("",j):j;}throw new SyntaxError("parseJSON");
}};}();}});tiki.module("bespin:util/canvas",function(require,exports,module){exports.fix=function(ctx){if(!ctx.fillText&&ctx.mozDrawText){ctx.fillText=function(textToDraw,x,y,maxWidth){ctx.translate(x,y);
ctx.mozTextStyle=ctx.font;ctx.mozDrawText(textToDraw);ctx.translate(-x,-y);};}if(!ctx.measureText&&ctx.mozMeasureText){ctx.measureText=function(text){if(ctx.font){ctx.mozTextStyle=ctx.font;
}var width=ctx.mozMeasureText(text);return{width:width};};}if(ctx.measureText&&!ctx.html5MeasureText){ctx.html5MeasureText=ctx.measureText;
ctx.measureText=function(text){var textMetrics=ctx.html5MeasureText(text);textMetrics.ascent=ctx.html5MeasureText("m").width;
return textMetrics;};}if(!ctx.fillText){ctx.fillText=function(){};}if(!ctx.measureText){ctx.measureText=function(){return 10;
};}return ctx;};});tiki.module("bespin:util/clipboard",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
var util=require("util/util");var keys=require("util/keys");var implementation=null;
exports.setup=function(editorWrapper){if(implementation){implementation.uninstall();
}if(false&&util.isWebKit){implementation=DOMEvents.create({editorWrapper:editorWrapper});
implementation.install();}else{implementation=HiddenWorld.create({editorWrapper:editorWrapper});
implementation.install();}};var ClipboardProxy=SC.Object.extend({_hasFocus:false,init:function(){this.textarea=document.createElement("textarea");
this.textarea.className="bespin-clipboardproxy";this.textarea.tabIndex=-1;this.textarea.style.position="absolute";
this.textarea.style.zIndex="999";this.textarea.style.top="-10000px";this.textarea.style.width=0;
this.textarea.style.height=0;document.body.appendChild(this.textarea);},takeFocus:function(text){text=text||"Hello";
this.textarea.value=text;this.textarea.focus();this.textarea.select();this._hasFocus=true;
},hasFocus:function(text){return this._hasFocus;},focusLost:function(){this._hasFocus=false;
},getValue:function(){return this.textarea.value;},dispose:function(){document.body.removeChild(this.textarea);
}});var DOMEvents=SC.Object.extend({editorWrapper:null,install:function(){var proxy=ClipboardProxy.create();
var element=document;var primeMenu=function(ev){if(!this.editorWrapper.hasFocus()){return;
}ev.preventDefault();proxy.takeFocus();}.bind(this);element.addEventListener("beforecopy",primeMenu,false);
element.addEventListener("beforecut",primeMenu,false);var onCopy=function(ev){if(!proxy.hasFocus()){return;
}var text=this.editorWrapper.getSelection();if(text&&text!=""){ev.clipboardData.setData("text/plain",text);
}console.log("onCopy",ev,text);this.editorWrapper.focus();proxy.focusLost();util.stopEvent(ev);
}.bind(this);element.addEventListener("copy",onCopy);var onCut=function(ev){if(!proxy.hasFocus()){return;
}var text=this.editorWrapper.removeSelection();if(text){ev.clipboardData.setData("text/plain",text);
}console.log("onCut",ev,text);this.editorWrapper.focus();proxy.focusLost();util.stopEvent(ev);
}.bind(this);element.addEventListener("cut",onCut);var onPaste=function(ev){if(!this.editorWrapper.hasFocus()){return;
}var text=ev.clipboardData.getData("text/plain");this.editorWrapper.replaceSelection(text);
console.log("onPaste",ev,text);this.editorWrapper.focus();proxy.focusLost();util.stopEvent(ev);
}.bind(this);element.addEventListener("paste",onPaste);this.uninstall=function(){element.removeEventListener("beforecopy",primeMenu,false);
element.removeEventListener("beforecut",primeMenu,false);element.removeEventListener("beforepaste",primeMenu,false);
element.removeEventListener("copy",onCopy,false);element.removeEventListener("cut",onCut,false);
element.removeEventListener("paste",onPaste,false);proxy.dispose();};},uninstall:function(){}});
var HiddenWorld=SC.Object.extend({editorWrapper:null,install:function(){this.proxy=ClipboardProxy.create();
var onKeyDown=function(ev){var text;if((util.isMac&&ev.metaKey)||ev.ctrlKey){if(ev.keyCode==keys.Key.C){text=this.editorWrapper.getSelection();
if(text&&text!=""){this.copyToClipboard(text);}}else{if(ev.keyCode==keys.Key.X){text=this.editorWrapper.removeSelection();
this.copyToClipboard(text);}else{if(ev.keyCode==keys.Key.V){this.pasteFromClipboard();
}}}}}.bind(this);var element=this.editorWrapper.getFocusElement();element.addEventListener("keydown",onKeyDown,false);
this.uninstall=function(){element.removeEventListener("keydown",onKeyDown,false);
this.proxy.dispose();};},copyToClipboard:function(text){this.proxy.takeFocus(text);
setTimeout(function(){this.editorWrapper.focus();}.bind(this),10);},pasteFromClipboard:function(){this.proxy.takeFocus();
setTimeout(function(){var text=this.proxy.getValue();this.editorWrapper.replaceSelection(text);
this.editorWrapper.focus();}.bind(this),0);},uninstall:function(){}});exports.manual=function(){var clipdata;
var privMan=window.netscape?netscape.security.PrivilegeManager:null;return{copy:function(copytext){try{if(privMan.enablePrivilege){privMan.enablePrivilege("UniversalXPConnect");
}else{clipdata=copytext;return;}}catch(ex){clipdata=copytext;return;}var str=Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data=copytext;var trans=Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if(!trans){return false;}trans.addDataFlavor("text/unicode");trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid=Components.interfaces.nsIClipboard;var clip=Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
if(!clip){return false;}clip.setData(trans,null,clipid.kGlobalClipboard);},data:function(){try{if(privilegeManager.enablePrivilege){privilegeManager.enablePrivilege("UniversalXPConnect");
}else{return clipdata;}}catch(ex){return clipdata;}var clip=Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
if(!clip){return false;}var trans=Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if(!trans){return false;}trans.addDataFlavor("text/unicode");clip.getData(trans,clip.kGlobalClipboard);
var str={};var strLength={};var pastetext="";trans.getTransferData("text/unicode",str,strLength);
if(str){str=str.value.QueryInterface(Components.interfaces.nsISupportsString);}if(str){pastetext=str.data.substring(0,strLength.value/2);
}return pastetext;}};}();});tiki.module("bespin:util/container",function(require,exports,module){var util=require("util/util");
var builtins=require("builtins");var pluginCatalog=require("plugins").catalog;var SC=require("sproutcore/runtime").SC;
var system=require("system");exports.Container=SC.Object.extend({init:function(){this.register("ioc",this);
this._beingCreated={};},register:function(id,object){SC.global(id,object);this.inject(object);
console.log("container.register",id,object);return object;},unregister:function(id){SC.global.remove(id);
},inject:function(object){var property,name;if(object&&object.requires){var requirements={};
for(property in object.requires){if(object.requires.hasOwnProperty(property)){name=object.requires[property];
requirements[property]=name;}}var checkCompleted=function(){var remaining=0;for(var i in requirements){if(object.requires.hasOwnProperty(property)){remaining++;
}}if(remaining==0){if(object.afterContainerSetup){object.afterContainerSetup();}}};
checkCompleted();for(property in requirements){if(object.requires.hasOwnProperty(property)){name=requirements[property];
var onFound=function(component){object[property]=component;delete requirements[property];
checkCompleted();}.bind(this);var source=object.requires[property];var component=system.global[source];
if(component!==undefined){onFound(component);}else{this._createFromFactory(name,function(component){this.register(name,component);
onFound(component);}.bind(this));}}}}},get:function(id){var object=system.global[id];
if(object===undefined){var onCreate=function(component){this.register(id,component);
object=component;}.bind(this);this._createFromFactory(id,onCreate);}return object;
},getComponent:function(id,callback,context){context=context||window;var component=system.global[id];
if(component!==undefined){callback.call(context,component);}else{var onCreate=function(component){this.register(id,component);
callback.call(context,component);}.bind(this);this._createFromFactory(id,onCreate);
}},_createFromFactory:function(id,onCreate){if(this._beingCreated[id]!==undefined){console.trace();
throw"Already creating "+id;}this._beingCreated[id]=onCreate;try{var extension=pluginCatalog.getExtensionByKey("factory",id);
if(extension===undefined){console.trace();throw"No component factory '"+id+"'";}else{var action=extension.action;
extension.load(function(exported){if(action=="call"){exported(onCreate);}else{if(action=="create"){onCreate(exported.create());
}else{if(action=="new"){onCreate(new exported());}else{if(action=="value"){onCreate(exported);
}else{throw"Create action must be call|create|new|value. "+"Found"+action;}}}}});
}}finally{delete this._beingCreated[id];}}});exports.dummyFactory=function(onCreate){onCreate(null);
};});tiki.module("bespin:util/cookie",function(require,exports,module){var escapeString=function(str,except){return str.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,function(ch){if(except&&except.indexOf(ch)!=-1){return ch;
}return"\\"+ch;});};exports.get=function(name){var matcher=new RegExp("(?:^|; )"+escapeString(name)+"=([^;]*)");
var matches=document.cookie.match(matcher);return matches?decodeURIComponent(matches[1]):undefined;
};exports.set=function(name,value,props){props=props||{};if(typeof props.expires=="number"){var date=new Date();
date.setTime(date.getTime()+props.expires*24*60*60*1000);props.expires=date;}if(props.expires&&props.expires.toUTCString){props.expires=props.expires.toUTCString();
}value=encodeURIComponent(value);var updatedCookie=name+"="+value,propName;for(propName in props){updatedCookie+="; "+propName;
var propValue=props[propName];if(propValue!==true){updatedCookie+="="+propValue;}}document.cookie=updatedCookie;
};exports.remove=function(name){exports.set(name,"",{expires:-1});};exports.isSupported=function(){if(!("cookieEnabled" in navigator)){exports.set("__djCookieTest__","CookiesAllowed");
navigator.cookieEnabled=exports.get("__djCookieTest__")=="CookiesAllowed";if(navigator.cookieEnabled){exports.remove("__djCookieTest__");
}}return navigator.cookieEnabled;};});tiki.module("bespin:util/globals",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
if(!Array.isArray){Array.isArray=function(data){return(data&&Object.prototype.toString.call(data)=="[object Array]");
};}if(!Function.prototype.bind){Function.prototype.bind=function(){var args=Array.prototype.slice.call(arguments);
var self=this;var bound=function(){return self.call.apply(self,args.concat(Array.prototype.slice.call(arguments)));
};bound.name=this.name;bound.displayName=this.displayName;bound.length=this.length;
bound.unbound=self;return bound;};}SC.Object.prototype.sc_super=function super_name(){super_name.caller.base.apply(this,super_name.caller.arguments);
};SC.objectForPropertyPathOriginal=SC.objectForPropertyPath;SC.objectForPropertyPath=function(path,root,stopAt){stopAt=(stopAt==undefined)?path.length:stopAt;
var hashed=path.split("#");if(hashed.length==1){return SC.objectForPropertyPathOriginal(path,root,stopAt);
}var module=require(hashed[0]);if(module===undefined){return undefined;}stopAt=stopAt-hashed[0].length;
return SC.objectForPropertyPathOriginal(hashed[1],module,stopAt);};});tiki.module("bespin:util/hub",function(require,exports,module){exports.Hub=SC.Object.extend({_topics:{},_eventLog:{},publish:function(topic,args){if(window.globalStorage&&window.globalStorage[location.hostname]&&window.globalStorage[location.hostname].debug){console.log("Publish",topic,args);
}this._eventLog[topic]=true;var topic="bespin:"+topic;args=Array.isArray(args)?args:[args||{}];
var dispatcher=this._topics[topic];if(dispatcher){dispatcher.apply(null,args);}},subscribe:function(topic,method,context){var topic="bespin:"+topic;
var boundMethod=method.bind(context);var dispatcher=this._topics[topic];if(!dispatcher||!dispatcher._listeners){var origDispatcher=dispatcher;
var self=this;var dispatcher=function(){var listeners=arguments.callee._listeners;
var target=arguments.callee.target;var r=target&&target.apply(self,arguments);var listeners=[].concat(listeners);
for(var i in listeners){if(!(i in Array.prototype)){listeners[i].apply(self,arguments);
}}return r;};dispatcher.target=origDispatcher;dispatcher._listeners=[];this._topics[topic]=dispatcher;
}var listened=dispatcher._listeners.push(boundMethod);return[topic,listened];},unsubscribe:function(handle){if(handle){var topic=handle[0];
var listener=handle[1];var dispatcher=this._topics[topic];if(dispatcher&&dispatcher._listeners&&listener--){delete dispatcher._listeners[listener];
}}},fireAfter:function(topicList,callback){if(!Array.isArray(topicList)){throw new Error("fireAfter() takes an array of topics. '"+topicList+"' is not an array.");
}var count=topicList.length;var done=function(){if(count==0){callback();}};for(var i=0;
i<topicList.length;++i){var topic=topicList[i];if(this._eventLog[topic]){--count;
}else{this.subscribe(topic,function(){--count;done();});}done();}}});});tiki.module("bespin:util/keys",function(require,exports,module){var util=require("util/util");
exports.Key={BACKSPACE:8,TAB:9,CLEAR:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,META:util.isSafari?91:224,PAUSE:19,CAPS_LOCK:20,ESCAPE:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT_ARROW:37,UP_ARROW:38,RIGHT_ARROW:39,DOWN_ARROW:40,INSERT:45,DELETE:46,HELP:47,LEFT_WINDOW:91,RIGHT_WINDOW:92,SELECT:93,NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_MULTIPLY:106,NUMPAD_PLUS:107,NUMPAD_ENTER:108,NUMPAD_MINUS:109,NUMPAD_PERIOD:110,NUMPAD_DIVIDE:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,NUM_LOCK:144,SCROLL_LOCK:145,copyKey:util.isMac&&!util.isAIR?(util.isSafari?91:224):17,FORWARD_SLASH:191,TILDE:192,SQUARE_BRACKET_OPEN:219,BACK_SLASH:220,SQUARE_BRACKET_CLOSE:221,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90};
exports.KeyCodeToName={};for(var key in exports.Key){var keyCode=exports.Key[key];
if(typeof keyCode=="number"){exports.KeyCodeToName[keyCode]=key;}}exports.toKeyCode=function(keyAsString){return exports.Key[keyAsString.toUpperCase()];
};exports.fillArguments=function(string,args){var keys=string.split(" ");args=args||{};
args.key=keys.pop();if(keys.length==0){args.modifiers="none";}else{args.modifiers=keys.join(",");
}return args;};var codes=["k","l","n","o","t","w","+","-","~","0","1","2","3","4","5","6","7","8","9"];
exports.PassThroughCharCodes=codes.map(function(item){return item.charCodeAt(0);});
exports.PassThroughKeyCodes=(function(){return[exports.Key.C,exports.Key.X,exports.Key.V,exports.Key.K,exports.Key.L,exports.Key.N,exports.Key.O,exports.Key.T,exports.Key.W,exports.Key.NUMPAD_PLUS,exports.Key.NUMPAD_MINUS,exports.Key.TILDE,exports.Key.ZERO,exports.Key.ONE,exports.Key.TWO,exports.Key.THREE,exports.Key.FOUR,exports.Key.FIVE,exports.Key.SIX,exports.Key.SEVEN,exports.Key.EIGHT,exports.Key.NINE];
})();exports.passThroughToBrowser=function(e){if(!e.ctrlKey){return true;}else{if(e.metaKey||e.altKey||e.ctrlKey){if(e.type=="keypress"){var match=exports.PassThroughCharCodes.some(function(item){return(item==e.charCode);
});if(match){return true;}}else{var match=exports.PassThroughKeyCodes.some(function(item){return(item==e.keyCode);
});if(match){return true;}}}}return false;};});tiki.module("bespin:util/mousewheelevent",function(require,exports,module){var SC=require("sproutcore/runtime:package").SC;
SC.mixin(exports,{wheel:function(event){var delta=0;if(!event){event=window.event;
}if(event.wheelDelta){delta=-event.wheelDelta/40;if(window.opera&&window.opera.version()<9.2){delta=-delta;
}}else{if(event.detail){delta=event.detail;}}return delta;},axis:function(event){var returnType="vertical";
if(event.axis){if(event.axis==event.HORIZONTAL_AXIS){returnType="horizontal";}}else{if(event.wheelDeltaY||event.wheelDeltaX){if(event.wheelDeltaX==event.wheelDelta){returnType="horizontal";
}}else{if(event.shiftKey){returnType="horizontal";}}}return returnType;}});});tiki.module("bespin:util/path",function(require,exports,module){exports.combine=function(){var args=Array.prototype.slice.call(arguments);
var path=args.join("/");path=path.replace(/\/\/+/g,"/");path=path.replace(/^\s+|\s+$/g,"");
return path;};exports.directory=function(path){var dirs=path.split("/");if(dirs.length==1){return"";
}else{if((dirs.length==2)&&dirs[dirs.length-1]==""){return path;}else{return dirs.slice(0,dirs.length-1).join("/");
}}};exports.makeDirectory=function(path){if(!/\/$/.test(path)){path+="/";}return path;
};exports.combineAsDirectory=function(){return this.makeDirectory(this.combine.apply(this,arguments));
};exports.escape=function(){return escape(this.combine.apply(this,arguments));};exports.trimLeadingSlash=function(path){if(path.indexOf("/")==0){path=path.substring(1,path.length);
}return path;},exports.fileType=function(path){if(path.indexOf(".")>=0){var split=path.split(".");
if(split.length>1){return split[split.length-1];}}};});tiki.module("bespin:util/tokenobject",function(require,exports,module){var bespin=require("package");
exports.TokenObject=SC.Object.extend({input:null,options:{},init:function(){this._splitterRegex=new RegExp(this.options.splitBy||"\\s+");
this.pieces=this.tokenize(this.input.split(this._splitterRegex));if(this.options.params){this._nametoindex={};
var namedparams=this.options.params.split(" ");for(var x=0;x<namedparams.length;x++){this._nametoindex[namedparams[x]]=x;
if(!this.options["noshortcutvalues"]){this[namedparams[x]]=this.pieces[x];}}}arguments.callee.base.apply(this,arguments);
},tokenize:function(incoming){var tokens=[];var nextToken;while(nextToken=incoming.shift()){if(nextToken[0]=='"'||nextToken[0]=="'"){var eaten=[nextToken.substring(1,nextToken.length)];
var eataway;while(eataway=incoming.shift()){if(eataway[eataway.length-1]=='"'||eataway[eataway.length-1]=="'"){eaten.push(eataway.substring(0,eataway.length-1));
break;}else{eaten.push(eataway);}}tokens.push(eaten.join(" "));}else{tokens.push(nextToken);
}}return tokens;},param:function(index){return(typeof index=="number")?this.pieces[index]:this.pieces[this._nametoindex[index]];
},length:function(){return this.pieces.length;}});});tiki.module("bespin:util/util",function(require,exports,module){exports.queryToObject=function(str,seperator){var ret={};
var qp=str.split(seperator||"&");var dec=decodeURIComponent;qp.forEach(function(item){if(item.length){var parts=item.split("=");
var name=dec(parts.shift());var val=dec(parts.join("="));if(exports.isString(ret[name])){ret[name]=[ret[name]];
}if(Array.isArray(ret[name])){ret[name].push(val);}else{ret[name]=val;}}});return ret;
};exports.objectToQuery=function(map){var enc=encodeURIComponent;var pairs=[];var backstop={};
for(var name in map){var value=map[name];if(value!=backstop[name]){var assign=enc(name)+"=";
if(_d.isArray(value)){for(var i=0;i<value.length;i++){pairs.push(assign+enc(value[i]));
}}else{pairs.push(assign+enc(value));}}}return pairs.join("&");};var nextRateLimitId=0;
var rateLimitTimeouts={};exports.rateLimit=function(maxRate,scope,func){if(maxRate){var rateLimitId=nextRateLimitId++;
return function(){if(rateLimitTimeouts[rateLimitId]){clearTimeout(rateLimitTimeouts[rateLimitId]);
}rateLimitTimeouts[rateLimitId]=setTimeout(function(){func.apply(scope,arguments);
delete rateLimitTimeouts[rateLimitId];},maxRate);};}};exports.isString=function(it){return(typeof it=="string"||it instanceof String);
};exports.isObject=function(it){return it!==undefined&&(it===null||typeof it=="object"||d.isArray(it)||d.isFunction(it));
};exports.isFunction=(function(){var _isFunction=function(it){var t=typeof it;return it&&(t=="function"||it instanceof Function)&&!it.nodeType;
};return exports.isSafari?function(it){if(typeof it=="function"&&it=="[object NodeList]"){return false;
}return _isFunction(it);}:_isFunction;})();exports.endsWith=function(str,end){return str.match(new RegExp(end+"$"));
};exports.include=function(array,item){return array.indexOf(item)>-1;};exports.indexOfProperty=function(array,propertyName,item){for(var i=0;
i<array.length;i++){if(array[i][propertyName]==item){return i;}}return null;};exports.last=function(array){if(Array.isArray(array)){return array[array.length-1];
}};exports.shrinkArray=function(array){var newArray=[];var stillAtBeginning=true;
array.reverse().forEach(function(item){if(stillAtBeginning&&item===undefined){return;
}stillAtBeginning=false;newArray.push(item);});return newArray.reverse();};exports.makeArray=function(number,character){if(number<1){return[];
}if(!character){character=" ";}var newArray=[];for(var i=0;i<number;i++){newArray.push(character);
}return newArray;};exports.repeatString=function(string,repeat){var newstring="";
for(var i=0;i<repeat;i++){newstring+=string;}return newstring;};exports.leadingSpaces=function(row){var numspaces=0;
for(var i=0;i<row.length;i++){if(row[i]==" "||row[i]==""||row[i]===undefined){numspaces++;
}else{return numspaces;}}return numspaces;};exports.leadingTabs=function(row){var numtabs=0;
for(var i=0;i<row.length;i++){if(row[i]=="\t"||row[i]==""||row[i]===undefined){numtabs++;
}else{return numtabs;}}return numtabs;};exports.leadingWhitespace=function(row){var leading=[];
for(var i=0;i<row.length;i++){if(row[i]==" "||row[i]=="\t"||row[i]==""||row[i]===undefined){leading.push(row[i]);
}else{return leading;}}return leading;};exports.englishFromCamel=function(camel){camel.replace(/([A-Z])/g,function(str){return" "+str.toLowerCase();
}).trim();};exports.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"};var ua=navigator.userAgent;
var av=navigator.appVersion;exports.isLinux=av.indexOf("Linux")>=0;exports.isWindows=av.indexOf("Win")>=0;
exports.isWebKit=parseFloat(ua.split("WebKit/")[1])||undefined;exports.isChrome=parseFloat(ua.split("Chrome/")[1])||undefined;
exports.isMac=av.indexOf("Macintosh")>=0;if(ua.indexOf("AdobeAIR")>=0){exports.isAIR=1;
}var index=Math.max(av.indexOf("WebKit"),av.indexOf("Safari"),0);if(index&&!exports.isChrome){exports.isSafari=parseFloat(av.split("Version/")[1]);
if(!exports.isSafari||parseFloat(av.substr(index+7))<=419.3){exports.isSafari=2;}}if(ua.indexOf("Gecko")>=0&&!exports.isWebKit){exports.isMozilla=parseFloat(av);
}exports.getOS=function(){if(exports.isMac){return exports.OS["MAC"];}else{if(exports.isLinux){return exports.OS["LINUX"];
}else{return exports.OS["WINDOWS"];}}};exports.contains=document.compareDocumentPosition?function(a,b){return a.compareDocumentPosition(b)&16;
}:function(a,b){return a!==b&&(a.contains?a.contains(b):true);};exports.stopEvent=function(ev){ev.preventDefault();
ev.stopPropagation();};exports.randomPassword=function(length){length=length||16;
var chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";var pass="";
for(var x=0;x<length;x++){var charIndex=Math.floor(Math.random()*chars.length);pass+=chars.charAt(charIndex);
}return pass;};exports.isEmpty=function(object){for(var x in object){if(object.hasOwnProperty(x)){return false;
}}return true;};exports.isMyProject=function(project){return project.indexOf("+")==-1;
};exports.formatDate=function(date){if(!date){return"Unknown";}return date.getDate()+" "+exports.formatDate.shortMonths[date.getMonth()]+" "+date.getFullYear();
};exports.formatDate.shortMonths=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
});tiki.script("bespin:en/163e0975202cdb540ae3a5016e0151448aed01e0/javascript.js");
tiki.require("bespin:boot");