//@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


String.English={};Object.extend(String.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."});if(!window.SC)SC={};SproutCore=SC;var YES=true;var NO=false;function require(file){return null;}
if(!window.console){window.console={_output:[],log:function(str){this._output.push(str);},tail:function(lines){if(!lines)lines=1;var loc=this._output.length-lines;if(loc<0)loc=0;var ret=[];while(loc<this._output.length){ret.push(this._output[loc]);loc++;}
return ret.join("\n");}};}
window.logCount=0;Object.extend(SC,{_downloadFrames:0,download:function(path){var tempDLIFrame=document.createElement('iframe');var frameId='DownloadFrame_'+this._downloadFrames;tempDLIFrame.setAttribute('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.isSafari())){tempDLIFrame.setAttribute('src',path);}
document.getElementsByTagName('body')[0].appendChild(tempDLIFrame);if(SC.isSafari()){tempDLIFrame.setAttribute('src',path);}
this._downloadFrames=this._downloadFrames+1;if(!(SC.isSafari())){var r=function(){document.body.removeChild(document.getElementById(frameId));};var t=r.invokeLater(null,2000);}},callOnLoad:function(func){if(SC._onloadQueueFlushed)func.call(document);var queue=SC._onloadQueue||[];queue.push(func);SC._onloadQueue=queue;},didLoad:function(){SC.app=SC.Application.create();SC.app.run();var b=$tag('body');Element.addClassName(b,String.currentLanguage().toLowerCase());var queue;SC.runLoop.beginRunLoop();if(window.callOnLoad){if(window.callOnLoad instanceof Array){queue=window.callOnLoad;}else if(window.callOnLoad instanceof Function){queue=[window.callOnLoad];}}else queue=[];queue=queue.concat(SC._onloadQueue);var func=null;while(func=queue.shift())func.call(document);SC._onloadQueueFlushed=true;if(window.main&&(main instanceof Function))main();if(typeof Routes!='undefined'){Routes.doRoutes();}else if(typeof SC.Routes!='undefined'){SC.Routes.ping();}
SC.runLoop.endRunLoop();},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;},typeOf:function(item){if(item===undefined)return T_UNDEFINED;if(item===null)return T_NULL;var ret=typeof(item);if(ret=="object"){if(item instanceof Array){ret=T_ARRAY;}else if(item instanceof Function){ret=(item.isClass)?T_CLASS:T_FUNCTION;}else if(item instanceof SC.Error){ret=T_ERROR;}else if(item.isObject===true){ret=T_OBJECT;}else ret=T_HASH;}else if(ret===T_FUNCTION)ret=(item.isClass)?T_CLASS:T_FUNCTION;return ret;},isEqual:function(a,b){if(a===null){return b===null;}else if(a===undefined){return b===undefined;}else if(typeof(a)==typeof(b)){return a==b;}},isArray:function(obj)
{return($type(obj)===T_ARRAY)||(obj&&obj.objectAt);},_nextGUID:0,guidFor:function(obj){if(obj==null)return 0;return obj._guid?obj._guid:(obj._guid=SC._nextGUID++);},inspect:function(obj){return $H(obj).inspect();},Platform:{IE:function(){if(Prototype.Browser.IE){return(navigator.appVersion.match(/\bMSIE.*7\.\b/))?7:6;}else return 0;}(),Safari:function(){if(Prototype.Browser.WebKit){var vers=parseInt(navigator.appVersion.replace(/^.*?AppleWebKit\/(\d+).*?$/,'$1'),0);return(vers>420)?3:2;}return 0;}(),Firefox:function(){var ret=0;if(Prototype.Browser.Gecko){if(navigator.userAgent.indexOf("Firefox")!=-1)
{ret=parseFloat((navigator.userAgent.match(/Firefox\/(.)/)[1])||0);}
if(ret<1)ret=2;}
return ret;}(),isWindows:function(){return!!(navigator.appVersion.match(/(Windows)/));}(),isMac:function(){if(Prototype.Browser.Gecko){return!!(navigator.appVersion.match(/(Macintosh)/));}else{return!!(navigator.appVersion.match(/(Mac OS X)/));}}()},isIE:function(){return SC.Platform.IE>0;},isSafari:function(){return SC.Platform.Safari>0;},isSafari3:function(){return SC.Platform.Safari>=3;},isIE7:function(){return SC.Platform.IE>=7;},isIE6:function(){return(SC.Platform.IE>=6)&&(SC.Platform.IE<7);},isWindows:function(){return SC.Platform.isWindows;},isMacOSX:function(){return SC.Platform.isMac;},isFireFox:function(){return SC.Platform.Firefox>0;},isFireFox2:function(){return SC.Platform.Firefox>=2;}});SC.getGUID=SC.guidFor;SC.Platform.Browser=function(){if(SC.Platform.IE>0){return'IE';}else if(SC.Platform.Safari>0){return'Safari';}else if(SC.Platform.Firefox>0){return'Firefox';}}();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';$type=SC.typeOf;$I=SC.inspect;Object.extend(Object,{serialize:function(obj){var ret=[];for(var key in obj){var value=obj[key];if(typeof value=='number'){value=''+value;}
if(!(typeof value=='string')){value=value.join(',');}
ret.push(encodeURIComponent(key)+"="+encodeURIComponent(value));}
return ret.join('&');}});Element.setClassName=function(element,className,flag){if(SC.isIE())
{if(flag){Element.addClassName(element,className);}else{Element.removeClassName(element,className);}}
else
{if(flag){element.addClassName(className);}else{element.removeClassName(className);}}};Object.extend(Event,{getCharCode:function(e){return(e.keyCode)?e.keyCode:((e.which)?e.which:0);},getCharString:function(e){return String.fromCharCode(Event.getCharCode(e));},pointerLocation:function(event){var ret={x:event.pageX||(event.clientX+
(document.documentElement.scrollLeft||document.body.scrollLeft)),y:event.pageY||(event.clientY+
(document.documentElement.scrollTop||document.body.scrollTop))};return ret;},ALT_KEY:'_ALT',CTRL_KEY:'_CTRL',SHIFT_KEY:'_SHIFT'});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;}
Object.extend(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="";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;}});Object.extend(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');}});Object.extend(String.prototype,{capitalize:function(mode){var words=(mode=='first')?this:this.split(' ');words=words.map(function(word){if(word.length==0)return word;return word.charAt(0).toUpperCase()+word.substring(1);});return words.join(' ');},format:function(){var args=$A(arguments);var str=this.gsub(/%@([0-9]+)/,function(m){return(args[parseInt(m[1],0)-1]||'').toString();});var ret=[];var idx=-1;var loc=0;while((idx=str.indexOf("%@",loc))>=0){ret.push(str.slice(loc,idx));loc=idx+2;var value=args.shift();if(value&&value.toString)value=value.toString();ret.push(value);}
if(loc<str.length){ret.push(str.slice(loc,str.length));}
return(ret.length>1)?ret.join(''):ret[0];},loc:function(){var kit=String[String.currentLanguage()];var str=kit[this];if(!str)str=String.English[this]||this;return str.format.apply(str,arguments);},locWithDefault:function(def){var kit=String[String.currentLanguage()];var str=kit[this];if(!str)str=String.English[this]||def;var args=$A(arguments);args.shift();return str.format.apply(str,args);},classify:function(){return this.camelize().capitalize();},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,' ');},toHref:function(){if(this.match(/.+@.+\...+/)){return'mailto:'+this;}else if(this.indexOf('http://')!=0&&this.indexOf('https://')!=0&&this.match(/[^.]+\.[^.]+/)){return'http://'+this;}else{return this;}},trim:function()
{return this.replace(/^\s+|\s+$/g,"");},strip:function()
{return this.trim();}});String.prototype.fmt=String.prototype.format;Object.extend(String,{browserLanguage:((navigator.language||navigator.browserLanguage).split('-',1)[0]),useAutodetectedLanguage:NO,preferredLanguage:null,currentLanguage:function(){var ret=(this.useAutodetectedLanguage)?(this.browserLanguage||this.preferredLanguage||'en'):(this.preferredLanguage||this.browserLanguage||'en');if(!this[ret])ret=this.normalizedLanguage(ret);return ret;},normalizedLanguage:function(ret){switch(ret){case'fr':ret='French';break;case'de':ret='German';break;case'ja':case'jp':ret='Japanese';break;case'en':ret='English';break;case'es':ret='Spanish';break;default:break;}
return ret;},addStringsFor:function(language,strings){language=String.normalizedLanguage(language);if(!String[language])String[language]={};Object.extend(String[language],strings||{});return this;}});String.English=String.English||{};String.French=String.French||{};String.German=String.German||{};String.Japanese=String.Japanese||{};require('core');require('foundation/date');require('foundation/string');SC.Benchmark={verbose:NO,enabled:YES,stats:{},start:function(key,topLevelOnly,time){if(!this.enabled)return;var stat=this._statFor(key);if(topLevelOnly&&stat._starts.length>0){stat._starts.push('ignore');}else{stat._starts.push(time||Date.now());}},end:function(key,time){if(!this.enabled)return;var stat=this._statFor(key);var start=stat._starts.pop();if(!start){console.log('WARNING: SC.Benchmark "%@" ended without a matching start.  No information was saved.'.fmt(key));return;}
if(start=='ignore')return;stat.amt+=(time||Date.now())-start;stat.runs++;if(this.verbose)this.log(key);},bench:function(func,key,reps){if(!key)key="bench%@".fmt(this._benchCount++);if(!reps)reps=1;var ret;while(--reps>=0){SC.Benchmark.start(key);ret=func();SC.Benchmark.end(key);}
return ret;},install:function(object,method,topLevelOnly){var __func=object['b__'+method]=object[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 key in this.stats){if(!this.stats.hasOwnProperty(key))continue;ret.push(this._genReport(key));}
return ret.join("\n");},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);},_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);},_statFor:function(key){var ret=this.stats[key];if(!ret)ret=this.stats[key]={runs:0,amt:0,name:key,_starts:[]};return ret;},reset:function(){this.stats={};},_bench:function(func,name){SC.Benchmark.bench(func,name,1);},_benchCount:1};SC.Observable={bind:function(toKey,fromPropertyPath){var r=SC.idt.active;var binding;var props={to:[this,toKey]};var pathType=$type(fromPropertyPath);if(pathType==T_STRING||pathType==T_ARRAY){binding=this[toKey+'BindingDefault']||SC.Binding.From;binding=binding(fromPropertyPath);}else binding=fromPropertyPath;var relayFrom=binding.prototype.from;if($type(relayFrom)==T_STRING)switch(relayFrom.slice(0,1)){case'*':case'.':relayFrom=[this,relayFrom.slice(1,relayFrom.length)];}
if(r)bt=new Date().getTime();binding=binding.create(props,{from:relayFrom});this.bindings.push(binding);if(r)SC.idt.b1_t+=(new Date().getTime())-bt;return binding;},didChangeFor:function(context){var keys=$A(arguments);context=keys.shift();var ret=false;if(!this._didChangeCache)this._didChangeCache={};if(!this._didChangeRevisionCache)this._didChangeRevisionCache={};var seen=this._didChangeCache[context]||{};var seenRevisions=this._didChangeRevisionCache[context]||{};var loc=keys.length;var rev=this._kvo().revision;while(--loc>=0){var key=keys[loc];if(seenRevisions[key]!=rev){var val=this.get(key);if(seen[key]!==val)ret=true;seen[key]=val;}
seenRevisions[key]=rev;}
this._didChangeCache[context]=seen;this._didChangeRevisionCache[context]=seenRevisions;return ret;},get:function(key){var ret=this[key];if(ret===undefined){return this.unknownProperty(key);}else if(ret&&(ret instanceof Function)&&ret.isProperty){return ret.call(this,key);}else return ret;},set:function(key,value){var func=this[key];var ret=value;this.propertyWillChange(key);if(func&&(func instanceof Function)&&(func.isProperty)){ret=func.call(this,key,value);}else if(func===undefined){ret=this.unknownProperty(key,value);}else ret=this[key]=value;this.propertyDidChange(key,ret);return this;},setIfChanged:function(key,value){return(this.get(key)!==value)?this.set(key,value):this;},getPath:function(path){var tuple=SC.Object.tupleForPropertyPath(path,this);if(tuple[0]===null)return undefined;return tuple[0].get(tuple[1]);},setPath:function(path,value){var tuple=SC.Object.tupleForPropertyPath(path,this);if(tuple[0]==null)return null;tuple[0].set(tuple[1],value);return this;},getEach:function(){var keys=$A(arguments).flatten();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);},unknownProperty:function(key,value){if(!(value===undefined)){this[key]=value;}
return value;},propertyObserver:function(observer,target,key,value){},beginPropertyChanges:function(){this._kvo().changes++;return this;},endPropertyChanges:function(){var kvo=this._kvo();kvo.changes--;if(kvo.changes<=0)this._notifyPropertyObservers();return this;},propertyWillChange:function(key){this._kvo().changes++;return this;},propertyDidChange:function(key,value){this._kvo().changed[key]=value;var kvo=this._kvo();kvo.changes--;kvo.revision++;if(kvo.changes<=0)this._notifyPropertyObservers();return this;},notifyPropertyChange:function(key,value){this.propertyWillChange(key);this.propertyDidChange(key,value);return this;},allPropertiesDidChange:function(){this._notifyPropertyObservers(true);return this;},addObserver:function(key,func){var kvo=this._kvo();key=key.toString();var parts=key.split('.');if(parts.length>1){var co=SC._ChainObserver.createChain(this,parts,func);co.masterFunc=func;var chainObservers=kvo.chainObservers[key]||[];chainObservers.push(co);kvo.chainObservers[key]=chainObservers;}else{var observers=kvo.observers[key]=(kvo.observers[key]||[]);var found=false;var loc=observers.length;while(!found&&--loc>=0)found=(observers[loc]==func);if(!found)observers.push(func);}
return this;},removeObserver:function(key,func){var kvo=this._kvo();key=key.toString();var parts=key.split('.');if(parts.length>1){var chainObservers=kvo.chainObserver[key]||[];var newObservers=[];chainObservers.each(function(co){if(co.masterFunc!=func)newObservers.push(co);});kvo.chainObservers[key]=newObservers;}else{var observers=kvo.observers[key]||[];observers=observers.without(func);kvo.observers[key]=observers;}
return this;},addProbe:function(key){this.addObserver(key,logChange);},removeProbe:function(key){this.removeObserver(key,logChange);},logProperty:function(){var props=$A(arguments);for(var idx=0;idx<props.length;idx++){var prop=props[idx];console.log('%@:%@: '.fmt(this._guid,prop),this.get(prop));}},observeOnce:function(key,func,timeout){var timeoutObject=null;var target=this;var handler=function(theTarget,theKey,theValue,didTimeout){func(theTarget,theKey,theValue,didTimeout);target.removeObserver(key,handler);if(timeoutObject){timeoutObject.invalidate();}};target.addObserver(key,handler);if(timeout)timeoutObject=function(){handler(target,key,target.get(key),true);}.invokeLater(this,timeout);handler.cancel=function(){target.removeObserver(key,handler);};return handler;},registerDependentKey:function(key){var keys=$A(arguments);var dependent=keys.shift();var kvo=this._kvo();for(var loc=0;loc<keys.length;loc++){var key=keys[loc];if(key instanceof Array){key.push(dependent);this.registerDependentKey.apply(this,key);}else{var dependents=kvo.dependents[key]||[];dependents.push(dependent);kvo.dependents[key]=dependents;}}},_kvo:function(){if(!this._kvod)this._kvod={changes:0,changed:{},observers:{},dependents:{},chainObservers:{},revision:0};return this._kvod;},propertyRevision:1,_notifyPropertyObservers:function(allObservers){var key;var observers;var keys=[];var loc;var oloc;var value;var kvo=this._kvo();SC.Observers.flush();this.propertyRevision++;var keySource=(allObservers)?kvo.observers:kvo.changed;var allKeys={};var _addDependentKeys=function(key){if(allKeys[key]!==undefined)return;allKeys[key]=key;if(allObservers)return;var dependents=kvo.dependents[key];if(dependents&&dependents.length>0){var loc=dependents.length;while(--loc>=0){var depKey=dependents[loc];_addDependentKeys(depKey);}}};for(key in keySource){if(!keySource.hasOwnProperty(key))continue;_addDependentKeys(key);}
for(key in allKeys){if(!allKeys.hasOwnProperty(key))continue;keys.push(key);}
var starObservers=kvo.observers['*'];var changed=kvo.changed;kvo.changed={};var target=this;loc=keys.length;var notifiedKeys={};while(--loc>=0){key=keys[loc];observers=kvo.observers[key];if(!notifiedKeys[key]){notifiedKeys[key]=key;value=(allObservers||(!changed[key]))?this.get(key):changed[key];if(starObservers){observers=(observers)?observers.concat(starObservers):starObservers;}
if(observers){oloc=observers.length;var args=[target,key,value,this.propertyRevision];while(--oloc>=0){var observer=observers[oloc];SC.NotificationQueue.add(null,observer,args);}}
if(this.propertyObserver!=SC.Object.prototype.propertyObserver){SC.NotificationQueue.add(this,this.propertyObserver,[null,target,key,value,this.propertyRevision]);}}}
SC.NotificationQueue.flush();}};Object.extend(Function.prototype,{property:function(){this.dependentKeys=$A(arguments);this.isProperty=true;return this;},observes:function(propertyPaths){this.propertyPaths=$A(arguments);return this;},typeConverter:function(){this.isTypeConverter=true;return this;},invokeLater:function(target,interval){if(interval===undefined)interval=1;var f=this;if(arguments.length>2){var args=$A(arguments).slice(2,arguments.length);args.unshift(target);f=f.bind.apply(f,args);}
return SC.Timer.schedule({target:target,action:f,interval:interval});}});SC.Observers={queue:{},addObserver:function(propertyPath,func){if(typeof(propertyPath)=="string"){var tuple=SC.Object.tupleForPropertyPath(propertyPath);}else{var tuple=propertyPath;}
if(tuple){tuple[0].addObserver(tuple[1],func);}else{var ary=this.queue[propertyPath]||[];ary.push(func);this.queue[propertyPath]=ary;}},removeObserver:function(propertyPath,func){var tuple=SC.Object.tupleForPropertyPath(propertyPath);if(tuple){tuple[0].removeObserver(tuple[1],func);}
var ary=this.queue[propertyPath];if(ary){ary=ary.without(func);this.queue[propertyPath]=ary;}},flush:function(){var newQueue={};for(var path in this.queue){var funcs=this.queue[path];var tuple=SC.Object.tupleForPropertyPath(path);if(tuple){var loc=funcs.length;while(--loc>=0){var func=funcs[loc];tuple[0].addObserver(tuple[1],func);}}else newQueue[path]=funcs;}
this.queue=newQueue;}};SC.NotificationQueue={queue:[],maxFlush:5000,_flushing:false,add:function(target,func,args){this.queue.push([target,func,args]);},flush:function(force){if(this._flushing&&!force)return;this._flushing=true;var start=new Date().getTime();var now=start;var n=null;while(((now-start)<this.maxFlush)&&(n=this.queue.pop())){var t=n[0]||n[1];n[1].apply(t,n[2]);now=Date.now();}
this._flushing=false;if(this.queue.length>0){SC.NotificationQueue.flush.invokeLater(SC.NotificationQueue,1);}}};require('mixins/observable');Object.extend(Array.prototype,SC.Observable);SC.OUT_OF_RANGE_EXCEPTION="Index out of range";SC.Array={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);},_each:function(iterator){var len;for(var i=0,len=this.get('length');i<len;i++)
iterator(this.objectAt(i));},arrayContentDidChange:function(){var kvo=(this._kvo)?this._kvo().changes:'(null)';this.notifyPropertyChange('[]');},'[]':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(idx){if((idx<0)||(idx>=this.get('length')))throw SC.OUT_OF_RANGE_EXCEPTION;var ret=this.objectAt(idx);this.replace(idx,1,[]);return ret;},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;},pushObject:function(obj){this.insertAt(this.get('length'),obj);return obj;},popObject:function(){var len=this.get('length');if(len==0)return null;var ret=this.objectAt(len-1);this.removeAt(len-1);return ret;},shiftObject:function(){if(this.get('length')==0)return null;var ret=this.objectAt(0);this.removeAt(0);return ret;},unshiftObject:function(obj){this.insertAt(0,obj);return obj;},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(ary.objectAt(loc)!=this.objectAt(loc))return false;}
return true;},invokeWhile:function(retValue,methodName){var ret;var args=$A(arguments);retValue=args.shift();methodName=args.shift();try{this._each(function(item){var func=(item)?item[methodName]:null;ret=func.apply(item,args);if(ret!=retValue)throw $break;});}catch(e){if(e!=$break)throw e;}
return ret;}};Object.extend(Array.prototype,SC.Array);Object.extend(SC.Array,Enumerable);Object.extend(SC.Array,{slice:function(beginIndex,endIndex){var ret=[];var length=this.get('length');if(beginIndex==null)beginIndex=0;if((endIndex==null)||(endIndex>length))endIndex=length;while(beginIndex<endIndex)ret[ret.length]=this.objectAt(beginIndex++);return ret;}});Object.extend(Array.prototype,{replace:function(idx,amt,objects){if(!objects||objects.length==0){this.splice(idx,amt);}else{var args=[idx,amt].concat(objects);this.splice.apply(this,args);}
this.arrayContentDidChange();return this;},each:function(iterator){try{for(var index=0;index<this.length;index++){var item=this[index];iterator.call(item,item,index);}}catch(e){if(e!=$break)throw e;}
return this;},invoke:function(iterator){var args=$A(arguments);var methodName=args.shift();var ret=[];try{for(var index=0;index<this.length;index++){var item=this[index];ret.push(item[methodName].apply(item,args));};}catch(e){if(e!=$break)throw e;}
return ret;},invokeWhile:function(retValue,methodName){var ret;var args=$A(arguments);retValue=args.shift();methodName=args.shift();try{for(var index=0;index<this.length;index++){var item=this[index];var func=(item)?item[methodName]:null;ret=func.apply(item,args);if(ret!=retValue)return retValue;}}catch(e){if(e!=$break)throw e;}
return ret;},map:function(iterator){var ret=[];try{for(var index=0;index<this.length;index++){var item=this[index];ret.push((iterator||Prototype.K).call(item,item,index));};}catch(e){if(e!=$break)throw e;}
return ret;},unknownProperty:function(key,value){if(value!==undefined)return null;return this.invoke('get',key);}});Array.prototype.collect=Array.prototype.map;Array.asArray=function(array){if(array&&((array.length===undefined)||($type(array)==T_FUNCTION))){return[array];}
return(array)?array:[];};Array.from=Array.asArray;Object.extend(Enumerable,{invokeWhile:function(retValue,methodName){var ret;var args=$A(arguments);retValue=args.shift();methodName=args.shift();try{var obj=this;this._each(function(item){var func=(item)?item[methodName]:null;ret=func.apply(item,args);if(ret!=retValue)$break;});}catch(e){if(e!=$break)throw e;}
return ret;}});require('core');require('foundation/benchmark');require('mixins/observable');require('mixins/array');SC.BENCHMARK_OBJECTS=NO;SC.Object=function(noinit){if(noinit===SC.Object._noinit_)return;var ret=SC.Object._init.apply(this,$A(arguments));return ret;};Object.extend(SC.Object,{_noinit_:'__noinit__',mixin:function(props){var ext=$A(arguments);for(var loc=0;loc<ext.length;loc++){Object.extend(this,ext[loc]);}
return this;},extend:function(props){if(SC.BENCHMARK_OBJECTS)SC.Benchmark.start('SC.Object.extend');var ret=function(noinit){if(noinit&&(typeof(noinit)=='string')&&(noinit==SC.Object._noinit_))return;var ret=SC.Object._init.apply(this,$A(arguments));return ret;};for(var prop in this){ret[prop]=this[prop];}
var base=new this(SC.Object._noinit_);var extensions=$A(arguments);for(var loc=0;loc<extensions.length;loc++){base=SC.Object._extend(base,extensions[loc]);}
ret.prototype=base;ret._guid=SC._nextGUID++;ret._type=this;if(SC.BENCHMARK_OBJECTS)SC.Benchmark.end('SC.Object.extend');return ret;},create:function(props){var ret=new this($A(arguments),this);return ret;},createArray:function(array){var obj=this;return array.map(function(props){return obj.create(props);});},outlet:function(){var obj=this;return function(){var ret=obj.create();ret.owner=this;return ret;};},isClass:YES,objectClassName:function(){if(!this._objectClassName)this._findObjectClassNames();if(this._objectClassName)return this._objectClassName;var ret=this;while(ret&&!ret._objectClassName)ret=ret._type;return(ret&&ret._objectClassName)?ret._objectClassName:'Anonymous';},_findObjectClassNames:function(){if(SC._foundObjectClassNames)return;SC._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=='_type')continue;if(!key.match(/^[A-Z0-9]/))continue;var path=(root)?[root,key].join('.'):key;var value=object[key];switch($type(value)){case T_CLASS:if(!value._objectClassName)value._objectClassName=path;if(levels>=0)searchObject(path,value,levels);break;case T_OBJECT:if(levels>=0)searchObject(path,value,levels);break;case T_HASH:if(((root!=null)||(path=='SC'))&&(levels>=0))searchObject(path,value,levels);break;default:break;}}};searchObject(null,window,2);},toString:function(){return this.objectClassName();},tupleForPropertyPath:function(path,root){if(path.constructor==Array)return path;var parts=path.split('*');var key=null;if(parts&&parts.length>1){key=parts.pop();path=parts.join('*');}
parts=path.split('.');if(!key)key=parts.pop();var obj=this.objectForPropertyPath(parts,root);return(obj&&key)?[obj,key]:null;},objectForPropertyPath:function(path,root){var parts=(typeof(path)=="string")?path.split('.'):path;if(!root)root=window;var key=parts.shift();while(key&&root){root=(root.get)?root.get(key):root[key];key=parts.shift();}
return(parts.length>0)?undefined:root;},_init:function(extensions,type){var ret=this;for(var loc=0;loc<extensions.length;loc++){ret=SC.Object._extend(ret,extensions[loc]);}
ret._guid=SC._nextGUID++;ret._type=type;ret.init();return ret;},_extend:function(base,ext){return this._extendAllProps(false,base,ext);},_extendAllProps:function(allProperties,base,ext){var cprops=base._cprops;var f=Prototype.emptyFunction;var concats={};if(cprops)for(var cloc=0;cloc<cprops.length;cloc++){var p=cprops[cloc];var p1=base[p];var p2=ext[p];p1=(p1&&p2)?Array.from(p1).concat(p2):(p1||p2);concats[p]=p1;}
var bindings=(ext._bindings)?null:(base._bindings||[]).slice();var observers=(ext._observers)?null:(base._observers||[]).slice();var properties=(ext._properties)?null:(base._properties||[]).slice();var outlets=(ext.outlets)?null:(base.outlets||[]).slice();for(var key in ext){if(!allProperties&&!ext.hasOwnProperty(key))continue;var value=(concats.hasOwnProperty(key)?concats[key]:null)||ext[key];if(value&&(value instanceof Function)&&(!value.base)){if(value!=base[key])value.base=base[key]||f;}
var keyLen=key.length;if(bindings&&(key.slice(keyLen-7,keyLen)=="Binding")){bindings.push(key);}else if(value&&(value instanceof Function)){if(observers&&value.propertyPaths){observers.push(key);}else if(properties&&value.dependentKeys){properties.push(key);}else if(outlets&&value.autoconfiguredOutlet){outlets.push(key);}}
base[key]=value;}
if(bindings)base._bindings=bindings;if(observers)base._observers=observers;if(properties)base._properties=properties;if(outlets&&outlets.length>0)base.outlets=outlets;return base;},subclassOf:function(scClass){if(this==scClass)return false;var t=this._type;while(t){if(t==scClass)return true;t=t._type;}
return false;},kindOf:function(scClass){if(this==scClass)return true;return this.subclassOf(scClass);}});SC.idt={count:0,t:0.0,keys:0,observers:0,bindings:0,pv:0,observers_t:0,bindings_t:0,pv_t:0,conf_t:0,b1_t:0,b2_t:0,b3_t:0,e_count:0,e_t:0,v_count:0,v_t:0,vc_t:0,active:false};SC.report=function(){var c=SC.idt.count;var e=SC.idt.e_count;var v=SC.idt.v_count;var ret=[];ret.push('CREATED: '+c+' (avg time: '+(Math.floor(SC.idt.t*100/c)/100)+' msec)');ret.push('EXTENDED: '+e+' (avg time: '+(Math.floor(SC.idt.e_t*100/e)/100)+' msec)');ret.push('AVG KEYS: '+(Math.floor(SC.idt.keys*100/c)/100));ret.push('AVG OBSERVERS: '+(Math.floor(SC.idt.observers*100/c)/100)+' ('+(Math.floor(SC.idt.observers_t*100/c)/100)+' msec)');ret.push('AVG BINDINGS: '+(Math.floor(SC.idt.bindings*100/c)/100)+' ('+(Math.floor(SC.idt.bindings_t*100/c)/100)+' msec)');ret.push('AVG PV: '+(Math.floor(SC.idt.pv*100/c)/100)+' ('+(Math.floor(SC.idt.pv_t*100/c)/100)+' msec)');ret.push('AVG CONFIGURE OUTLETS: '+(Math.floor(SC.idt.conf_t*100/c)/100)+' msec');ret.push('AVG B1: '+(Math.floor(SC.idt.b1_t*100/c)/100)+' msec');ret.push('EXT: '+SC.idt.ext_c+' (avg time: '+(Math.floor(SC.idt.ext_t*100/SC.idt.ext_c)/100)+' msec)');ret.push('VIEWS: '+v+' (avg time: '+(Math.floor(SC.idt.v_t*100/v)/100)+' msec)');ret.push('VIEW CREATE: '+(Math.floor(SC.idt.vc_t*100/v)/100)+' msec)');console.log(ret.join("\n"));return ret.join("\n");};SC.Object.prototype={isObject:true,respondsTo:function(methodName)
{return!!(methodName&&this[methodName]&&($type(this[methodName])==T_FUNCTION));},tryToPerform:function(methodName,args)
{if(!methodName)return false;var args=$A(arguments);var name=args.shift();if(this.respondsTo(name))
{return this[name].apply(this,args);}
return false;},init:function(){var keySource=this.viewType||this;var loc;var keys;var key;var value;var r=SC.idt.active;var idtStart;var idtSt;if(r){SC.idt.count++;idtStart=new Date().getTime();};if(keys=keySource._observers)for(loc=0;loc<keys.length;loc++){key=keys[loc];value=this[key];if(r){SC.idt.keys++;SC.idt.observers++;idtSt=new Date().getTime();}
var propertyPaths=null;if((value instanceof Function)&&value.propertyPaths){propertyPaths=value.propertyPaths;value=value.bind(this);}else if(typeof(value)=="string"){propertyPaths=[value];value=this.propertyObserver.bind(this,key.slice(0,-8));}
if(propertyPaths)for(var ploc=0;ploc<propertyPaths.length;ploc++){var propertyPath=propertyPaths[ploc];var object=null;if(propertyPath.indexOf('.')==-1){this.addObserver(propertyPath,value);}else switch(propertyPath.slice(0,1)){case'*':case'.':propertyPath=propertyPath.slice(1,propertyPath.length);this.addObserver(propertyPath,value);break;default:SC.Observers.addObserver(propertyPath,value);}}
if(r)SC.idt.observers_t+=(new Date().getTime())-idtSt;}
this.bindings=[];if(keys=keySource._bindings)for(loc=0;loc<keys.length;loc++){key=keys[loc];value=this[key];if(r){SC.idt.keys++;SC.idt.bindings++;idtSt=new Date().getTime();}
var propertyKey=key.slice(0,-7);this[key]=this.bind(propertyKey,value);if(r)SC.idt.bindings_t+=(new Date().getTime())-idtSt;}
if(keys=keySource._properties)for(loc=0;loc<keys.length;loc++){key=keys[loc];value=this[key];if(value&&value.dependentKeys&&(value.dependentKeys.length>0)){args=value.dependentKeys.slice();args.unshift(key);this.registerDependentKey.apply(this,args);}}
if(this.initMixin){var inc=Array.from(this.initMixin);for(var idx=0;idx<inc.length;idx++)inc[idx].call(this);}
if(r){SC.idt.t+=((new Date().getTime())-idtStart);}},$super:function(args){var caller=SC.Object.prototype.$super.caller;if(!caller)throw"$super cannot determine the caller method";if(caller.base)caller.base.apply(this,arguments);},mixin:function(){return SC.Object.mixin.apply(this,arguments);},keys:function(all){var ret=[];for(var key in this){if(all||ret.hasOwnProperty(key))ret.push(key);};return ret;},instanceOf:function(scClass){return this._type==scClass;},kindOf:function(scClass){var t=this._type;while(t){if(t==scClass)return true;t=t._type;}
return false;},toString:function(){if(!this.__toString){this.__toString="%@:%@".fmt(this._type.objectClassName(),this._guid);}
return this.__toString;},awake:function(key){if(key!==undefined){var obj=this.outlet(key);if(obj)obj.awake();return;}
if(this._awake)return;this._awake=true;this.bindings.invoke('relay');if(this.outlets&&this.outlets.length){var stack=[];var working=[this,this.outlets.slice()];while(working){var next=working[1].pop();var obj=working[0];if(next){next=obj[next];if(next){if(next.bindings)next.bindings.invoke('relay');if(next.outlets&&next.outlets.length>0){stack.push(working);working=[next,next.outlets.slice()];}}}else working=stack.pop();}}},outlets:[],outlet:function(key){var value=this[key];if(value&&(value instanceof Function)&&value.isOutlet==true){if(!this._originalOutlets)this._originalOutlets={};this._originalOutlets[key]=value;value=value.call(this);this.set(key,value);}else if(typeof(value)=="string"){if(!this._originalOutlets)this._originalOutlets={};this._originalOutlets[key]=value;value=(this.$$sel)?this.$$sel(value):$$sel(value);if(value)value=(value.length>0)?((value.length==1)?value[0]:value):null;this.set(key,value);}
return value;},invokeLater:function(methodName,interval){if(interval===undefined)interval=1;var f=methodName;if(arguments.length>2){var args=$A(arguments).slice(2,arguments.length);args.unshift(this);if($type(f)===T_STRING)f=this[methodName];f=f.bind.apply(f,args);}
return SC.Timer.schedule({target:this,action:f,interval:interval});},_cprops:['_cprops','outlets','_bindings','_observers','_properties','initMixin']};Object.extend(SC.Object.prototype,SC.Observable);function logChange(target,key,value){console.log("CHANGE: "+target+"["+key+"]="+value);}
SC._ChainObserver=SC.Object.extend({isChainObserver:true,target:null,property:null,next:null,func:null,propertyObserver:function(observing,target,key,value){if((key=='target')&&(value!=this._target)){var func=this.boundObserver();if(this._target&&this._target.removeObserver){this._target.removeObserver(this.property,func);}
this._target=value;if(this._target&&this._target.addObserver){this._target.addObserver(this.property,func);}
if(!(observing=='init'))this.targetPropertyObserver();}},boundObserver:function(){if(!this._boundObserver){this._boundObserver=this.targetPropertyObserver.bind(this);}
return this._boundObserver;},targetPropertyObserver:function(){var value=(this.target&&this.target.get&&this.property)?this.target.get(this.property):null;if(value!==this._lastTargetProperty){this._lastTargetProperty=value;if(this.next){this.next.set('target',value);}else if(this.func)this.func(this.target,this.property,value);}},init:function(){arguments.callee.base.call(this);this.propertyObserver('init',this,'target',this.get('target'));}});SC._ChainObserver.mixin({createChain:function(target,keys,func){var property=keys.shift();var nextTarget=(target&&property&&target.get)?target.get(property):null;var next=(keys&&keys.length>0)?this.createChain(nextTarget,keys,func):null;return this.create({target:target,property:property,next:next,func:((next)?null:func)});}});require('core');require('foundation/object');SC.InputManager=SC.Object.extend({interpretKeyEvents:function(event,responder)
{var codes=this.codesForEvent(event);var cmd=codes[0];var chr=codes[1];if(!cmd&&!chr)return false;if(cmd)
{var methodName=SC.MODIFIED_COMMAND_MAP[cmd]||SC.BASE_COMMAND_MAP[cmd.split('_').last()];if(methodName&&responder.respondsTo(methodName))
{return responder[methodName](event);}}
if(chr&&responder.respondsTo('insertText'))
{return responder.insertText(chr);}
return false;},codesForEvent:function(e){var code=e.keyCode;var ret=null;var key=null;var modifiers='';if(code){ret=SC.FUNCTION_KEYS[code];if(!ret&&(e.altKey||e.ctrlKey))ret=SC.PRINTABLE_KEYS[code];if(ret){if(e.altKey)modifiers+='alt_';if(e.ctrlKey)modifiers+='ctrl_';if(e.shiftKey)modifiers+='shift_';}}
if(!ret){var code=e.charCode||e.keyCode;key=ret=String.fromCharCode(code);var lowercase=ret.toLowerCase();if(ret!=lowercase){modifiers='shift_';ret=lowercase;}else ret=null;}
if(ret)ret=modifiers+ret;return[ret,key];}});SC.MODIFIED_COMMAND_MAP={'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_COMMAND_MAP={'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.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.KEY_CODES={};for(var i=0,n=256;i<n;i++)
{if(SC.MODIFIER_KEYS[i]!==undefined){SC.KEY_CODES[SC.MODIFIER_KEYS[i]]=i;}else if(SC.FUNCTION_KEYS[i]!==undefined){SC.KEY_CODES[SC.FUNCTION_KEYS[i]]=i;}else if(SC.PRINTABLE_KEYS[i]!==undefined){SC.KEY_CODES[SC.PRINTABLE_KEYS[i]]=i;}}
require('core');require('foundation/object');require('foundation/input_manager');SC.Responder=SC.Object.extend({acceptsFirstResponder:false,nextResponder:null,isFirstResponder:false,pane:null,becomeFirstResponder:function()
{if(!this.get('acceptsFirstResponder'))return false;var pane=this.get('pane');if(!pane)return false;if(pane.get('firstResponder')==this)return true;pane.set('firstResponder',this);return true;},resignFirstResponder:function()
{var pane=this.get('pane');if(!pane)return false;if(pane.get('firstResponder')!=this)return false;pane.set('firstResponder',null);return true;},noResponderFor:function(){},didBecomeFirstResponder:function(){},willLoseFirstResponder:function(){},inputManager:function()
{return SC.Responder.inputManager;}.property(),keyDown:function(evt){var nr=this.get('nextResponder');return(nr&&nr.keyDown)?nr.keyDown(evt):false;},keyUp:function(evt){var nr=this.get('nextResponder');return(nr&&nr.keyUp)?nr.keyUp(evt):false;},flagsChanged:function(pressedFlags,evt){var nr=this.get('nextResponder');return(nr&&nr.flagsChanges)?nr.flagsChanges(pressedFlags,evt):false;},performKeyEquivalent:function(keystring,evt){return false;},interpretKeyEvents:function(evts){var inputManager=this.get('inputManager');if(inputManager)return inputManager.interpretKeyEvents(evts,this);return false;},doCommand:function(method)
{var responder=this;var args=$A(arguments);var method=args.shift();var aliases=this._commandAliases[method];var handled=false;do{if(this._responderHandledCommand(responder,method,args))return responder;if(aliases)
{for(var i=0,n=aliases.length;i<n;i++)
{if(this._responderHandledCommand(responder,aliases[i],args))return responder;}}}while(responder=responder.get('nextResponder'));return false;},_responderHandledCommand:function(responder,method,args)
{return(responder.respondsTo(method)&&(responder[method].apply(responder,args)!=false));},_commandAliases:{'mouseDown':['didMouseDown'],'mouseUp':['didMouseUp'],'doubleClick':['didDoubleClick'],'click':['didClick'],'mouseDown':['didMouseDown']}});SC.Responder.mixin({inputManager:SC.InputManager.create()});require('core');SC.NodeDescriptor={create:function(descriptor,opts){if(!opts)opts={};var tag=opts.tag||descriptor.tag||'div';var className=opts.cssClass||descriptor.cssClass;var elementId=opts.id||descriptor.id;var style=opts.style||descriptor.style;var innerHTML=opts.innerHTML||descriptor.innerHTML;if(!innerHTML){var childNodes=opts.childNodes||descriptor.childNodes;}
var ret=$(document.createElement(tag));if(className)ret.className=className;if(elementId)ret.id=elementId;if(style){for(var name in style)element.style[name.camelize()]=style[name];}
for(var attr in descriptor){if(this.ignoredProperties.indexOf(attr)==-1){ret.setAttribute(attr,descriptor[attr]);}}
if(innerHTML){ret.innerHTML=innerHTML;}else if(childNodes){var that=this;childNodes.each(function(desc){ret.appendChild(that.create(desc));});}
return ret;},ignoredProperties:['tag','cssClass','id','style','childNodes','innerHTML']};require('foundation/object');SC.Binding=SC.Object.extend({from:'',to:'',oneWay:false,emptyPlaceholder:null,nullPlaceholder:null,multiplePlaceholder:null,transform:null,connect:function(){if(this._connected)return;var funcs=this._boundObservers();SC.Observers.addObserver(this.get('from'),funcs.from);SC.Observers.addObserver(this.get('to'),funcs.to);this._connected=true;return this;},disconnect:function(){if(!this._connected)return;var funcs=this._boundObservers();SC.Observers.removeObserver(this.get('from'),funcs.from);SC.Observers.removeObserver(this.get('to'),funcs.to);this._connected=false;return this;},relay:function(){var tuple=SC.Object.tupleForPropertyPath(this.get('from'));if(tuple)tuple=this._walkTuple(tuple);if(tuple)this._fromObserver(tuple[0],tuple[1],tuple[0].get(tuple[1]));},init:function(){arguments.callee.base.call(this);this.connect();},_boundObservers:function(){var ret=this._boundObserverFuncs;if(!ret){this._boundObserverFuncs=ret={from:this._fromObserver.bind(this),to:this._toObserver.bind(this)};}
return ret;},_fromObserver:function(target,key,value,propertyRevision){if(propertyRevision<=this._lastFromPropertyRevision)return;this._lastFromPropertyRevision=propertyRevision;if(!this._didChange(this._lastFromValue,value))return;this._lastFromValue=value;var tuple=SC.Object.tupleForPropertyPath(this.get('to'));if(tuple)tuple=this._walkTuple(tuple);if(tuple){var transformFunc=this.transform;if(transformFunc)value=transformFunc('to',key,value);this._lastToValue=value;var pholder;if(value&&(value==[])&&(pholder=this.get('emptyPlaceholder'))){value=pholder;}else if(value&&(value instanceof Array)&&(pholder=this.get('multiplePlaceholder'))){value=(value.length==1)?value[0]:pholder;}
if((value==null)&&(pholder=this.get('nullPlaceholder')||this.get('emptyPlaceholder'))){value=pholder;}
tuple[0].set(tuple[1],value);this._lastToPropertyRevision=tuple[0].propertyRevision;}},_toObserver:function(target,key,value,propertyRevision){if(this.get('oneWay'))return;if(propertyRevision<=this._lastToPropertyRevision)return;this._lastToPropertyRevision=propertyRevision;if(!this._didChange(this._lastToValue,value))return;this._lastToValue=value;var tuple=SC.Object.tupleForPropertyPath(this.get('from'));if(tuple)tuple=this._walkTuple(tuple);if(tuple){var transformFunc=this.get('transform');if(transformFunc)value=transformFunc('from',key,value);this._lastFromValue=value;tuple[0].set(tuple[1],value);var result=tuple[0].get(tuple[1]);if(result)this._lastFromPropertyRevision=result.propertyRevision;if(result!=value){target.set(key,result);this._lastToPropertyRevision=target.propertyRevision;}}},_didChange:function(lastValue,newValue){if(newValue&&lastValue){if(typeof(newValue)==typeof(lastValue)){if(lastValue==newValue)return false;}}else if(((newValue===null)&&(lastValue===null))||((newValue===undefined)&&(lastValue===undefined)))return false;return true;},_lastToPropertyRevision:0,_lastFromPropertyRevision:0,_walkTuple:function(tuple){var parts=tuple[1].split('.');if(parts.length>1){tuple=tuple.slice();var obj=tuple[0];tuple[1]=parts.pop();for(var loc=0;(obj&&(loc<parts.length));loc++){obj=obj.get(parts[loc]);}
tuple[0]=obj;}
return(tuple[0]&&tuple[1])?tuple:null;}});SC.Binding.mixin({MULTIPLE_PLACEHOLDER:'@@MULT@@',NULL_PLACEHOLDER:'@@NULL@@',EMPTY_PLACEHOLDER:'@@EMPTY@@'});SC.Binding.From=function(from,opts){if(!opts)opts={};if(($type(from)==T_STRING)||($type(from)==T_ARRAY)){opts.from=from;}else Object.extend(opts,from);var ret=SC.Binding.extend(opts);return ret;};SC.Binding.build=function(tr){return function(from){return SC.Binding.From(from,{transform:tr});};};SC.Binding.NoChange=SC.Binding.From;SC.Binding.NoError=SC.Binding.build(function(dir,key,value){return($type(value)==T_ERROR)?null:value;});SC.Binding.NoError.ext=function(bindFunc){return function(d,k,v){return($type(value)==T_ERROR)?null:bindFunc(d,k,v);};};SC.Binding.Single=SC.Binding.build(function(d,k,v){if($type(v)==T_ARRAY){switch(v.length){case 0:v=null;break;case 1:v=v[0];break;default:v=SC.Binding.MULTIPLE_PLACEHOLDER;}}
return v;});SC.Binding.SingleNull=SC.Binding.build(function(d,k,v){if($type(v)==T_ARRAY){switch(v.length){case 0:v=null;break;case 1:v=v[0];break;default:v=null;}}
return v;});SC.Binding.SingleNoError=SC.Binding.NoError.ext(SC.Binding.Single);SC.Binding.SingleNullNoError=SC.Binding.NoError.ext(SC.Binding.SingleNull);SC.Binding.Multiple=SC.Binding.build(function(d,k,v){var t=$type(v);if(t!=T_ARRAY){if(t==null){v=[];}else if(t!=T_ERROR){v=[v];}}
return v;});SC.Binding.MultipleNoError=SC.Binding.NoError.ext(SC.Binding.Multiple);SC.Binding.Bool=SC.Binding.build(function(d,k,v){return($type(v)==T_ARRAY)?(v.length>0):!!v;});SC.Binding.NotNull=SC.Binding.build(function(d,k,v){return(v!=null);});SC.Binding.Not=SC.Binding.build(function(d,k,v){return!(($type(v)==T_ARRAY)?(v.length>0):!!v);});SC.Binding.IsNull=SC.Binding.build(function(d,k,v){return(v==null);});SC.Binding.BoolNoError=SC.Binding.NoError.ext(SC.Binding.Bool);SC.Binding.NotNullNoError=SC.Binding.NoError.ext(SC.Binding.NotNull);SC.Binding.NotNoError=SC.Binding.NoError.ext(SC.Binding.Not);SC.Binding.IsNullNoError=SC.Binding.NoError.ext(SC.Binding.IsNull);SC.Binding.Multiple=function(from){return SC.Binding.From(from,{transform:function(dir,key,value){return(value)?(SC.isArray(value)?value:[value]):value;}});};SC.Binding.MultipleNotEmpty=function(from){return SC.Binding.From(from,{transform:function(dir,key,value){return(value)?(SC.isArray(value)?value:[value]):[];}});};SC.Binding.SingleNotEmpty=function(from){return SC.Binding.From(from,{multiplePlaceholder:SC.Binding.MULTIPLE_PLACEHOLDER,emptyPlaceholder:SC.Binding.EMPTY_PLACEHOLDER,nullPlaceholder:SC.Binding.NULL_PLACEHOLDER});};SC.Binding.OneWay=function(from){return SC.Binding.From(from,{oneWay:true});};SC.Binding.Flag=function(from){return SC.Binding.From(from,{transform:function(dir,key,value){return(value&&(value instanceof Array))?(value.length==0):!!value;}});};SC.Binding.OneWayFlag=function(from){var ret=SC.Binding.Flag(from);ret.oneWay=true;return ret;};require('core');require('foundation/benchmark');SC.BENCHMARK_SELECTOR=NO;NO_LIMIT=10000;SC.PathModule={$$func:function(func,levels,max,nest){return SC._PathModule.$$func(this.rootElement,func,levels,max,nest);},$$C:function(className,levels,max,nest){return SC._PathModule.$$C(this.rootElement,className,levels,max,nest);},$$T:function(tagName,levels,max,nest){return SC._PathModule.$$T(this.rootElement,tagName,levels,max,nest);},$$P:function(property,value,levels,max,nest){return SC._PathModule.$$P(this.rootElement,property,value,levels,max,nest);},$$S:function(selector,levels,max,nest){return SC._PathModule.$$S(this.rootElement,selector,levels,max,nest);},$func:function(func,levels){return SC._PathModule.$func(this.rootElement,func,levels);},$C:function(className,levels){return SC._PathModule.$C(this.rootElement,className,levels);},$T:function(tagName,levels){return SC._PathModule.$T(this.rootElement,tagName,levels);},$P:function(attr,value,levels){return SC._PathModule.$P(this.rootElement,attr,value,levels);},$S:function(selector,levels){return SC._PathModule.$S(this.rootElement,selector,levels);},$$view:function(selector,viewClass,levels,max,nest){return SC._PathModule.$$view(this.rootElement,selector,viewClass,levels,max,nest);},$view:function(selector,viewClass,levels){return SC._PathModule.$view(this.rootElement,selector,viewClass,levels);}};SC._PathModule={$$func:function(el,func,levels,max,nest){levels=levels||NO_LIMIT;max=max||NO_LIMIT;nest=nest||false;var searchNode=function(node,depth,remain,includeThisNode){var ret=[];var match=(includeThisNode)?func(node):false;if(match){ret.push(node);remain--;}
depth--;if((match&&!nest)||(remain<=0)||(depth<=0))return ret;node=node.firstChild;while(node&&(remain>0)){var found=searchNode(node,depth,remain,true);remain-=found.length;ret=ret.concat(found);node=node.nextSibling;}
return ret;};return searchNode(el||document,levels+1,max,false);},$$C:function(el,className,levels,max,nest){return SC._PathModule.$$func(el,function(node){return Element.hasClassName(node,className);},levels,max,nest);},$$T:function(el,tagName,levels,max,nest){tagName=tagName.toUpperCase();return SC._PathModule.$$func(el,function(node){return node.tagName==tagName;},levels,max,nest);},$$P:function(el,property,value,levels,max,nest){return SC._PathModule.$$func(el,function(node){var pvalue=(node.getAttribute)?node.getAttribute(property):node[property];return pvalue==value;},levels,max,nest);},$$S:function(el,selector,levels,max,nest){var parts=selector.split(' ');var ret=[el];var nextMax=null;var bits;var blevels;var bmax;var q;var indicies;parts.each(function(part){if(part=='?'){nextMax=1;return;}
blevels=levels;bmax=(nextMax)?nextMax:max;nextMax=null;if(part.slice(part.length-1,part.length)==']'){bits=part.split('[');part=bits.shift();indicies=bits.map(function(b){return parseInt(b.slice(0,-1),0);});}else indicies=null;bits=part.split('?');part=bits[0];if(bits.length>1){bmax=(bits[1].length==0)?1:parseInt(bits[1],0);}
bits=part.split(':');part=bits[0];if(bits.length>1)blevels=(bits[1]=='*')?'*':parseInt(bits[1],0);if(bits.length>2)bmax=(bits[2]=='*')?'*':parseInt(bits[2],0);if(blevels=='*')blevels=NO_LIMIT;if(bmax=='*')bmac=NO_LIMIT;if(part&&part.length>0){q=part.slice(0,1);if(['.','#'].indexOf(q)>=0){part=part.slice(1,part.length);}
bits=part.split('.');part=bits[0];bits=bits.slice(1,bits.length);var fret=null;if(q=='#'){fret=$(part);fret=(fret)?[fret]:null;if(fret)ret=fret;}
if(fret==null){fret=[];for(var i=0;i<ret.length;i++){var found=SC._PathModule.$$func(ret[i],function(node){var match;switch(q){case'.':NODE=node;var elementClassName=node.className;if(elementClassName&&(elementClassName.length>0)){match=(elementClassName==part||elementClassName.match(new RegExp("(^|\\s)"+part+"(\\s|$)")));}else match=false;break;case'#':match=node.id==part;break;default:if(node.tagName){match=(node.tagName.toLowerCase()==part.toLowerCase());}else{match=false;}}
for(var i=0;match&&i<bits.length;i++){if(!Element.hasClassName(node,bits[i]))match=false;}
return match;},blevels,bmax,nest);fret=fret.concat(found);}
ret=fret;}}else if($type(ret)!=T_ARRAY)ret=[ret];if(indicies&&indicies.length>0&&ret){ret=ret.map(function(el){for(var iloc=0;el&&(iloc<indicies.length);iloc++){el=el.childNodes[indicies[iloc]];}
return el;});}});return ret;},$func:function(el,func,levels){var ret=SC._PathModule.$$func(el,func,levels,1,false);return(ret.length>0)?ret[0]:null;},$C:function(el,className,levels){var ret=SC._PathModule.$$C(el,className,levels,1,false);return(ret.length>0)?ret[0]:null;},$T:function(el,tagName,levels){var ret=SC._PathModule.$$T(el,tagName,levels,1,false);return(ret.length>0)?ret[0]:null;},$P:function(el,attr,value,levels){var ret=SC._PathModule.$$P(el,attr,value,levels,1,false);return(ret.length>0)?ret[0]:null;},$S:function(el,selector,levels){var ret=SC._PathModule.$$S(el,selector,levels,1,false);return(ret.length>0)?ret[0]:null;},$$view:function(el,selector,viewClass,levels,max,nest){var ret;if(selector&&(typeof(selector)!='string')){ret=[selector];}else{ret=SC._PathModule.$$S(el,selector,levels,max,nest);}
if(ret)ret=ret.map(function(x){return(viewClass)?viewClass.viewFor(x):SC.View.findViewForElement(x);});return ret;},$view:function(el,selector,viewClass,levels){var ret=SC._PathModule.$$view(el,selector,viewClass,levels,1,false);return(ret.length>0)?ret[0]:null;}};if(SC.BENCHMARK_SELECTOR){['$$S','$$C','$$T','$S','$C','$T'].each(function(mname){SC.Benchmark.install(SC._PathModule,mname);});SC.Benchmark.install(window,'$$$');}
Object.extend(SC._PathModule,{$$class:SC._PathModule.$$C,$$tag:SC._PathModule.$$T,$$sel:SC._PathModule.$$S,$$prop:SC._PathModule.$$P,$class:SC._PathModule.$C,$tag:SC._PathModule.$T,$sel:SC._PathModule.$S,$prop:SC._PathModule.$P});Object.extend(SC.PathModule,{$$class:SC.PathModule.$$C,$$tag:SC.PathModule.$$T,$$sel:SC.PathModule.$$S,$$prop:SC.PathModule.$$P,$class:SC.PathModule.$C,$tag:SC.PathModule.$T,$sel:SC.PathModule.$S,$prop:SC.PathModule.$P});Object.extend(Element.Methods,SC._PathModule);Object.extend(Element,SC._PathModule);if(typeof HTMLElement!='undefined'){Object.extend(HTMLElement.prototype,SC.PathModule);}
Object.extend(document,SC.PathModule);document.rootElement=document;Object.extend(Object.extend(window,SC.PathModule),{$$func:function(func,levels,max,nest){return document.$$func(func,levels,max,nest);}});Object.extend(Object.extend(Array.prototype,SC.PathModule),{$$func:function(func,levels,max,nest){var ret=[];for(var loc=0;loc<this.length;loc++){ret=ret.concat(this[loc].$$func(func,levels,max,nest));}
return ret;}});SC.DelegateSupport={invokeDelegateMethod:function(delegate,methodName,args){args=$A(arguments);args=args.slice(2,args.length);if(!delegate||!delegate[methodName])delegate=this;return delegate[methodName].apply(delegate,args);},getDelegateProperty:function(delegate,key){return(delegate&&(delegate[key]!=null))?delegate.get(key):this.get(key);}};require('foundation/object');require('foundation/responder');require('foundation/node_descriptor');require('foundation/binding');require('foundation/path_module');require('mixins/delegate_support');SC.BENCHMARK_OUTLETS=NO;SC.BENCHMARK_CONFIGURE_OUTLETS=NO;SC.View=SC.Responder.extend(SC.PathModule,SC.DelegateSupport,{insertBefore:function(view,beforeView){this._insertBefore(view,beforeView,true);},_insertBefore:function(view,beforeView,updateDom){if(beforeView){if(beforeView.parentNode!=this)throw"insertBefore() beforeView must belong to the receiver";if(beforeView==view)throw"insertBefore() views cannot be the same";}
if(view.parentNode)view.removeFromParent();this.willAddChild(this,beforeView);view.willAddToParent(this,beforeView);if(beforeView){view.set('previousSibling',beforeView.previousSibling);view.set('nextSibling',beforeView);beforeView.set('previousSibling',view);}else{view.set('previousSibling',this.lastChild);view.set('nextSibling',null);this.set('lastChild',view);}
if(view.previousSibling)view.previousSibling.set('nextSibling',view);if(view.previousSibling==null)this.set('firstChild',view);view.set('parentNode',this);if(updateDom){var beforeElement=(beforeView)?beforeView.rootElement:null;(this.containerElement||this.rootElement).insertBefore(view.rootElement,beforeElement);this._rebuildChildNodes();}
view._updateIsVisibleInWindow();view._flushInternalCaches();view._invalidateClippingFrame();view.didAddToParent(this,beforeView);this.didAddChild(view,beforeView);return this;},removeChild:function(view){if(!view)return;if(view.parentNode!=this)throw"removeChild: view must belong to parent";view.willRemoveFromParent();this.willRemoveChild(view);if(view.previousSibling){view.previousSibling.set('nextSibling',view.nextSibling);}else this.set('firstChild',view.nextSibling);if(view.nextSibling){view.nextSibling.set('previousSibling',view.previousSibling);}else this.set('lastChild',view.previousSibling);var el=(this.containerElement||this.rootElement);if(el&&(view.rootElement.parentNode==el)&&(el!=document)){el.removeChild(view.rootElement);}
this._rebuildChildNodes();view.set('nextSibling',null);view.set('previousSibling',null);view.set('parentNode',null);view._updateIsVisibleInWindow();view._flushInternalCaches();view._invalidateClippingFrame();view.didRemoveFromParent(this);this.didRemoveChild(view);return this;},replaceChild:function(view,oldView){this.insertBefore(view,oldView);this.removeChild(oldView);return this;},removeFromParent:function(){if(this.parentNode)this.parentNode.removeChild(this);return null;},destroy:function(){this.removeFromParent();delete SC.View._view[SC.guidFor(this)];return null;},appendChild:function(view){this.insertBefore(view,null);return this;},childNodes:[],firstChild:null,lastChild:null,nextSibling:null,previousSibling:null,parentNode:null,pane:function()
{var view=this;while(view=view.get('parentNode'))
{if(view.get('isPane'))break;}
return view;}.property(),clear:function(){while(this.firstChild)this.removeChild(this.firstChild);},willAddToParent:function(parent,beforeView){},didAddToParent:function(parent,beforeView){},willRemoveFromParent:function(){},didRemoveFromParent:function(oldParent){},willAddChild:function(child,beforeView){},didAddChild:function(child,beforeView){},willRemoveChild:function(child){},didRemoveChild:function(child){},nextKeyView:null,previousKeyView:null,nextValidKeyView:function()
{var view=this;while(view=view.get('nextKeyView'))
{if(view.get('isVisible')&&view.get('acceptsFirstResponder')){return view;}}
return null;},previousValidKeyView:function()
{var view=this;while(view=view.get('previousKeyView'))
{if(view.get('isVisible')&&view.get('acceptsFirstResponder')){return view;}}
return null;},_flushInternalCaches:function(){if((this._needsClippingFrame!=null)||(this._needsFrameChanges!=null)){this._needsClippingFrame=this._needsFrameChanges=null;if(this.parentNode)this.parentNode._flushInternalCaches();}},nextResponder:function()
{return this.parentNode;}.property('parentNode'),performKeyEquivalent:function(keystring,evt)
{var child=this.get('firstChild');while(child)
{if(child.performKeyEquivalent(keystring,evt))return true;child=child.get('nextSibling');}
return false;},classNames:function(key,value){if(value!==undefined){value=Array.from(value);if(this.rootElement)this.rootElement.className=value.join(' ');this._classNames=value.slice();}
if(!this._classNames){var classNames=this.rootElement.className;this._classNames=(classNames&&classNames.length>0)?classNames.split(' '):[];}
return this._classNames;}.property(),hasClassName:function(className){return(this._classNames||this.get('classNames')).indexOf(className)>=0;},addClassName:function(className){if(this.hasClassName(className))return;var classNames=this._classNames||this.get('classNames');classNames.push(className);this.set('classNames',classNames);return className;},removeClassName:function(className){if(!this.hasClassName(className))return;var classNames=this._classNames||this.get('classNames');classNames=this._classNames=classNames.without(className);this.set('classNames',classNames);return className;},setClassName:function(className,flag){return(!!flag)?this.addClassName(className):this.removeClassName(className);},toggleClassName:function(className){return this.setClassName(className,!this.hasClassName(className));},getStyle:function(style){var element=this.rootElement;if(!this._computedStyle){this._computedStyle=document.defaultView.getComputedStyle(element,null);}
style=(style==='float')?'cssFloat':style.camelize();var value=element.style[style];if(!value){value=this._computedStyle?this._computedStyle[style]:null;}
if(style==='opacity'){value=value?parseFloat(value):1.0;}
if(value==='auto')value=null;return value;},setStyle:function(styles,camelized){return Element.setStyle(this.rootElement,styles,camelized);},update:function(html){Element.update((this.containerElement||this.rootElement),html);this.propertyDidChange('innerHTML');},getAttribute:function(attrName){return Element.readAttribute(this.rootElement,attrName);},setAttribute:function(attrName,value){this.rootElement.setAttribute(attrName,value);},hasAttribute:function(attrName){return Element.hasAttribute(this.rootElement,attrName);},unknownProperty:function(key,value){if(key&&key.match&&key.match(/^style/)){key=key.slice(5,key.length).replace(/^./,function(x){return x.toLowerCase();});var ret=null;if(key.match(/height$|width$|top$|bottom$|left$|right$/i)){if(value!==undefined){this.viewFrameWillChange();var props={};props[key]=(value)?value+'px':'auto';this.setStyle(props);this.viewFrameDidChange();}
ret=this.getStyle(key);ret=(ret==='auto')?null:parseInt(ret,0);}else{if(value!==undefined){var props={};props[key]=value;this.setStyle(props);}
ret=this.getStyle(key);}
return ret;}else return arguments.callee.base.call(this,key,value);},rootElement:null,containerElement:null,needsClippingFrame:function(){if(this._needsClippingFrame==null){var ret=this.clippingFrameDidChange!=SC.View.prototype.clippingFrameDidChange;var view=this.get('firstChild');while(!ret&&view){ret=view.get('needsClippingFrame');view=view.get('nextSibling');}
this._needsClippingFrame=ret;}
return this._needsClippingFrame;}.property(),needsFrameChanges:function(){if(this._needsFrameChanges==null){var ret=this.get('needsClippingFrame')||this.get('hasManualLayout');var view=this.get('firstChild');while(!ret&&view){ret=view.get('needsFrameChanges');view=view.get('nextSibling');}
this._needsFrameChanges=ret;}
return this._needsFrameChanges;}.property(),hasManualLayout:function(){return(this.resizeChildrenWithOldSize!=SC.View.prototype.resizeChildrenWithOldSize)||(this.resizeWithOldParentSize!=SC.View.prototype.resizeWithOldParentSize)||(this.clippingFrameDidChange!=SC.View.prototype.clippingFrameDidChange);}.property(),convertFrameFromView:function(f,targetView){var thisOffset=SC.viewportOffset(this.get('offsetParent'));var thatOffset=(targetView)?SC.viewportOffset(targetView.get('offsetParent')):SC.ZERO_POINT;var adjustX=thatOffset.x-thisOffset.x;var adjustY=thatOffset.y-thisOffset.y;return{x:(f.x+adjustX),y:(f.y+adjustY),width:f.width,height:f.height};},convertFrameToView:function(f,sourceView){var thisOffset=SC.viewportOffset(this.get('offsetParent'));var thatOffset=(sourceView)?SC.viewportOffset(sourceView.get('offsetParent')):SC.ZERO_POINT;var adjustX=thisOffset.x-thatOffset.x;var adjustY=thisOffset.y-thatOffset.y;return{x:(f.x+adjustX),y:(f.y+adjustY),width:f.width,height:f.height};},offsetParent:function(){var el=this.rootElement;if(!el||el===document.body)return el;if(el.offsetParent)return el.offsetParent;var ret=null;while(!ret&&(el=el.parentNode)&&(el.nodeType!==11)&&(el!==document.body)){if(Element.getStyle(el,'position')!=='static')ret=el;}
if(!ret&&(el===document.body))ret=el;return ret;}.property(),innerFrame:function(key,value){var f;if(this._innerFrame==null){var el=this.rootElement;f=this._collectFrame(SC.View._collectInnerFrame);if(SC.Platform.Firefox){var parent=el.offsetParent;if(parent&&(Element.getStyle(parent,'overflow')!='visible')){var left=parseInt(Element.getStyle(parent,'borderLeftWidth'),0)||0;var top=parseInt(Element.getStyle(parent,'borderTopWidth'),0)||0;f.x+=left;f.y+=top;}}
var clientLeft,clientTop;if(el.clientLeft==null){clientLeft=parseInt(this.getStyle('border-left-width'),0)||0;}else clientLeft=el.clientLeft;if(el.clientTop==null){clientTop=parseInt(this.getStyle('border-top-width'),0)||0;}else clientTop=el.clientTop;f.x+=clientLeft;f.y+=clientTop;this._innerFrame=SC.cloneRect(f);}else f=SC.cloneRect(this._innerFrame);return f;}.property('frame'),frame:function(key,value){if(value!==undefined){this.viewFrameWillChange();var f=value;var style={};var didResize=false;if(value.x!==undefined){style.left=Math.floor(f.x)+'px';style.right='auto';}
if(value.y!==undefined){style.top=Math.floor(f.y)+'px';style.bottom='auto';}
if(value.width!==undefined){didResize=true;var padding=0;var idx=SC.View.WIDTH_PADDING_STYLES.length;while(--idx>=0){padding+=parseInt(this.getStyle(SC.View.WIDTH_PADDING_STYLES[idx]),0)||0;}
style.width=(Math.floor(f.width)-padding).toString()+'px';}
if(value.height!==undefined){didResize=true;var padding=0;var idx=SC.View.HEIGHT_PADDING_STYLES.length;while(--idx>=0){padding+=parseInt(this.getStyle(SC.View.HEIGHT_PADDING_STYLES[idx]),0)||0;}
style.height=(Math.floor(f.height)-padding).toString()+'px';}
this.setStyle(style);this.viewFrameDidChange();}
var f;if(this._frame==null){var el=this.rootElement;f=this._collectFrame(function(){return{x:el.offsetLeft,y:el.offsetTop,width:el.offsetWidth,height:el.offsetHeight};});if(SC.Platform.Firefox){var parent=el.offsetParent;if(parent&&(Element.getStyle(parent,'overflow')!='visible')){var left=parseInt(Element.getStyle(parent,'borderLeftWidth'),0)||0;var top=parseInt(Element.getStyle(parent,'borderTopWidth'),0)||0;f.x+=left;f.y+=top;}}
this._frame=SC.cloneRect(f);}else f=SC.cloneRect(this._frame);return f;}.property(),size:function(key,value){if(value!==undefined){this.set('frame',{width:value.width,height:value.height});}
return this.get('frame');}.property('frame'),origin:function(key,value){if(value!==undefined){this.set('frame',{x:value.x,y:value.y});}
return this.get('frame');}.property('frame'),viewFrameWillChange:function(){if(this._frameChangeLevel++<=0){this._frameChangeLevel=1;if(this.get('needsFrameChanges')){this._cachedFrames=this.getEach('innerFrame','clippingFrame','frame');}else this._cachedFrames=null;this.beginPropertyChanges();}},viewFrameDidChange:function(force){this.recacheFrames();if(--this._frameChangeLevel<=0){this._frameChangeLevel=0;if(this._cachedFrames){var newFrames=this.getEach('innerFrame','clippingFrame');var nf=newFrames[1];var of=this._cachedFrames[1];if(force||(nf.width!=of.width)||(nf.height!=of.height)){this._invalidateClippingFrame();}
var nf=newFrames[0];var of=this._cachedFrames[0];if(force||(nf.width!=of.width)||(nf.height!=of.height)){this.resizeChildrenWithOldSize(this._cachedFrames.last());}
var parent=this.parentNode;while(parent&&parent!=SC.window){if(parent._scrollFrame)parent._scrollFrame=null;parent=parent.parentNode;}
this.notifyPropertyChange('frame');}
this.endPropertyChanges();}},recacheFrames:function(){this._innerFrame=this._frame=this._clippingFrame=this._scrollFrame=null;},isScrollable:false,scrollFrame:function(key,value){if(value!=undefined){var el=this.rootElement;if(value.x!=null)el.scrollLeft=0-value.x;if(value.y!=null)el.scrollTop=0-value.y;this._scrollFrame=null;this._invalidateClippingFrame();}
var f;if(this._scrollFrame==null){var el=this.rootElement;f=this._collectFrame(function(){return{x:0-el.scrollLeft,y:0-el.scrollTop,width:el.scrollWidth,height:el.scrollHeight};});this._scrollFrame=SC.cloneRect(f);}else f=SC.cloneRect(this._scrollFrame);return f;}.property('frame'),clippingFrame:function(){var f;if(this._clippingFrame==null){f=this.get('frame');if(this.parentNode){var parent=this.parentNode;var prect=SC.intersectRects(parent.get('clippingFrame'),parent.get('innerFrame'));prect=this.convertFrameFromView(prect,parent);if(this.parentNode.get('isScrollable')){var scrollFrame=this.get('scrollFrame');prect.x-=scrollFrame.x;prect.y-=scrollFrame.y;}
f=SC.intersectRects(f,prect);}else{f.width=f.height=0;}
this._clippingFrame=SC.cloneRect(f);}else f=SC.cloneRect(this._clippingFrame);return f;}.property('frame','scrollFrame'),clippingFrameDidChange:function(){},resizeChildrenWithOldSize:function(oldSize){var child=this.get('firstChild');while(child){child.resizeWithOldParentSize(oldSize);child=child.get('nextSibling');}},resizeWithOldParentSize:function(oldSize){this.viewFrameWillChange();this.viewFrameDidChange(YES);},_onscroll:function(){this._scrollFrame=null;this.notifyPropertyChange('scrollFrame');SC.Benchmark.start('%@.onscroll'.fmt(this));this._invalidateClippingFrame();SC.Benchmark.end('%@.onscroll'.fmt(this));},_frameChangeLevel:0,_collectFrame:function(func){var el=this.rootElement;var isVisibleInWindow=this.get('isVisibleInWindow');if(!isVisibleInWindow){var pn=el.parentNode||el;if(pn===SC.window.rootElement)pn=el;var pnParent=pn.parentNode;var pnSib=pn.nextSibling;SC.window.rootElement.insertBefore(pn,null);}
var display=this.getStyle('display');var isHidden=!(display!='none'&&display!=null);if(isHidden){var els=this.rootElement.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';els.position='absolute';els.display='block';}
var ret=func.call(this);if(isHidden){els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;}
if(!isVisibleInWindow){if(pnParent){pnParent.insertBefore(pn,pnSib);}else{if(pn.parentNode)
SC.window.rootElement.removeChild(pn);}}
return ret;},_invalidateChildrenClippingFrames:function(){var view=this.get('firstChild');while(view){view._invalidateClippingFrame();view=view.get('nextSibling');}},_invalidateClippingFrame:function(){if(this.get('needsClippingFrame')){this._clippingFrame=null;this.clippingFrameDidChange();this.notifyPropertyChange('clippingFrame');this._invalidateChildrenClippingFrames();}},isVisible:true,isVisibleBindingDefault:SC.Binding.Bool,displayIsVisible:true,isVisibleInWindow:NO,localize:false,toolTip:'',emptyElement:"<div></div>",isPanel:false,isModal:true,isAnimationEnabled:true,transitionTo:function(target,animator,opts){var animatorOptions=opts||{};if(animator&&!animator._isAnimator){var finalStyle=animator;if(!this.get("isAnimationEnabled")){animatorOptions=Object.clone(animatorOptions);animatorOptions.duration=1;}
if(animatorOptions.duration){animatorOptions.duration=parseInt(animatorOptions.duration,0);}
animator=Animator.apply(this.rootElement,finalStyle,animatorOptions);animator._isAnimator=true;}
if(animator){animator.jumpTo(animator.state);animator.seekTo(target);}
return animator;},innerHTML:function(key,value){if(value!==undefined){this._textNode=null;if(SC.isSafari()&&!SC.isSafari3()){var el=(this.containerElement||this.rootElement);var reps=0;var f=function(){el.innerHTML='';el.innerHTML=value;if((reps++<5)&&(value.length>0)&&(el.innerHTML=='')){f.invokeLater();}};f();}else(this.containerElement||this.rootElement).innerHTML=value;}else value=(this.containerElement||this.rootElement).innerHTML;return value;}.property(),innerText:function(key,value){if(value!==undefined){if(value==null)value='';if(this._textNode==null){this._textNode=document.createTextNode(value);var el=this.rootElement||this.containerElement;while(el.firstChild)el.removeChild(el.firstChild);el.appendChild(this._textNode);}else this._textNode.data=value;}
return(this._textNode)?this._textNode.data:this.innerHTML().unescapeHTML();}.property(),init:function(){arguments.callee.base.call(this);if(SC.BENCHMARK_CONFIGURE_OUTLETS)SC.Benchmark.start('SC.View.configureOutlets');this.configureOutlets();if(SC.BENCHMARK_CONFIGURE_OUTLETS)SC.Benchmark.end('SC.View.configureOutlets');var toolTip=this.get('toolTip');if(toolTip&&(toolTip!=''))this._updateToolTipObserver();if(this.containerElement&&($type(this.containerElement)===T_STRING)){this.containerElement=this.$sel(this.containerElement);}
if(this.get('isDropTarget'))SC.Drag.addDropTarget(this);if(this.get('isScrollable'))SC.Drag.addScrollableView(this);if(this.isScrollable)this.rootElement.onscroll=SC.View._onscroll;this.isVisibleInWindow=(this.parentNode)?this.parentNode.get('isVisibleInWindow'):NO;},configureOutlets:function(){if(!this.outlets||(this.outlets.length<=0))return;this.beginPropertyChanges();for(var oloc=0;oloc<this.outlets.length;oloc++){var view=this.outlet(this.outlets[oloc]);}
this.endPropertyChanges();},show:function(){Element.show(this.rootElement);this.removeClassName('hidden');this.set('displayIsVisible',true);},hide:function(){Element.hide(this.rootElement);this.addClassName('hidden');this.set('displayIsVisible',false);},animateVisible:function(key,value){if(value!==undefined)return this.set('isAnimationEnabled',value);return this.get('isAnimationEnabled');}.property('isAnimationEnabled'),_attachRootElement:function(el){if(this.rootElement)this.rootElement._configured=null;this.rootElement=el;el._configured=this._guid;},_rebuildChildNodes:function(){var ret=[];var view=this.firstChild;while(view){ret.push(view);view=view.nextSibling;}
this.set('childNodes',ret);},_toolTipObserver:function(){var toolTip=this.get('toolTip');if(this.get('localize'))toolTip=toolTip.loc();this.rootElement.title=toolTip;}.observes("toolTip"),_isVisibleObserver:function(){var flag=this.get('isVisible');if((this._isVisible===undefined)||(flag!=this._isVisible)){this._isVisible=flag;if(flag){this._show();}else this._hide();this._updateIsVisibleInWindow();}}.observes('isVisible'),_updateIsVisibleInWindow:function(parentNodeState){if(parentNodeState===undefined){var parentNode=this.get('parentNode');parentNodeState=(parentNode)?parentNode.get('isVisibleInWindow'):false;}
var visible=parentNodeState&&this.get('isVisible');if(visible!=this.get('isVisibleInWindow')){this.set('isVisibleInWindow',visible);this.recacheFrames();var child=this.get('firstChild');while(child){child._updateIsVisibleInWindow(visible);child=child.get('nextSibling');}}},_show:function(anchorView,triggerEvent){if(this.showView)return this.showView();var paneType=this.get('paneType');if(this.get('isPanel'))paneType=SC.PANEL_PANE;if(paneType){if(anchorView===undefined)anchorView=null;if(triggerEvent===undefined)triggerEvent=null;SC.PaneManager.manager().showPaneView(this,paneType,anchorView,triggerEvent);this.set('displayIsVisible',true);}else if(this.visibleAnimation&&this.get('isAnimationEnabled')){this._transitionVisibleTo(1.0);this.show();}else{this._visibleAnimator=null;this.show();}
return this;},_hide:function(){if(this.hideView)return this.hideView();var isPane=(!!this.get('paneType'))||this.get('isPanel');if(isPane){SC.PaneManager.manager().hidePaneView(this);this.set('displayIsVisible',false);}else if(this.visibleAnimation&&this.get('isAnimationEnabled')){this._transitionVisibleTo(0.0);}else{this._visibleAnimator=null;this.hide();}
return this;},_transitionVisibleTo:function(target){var a;if(this._visibleAnimator){this.transitionTo(target,this._visibleAnimator);}else{var opts=this.visibleAnimation;var style=[opts.hidden,opts.visible];opts.onComplete=this._animateVisibleDidComplete.bind(this,opts.onComplete);this._visibleAnimator=this.transitionTo(target,style,opts);}},_animateVisibleDidComplete:function(chainFunc){if(!this.get('isVisible'))this.hide();if(chainFunc)chainFunc(this);},_firstResponderObserver:function(target,key,value){this.setClassName('focus',value);}.observes('isFirstResponder'),_dropTargetObserver:function(){if(this.get('isDropTarget')){SC.Drag.addDropTarget(this);}else SC.Drag.removeDropTarget(this);}.observes('isDropTarget'),popup:function(anchorView,triggerEvent){this._isVisible=true;this._show(anchorView,triggerEvent);this.set('isVisible',true);},configureObserverMethods:function(methodMap){for(var name in methodMap){if(!methodMap.hasOwnProperty(name))continue;if(this[name]){var method=this[name].bindAsEventListener(this);Event.observe(this.rootElement,methodMap[name],method);}}}});SC.View.mixin({_view:{},findViewForElement:function(el){var guid=el._configured;return(guid)?SC.View._view[guid]:null;},viewFor:function(el,config){if(el)el=$(el);var r=SC.idt.active;var vStart;if(r)SC.idt.v_count++;if(r)vStart=new Date().getTime();if(!el){var emptyElement=this.prototype._cachedEmptyElement||this.prototype.emptyElement;var isString=typeof(emptyElement)=='string';if(isString&&(emptyElement.slice(0,1)!='<')){var el=$sel(emptyElement);if(el){this.prototype.emptyElement=emptyElement=el;isString=false;}}
if(isString){SC._ViewCreator.innerHTML=emptyElement;el=$(SC._ViewCreator.firstChild);SC.NodeCache.appendChild(el);this.prototype._cachedEmptyElement=el.cloneNode(true);}else if(typeof(emptyElement)=="object"){if(emptyElement.tagName){el=emptyElement.cloneNode(true);}else el=SC.NodeDescriptor.create(emptyElement);}}
if(r)SC.idt.vc_t+=(new Date().getTime())-vStart;if(el&&el._configured)return SC.View.findViewForElement(el);var args=$A(arguments);args[0]={rootElement:el};if(r)vStart=new Date().getTime();var ret=new this(args,this);if(r)SC.idt.v_t+=(new Date().getTime())-vStart;el._configured=ret._guid;SC.View._view[ret._guid]=ret;return ret;},create:function(configs){var args=$A(arguments);args.unshift(null);return this.viewFor.apply(this,args);},extend:function(configs){var ret=SC.Object.extend.apply(this,arguments);ret.prototype._cachedEmptyElement=null;return ret;},outletFor:function(path){var viewClass=this;var func=function(){if(SC.BENCHMARK_OUTLETS)SC.Benchmark.start("OUTLET(%@)".format(path));if(path==null){var ret=viewClass.viewFor(null);}else{var ret=(this.$$sel)?this.$$sel(path):$$sel(path);if(ret){var owner=this;var views=[];for(var loc=0;loc<ret.length;loc++){var view=viewClass.viewFor(ret[loc],{owner:owner});if(view&&view.rootElement&&view.rootElement.parentNode){var node=view.rootElement.parentNode;var parentView=null;while(node&&!parentView){switch(node){case this.rootElement:parentView=this;break;case SC.page.rootElement:parentView=SC.page;break;case SC.window.rootElement:parentView=SC.window;default:node=node.parentNode;}}
if(parentView){parentView._insertBefore(view,null,false);parentView._rebuildChildNodes();view._updateIsVisibleInWindow();}}
views[views.length]=view;}
ret=views;ret=(ret.length==0)?null:((ret.length==1)?ret[0]:ret);}}
if(SC.BENCHMARK_OUTLETS)SC.Benchmark.end("OUTLET(%@)".format(path));return ret;};func.isOutlet=true;return func;},automaticOutletFor:function(){var ret=this.outletFor.apply(this,arguments);ret.autoconfiguredOutlet=YES;return ret;}});if(SC.Platform.IE){SC.View.prototype.getStyle=function(style){var element=this.rootElement;style=(style=='float'||style=='cssFloat')?'styleFloat':style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style==='opacity'){if(value=(this.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/)){if(value[1])value=parseFloat(value[1])/100;}
value=1.0;}
if(value==='auto'){switch(style){case'width':if(this.getStyle('display')==='none'){value=null;}else if(element.currentStyle){var paddingLeft=parseInt(element.currentStyle.paddingLeft,0)||0;var paddingRight=parseInt(element.currentStyle.paddingRight,0)||0;var borderLeftWidth=parseInt(element.currentStyle.borderLeftWidth,0)||0;var borderRightWidth=parseInt(element.currentStyle.borderRightWidth,0)||0;value=(element.offsetWidth-paddingLeft-paddingRight-borderLeftWidth-borderRightWidth)+'px';}
break;case'height':if(this.getStyle('display')==='none'){value=null;}else if(element.currentStyle){var paddingTop=parseInt(element.currentStyle.paddingTop,0)||0;var paddingBottom=parseInt(element.currentStyle.paddingBottom,0)||0;var borderTopWidth=parseInt(element.currentStyle.borderTopWidth,0)||0;var borderBottomWidth=parseInt(element.currentStyle.borderBottomWidth,0)||0;value=(element.offsetHeight-paddingTop-paddingBottom-borderTopWidth-borderBottomWidth)+'px';}
break;default:value=null;}}
return value;};SC.View._collectInnerFrame=function(){var el=this.rootElement;var hasLayout=(el.currentStyle)?el.currentStyle.hasLayout:NO;return{x:el.offsetLeft,y:el.offsetTop,width:(hasLayout)?Math.min(el.scrollWidth,el.clientWidth):el.scrollWidth,height:(hasLayout)?Math.min(el.scrollHeight,el.clientHeight):el.scrollHeight};};}else{SC.View._collectInnerFrame=function(){var el=this.rootElement;return{x:el.offsetLeft,y:el.offsetTop,width:Math.min(el.scrollWidth,el.clientWidth),height:Math.min(el.scrollHeight,el.clientHeight)};};}
SC.View._onscroll=function(evt){$view(this)._onscroll(evt);};SC.View.WIDTH_PADDING_STYLES=['paddingLeft','paddingRight','borderLeftWidth','borderRightWidth'];SC.View.HEIGHT_PADDING_STYLES=['paddingTop','paddingBottom','borderTopWidth','borderBottomWidth'];SC.View.SCROLL_WIDTH_PADDING_STYLES=['borderLeftWidth','borderRightWidth'];SC.View.SCROLL_HEIGHT_PADDING_STYLES=['borderTopWidth','borderBottomWidth'];SC.View.elementFor=SC.View.viewFor;SC._ViewCreator=document.createElement('div');SC.NodeCache=document.createElement('div');require('views/view');SC.KEYVIEW_SELECTING_NONE=0;SC.KEYVIEW_SELECTING_NEXT=1;SC.KEYVIEW_SELECTING_PREVIOUS=2;SC.PaneView=SC.View.extend({pane:null,isPane:true,isModal:false,canBecomeKeyPane:true,isKeyPane:false,makeKeyPane:function()
{if(!this.get('canBecomeKeyPane'))return false;if(this.get('isKeyPane'))return false;SC.app.set('keyPane',this);return true;},didBecomeKeyPane:function(){},willResignKeyPane:function(){},canBecomeMainPane:true,isMainPane:false,makeMainPane:function()
{if(!this.get('canBecomeMainPane'))return false;if(this.get('isMainPane'))return false;SC.app.set('mainPane',this);return true;},didBecomeMainPane:function(){},willResignMainPane:function(){},performKeyInterfaceControl:function(keystring,evt)
{return false;},keyViewSelectionDirection:SC.KEYVIEW_SELECTING_NONE,selectPreviousKeyView:function(){},selectNextKeyView:function(){},autorecalculatesKeyViewLoop:false,recalculateKeyViewLoop:function(){},nextResponder:null,_firstResponder:null,firstResponder:function(key,value)
{if(value!==undefined){if(this._firstResponder){this._firstResponder.willLoseFirstResponder();}
if(this._firstResponder){this._firstResponder.set('isFirstResponder',false);}
this._firstResponder=value;if(this._firstResponder){this._firstResponder.set('isFirstResponder',true);}
if(this._firstResponder){this._firstResponder.didBecomeFirstResponder();}}
return this._firstResponder;}.property(),defaultResponder:null});require('views/view');SC.ContainerView=SC.View.extend({content:null,contentBindingDefault:SC.Binding.Single,rootView:null,replaceContent:function(newContent){var containerView=this.get('rootView')||this;containerView.clear();var newView=newContent;if(newView){newView.viewFrameWillChange();containerView.appendChild(newView);newView.viewFrameDidChange();}},_contentObserver:function(){this.replaceContent(this.get('content'));}.observes('content')});require('panes/pane');require('views/container');SC.OverlayPaneView=SC.PaneView.extend({content:null,layer:0,anchorView:null,triggerEvent:null,isModal:true,positionPane:function(){},fitPositionToScreen:function(preferredPosition,paneView,anchor){var f=paneView.get('frame');f.x=preferredPosition.x;f.y=preferredPosition.y;f=paneView.convertFrameToView(f,null);var aframe=anchor.convertFrameToView(anchor.get('frame'),null);var wframe=SC.window.get('frame');if(SC.maxX(f)>wframe.width){var mx=Math.max(SC.maxX(aframe),f.width);f.x=Math.min(mx,wframe.width)-f.width;}
if(SC.minX(f)<0){f.x=SC.minX(Math.max(aframe,0));if(SC.maxX(f)>wframe.width){f.x=Math.max(0,wframe.width-f.width);}}
if(SC.maxY(f)>wframe.height){var mx=Math.max((aframe.y-f.height),0);if(mx>wframe.height){f.y=Math.max(0,wframe.height-f.height);}else f.y=mx;}
if(SC.minY(f)<0){var mx=Math.min(SC.maxY(aframe),(wframe.height-aframe.height));f.y=Math.max(mx,0);}
return f;},resizeWithOldParentSize:function(oldSize){this.positionPane();},acceptsFirstResponder:true,keyDown:function(evt){if(!this.interpretKeyEvents(evt)){return arguments.callee.base.apply(this,arguments);}},insertNewline:function(sender,evt){var button=this._findViewWithKeyIn('isDefault',SC.ButtonView,this);if(button){button.triggerAction(evt);return true;}else return false;},cancel:function(sender,evt){var button=this._findViewWithKeyIn('isCancel',SC.ButtonView,this);if(button){button.triggerAction(evt);return true;}else return false;},_findViewWithKeyIn:function(keyName,rootClass,rootView,ignoreRoot){if(!ignoreRoot){if((rootView instanceof rootClass)&&rootView.get(keyName)){return rootView;}}
var child=rootView.get('firstChild');while(child){var ret=this._findViewWithKeyIn(keyName,rootClass,child);if(ret)return ret;child=child.get('nextSibling');}
return null;},focusFirstKeyView:function(){var fr=this._findViewWithKeyIn('acceptsFirstResponder',SC.Responder,this,true);if(!fr)fr=this;fr.becomeFirstResponder();},click:function(evt){if(!this.get('isModal')){var content=this.containerView.get('content');if(content)content.set('isVisible',false);}
return true;},_contentDidChange:function(){var containerView=this.get('containerView');if(containerView)containerView.set('content',this.get('content'));}.observes('content'),outlets:['containerView'],containerView:SC.ContainerView.extend({outlets:['rootView'],rootView:SC.View.extend({click:function(){return true;}}).outletFor('.pane-root?'),_fixWidth:function(){var content=this.get('content');if(content){content.resizeWithOldParentSize(this.get('size'));var padding=0;this.getEach('styleBorderLeftWidth','styleBorderRightWidth','stylePaddingLeft','stylePaddingRight').each(function(x){padding+=x||0;});this.recacheFrames();content.recacheFrames();this.set('size',{width:(content.get('size').width+padding)});this.owner.positionPane();this.owner.setStyle({visibility:'visible'});}
if(this.get('isVisibleInWindow'))
{this.owner.focusFirstKeyView();}}.observes('content'),init:function(){arguments.callee.base.apply(this,arguments);if(SC.isSafari()){this.visibleAnimation={visible:'opacity: 1.0',hidden:'opacity: 0.0',duration:100};}},click:function(evt){return false;}}).outletFor('.pane-wrapper?'),show:function(){this.containerView._fixWidth();arguments.callee.base.apply(this,arguments);}});require('foundation/object');SC.Validator=SC.Object.extend({fieldValueForObject:function(object,form,view){return object;},objectForFieldValue:function(value,form,view){return value;},validate:function(form,field){return true;},validateError:function(form,field){return $error("Invalid.General(%@)".loc(field.get('fieldValue')),field.get('fieldKey'));},validateChange:function(form,field,oldValue){return(this.validate(form,field))?SC.Validator.OK:this.validateError(form,field);},validateSubmit:function(form,field){return(this.validate(form,field))?SC.Validator.OK:this.validateError(form,field);},validatePartial:function(form,field){if(!field.get('isValid')){return(this.validate(form,field))?SC.Validator.OK:this.validateError(form,field);}else return SC.Validator.NO_CHANGE;},validateKeypress:function(form,field,charStr){return true;},attachTo:function(form,field){},detachFrom:function(form,field){}});SC.Validator.mixin({OK:true,NO_CHANGE:false,findFor:function(form,field,validatorKey){var validator;if(!validatorKey)return;if(validatorKey instanceof SC.Validator){validator=validatorKey;}else if(validatorKey.isClass){validator=validatorKey.create();}else if($type(validatorKey)==T_STRING){var name=null;var m=validatorKey.match(/^(.+)\[(.*)\]/);if(m){validatorKey=m[1];name=m[2];}
validatorKey=('-'+validatorKey).camelize();var validatorClass=SC.Validator[validatorKey];if(validatorClass==null){throw"validator %@ not found for %@".fmt(validatorKey,field);return null;}else if(name){if(!form){throw"named validator (%@) could not be found for field %@ because the field does not belong to a form".fmt(name,field);return null;}
if(!form._validatorHash)form._validatorHash={};var validator=(name)?form._validatorHash[name]:null;if(!validator)validator=validatorClass.create();if(name)form._validatorHash[name]=validator;}else validator=validatorClass.create();}
return validator;},fieldValueForObject:function(object,form,field){return this.prototype.fieldValueForObject(object,form,field);},objectForFieldValue:function(value,form,field){return this.prototype.objectForFieldValue(value,form,field);}});require('validators/validator');SC.Validator.CreditCard=SC.Validator.extend({fieldValueForObject:function(object,form,field){if(typeof(object)=="string"&&object.length==16){object=[object.slice(0,4),object.slice(4,8),object.slice(8,12),object.slice(12,16)].join(' ');}
return object;},objectForFieldValue:function(value,form,field){return value.replace(/[\s-\.\:]/g,'');},validate:function(form,field){return this.checkNumber(field.get('fieldValue'));},validateError:function(form,field){var label=field.get('errorLabel')||'Field';return $error("Invalid.CreditCard(%@)".loc(label),label);},checkNumber:function(ccNumb){var valid="0123456789";var len=ccNumb.length;var iCCN=parseInt(ccNumb,0);var sCCN=ccNumb.toString();sCCN=sCCN.replace(/^\s+|\s+$/g,'');var iTotal=0;var bNum=true;var bResult=false;var temp;var calc;for(var j=0;j<len;j++){temp=""+sCCN.substring(j,j+1);if(valid.indexOf(temp)=="-1"){bNum=false;}}
if(!bNum)bResult=false;if((len==0)&&(bResult)){bResult=false;}else{if(len>=15){for(var i=len;i>0;i--){calc=parseInt(iCCN,0)%10;calc=parseInt(calc,0);iTotal+=calc;i--;iCCN=iCCN/10;calc=parseInt(iCCN,0)%10;calc=calc*2;switch(calc){case 10:calc=1;break;case 12:calc=3;break;case 14:calc=5;break;case 16:calc=7;break;case 18:calc=9;break;default:calc=calc;}
iCCN=iCCN/10;iTotal+=calc;}
if((iTotal%10)==0){bResult=true;}else{bResult=false;}}}
return bResult;}});require('foundation/object');SC.Error=SC.Object.extend({code:-1,description:'',label:null});SC.Error.desc=function(description,label,code){var opts={description:description};if(label!==undefined)opts.label=label;if(code!==undefined)opts.code=code;return this.create(opts);};SC.$error=function(description,label,c){return SC.Error.desc(description,label,c);};var $error=SC.$error;SC.$ok=function(ret){return(ret!==false)&&($type(ret)!=T_ERROR);};var $ok=SC.$ok;SC.Error.HAS_MULTIPLE_VALUES=-100;require('core');require('views/view');SC.DRAG_LINK=0x0004;SC.DRAG_COPY=0x0001;SC.DRAG_MOVE=0x0002;SC.DRAG_NONE=0x0000;SC.DRAG_ANY=0x0007;SC.DRAG_AUTOSCROLL_ZONE_THICKNESS=20;SC.Drag=SC.Object.extend({source:null,ghostView:null,dragView:null,ghost:YES,slideBack:YES,mouseDownEvent:null,ghostOffset:{x:0,y:0},location:null,dataTypes:function(){if(this.dataSource)return this.dataSource.get('dragDataTypes');if(this.data){var ret=[];for(var key in this._data){if(this.data.hasOwnProperty(key))ret.push(key);}
return ret;}
var source=this.get('source');if(source&&source.dragDataTypes)return source.get('dragDataTypes');return[];}.property(),hasDataType:function(dataType){var dataTypes=this.get('dataTypes')||[];return(dataTypes.indexOf(dataType)>=0);},dataForType:function(dataType){if(this.dataSource){return this.dataSource.dragDataForType(dataType,this);}else if(this.data){return this.data[dataType];}else{var source=this.get('source');if(source&&$type(source.dragDataForType)==T_FUNCTION){return source.dragDataForType(dataType,this);}else return null;}},dataSource:null,data:null,_dragInProgress:YES,startDrag:function(){this._createGhostView();var origin=this.dragView.convertFrameToView(this.dragView.get('frame'),null);var pointer=Event.pointerLocation(this.event);window.dragEvent=this.event;this.ghostOffset={x:(pointer.x-origin.x),y:(pointer.y-origin.y)};this._positionGhostView(this.event);SC.window.dragDidStart(this);if(this.source&&this.source.dragDidBegin){this.source.dragDidBegin(this,pointer);}},_lastLoc:{},mouseDragged:function(evt){var loc=Event.pointerLocation(evt);var scrolled=this._autoscroll(evt);if(!scrolled&&(loc.x==this._lastLoc.x)&&(loc.y==this._lastLoc.y))return;this._lastLoc=loc;this.set('location',loc);this._positionGhostView(evt);var last=this._lastTarget;var target=this._findDropTarget(evt);var op=SC.DRAG_NONE;while(target&&(target!=last)&&(op==SC.DRAG_NONE)){if(target&&this.source&&this.source.dragSourceOperationMaskFor){op=this.source.dragSourceOperationMaskFor(target,this);}else op=SC.DRAG_ANY;if((op!=SC.DRAG_NONE)&&target&&target.dragEntered){op=op&target.dragEntered(this,evt);}else op=SC.DRAG_NONE;if(op==SC.DRAG_NONE)target=this._findNextDropTarget(target);}
if(target!=last){if(last&&last.dragExited)last.dragExited(this,evt);if(target&&this.source&&this.source.dragSourceOperationMaskFor){op=this.source.dragSourceOperationMaskFor(target,this);}else op=SC.DRAG_ANY;this.sourceDropOperations=op;if(target&&target.dragEntered){this.dropOperations=op&target.dragEntered(this,evt);}else this.dropOperations=SC.DRAG_NONE;if(this.dropOperations==SC.DRAG_NONE)target=null;}else{if(target&&target.dragUpdated)target.dragUpdated(this,evt);}
if(this.source&&this.source.dragDidMove){this.source.dragDidMove(this,loc);}
this._lastTarget=target;},mouseUp:function(evt){var loc=Event.pointerLocation(evt);var target=this._lastTarget;var op=this.dropOperations;if(target&&target.prepareForDragOperation(op,this)){op=target.performDragOperation(op,this);}else{op=SC.DRAG_NONE;}
var drag=this;var cleanupFunc=function(){if(target)target.concludeDragOperation(op,this);drag._destroyGhostView();};if(target&&target.dragEnded)target.dragEnded(this,evt);this._lastTarget=null;if((op==SC.DRAG_NONE)&&this.get('slideBack')){var loc=this.dragView.convertFrameToView(this.dragView.get('origin'),null);this._ghostView.transitionTo(1.0,"left: %@px; top: %@px".fmt(loc.x,loc.y),{duration:200,onComplete:cleanupFunc});}else cleanupFunc();if(this.source&&this.source.dragDidEnd){this.source.dragDidEnd(this,loc,op);}
this._dragInProgress=NO;},_ghostViewClass:SC.View.extend({emptyElement:'<div class="sc-ghost-view"></div>'}),_positionGhostView:function(evt){var loc=Event.pointerLocation(evt);loc.x-=this.ghostOffset.x;loc.y-=this.ghostOffset.y;loc=this._ghostView.convertFrameFromView(loc,null);this._ghostView.set('origin',loc);},_createGhostView:function(){var el=this.dragView.rootElement.cloneNode(true);this._ghostView=this._ghostViewClass.viewFor(el);this._ghostView.owner=this;this._ghostView.addClassName('sc-ghost-view');SC.window.appendChild(this._ghostView);},_destroyGhostView:function(){if(this._ghostView){this._ghostView.removeFromParent();this._ghostView=null;}},_ghostView:null,_getOrderedDropTargets:function(){if(this._cachedDropTargets)return this._cachedDropTargets;var ret=[];var dt=SC.Drag._dropTargets;for(var key in dt){if(!dt.hasOwnProperty(key))continue;ret.push(dt[key]);}
var depth={};var getDepthFor=function(x){if(!x)return 0;var guid=SC.guidFor(x);var ret=depth[guid];if(!ret){ret=1;while((x=x.parentNode)&&(x!==SC.window)){if(dt[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 dt=this._getOrderedDropTargets();var loc=Event.pointerLocation(evt);var ret=null;for(var idx=0;idx<dt.length;idx++){var t=dt[idx];if(!t.get('isVisibleInWindow'))continue;var f=t.convertFrameToView(t.get('clippingFrame'),null);if(SC.pointInRect(loc,f))return t;}
return null;},_findNextDropTarget:function(target){while((target=target.parentNode)&&(target!=SC.window)){if(SC.Drag._dropTargets[target._guid])return target;}
return null;},_autoscroll:function(evt){if(!this._dragInProgress)return;var loc=(evt)?Event.pointerLocation(evt):this._lastMouseLocation;if(!loc)return false;this._lastMouseLocation=loc;var view=this._findScrollableView(loc);var verticalScroll,horizontalScroll;var min,max,edge;var scrollableView=null;while(view&&!scrollableView){verticalScroll=view.get('hasVerticalScroller')?1:0;horizontalScroll=view.get('hasHorizontalScroller')?1:0;if((verticalScroll!=0)||(horizontalScroll!=0)){var f=view.convertFrameToView(view.get('frame'),null);var innerSize=view.get('innerFrame');var scrollFrame=view.get('scrollFrame');}
if(verticalScroll!=0){max=SC.maxY(f);min=max-SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;edge=SC.maxY(scrollFrame);if((edge>=innerSize.height)&&(loc.y>=min)&&(loc.y<=max)){verticalScroll=1;}else{min=SC.minY(f);max=min+SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;edge=SC.minY(scrollFrame);if((edge<=innerSize.height)&&(loc.y>=min)&&(loc.y<=max)){verticalScroll=-1;}else verticalScroll=0;}}
if(horizontalScroll!=0){max=SC.maxX(f);min=max-SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;edge=SC.maxX(scrollFrame);if((edge>=innerSize.width)&&(loc.x>=min)&&(loc.x<=max)){horizontalScroll=1;}else{min=SC.minY(f);max=min+SC.DRAG_AUTOSCROLL_ZONE_THICKNESS;edge=SC.minY(scrollFrame);if((edge<=innerSize.width)&&(loc.x>=min)&&(loc.x<=max)){horizontalScroll=-1;}else horizontalScroll=0;}}
if((verticalScroll!=0)||(horizontalScroll!=0)){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;horizontalScroll=verticalScroll=0;}
if(scrollableView&&((horizontalScroll!=0)||(verticalScroll!=0))){var scroll={x:horizontalScroll*this._horizontalScrollAmount,y:verticalScroll*this._verticalScrollAmount};scrollableView.scrollBy(scroll);}
if(scrollableView){this.invokeLater('_autoscroll',100,null);return true;}else return false;},_scrollableViews:function(){if(this._cachedScrollableView)return this._cachedScrollableView;var ret=[];var dt=SC.Drag._scrollableViews;for(var key in dt){if(!dt.hasOwnProperty(key))continue;ret.push(dt[key]);}
ret=ret.sort(function(a,b){var view=a;while((view=view.parentNode)&&(view!=SC.window)){if(b==view)return-1;}
return 1;});this._cachedScrollableView=ret;return ret;},_findScrollableView:function(loc){var dt=this._scrollableViews();var ret=null;for(var idx=0;idx<dt.length;idx++){var t=dt[idx];if(!t.get('isVisibleInWindow'))continue;var f=t.convertFrameToView(t.get('frame'),null);if(SC.pointInRect(loc,f))return t;}
return null;},_findNextScrollableView:function(view){while((view=view.parentNode)&&(view!=SC.window)){if(SC.Drag._scrollableViews[view._guid])return view;}
return null;}});SC.Drag.mixin({start:function(ops){var ret=this.create(ops);ret.startDrag();return ret;},_dropTargets:{},_scrollableViews:{},addScrollableView:function(target){this._scrollableViews[target._guid]=target;},removeScrollableView:function(target){delete this._scrollableViews[target._guid];},addDropTarget:function(target){this._dropTargets[target._guid]=target;},removeDropTarget:function(target){delete this._dropTargets[target._guid];},inspectOperation:function(op){var ret=[];if(op===SC.DRAG_NONE){ret=['DRAG_NONE'];}else if(op===SC.DRAG_ANY){ret=['DRAG_ANY'];}else{if(op&SC.DRAG_LINK){ret.push('DRAG_LINK');}
if(op&SC.DRAG_COPY){ret.push('DRAG_COPY');}
if(op&SC.DRAG_MOVE){ret.push('DRAG_MOVE');}}
return ret.join('|');}});require('drag/drag');SC.DragDataSource={dragDataTypes:[],dragDataForType:function(dataType,drag){return null;}};Event.simulateMouse=function(element,eventName){var options=Object.extend({pointerX:0,pointerY:0,buttons:0,ctrlKey:false,altKey:false,shiftKey:false,metaKey:false},arguments[2]||{});var oEvent=document.createEvent("MouseEvents");oEvent.initMouseEvent(eventName,true,true,document.defaultView,options.buttons,options.pointerX,options.pointerY,options.pointerX,options.pointerY,options.ctrlKey,options.altKey,options.shiftKey,options.metaKey,0,$(element));if(this.mark)Element.remove(this.mark);this.mark=document.createElement('div');this.mark.appendChild(document.createTextNode(" "));document.body.appendChild(this.mark);this.mark.style.position='absolute';this.mark.style.top=options.pointerY+"px";this.mark.style.left=options.pointerX+"px";this.mark.style.width="5px";this.mark.style.height="5px;";this.mark.style.borderTop="1px solid red;";this.mark.style.borderLeft="1px solid red;";if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));$(element).dispatchEvent(oEvent);};Event.simulateKey=function(element,eventName){var options=Object.extend({ctrlKey:false,altKey:false,shiftKey:false,metaKey:false,keyCode:0,charCode:0},arguments[2]||{});var oEvent=document.createEvent("KeyEvents");oEvent.initKeyEvent(eventName,true,true,window,options.ctrlKey,options.altKey,options.shiftKey,options.metaKey,options.keyCode,options.charCode);$(element).dispatchEvent(oEvent);};Event.simulateKeys=function(element,command){for(var i=0;i<command.length;i++){Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});}};var Test={};Test.Unit={};Test.Unit.inspect=Object.inspect;Test.Unit.Logger=Class.create();Test.Unit.Logger.prototype={initialize:function(log){this.log=$(log);this.logId=this.log.id||'x';if(this.log){this._createLogTable();}},start:function(testName){if(!this.log)return;this.testName=testName;this.lastLogLine=document.createElement('tr');this.statusCell=document.createElement('td');this.nameCell=document.createElement('td');this.nameCell.className="nameCell";this.nameCell.appendChild(document.createTextNode(testName));this.messageCell=document.createElement('td');this.lastLogLine.appendChild(this.statusCell);this.lastLogLine.appendChild(this.nameCell);this.lastLogLine.appendChild(this.messageCell);this.loglines.appendChild(this.lastLogLine);},finish:function(status,summary){if(!this.log)return;this.lastLogLine.className=status;this.statusCell.innerHTML=status;this.messageCell.innerHTML=this._toHTML(summary);this.addLinksToResults();},message:function(message){if(!this.log)return;this.messageCell.innerHTML=this._toHTML(message);},summary:function(summary){if(!this.log)return;this.logsummary.innerHTML=this._toHTML(summary);},_createLogTable:function(){this.log.innerHTML='<div id="'+this.logId+'-logsummary" class="logsummary"></div>'+'<table id="'+this.logId+'-logtable">'+'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>'+'<tbody id="'+this.logId+'-loglines"></tbody>'+'</table>';this.logsummary=$(this.logId+'-logsummary');this.loglines=$(this.logId+'-loglines');},_toHTML:function(txt){return txt.escapeHTML().replace(/\n/g,"<br/>");},addLinksToResults:function(){$$("tr.failed .nameCell").each(function(td){td.title="Run only this test";Event.observe(td,'click',function(){window.location.search="?tests="+td.innerHTML;});});$$("tr.passed .nameCell").each(function(td){td.title="Run all tests";Event.observe(td,'click',function(){window.location.search="";});});}};document.incrementQueuedTests=function(amt){if(amt==undefined)amt=1;var cnt=document.queuedTests||0;document.queuedTests=cnt+amt;};document.setTestStatus=function(stat){var cur=document.testStatus||'SUCCESS';document.testStatus=(cur=='SUCCESS')?stat:cur;};Test.Unit.Runner=Class.create();Test.Unit.Runner.prototype={initialize:function(testcases){this.options=Object.extend({testLog:'testlog'},arguments[1]||{});this.options.resultsURL=this.parseResultsURLQueryParameter();this.options.tests=this.parseTestsQueryParameter();if(this.options.testLog){var testLogElement=$(this.options.testLog)||null;var rootLog=$('test-log');if(!rootLog){var el=document.createElement('div');el.id='test-log';$(el).addClassName('testlog');var body=document.getElementsByTagName('body')[0];body.insertBefore(el,body.firstChild);rootLog=el;}
if(rootLog){var el=document.createElement('div');el.id=this.options.testLog;rootLog.appendChild(el);testLogElement=el;}
this.options.testLog=testLogElement;}
if(this.options.tests){this.tests=[];for(var i=0;i<this.options.tests.length;i++){if(/^test/.test(this.options.tests[i])){this.tests.push(new Test.Unit.Testcase(this.options.tests[i],testcases[this.options.tests[i]],testcases["setup"],testcases["teardown"]));}}}else{if(this.options.test){this.tests=[new Test.Unit.Testcase(this.options.test,testcases[this.options.test],testcases["setup"],testcases["teardown"])];}else{this.tests=[];for(var testcase in testcases){if(/^test/.test(testcase)){this.tests.push(new Test.Unit.Testcase(this.options.context?' -> '+this.options.titles[testcase]:testcase,testcases[testcase],testcases["setup"],testcases["teardown"]));}}}}
this.currentTest=0;this.logger=new Test.Unit.Logger(this.options.testLog);document.incrementQueuedTests(1);setTimeout(this.runTests.bind(this),1000);},parseResultsURLQueryParameter:function(){return window.location.search.parseQuery()["resultsURL"];},parseTestsQueryParameter:function(){if(window.location.search.parseQuery()["tests"]){return window.location.search.parseQuery()["tests"].split(',');};},getResult:function(){var hasFailure=false;for(var i=0;i<this.tests.length;i++){if(this.tests[i].errors>0){return"ERROR";}
if(this.tests[i].failures>0){hasFailure=true;}}
if(hasFailure){return"FAILURE";}else{return"SUCCESS";}},postResults:function(){if(this.options.resultsURL){new Ajax.Request(this.options.resultsURL,{method:'get',parameters:'result='+this.getResult(),asynchronous:false});}},runTests:function(){var test=this.tests[this.currentTest];if(!test){this.postResults();this.logger.summary(this.summary());document.incrementQueuedTests(-1);document.setTestStatus(this.getResult());return;}
if(!test.isWaiting){this.logger.start(test.name);}
test.run();if(test.isWaiting){this.logger.message("Waiting for "+test.timeToWait+"ms");setTimeout(this.runTests.bind(this),test.timeToWait||1000);}else{this.logger.finish(test.status(),test.summary());this.currentTest++;this.runTests();}},summary:function(){var assertions=0;var failures=0;var errors=0;var messages=[];for(var i=0;i<this.tests.length;i++){assertions+=this.tests[i].assertions;failures+=this.tests[i].failures;errors+=this.tests[i].errors;}
return((this.options.context?this.options.context+': ':'')+
this.tests.length+" tests, "+
assertions+" assertions, "+
failures+" failures, "+
errors+" errors");}};Test.Unit.Assertions=Class.create();Test.Unit.Assertions.prototype={initialize:function(){this.assertions=0;this.failures=0;this.errors=0;this.messages=[];},summary:function(){return(this.assertions+" assertions, "+
this.failures+" failures, "+
this.errors+" errors"+"\n"+
this.messages.join("\n"));},pass:function(){this.assertions++;},fail:function(message){this.failures++;this.messages.push("Failure: "+message);},info:function(message){this.messages.push("Info: "+message);},error:function(error){this.errors++;this.messages.push(error.name+": "+error.message+"("+Test.Unit.inspect(error)+")");},status:function(){if(this.failures>0)return'failed';if(this.errors>0)return'error';return'passed';},assert:function(expression){var message=arguments[1]||'assert: got "'+Test.Unit.inspect(expression)+'"';try{expression?this.pass():this.fail(message);}
catch(e){this.error(e);}},assertEqual:function(expected,actual){var message=arguments[2]||"assertEqual";try{(expected==actual)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertInspect:function(expected,actual){var message=arguments[2]||"assertInspect";try{(expected==actual.inspect())?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertEnumEqual:function(expected,actual){var message=arguments[2]||"assertEnumEqual";try{$A(expected).length==$A(actual).length&&expected.zip(actual).all(function(pair){return pair[0]==pair[1];})?this.pass():this.fail(message+': expected '+Test.Unit.inspect(expected)+', actual '+Test.Unit.inspect(actual));}
catch(e){this.error(e);}},assertNotEqual:function(expected,actual){var message=arguments[2]||"assertNotEqual";try{(expected!=actual)?this.pass():this.fail(message+': got "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertIdentical:function(expected,actual){var message=arguments[2]||"assertIdentical";try{(expected===actual)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertNotIdentical:function(expected,actual){var message=arguments[2]||"assertNotIdentical";try{!(expected===actual)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+'", actual "'+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertNull:function(obj){var message=arguments[1]||'assertNull';try{(obj==null)?this.pass():this.fail(message+': got "'+Test.Unit.inspect(obj)+'"');}
catch(e){this.error(e);}},assertMatch:function(expected,actual){var message=arguments[2]||'assertMatch';var regex=new RegExp(expected);try{(regex.exec(actual))?this.pass():this.fail(message+' : regex: "'+Test.Unit.inspect(expected)+' did not match: '+Test.Unit.inspect(actual)+'"');}
catch(e){this.error(e);}},assertHidden:function(element){var message=arguments[1]||'assertHidden';this.assertEqual("none",element.style.display,message);},assertNotNull:function(object){var message=arguments[1]||'assertNotNull';this.assert(object!=null,message);},assertType:function(expected,actual){var message=arguments[2]||'assertType';try{(actual.constructor==expected)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+'", actual "'+(actual.constructor)+'"');}
catch(e){this.error(e);}},assertNotOfType:function(expected,actual){var message=arguments[2]||'assertNotOfType';try{(actual.constructor!=expected)?this.pass():this.fail(message+': expected "'+Test.Unit.inspect(expected)+'", actual "'+(actual.constructor)+'"');}
catch(e){this.error(e);}},assertInstanceOf:function(expected,actual){var message=arguments[2]||'assertInstanceOf';try{(actual instanceof expected)?this.pass():this.fail(message+": object was not an instance of the expected type");}
catch(e){this.error(e);}},assertNotInstanceOf:function(expected,actual){var message=arguments[2]||'assertNotInstanceOf';try{!(actual instanceof expected)?this.pass():this.fail(message+": object was an instance of the not expected type");}
catch(e){this.error(e);}},assertRespondsTo:function(method,obj){var message=arguments[2]||'assertRespondsTo';try{(obj[method]&&typeof obj[method]=='function')?this.pass():this.fail(message+": object doesn't respond to ["+method+"]");}
catch(e){this.error(e);}},assertReturnsTrue:function(method,obj){var message=arguments[2]||'assertReturnsTrue';try{var m=obj[method];if(!m)m=obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];m()?this.pass():this.fail(message+": method returned false");}
catch(e){this.error(e);}},assertReturnsFalse:function(method,obj){var message=arguments[2]||'assertReturnsFalse';try{var m=obj[method];if(!m)m=obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];!m()?this.pass():this.fail(message+": method returned true");}
catch(e){this.error(e);}},assertRaise:function(exceptionName,method){var message=arguments[2]||'assertRaise';try{method();this.fail(message+": exception expected but none was raised");}
catch(e){((exceptionName==null)||(e.name==exceptionName))?this.pass():this.error(e);}},assertElementsMatch:function(){var expressions=$A(arguments),elements=$A(expressions.shift());if(elements.length!=expressions.length){this.fail('assertElementsMatch: size mismatch: '+elements.length+' elements, '+expressions.length+' expressions');return false;}
elements.zip(expressions).all(function(pair,index){var element=$(pair.first()),expression=pair.last();if(element.match(expression))return true;this.fail('assertElementsMatch: (in index '+index+') expected '+expression.inspect()+' but got '+element.inspect());}.bind(this))&&this.pass();},assertElementMatches:function(element,expression){this.assertElementsMatch([element],expression);},benchmark:function(operation,iterations){var startAt=new Date();(iterations||1).times(operation);var timeTaken=((new Date())-startAt);this.info((arguments[2]||'Operation')+' finished '+
iterations+' iterations in '+(timeTaken/1000)+'s');return timeTaken;},_isVisible:function(element){element=$(element);if(!element.parentNode)return true;this.assertNotNull(element);if(element.style&&Element.getStyle(element,'display')=='none')
return false;return this._isVisible(element.parentNode);},assertNotVisible:function(element){this.assert(!this._isVisible(element),Test.Unit.inspect(element)+" was not hidden and didn't have a hidden parent either. "+(""||arguments[1]));},assertVisible:function(element){this.assert(this._isVisible(element),Test.Unit.inspect(element)+" was not visible. "+(""||arguments[1]));},benchmark:function(operation,iterations){var startAt=new Date();(iterations||1).times(operation);var timeTaken=((new Date())-startAt);this.info((arguments[2]||'Operation')+' finished '+
iterations+' iterations in '+(timeTaken/1000)+'s');return timeTaken;}};Test.Unit.Testcase=Class.create();Object.extend(Object.extend(Test.Unit.Testcase.prototype,Test.Unit.Assertions.prototype),{initialize:function(name,test,setup,teardown){Test.Unit.Assertions.prototype.initialize.bind(this)();this.name=name;if(typeof test=='string'){test=test.gsub(/(\.should[^\(]+\()/,'#{0}this,');test=test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');this.test=function(){eval("with(this){\n"+test+"\n}");};}else{this.test=test||function(){};}
this.setup=setup||function(){};this.teardown=teardown||function(){};this.isWaiting=false;this.timeToWait=1000;},wait:function(time,nextPart){this.isWaiting=true;this.test=nextPart;this.timeToWait=time;},run:function(){if(!this.isWaiting)this.setup.bind(this)();this.isWaiting=false;this.test.bind(this)();if(!this.isWaiting){this.teardown.bind(this)();}}});Test.setupBDDExtensionMethods=function(){var METHODMAP={shouldEqual:'assertEqual',shouldNotEqual:'assertNotEqual',shouldEqualEnum:'assertEnumEqual',shouldBeA:'assertType',shouldNotBeA:'assertNotOfType',shouldBeAn:'assertType',shouldNotBeAn:'assertNotOfType',shouldBeNull:'assertNull',shouldNotBeNull:'assertNotNull',shouldBe:'assertReturnsTrue',shouldNotBe:'assertReturnsFalse',shouldRespondTo:'assertRespondsTo'};var makeAssertion=function(assertion,args,object){this[assertion].apply(this,(args||[]).concat([object]));};Test.BDDMethods={};$H(METHODMAP).each(function(pair){Test.BDDMethods[pair.key]=function(){var args=$A(arguments);var scope=args.shift();makeAssertion.apply(scope,[pair.value,args,this]);};});[Array.prototype,String.prototype,Number.prototype,Boolean.prototype].each(function(p){Object.extend(p,Test.BDDMethods);});};Test.context=function(name,spec,log){Test.setupBDDExtensionMethods();var compiledSpec={};var titles={};for(specName in spec){switch(specName){case"setup":case"teardown":compiledSpec[specName]=spec[specName];break;default:var testName='test'+specName.gsub(/\s+/,'-').camelize();var body=spec[specName].toString().split('\n').slice(1);if(/^\s*\{/.test(body[0]))body=body.slice(1);body.pop();body=body.map(function(statement){return statement.strip();});compiledSpec[testName]=body.join('\n');titles[testName]=specName;}}
if(log===undefined)log=name.dasherize();new Test.Unit.Runner(compiledSpec,{titles:titles,testLog:(log||'testlog'),context:name});};Test.Observer=function()
{return function(){if(!arguments.callee.notified)arguments.callee.notified=0;return++arguments.callee.notified;};};require('drag/drag');SC.DragSource={dragDidBegin:function(drag,atPoint){},dragDidEnd:function(drag,endPoint,operation){},dragDidMove:function(drag,newPoint){},dragSourceOperationMaskFor:function(dropTarget,drag){return SC.DRAG_NONE;},ignoreModifierKeysWhileDragging:NO};SC.MIXED_STATE='__MIXED__';SC.Control={initMixin:function(){this._contentObserver();this.isSelectedObserver();this.isEnabledObserver();this.isFocusedObserver();},isSelected:false,isSelectedBindingDefault:SC.Binding.OneWayBool,isEnabled:true,isEnabledBindingDefault:SC.Binding.OneWayBool,value:null,content:null,contentValueKey:null,contentPropertyDidChange:function(target,key){if(!!this._contentValueKey&&((key==this._contentValueKey)||(key=='*'))){var content=this.get('content');var value=(content)?content.get(this._contentValueKey):null;if(value!=this._contentValue){this._contentValue=value;this.set('value',value);}}},updateContentWithValueObserver:function(){if(!this._contentValueKey)return;var value=this.get('value');if(value==this._contentValue)return;var content=this.get('content');if(!content)return;this._contentValue=value;content.set(this._contentValueKey,value);}.observes('value'),isSelectedObserver:function(){var sel=this.get('isSelected');this.setClassName('mixed',sel==SC.MIXED_STATE);this.setClassName('sel',sel&&(sel!=SC.MIXED_STATE));}.observes('isSelected'),isEnabledObserver:function(){var disabled=!this.get('isEnabled');this.setClassName('disabled',disabled);if(this.rootElement&&(this.rootElement.disabled!==undefined)&&(this.rootElement.disabled!=disabled)){this.rootElement.disabled=disabled;}}.observes('isEnabled'),isFocusedObserver:function(){this.setClassName('focus',!!this.get('isFirstResponder'));}.observes('isFirstResponder'),_content:null,_contentObserver:function(){var content=this.get('content');if(this._content==content)return;if(!this._boundContentPropertyDidChangeObserver){this._boundContentPropertyDidChangeObserver=this.contentPropertyDidChange.bind(this);}
var f=this._boundContentPropertyDidChangeObserver;if(this._content&&this._content.removeObserver){this._content.removeObserver('*',f);}
var del=this.displayDelegate;this._contentValueKey=this.getDelegateProperty(del,'contentValueKey');this._content=content;if(this._content&&this._content.addObserver){this._content.addObserver('*',f);}
this.contentPropertyDidChange(this._content,'*');}.observes('content')};SC.Validatable={initMixin:function(){this._validatorObserver();},validator:null,errorLabel:null,isValid:function(){return $type(this.get('value'))!=T_ERROR;}.property('value'),ownerForm:null,performValidate:function(partialChange){var ret=SC.Validator.OK;if(this._validator){var form=this.get('ownerForm');if(partialChange){ret=this._validator.validatePartial(form,this);if((ret==SC.Validator.NO_CHANGE)&&(this._validator.validateChange(form,this)==SC.Validator.OK)){ret=SC.Validator.OK;}}else ret=this._validator.validateChange(form,this);}
return ret;},performValidateSubmit:function(){return(this._validator)?this._validator.validateSubmit(this.get('ownerForm'),this):SC.Validator.OK;},validateSubmit:function(){return this.performValidateSubmit();},objectForFieldValue:function(fieldValue){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;},isValidObserver:function(){var invalid=!this.get('isValid');this.setClassName('invalid',invalid);}.observes('isValid'),_validatorObserver:function(){var form=this.get('ownerForm');var val=SC.Validator.findFor(form,this,this.get('validator'));if(val!=this._validator){if(this._validator)this._validator.detachFrom(form,this);this._validator=val;if(this._validator)this._validator.attachTo(form,this);}}.observes('validator','ownerForm')};require('views/view');require('mixins/control');require('mixins/validatable');SC.FieldView=SC.View.extend(SC.Control,SC.Validatable,{value:null,fieldKey:null,fieldLabel:null,errorLabel:function(){var ret=this.get('fieldLabel');if(ret)return ret;var fk=this.get('fieldKey');var def=(fk||'').humanize().capitalize();return"FieldKey.%@".fmt(fk).locWithDefault(def);}.property('fieldLabel','fieldKey'),fieldValue:function(key,value){if(value!==undefined)this._setFieldValue(value);return this._getFieldValue();}.property('value'),validateSubmit:function(){var ret=this.performValidateSubmit();var value=($ok(ret))?this._getFieldValue():ret;if(value!=this.get('value'))this.set('value',value);return ret;},setFieldValue:function(newValue){if(this.rootElement.value!=newValue)this.rootElement.value=newValue;},getFieldValue:function(){return this.rootElement.value;},fieldValueDidChange:function(partialChange){var ret=this.performValidate(partialChange);if(ret==SC.Validator.NO_CHANGE)return ret;var value=($ok(ret))?this._getFieldValue():ret;if(!partialChange&&$ok(ret))this._setFieldValue(value);if(value!=this.get('value'))this.set('value',value);return ret;},enableField:function(){this.rootElement.disabled=NO;},disableField:function(){this.rootElement.disabled=YES;},isEnabledObserver:function(){isEnabled=this.get('isEnabled');arguments.callee.base.apply(this,arguments);(isEnabled)?this.enableField():this.disableField();}.observes('isEnabled'),init:function(){arguments.callee.base.call(this);if(this.rootElement)this._setFieldValue(this.get('value'));},_valueObserver:function(){var value=this.get('value');var isError=$type(value)==T_ERROR;if(!isError&&(value!=this._getFieldValue())){this._setFieldValue(value);}}.observes('value'),_setFieldValue:function(newValue){return this.setFieldValue(this.fieldValueForObject(newValue));},_getFieldValue:function(){return this.objectForFieldValue(this.getFieldValue());}});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;}};require('views/field/field');require('mixins/editable');SC.TextFieldView=SC.FieldView.extend(SC.Editable,{emptyElement:'<input type="text" value="" />',hint:null,isHintShowing:false,isEditing:NO,init:function(){if(this.hint==null){this.hint=this.rootElement.getAttribute('hint');}
if(this.validator==null){this.validator=this.rootElement.getAttribute('validate');}
arguments.callee.base.call(this);var focusListener=this._fieldDidFocus.bindAsEventListener(this);Event.observe(this.rootElement,'focus',focusListener);var blurListener=this._fieldDidBlur.bindAsEventListener(this);Event.observe(this.rootElement,'blur',blurListener);this._updateFieldHint();},_fieldDidFocus:function(){if(!this._isFocused){this._isFocused=true;this.becomeFirstResponder();}},_fieldDidBlur:function(){if(this._isFocused){this._isFocused=false;this.resignFirstResponder();}},acceptsFirstResponder:function(){return this.get('isEnabled');}.property('isEnabled'),didBecomeFirstResponder:function(){if(!this._isFocused){this._isFocused=true;if(this.get('isVisibleInWindow')){this.rootElement.focus();this.invokeLater(this._selectRootElement,1);}}
this._updateFieldHint();},_selectRootElement:function(){this.rootElement.select();},willLoseFirstResponder:function(){if(this._isFocused){this._isFocused=false;this._updateFieldHint();return this.rootElement.blur();}else{this._value=this.rootElement.value;this.fieldValueDidChange();this._updateFieldHint();return true;}},_isFocused:false,_updateFieldHint:function(){var hint=this.get('hint');var showHint=!!(!this._isFocused&&((this._value==null)||this._value=='')&&(hint));this.setClassName('show-hint',showHint);this.rootElement.value=(showHint)?hint:(this._value||'');this.set('isHintShowing',showHint);},getFieldValue:function(){return this._value;},setFieldValue:function(value){if(this._value==value)return;this._value=value;this._updateFieldHint();},mouseDown:function(e)
{e._stopWhenHandled=false;return false;},keyDown:function(evt){if(this._value!=this.rootElement.value){this._value=this.rootElement.value;this.fieldValueDidChange(true);}
return this.interpretKeyEvents(evt);},keyUp:function(){if(this._value!=this.rootElement.value){this._value=this.rootElement.value;this.fieldValueDidChange(true);}},_focusOnVisible:function(){if(this.get('isVisibleInWindow')&&this._isFocused){this.rootElement.focus();if(SC.isIE()){var selector=function(){Element.select(arguments.callee.it);};selector.it=this.rootElement;setTimeout(selector,0.05);}else{this.rootElement.select.bind(this.rootElement).delay(0.05);}}}.observes('isVisibleInWindow'),deleteBackward:function(evt){evt._stopWhenHandled=false;return true;},deleteForward:function(evt){evt._stopWhenHandled=false;return true;},moveLeft:function(evt){evt._stopWhenHandled=false;return true;},moveRight:function(evt){evt._stopWhenHandled=false;return true;},moveUp:function(evt){evt._stopWhenHandled=false;return true;},moveDown:function(evt){evt._stopWhenHandled=false;return true;},moveLeftAndModifySelection:function(evt){evt._stopWhenHandled=false;return true;},moveRightAndModifySelection:function(evt){evt._stopWhenHandled=false;return true;},moveUpAndModifySelection:function(evt){evt._stopWhenHandled=false;return true;},moveDownAndModifySelection:function(evt){evt._stopWhenHandled=false;return true;},moveToBeginningOfDocument:function(evt){evt._stopWhenHandled=false;return true;},moveToEndOfDocument:function(evt){evt._stopWhenHandled=false;return true;},selectAll:function(evt){evt._stopWhenHandled=false;return true;}});require('views/field/text_field');SC.TextareaFieldView=SC.TextFieldView.extend({emptyElement:'<textarea></textarea>',didBecomeFirstResponder:function(){if(this.get('isVisibleInWindow')){this.rootElement.focus();this.invokeLater(this._selectRootElement,1);}
this._updateFieldHint();},insertNewline:function(evt){evt._stopWhenHandled=false;return true;}});SC.InlineEditorDelegate={inlineEditorClassName:"",inlineEditorWillBeginEditing:function(inlineEditor){},inlineEditorDidBeginEditing:function(inlineEditor){},inlineEditorShouldEndEditing:function(inlineEditor,finalValue){return YES;},inlineEditorDidEndEditing:function(inlineEditor,finalValue){}};require('views/view');require('mixins/delegate_support');require('views/field/text_field');require('views/field/textarea_field');require('mixins/inline_editor_delegate');SC.InlineTextFieldView=SC.View.extend(SC.DelegateSupport,SC.InlineEditorDelegate,{beginEditing:function(options){this.beginPropertyChanges();if(this.get('isEditing')&&!this.blurEditor()){this.endPropertyChanges();return NO;}
this._optframe=options.frame;this._exampleElement=options.exampleElement;this._delegate=options.delegate;if(!this._optframe||!this._delegate){throw"At least frame and delegate options are required for inline editor";}
this._originalValue=options.value||'';this._multiline=(options.multiline!==undefined)?options.multiline:NO;this._commitOnBlur=(options.commitOnBlur!==undefined)?options.commitOnBlur:YES;var field=this.outlet('field');field.set('validator',options.validator);field.set('value',this._originalValue);field.set('selectedRange',options.selectedRange||{start:this._originalValue.length,length:0});this.set('isEditing',YES);SC.app.get("keyPane").appendChild(this);this.updateViewStyle();var del=this._delegate;this._className=this.getDelegateProperty(del,"inlineEditorClassName");if(this._className&&!this.hasClassName(this._className)){this.setClassName(this._className,true);}
this.invokeDelegateMethod(del,'inlineEditorWillBeginEditing',this);this.resizeToFit(field.getFieldValue());this.endPropertyChanges();this.field.becomeFirstResponder();this.invokeDelegateMethod(del,'inlineEditorDidBeginEditing',this);},commitEditing:function(){var field=this.outlet('field');if(!$ok(field.validateSubmit()))return NO;return this._endEditing(field.get('value'));},discardEditing:function(){return this._endEditing(this._originalValue);},blurEditor:function(){if(!this.get('isEditing'))return YES;return(this._commitOnBlur)?this.commitEditing():this.discardEditing();},_endEditing:function(finalValue){if(!this.get('isEditing'))return YES;var del=this._delegate;if(!this.invokeDelegateMethod(del,'inlineEditorShouldEndEditing',this,finalValue))return NO;this.invokeDelegateMethod(del,'inlineEditorDidEndEditing',this,finalValue);if(this._className)this.setClassName(this._className,false);this._originalValue=this._delegate=this._exampleElement=this._optframe=this._className=null;this.set('isEditing',NO);if(this.field.get('isFirstResponder'))this.field.resignFirstResponder();if(this.get('parentNode'))this.removeFromParent();return YES;},isEditing:NO,emptyElement:['<div class="sc-inline-text-field-view">','<div class="sizer"></div>','<textarea class="inner-field" wrap="virtual"></textarea>','</div>'].join(''),updateViewStyle:function(){var f=this._optframe;var el=this._exampleElement;var styles={fontSize:Element.getStyle(el,'font-size'),fontFamily:Element.getStyle(el,'font-family'),fontWeight:Element.getStyle(el,'font-weight'),paddingLeft:Element.getStyle(el,'padding-left'),paddingRight:Element.getStyle(el,'padding-right'),paddingTop:Element.getStyle(el,'padding-top'),paddingBottom:Element.getStyle(el,'padding-bottom'),lineHeight:Element.getStyle(el,'line-height'),textAlign:Element.getStyle(el,'text-align')};var field=this.outlet('field');var sizer=this.outlet('sizer');field.setStyle(styles);styles.opacity=0;sizer.setStyle(styles);sizer.recacheFrames();this.set('frame',f);},resizeToFit:function(newValue)
{var sizer=this.outlet('sizer');var field=this.outlet('field');var text=(newValue||'').escapeHTML();text=text.replace(/  /g,"&nbsp; ").replace(/\n/g,"<br />&nbsp;");sizer.set('innerHTML',text||"&nbsp;");sizer.recacheFrames();var h=sizer.get('frame').height;this.set('frame',{height:h});},field:SC.TextareaFieldView.extend({mouseDown:function(e){arguments.callee.base.call(this,e);return this.owner.get('isEditing');},willRemoveFromParent:function(){this.get('rootElement').blur();},willLoseFirstResponder:function()
{this.get('rootElement').blur();return this.owner.blurEditor();},cancel:function(){this.owner.discardEditing();return YES;},fieldValueDidChange:function(partialChange){arguments.callee.base.call(this,partialChange);this.owner.resizeToFit(this.getFieldValue());},insertNewline:function(evt){if(this.owner._multiline){return arguments.callee.base.call(this,evt);}else{this.owner.commitEditing();return YES;}},insertTab:function(evt)
{var next=this.get("owner")._delegate.nextValidKeyView();this.owner.commitEditing();if(next)next.beginEditing();return YES;},insertBacktab:function(evt)
{var prev=this.get("owner")._delegate.previousValidKeyView();this.owner.commitEditing();if(prev)prev.beginEditing();return YES;}}).outletFor('.inner-field?'),sizer:SC.View.outletFor('.sizer?')});SC.InlineTextFieldView.mixin({beginEditing:function(options){if(!this.sharedEditor)this.sharedEditor=this.create();return this.sharedEditor.beginEditing(options);},commitEditing:function(){return(this.sharedEditor)?this.sharedEditor.commitEditing():YES;},discardEditing:function(){return(this.sharedEditor)?this.sharedEditor.discardEditing():YES;},sharedEditor:null});require('views/view');require('mixins/control');require('mixins/delegate_support');require('views/inline_text_field');require('mixins/inline_editor_delegate');SC.LabelView=SC.View.extend(SC.DelegateSupport,SC.Control,SC.InlineEditorDelegate,{emptyElement:'<span class="sc-label-view"></span>',escapeHTML:true,localize:false,formatter:null,value:'',displayValue:function(){var value=this.get('value');var formatter=this.getDelegateProperty(this.displayDelegate,'formatter');if(formatter){var formattedValue=($type(formatter)==T_FUNCTION)?formatter(value,this):formatter.fieldValueForObject(value,this);if(formattedValue!=null)value=formattedValue;}
if($type(value)==T_ARRAY){var ary=[];for(var idx=0;idx<value.get('length');idx++){var x=value.objectAt(idx);if(x!=null&&x.toString)x=x.toString();ary.push(x);}
value=ary.join(',');}
if(value!=null&&value.toString)value=value.toString();if(value&&this.getDelegateProperty(this.displayDelegate,'localize'))value=value.loc();return value;}.property('value'),isEditable:NO,isEditing:NO,localize:false,validator:null,doubleClick:function(evt){return this.beginEditing();},beginEditing:function()
{if(this.get('isEditing'))return YES;if(!this.get('isEditable'))return NO;var value=this.get('value')||'';var f=this.convertFrameToView(this.get('frame'),null);var el=this.rootElement;SC.InlineTextFieldView.beginEditing({frame:f,delegate:this,exampleElement:el,value:value,multiline:NO,validator:this.get('validator')});},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.getStyle('opacity');this.setStyle({opacity:0.0});},inlineEditorShouldEndEditing:function(inlineEditor,finalValue){return YES;},inlineEditorDidEndEditing:function(inlineEditor,finalValue){this.setIfChanged('value',finalValue);this.setStyle({opacity:this._oldOpacity});this._oldOpacity=null;this.set('isEditing',NO);},_valueDidChange:function(){var value=this.get('value');if(value===this._value)return;this._value=value;value=this.get('displayValue');if(this.getDelegateProperty(this.displayDelegate,'escapeHTML')){this.set('innerText',value||'');}else this.set('innerHTML',value||'');}.observes('value')});SC.DROP_ON=0x01;SC.DROP_BEFORE=0x02;SC.DROP_ANY=0x03;SC.CollectionViewDelegate={collectionViewSelectionForProposedSelection:function(view,sel){return sel;},collectionViewShouldBeginDrag:function(view){return YES;},collectionViewDragDataTypes:function(view){return[];},collectionViewDragDataForType:function(view,dataType,drag){return null;},collectionViewValidateDrop:function(view,drag,dropOperation,proposedInsertionIndex,proposedDragOperation){return proposedDragOperation;},collectionViewAcceptDrop:function(view,drag,dropOperation,proposedInsertionIndex,dragOperation){return SC.DRAG_NONE;},collectionViewShouldDeleteContent:function(view,items){return items;},collectionViewDeleteContent:function(view,items){return NO;}};require('views/view');require('views/label');require('mixins/collection_view_delegate');SC.BENCHMARK_UPDATE_CHILDREN=NO;SC.VALIDATE_COLLECTION_CONSISTANCY=NO;SC.DRAG_REORDER=0xfff0001;SC.HORIZONTAL_ORIENTATION='horizontal';SC.VERTICAL_ORIENTATION='vertical';SC.ZOMBIE_GROUPS_ENABLED=YES;SC.REMOVE_COLLECTION_ROOT_ELEMENT_DURING_RENDER=NO;SC.CollectionView=SC.View.extend(SC.CollectionViewDelegate,{content:[],contentBindingDefault:SC.Binding.MultipleNotEmpty,selection:[],selectionBindingDefault:SC.Binding.Multiple,delegate:null,isSelectable:true,isSelectableBindingDefault:SC.Binding.Bool,isEnabled:true,isEnabledBindingDefault:SC.Binding.Bool,isEditable:true,isEditableBindingDefault:SC.Binding.Bool,canReorderContent:false,canReorderContentBindingDefault:SC.Binding.Bool,canDeleteContent:NO,canDeleteContentBindingDefault:SC.Binding.Bool,isDropTarget:NO,useToggleSelection:NO,actOnSelect:false,selectOnMouseDown:true,groupBy:null,exampleView:SC.View,exampleGroupView:SC.View.extend({emptyElement:'<div><h1></h1><div class="well"></div></div>',outlets:['labelView','itemView'],labelView:SC.LabelView.outletFor('h1?'),itemView:SC.View.outletFor('.well?')}),action:null,target:null,isDirty:false,maxRenderTime:0,contentValueKey:null,acceptsFirstResponder:false,itemsPerRow:1,itemViews:function(){if(!this._itemViews){var range=this.get('nowShowingRange');var content=this.get('content')||[];this._itemViews=[];for(var idx=0;idx<range.length;idx++){var cur=content.objectAt(idx);this._itemViews.push(this.itemViewForContent(cur));}}
return this._itemViews;}.property(),groupViews:function(){if(!this._groupViews){var groupBy=this.get('groupBy');if(groupBy){var range=this.get('nowShowingRange');var content=this.get('content')||[];var groupValue=undefined;this._groupViews=[];for(var idx=0;idx<range.length;idx++){var cur=content.objectAt(idx);var curGroupValue=(cur)?cur.get(groupBy):null;if(curGroupValue!=groupValue){groupValue=curGroupValue;this._groupViews.push(this.groupViewForGroupValue(groupValue));}}}}
return this._groupViews;}.property(),hasItemView:function(view){if(!this._itemViewsByGuid)this._itemViewsByGuid={};return!!this._itemViewsByGuid[SC.guidFor(view)];},itemViewAtLocation:function(loc){var itemView=this._itemViewRoot;while(itemView){var frame=itemView.get('frame');if(SC.pointInRect(loc,frame))return itemView;}
return null;},itemViewForEvent:function(evt)
{var view=SC.window.firstViewForEvent(evt);do{if(view==this)return null;if(this.hasItemView(view)&&(!view.hitTest||view.hitTest(evt)))return view;}while(view=view.get('parentNode'));return null;},itemViewForContent:function(obj){var key=(obj)?SC.guidFor(obj):'0';return this._itemViewsByContent[key];},groupViewForGroupValue:function(groupValue){return this._groupViewsByValue[groupValue];},groupValueForGroupView:function(groupView){if(!groupView)return null;var ret;if(groupView.groupValue===undefined){ret=groupView.get('content');}else ret=groupView.get('groupValue');return ret;},groupRangeForContentIndex:function(contentIndex){var content=Array.from(this.get('content'));var len=content.get('length');var groupBy=this.get('groupBy');if(!groupBy)return{start:0,length:len};var min=contentIndex,max=contentIndex;var cur=content.objectAt(contentIndex);var groupValue=(cur)?cur.get(groupBy):null;while(--min>=0){var cur=content.objectAt(min);var curGroupValue=(cur)?cur.get(groupBy):null;if(curGroupValue!==groupValue)break;}
min++;while(++max<len){var cur=content.objectAt(max);var curGroupValue=(cur)?cur.get(groupBy):null;if(curGroupValue!==groupValue)break;}
return{start:min,length:max-min};},groupValueAtContentIndex:function(contentIndex){var groupBy=this.get('groupBy');var content=Array.from(this.get('content')).objectAt(contentIndex);return(groupBy&&content&&content.get)?content.get(groupBy):null;},updateChildren:function(fullUpdate){var f;if(!this.get('isVisibleInWindow')){this.set('isDirty',true);this._needsFullUpdate=this._needsFullUpdate||fullUpdate;return;}
if(SC.BENCHMARK_UPDATE_CHILDREN){var bkey='%@.updateChildren(%@)'.fmt(this,(fullUpdate)?'FULL':'FAST');SC.Benchmark.start(bkey);}
this.beginPropertyChanges();var f;if((f=this.computeFrame())&&!SC.rectsEqual(f,this.get('frame'))){var parent=this.get('parentNode');if(parent)parent.viewFrameWillChange();this.set('frame',f);if(parent)parent.viewFrameDidChange();if((f=this.computeFrame())&&!SC.rectsEqual(f,this.get('frame'))){this.set('frame',f);}}
var clippingFrame=this._lastClippingFrame=this.get('clippingFrame');if(clippingFrame.width==0&&clippingFrame.height==0){clippingFrame=this._lastClippingFrame=f;}
var range=this.contentRangeInFrame(clippingFrame);var content=Array.from(this.get('content'));range.length=Math.min(SC.maxRange(range),content.get('length'))-range.start;var nowShowingRange=this.get('nowShowingRange');fullUpdate=fullUpdate||(SC.intersectRanges(range,nowShowingRange).length<=0);this.set('nowShowingRange',range);var groupBy=this.get('groupBy');var didChange=false;if(fullUpdate){var itemViewsByContent={};var idx=SC.maxRange(range);while(--idx>=range.start){var c=content.objectAt(idx);var key=SC.guidFor(c);var itemView=this._insertItemViewFor(c,groupBy,idx);itemViewsByContent[key]=itemView;delete this._itemViewsByContent[key];}
for(var key in this._itemViewsByContent){if(!this._itemViewsByContent.hasOwnProperty(key))continue;var itemView=this._itemViewsByContent[key];this._removeItemView(itemView,groupBy);};this._itemViewsByContent=itemViewsByContent;didChange=true;}else{var start=range.start;var length=(nowShowingRange.start-start);if(length!=0){this._insertOrRemoveItemViewsInRange(start,length,groupBy);didChange=true;}
var start=SC.maxRange(nowShowingRange);var length=SC.maxRange(range)-start;if(length!=0){this._insertOrRemoveItemViewsInRange(start,length,groupBy);didChange=true;}}
this.recacheFrames();this._hasChildren=range.length>0;this.set('isDirty',false);if(didChange){this._flushZombieGroupViews();this.updateSelectionStates();this._itemViews=null;this.notifyPropertyChange('itemViews');this._groupViews=null;this.notifyPropertyChange('groupViews');}
this.endPropertyChanges();if(SC.BENCHMARK_UPDATE_CHILDREN)SC.Benchmark.end(bkey);},rebuildChildren:function(){this.beginPropertyChanges();while(this._itemViewRoot)this._removeItemViewFromChain(this._itemViewRoot);while(this._groupViewRoot)this._removeGroupView(this._groupViewRoot);this._hasChildren=false;this.updateChildren();this.endPropertyChanges();},updateSelectionStates:function(){if(!this._hasChildren)return;var selection=this.get('selection')||[];var selectionHash=this._selectionHash;if(!selectionHash){selectionHash={};var idx=selection.get('length');while(--idx>=0){var cur=selection.objectAt(idx);var key=SC.guidFor(cur);selectionHash[key]=true;}
this._selectionHash=selectionHash;}
for(var key in this._itemViewsByContent){if(!this._itemViewsByContent.hasOwnProperty(key))continue;var itemView=this._itemViewsByContent[key];var isSelected=(key)?selectionHash[key]:false;if(itemView.get('isSelected')!=isSelected){itemView.set('isSelected',isSelected);}}},resizeChildrenWithOldSize:function(oldSize){if(!this._hasChildren)return;this.updateChildren();this.layoutResize();},clippingFrameDidChange:function(){if(!this._hasChildren)return;SC.Benchmark.start('%@.clippingFrameDidChange'.fmt(this.toString()));if(!SC.rectsEqual(this._lastClippingFrame,this.get('clippingFrame'))){if(this._hasChildren)this.updateChildren();}
SC.Benchmark.end('%@.clippingFrameDidChange'.fmt(this.toString()));},computeFrame:function(){return null;},contentRangeInFrame:function(frame){var content=this.get('content');var len=((content&&content.get)?content.get('length'):0)||0;return{start:0,length:len};},layoutGroupView:function(groupView,groupValue,contentIndexHint,firstLayout){},layoutItemView:function(itemView,contentIndex,firstLayout){},layoutResize:function(){if(!this._hasChildren)return;var nowShowingRange=this.get('nowShowingRange');var groupBy=this.get('groupBy');var groupValue=undefined;var content=this.get('content')||[];var idx=SC.maxRange(nowShowingRange);while(--idx>=nowShowingRange.start){var cur=content.objectAt(idx);var itemView=this.itemViewForContent(cur);if(!itemView)continue;if(groupBy&&((curGroupValue=(cur)?cur.get(groupBy):null)!==groupValue)){var groupView=this.groupViewForGroupValue(groupValue);if(groupView){this.layoutGroupView(groupView,groupValue,idx,false);}}
this.layoutItemView(itemView,idx,false);}},_itemViews:null,_groupViews:null,_visibleContentRange:null,_itemViewsByContent:null,_groupViewsByValue:null,_groupViewCounts:null,_itemViewPool:null,_groupViewPool:null,_zombieGroupViews:null,_insertItemViewFor:function(content,groupBy,contentIndex){var key=SC.guidFor(content);var ret=this._itemViewsByContent[key];var firstLayout=false;if(!ret){ret=this._itemViewPool.pop()||this.get('exampleView').create({owner:this,displayDelegate:this});ret.addClassName('sc-collection-item');ret.set('content',content);this._itemViewsByContent[key]=ret;this._itemViewsByGuid[SC.guidFor(ret)]=ret;firstLayout=true;}
if(!ret)throw"Could not create itemView for content: %@".fmt(content);var canGroup=!!(groupBy&&content);var groupValue=(canGroup)?content.get(groupBy):null;var parentView=(canGroup)?this._insertGroupViewFor(groupValue,contentIndex):this;var curParentView=ret.get('parentNode');if(curParentView!=parentView){if(groupBy&&curParentView){if(--this._groupViewCounts[SC.guidFor(curParentView)]<=0){this._removeGroupView(curParentView,groupValue);}}
parentView.appendChild(ret);if(groupBy)this._groupViewCounts[SC.guidFor(parentView)]++;}
this.layoutItemView(ret,contentIndex,firstLayout);return ret;},_removeItemView:function(itemView,groupBy){var groupView=null;var groupValue;if(groupBy&&(groupView=itemView.get('parentNode'))){if(--this._groupViewCounts[SC.guidFor(groupView)]>0)groupView=null;if(groupView){var content=itemView.get('content');groupValue=(content)?content.get(groupBy):null;}}
var content=itemView.get('content');var key=SC.guidFor(content);delete this._itemViewsByContent[key];delete this._itemViewsByGuid[SC.guidFor(itemView)];itemView.removeFromParent();itemView.set('content',null);this._itemViewPool.push(itemView);if(groupView)this._removeGroupView(groupView,groupValue);return itemView;},_insertOrRemoveItemViewsInRange:function(start,length,groupBy){if(length==0)return;var content=this.get('content')||[];if(length<0){while(++length<0){var c=content.objectAt(start+length);var itemView=this.itemViewForContent(c);if(itemView)this._removeItemView(itemView,groupBy);}}else if(length>0){while(--length>=0){var idx=start+length;var c=content.objectAt(idx);this._insertItemViewFor(c,groupBy,idx);}}},_insertGroupViewFor:function(groupValue,contentIndex){var ret=this._groupViewsByValue[groupValue];var firstLayout=false;if(!ret&&this._zombieGroupViews){ret=this._zombieGroupViews[groupValue];if(ret){delete this._zombieGroupViews[groupValue];this._groupViewsByValue[groupValue]=ret;this._groupViewCounts[SC.guidFor(ret)]=0;}}
if(!ret){ret=this._groupViewPool.pop()||this.get('exampleGroupView').create({owner:this,displayDelegate:this});ret.addClassName('sc-collection-group');if(ret.groupValue!==undefined){ret.set('groupValue',groupValue);}else ret.set('content',groupValue);this._groupViewsByValue[groupValue]=ret;this._groupViewCounts[SC.guidFor(ret)]=0;firstLayout=true;}
if(!ret)throw"Could not create a groupView for value: %@".fmt(groupValue);if(ret.get('parentNode')!=this)this.appendChild(ret);this.layoutGroupView(ret,groupValue,contentIndex,firstLayout);return ret;},_removeGroupView:function(groupView,groupValue){if(SC.ZOMBIE_GROUPS_ENABLED){this._zombieGroupViews[groupValue]=groupView;}else{this._finalRemoveGroupView(groupView);}
delete this._groupViewsByValue[groupValue];delete this._groupViewCounts[SC.guidFor(groupView)];return groupView;},_flushZombieGroupViews:function(){if(!SC.ZOMBIE_GROUPS_ENABLED)return;for(var key in this._zombieGroupViews){if(!this._zombieGroupViews.hasOwnProperty(key))continue;var groupView=this._zombieGroupViews[key];this._finalRemoveGroupView(groupView);}
this._zombieGroupViews={};},_finalRemoveGroupView:function(groupView){groupView.removeFromParent();if(groupView.groupValue!==undefined){groupView.set('groupValue',null);}else groupView.set('content',null);this._groupViewPool.push(groupView);return groupView;},_removeRootElementFromDom:function(){if(!SC.REMOVE_COLLECTION_ROOT_ELEMENT_DURING_RENDER)return;if(this._cachedRootElementParent===undefined){var parent=this._cachedRootElementParent=this.rootElement.parentNode;this._cachedRootElementNextSibling=this.rootElement.nextSibling;if(parent)parent.removeChild(this.rootElement);}},_restoreRootElementInDom:function(){if(!SC.REMOVE_COLLECTION_ROOT_ELEMENT_DURING_RENDER)return;if(this._cachedRootElementParent){this._cachedRootElementParent.insertBefore(this.rootElement,this._cachedRootElementNextSibling);}
this._cachedRootElementParent=this._cachedRootElementNextSibling=null;},_indexOfSelectionTop:function(){var content=this.get('content');var sel=this.get('selection');if(!content||!sel)return-1;var contentLength=content.get('length');var indexOfSelected=contentLength;var idx=sel.length;while(--idx>=0){var curIndex=content.indexOf(sel[idx]);if((curIndex>=0)&&(curIndex<indexOfSelected))indexOfSelected=curIndex;}
return(indexOfSelected>=contentLength)?-1:indexOfSelected;},_indexOfSelectionBottom:function(){var content=this.get('content');var sel=this.get('selection');if(!content||!sel)return-1;var indexOfSelected=-1;var idx=sel.length;while(--idx>=0){var curIndex=content.indexOf(sel[idx]);if(curIndex>indexOfSelected)indexOfSelected=curIndex;}
return(indexOfSelected<0)?-1:indexOfSelected;},selectPreviousItem:function(extend,numberOfItems)
{if(numberOfItems==null)numberOfItems=1;if(extend==null)extend=false;var content=this.get('content');var contentLength=content.get('length');var selTop,selBottom,anchor;if(extend){selTop=this._indexOfSelectionTop();selBottom=this._indexOfSelectionBottom();anchor=(this._selectionAnchor==null)?selTop:this._selectionAnchor;this._selectionAnchor=anchor;if(selBottom>anchor){selBottom=selBottom-numberOfItems;}else{selTop=selTop-numberOfItems;}
if(selTop<0)selTop=0;if(selBottom<selTop)selBottom=selTop;}else{selTop=this._indexOfSelectionTop()-numberOfItems;if(selTop<0)selTop=0;selBottom=selTop;anchor=null;}
var items=[];while(selTop<=selBottom){items[items.length]=content.objectAt(selTop++);}
if(items.length>0){this.scrollToContent(items.first());this.selectItems(items);}
this._selectionAnchor=anchor;},selectNextItem:function(extend,numberOfItems)
{if(numberOfItems==null)numberOfItems=1;if(extend==null)extend=false;var content=this.get('content');var contentLength=content.get('length');var selTop,selBottom,anchor;if(extend){selTop=this._indexOfSelectionTop();selBottom=this._indexOfSelectionBottom();anchor=(this._selectionAnchor==null)?selTop:this._selectionAnchor;this._selectionAnchor=anchor;if(selTop<anchor){selTop=selTop+numberOfItems;}else{selBottom=selBottom+numberOfItems;}
if(selBottom>=contentLength)selBottom=contentLength-1;if(selTop>selBottom)selTop=selBottom;}else{selBottom=this._indexOfSelectionBottom()+numberOfItems;if(selBottom>=contentLength)selBottom=contentLength-1;selTop=selBottom;anchor=null;}
var items=[];while(selTop<=selBottom){items[items.length]=content.objectAt(selTop++);}
if(items.length>0){this.scrollToContent(items.first());this.selectItems(items);}
this._selectionAnchor=anchor;},scrollToContent:function(record){var itemView=this.itemViewForContent(record);if(!itemView){var content=Array.from(this.get('content'));var contentIndex=content.indexOf(record);var groupBy=this.get('groupBy');itemView=this._insertItemViewFor(record,groupBy,contentIndex);}
if(itemView)this.scrollToItemView(itemView);},scrollToItemView:function(view)
{var scrollable=this;while(scrollable&&(scrollable!=SC.window)&&(!scrollable.get('isScrollable'))){scrollable=scrollable.get('parentNode');}
if(!scrollable||(scrollable==SC.window))return;scrollable.scrollToVisible(view);},selectItems:function(items,extendSelection){var base=(extendSelection)?this.get('selection'):[];var sel=[items].concat(base).flatten().uniq();this._selectionAnchor=null;this.set('selection',sel);},deselectItems:function(items){items=[items].flatten();var base=this.get('selection')||[];var sel=base.map(function(i){return(items.include(i))?null:i;});sel=sel.compact();this.set('selection',sel);},deleteSelection:function(){if(!this.get('canDeleteContent'))return NO;var sel=Array.from(this.get('selection'));if(!sel||sel.get('length')===0)return NO;sel=this.invokeDelegateMethod(this.delegate,'collectionViewShouldDeleteContent',this,sel);sel=Array.from(sel);if(!sel||sel.get('length')===0)return YES;this.invokeDelegateMethod(this.delegate,'collectionViewDeleteContent',this,sel);return YES;},collectionViewDeleteContent:function(view,sel){var content=this.get('content');if(!content||!content.removeObject)return NO;if(content.beginPropertyChanges)content.beginPropertyChanges();var idx=sel.get('length');while(--idx>=0){var item=sel.objectAt(idx);content.removeObject(item);}
if(content.endPropertyChanges)content.endPropertyChanges();return YES;},keyDown:function(evt){return this.interpretKeyEvents(evt);},keyUp:function(){return true;},selectAll:function(evt){var content=(this.get('content')||[]).slice();this.selectItems(content,NO);return YES;},deleteBackward:function(evt){return this.deleteSelection();},deleteForward:function(evt){return this.deleteSelection();},moveDown:function(sender,evt){this.selectNextItem(false,this.get('itemsPerRow')||1);return true;},moveUp:function(sender,evt){this.selectPreviousItem(false,this.get('itemsPerRow')||1);return true;},moveLeft:function(sender,evt){if((this.get('itemsPerRow')||1)>1)this.selectPreviousItem(false,1);return true;},moveRight:function(sender,evt){if((this.get('itemsPerRow')||1)>1)this.selectNextItem(false,1);return true;},moveDownAndModifySelection:function(sender,evt){this.selectNextItem(true,this.get('itemsPerRow')||1);return true;},moveUpAndModifySelection:function(sender,evt){this.selectPreviousItem(true,this.get('itemsPerRow')||1);return true;},moveLeftAndModifySelection:function(sender,evt){if((this.get('itemsPerRow')||1)>1)this.selectPreviousItem(true,1);return true;},moveRightAndModifySelection:function(sender,evt){if((this.get('itemsPerRow')||1)>1)this.selectNextItem(true,1);return true;},mouseDown:function(ev){this._mouseDownEvent=ev;if(this.useToggleSelection)return true;this._mouseDownAt=this._shouldSelect=this._shouldDeselect=this._shouldReselect=this._refreshSelection=false;var mouseDownView=this._mouseDownView=this.itemViewForEvent(ev);var mouseDownContent=this._mouseDownContent=(mouseDownView)?mouseDownView.get('content'):null;this.becomeFirstResponder();if(!mouseDownView){if(this.get('allowDeselectAll'))this.selectItems([],false);return true;}
var selection=this.get('selection')||[];var isSelected=selection.include(mouseDownContent);var modifierKeyPressed=ev.ctrlKey||ev.metaKey;if(mouseDownView.checkboxView&&(Event.element(ev)==el.checkboxView.rootElement)){modifierKeyPressed=true;}
this._modifierKeyPressed=modifierKeyPressed;this._mouseDownAt=Date.now();if(modifierKeyPressed&&isSelected){this._shouldDeselect=mouseDownContent;}else if(ev.shiftKey&&selection.get('length')>0){selection=this._findSelectionExtendedByShift(selection,mouseDownContent);this.selectItems(selection);}else if(!modifierKeyPressed&&isSelected){this._shouldReselect=mouseDownContent;}else{if(this.get("selectOnMouseDown")){this.selectItems(mouseDownContent,modifierKeyPressed);}else this._shouldSelect=mouseDownContent;}
this._previousMouseDownContent=mouseDownContent;return true;},mouseUp:function(ev){var canAct=this.get('actOnSelect');var view=this.itemViewForEvent(ev);if(this.useToggleSelection){if(!view)return;var selection=this.get('selection')||[];var content=(view)?view.get('content'):null;var isSelected=selection.include(content);if(isSelected){this.deselectItems([content]);}else this.selectItems([content],true);}else{var content=(view)?view.get('content'):null;if(this._shouldSelect)this.selectItems(this._shouldSelect,this._modifierKeyPressed);if(this._shouldDeselect)this.deselectItems(this._shouldDeselect);if(this._shouldReselect){var canEdit=this.get('contentValueIsEditable');if(canEdit){var sel=this.get('selection');canEdit=sel&&(sel.get('length')===1)&&(sel.objectAt(0)===this._shouldReselect);}
if(canEdit){var itemView=this.itemViewForContent(this._shouldReselect);canEdit=itemView&&(!itemView.contentHitTest||itemView.contentHitTest(ev));canEdit=(canEdit&&itemView.beginEditing)?itemView.beginEditing():NO;}
if(!canEdit)this.selectItems(this._shouldReselect,false);}
this._cleanupMouseDown();}
this._mouseDownEvent=null;if(canAct)this._action(ev,view);return false;},_cleanupMouseDown:function(){this._mouseDownAt=this._shouldDeselect=this._shouldReselect=this._refreshSelection=this._shouldSelect=false;this._mouseDownEvent=this._mouseDownContent=this._mouseDownView=null;},mouseMoved:function(ev){var view=this.itemViewForEvent(ev);if(this._lastHoveredItem&&((view===null)||(view!=this._lastHoveredItem))&&this._lastHoveredItem.mouseOut){this._lastHoveredItem.mouseOut(ev);}
this._lastHoveredItem=view;if(view&&view.mouseOver)view.mouseOver(ev);},mouseOut:function(ev){var view=this._lastHoveredItem;this._lastHoveredItem=null;if(view&&view.didMouseOut)view.didMouseOut(ev);},doubleClick:function(ev){var view=this.itemViewForEvent(ev);if(view){this._action(view,ev);return true;}else return false;},_findSelectionExtendedByShift:function(selection,mouseDownContent){var content=this.get('content');var contentLowerBounds=0;var contentUpperBounds=(content.get('length')-1);var selectionBeginIndex=content.indexOf(selection.first());var selectionEndIndex=content.indexOf(selection.last());var previousMouseDownIndex=content.indexOf(this._previousMouseDownContent);if(previousMouseDownIndex==-1)previousMouseDownIndex=selectionBeginIndex;var currentMouseDownIndex=content.indexOf(mouseDownContent);if(currentMouseDownIndex==-1)throw"Unable to extend selection to an item that's not in the content array!";if(currentMouseDownIndex<selectionBeginIndex){selectionBeginIndex=currentMouseDownIndex;}
if(currentMouseDownIndex>selectionEndIndex){selectionEndIndex=currentMouseDownIndex;}
if((currentMouseDownIndex>selectionBeginIndex)&&(currentMouseDownIndex<selectionEndIndex)){if(currentMouseDownIndex===previousMouseDownIndex){selectionBeginIndex=currentMouseDownIndex;selectionEndIndex=currentMouseDownIndex;}else if(currentMouseDownIndex>previousMouseDownIndex){selectionBeginIndex=previousMouseDownIndex;selectionEndIndex=currentMouseDownIndex;}else if(currentMouseDownIndex<previousMouseDownIndex){selectionBeginIndex=currentMouseDownIndex;selectionEndIndex=previousMouseDownIndex;}}
selectionEndIndex++;return content.slice(selectionBeginIndex,selectionEndIndex);},insertNewline:function(){if(this.get('contentValueIsEditable')){var sel=this.get('selection');if(sel&&sel.get('length')===1){var itemView=this.itemViewForContent(sel.objectAt(0));if(itemView&&itemView.beginEditing){this.scrollToItemView(itemView);itemView.beginEditing();}}}else{var sel=this.get('selection');var itemView=(sel&&sel.get('length')===1)?this.itemViewForContent(sel.objectAt(0)):null;this._action(itemView,null);}
return YES;},didBecomeFirstResponder:function(){this.addClassName('focus');},willLoseFirstResponder:function(){this.removeClassName('focus');},reorderDataType:function(){if(!this._reorderDataTypeKey){this._reorderDataTypeKey="SC.CollectionView.Reorder.%@".fmt(SC.guidFor(this));}
return this._reorderDataTypeKey;}.property(),_reorderDataType:function(){return this.get('reorderDataType');},dragContent:null,proposedInsertionIndex:null,proposedDropOperation:null,mouseDragged:function(ev){if(this._mouseDownEvent===null)return YES;if((Date.now()-this._mouseDownAt)<123)return YES;if(this.invokeDelegateMethod(this.delegate,'collectionViewShouldBeginDrag',this)){var content=this.get('content')||[];var dragContent;if(!this.get("selectOnMouseDown")){dragContent=[this._mouseDownContent];}else{dragContent=this.get('selection').sort(function(a,b){a=content.indexOf(a);b=content.indexOf(b);return(a<b)?-1:((a>b)?1:0);});}
this.set('dragContent',dragContent);if(this.get('dragDataTypes').get('length')>0){var view=this.ghostViewFor(dragContent);SC.Drag.start({event:this._mouseDownEvent,source:this,dragView:view,ghost:NO,slideBack:YES,dataSource:this});this._cleanupMouseDown();this._lastInsertionIndex=null;}else{this.set('dragContent',null);}
return YES;}},dragDataTypes:function(){var ret=this.invokeDelegateMethod(this.delegate,'collectionViewDragDataTypes',this);var canReorderContent=this.get('canReorderContent');if((!ret||ret.get('length')===0)&&!canReorderContent)return[];if(canReorderContent){ret=(ret)?ret.slice():[];var key=this.get('reorderDataType');if(ret.indexOf(key)<0)ret.push(key);}
return ret;}.property(),dragDataForType:function(dataType,drag){if(this.get('canReorderContent')){if(dataType===this.get('reorderDataType'))return this.get('dragContent');}
return this.invokeDelegateMethod(this.delegate,'collectionViewDragDataForType',this,dataType,drag);},dragEntered:function(drag,evt){var op=SC.DRAG_NONE;if(this.get('canReorderContent')){var types=drag.get('dataTypes');if(types.indexOf(this.get('reorderDataType'))>=0){op=SC.DRAG_REORDER;}}
op=this.invokeDelegateMethod(this.delegate,'collectionViewValidateDrop',this,drag,SC.DROP_ANY,-1,op);if(op===SC.DRAG_REORDER)op=SC.DRAG_MOVE;return op;},_computeDropOperationState:function(drag,evt){var loc=drag.get('location');loc=this.convertFrameFromView(loc,null);var dropOp=SC.DROP_BEFORE;var dragOp=SC.DRAG_NONE;var idx=this.insertionIndexForLocation(loc,SC.DROP_ON);if($type(idx)===T_ARRAY){dropOp=idx[1];idx=idx[0];}
if(dropOp===SC.DROP_ON){this.set('proposedInsertionIndex',idx);this.set('proposedDropOperation',dropOp);dragOp=this.invokeDelegateMethod(this.delegate,'collectionViewValidateDrop',this,drag,dropOp,idx,dragOp);idx=this.get('proposedInsertionIndex');dropOp=this.get('proposedDropOperation');this._dropInsertionIndex=this._dropOperation=null;if(dragOp!==SC.DRAG_NONE){return[idx,dropOp,dragOp];}else{dropOp=SC.DROP_BEFORE;idx=this.insertionIndexForLocation(loc,SC.DROP_BEFORE);if($type(idx)===T_ARRAY){dropOp=idx[1];idx=idx[0];}}}
if((idx>=0)&&this.get('canReorderContent')&&(dropOp===SC.DROP_BEFORE)){var objects=drag.dataForType(this.get('reorderDataType'));if(objects){var content=this.get('content')||[];var previousContent=(idx>0)?content.objectAt(idx-1):null;var nextContent=(idx<content.get('length'))?content.objectAt(idx):null;var isPreviousInDrag=(previousContent)?objects.indexOf(previousContent)>=0:NO;var isNextInDrag=(nextContent)?objects.indexOf(nextContent)>=0:NO;if(isPreviousInDrag&&isNextInDrag){if(this._lastInsertionIndex==null){while((idx>=0)&&(objects.indexOf(content.objectAt(idx))>=0)){idx--;}}else idx=this._lastInsertionIndex;}
if(idx>=0)dragOp=SC.DRAG_REORDER;}}
this.set('proposedInsertionIndex',idx);this.set('proposedDropOperation',dropOp);dragOp=this.invokeDelegateMethod(this.delegate,'collectionViewValidateDrop',this,drag,dropOp,idx,dragOp);idx=this.get('proposedInsertionIndex');dropOp=this.get('proposedDropOperation');this._dropInsertionIndex=this._dropOperation=null;return[idx,dropOp,dragOp];},dragUpdated:function(drag,evt){var state=this._computeDropOperationState(drag,evt);var idx=state[0],dropOp=state[1],dragOp=state[2];if(dragOp!==SC.DRAG_NONE){if((this._lastInsertionIndex!==idx)||(this._lastDropOperation!==dropOp)){var itemView=this.itemViewForContent(this.get('content').objectAt(idx));this.showInsertionPoint(itemView,dropOp);}
this._lastInsertionIndex=idx;this._lastDropOperation=dropOp;}else{this.hideInsertionPoint();this._lastInsertionIndex=this._lastDropOperation=null;}
return(dragOp===SC.DRAG_REORDER)?SC.DRAG_MOVE:dragOp;},dragExited:function(){this.hideInsertionPoint();this._lastInsertionIndex=this._lastDropOperation=null;},dragEnded:function(){this.hideInsertionPoint();this._lastInsertionIndex=this._lastDropOperation=null;},prepareForDragOperation:function(op,drag){return YES;},performDragOperation:function(op,drag){var state=this._computeDropOperationState(drag,null,op);var idx=state[0],dropOp=state[1],dragOp=state[2];if(dragOp===SC.DRAG_REORDER){op=(op&SC.DRAG_MOVE)?SC.DRAG_REORDER:SC.DRAG_NONE;}else{op=op&dragOp;}
if(op===SC.DRAG_NONE)return op;var performed=this.invokeDelegateMethod(this.delegate,'collectionViewAcceptDrop',this,drag,dropOp,idx,op);if((performed===SC.DRAG_NONE)&&(op===SC.DRAG_REORDER)){var objects=drag.dataForType(this.get('reorderDataType'));if(!objects)return SC.DRAG_NONE;var content=this.get('content');content.beginPropertyChanges();var objectsIdx=objects.get('length');while(--objectsIdx>=0){var obj=objects.objectAt(objectsIdx);var old=content.indexOf(obj);if(old>=0)content.removeAt(old);if((old>=0)&&(old<idx))idx--;}
content.replace(idx,0,objects);content.endPropertyChanges();op=SC.DRAG_MOVE;}
return op;},collectionViewShouldBeginDrag:function(view){return this.get('canReorderContent');},concludeDragOperation:function(op,drag){this.hideInsertionPoint();this._lastInsertionIndex=null;},insertionOrientation:SC.HORIZONTAL_ORIENTATION,insertionIndexForLocation:function(loc,dropOperation){var content=this.get('content');var f,itemView,curSide,lastSide=null;var orient=this.get('insertionOrientation');var ret=null;for(var idx=0;((ret==null)&&(idx<content.length));idx++){itemView=this.itemViewForContent(content.objectAt(idx));f=this.convertFrameFromView(itemView.get('frame'),itemView);if(orient==SC.HORIZONTAL_ORIENTATION){if(SC.maxY(f)>loc.y){curSide=(SC.maxX(f)<loc.x)?-1:1;}else curSide=null;}else{if(SC.minX(f)<loc.x){curSide=(SC.maxY(f)<loc.y)?-1:1;}else curSide=null;}
if(curSide!==null){if((lastSide!==null)&&(curSide!=lastSide)){ret=idx;if(orient==SC.HORIZONTAL_ORIENTATION){if(SC.midX(f)<loc.x)ret++;}else{if(SC.midY(f)<loc.y)ret++;}}
lastSide=curSide;}}
if((ret==null)||(ret<0))ret=0;if(ret>content.length)ret=content.length;return ret;},showInsertionPoint:function(itemView,dropOperation){return(dropOperation===SC.DROP_BEFORE)?this.showInsertionPointBefore(itemView):this.hideInsertionPoint();},showInsertionPointBefore:function(itemView){},hideInsertionPoint:function(){},ghostViewFor:function(dragContent){var view=SC.View.create();view.setStyle({position:'absolute',overflow:'hidden'});var viewFrame=this.convertFrameToView(this.get('frame'),null);view.set('frame',viewFrame);var idx=dragContent.length;var maxX=0;var maxY=0;var minX=100000;var minY=100000;while(--idx>=0){var itemView=this.itemViewForContent(dragContent[idx]);if(!itemView)continue;var f=itemView.get('frame');f=this.convertFrameFromView(f,itemView);var dom=itemView.rootElement;if(!dom)continue;if(SC.maxX(f)>maxX)maxX=SC.maxX(f);if(SC.maxY(f)>maxY)maxY=SC.maxY(f);if(SC.minX(f)<minX)minX=SC.minX(f);if(SC.minY(f)<minY)minY=SC.minY(f);dom=dom.cloneNode(true);Element.setStyle(dom,{position:"absolute",left:"%@px".fmt(f.x),top:"%@px".fmt(f.y),width:"%@px".fmt(f.width),height:"%@px".fmt(f.height)});view.rootElement.appendChild(dom);}
var wrapper=SC.View.create();wrapper.setStyle({position:'absolute',overflow:'hidden'});wrapper.set('frame',{x:viewFrame.x+minX,y:viewFrame.y+minY,width:(maxX-minX+1),height:(maxY-minY+1)});wrapper.appendChild(view);view.set('frame',{x:0-minX,y:0-minY});return wrapper;},init:function(){this._itemViewsByContent={};this._groupViewsByValue={};this._groupViewCounts={};this._zombieGroupViews={};this._itemViewsByGuid={};this._itemViewPool=[];this._groupViewPool=[];arguments.callee.base.apply(this,arguments);this._dropTargetObserver();},_action:function(view,evt){var action=this.get('action');var target=this.get('target')||null;if(action){if($type(action)==T_FUNCTION)return this.action(view,evt);SC.app.sendAction(action,target,this);}else if(!view){return;}else if($type(view._action)==T_FUNCTION){return view._action(evt);}else if($type(view.action)==T_FUNCTION){return view.action(evt);}},_dropTargetObserver:function(){var canDrop=this.get('canReorderContent')||this.get('isDropTarget');if(canDrop){SC.Drag.addDropTarget(this);}else{SC.Drag.removeDropTarget(this);}}.observes('canReorderContent','isDropTarget'),_contentObserver:function(){var content=this.get('content');if(SC.isEqual(content,this._content))return;if(!this._boundContentPropertyObserver){this._boundContentPropertyObserver=this._contentPropertyObserver.bind(this);}
var func=this._boundContentPropertyObserver;if(this._content)this._content.removeObserver('[]',func);if(content)content.addObserver('[]',func);this._content=content;this._contentPropertyRevision=null;var rev=(content)?content.propertyRevision:-1;this._contentPropertyObserver(this,'[]',content,rev);}.observes('content'),_selectionObserver:function(){var sel=this.get('selection');if(SC.isEqual(sel,this._selection))return;if(!this._boundSelectionPropertyObserver){this._boundSelectionPropertyObserver=this._selectionPropertyObserver.bind(this);}
var func=this._boundSelectionPropertyObserver;if(this._selection)this._selection.removeObserver('[]',func);if(sel)sel.addObserver('[]',func);this._selection=sel;this._selectionPropertyRevision=null;var propertyRevision=(sel)?sel.propertyRevision:null;this._selectionPropertyObserver(this,'[]',sel,propertyRevision);}.observes('selection'),_contentPropertyObserver:function(target,key,value,rev){if(!this._updatingContent&&(!rev||(rev!=this._contentPropertyRevision))){this._contentPropertyRevision=rev;this._updatingContent=true;this._hasChildren=false;this.updateChildren(true);this._updatingContent=false;}},_selectionPropertyObserver:function(target,key,value,rev){if(!this._updatingSel&&(!rev||(rev!=this._selectionPropertyRevision))){this._selectionPropertyRevision=rev;this._updatingSel=true;this._selectionHash=null;this.updateSelectionStates();this._updatingSel=false;}},_isVisibleInWindowObserver:function(){if(this.get('isDirty'))this.updateChildren();}.observes('isVisibleInWindow'),allowDeselectAll:true,itemExistsInCollection:function(view){return this.hasItemView(view);},viewForContentRecord:function(rec){return this.itemViewForContent(rec);}});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.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;}};require('views/view');require('views/label');require('mixins/control');SC.TOGGLE_BEHAVIOR='toggle';SC.PUSH_BEHAVIOR='push';SC.TOGGLE_ON_BEHAVIOR="on";SC.TOGGLE_OFF_BEHAVIOR="off";SC.ButtonView=SC.View.extend(SC.Control,{emptyElement:'<a href="javascript:;" class="sc-button-view regular"><span class="button-inner"><span class="label"></span></span></a>',value:false,toggleOnValue:true,toggleOffValue:false,theme:'regular',buttonBehavior:SC.PUSH_BEHAVIOR,isEnabled:YES,isSelected:NO,isDefault:NO,isDefaultBindingDefault:SC.Binding.OneWayBool,isCancel:NO,isCancelBindingDefault:SC.Binding.OneWayBool,localize:NO,titleSelector:'.label',title:function(key,value){if(value!==undefined){if(this._title!=value){var text=this._title=value;var lsel=this.get('titleSelector');var el=(lsel)?this.$sel(lsel):this.rootElement;if(this.get('localize'))text=text.loc();el.innerHTML=text;}}
if(!this._title){var el=this.$sel(this.get('titleSelector'));this._title=(el)?el.innerHTML:'';}
return this._title;}.property(),href:function(key,value){var el=this.rootElement;if(value!==undefined){if(el){el.setAttribute('href',value);}}
return(el)?el.getAttribute('href'):null;}.property(),action:null,target:null,keyEquivalent:null,_defaultKeyEquivalent:null,performKeyEquivalent:function(keystring,evt)
{if(!this.get('isEnabled'))return false;var keyEquivalent=this.get('keyEquivalent');if(keyEquivalent&&(keyEquivalent==keystring))
{return this.triggerAction(evt);}
return false;},triggerAction:function(evt){if(!this.get('isEnabled'))return false;this.setClassName('active',true);this.didTriggerAction();this._action(evt);this.invokeLater('setClassName',200,'active',false);return true;},didTriggerAction:function(){},init:function(){arguments.callee.base.call(this);if(this.get("keyEquivalent"))this._defaultKeyEquivalent=this.get("keyEquivalent");this._isDefaultOrCancelObserver();var el;var sel=this.get('titleSelector');if(this.get('localize')&&sel&&(el=this.$sel(sel))){this._title=(el.innerHTML||'').strip();el.innerHTML=this._title.loc();}},_selectedStateFromValue:function(value){var targetValue=this.get('toggleOnValue');var state;if($type(value)==T_ARRAY){if(value.length==1){state=(value[0]==targetValue);}else{state=(value.indexOf(targetValue)>=0)?SC.MIXED_STATE:false;}}else{state=(value==targetValue);}
return state;},propertyObserver:function(observing,target,key,value){if(target!=this)return;switch(key){case'value':value=this.get('value');if(value==this._value)return;this._value=value;var state=this._selectedStateFromValue(value);this.setIfChanged('isSelected',state);break;case'isSelected':var newState=this.get('isSelected');var curState=this._selectedStateFromValue(this.get('value'));if(curState!=newState){var valueKey=(newState)?'toggleOnValue':'toggleOffValue';this.set('value',this.get(valueKey));}
break;default:break;}},_isDefaultOrCancelObserver:function(){var isDef=!!this.get('isDefault');var isCancel=!isDef&&this.get('isCancel');if(this.didChangeFor('defaultCancelChanged','isDefault','isCancel')){this.setClassName('def',isDef);if(isDef){this.setIfChanged('keyEquivalent','return');}
else if(isCancel)
{this.setIfChanged('keyEquivalent','escape');}
else
{this.set("keyEquivalent",this._defaultKeyEquivalent);}}}.observes('isDefault','isCancel'),isMouseDown:false,mouseDown:function(evt){this.setClassName('active',this.get('isEnabled'));this._isMouseDown=true;return true;},mouseOut:function(evt)
{this.setClassName('active',false);return true;},mouseOver:function(evt)
{this.setClassName('active',this._isMouseDown);return true;},mouseUp:function(evt){this.setClassName('active',false);this._isMouseDown=false;var tgt=Event.element(evt);var inside=false;while(tgt&&(tgt!=this.rootElement))tgt=tgt.parentNode;if(tgt==this.rootElement)inside=true;if(inside&&this.get('isEnabled'))this._action(evt);return true;},_action:function(evt){switch(this.get('buttonBehavior')){case SC.TOGGLE_BEHAVIOR:var sel=this.get('isSelected');if(sel==true){this.set('value',this.get('toggleOffValue'));}else{this.set('value',this.get('toggleOnValue'));}
break;case SC.TOGGLE_ON_BEHAVIOR:this.set('value',this.get('toggleOnValue'));break;case SC.TOGGLE_OFF_BEHAVIOR:this.set('value',this.get('toggleOffValue'));break;default:var action=this.get('action');var target=this.get('target')||null;if(action)
{if(this._hasLegacyActionHandler()){this._triggerLegacyActionHandler(evt);}else{SC.app.sendAction(action,target,this);}}}},_hasLegacyActionHandler:function()
{var action=this.get('action');if(action&&($type(action)==T_FUNCTION))return true;if(action&&($type(action)==T_STRING)&&(action.indexOf('.')!=-1))return true;return false;},_triggerLegacyActionHandler:function(evt)
{if(!this._hasLegacyActionHandler())return false;var action=this.get('action');if($type(action)==T_FUNCTION)this.action(evt);if($type(action)==T_STRING)
{eval("this.action = function(e) { return "+action+"(this, e); };");this.action(evt);}}});require('views/button/button');SC.DisclosureView=SC.ButtonView.extend({emptyElement:'<a href="javascript:;" class="sc-disclosure-view sc-button-view button disclosure"><img src="%@" class="button" /><span class="label"></span></a>'.fmt('/static/sproutcore/en/blank.gif'),buttonBehavior:SC.TOGGLE_BEHAVIOR,toggleOnValue:YES,toggleOffValue:NO,valueBindingDefault:SC.Binding.Bool,init:function(){arguments.callee.base.apply(this,arguments);if(this.get('value')==this.get('toggleOnValue')){this.set('isSelected',true);}}});require('views/view');require('mixins/delegate_support');require('mixins/control');require('views/button/disclosure');SC.SourceListGroupView=SC.View.extend(SC.Control,SC.DelegateSupport,{emptyElement:['<div class="sc-source-list-group">','<a href="javascript:;" class="sc-source-list-label sc-disclosure-view sc-button-view button disclosure no-disclosure">','<img src="%@" class="button" />'.fmt('/static/sproutcore/en/blank.gif'),'<span class="label"></span></a>','</div>'].join(''),content:null,isGroupVisible:YES,hasGroupTitle:YES,groupTitleKey:null,groupVisibleKey:null,contentPropertyDidChange:function(target,key){var content=this.get('content');var labelView=this.outlet('labelView');if(content==null){labelView.setIfChanged('isVisible',NO);this.setIfChanged('hasGroupTitle',NO);return;}else{labelView.setIfChanged('isVisible',YES);this.setIfChanged('hasGroupTitle',YES);}
var groupTitleKey=this.getDelegateProperty(this.displayDelegate,'groupTitleKey');if((key=='*')||(groupTitleKey&&(key==groupTitleKey))){var title=(content&&content.get&&groupTitleKey)?content.get(groupTitleKey):content;if(title!=this._title){this._title=title;if(title)title=title.capitalize();labelView.set('title',title);}}
var groupVisibleKey=this.getDelegateProperty(this.displayDelegate,'groupVisibleKey');if((key=='*')||(groupVisibleKey&&(key==groupVisibileKey))){if(groupVisibleKey){labelView.removeClassName('no-disclosure');var isVisible=(content&&content.get)?!!content.get(groupVisibleKey):YES;if(isVisible!=this.get('isGroupVisible')){this.set('isGroupVisible',isVisible);labelView.set('value',isVisible);}}else labelView.addClassName('no-disclosure');}},disclosureValueDidChange:function(newValue){if(newValue==this.get('isGroupVisible'))return;var group=this.get('content');var groupVisibleKey=this.getDelegateProperty(this.displayDelegate,'groupVisibleKey');if(group&&group.set&&groupVisibleKey){group.set(groupVisibleKey,newValue);}
this.set('isGroupVisible',newValue);if(this.owner&&this.owner.updateChildren)this.owner.updateChildren(true);},labelView:SC.DisclosureView.extend({value:YES,_valueObserver:function(){if(this.owner)this.owner.disclosureValueDidChange(this.get('value'));}.observes('value')}).outletFor('.sc-source-list-label:1:1')});require('views/view');require('mixins/control');lc_cnt=0;SC.IMAGE_STATE_NONE='none';SC.IMAGE_STATE_LOADING='loading';SC.IMAGE_STATE_LOADED='loaded';SC.IMAGE_STATE_FAILED='failed';SC.BLANK_IMAGE_URL='/static/sproutcore/en/blank.gif';SC.ImageView=SC.View.extend(SC.Control,{emptyElement:'<img src="%@" class="sc-image-view" />'.fmt(SC.BLANK_IMAGE_URL),status:SC.IMAGE_STATE_NONE,value:null,_value:null,transform:function(content){return content;},valueObserver:function(){var value=this.get('value');if(this.transform!==SC.ImageView.prototype.transform){var content=this.get('content')||'';value=this.transform(content);}
if(value==this._value)return;if(this._value&&this._value.length>0&&!SC.ImageView.valueIsUrl(this._value)){var classNames=this._value.split(' ');var idx=classNames.length;while(--idx>=0){this.removeClassName(classNames[idx]);}
this.removeClassName('sc-sprite');}
this._value=value;if(!value||value.length==0){this.rootElement.src=SC.BLANK_IMAGE_URL;this.set('status',SC.IMAGE_STATE_NONE);this._imageUrl=null;}else if(SC.ImageView.valueIsUrl(value)){this.beginPropertyChanges();this.set('status',SC.IMAGE_STATE_LOADING);this._imageUrl=value;SC.imageCache.loadImage(value,this,this._onLoadComplete);this.endPropertyChanges();}else{var classNames=value.split(' ');var idx=classNames.length;while(--idx>=0)this.addClassName(classNames[idx]);this.addClassName('sc-sprite');this.rootElement.src=SC.BLANK_IMAGE_URL;this.set('status',SC.IMAGE_STATE_LOADED);}}.observes('value'),_onLoadComplete:function(url,status,img){if(url!==this._imageUrl)return;this.beginPropertyChanges();this.set('imageWidth',parseInt(img.width,0));this.set('imageHeight',parseInt(img.height,0));this.set('status',status);this.endPropertyChanges();if(status==SC.IMAGE_STATE_LOADED){if(this.imageDidLoad)this.imageDidLoad(url);this.rootElement.src=url;}else{if(this.imageDidFail)this.imageDidFail(url,status);}},init:function(){arguments.callee.base.apply(this,arguments);this.valueObserver();if(this.rootElement.src){this.set('imageWidth',parseInt(this.rootElement.width,0));this.set('imageHeight',parseInt(this.rootElement.height,0));}}});SC.ImageView.valueIsUrl=function(value){return(value.indexOf('/')>=0)||(value.indexOf('.')>=0);};SC.imageCache=SC.Object.create({loadLimit:4,loadImage:function(url,objOrFunc,method){var dta=this._images[url]=(this._images[url]||{url:url,img:null,handlers:[],status:'unknown'});if(dta.img==null){this._queue.push(dta);if(!this._imgTimeout){this._imgTimeout=this.invokeLater(this.loadNextImage,100);}}
var handler=(method)?[objOrFunc,method]:[this,objOrFunc];if(dta.status=='unknown'){dta.handlers.push(handler);}else if(handler[1]){handler[1].call(handler[0],url,dta.status,dta.img);}},loadNextImage:function(){this._imgTimeout=null;while((this._queue.length>0)&&(this._loading.length<this.loadLimit)){var dta=this._queue.pop();var url=dta.url;dta.img=new Image();dta.img.onabort=this._onAbort.bind(this,url);dta.img.onerror=this._onError.bind(this,url);dta.img.onload=this._onLoad.bind(this,url);dta.img.src=dta.url;this._loading.push(dta.url);}},_onAbort:function(url){this._changeStatus(url,'aborted');},_onError:function(url){this._changeStatus(url,'error');},_onLoad:function(url){this._changeStatus(url,'loaded');},_changeStatus:function(url,status){var dta=this._images[url];if(!dta)return;dta.status=status;var handler;while(handler=dta.handlers.pop()){if(handler[1])handler[1].call(handler[0],url,dta.status,dta.img);}
this._loading=this._loading.without(dta.url);this.loadNextImage();},_images:{},_loading:[],_queue:[]});require('core');require('views/view');require('mixins/control');require('mixins/inline_editor_delegate');SC.LIST_ITEM_ACTION_CANCEL='sc-list-item-cancel-action';SC.LIST_ITEM_ACTION_REFRESH='sc-list-item-cancel-refresh';SC.LIST_ITEM_ACTION_EJECT='sc-list-item-cancel-eject';SC.ListItemView=SC.View.extend(SC.Control,SC.InlineEditorDelegate,{emptyElement:'<div class="sc-list-item-view sc-collection-item"></div>',content:null,hasContentIcon:NO,hasContentBranch:NO,contentIconKey:null,contentValueKey:null,contentUnreadCountKey:null,contentIsBranchKey:null,isEditing:NO,contentPropertyDidChange:function(){if(this.get('isEditing'))this.discardEditing();this.render();},render:function(){var html=[];var content=this.get('content');var del=this.displayDelegate;if(this.getDelegateProperty(del,'hasContentIcon')){var iconKey=this.getDelegateProperty(del,'contentIconKey');var icon=(iconKey&&content&&content.get)?content.get(iconKey):null;html.push(this.renderIconHtml(icon));}
var labelKey=this.getDelegateProperty(del,'contentValueKey');var label=(labelKey&&content&&content.get)?content.get(labelKey):null;html.push(this.renderLabelHtml(label));var countKey=this.getDelegateProperty(del,'contentUnreadCountKey');var count=(countKey&&content&&content.get)?content.get(countKey):null;if((count!=null)&&(count!=0)){html.push(this.renderCountHtml(count));}
var actionKey=this.getDelegateProperty(del,'listItemActionProperty');var actionClassName=(actionKey&&content&&content.get)?content.get(actionKey):null;if(actionClassName){html.push(this.renderActionHtml(actionClassName));}
this.setClassName('sc-has-action',actionClassName);if(this.getDelegateProperty(del,'hasContentBranch')){var branchKey=this.getDelegateProperty(del,'contentIsBranchKey');var hasBranch=(branchKey&&content&&content.get)?content.get(branchKey):false;html.push(this.renderBranchHtml(hasBranch));this.setClassName('sc-has-branch',true);}else this.setClassName('sc-has-branch',false);html=html.join('');if(html!=this._lastRenderedHtml){this._lastRenderedHtml=html;this.set('innerHTML',html);}},renderIconHtml:function(icon){var html=[];var url=null,className=null;if(icon&&SC.ImageView.valueIsUrl(icon)){url=icon;className='';}else{className=icon;url='/static/sproutcore/en/blank.gif';}
html.push('<img class="sc-icon ');html.push(className||'');html.push('" src="');html.push(url||'/static/sproutcore/en/blank.gif');html.push('" />');html=html.join('');return html;},renderLabelHtml:function(label){var html=[];html.push('<span class="sc-label">');html.push(label||'');html.push('</span>');return html.join('');},findLabelElement:function(){return this.$class('sc-label');},renderCountHtml:function(count){var html=[];html.push('<span class="sc-count"><span class="inner">');html.push(count.toString());html.push('</span></span>');return html.join('');},renderActionHtml:function(actionClassName){var html=[];html.push('<img src="');html.push('/static/sproutcore/en/blank.gif');html.push('" class="sc-action" />');return html.join('');},renderBranchHtml:function(hasBranch){var html=[];html.push('<span class="sc-branch ');html.push(hasBranch?'sc-branch-visible':'sc-branch-hidden');html.push('">&nbsp;</span>');return html.join('');},contentHitTest:function(evt){var del=this.displayDelegate;var labelKey=this.getDelegateProperty(del,'contentValueKey');if(!labelKey)return NO;var el=this.findLabelElement();if(!el)return NO;var cur=Event.element(evt);while(cur&&(cur!=(this.rootElement))&&(cur!=window)){if(cur===el)return YES;cur=cur.parentNode;}
return NO;},beginEditing:function(){if(this.get('isEditing'))return YES;var content=this.get('content');var del=this.displayDelegate;var labelKey=this.getDelegateProperty(del,'contentValueKey');var v=(labelKey&&content&&content.get)?content.get(labelKey):null;var f=this.get('frame');var el=this.findLabelElement();if(!el)return NO;var oldLineHeight=Element.getStyle(el,'lineHeight');var fontSize=parseInt(Element.getStyle(el,'fontSize'),0);var lineHeight=parseInt(oldLineHeight,0);var lineHeightShift=0;if(fontSize&&lineHeight){var targetLineHeight=fontSize*1.5;if(targetLineHeight<lineHeight){Element.setStyle(el,{lineHeight:'1.5'});lineHeightShift=(lineHeight-targetLineHeight)/2;}else oldLineHeight=null;}
f.x+=el.offsetLeft;f.y+=el.offsetTop+lineHeightShift-2;f.height=el.offsetHeight;f.width=(f.width-30-el.offsetLeft);f=this.convertFrameToView(f,null);var ret=SC.InlineTextFieldView.beginEditing({frame:f,exampleElement:el,delegate:this,value:v});if(oldLineHeight)Element.setStyle(el,{lineHeight:oldLineHeight});return ret;},commitEditing:function(){if(!this.get('isEditing'))return YES;return SC.InlineTextFieldView.commitEditing();},discardEditing:function(){if(!this.get('isEditing'))return YES;return SC.InlineTextFieldView.discardEditing();},inlineEditorWillBeginEditing:function(inlineEditor){this.set('isEditing',YES);},inlineEditorDidBeginEditing:function(inlineEditor){var el=this.findLabelElement();this._oldOpacity=Element.getStyle(el,'opacity');Element.setStyle(el,{opacity:0.0});},inlineEditorShouldEndEditing:function(inlineEditor,finalValue){return YES;},inlineEditorDidEndEditing:function(inlineEditor,finalValue){this.set('isEditing',NO);var content=this.get('content');var del=this.displayDelegate;var labelKey=this.getDelegateProperty(del,'contentValueKey');if(labelKey&&content&&content.set){content.set(labelKey,finalValue);}
this._lastRenderedHtml=null;this.render();}});require('foundation/object');SC.Controller=SC.Object.extend({hasChanges:false,context:null,commitChangesImmediately:true,init:function()
{arguments.callee.base.apply(this,arguments);this._contextObserver();},_contextObserver:function()
{if(this.context)
{this.commitChangesImmediately=this.context.commitChangesImmediately;}}.observes('context'),commitChanges:function(){this._commitTimeout=null;var ret=this._canCommitChanges();if(!$ok(ret))return ret;return this._performCommitChanges();},discardChanges:function(){var ret=this._canDiscardChanges();if(!$ok(ret))return ret;return this._performDiscardChanges();},controllerForValue:function(value){var ret=null;switch($type(value)){case T_OBJECT:if(value.kindOf(SC.Collection)){ret=SC.CollectionController;}else ret=SC.ObjectController;break;case T_ARRAY:ret=SC.ArrayController;break;default:ret=null;}
return(ret)?ret.create({content:value,context:this}):value;},editorDidChange:function(editor){if(!editor)editor=this;if(editor!=this){if(!this._dirtyEditors)this._dirtyEditors=SC.Set.create();this._dirtyEditors.add(editor);}else{this._hasLocalChanges=true;}
if(!this.get('hasChanges')){this.set('hasChanges',true);if(this.context){this.context.editorDidChange(this);}else if(this.get('commitChangesImmediately')){if(!this._commitTimeout){this._commitTimeout=this.commitChanges.bind(this).defer();}}}},editorDidClearChanges:function(editor){if(!editor)editor=this;if(editor!=this){if(this._clearingChanges)return;if(this._dirtyEditors)this._dirtyEditors.remove(editor);}else{this._hasLocalChanges=false;}
var hasChanges=!!(this._hasLocalChanges||(this._dirtyEditors&&this._dirtyEditors.length>0));if(this.get('hasChanges')!=hasChanges){this.set('hasChanges',hasChanges);if(this.context)this.context.editorDidClearChanges(editor);}},canCommitChanges:function(){return true;},performCommitChanges:function(){return $error('performCommitChanges is not implemented');},canDiscardChanges:function(){return true;},performDiscardChanges:function(){return $error('performDiscardChanges is not implemented');},_canCommitChanges:function(){if(!this.get('hasChanges'))return false;var ret=true;if(this._dirtyEditors){ret=this._dirtyEditors.invokeWhile(true,'_canCommitChanges');if(!$ok(ret))return ret;}
return this.canCommitChanges();},_performCommitChanges:function(){if(!this.get('hasChanges'))return true;var ret=true;if(this._dirtyEditors){this._clearingChanges=true;ret=this._dirtyEditors.invokeWhile(true,'_performCommitChanges');this._clearingChanges=false;if($ok(ret)){this._dirtyEditors=null;}else return ret;}
ret=this.performCommitChanges();if($ok(ret))this.editorDidClearChanges();return ret;},_canDiscardChanges:function(){if(!this.get('hasChanges'))return false;var ret=true;if(this._dirtyEditors){ret=this._dirtyEditors.invokeWhile(true,'_canDiscardChanges');if(!$ok(ret))return ret;}
return this.canDiscardChanges();},_performDiscardChanges:function(){if(!this.get('hasChanges'))return true;var ret=true;if(this._dirtyEditors){this._clearingChanges=true;ret=this._dirtyEditors.invokeWhile(true,'_performDiscardChanges');this._clearingChanges=false;if($ok(ret)){this._dirtyEditors=null;}else return ret;}
ret=this.performDiscardChanges();if($ok(ret))this.editorDidClearChanges();return ret;}});require('controllers/controller');SC.ObjectController=SC.Controller.extend({content:null,hasNoContent:true,hasSingleContent:false,hasMultipleContent:false,allowsMultipleContent:true,destroy:function(){var content=this.get('content');if(content&&$type(content.destroy)===T_FUNCTION)content.destroy();this.set('content',null);},performCommitChanges:function(){var content=this.get('content');var ret=true;var isArray=false;if(this._isArray(content)){var len=this._lengthFor(content);if(len==0){content=null;}else if(len==1){content=this._objectAt(0,content);}else if(this.get('allowsMultipleContent')){isArray=true;}else content=null;}
if(!this._changes)this._changes={};if(!content){return $error("No Content");}else if(isArray){var loc=this._lengthFor(content);while(--loc>=0){var object=this._objectAt(loc,content);if(!object)continue;if(object.beginPropertyChanges)object.beginPropertyChanges();for(var key in this._changes){if(!this._changes.hasOwnProperty(key))continue;var value=this._changes[key];if(this._isArray(value)){value=this._objectAt(loc,value);}
if(object.set){object.set(key,value);}else object[key]=value;}
if(object.endPropertyChanges)object.endPropertyChanges();if(object.commitChanges)ret=object.commitChanges();}}else{if(content.beginPropertyChanges)content.beginPropertyChanges();for(var key in this._changes){if(!this._changes.hasOwnProperty(key))continue;var oldValue=content.get?content.get(key):content[key];var newValue=this._changes[key];if(oldValue==null&&newValue=='')newValue=null;if(newValue!=oldValue)
{(content.set)?content.set('isDirty',true):(content['isDirty']=true);}
if(content.set){content.set(key,newValue);}else{content[key]=newValue;}}
if(content.endPropertyChanges)content.endPropertyChanges();if(content.commitChanges)ret=content.commitChanges();}
if($ok(ret)){this._changes={};this.editorDidClearChanges();}
return ret;},performDiscardChanges:function(){this._changes={};this._valueControllers={};this.editorDidClearChanges();this.allPropertiesDidChange();return true;},unknownProperty:function(key,value)
{if(key=="content")
{if(!(value===undefined))this[key]=value;return this[key];}
else
{if(!this._changes)this._changes={};if(!this._valueControllers)this._valueControllers={};if(value!==undefined)
{this._changes[key]=value;if(this._valueControllers[key])
{this._valueControllers[key]=null;}
this.propertyWillChange(key+"Controller");this.propertyDidChange(key+"Controller");this.editorDidChange();}
else
{if(key.slice(key.length-10,key.length)=="Controller")
{key=key.slice(0,-10);if(!this._valueControllers[key])
{this._valueControllers[key]=this.controllerForValue(this._getValueForPropertyKey(key));}
value=this._valueControllers[key];}
else
{value=this._getValueForPropertyKey(key);}}
return value;}},_getValueForPropertyKey:function(key)
{var value=this._changes[key];if(value!==undefined)return value;var obj=this.get('content');if(!obj)return null;if(this._isArray(obj))
{var value=[];var len=this._lengthFor(obj);if(len>1)
{if(this.get('allowsMultipleContent')){for(var idx=0;idx<len;idx++){var item=this._objectAt(idx,obj);value.push((item)?((item.get)?item.get(key):item[key]):null);}}else{value=null;}}
else if(len==1)
{obj=this._objectAt(0,obj);value=(obj.get)?obj.get(key):obj[key];}
else
{value=null;}}
else
{value=(obj.get)?obj.get(key):obj[key];}
return value;},_lastPropertyRevision:0,propertyObserver:function(observer,target,key,value,propertyRevision){if(propertyRevision<=this._lastPropertyRevision)return;this._lastPropertyRevision=propertyRevision;if(!this._boundObserver){this._boundObserver=this._contentPropertyObserver.bind(this);}
if(target!=this)return;if((key=='content')&&(value!=this._content)){var f=this._boundObserver;if(this.get('hasChanges')){var er=this.discardChanges();if(!$ok(er))throw(er);}else{this._valueControllers={};}
if(this._content){var objects=Array.from(this._content);var loc=objects.length;while(--loc>=0){var obj=objects[loc];if(obj&&obj.removeObserver)obj.removeObserver('*',f);}}
this._content=value;if(this._content){var objects=Array.from(this._content);var loc=objects.length;while(--loc>=0){var obj=objects[loc];if(obj&&obj.addObserver)obj.addObserver('*',f);}}
var count=0;if(this._content){count=(this._isArray(this._content))?this._lengthFor(this._content):1;};this.beginPropertyChanges();this.set('hasNoContent',count==0);this.set('hasSingleContent',count==1);this.set('hasMultipleContent',count>1);this.allPropertiesDidChange();this.endPropertyChanges();}},_contentPropertyObserver:function(target,key,value){this._changeFromContent=true;if(key=='*'){this.allPropertiesDidChange();}else{this.propertyWillChange(key);this.propertyDidChange(key,value);}
this._changeFromContent=false;},_lengthFor:function(obj){return((obj.get)?obj.get('length'):obj.length)||0;},_objectAt:function(idx,obj){return(obj.objectAt)?obj.objectAt(idx):((obj.get)?obj.get(idx):obj[idx]);},_isArray:function(obj){return($type(obj)==T_ARRAY)||(obj&&obj.objectAt);}});function Animator(options){this.setOptions(options);var _this=this;this.timerDelegate=function(){_this.onTimerEvent();};this.subjects=[];this.target=0;this.state=0;this.lastTime=null;};Animator.prototype={setOptions:function(options){this.options=Animator.applyDefaults({interval:20,duration:400,onComplete:function(){},onStep:function(){},transition:Animator.tx.easeInOut},options);},seekTo:function(to){this.seekFromTo(this.state,to);},seekFromTo:function(from,to){this.target=Math.max(0,Math.min(1,to));this.state=Math.max(0,Math.min(1,from));this.lastTime=new Date().getTime();if(!this.intervalId){this.intervalId=SC.Timer.schedule({target:this,action:this.timerDelegate,interval:this.options.interval,repeats:YES});}},jumpTo:function(to){this.target=this.state=Math.max(0,Math.min(1,to));this.propagate();},toggle:function(){this.seekTo(1-this.target);},addSubject:function(subject){this.subjects[this.subjects.length]=subject;return this;},clearSubjects:function(){this.subjects=[];},propagate:function(){var value=this.options.transition(this.state);for(var i=0;i<this.subjects.length;i++){if(this.subjects[i].setState){this.subjects[i].setState(value);}else{this.subjects[i](value);}}},onTimerEvent:function(){var now=new Date().getTime();var timePassed=now-this.lastTime;this.lastTime=now;var movement=(timePassed/this.options.duration)*(this.state<this.target?1:-1);if(Math.abs(movement)>=Math.abs(this.state-this.target)){this.state=this.target;}else{this.state+=movement;}
try{this.propagate();}finally{this.options.onStep.call(this);if(this.target==this.state){this.intervalId.invalidate();this.intervalId=null;this.options.onComplete.call(this);}}},play:function(){this.seekFromTo(0,1);},reverse:function(){this.seekFromTo(1,0);},inspect:function(){var str="#<Animator:\n";for(var i=0;i<this.subjects.length;i++){str+=this.subjects[i].inspect();}
str+=">";return str;}};Animator.applyDefaults=function(defaults,prefs){prefs=prefs||{};var prop,result={};for(prop in defaults)result[prop]=prefs[prop]!==undefined?prefs[prop]:defaults[prop];return result;};Animator.makeArray=function(o){if(o==null)return[];if(!o.length)return[o];var result=[];for(var i=0;i<o.length;i++)result[i]=o[i];return result;};Animator.camelize=function(string){var oStringList=string.split('-');if(oStringList.length==1)return oStringList[0];var camelizedString=string.indexOf('-')==0?oStringList[0].charAt(0).toUpperCase()+oStringList[0].substring(1):oStringList[0];for(var i=1,len=oStringList.length;i<len;i++){var s=oStringList[i];camelizedString+=s.charAt(0).toUpperCase()+s.substring(1);}
return camelizedString;};Animator.apply=function(el,style,options){if(style instanceof Array){return new Animator(options).addSubject(new CSSStyleSubject(el,style[0],style[1]));}
return new Animator(options).addSubject(new CSSStyleSubject(el,style));};Animator.makeEaseIn=function(a){return function(state){return Math.pow(state,a*2);};};Animator.makeEaseOut=function(a){return function(state){return 1-Math.pow(1-state,a*2);};};Animator.makeElastic=function(bounces){return function(state){state=Animator.tx.easeInOut(state);return((1-Math.cos(state*Math.PI*bounces))*(1-state))+state;};};Animator.makeADSR=function(attackEnd,decayEnd,sustainEnd,sustainLevel){if(sustainLevel==null)sustainLevel=0.5;return function(state){if(state<attackEnd){return state/attackEnd;}
if(state<decayEnd){return 1-((state-attackEnd)/(decayEnd-attackEnd)*(1-sustainLevel));}
if(state<sustainEnd){return sustainLevel;}
return sustainLevel*(1-((state-sustainEnd)/(1-sustainEnd)));};};Animator.makeBounce=function(bounces){var fn=Animator.makeElastic(bounces);return function(state){state=fn(state);return state<=1?state:2-state;};};Animator.tx={easeInOut:function(pos){return((-Math.cos(pos*Math.PI)/2)+0.5);},linear:function(x){return x;},easeIn:Animator.makeEaseIn(1.5),easeOut:Animator.makeEaseOut(1.5),strongEaseIn:Animator.makeEaseIn(2.5),strongEaseOut:Animator.makeEaseOut(2.5),elastic:Animator.makeElastic(1),veryElastic:Animator.makeElastic(3),bouncy:Animator.makeBounce(1),veryBouncy:Animator.makeBounce(3)};function NumericalStyleSubject(els,property,from,to,units){this.els=Animator.makeArray(els);if(property=='opacity'&&window.ActiveXObject){this.property='filter';}else{this.property=Animator.camelize(property);}
this.from=parseFloat(from);this.to=parseFloat(to);this.units=units!=null?units:'px';};NumericalStyleSubject.prototype={setState:function(state){var style=this.getStyle(state);var visibility=(this.property=='opacity'&&state==0)?'hidden':'';var j=0;for(var i=0;i<this.els.length;i++){try{this.els[i].style[this.property]=style;}catch(e){if(this.property!='fontWeight')throw e;}
if(j++>20)return;}},getStyle:function(state){state=this.from+((this.to-this.from)*state);if(this.property=='filter')return"alpha(opacity="+Math.round(state*100)+")";if(this.property=='opacity')return state;return Math.round(state)+this.units;},inspect:function(){return"\t"+this.property+"("+this.from+this.units+" to "+this.to+this.units+")\n";}};function ColorStyleSubject(els,property,from,to){this.els=Animator.makeArray(els);this.property=Animator.camelize(property);this.to=this.expandColor(to);this.from=this.expandColor(from);this.origFrom=from;this.origTo=to;};ColorStyleSubject.prototype={expandColor:function(color){var hexColor,red,green,blue;hexColor=ColorStyleSubject.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];}
if(window.DEBUG){alert("Invalid colour: '"+color+"'");}},getValueForState:function(color,state){return Math.round(this.from[color]+((this.to[color]-this.from[color])*state));},setState:function(state){var color='#'
+ColorStyleSubject.toColorPart(this.getValueForState(0,state))
+ColorStyleSubject.toColorPart(this.getValueForState(1,state))
+ColorStyleSubject.toColorPart(this.getValueForState(2,state));for(var i=0;i<this.els.length;i++){this.els[i].style[this.property]=color;}},inspect:function(){return"\t"+this.property+"("+this.origFrom+" to "+this.origTo+")\n";}};ColorStyleSubject.parseColor=function(string){var color='#',match;if(match=ColorStyleSubject.parseColor.rgbRe.exec(string)){var part;for(var i=1;i<=3;i++){part=Math.max(0,Math.min(255,parseInt(match[i],0)));color+=ColorStyleSubject.toColorPart(part);}
return color;}
if(match=ColorStyleSubject.parseColor.hexRe.exec(string)){if(match[1].length==3){for(var i=0;i<3;i++){color+=match[1].charAt(i)+match[1].charAt(i);}
return color;}
return'#'+match[1];}
return false;};ColorStyleSubject.toColorPart=function(number){if(number>255)number=255;var digits=number.toString(16);if(number<16)return'0'+digits;return digits;};ColorStyleSubject.parseColor.rgbRe=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;ColorStyleSubject.parseColor.hexRe=/^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function DiscreteStyleSubject(els,property,from,to,threshold){this.els=Animator.makeArray(els);this.property=Animator.camelize(property);this.from=from;this.to=to;this.threshold=threshold||0.5;};DiscreteStyleSubject.prototype={setState:function(state){var j=0;for(var i=0;i<this.els.length;i++){this.els[i].style[this.property]=state<=this.threshold?this.from:this.to;}},inspect:function(){return"\t"+this.property+"("+this.from+" to "+this.to+" @ "+this.threshold+")\n";}};function CSSStyleSubject(els,style1,style2){els=Animator.makeArray(els);this.subjects=[];if(els.length==0)return;var prop,toStyle,fromStyle;if(style2){fromStyle=this.parseStyle(style1,els[0]);toStyle=this.parseStyle(style2,els[0]);}else{toStyle=this.parseStyle(style1,els[0]);fromStyle={};for(prop in toStyle){fromStyle[prop]=CSSStyleSubject.getStyle(els[0],prop);}}
var prop;for(prop in fromStyle){if(fromStyle[prop]==toStyle[prop]){delete fromStyle[prop];delete toStyle[prop];}}
var prop,units,match,type,from,to;for(prop in fromStyle){var fromProp=String(fromStyle[prop]);var toProp=String(toStyle[prop]);if(toStyle[prop]==null){if(window.DEBUG)alert("No to style provided for '"+prop+'"');continue;}
if(from=ColorStyleSubject.parseColor(fromProp)){to=ColorStyleSubject.parseColor(toProp);type=ColorStyleSubject;}else if(fromProp.match(CSSStyleSubject.numericalRe)&&toProp.match(CSSStyleSubject.numericalRe)){from=parseFloat(fromProp);to=parseFloat(toProp);type=NumericalStyleSubject;match=CSSStyleSubject.numericalRe.exec(fromProp);var reResult=CSSStyleSubject.numericalRe.exec(toProp);if(match[1]!=null){units=match[1];}else if(reResult[1]!=null){units=reResult[1];}else{units=reResult;}}else if(fromProp.match(CSSStyleSubject.discreteRe)&&toProp.match(CSSStyleSubject.discreteRe)){from=fromProp;to=toProp;type=DiscreteStyleSubject;units=0;}else{if(window.DEBUG){alert("Unrecognised format for value of "
+prop+": '"+fromStyle[prop]+"'");}
continue;}
this.subjects[this.subjects.length]=new type(els,prop,from,to,units);}};CSSStyleSubject.prototype={parseStyle:function(style,el){var rtn={};if(style.indexOf(":")!=-1){var styles=style.split(";");for(var i=0;i<styles.length;i++){var parts=CSSStyleSubject.ruleRe.exec(styles[i]);if(parts){rtn[parts[1]]=parts[2];}}}
else{var prop,value,oldClass;oldClass=el.className;el.className=style;for(var i=0;i<CSSStyleSubject.cssProperties.length;i++){prop=CSSStyleSubject.cssProperties[i];value=CSSStyleSubject.getStyle(el,prop);if(value!=null){rtn[prop]=value;}}
el.className=oldClass;}
return rtn;},setState:function(state){for(var i=0;i<this.subjects.length;i++){this.subjects[i].setState(state);}},inspect:function(){var str="";for(var i=0;i<this.subjects.length;i++){str+=this.subjects[i].inspect();}
return str;}};CSSStyleSubject.getStyle=function(el,property){var style;if(document.defaultView&&document.defaultView.getComputedStyle){style=document.defaultView.getComputedStyle(el,"").getPropertyValue(property);if(style){return style;}}
property=Animator.camelize(property);if(el.currentStyle){style=el.currentStyle[property];}
return style||el.style[property];};CSSStyleSubject.ruleRe=/^\s*([a-zA-Z\-]+)\s*:\s*(\S(.+\S)?)\s*$/;CSSStyleSubject.numericalRe=/^-?\d+(?:\.\d+)?(%|[a-zA-Z]{2})?$/;CSSStyleSubject.discreteRe=/^\w+$/;CSSStyleSubject.cssProperties=['azimuth','background','background-attachment','background-color','background-image','background-position','background-repeat','border-collapse','border-color','border-spacing','border-style','border-top','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','border-top-width','border-right-width','border-bottom-width','border-left-width','border-width','bottom','clear','clip','color','content','cursor','direction','display','elevation','empty-cells','css-float','font','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','height','left','letter-spacing','line-height','list-style','list-style-image','list-style-position','list-style-type','margin','margin-top','margin-right','margin-bottom','margin-left','max-height','max-width','min-height','min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding','padding-top','padding-right','padding-bottom','padding-left','pause','position','right','size','table-layout','text-align','text-decoration','text-indent','text-shadow','text-transform','top','vertical-align','visibility','white-space','width','word-spacing','z-index','opacity','outline-offset','overflow-x','overflow-y'];function AnimatorChain(animators,options){this.animators=animators;this.setOptions(options);for(var i=0;i<this.animators.length;i++){this.listenTo(this.animators[i]);}
this.forwards=false;this.current=0;};AnimatorChain.prototype={setOptions:function(options){this.options=Animator.applyDefaults({resetOnPlay:true},options);},play:function(){this.forwards=true;this.current=-1;if(this.options.resetOnPlay){for(var i=0;i<this.animators.length;i++){this.animators[i].jumpTo(0);}}
this.advance();},reverse:function(){this.forwards=false;this.current=this.animators.length;if(this.options.resetOnPlay){for(var i=0;i<this.animators.length;i++){this.animators[i].jumpTo(1);}}
this.advance();},toggle:function(){if(this.forwards){this.seekTo(0);}else{this.seekTo(1);}},listenTo:function(animator){var oldOnComplete=animator.options.onComplete;var _this=this;animator.options.onComplete=function(){if(oldOnComplete)oldOnComplete.call(animator);_this.advance();};},advance:function(){if(this.forwards){if(this.animators[this.current+1]==null)return;this.current++;this.animators[this.current].play();}else{if(this.animators[this.current-1]==null)return;this.current--;this.animators[this.current].reverse();}},seekTo:function(target){if(target<=0){this.forwards=false;this.animators[this.current].seekTo(0);}else{this.forwards=true;this.animators[this.current].seekTo(1);}}};function Accordion(options){this.setOptions(options);var selected=this.options.initialSection,current;if(this.options.rememberance){current=document.location.hash.substring(1);}
this.rememberanceTexts=[];this.ans=[];var _this=this;for(var i=0;i<this.options.sections.length;i++){var el=this.options.sections[i];var an=new Animator(this.options.animatorOptions);var from=this.options.from+(this.options.shift*i);var to=this.options.to+(this.options.shift*i);an.addSubject(new NumericalStyleSubject(el,this.options.property,from,to,this.options.units));an.jumpTo(0);var activator=this.options.getActivator(el);activator.index=i;activator.onclick=function(){_this.show(this.index);};this.ans[this.ans.length]=an;this.rememberanceTexts[i]=activator.innerHTML.replace(/\s/g,"");if(this.rememberanceTexts[i]===current){selected=i;}}
this.show(selected);};Accordion.prototype={setOptions:function(options){this.options=Object.extend({sections:null,getActivator:function(el){return document.getElementById(el.getAttribute("activator"));},shift:0,initialSection:0,rememberance:true,animatorOptions:{}},options||{});},show:function(section){for(var i=0;i<this.ans.length;i++){this.ans[i].seekTo(i>section?1:0);}
if(this.options.rememberance){document.location.hash=this.rememberanceTexts[section];}}};require('validators/validator');SC.Validator.Email=SC.Validator.extend({validate:function(form,field){return(field.get('fieldValue')||'').match(/.+@.+\...+/);},validateError:function(form,field){var label=field.get('errorLabel')||'Field';return $error("Invalid.Email(%@)".loc(label),label);}});SC.Validator.EmailOrEmpty=SC.Validator.Email.extend({validate:function(form,field){var value=field.get('fieldValue');return(value&&value.length>0)?value.match(/.+@.+\...+/):true;}});if(!Object.toJSONString){Array.prototype.toJSONString=function(){var a=['['],b,i,l=this.length,v;function p(s){if(b){a.push(',');}
a.push(s);b=true;}
for(i=0;i<l;i+=1){v=this[i];switch(typeof v){case'object':if(v){if(typeof v.toJSONString==='function'){p(v.toJSONString());}else p(Object.toJSONString(v));}else{p("null");}
break;case'string':case'number':case'boolean':p(v.toJSONString());}}
a.push(']');return a.join('');};Boolean.prototype.toJSONString=function(){return String(this);};Date.prototype.toJSONString=function(){function f(n){return n<10?'0'+n:n;}
return'"'+this.getFullYear()+'-'+
f(this.getMonth()+1)+'-'+
f(this.getDate())+'T'+
f(this.getHours())+':'+
f(this.getMinutes())+':'+
f(this.getSeconds())+'"';};Number.prototype.toJSONString=function(){return isFinite(this)?String(this):"null";};Object.toJSONString=function(object){var a=['{'],b,k,v;function p(s){if(b){a.push(',');}
a.push(k.toJSONString(),':',s);b=true;}
for(k in object){if(object.hasOwnProperty(k)){v=object[k];switch(typeof v){case'object':if(v){if(typeof v.toJSONString==='function'){p(v.toJSONString());}else p(Object.toJSONString(v));}else{p("null");}
break;case'string':case'number':case'boolean':p(v.toJSONString());}}}
a.push('}');return a.join('');};(function(s){var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};s.parseJSON=function(filter){try{if(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)){var j=eval('('+this+')');if(typeof filter==='function'){function walk(k,v){if(v&&typeof v==='object'){for(var i in v){if(v.hasOwnProperty(i)){v[i]=walk(i,v[i]);}}}
return filter(k,v);}
j=walk('',j);}
return j;}}catch(e){}
throw new SyntaxError("parseJSON");};s.toJSONString=function(){if(/["\\\x00-\x1f]/.test(this)){return'"'+this.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c;}
c=b.charCodeAt();return'\\u00'+
Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"';}
return'"'+this+'"';};})(String.prototype);}
require('core');SC.Server=SC.Object.extend({prefix:null,urlFormat:'/%@/%@',preload:function(clientData){if((!clientData)||(clientData.size==0))return;this.refreshRecordsWithData(clientData,SC.Record,null,false);},request:function(resource,verb,ids,params,method){if(!params)params={};var opts={};var onSuccess=params.onSuccess;delete params.onSuccess;var onNotModified=params.onNotModified;delete params.onNotModified;var onFailure=params.onFailure;delete params.onFailure;var context=params.requestContext;delete params.requestContext;var cacheCode=params.cacheCode;delete params.cacheCode;var idPart='';if(ids)if(ids.length>1){params.ids=[ids].flatten().join(',');}else if(ids.length==1){idPart='/'+ids[0];}
var parameters=this._toQueryString(params);if(parameters&&parameters.length>0)opts.parameters=parameters;if(cacheCode)opts.requestHeaders=['Sproutit-Cache',cacheCode];opts.method=method||'get';var url=this.urlFormat.format(resource,verb)+idPart;var request=null;opts.onSuccess=function(transport){var cacheCode=request.getHeader('Last-Modified');if((transport.status=='200')&&(transport.responseText=='304 Not Modified')){if(onNotModified)onNotModified(transport.status,transport,cacheCode,context);}else{if(onSuccess)onSuccess(transport.status,transport,cacheCode,context);}};opts.onFailure=function(transport){var cacheCode=request.getHeader('Last-Modified');if(onFailure)onFailure(transport.status,transport,cacheCode,context);};console.log('REQUEST: %@'.fmt(url));request=new Ajax.Request(url,opts);},listFor:function(opts){var recordType=opts.recordType;var resource=recordType.resourceURL();if(!resource)return false;var order=opts.order||'id';if(!(order instanceof Array))order=[order];order=order.map(function(str){return str.decamelize();}).join(',');params={};if(opts.conditions){var conditions=this._decamelizeData(opts.conditions);for(var key in conditions){params[key]=conditions[key];}}
params.requestContext=opts;params.onSuccess=this._listSuccess.bind(this);params.onNotModified=this._listNotModified.bind(this);params.onFailure=this._listFailure.bind(this);if(opts.cacheCode)params.cacheCode=opts.cacheCode;if(opts.offset)params.offset=opts.offset;if(opts.limit)params.limit=opts.limit;if(order)params.order=order;this.request(resource,'list',null,params);},_listSuccess:function(status,transport,cacheCode,context){var json=eval('json='+transport.responseText);if(!json){console.log('invalid json!');return;}
if(json.records){this.refreshRecordsWithData(json.records,context.recordType,cacheCode,false);}
var recs=(json.ids)?json.ids.map(function(guid){return SC.Store.getRecordFor(guid,context.recordType);}):[];if(context.callback)context.callback(recs,json.count,cacheCode);},_listNotModified:function(status,transport,cacheCode,context){if(context.callback)context.callback(null,null,null);},_listFailure:function(status,transport,cacheCode,records){console.log('listFailed!');},createRecords:function(records){if(!records||records.length==0)return;records=this._recordsByResource(records);for(var resource in records){if(resource=='*')continue;var curRecords=records[resource];var server=this;var context={};var data=curRecords.map(function(rec){var recData=server._decamelizeData(rec.getPropertyData());recData._guid=rec._guid;context[rec._guid]=rec;rec.set('newRecord',false);return recData;});this.request(resource,'create',null,{requestContext:context,onSuccess:this._createSuccess.bind(this),onFailure:this._createFailure.bind(this),records:data},'post');}},_createSuccess:function(status,transport,cacheCode,context){var json=eval('json='+transport.responseText);if(!(json instanceof Array))json=[json];if(!context)context={};json.each(function(data){var guid=data._guid;var rec=(guid)?context[guid]:null;if(rec){var pk=rec.get('primaryKey');var dataKey=(pk=='guid')?'id':pk.decamelize().toLowerCase().replace(/\-/g,'_');rec.set(pk,data[dataKey]);}});this.refreshRecordsWithData(json,context._recordType,cacheCode,true);},_createFailure:function(status,transport,cacheCode,records){console.log('createFailed!');},refreshRecords:function(records){if(!records||records.length==0)return;records=this._recordsByResource(records);for(var resource in records){if(resource=='*')continue;var curRecords=records[resource];var cacheCode=null;var ids=[];var context={};var primaryKey=curRecords[0].get('primaryKey');curRecords.each(function(r){cacheCode=cacheCode||r._cacheCode;var key=r.get(primaryKey);if(key){ids.push(key);context[key]=r;}});context._recordType=curRecords[0].recordType;this.request(resource,'show',ids,{requestContext:context,cacheCode:((cacheCode=='')?null:cacheCode),onSuccess:this._refreshSuccess.bind(this),onFailure:this._refreshFailure.bind(this)});}},_refreshSuccess:function(status,transport,cacheCode,context){var json=eval('json='+transport.responseText);if(!(json instanceof Array))json=[json];this.refreshRecordsWithData(json,context._recordType,cacheCode,true);},_refreshFailure:function(status,transport,cacheCode,records){console.log('refreshFailed!');},commitRecords:function(records){if(!records||records.length==0)return;records=this._recordsByResource(records);for(var resource in records){if(resource=='*')continue;var curRecords=records[resource];var server=this;var data=curRecords.map(function(rec){return server._decamelizeData(rec.getPropertyData());});this.request(resource,'update',null,{requestContext:records,onSuccess:this._commitSuccess.bind(this),onFailure:this._commitFailure.bind(this),records:data},'post');}},_commitSuccess:function(status,transport,cacheCode,context){var json=eval('json='+transport.responseText);if(!(json instanceof Array))json=[json];this.refreshRecordsWithData(json,context._recordType,cacheCode,true);},_commitFailure:function(status,transport,cacheCode,records){console.log('commitFailed!');},destroyRecords:function(records){if(!records||records.length==0)return;records=this._recordsByResource(records);for(var resource in records){var curRecords=records[resource];if(resource=='*'){curRecords.each(function(rec){rec.set('isDeleted',true);SC.Store.removeRecord(rec);});continue;}
var ids=[];var key;var primaryKey=curRecords[0].get('primaryKey');curRecords.each(function(rec){if((key=rec.get(primaryKey))&&(!rec.get('newRecord'))){ids.push(key);}
rec.set('isDeleted',true);SC.Store.removeRecord(rec);});if(ids&&ids.length>0)this.request(resource,'destroy',ids,{requestContext:records,onSuccess:this._destroySuccess.bind(this),onFailure:this._destroyFailure.bind(this)},'post');}},_destroySuccess:function(status,transport,cacheCode,records){console.log('destroySuccess!');},_destroyFailure:function(status,transport,cacheCode,records){console.log('destroyFailed!');},refreshRecordsWithData:function(dataAry,recordType,cacheCode,loaded){var server=this;dataAry=dataAry.map(function(data){data=server._camelizeData(data);if(data.id){data.guid=data.id;delete data.id;}
if(data.type){var recordName=data.type.capitalize();if(server.prefix)for(var prefixLoc=0;prefixLoc<server.prefix.length;prefixLoc++){var namespace=window[server.prefix[prefixLoc]];if(namespace)data.recordType=namespace[recordName];if(data.recordType)break;}else data.recordType=window[recordName];if(!data.recordType)console.log('skipping undefined recordType:'+recordName);}else data.recordType=recordType;if(!data.recordType)return null;return data;}).compact();SC.Store.updateRecords(dataAry,server,recordType,loaded);},_recordsByResource:function(records){var ret={};records.each(function(rec){var recs=ret[rec.resourceURL||'*']||[];recs.push(rec);ret[rec.resourceURL||'*']=recs;});return ret;},_camelizeData:function(data){if(data==null)return data;var that=this;if(data instanceof Array)return data.map(function(d){return that._camelizeData(d);});if(typeof(data)=="object"){var ret={};for(var key in data){var value=that._camelizeData(data[key]);if(key=='id')key='guid';ret[key.replace(/_/g,'-').camelize()]=value;}
return ret;}
return data;},_decamelizeData:function(data){if(data==null)return data;var that=this;if(data instanceof Array)return data.map(function(d){return that._decamelizeData(d);});if(typeof(data)=="object"){var ret={};for(var key in data){var value=that._decamelizeData(data[key]);if(key=='guid')key='id';ret[key.decamelize()]=value;}
return ret;}
return data;},_toQueryString:function(params,rootKey){if(params==null){return rootKey+'=';}else if(params instanceof Array){var ret=[];for(var loc=0;loc<params.length;loc++){var key=(rootKey)?(rootKey+'['+loc+']'):loc;ret.push(this._toQueryString(params[loc],key));}
return ret.join('&');}else if(typeof(params)=="object"){var ret=[];for(var cur in params){var key=(rootKey)?(rootKey+'['+cur+']'):cur;ret.push(this._toQueryString(params[cur],key));}
return ret.join('&');}else return[rootKey,params].join('=');}});require('views/button/button');SC.CheckboxView=SC.ButtonView.extend({emptyElement:'<a href="javascript:;" class="sc-checkbox-view sc-button-view button checkbox"><img src="%@" class="button" /><span class="label"></span></a>'.fmt('/static/sproutcore/en/blank.gif'),buttonBehavior:SC.TOGGLE_BEHAVIOR});SC.SelectionSupport={updateSelectionAfterContentChange:function(){var objects=Array.from(this.get('arrangedObjects'));var currentSelection=Array.from(this.get('selection'));var sel=[];var max=currentSelection.get('length');if(this.get('allowsSelection')){for(var idx=0;idx<max;idx++){var obj=currentSelection.objectAt(idx);if(objects.indexOf(obj)>=0)sel.push(obj);}}
var selectionLength=sel.get('length');if((selectionLength>1)&&!this.get('allowsMultipleSelection')){sel=[sel.objectAt(0)];}
if((selectionLength==0)&&!this.get('allowsEmptySelection')){if(objects.get('length')>0)sel=[objects.objectAt(0)];}
this.set('selection',sel);},arrangedObjects:function(){return this;}.property(),selection:function(key,value)
{if(value!==undefined){value=Array.from(value);var allowsSelection=this.get('allowsSelection');var allowsEmptySelection=this.get('allowsEmptySelection');var allowsMultipleSelection=this.get('allowsMultipleSelection');if(!allowsSelection)return this._selection;switch(value.get('length'))
{case 0:if(!allowsEmptySelection){var objects=this.get('arrangedObjects');if(objects.get('length')>0)value=[objects.objectAt(0)];}
this._selection=value;break;case 1:this._selection=value;break;default:this._selection=allowsMultipleSelection?value:this._selection;break;}}
return this._selection;}.property(),allowsSelection:true,allowsMultipleSelection:true,allowsEmptySelection:true};require('controllers/controller');require('mixins/array');require('mixins/selection_support');require('foundation/binding');SC.ArrayController=SC.Controller.extend(SC.Array,SC.SelectionSupport,{useControllersForContent:NO,arrangedObjects:function(){return this;}.property('content'),content:null,contentBindingDefault:SC.Binding.Multiple,destroyOnRemoval:NO,_contentObserver:function(){var content=this.get('content');if(SC.isEqual(content,this._content))return;if(!this._boundContentPropertyObserver){this._boundContentPropertyObserver=this._contentPropertyObserver.bind(this);}
var func=this._boundContentPropertyObserver;if(this._content&&this._content.removeObserver)this._content.removeObserver('[]',func);if(content&&content.addObserver)content.addObserver('[]',func);this._content=content;this._contentPropertyRevision=null;var rev=(content)?content.propertyRevision:-1;this._contentPropertyObserver(this,'[]',content,rev);}.observes('content'),_contentPropertyObserver:function(target,key,value,rev){if(!this._updatingContent&&(!rev||(rev!=this._contentPropertyRevision))){this._contentPropertyRevision=rev;this._updatingContent=true;this.beginPropertyChanges();this.contentCloneReset();this.arrayContentDidChange();this.notifyPropertyChange('length');this.updateSelectionAfterContentChange();this.endPropertyChanges();this._updatingContent=false;}},contentClone:null,contentCloneReset:function(){this._changelog=[];this.set('contentClone',null);},replace:function(idx,amt,objects){var content=this.get('content');var copyIdx=objects.length;var sourceObjects=[];while(--copyIdx>=0)sourceObjects[copyIdx]=this._sourceObjectFor(objects[copyIdx]);var contentClone=this.get('contentClone');if(!contentClone){this.set('contentClone',contentClone=content.clone());}
if(this.get('destroyOnRemoval')){if(!this._deletions)this._deletions=[];for(var i=0;i<amt;i++){this._deletions.push(content.objectAt(idx+i));}}
if(!this._changelog)this._changelog=[];this._changelog.push({idx:idx,amt:amt,objects:sourceObjects});contentClone.replace(idx,amt,sourceObjects);this.editorDidChange();this.arrayContentDidChange();this.updateSelectionAfterContentChange();return this;},objectAt:function(idx){var obj=this._getSourceContent();obj=(obj&&obj.objectAt)?obj.objectAt(idx):null;return this._objectControllerFor(obj);},length:function(key,value){var ret=this._getSourceContent();return(ret&&ret.get)?(ret.get('length')||0):0;}.property(),indexOf:function(obj){return this._getSourceContent().indexOf(this._sourceObjectFor(obj));},_getSourceContent:function(){return this.get('contentClone')||this.get('content')||[];},performCommitChanges:function()
{var content=this.get('content');var ret=true;if(!content){return $error("No Content");}
if(content.beginPropertyChanges)content.beginPropertyChanges();var changelog=this._changelog||[];for(var idx=0;idx<changelog.length;idx++){var change=changelog[idx];content.replace(change.idx,change.amt,change.objects);}
this._changelog=[];if(this.get('destroyOnRemoval')&&this._deletions&&this._deletions.length>0){var idx=this._deletions.length;while(--idx>=0){var obj=this._deletions[idx];if(obj&&obj.destroy&&(content.indexOf(obj)<0)){obj.destroy();}}
this._deletions=[];}
if(content.endPropertyChanges)content.endPropertyChanges();if(content.commitChanges)ret=content.commitChanges();if($ok(ret)){this.contentCloneReset();this.editorDidClearChanges();}
return ret;},performDiscardChanges:function()
{this.contentCloneReset();this.editorDidClearChanges();return true;},_objectControllerFor:function(obj){if(!this.useControllersForContent)return obj;var controllers=this._objControllers=this._objControllers||{};var guid=SC.getGUID(obj);var ret=controllers[guid];if(!ret){ret=controllers[guid]=this.controllerForValue(obj);if(ret)ret.__isArrayController=true;}
return ret;},_sourceObjectFor:function(obj){return(obj&&obj.kindOf&&obj.kindOf(SC.Controller))?obj.get('content'):obj;},init:function(){arguments.callee.base.apply(this,arguments);if(this.get('content'))this._contentObserver();}});require('foundation/object');SC.Record=SC.Object.extend({properties:['guid'],primaryKey:'guid',newRecord:false,changeCount:0,isDeleted:false,resourceURL:null,dataSource:SC.Store,init:function()
{arguments.callee.base.apply(this,arguments);var primaryKeyName=this.get('primaryKey');if(!this.get(primaryKeyName))
{var value=this.generateTempPrimaryKey();if(value)this.set(primaryKeyName,value);}},generateTempPrimaryKey:function()
{return"@"+SC.getGUID(this);},refresh:function(){if(!this.get('newRecord'))this.dataSource.refreshRecords([this]);},commit:function(){if(this.get('newRecord')){this.dataSource.createRecords([this]);}else{this.dataSource.commitRecords([this]);}},destroy:function(){this.dataSource.destroyRecords([this]);},readAttribute:function(key){if(!this._cachedAttributes)this._cachedAttributes={};var ret=this._cachedAttributes[key];if(ret===undefined){var attr=this._attributes;ret=(attr)?attr[key]:undefined;if(ret!==undefined){var recordType=this._getRecordType(key+'Type');ret=this._propertyFromAttribute(ret,recordType);}
this._cachedAttributes[key]=ret;}
return(ret===undefined)?null:ret;},writeAttribute:function(key,value){var recordType=this._getRecordType(key+'Type');var ret=this._attributeFromProperty(value,recordType);if(!this._attributes)this._attributes={};this._attributes[key]=ret;if(this._cachedAttributes)delete this._cachedAttributes[key];this.incrementProperty('changeCount');if(SC.Store)SC.Store.recordDidChange(this);return value;},updateAttributes:function(newAttrs,replace,isLoaded){var changed=false;if(this._attributes&&(replace!==true)){for(var key in newAttrs){if(!newAttrs.hasOwnProperty(key))continue;if(!changed)changed=(this._attributes[key]!=newAttrs[key]);this._attributes[key]=newAttrs[key];}}else{this._attributes=newAttrs;changed=true;}
this._cachedAttributes={};if(changed){this.beginPropertyChanges();this.set('changeCount',0);this.set('isLoaded',isLoaded);this.allPropertiesDidChange();this.endPropertyChanges();if(SC.Store)SC.Store.recordDidChange(this);}},attributes:function(){return Object.clone(this._attributes);}.property(),unknownProperty:function(key,value)
{if(value!==undefined){var primaryKeyName=this.get('primaryKey');if(key==primaryKeyName)
{var oldPrimaryKey=this.get(key);var newPrimaryKey=value;}
this.writeAttribute(key,value);if((key==primaryKeyName)&&oldPrimaryKey)SC.Store.relocateRecord(oldPrimaryKey,newPrimaryKey,this);}else{value=this.readAttribute(key);}
return value;},_attributeFromProperty:function(value,recordType){if(value&&value instanceof Array){var that=this;return value.map(function(v){return that._attributeFromProperty(v,recordType);});}else{var typeConverter=this._pickTypeConverter(recordType);if(typeConverter)return typeConverter(value,'out');if(recordType){return(value)?value.get(recordType.primaryKey()):null;}else return value;}},_propertyFromAttribute:function(value,recordType){if(value&&value instanceof Array){var that=this;return value.map(function(v){return that._propertyFromAttribute(v,recordType);});}else{var typeConverter=this._pickTypeConverter(recordType);if(typeConverter)return typeConverter(value,'in');if(recordType){if(!value)return null;return SC.Store.getRecordFor(value,recordType);}else return value;}},_getRecordType:function(recordTypeKey){var type=this[recordTypeKey];if(type&&(typeof(type)=="string")){type=eval(type);if(type)this[recordTypeKey]=type;}
return type;},valueForSortKey:function(key){return this.get(key);},compareTo:function(object,orderBy){if(!orderBy)orderBy=[this.get('primaryKey')];var ret=SC.Record.SORT_SAME;var loc;for(loc=0;(ret==SC.Record.SORT_SAME&&loc<orderBy.length);loc++){var key=orderBy[loc];var asc=true;if(key.match(/ DESC$/)){asc=false;key=key.slice(0,-5);}else if(key.match(/ ASC$/)){asc=true;key=key.slice(0,-4);}
var keys=key.split('.');key=keys.shift();var a=this.valueForSortKey(key);var b=object.valueForSortKey(key);a=this._comparableValueFor(a,keys);b=this._comparableValueFor(b,keys);if(asc){ret=(a<b)?SC.Record.SORT_BEFORE:((a>b)?SC.Record.SORT_AFTER:SC.Record.SORT_SAME);}else{ret=(a>b)?SC.Record.SORT_BEFORE:((a<b)?SC.Record.SORT_AFTER:SC.Record.SORT_SAME);}}
return ret;},_comparableValueFor:function(value,keys){if(keys&&keys.length>0){var key;var loc=0;while(value&&(loc<keys.length)){key=keys[loc];value=(value.get)?value.get(key):value[key];loc++;}}else value=(value&&value._guid)?value._guid:value;return value;},matchConditions:function(conditions){for(var key in conditions){var value=conditions[key];if(value instanceof Array){var loc=value.length;var isMatch=false;while(--loc>=0){if(this.matchCondition(key,value[loc]))isMatch=true;}
if(!isMatch)return false;}else if(!this.matchCondition(key,value))return false;}
return true;},matchCondition:function(key,value){var recValue=this.get(key);var isMatch;var loc;if(value&&value.primaryKey){if($type(recValue)===T_ARRAY){loc=recValue.length;while(--loc>=0){if(recValue===value)return true;}}else return recValue===value;}else{if($type(recValue)===T_ARRAY){loc=recValue.length;while(--loc>=0){if(this._matchValue(recValue[loc],value))return true;}}else return this._matchValue(recValue,value);}
return false;},_matchValue:function(recValue,value){if(recValue&&recValue.primaryKey)recValue=recValue.get(recValue.primaryKey);var stringify=(value instanceof RegExp);if(stringify){return recValue.toString().match(value)}else{return recValue==value;}},toString:function(){var that=this;var ret=this.get('properties').map(function(key){var value=that.get(key);if(typeof(value)=="string")value='"'+value+'"';if(value===undefined)value="(undefined)";if(value===null)value="(null)";return[key,value].join('=');});return this._type.toString()+'({ '+ret.join(', ')+' })';},propertyObserver:function(observing,target,key,value){},_cprops:['properties'],updateProperties:function(data,isLoaded){var rec=this;this.beginPropertyChanges();if(isLoaded)this.set('isLoaded',true);try{var loc=this.properties.length;while(--loc>=0){var prop=this.properties[loc];var newValue=data[prop];if(newValue===null){if(rec.get(prop)!=null)rec.set(prop,null);}else if(newValue!==undefined){var oldValue=rec.get(prop);var recordType=rec.get(prop+'Type');var typeConverter=this._pickTypeConverter(recordType);if(typeConverter)recordType=null;var isSame;var rec=this;if(newValue instanceof Array){newValue=newValue.map(function(nv){return rec._convertValueIn(nv,typeConverter,recordType);});isSame=newValue.isEqual(oldValue);}else{newValue=this._convertValueIn(newValue,typeConverter,recordType);isSame=newValue==oldValue;}
if(!isSame)this.set(prop,newValue);}}}
catch(e){console.log(this._guid+': Exception raised on UPDATE: '+e);}
this.endPropertyChanges();this.set('changeCount',0);},getPropertyData:function(){var ret={};var properties=this.get('properties')||[];var loc=properties.length;while(--loc>=0){var key=properties[loc];var value=this.get(key);var recordType=this[key+'Type'];var typeConverter=this._pickTypeConverter(recordType);if(typeConverter)recordType=null;if(value instanceof Array){var ary=[];for(var vloc=0;vloc<value.length;vloc++){var v=value[vloc];ary.push(this._convertValueOut(v,typeConverter,recordType));}
value=ary;}else value=this._convertValueOut(value,typeConverter,recordType);ret[key]=value;}
return ret;},_pickTypeConverter:function(recordType){var typeConverter=null;if(recordType&&recordType.isTypeConverter){typeConverter=recordType;recordType=null;}else if(recordType)switch(recordType){case Date:typeConverter=SC.Record.Date;recordType=null;break;case Number:typeConverter=SC.Record.Number;recordType=null;break;case String:typeConverter=null;recordType=null;break;}
return typeConverter;},_convertValueOut:function(value,typeConverter,recordType){if(typeConverter)return typeConverter(value,'out');if(recordType){return(value)?value.get(recordType.primaryKey):null;}else return value;},_convertValueIn:function(value,typeConverter,recordType){if(typeConverter)return typeConverter(value,'in');if(recordType){return SC.Store.getRecordFor(value,recordType);}else return value;},_storeKey:function(){return this._type._storeKey();}});SC.Record.mixin({SORT_BEFORE:-1,SORT_AFTER:1,SORT_SAME:0,find:function(guid){var args;if(typeof(guid)=='object'){args=$A(arguments);args.push(this);var ret=SC.Store.findRecords.apply(SC.Store,args);return(ret&&ret.length>0)?ret[0]:null;}else return SC.Store._getRecordFor(guid,this);},findOrCreate:function(guid){var ret=this.find(guid);if(!ret){var opts=(typeof(guid)=="object")?guid:{guid:guid};ret=this.create(opts);SC.Store.addRecord(ret);}
return ret;},findAll:function(filter){if(!filter)filter={};args=$A(arguments);args.push(this);return SC.Store.findRecords.apply(SC.Store,args);},collection:function(opts){if(!opts)opts={};opts.recordType=this;return SC.Collection.create(opts);},extend:function(){var ret=SC.Object.extend.apply(this,arguments);if(ret.coreRecordType==null)ret.coreRecordType=ret;return ret;},_storeKey:function(){return(this.coreRecordType)?this.coreRecordType._guid:this._guid;},primaryKey:function(){return this.prototype.primaryKey;},coreRecordType:null,resourceURL:function(){return this.prototype.resourceURL;},hasMany:function(recordTypeString,conditionKey,opts){opts=(opts===undefined)?{}:Object.clone(opts);var conditions=opts.conditions||{};opts.conditions=conditions;var privateKey='_'+conditionKey;return function(){if(!this[privateKey]){var recordType=eval(recordTypeString);conditions[conditionKey]=this;this[privateKey]=recordType.collection(opts);this[privateKey].refresh();}
return this[privateKey];}.property();},newRecord:function(attrs,dataSource){if(!dataSource)dataSource=SC.Store;var rec=this.create({dataSource:dataSource});rec.beginPropertyChanges();rec.set('newRecord',true);for(var key in attrs){if(attrs.hasOwnProperty(key))rec.set(key,attrs[key]);}
rec.endPropertyChanges();SC.Store.addRecord(rec);return rec;}});SC.Record.Date=function(value,direction){if(direction=='out'){if(value instanceof Date)value=value.utcFormat();}else if(typeof(value)=="string"){var ret=Date.parse(value.replace(/\.\d+$/,''));if(ret)value=ret;}
return value;}.typeConverter();SC.Record.Number=function(value,direction){if(direction=='out'){if(typeof(value)=="number")value=value.toString();}else if(typeof(value)=="string"){var ret=(value.match('.'))?parseFloat(value):parseInt(value,0);if(ret)value=ret;}
return value;}.typeConverter();SC.Record.Flag=function(value,direction){if(direction=='out'){return value=(value)?'t':'f';}else if(typeof(value)=="string"){return!('false0'.match(value.toLowerCase()));}else return(value)?true:false;}.typeConverter();SC.Record.Bool=SC.Record.Flag;require('foundation/object');SC.Store=SC.Object.create({updateRecords:function(dataHashes,dataSource,recordType,isLoaded){this.set('updateRecordsInProgress',true);var store=this;var ret=[];if(!recordType)recordType=SC.Record;this.beginPropertyChanges();dataHashes.each(function(data){var rt=data.recordType||recordType;if(data.recordType!==undefined)delete data.recordType;var pkValue=data[rt.primaryKey()];var rec=store.getRecordFor(pkValue,rt,true);rec.dataSource=dataSource;rec.updateAttributes(data,isLoaded,isLoaded);if(rec.needsAddToStore)store.addRecord(rec);ret.push(rec);});this.endPropertyChanges();this.set('updateRecordsInProgress',false);return ret;},refreshRecords:function(records){},createRecords:function(recs){recs.invoke('set','newRecord','false');this.commitRecords(recs);},commitRecords:function(recs){recs.invoke('set','isDirty','false');},destroyRecords:function(recs){var store=this;recs.each(function(r){r.set('isDeleted',true);store.removeRecord(r);});},addRecord:function(rec){rec.needsAddToStore=false;var guid=rec._storeKey();var records=this._records[guid]||[];records.push(rec);this._records[guid]=records;if(!this._quickCache)this._quickCache={};var records=this._quickCache[guid]||{};var pkey=rec.get(rec.primaryKey);records[pkey]=rec;this._quickCache[guid]=records;rec.addObserver('*',this._boundRecordObserver);this.recordDidChange(rec);},removeRecord:function(rec){var guid=rec._storeKey();var records=this._records[guid]||[];records=records.without(rec);this._records[guid]=records;if(this._quickCache)
{var records=this._quickCache[guid]||{};var pkey=rec.get(rec.primaryKey);delete records[pkey];this._quickCache[guid]=records;}
rec.removeObserver('*',this._boundRecordObserver);this.recordDidChange(rec);},relocateRecord:function(oldkey,newkey,rec)
{if(!this._quickCache)return rec;var classKey=rec._storeKey();var records=this._quickCache[classKey]||{};records[newkey]=rec;delete records[oldkey];this._quickCache[classKey]=records;return rec;},findRecords:function(){var allConditions=$A(arguments);var recordType=allConditions.pop();var guid=recordType._storeKey();var records=this._records[guid];while(allConditions.length>0){var conditions=allConditions.pop();var ret=[];var loc=(records)?records.length:0;while(--loc>=0){var rec=records[loc];if((rec._type==recordType)||(rec._type.coreRecordType==recordType)){if(rec.matchConditions(conditions))ret.push(rec);}}
records=ret;}
return records;},_getRecordFor:function(pkValue,recordType){var guid=recordType._storeKey();var records=(this._quickCache)?this._quickCache[guid]:null;var ret=(records)?records[pkValue]:null;return ret;},getRecordFor:function(pkValue,recordType,dontAutoaddRecord){var ret=this._getRecordFor(pkValue,recordType);if(!ret){var opts={};opts[recordType.primaryKey()]=pkValue;ret=recordType.create(opts);if(dontAutoaddRecord){ret.needsAddToStore=true;}else this.addRecord(ret);}
return ret;},records:function(){var ret=[];if(this._quickCache){for(var key in this._quickCache){var recs=this._quickCache[key];for(var recKey in recs){ret.push(recs[recKey]);}}}
return ret;}.property(),addCollection:function(collection){var guid=collection.recordType._storeKey();var collections=this._collections[guid]||[];collections.push(collection);this._collections[guid]=collections;},removeCollection:function(collection){var guid=collection.recordType._storeKey();var collections=this._collections[guid]||[];collections=collections.without(collection);this._collections[guid]=collections;},listFor:function(opts){var conditions=opts.conditions||{};var order=opts.order||['guid'];var records=this.findRecords(conditions,opts.recordType);var count=records.length;records=records.sort(function(a,b){return a.compareTo(b,order);});if(opts.limit&&(opts.limit>0)){var start=(opts.offset)?opts.offset:0;var end=start+opts.limit;records=records.slice(start,end);}
if(opts.callback)opts.callback(records,count);},_records:{},_changedRecords:null,_collections:{},recordDidChange:function(rec){var guid=rec._storeKey();changed=this.get('_changedRecords')||{};records=changed[guid]||{};records[rec._guid]=rec;changed[guid]=records;this.set('_changedRecords',changed);},_changedRecordsObserver:function(){for(var guid in this._changedRecords){var collections=this._collections[guid];if(collections&&collections.length>0){var records=[];for(var key in this._changedRecords[guid]){records.push(this._changedRecords[guid][key]);}
var cloc=collections.length;while(--cloc>=0){var col=collections[cloc];col.beginPropertyChanges();try{var rloc=records.length;while(--rloc>=0){var record=records[rloc];if(col.recordType==record._type){col.recordDidChange(record);}}}
catch(e){console.log('EXCEPTION: While notifying collection');}
col.endPropertyChanges();}}}
this._changedRecords={};}.observes('_changedRecords'),init:function(){arguments.callee.base.call(this);this._boundRecordObserver=this.recordDidChange.bind(this);}});require('models/record');require('models/store');SC.Collection=SC.Object.extend({orderBy:['guid'],offset:0,limit:0,conditions:{},records:function(){if(this._changedRecords)this._flushChangedRecords();return this._records;}.property(),count:function(key,value){if(value!==undefined){this._count=value;}else if(this._changedRecords)this._flushChangedRecords();return this._count||0;}.property(),isDeleted:false,dataSource:SC.Store,recordType:SC.Record,isLoading:false,isDirty:false,refresh:function(){var recordType=this.get('recordType')||SC.Record;var offset=(this._limit>0)?this._offset:0;if(!this._boundRefreshFunc){this._boundRefreshFunc=this._refreshDidComplete.bind(this);}
if(!this.dataSource)throw"collection does not have dataSource";this.beginPropertyChanges();if(!this.isLoading)this.set('isLoading',true);this._refreshing=true;var order=this.get('orderBy');if(order&&!(order instanceof Array))order=[order];this.dataSource.listFor({recordType:recordType,offset:offset,limit:this._limit,conditions:this.get('conditions'),order:order,callback:this._boundRefreshFunc,cacheCode:this._cacheCode});this.endPropertyChanges();return this;},destroy:function(){SC.Store.removeCollection(this);return this;},newRecord:function(settings){if(!settings)settings={};settings.newRecord=true;settings.dataSource=this.get('dataSource');var ret=this.recordType.create(settings);SC.Store.addRecord(ret);return ret;},_offset:0,_limit:0,_records:null,_members:null,_store:null,init:function(){arguments.callee.base.call(this);SC.Store.addCollection(this);this._computeInteralOffsetAndLimit();},_refreshDidComplete:function(records,count,cacheCode){if(cacheCode)this._cacheCode=cacheCode;if(records){this.beginPropertyChanges();if(this.get('count')!=count)this.set('count',count);this.propertyWillChange('records');records=this._store=records.slice();this._reslice();this.propertyDidChange('records');this.endPropertyChanges();}
this._refreshing=false;},recordDidChange:function(rec){if(!rec&&!rec._guid)return;if(!this._changedRecords)this._changedRecords={};this._changedRecords[rec._guid]=rec;this.propertyWillChange('records');this.propertyDidChange('records');this.propertyWillChange('count');this.propertyDidChange('count');},_flushChangedRecords:function(){if(!this._changedRecords)return;if(this.dataSource!=SC.Store)throw"non-local data source is not supported";var current=this._store||[];var order=this.get('orderBy')||[this.recordType.primaryKey()];if(!(order instanceof Array))order=[order];var conditions=this.get('conditions');var records=[];var changed=this._changedRecords;for(var guid in changed){if(!changed.hasOwnProperty(guid))continue;records.push(changed[guid]);}
records=records.sort(function(a,b){return a.compareTo(b,order);});this._changedRecords=null;var loc=0;while(loc<current.length){var working=current[loc];var compareToPrev,compareToNext;if(changed[working._guid]){var belongs=(!working.get('isDeleted'))&&working.matchConditions(conditions);if(belongs){if(loc>0){belongs=(working.compareTo(current[loc-1],order)>=0);}
if(belongs&&(loc+1<current.length)){belongs=(working.compareTo(current[loc+1],order)<=0);}}
if(!belongs){current.splice(loc,1);continue;}}
var goAgain=true;while((records.length>0)&&goAgain){var rec=records[0];if((rec!=working)&&!rec.get('isDeleted')&&rec.matchConditions(conditions)){if((rec==working)||(rec.compareTo(working,order)<=0)){if(rec!=working)current.splice(loc,0,rec);loc++;}else goAgain=false;}
if(goAgain)records.shift();}
loc++;}
while(records.length>0){var rec=records.shift();if(!rec.get('isDeleted')&&rec.matchConditions(conditions)){current.push(rec);}}
this._store=current;this._count=current.length;this._reslice();},_oldRecordsDidChange:function(){var state=((!rec.isDeleted)&&rec.matchConditions(this.get('conditions')))?'in':'out';var records=this._records;if((this._limit>0)&&(state=="in")&&records&&(records.length>0)){var order=this.get('orderBy');if(rec.compareTo(records[0],order)<0){state="before";}else if(rec.compareTo(records[records.length-1],order)>0){state="after";}}
var belongs=records.include(rec);var reslice=false;var refresh=false;switch(state){case'before':if(belongs){records=records.without(rec);reslice=true;}
refresh=true;break;case'after':case'out':if(belongs){records=records.without(rec);reslice=refresh=true;}
break;case'in':if(!belongs){records=records.slice();records.push(rec);}
records=records.sort(function(a,b){return a.compareTo(b,order);});if(!records.isEqual(this._records))reslice=refresh=true;break;}
if(reslice){this._records=records;if(this._limit>0){var start=this.get('offset')-this._offset;var end=start+this.get('limit');records=records.slice(start,end);}
this.set('records',records);}},propertyObserver:function(observing,target,key,value){if(target!=this)return;var needsRefresh=false;var nv;value=this.get(key);switch(key){case'offset':case'limit':var oldOffset=this._offset;var oldLimit=this._limit;this._computeInteralOffsetAndLimit();if((this._offset==oldOffset)&&(this._limit==oldLimit)){this.propertyWillChange('records');this._reslice();this.propertyDidChange('records');}else needsRefresh=true;break;case'conditions':case'orderBy':needsRefresh=true;break;default:break;}
if(needsRefresh&&!this._refreshing){this._refreshing=true;this._cacheCode=null;this.set('isLoading',true);this.invokeLater(this.refresh);}},_computeInteralOffsetAndLimit:function(){if(this.dataSource!=SC.Store){var v;this._offset=((v=this.get('offset'))>this.MARGIN)?(v-this.MARGIN):0;this._limit=((v=this.get('limit'))>0)?(v+this.MARGIN):0;}else this._offset=this._limit=0;},_reslice:function(){var offset=this.get('offset');var limit=this.get('limit');if((offset>0)||(limit>0)){var start=offset-this._offset;var end=start+((limit<=0)?(this._store||[]).length:limit);this._records=this._store.slice(start,end);}else this._records=this._store;},MARGIN:10});require('views/collection/collection');require('views/button/disclosure');require('views/source_list_group');require('views/list_item');SC.BENCHMARK_SOURCE_LIST_VIEW=NO;SC.SourceListView=SC.CollectionView.extend({emptyElement:'<div class="sc-source-list-view"></div>',contentValueKey:null,contentValueIsEditable:NO,selectOnMouseDown:NO,hasContentIcon:NO,hasContentBranch:NO,contentIconKey:null,contentUnreadCountKey:null,contentIsBranchKey:null,groupTitleKey:null,groupVisibleKey:null,rowHeight:32,exampleView:SC.ListItemView,exampleGroupView:SC.SourceListGroupView,updateChildren:function(deep){if(deep)this._groupRows=null;return arguments.callee.base.apply(this,arguments);},groupAtContentIndexIsVisible:function(contentIndex){if(!this.get('groupBy'))return YES;var groupValue=this.groupValueAtContentIndex(contentIndex);var groupView=this.groupViewForGroupValue(groupValue);var ret=YES;if(groupView)ret=groupView.get('isGroupVisible');if(((ret===undefined)||(ret===null)||!groupView)&&groupValue&&groupValue.get){var key=this.get('groupVisibleKey');if(key)ret=!!groupValue.get(key);}
if((ret===undefined)||(ret===null))ret=YES;return ret;},computedGroupRows:function(){if(this._groupRows)return this._groupRows;var loc=0;var content=Array.from(this.get('content'));var max=content.get('length');var ret={};while(loc<max){var range=this.groupRangeForContentIndex(loc);var isVisible=this.groupAtContentIndexIsVisible(range.start);ret[range.start]=(isVisible)?range.length:0;var groupValue=this.groupValueAtContentIndex(range.start);if(groupValue!=null)ret[range.start]++;loc=(range.length<=0)?max:SC.maxRange(range);}
return this._groupRows=ret;},countRowsInRange:function(range){var groupRows=this.computedGroupRows();var max=SC.maxRange(range);var loc=SC.minRange(range);var ret=0;while(loc<max){var range=this.groupRangeForContentIndex(loc);loc=(range.length<=0)?max:SC.maxRange(range);ret+=groupRows[range.start]||(range+1);}
return ret;},computeFrame:function(){var content=this.get('content');var rowHeight=this.get('rowHeight')||20;var rows=this.countRowsInRange({start:0,length:content.get('length')});if(rows<=0)rows=0;var parent=this.get('parentNode');var f=(parent)?parent.get('innerFrame'):{width:100,height:100};f.x=f.y=0;f.height=Math.max(f.height,rows*rowHeight);return f;},contentRangeInFrame:function(frame){var content=this.get('content');var len=(content)?content.get('length'):0;var ret={start:0,length:len};return ret;},layoutItemView:function(itemView,contentIndex,firstLayout){if(SC.BENCHMARK_SOURCE_LIST_VIEW){SC.Benchmark.start('SC.SourceListView.layoutItemViewsFor');}
if(!this.groupAtContentIndexIsVisible(contentIndex)){itemView.set('isVisible',false);}else{if(!itemView.get('isVisible')){firstLayout=YES;itemView.set('isVisible',true);}
var rowHeight=this.get('rowHeight')||0;if(this.get("groupBy"))
{var range=this.groupRangeForContentIndex(contentIndex);contentIndex=(contentIndex-range.start);var groupValue=this.groupValueAtContentIndex(range.start);if(groupValue!=null)contentIndex++;}
var f={x:0,y:contentIndex*rowHeight,height:rowHeight,width:this.get('innerFrame').width};if(firstLayout||!SC.rectsEqual(itemView.get('frame'),f)){itemView.set('frame',f);}}
if(SC.BENCHMARK_SOURCE_LIST_VIEW){SC.Benchmark.end('SC.SourceListView.layoutItemViewsFor');}},layoutGroupView:function(groupView,groupValue,contentIndexHint,firstLayout){if(SC.BENCHMARK_SOURCE_LIST_VIEW){SC.Benchmark.start('SC.SourceListView.layoutGroupView');}
var range=this.groupRangeForContentIndex(contentIndexHint);var isVisible=this.groupAtContentIndexIsVisible(range.start);var priorRows=this.countRowsInRange({start:0,length:range.start});var rowHeight=this.get('rowHeight')||0;var parentView=groupView.get('parentView')||this;var rows=(isVisible)?range.length:0;if(groupValue!=null)rows++;var f={x:0,y:priorRows*rowHeight,height:rowHeight*rows,width:(parentView||this).get('innerFrame').width};if(firstLayout||!SC.rectsEqual(groupView.get('frame'),f)){groupView.set('frame',f);}
if(SC.BENCHMARK_SOURCE_LIST_VIEW){SC.Benchmark.end('SC.SourceListView.layoutGroupView');}},insertionOrientation:SC.VERTICAL_ORIENTATION,insertionPointClass:SC.View.extend({emptyElement:'<div class="list-insertion-point"><span class="anchor"></span></div>'}),showInsertionPoint:function(itemView,dropOperation){if(!itemView)return;if(dropOperation===SC.DROP_ON){if(itemView!==this._dropOnInsertionPoint){this.hideInsertionPoint();itemView.addClassName('drop-target');this._dropOnInsertionPoint=itemView;}}else{if(this._dropOnInsertionPoint){this._dropOnInsertionPoint.removeClassName('drop-target');this._dropOnInsertionPoint=null;}
if(!this._insertionPointView){this._insertionPointView=this.insertionPointClass.create();};var insertionPoint=this._insertionPointView;var f=this.calculateInsertionPointFrame(itemView);insertionPoint.set('frame',f);if(insertionPoint.parentNode!=itemView.parentNode){itemView.parentNode.appendChild(insertionPoint);}}},calculateInsertionPointFrame:function(itemView){return{height:0,x:8,y:itemView.get('frame').y,width:itemView.owner.get('frame').width};},hideInsertionPoint:function(){var insertionPoint=this._insertionPointView;if(insertionPoint)insertionPoint.removeFromParent();if(this._dropOnInsertionPoint){this._dropOnInsertionPoint.removeClassName('drop-target');this._dropOnInsertionPoint=null;}},insertionIndexForLocation:function(loc,dropOperation){var f=this.get('innerFrame');var sf=this.get('scrollFrame');var rowHeight=this.get('rowHeight')||0;var headerRowCount=(this.get("groupBy"))?1:0;var offset=loc.y-f.y-sf.y;var ret=-1;var retOp=SC.DROP_BEFORE;var top=0;var idx=0;while((ret<0)&&(range=this.groupRangeForContentIndex(idx)).length>0){var max=top+((range.length+headerRowCount)*rowHeight);if(max>=offset){offset-=top;ret=Math.floor(offset/rowHeight);var percentage=(offset/rowHeight)-ret;if(dropOperation===SC.DROP_ON){if(percentage>0.80)ret++;if((percentage>=0.20)&&(percentage<=0.80)){retOp=SC.DROP_ON;}}else{if(percentage>0.45)ret++;}
if(ret<headerRowCount)return[-1,SC.DROP_BEFORE];ret=(ret-headerRowCount)+idx;}else{idx+=range.length;top=max;}}
return[ret,retOp];}});require('views/view');require('mixins/delegate_support');SC.HORIZONTAL='horizontal';SC.VERTICAL='vertical';SC.SplitView=SC.View.extend(SC.DelegateSupport,{emptyElement:'<div class="sc-split-view"></div>',delegate:null,layoutDirection:SC.HORIZONTAL,canCollapseViews:YES,canCollapseView:function(view){if(!this.get('canCollapseViews'))return NO;if(view.get('canCollapse')===NO)return NO;return this.invokeDelegateMethod(this.delegate,'splitViewCanCollapse',this,view);},flexibleView:null,setThicknessForView:function(view,thickness){if(view.get('parentNode')!=this){throw"view must belong to reciever (view: %@)".fmt(view);}
var direction=this.get('layoutDirection');var max=view.get('maxThickness');var min=view.get('minThickness');if(max!=null)thickness=Math.min(max,thickness);if(min!=null)thickness=Math.max(min,thickness);thickness=this.invokeDelegateMethod(this.delegate,'splitViewConstrainThickness',this,view,thickness);var total=this.get('innerFrame');available=(direction==SC.HORIZONTAL)?total.width:total.height;var views=this.get('childNodes');var idx=view.length;var flexibleView=this.get('flexibleView');while(--idx>=0){var currentView=views[idx];if((currentView!=view)&&(currentView!=flexibleView)){available-=this.thicknessForView(currentView);}}
thickness=Math.min(thickness,available);thickness=Math.max(0,thickness);if(thickness!=this.thicknessForView(view)){view.set('isCollapsed',(thickness<=0));var f=(direction===SC.HORIZONTAL)?{width:thickness}:{height:thickness};view.set('frame',f);this.layout();}},thicknessForView:function(view){var direction=this.get('layoutDirection');var ret=view.get('frame');return(direction===SC.HORIZONTAL)?ret.width:ret.height;},computeFlexibleView:function(){var flexibleView=this.get('flexibleView');if(!flexibleView){var views=this.get('childNodes');flexibleView=views[Math.ceil(views.length/2)];}
while(flexibleView&&(flexibleView instanceof SC.SplitDividerView)){flexibleView=flexibleView.get('nextSibling');}
return flexibleView;},layout:function(){var views=this.get('childNodes');var flexibleView=this.computeFlexibleView();var direction=this.get('layoutDirection');var view=views[0];var offset=0;while(view&&(view!==flexibleView)){var isCollapsed=view.get('isCollapsed')||NO;view.setIfChanged('isVisible',!isCollapsed);if(!isCollapsed){view.viewFrameWillChange();if(direction==SC.HORIZONTAL){view.setIfChanged('styleLeft',offset);view.setIfChanged('styleRight',null);}else{view.setIfChanged('styleTop',offset);view.setIfChanged('styleBottom',null);}
view.viewFrameDidChange();offset+=this.thicknessForView(view);}
view=view.get('nextSibling');}
var flexHead=offset;var view=views.last();var offset=0;while(view&&(view!==flexibleView)){var isCollapsed=view.get('isCollapsed')||NO;view.setIfChanged('isVisible',!isCollapsed);if(!isCollapsed){view.viewFrameWillChange();if(direction==SC.HORIZONTAL){view.setIfChanged('styleLeft',null);view.setIfChanged('styleRight',offset);}else{view.setIfChanged('styleTop',null);view.setIfChanged('styleBottom',offset);}
view.viewFrameDidChange();offset+=this.thicknessForView(view);}
view=view.get('previousSibling');}
var flexTail=offset;if(flexibleView){view=flexibleView;view.viewFrameWillChange();if(direction==SC.HORIZONTAL){view.setIfChanged('styleLeft',flexHead);view.setIfChanged('styleRight',flexTail);view.setIfChanged('styleWidth',null);}else{view.setIfChanged('styleTop',flexHead);view.setIfChanged('styleBottom',flexTail);view.setIfChanged('styleHeight',null);}
view.viewFrameDidChange();}},splitViewCanCollapse:function(splitView,view){return YES;},splitViewConstrainThickness:function(splitView,view,proposedThickness){return proposedThickness;},init:function(){arguments.callee.base.apply(this,arguments);this.addClassName(this.get('layoutDirection'));}});require('views/view');SC.SpinnerView=SC.View.extend({isVisibleBindingDefault:SC.Binding.Not});require('views/field/field');SC.CheckboxFieldView=SC.FieldView.extend({emptyElement:'<input type="checkbox" value="1" />',setFieldValue:function(value){this.rootElement.checked=!!value;},getFieldValue:function(){return this.rootElement.checked;},valueBindingDefault:SC.Binding.Bool,init:function(){arguments.callee.base.apply(this,arguments);var f=this.fieldValueDidChange.bind(this,false);Event.observe(this.rootElement,'click',f);}});require('views/view');SC.ClearButtonView=SC.View.extend({mouseUp:function(){alert('hello world');}});require('drag/drag');SC.DropTarget={isDropTarget:true,dragEntered:function(drag,evt){return SC.DRAG_NONE;},dragUpdated:function(drag,evt){},dragExited:function(drag,evt){},dragEnded:function(drag,evt){},prepareForDragOperation:function(operation,drag){return true;},performDragOperation:function(operation,drag){return SC.DRAG_NONE;},concludeDragOperation:function(operation,drag){}};require('panes/overlay');SC.DIALOG_PANE='dialog';SC.DialogPaneView=SC.OverlayPaneView.extend({emptyElement:'<div class="pane dialog-pane"><div class="shadow pane-wrapper"><div class="pane-root"></div><div class="top-left-edge"></div><div class="top-edge"></div><div class="top-right-edge"></div><div class="right-edge"></div><div class="bottom-right-edge"></div><div class="bottom-edge"></div><div class="bottom-left-edge"></div><div class="left-edge"></div></div></div>',layer:200});require('views/button/button');SC.RadioView=SC.ButtonView.extend({emptyElement:'<a href="javascript:;" class="sc-radio-view sc-button-view button radio"><img src="%@" class="button" /><span class="label"></span></a>'.fmt('/static/sproutcore/en/blank.gif'),buttonBehavior:SC.TOGGLE_ON_BEHAVIOR});require('core');require('foundation/object');SC.Mock={};SC.Mock.DOMEvent=SC.Object.extend({type:null,target:null,stopped:false,preventDefault:function(){},stopPropagation:function(){}});SC.Mock.KeyEvent=SC.Mock.DOMEvent.extend({keyCode:0,altKey:false,ctrlKey:false,shiftKey:false,metaKey:false});require('views/collection/collection');require('views/label');require('views/list_item');SC.ListView=SC.CollectionView.extend({emptyElement:'<div class="list-view"></div>',rowHeight:20,exampleView:SC.ListItemView,insertionOrientation:SC.VERTICAL_ORIENTATION,contentRangeInFrame:function(frame){var rowHeight=this.get('rowHeight')||0;var min=Math.max(0,Math.floor(SC.minY(frame)/rowHeight)-1);var max=Math.ceil(SC.maxY(frame)/rowHeight);var ret={start:min,length:max-min};return ret;},layoutItemView:function(itemView,contentIndex,firstLayout){var rowHeight=this.get('rowHeight')||0;var parentView=itemView.get('parentView');var f={x:0,y:contentIndex*rowHeight,height:rowHeight,width:(parentView||this).get('innerFrame').width};if(firstLayout||!SC.rectsEqual(itemView.get('frame'),f)){itemView.set('frame',f);itemView.setStyle({zIndex:contentIndex.toString()});}},computeFrame:function(){var content=this.get('content');var rows=(content)?content.get('length'):0;var rowHeight=this.get('rowHeight')||20;var parent=this.get('parentNode');var f=(parent)?parent.get('innerFrame'):{width:100,height:100};f.x=f.y=0;f.height=Math.max(f.height,rows*rowHeight);return f;},insertionPointClass:SC.View.extend({emptyElement:'<div class="list-insertion-point"><span class="anchor"></span></div>'}),showInsertionPoint:function(itemView,dropOperation){if(!itemView)return;if(dropOperation===SC.DROP_ON){if(itemView!==this._dropOnInsertionPoint){this.hideInsertionPoint();itemView.addClassName('drop-target');this._dropOnInsertionPoint=itemView;}}else{if(this._dropOnInsertionPoint){this._dropOnInsertionPoint.removeClassName('drop-target');this._dropOnInsertionPoint=null;}
if(!this._insertionPointView){this._insertionPointView=this.insertionPointClass.create();};var insertionPoint=this._insertionPointView;f={height:0,x:8,y:itemView.get('frame').y,width:itemView.owner.get('frame').width};insertionPoint.set('frame',f);if(insertionPoint.parentNode!=itemView.parentNode){itemView.parentNode.appendChild(insertionPoint);}}},hideInsertionPoint:function(){var insertionPoint=this._insertionPointView;if(insertionPoint)insertionPoint.removeFromParent();if(this._dropOnInsertionPoint){this._dropOnInsertionPoint.removeClassName('drop-target');this._dropOnInsertionPoint=null;}},insertionIndexForLocation:function(loc,dropOperation){var f=this.get('innerFrame');var sf=this.get('scrollFrame');var rowHeight=this.get('rowHeight')||0;var offset=loc.y-f.y-sf.y;var retOp=SC.DROP_BEFORE;var ret=Math.floor(offset/this.get('rowHeight'));var percentage=(offset/rowHeight)-ret;if(dropOperation===SC.DROP_ON){if(percentage>0.80)ret++;if((percentage>=0.20)&&(percentage<=0.80)){retOp=SC.DROP_ON;}}else{if(percentage>0.45)ret++;}
return[ret,retOp];}});require('core');require('views/view');require('mixins/control');require('mixins/inline_editor_delegate');SC.TableRowView=SC.View.extend(SC.Control,SC.InlineEditorDelegate,{emptyElement:'<div class="sc-list-item-view sc-collection-item"></div>',cells:[],render:function(){var rowContent=this.get('content');var html=[];var count=this.parentNode.columnValueKeys.length;for(i=0;i<count;i++){this.cells[i]=this.renderLabel(rowContent.get(this.parentNode.columnValueKeys[i]),this.parentNode.columnWidths[i]);html.push(this.cells[i]);}
this.set('innerHTML',html.join(''));},renderLabel:function(label,width){var html=[];html.push('<div class="sc-label" style="width: '+width+'px; float: left; padding-left: 5px;">');html.push(label||'&nbsp;');html.push('</div>');return html.join('');},contentValueIsEditable:YES,contentHitTest:function(evt){this.lastHitEvent=evt;return YES;},leftOffset:25,lastHitEvent:null,editingColumn:null,beginEditing:function(){if(this.get('isEditing'))return YES;var rowContent=this.get('content');var i=0;var totalOffset=this.leftOffset;while(i<this.parentNode.columnWidths.length&&totalOffset<this.lastHitEvent.clientX){totalOffset+=this.parentNode.columnWidths[i];i++;}
this.editingColumn=i-1;if(!this.parentNode.columnEditable[this.editingColumn])return NO;var content=this.get('content');var del=this.displayDelegate;var labelKey=this.getDelegateProperty(del,'contentValueKey');var v=(labelKey&&content&&content.get)?content.get(labelKey):null;var f=this.get('frame');var el=this.findLabelElement();if(!el)return NO;var oldLineHeight=Element.getStyle(el,'lineHeight');var fontSize=parseInt(Element.getStyle(el,'fontSize'),0);var lineHeight=parseInt(oldLineHeight,0);var lineHeightShift=0;if(fontSize&&lineHeight){var targetLineHeight=fontSize*1.5;if(targetLineHeight<lineHeight){Element.setStyle(el,{lineHeight:'1.5'});lineHeightShift=(lineHeight-targetLineHeight)/2;}else oldLineHeight=null;}
f.x+=totalOffset-this.parentNode.columnWidths[i-1]-this.leftOffset+((i-1)*3);f.y+=el.offsetTop+lineHeightShift-2;f.height=el.offsetHeight;f.width=this.parentNode.columnWidths[i-1];f=this.convertFrameToView(f,null);var ret=SC.InlineTextFieldView.beginEditing({frame:f,exampleElement:el,delegate:this,value:rowContent.get(this.parentNode.columnValueKeys[i-1])});if(oldLineHeight)Element.setStyle(el,{lineHeight:oldLineHeight});return ret;},commitEditing:function(){if(!this.get('isEditing'))return YES;return SC.InlineTextFieldView.commitEditing();},discardEditing:function(){if(!this.get('isEditing'))return YES;return SC.InlineTextFieldView.discardEditing();},contentPropertyDidChange:function(){Stonehill.invoiceController.recalculateTotals();this.render();},inlineEditorWillBeginEditing:function(inlineEditor){this.set('isEditing',YES);},inlineEditorShouldEndEditing:function(inlineEditor,finalValue){return YES;},inlineEditorDidEndEditing:function(inlineEditor,finalValue){this.set('isEditing',NO);var newValue=finalValue;if(this.parentNode.columnTypes[this.editingColumn]=='dollar'){newValue=parseFloat(finalValue).toFixed(2);if(!newValue||newValue.toString()=="NaN"){newValue="0";}}
if(this.parentNode.columnTypes[this.editingColumn]=='integer'){newValue=Math.round(parseFloat(finalValue));if(!newValue){newValue="0";}}
if(this.parentNode.columnTypes[this.editingColumn]=='boolean'){if(finalValue[0]=='y'||finalValue[0]=='Y'){newValue="Yes";}else{newValue="No";}}
var content=this.get('content');content.set(this.parentNode.columnValueKeys[this.editingColumn],newValue);this.render();},findLabelElement:function(){return this.$class('sc-label');}});require('views/collection/collection');require('views/label');require('views/table_row');SC.TableView=SC.CollectionView.extend({emptyElement:'<div class="sc-table-view"></div>',columnNames:null,columnWidths:null,columnValueKeys:null,columnEditable:null,columnTypes:null,rowHeight:20,exampleView:SC.TableRowView,insertionOrientation:SC.VERTICAL_ORIENTATION,contentRangeInFrame:function(frame){var rowHeight=this.get('rowHeight')||0;var min=Math.max(0,Math.floor(SC.minY(frame)/rowHeight)-1);var max=Math.ceil(SC.maxY(frame)/rowHeight);var ret={start:min,length:max-min};return ret;},layoutItemView:function(itemView,contentIndex,firstLayout){SC.Benchmark.start('SC.TableView.layoutItemViewsFor');var rowHeight=this.get('rowHeight')||0;var parentView=itemView.get('parentView');var f={x:0,y:contentIndex*rowHeight,height:rowHeight,width:(parentView||this).get('innerFrame').width};if(firstLayout||!SC.rectsEqual(itemView.get('frame'),f)){itemView.set('frame',f);}
SC.Benchmark.end('SC.TableView.layoutItemViewsFor');},computeFrame:function(){var content=this.get('content');var rows=(content)?content.get('length'):0;var rowHeight=this.get('rowHeight')||20;var parent=this.get('parentNode');var f=(parent)?parent.get('innerFrame'):{width:100,height:100};f.x=f.y=0;f.height=Math.max(f.height,rows*rowHeight);return f;},insertionPointClass:SC.View.extend({emptyElement:'<div class="list-insertion-point"><span class="anchor"></span></div>'}),showInsertionPointBefore:function(itemView){if(!itemView)return;if(!this._insertionPointView){this._insertionPointView=this.insertionPointClass.create();};var insertionPoint=this._insertionPointView;f={height:0,x:8,y:itemView.get('frame').y,width:itemView.owner.get('frame').width};insertionPoint.set('frame',f);if(insertionPoint.parentNode!=itemView.parentNode){itemView.parentNode.appendChild(insertionPoint);}},hideInsertionPoint:function(){var insertionPoint=this._insertionPointView;if(insertionPoint)insertionPoint.removeFromParent();},insertionIndexForLocation:function(loc){var f=this.get('innerFrame');var sf=this.get('scrollFrame');var ret=Math.floor(((loc.y-f.y-sf.y)/this.get('rowHeight'))+0.4);return ret;}});require('views/field/field');SC.RadioFieldView=SC.FieldView.extend({emptyElement:'<div></div>',values:function(){if(!this._fields)return[];return Object.keys(this._fields);}.property(),objects:null,setFieldValue:function(value){if(!this._fields)return;var objects=this.get('objects');if(objects){for(var key in objects){if(!objects.hasOwnProperty(key))continue;if(objects[key]==value){value=key;break;}}}
var field=this._fields[value];if(field){field.checked=true;}else{for(var key in this._fields){if(!this._fields.hasOwnProperty(key))continue;this._fields[key].checked=false;}}},getFieldValue:function(){if(!this._fields)return null;var ret=null;for(var key in this._fields){if(!this._fields.hasOwnProperty(key))continue;if(this._fields[key].checked==true){ret=key;break;};}
var objects=this.get('objects');if(objects&&ret)ret=objects[ret];return ret;},enableField:function(){if(!this._fields)return;for(var key in this._fields){if(!this._fields.hasOwnProperty(key))continue;Form.Element.enable(this._fields[key]);}},disableField:function(){if(!this._fields)return;for(var key in this._fields){if(!this._fields.hasOwnProperty(key))continue;Form.Element.disable(this._fields[key]);}},init:function(){arguments.callee.base.apply(this,arguments);this._fields={};var inputFields=this.$$tag('input');var f=this.fieldValueDidChange.bind(this,false);var loc=inputFields.length;this._fields={};while(--loc>=0){var field=inputFields[loc];this._fields[field.value]=field;Event.observe(field,'change',f);}}});require('views/label');SC.ErrorExplanationView=SC.View.extend(SC.Control,{emptyElement:'<ul class="errors"></ul>',explanationTemplate:'<li>%@</li>',_errorsFor:function(errors){if(!errors||errors.length==0)return[];return errors.map(function(er){return($type(er)==T_ERROR)?er:null;}).compact();},valueBindingDefault:SC.Binding.Multiple,formatter:function(errors,view){errors=view._errorsFor(errors);if(!errors||errors.length==0)return'';return errors.map(function(er){er=er.get('description');if(er.escapeHTML)er=er.escapeHTML();return view.explanationTemplate.fmt(er);}).join("");},escapeHTML:false,_valueObserver:function(){var errors=this._errorsFor(this.get('value'));var isVisible=errors&&errors.length>0;if(this.get('isVisible')!=isVisible)this.set('isVisible',isVisible);this.set('innerHTML',this.formatter(errors,this));}.observes('value'),init:function(){arguments.callee.base.apply(this,arguments);this._valueObserver();}});require('foundation/path_module');SC.Page=SC.Object.extend({get:function(key){var value=this[key];if(value&&(value instanceof Function)&&(value.isOutlet)){var ret=this.outlet(key);if(SC.window&&!ret.parentNode){SC.window._insertBefore(ret,null,false);SC.window._rebuildChildNodes();}
ret.awake();return ret;}else return arguments.callee.base.apply(this,arguments);},awake:function(){arguments.callee.base.call(this);for(var key in this){if(this.hasOwnProperty(key)&&this[key]&&this[key].isOutlet){this.get(key);}}},init:function(){arguments.callee.base.apply(this,arguments);var el=this.rootElement=$('resources');SC.callOnLoad(function(){if(el&&el.parentNode)el.parentNode.removeChild(el);});},getIfConfigured:function(key){var value=this[key];if(value&&(value instanceof Function)&&(value.isOutlet)){return null;}else return value;},_insertBefore:function(){},_rebuildChildNodes:function(){}});Object.extend(SC.Page.prototype,SC.PathModule);require('mixins/scrollable');require('views/container');SC.ScrollView=SC.ContainerView.extend(SC.Scrollable,{emptyElement:'<div class="sc-scroll-view"></div>',canScrollVertical:YES,canScrollHorizontal:NO,_canScrollVerticalObserver:function(){this.setClassName('sc-scroll-vertical',this.get('canScrollVertical'));}.observes('canScrollVertical'),_canScrollHorizontalObserver:function(){this.setClassName('sc-scroll-horizontal',this.get('canScrollHorizontal'));}.observes('canScrollHorizontal'),init:function(){arguments.callee.base.apply(this,arguments);this._canScrollVerticalObserver();this._canScrollHorizontalObserver();},resizeChildrenWithOldSize:function(oldSize){var v=this.get('firstChild');if(v){var f=v.get('frame');var orig=Object.clone(f);var innerFrame=this.get('innerFrame');f.x=f.y=0;if(!this.get('canScrollHorizontal'))f.width=innerFrame.width;if(!this.get('canScrollVertical'))f.height=innerFrame.height;if(!SC.rectsEqual(f,orig))v.set('frame',f);}}});require('views/view');SC.RadioGroupView=SC.View.extend({value:null,isEnabled:true,init:function(){arguments.callee.base.apply(this,arguments);var loc=this.outlets.length;var ret=[];var valuePropertyPath=[this,'value'];while(--loc>=0){var key=this.outlets[loc];var button=this[key];if(button&&(button.toggleOnValue!==undefined)){button.bind('value',valuePropertyPath);ret.push(button);}}
this._radioButtons=ret;},_isEnabledObserver:function(){var newFlag=this.get('isEnabled');if(!this.didChangeFor('_isEnabled','isEnabled'))return;if(this.radioButtons){this.radioButtons.invoke('set','isEnabled',newFlag);}}.observes('isEnabled')});require('mixins/array');SC.Set=SC.Object.extend(SC.Array,{length:0,revision:0,contains:function(obj){if(obj===null)return false;return this[this._guidFor(obj)]===obj;},add:function(obj){if(obj==null)return NO;var guid=this._guidFor(obj);if(this[guid]==null){this[this._guidFor(obj)]=obj;this.incrementProperty('length');this.incrementProperty('revision');return YES;}else return NO;},remove:function(obj){if(obj==null)return NO;var guid=this._guidFor(obj);if(this[guid]===obj){delete this[this._guidFor(obj)];this.decrementProperty('length');this.incrementProperty('revision');return YES;}else return NO;},_guidFor:function(obj){return'@'+SC.guidFor(obj);},_each:function(iterator){for(var key in this){if(!this.hasOwnProperty(key))continue;if(key.match(/^@/))iterator(this[key]);}}});SC.Set.prototype.push=SC.Set.prototype.unshift=SC.Set.prototype.add;SC.Set.prototype.pop=SC.Set.prototype.shift=SC.Set.prototype.remove;SC.Set._create=SC.Set.create;SC.Set.create=function(items){if(!items)items=[];var hash={},loc=items.length;while(--loc>=0){var item=items[loc];if(item==null)continue;hash[SC.Set.prototype._guidFor(item)]=item;}
hash.length=items.length;return SC.Set._create(hash);};require('core');SC.runLoop=SC.Object.create({maxRunTime:3000,notifyObserver:function(target,action,args){if(!this._notifications)this._notifications=[];this._notifications.push({target:target,action:action,args:args});},deliverNotifications:function(){if(!this._notifications||this._notifications.length<=0)return;if(this._notifying)return;this._notifying=YES;var start=this.get('startTime');var max=start+this.get('maxRunTime');var loc=0;while((Date.now()<max)&&(loc<this._notifications.length)){var notify=this._notifications[loc];this._notifications[loc]=null;loc++;if(notify){var args=notify.args;notify.action.call(notify.target,args[0],args[1],args[2],args[3]);}}
if(loc>=this._notifications.length){this._notifications=[];}else{this.invokeLater(this.deliverNotifications);}
this._notifying=NO;},beginRunLoop:function(){this._start=Date.now();},endRunLoop:function(){this._flushExpiredTimers();this._start=null;},startTime:function(){if(!this._start)this._start=Date.now();return this._start;}.property(),scheduleTimer:function(timer,runTime){if(!timer)throw"scheduleTimer requires a timer";if(!this._timers)this._timers={};var guid=SC.guidFor(timer);var t=this._timers[guid];if(t){if(t.prev)t.prev.next=t.next;if(t.next)t.next.prev=t.prev;t.next=t.prev=null;t.at=runTime;}else{t=this._timers[guid]={timer:timer,at:runTime,guid:guid,next:null,prev:null};}
var cur=this._next;if(!cur||cur.at>runTime){this._next=t;t.next=cur;if(cur)cur.prev=t.next;this._rescheduleTimeout();}else{while(cur.next&&cur.next.at<=runTime)cur=cur.next;t.next=cur.next;if(cur.next)cur.next.prev=t;cur.next=t;t.prev=cur;}},cancelTimer:function(timer){if(!timer)return;if(!this._timers)this._timers={};var guid=SC.guidFor(timer);var t=this._timers[guid];if(t){if(t.next)t.next.prev=t.prev;if(t.prev)t.prev.next=t.next;if(this._next===t){this._next=t.next;this._rescheduleTimeout();}
t.next=t.prev=t.timer=null;}},timerPausedStateDidChange:function(timer){this._rescheduleTimeout();},_rescheduleTimeout:function(){if(this._flushing)return;if(!this._timers)this._timers={};var rec=this._next;while(rec&&rec.timer.get('isPaused'))rec=rec.next;if(!rec){this._timeoutAt=0;if(this._timeout)clearTimeout(this._timeout);this._timeout=null;}else if((this._timeoutAt===0)||(rec.at!==this._timeoutAt)){if(this._timeout)clearTimeout(this._timeout);var delay=Math.max(rec.at-Date.now(),0);this._timeout=setTimeout(this._timeoutAction,delay);this.timeoutAt=rec.at;}},_timeoutAction:function(){var rl=SC.runLoop;rl._timeout=null;rl._timeoutAt=0;rl.beginRunLoop();rl._flushExpiredTimers();rl.endRunLoop();},_flushExpiredTimers:function(){if(!this._timers)this._timers={};var now=this.get('startTime');var max=now+this.get('maxRunTime');this._flushing=YES;var fired={};var rec=this._next;while(rec&&(rec.at<=now)&&(Date.now()<max)){var guid=SC.guidFor(rec.timer);if(fired[guid]){rec=rec.next;}else{var next=rec.next;if(this._next===rec)this._next=rec.next;if(rec.next)rec.next.prev=rec.prev;if(rec.prev)rec.prev.next=rec.next;delete this._timers[rec.guid];fired[guid]=YES;if(rec.timer)rec.timer.fire();rec.next=rec.prev=rec.timer=null;rec=next;}}
this._flushing=NO;this._rescheduleTimeout();}});require('views/view');SC.PopupMenuView=SC.View.extend({emptyElement:"<ul></ul>",acceptsFirstResponder:true,keyDown:function(evt)
{return this.interpretKeyEvents(evt);},cancel:function()
{this.set('currentSelectedMenuItem',null);this.set('isVisible',false);},moveUp:function()
{this.selectPreviousMenuItem();},moveDown:function()
{this.selectNextMenuItem();},_currentSelectedMenuItem:null,currentSelectedMenuItem:function(key,value)
{if(value!==undefined)
{if(this._currentSelectedMenuItem)this._currentSelectedMenuItem.set('isDefault',false);this._currentSelectedMenuItem=value;if(this._currentSelectedMenuItem)this._currentSelectedMenuItem.set('isDefault',true);}
return this._currentSelectedMenuItem;}.property(),selectPreviousMenuItem:function()
{var item=this.previousValidMenuItem();if(!item)return false;this.set('currentSelectedMenuItem',item);},selectNextMenuItem:function()
{var item=this.nextValidMenuItem();if(!item)return false;this.set('currentSelectedMenuItem',item);},previousValidMenuItem:function()
{return this._validMenuItemInDirection('previousSibling','lastChild');},nextValidMenuItem:function()
{return this._validMenuItemInDirection('nextSibling','firstChild');},_validMenuItemInDirection:function(direction,begin)
{var curr=this.get('currentSelectedMenuItem');var view=curr?curr.get(direction):this.get(begin);if(!view)return null;do{if(view.get('isEnabled'))return view;}while(view=view.get(direction));return null;},_show:function()
{this.set('currentSelectedMenuItem',null);var menuItems=this.get('childNodes');for(var i=0,n=menuItems.length;i<n;i++)
{var sender=menuItems[i];if(sender._hasLegacyActionHandler())continue;var action=sender.get('action');var target=SC.app.targetForAction(action,sender.get('target'),sender);if(target&&target.respondsTo('validateMenuItem'))sender.set('isEnabled',target.validateMenuItem(sender));if(target&&!target.respondsTo('validateMenuItem'))sender.set('isEnabled',true);if(!target)sender.set('isEnabled',false);}
arguments.callee.base.apply(this,arguments);},resizeWithOldParentSize:function(){var requiredWidth=0;var child=this.get('firstChild');while(child){var w=(child.computedRequiredWidth)?child.computedRequiredWidth():0;if(w>requiredWidth)requiredWidth=w;child=child.get('nextSibling');}
var oldWidth=this.get("size").width;if(requiredWidth!=oldWidth)
{var size={width:requiredWidth};this.set('size',size);}}});require('panes/overlay');SC.MENU_PANE='menu';SC.MenuPaneView=SC.OverlayPaneView.extend({emptyElement:'<div class="pane menu-pane"><div class="shadow pane-wrapper"><div class="pane-root"></div><div class="top-left-edge"></div><div class="top-edge"></div><div class="top-right-edge"></div><div class="right-edge"></div><div class="bottom-right-edge"></div><div class="bottom-edge"></div><div class="bottom-left-edge"></div><div class="left-edge"></div></div></div>',layer:400,isModal:false,positionPane:function(){var anchor=this.anchorView;var picker=this.containerView;var origin;if(anchor){origin=picker.convertFrameFromView(anchor.get('frame'),anchor);origin.y+=origin.height;origin=this.fitPositionToScreen(origin,picker,anchor);}else{var wsize=SC.window.get('size');var psize=picker.get('size');origin={};origin.x=(wsize.width-psize.width)/2;origin.y=(wsize.height-psize.height)/2;}
picker.set('origin',origin);}});require('views/view');require('mixins/delegate_support');require('views/field/text_field');require('views/field/textarea_field');require('mixins/inline_editor_delegate');SC.TableInlineTextFieldView=SC.View.extend(SC.DelegateSupport,SC.InlineEditorDelegate,{beginEditing:function(options){this.beginPropertyChanges();if(this.get('isEditing')&&!this.blurEditor()){this.endPropertyChanges();return NO;}
this._optframe=options.frame;this._exampleElement=options.exampleElement;this._delegate=options.delegate;if(!this._optframe||!this._delegate){throw"At least frame and delegate options are required for inline editor";}
this._originalValue=options.value||'';this._multiline=(options.multiline!==undefined)?options.multiline:NO;this._commitOnBlur=(options.commitOnBlur!==undefined)?options.commitOnBlur:YES;var field=this.outlet('field');field.set('validator',options.validator);field.set('value',this._originalValue);field.set('selectedRange',options.selectedRange||{start:this._originalValue.length,length:0});this.set('isEditing',YES);SC.app.get("keyPane").appendChild(this);this.updateViewStyle();var del=this._delegate;this._className=this.getDelegateProperty(del,"inlineEditorClassName");if(this._className&&!this.hasClassName(this._className)){this.setClassName(this._className,true);}
this.invokeDelegateMethod(del,'inlineEditorWillBeginEditing',this);this.resizeToFit(field.getFieldValue());this.endPropertyChanges();this.field.becomeFirstResponder();this.invokeDelegateMethod(del,'inlineEditorDidBeginEditing',this);},commitEditing:function(){var field=this.outlet('field');if(!$ok(field.validateSubmit()))return NO;return this._endEditing(field.get('value'));},discardEditing:function(){return this._endEditing(this._originalValue);},blurEditor:function(){if(!this.get('isEditing'))return YES;return(this._commitOnBlur)?this.commitEditing():this.discardEditing();},_endEditing:function(finalValue){if(!this.get('isEditing'))return YES;var del=this._delegate;if(!this.invokeDelegateMethod(del,'inlineEditorShouldEndEditing',this,finalValue))return NO;this.invokeDelegateMethod(del,'inlineEditorDidEndEditing',this,finalValue);if(this._className)this.setClassName(this._className,false);this._originalValue=this._delegate=this._exampleElement=this._optframe=this._className=null;this.set('isEditing',NO);if(this.field.get('isFirstResponder'))this.field.resignFirstResponder();if(this.get('parentNode'))this.removeFromParent();return YES;},isEditing:NO,emptyElement:['<div class="sc-inline-text-field-view">','<div class="sizer"></div>','<textarea class="inner-field" wrap="virtual"></textarea>','</div>'].join(''),updateViewStyle:function(){var f=this._optframe;var el=this._exampleElement;var styles={fontSize:Element.getStyle(el,'font-size'),fontFamily:Element.getStyle(el,'font-family'),fontWeight:Element.getStyle(el,'font-weight'),paddingLeft:Element.getStyle(el,'padding-left'),paddingRight:Element.getStyle(el,'padding-right'),paddingTop:Element.getStyle(el,'padding-top'),paddingBottom:Element.getStyle(el,'padding-bottom'),lineHeight:Element.getStyle(el,'line-height'),textAlign:Element.getStyle(el,'text-align')};var field=this.outlet('field');var sizer=this.outlet('sizer');field.setStyle(styles);styles.opacity=0;sizer.setStyle(styles);sizer.recacheFrames();this.set('frame',f);},resizeToFit:function(newValue)
{var sizer=this.outlet('sizer');var field=this.outlet('field');var text=(newValue||'').escapeHTML();text=text.replace(/  /g,"&nbsp; ").replace(/\n/g,"<br />&nbsp;");sizer.set('innerHTML',text||"&nbsp;");sizer.recacheFrames();var h=sizer.get('frame').height;this.set('frame',{height:h});},field:SC.TextareaFieldView.extend({mouseDown:function(e){arguments.callee.base.call(this,e);return this.owner.get('isEditing');},willRemoveFromParent:function(){this.get('rootElement').blur();},willLoseFirstResponder:function()
{this.get('rootElement').blur();return this.owner.blurEditor();},cancel:function(){this.owner.discardEditing();return YES;},fieldValueDidChange:function(partialChange){arguments.callee.base.call(this,partialChange);this.owner.resizeToFit(this.getFieldValue());},insertNewline:function(evt){if(this.owner._multiline){return arguments.callee.base.call(this,evt);}else{this.owner.commitEditing();return YES;}},insertTab:function(evt)
{var next=this.get("owner")._delegate.nextValidKeyView();this.owner.commitEditing();if(next)next.beginEditing();return YES;},insertBacktab:function(evt)
{var prev=this.get("owner")._delegate.previousValidKeyView();this.owner.commitEditing();if(prev)prev.beginEditing();return YES;}}).outletFor('.inner-field?'),sizer:SC.View.outletFor('.sizer?')});SC.InlineTextFieldView.mixin({beginEditing:function(options){if(!this.sharedEditor)this.sharedEditor=this.create();return this.sharedEditor.beginEditing(options);},commitEditing:function(){return(this.sharedEditor)?this.sharedEditor.commitEditing():YES;},discardEditing:function(){return(this.sharedEditor)?this.sharedEditor.discardEditing():YES;},sharedEditor:null});require('core');require('foundation/object');SC.Timer=SC.Object.extend({target:null,action:null,interval:0,startTime:null,repeats:NO,until:null,isPaused:NO,isScheduled:NO,isValid:function(){return!this._invalid;}.property('isPaused'),fireTime:null,invalidate:function(){this.propertyWillChange('isValid');this._invalid=YES;SC.runLoop.cancelTimer(this);this.propertyDidChange('isValid');this.action=this.target=null;return this;},fire:function(){var nextFireTime=this._computeNextFireTime();if(!this.get('isPaused'))this.performAction();(nextFireTime>0)?this.schedule():this.invalidate();},performAction:function(){if($type(this.action)==T_FUNCTION){this.action.call((this.target||this),this);}else if(this.action.indexOf('.')>=0){var path=this.action.split('.');var property=path.pop();var target=SC.Object.objectForPropertyPath(path,window);var action=(target.get)?target.get(property):target[property];if(action&&$type(action)==T_FUNCTION){action.call(target,this);}else{throw'%@: Timer could not find a function at %@'.fmt(this,this.action);}}else SC.app.sendAction(this.action,this.target,this);},schedule:function(){this.beginPropertyChanges();if(!this.startTime)this.set('startTime',SC.runLoop.get('startTime'));var fireTime=(this.fireTime)?this.get('fireTime'):this._computeNextFireTime();if(!this._invalid){this.set('isScheduled',YES);SC.runLoop.scheduleTimer(this,fireTime);}
this.endPropertyChanges();return this;},init:function(){arguments.callee.base.call(this);if(this.startTime instanceof Date){this.startTime=this.startTime.getTime();}
if(this.until instanceof Date){this.until=this.until.getTime();}},_isPausedObserver:function(){SC.runLoop.timerPausedStateDidChange(this);}.observes('isPaused'),_computeNextFireTime:function(){var fireTime=0;if(!this._invalid&&this.get('isValid')){var now=Date.now();var start=this.get('startTime')||now;var until=this.get('until');if((!until)||(until===0)||(now<until)){var interval=this.get('interval');var repeats=this.get('repeats');var cycle=Math.ceil(((now-start)/interval)+0.01);if(cycle<1)cycle=1;fireTime=((cycle<=1)||repeats)?start+(cycle*interval):0;}}
this.setIfChanged('fireTime',fireTime);return fireTime;}});SC.Timer.schedule=function(props){return this.create(props).schedule();};require('views/button/button');SC.PopupButtonView=SC.ButtonView.extend({performKeyEquivalent:function(keystring,evt)
{if(!this.get('isEnabled'))return false;if(arguments.callee.base.apply(this,arguments))return true;var menu=this.get('menu');return(!!menu&&menu.performKeyEquivalent(keystring,evt));},menuName:null,menu:function(key,value)
{if(value!==undefined)
{value.set('isVisible',false);this.set('_menu',value);}
if(!this._menu)
{var menu=SC.page.get(this.get('menuName'));if(menu)menu.set('isVisible',false);this.set('_menu',menu);}
return this._menu;}.property(),isSelectedBinding:'*_menu.isVisible',action:function(evt)
{var menu=this.get('menu');if(!menu)return false;if(!this._didFirstRun){menu.popup(this,evt);this._didFirstRun=true;}else{this.get('isSelected')?menu.set('isVisible',false):menu.popup(this,evt);}
return true;}});require('mixins/selection_support');require('controllers/object');SC.CollectionController=SC.ObjectController.extend(SC.SelectionSupport,{arrangedObjects:[],canEditCollection:false,pageSize:0,pageCount:function(){var pageSize=this.get('pageSize');if(pageSize<=0)return 1;var content=this.get('content');var count=(content&&content.get)?content.get('count'):0;if(count===null)count=0;return Math.ceil(count/pageSize);}.property(),currentPage:function(key,value){if(value!==undefined){if(this._currentPage!=value){var pc=Math.max(this.get('pageCount')-1,0);if(value>pc)value=pc;if(value<0)value=0;this._currentPage=value;}}
return this._currentPage||0;}.property(),newObject:function(settings){var content=this.get('content');if(!content||!this.get('canEditCollection'))return;try{if(content.newRecord){var rec=content.newRecord(settings);var t=function(){this.set('selection',(rec)?[rec]:[]);this._editingNewRecord=rec;}.invokeLater(this,1);return rec;}}
catch(e){}},addObjects:function(objects){var content=this.get('content');if(!content||!this.get('canEditCollection'))return;try{objects=$A(arguments).flatten();if(content.addRecords){content.addRecords(objects);this.set('selection',(objects)?objects:[]);}}
catch(e){}},addSelection:function(){return this.addObjects(this.get('selection'));},removeObjects:function(objects){var content=this.get('content');if(!content||!this.get('canEditCollection'))return;try{objects=$A(arguments).flatten();alert(this.get('content'));alert(content);alert("B");var rec=content.removeRecords(objects);var sel=(this.get('selection')||[]).without(objects);this.set('selection',(sel)?sel:[]);}
catch(e){}},removeSelection:function(){return this.removeObjects(this.get('selection'));},newObjectDidLoseFocus:function(rec){rec.destroy();},_newRecordDidLoseFocus:function(rec){if(rec.get('newRecord'))this.newObjectDidLoseFocus(rec);},_pageObserver:function(){var content=this.get('content');if(content instanceof Array)content=content[0];if(!content)return;var curOffset=content.get('offset')||0;var curLimit=content.get('limit')||0;var count=content.get('count')||0;var currentPage=this.get('currentPage');var pageSize=this.get('pageSize');var newOffset,newLimit;if(pageSize==0){newOffset=0;newLimit=0;}else{newOffset=currentPage*pageSize;newLimit=pageSize;}
if((newOffset!=curOffset)||(newLimit!=curLimit)){content.beginPropertyChanges();content.set('offset',newOffset);content.set('limit',newLimit);content.endPropertyChanges();}}.observes('currentPage','pageCount','pageSize'),_recordsObserver:function(target,key,value){var old=this.get('arrangedObjects');value=Array.asArray(target.get(key));this.set('arrangedObjects',value.slice());this.updateSelectionAfterContentChange();}.observes('records')});require('views/view');require('controllers/collection');require('views/button/button');SC.PaginationView=SC.View.extend({pageSize:0,pageCount:0,currentPage:0,currentPageString:"_%@-%@ of %@",pageOptionString:"_Page %@: %@-%@",hasPreviousPage:function(){return this.get('currentPage')>0;}.property(),hasNextPage:function(){return this.get('currentPage')<this.get('pageCount');}.property(),emptyElement:'<div class="pagination">\
    <button class="prev">«</button>\
    <button class="page"></button>\
    <button class="next">»</button>\
  </div>',outlets:['prevButton','nextButton','pageButton'],prevButton:SC.ButtonView.extend({action:function(){this.owner.decrementProperty('currentPage');},isEnabledBinding:"*owner.hasPreviousPage"})});require('mixins/control');require('views/image');SC.ImageCellView=SC.View.extend(SC.Control,{emptyElement:'<div class="image-cell sc-collection-item"><img src="%@"  style="position:relative;" /></div>'.fmt('/static/sproutcore/en/blank.gif'),value:null,owner:null,formatter:null,contentValueKey:null,imageMargin:2,imageView:SC.ImageView.extend({sizeToFit:function(){if(this.get('status')!='loaded')return;var f=this.owner.get('frame');var margin=this.owner.get('imageMargin');f.width-=margin*2;f.height-=margin*2;var w=this.get('imageWidth');var h=this.get('imageHeight');var wideScaleFactor=(f.width/w);var tallScaleFactor=(f.height/h);var scaleFactor=(tallScaleFactor<wideScaleFactor)?tallScaleFactor:wideScaleFactor;w=w*scaleFactor;h=h*scaleFactor;var f=this.owner.get('frame');var newFrame={width:w,height:h,x:Math.floor((f.width-w)/2),y:Math.floor((f.height-h)/2)};if(!SC.rectsEqual(newFrame,this.get('frame'))){this.set('frame',newFrame);}}.observes('status')}).outletFor('img?'),outlets:['imageView'],resizeChildrenWithOldSize:function(){if(this.get('content')){this.outlet('imageView').sizeToFit();}},_valueDidChange:function(){var value=this.get('value');var owner=this.get('owner');var formatter=this.getDelegateProperty(this.displayDelegate,'formatter');if(formatter){var formattedValue=($type(formatter)==T_FUNCTION)?formatter(value,this):formatter.fieldValueForObject(value,this);if(formattedValue!=null)value=formattedValue;}
if(value!=null&&value.toString)value=value.toString();this.outlet('imageView').set('value',value);}.observes('value')});require('core');require('foundation/responder');SC.Application=SC.Responder.extend({keyPane:function(key,value)
{if(value!=undefined)
{if(this._keyPane)this._keyPane.willResignKeyPane();if(this._keyPane)this._keyPane.set('isKeyPane',false);this._keyPane=value;if(this._keyPane)this._keyPane.set('isKeyPane',true);if(this._keyPane)this._keyPane.didBecomeKeyPane();}
return this._keyPane||null;}.property(),mainPane:function(key,value)
{if(value!=undefined)
{if(this._mainPane)this._mainPane.willResignMainPane();if(this._mainPane)this._mainPane.set('isMainPane',false);this._mainPane=value;if(this._mainPane)this._mainPane.set('isMainPane',true);if(this._mainPane)this._mainPane.didBecomeMainPane();}
return this._mainPane||null;}.property(),run:function()
{SC.window.setup();SC.window.makeMainPane();SC.window.makeKeyPane();},sendAction:function(action,target,sender)
{var target=this.targetForAction(action,target,sender);return(!!target&&(target.tryToPerform(action,sender)!=false));},targetForAction:function(action,target,sender)
{if(!action||($type(action)!=T_STRING))return null;if(target)return target.respondsTo(action)?target:null;var keyPane=this.get('keyPane');var mainPane=this.get('mainPane');if(keyPane)
{target=keyPane.get('firstResponder')||keyPane.get('defaultResponder')||keyPane;do{if(target.respondsTo(action))return target;}while(target=target.get('nextResponder'));}
if(mainPane&&(mainPane!=keyPane))
{target=mainPane.get('firstResponder')||mainPane.get('defaultResponder')||mainPane;do{if(target.respondsTo(action))return target;}while(target=target.get('nextResponder'));}
target=this;if(target.respondsTo(action))return target;return null;},sendEvent:function(evt,target)
{var target=target||null;var handler=null;if(target&&target.respondsTo(evt._type))
{return(target.tryToPerform(evt._type,evt))?target:false;}
switch(evt._type)
{case'keyDown':case'keyUp':case'flagsChanged':var pane=this.get('keyPane');if(!pane)return null;target=pane.get('firstResponder')||pane.get('defaultResponder')||pane;break;case'mouseOver':case'mouseOut':case'mouseMoved':case'mouseDown':case'mouseUp':case'click':case'doubleClick':target=SC.window.firstViewForEvent(evt);break;default:return null;}
if(!target)return null;handler=target.doCommand(evt._type,evt);if((evt._type=='keyDown')&&!handler)
{if(this._attemptKeyEquivalent(evt))return true;if(this._attemptKeyInterfaceControl(evt))return true;}
return handler;},_attemptKeyEquivalent:function(evt)
{var keystring=SC.Responder.inputManager.codesForEvent(evt).first();if(!keystring)return false;var keyPane=this.get('keyPane');var mainPane=this.get('mainPane');if(keyPane&&keyPane.performKeyEquivalent(keystring,evt))return true;if(mainPane&&(mainPane!=keyPane)&&mainPane.performKeyEquivalent(keystring,evt))return true;return this.performKeyEquivalent(keystring,evt);},_attemptKeyInterfaceControl:function(evt)
{var keystring=SC.Responder.inputManager.codesForEvent(evt).first();var pane=this.get('keyPane');if(!pane)return false;return pane.performKeyInterfaceControl(keystring,evt);}});require('views/view');require('views/container');SC.PanelView=SC.View.extend({emptyElement:'<div id="panels" class="panels"><div class="overlay"></div></div>',wrapperView:SC.ContainerView.extend({emptyElement:'<div class="panel"><div class="root"></div><div class="top-left-edge"></div><div class="top-edge"></div><div class="top-right-edge"></div><div class="right-edge"></div><div class="bottom-right-edge"></div><div class="bottom-edge"></div><div class="bottom-left-edge"></div><div class="left-edge"></div></div>',outlets:['rootView'],rootView:SC.View.outletFor('.root?')}),_wrapperPool:null,_getWrapperView:function(){var ret=this._wrapperPool.pop();if(ret)return ret;ret=this.wrapperView.viewFor();if(ret.visibleAnimation){var va=Object.clone(ret.visibleAnimation);va.onComplete=this.hidePanelDidComplete.bind(this);ret.visibleAnimation=va;}
return ret;},locationFor:function(view,evt){return{top:'50px',left:'auto'};},showPanel:function(view,evt){var wrapperView=this._getWrapperView();wrapperView.set('animateVisible',false);wrapperView.set('isVisible',false);wrapperView.set('content',view);wrapperView.setClassName('standard-panel',!(view.get('hasCustomPanelWrapper')||false));view._wrapperView=wrapperView;this.nowShowing.push(view);this.appendChild(wrapperView);this.set('isVisible',true);wrapperView.setStyle({visibility:'hidden'});wrapperView.set('isVisible',true);var dim=Element.getDimensions(view.rootElement);wrapperView.setStyle(this.locationFor(view,evt));wrapperView.set('isVisible',false);wrapperView.setStyle({width:dim.width+'px',visibility:'visible'});wrapperView.set('animateVisible',true);wrapperView.set('isVisible',true);},hidePanel:function(view){var didHideWrapperView=null;if(view._wrapperView){if(view._wrapperView.visibleAnimation){}else{didHideWrapperView=view._wrapperView;}
view._wrapperView.set('isVisible',false);view._wrapperView=null;}
this.nowShowing=this.nowShowing.without(view);if(didHideWrapperView)this.hidePanelDidComplete(didHideWrapperView);},hidePanelDidComplete:function(wrapperView){if(wrapperView.get('isVisible')!=false)return;if(wrapperView){wrapperView.set('content',null);this._wrapperPool.push(wrapperView);}
if(this.nowShowing.length<=0)this.set('isVisible',false);},init:function(){arguments.callee.base.call(this);this.nowShowing=[];this._wrapperPool=[];},panelStyle:{zIndex:'10000',visibility:'visible',position:'absolute',top:'0',left:'0',width:'100%',height:'100%',overflow:'hidden'},showView:function(){var bodyNode=$tag('body');if(this.rootElement.parentNode!=bodyNode)bodyNode.appendChild(this.rootElement);this.setStyle(this.panelStyle);if(!SC.isIE7()&&bodyNode)Element.addClassName(bodyNode,'under-panel');},hideView:function(){var bodyNode=$tag('body');this.setStyle({zIndex:'-10000',visibility:'hidden'});if(!SC.isIE7()&&bodyNode)Element.removeClassName(bodyNode,'under-panel');},didClick:function(ev){if(this.nowShowing.length==0)return;var topPanel=this.nowShowing[this.nowShowing.length-1];var tgt=Event.element(ev);var tgtView=$view(tgt);var view=topPanel._wrapperView;while(tgt&&(tgt!=this.rootElement)&&(tgtView!=view)){tgt=tgt.parentNode;tgtView=(tgt)?$view(tgt):null;}
if((tgtView!=view)&&(!topPanel.get('isModal'))){topPanel.set('isVisible',false);}}});SC.callOnLoad(function(){if(!SC.page)SC.page=SC.Page.create();SC.page.panels=SC.PanelView.outletFor(null);});require('views/view');require('views/container');require('globals/panels');SC.PopupView=SC.PanelView.extend({emptyElement:'<div id="popups" class="popups"></div>',wrapperView:SC.ContainerView.extend({emptyElement:'<div class="popup"></div>',visibleAnimation:{visible:'opacity: 1.0',hidden:'opacity: 0.0',duration:200,onComplete:function(wrapperView){if(!wrapperView.get('isVisible')){SC.popups.hidePanelDidComplete(wrapperView);}}}}),locationFor:function(view,ev){var loc=Event.pointerLocation(ev);var x=(ev)?(loc.x-20):100;var y=(ev)?lox.y:100;var dim=view.get('size');var screenSize=Element.getDimensions(this);var shift=(x+dim.width+50)-screenSize.width;if(shift>0)x-=shift;var shift=(y+dim.height+20)-screenSize.height;if(shift>0)y-=shift;return{left:x+'px',top:y+'px'};},viewHide:function(){SC.page.get('popups').hidePanel(this);}});SC.callOnLoad(function(){if(!SC.page)SC.page=SC.Page.create();SC.page.popups=SC.PopupView.outletFor(null);});require('panes/overlay');SC.PANEL_PANE='panel';SC.PanelPaneView=SC.OverlayPaneView.extend({emptyElement:'<div class="pane panel-pane"><div class="shadow pane-wrapper"><div class="pane-root"></div><div class="top-left-edge"></div><div class="top-edge"></div><div class="top-right-edge"></div><div class="right-edge"></div><div class="bottom-right-edge"></div><div class="bottom-edge"></div><div class="bottom-left-edge"></div><div class="left-edge"></div></div></div>',layer:100});require('foundation/object');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.each(function(p){var bits=p.split('=');params[bits[0]]=bits[1];});for(var key in value){if(!value.hasOwnProperty(key))continue;if(key!='route'){params[key]=encodeURIComponent(''+value[key]);}}
parts=[route];for(var 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();},addRoute:function(route,func){var parts=route.split('/');if(!this._routes)this._routes=SC.Routes._Route.create();this._routes.addRoute(parts,func);},gotoRoute:function(route){var params={};var parts,route,func;this._lastRoute=route;var parts=route.split('&');if(parts&&parts.length>0){route=parts.shift();parts.each(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();func=this._routes.functionForRoute(parts,params);if(func)func(params);},init:function(){arguments.callee.base.call(this);if(SC.isSafari()&&!SC.isSafari3()){Object.extend(this,this.browserFuncs.safari);}else if(SC.isIE()){Object.extend(this,this.browserFuncs.ie);}
this._didSetupHistory=false;},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.invokeLater(this._checkWindowLocation,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(var 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.invokeLater(this._checkWindowLocation,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.invokeLater(this._checkWindowLocation,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.invokeLater(this._checkWindowLocation,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);}}},_setupHistory:function(){this.invokeLater(this._checkWindowLocation,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.invokeLater(this._checkWindowLocation,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);},_routes:null,_Route:SC.Object.extend({_func:null,_static:null,_dynamic:null,_wildcard:null,addRoute:function(parts,func){if(!parts||parts.length==0){this._func=func;}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._func=func;break;default:var routes=this._static[part]||[];nextRoute=SC.Routes._Route.create();routes.push(nextRoute);this._static[part]=routes;}
if(nextRoute)nextRoute.addRoute(parts,func);}},functionForRoute:function(parts,params){if(!parts||parts.length==0){return this._func;}else{var part=parts.shift();var routes,nextRoute,ret,loc;routes=this._static[part];if(routes)for(loc=0;(loc<routes.length)&&(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;(loc<routes.length)&&(ret==null);loc++){var 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._func;}
return ret;}},init:function(){arguments.callee.base.call(this);this._static={};this._dynamic={};}})});require('views/field/field');SC.SelectFieldView=SC.FieldView.extend({emptyElement:'<select></select>',objects:null,nameKey:null,sortKey:null,valueKey:null,emptyName:null,localize:false,validateMenuItem:function(itemValue,itemName){return true;},sortObjects:function(objects){var nameKey=this.get('sortKey')||this.get('nameKey');objects=objects.sort(function(a,b){if(nameKey){a=(a.get)?a.get(nameKey):a[nameKey];b=(b.get)?b.get(nameKey):b[nameKey];}
return(a<b)?-1:((a>b)?1:0);});return objects;},rebuildMenu:function(){this._rebuildMenu();},mouseDown:function(e){e._stopWhenHandled=false;return false;},getFieldValue:function(){var value=this.rootElement.value;var valueKey=this.get('valueKey');var objects=this.get('objects');if(value=='***'){value=null;}else if(value&&objects){objects=Array.from(objects);var loc=objects.length;var found=null;while(!found&&(--loc>=0)){var object=objects[loc];if(valueKey)object=(object.get)?object.get(valueKey):object[valueKey];ov=(object)?((object._guid)?object._guid:object.toString()):null;if(value==ov)found=object;}}
return value;},setFieldValue:function(nv){if(nv){nv=(nv._guid)?nv._guid:nv.toString();}else{nv="***";}
if(this.rootElement.value!=nv)this.rootElement.value=nv;},_rebuildMenu:function(){var nameKey=this.get('nameKey');var valueKey=this.get('valueKey');var objects=this.get('objects');var fieldValue=this.get('value');var shouldLocalize=this.get('localize');if(!valueKey&&fieldValue)fieldValue=fieldValue._guid;if((fieldValue==null)||(fieldValue==''))fieldValue='***';if(objects){objects=Array.from(objects);objects=this.sortObjects(objects);var html=[];var emptyName=this.get('emptyName');if(emptyName){if(shouldLocalize)emptyName=emptyName.loc();html.push('<option value="***">%@</option>'.fmt(emptyName));html.push('<option disabled="disabled"></option>');}
objects.each(function(object){if(object){var name=(nameKey)?((object.get)?object.get(nameKey):object[nameKey]):object.toString();if(shouldLocalize)
{name=name.loc();}
var value=(valueKey)?((object.get)?object.get(valueKey):object[valueKey]):object;if(value)value=(value._guid)?value._guid:value.toString();var disable=(this.validateMenuItem&&this.validateMenuItem(value,name))?'':'disabled="disabled" ';html.push('<option %@value="%@">%@</option>'.fmt(disable,value,name));}else{html.push('<option disabled="disabled"></option>');}}.bind(this));this.update(html.join(""));this.rootElement.value=fieldValue;}else{this.set('value',null);}},_objectsObserver:function(){if(!this._boundObserver){this._boundObserver=this._objectsItemObserver.bind(this);}
if(this.didChangeFor('_objO','objects','nameKey','valueKey')){var loc;var objects=Array.from(this.get('objects'));var func=this._boundObserver;if(this._objects){loc=this._objects.length;while(--loc>=0){var object=this._objects[loc];if(object&&object.removeObserver){if(this._nameKey&&this._valueKey){object.removeObserver(this._nameKey,func);object.removeObserver(this._valueKey,func);}else{object.removeObserver('*',func);}}}}
this._objects=objects;this._nameKey=this.get('nameKey');this._valueKey=this.get('valueKey');if(this._objects){loc=this._objects.length;while(--loc>=0){var object=this._objects[loc];if(object&&object.addObserver){if(this._nameKey&&this._valueKey){object.addObserver(this._nameKey,func);object.addObserver(this._valueKey,func);}else{object.addObserver('*',func);}}}}
this._rebuildMenu();}}.observes('objects','nameKey','valueKey'),_objectsItemObserver:function(item,key,value){if(item.didChangeFor(this._guid,key)){console.log('rebuildMenu');this._rebuildMenu();}},_fieldDidFocus:function(){var isFocused=this.get('isFocused');if(!isFocused)this.set('isFocused',true);},_fieldDidBlur:function(){var isFocused=this.get('isFocused');if(isFocused)this.set('isFocused',false);},_isFocusedObserver:function(){var isFocused=this.get('isFocused');this.setClassName('focus',isFocused);}.observes('isFocused'),init:function(){arguments.callee.base.call(this);this._rebuildMenu();var changeListener=this.fieldValueDidChange.bind(this,false);Element.observe(this.rootElement,'change',changeListener);var focusListener=this._fieldDidFocus.bindAsEventListener(this);Element.observe(this.rootElement,'focus',focusListener);var blurListener=this._fieldDidBlur.bindAsEventListener(this);Element.observe(this.rootElement,'blur',blurListener);}});require('views/view');require('views/button/button');require('views/field/text_field');SC.FormView=SC.View.extend({content:null,contentBindingDefault:SC.Binding.Single,isDirty:false,isCommitting:true,isEnabled:true,passThroughToContent:false,isValid:function(){return this.get('errors').length==0;}.property('errors'),canCommit:function(){return this.get('isValid')&&this.get('isEnabled');}.property('isValid','isEnabled'),generalErrors:null,errors:function(){if(!this._fields)return[];if(!this._errors){var fview=this;this._errors=[];this.get('fieldKeys').each(function(k){var value=fview.get(k);if($type(value)==T_ERROR)fview._errors.push(value);});}
return this._errors.concat(this.get('generalErrors')||[]);}.property('generalErrors'),fieldKeys:function(){if(!this._fieldKeys&&this._fields){var keys=[];for(var key in this._fields){if(!this._fields.hasOwnProperty(key))continue;keys.push(key);}
this._fieldKeys=keys;}
return this._fieldKeys;}.property(),validate:function(){if(!this._fields)return true;for(var key in this._fields){if(this._fields.hasOwnProperty(key)){var field=this._fields[key];if(field.validateSubmit)field.validateSubmit();}}
return this.get('isValid');},commit:function(){if(!this.validate())return false;var ret=true;var content=this.get('content');if(!content||!this._fields)return;var wasEnabled=this.get('isEnabled');this.beginPropertyChanges();this.set('isEnabled',false);this.set('isCommitting',true);this.endPropertyChanges();ret=this.get('passThroughToContent')?this._commitChanges():this._copyContentAndCommitChanges();this.beginPropertyChanges();this.set('isCommitting',false);this.set('isEnabled',wasEnabled);this.endPropertyChanges();return ret;},_copyContentAndCommitChanges:function()
{var ret=true;var content=this.get('content');if(!content||!this._fields)return false;try{content.beginPropertyChanges();for(var key in this._fields)
{if(key.match(/Button$/))continue;if(this._fields.hasOwnProperty(key)){var newValue=this.get(key);content.set(key,newValue);}}
content.endPropertyChanges();ret=this._commitChanges();this.set('isDirty',!ret);}
catch(e){console.log("commit() exception: "+e);ret=false;}
return ret;},_commitChanges:function()
{var content=this.get('content');var success=false;if(content&&content.commit){success=content.commit(this);}else if(content&&content.commitChanges){success=content.commitChanges();}
return success;},reset:function()
{if(!this._fields)return;var content=this.get('content');if(content&&content.discardChanges)content.discardChanges();this.beginPropertyChanges();for(var key in this._fields){if(this._fields.hasOwnProperty(key)){var value=(content)?content.get(key):null;this.set(key,value);}}
this.set('isDirty',false);this.endPropertyChanges();},rebuildFields:function(){this.beginPropertyChanges();if(this._fields){for(var key in this._fields){if(this._fields.hasOwnProperty(key))this.removeField(key);}}
this._fields={};this._buttons={};this._values={};this._rebuildFieldsForNode(this,true);this.endPropertyChanges();},addField:function(key,field){if(this[key]!==undefined){throw"FormView cannot add the field '%@' because that property already exists.  Try using another name.".fmt(key);}
var form=this;if(key=='submitButton'&&(field.action==SC.ButtonView.prototype.action)){field.action=function(){form.commit();};}
if(key=="resetButton"&&(field.action==SC.ButtonView.prototype.action)){field.action=function(){form.reset();};}
this._fields[key]=field;if(key.substr(-6,6)=="Button"){this._buttons[key]=field;};this.propertyWillChange(key);this.setValueForField(key,field.get('value'));this.propertyDidChange(key,this.getValueForField(key));field.addObserver('value',this._fieldValueObserver_b());field.set('ownerForm',this);this.propertyWillChange('fieldKeys');this._fieldKeys=null;this.propertyDidChange('fieldKeys',null);},removeField:function(key){var field=this._fields[key];if(field){field.removeObserver('value',this._fieldValueObserver_b());field.set('ownerForm',null);}
this.propertyWillChange(key);delete this._fields[key];delete this._values[key];delete this._buttons[key];this.propertyDidChange(key,null);this.propertyWillChange('fieldKeys');this._fieldKeys=null;this.propertyDidChange('fieldKeys',null);},getField:function(key){return this._fields[key];},keyDown:function(evt){return this.interpretKeyEvents(evt);},keyUp:function(){},insertNewline:function(sender,evt){var button=this._findDefaultButton(this);if(!button&&this._fields&&this._fields.submitButton){button=this._fields.submitButton;}
if(button&&button.triggerAction)button.triggerAction(evt);return true;},_findDefaultButton:function(view){if(view.triggerAction&&view.get('isDefault'))return view;view=view.firstChild;while(view){var ret=this._findDefaultButton(view);if(ret)return ret;view=view.nextSibling;}
return null;},unknownProperty:function(key,value){var field=(this._fields)?this._fields[key]:null;if(value!==undefined){if(field){var oldValue=this.getValueForField(key);this.setValueForField(key,value);field.set('value',value);var isOldError=$type(oldValue)==T_ERROR;var isNewError=$type(value)==T_ERROR;if(isOldError!=isNewError){this.propertyWillChange('errors');this._errors=null;this.propertyDidChange('errors',null);}}else this[key]=value;}else{if(field){if(this.getValueForField(key)===undefined){this.setValueForField(key,field.get('value'));}
return this.getValueForField(key);}}
return value;},getValueForField:function(key)
{if(this.get('passThroughToContent')){var content=this.get('content');return(content&&content.get)?content.get(key):undefined;}else{return this._values[key];}},setValueForField:function(key,value)
{if(this.get('passThroughToContent')){var content=this.get('content');if(content&&content.get&&content.set&&(content.get(key)!==value))
{content.set(key,value);}}else{this._values[key]=value;}
return value;},init:function(){arguments.callee.base.apply(this,arguments);if(this.rootElement&&this.rootElement.tagName.toLowerCase()=="form"){this.rootElement.onsubmit=function(){return false;};}
this.rebuildFields();},_rebuildFieldsForNode:function(node,_force){if(node.fieldKey)this.addField(node.fieldKey,node);if((_force!=true)&&(node instanceof SC.FormView))return;var nodes=(node.childNodesForFormField)?node.childNodesForFormField():node.get('childNodes');var loc=nodes.length;while(--loc>=0){node=nodes[loc];this._rebuildFieldsForNode(node,false);}},_fieldValueObserver:function(field,key,value){if(!(key=field.fieldKey))return;var oldValue=this.getValueForField(key);if(oldValue==value)return;this.beginPropertyChanges();this.propertyWillChange(key);this.setValueForField(key,value);this.propertyDidChange(key,value);var isOldError=$type(oldValue)==T_ERROR;var isNewError=$type(value)==T_ERROR;if(isOldError!=isNewError){this.propertyWillChange('errors');this._errors=null;this.propertyDidChange('errors',null);}
if(!this.get('isDirty'))this.set('isDirty',true);this.endPropertyChanges();},_fieldValueObserver_b:function(){return this._bound_fieldValueObserver=(this._bound_fieldValueObserver||this._fieldValueObserver.bind(this));},_contentPropertyObserver:function(content,key,value){if(!this._fields||!content)return;var fields=this._fields;if(fields[key]&&content.didChangeFor(this,key)){this.set(key,value);}else if(key=="*"){for(var key in fields){if(fields.hasOwnProperty(key)&&content.didChangeFor(this,key)){this.set(key,content.get(key));}}}},_contentPropertyObserver_b:function(){return this._bound_contentPropertyObserver=(this._bound_contentPropertyObserver||this._contentPropertyObserver.bind(this));},_isEnabledObserver:function(){var fields=this._fields;if(!fields)return;var enabled=this.get('isEnabled');var canCommit=this.get('canCommit');for(var key in fields){if(fields.hasOwnProperty(key)){var field=fields[key];if(field.set)if(key=='submitButton'){field.set('isEnabled',canCommit);}else field.set('isEnabled',enabled);}}}.observes('isEnabled'),_contentObserver:function(){var content=this.get('content');if(content==this._content)return;var func=this._contentPropertyObserver_b();if(this._content)this._content.removeObserver('*',func);this._content=content;if(!content)return;content.addObserver('*',func);this.reset();}.observes('content'),_canCommitObserver:function(){var buttons=this._buttons;var canCommit=this.get('canCommit');if(buttons&&buttons.submitButton){var button=buttons.submitButton;if(button.set)button.set('isEnabled',canCommit);}}.observes('canCommit')});require('validators/validator');SC.Validator.Password=SC.Validator.extend({attachTo:function(form,field){argments.callee.base.call(this,form,field);if(!this.fields)this.fields=[];this.fields.push(field);},validate:function(force){if(!this.fields||this.fields.length==0)return true;var empty=false;var notEmpty=false;var ret=true;var value=this.fields[0].get('fieldValue');this.fields.each(function(field){var curValue=field.get('fieldValue');if(curValue!=value)ret=false;if(!curValue||curValue.length==0)empty=true;if(curValue&&curValue.length>0)notEmpty=true;});if(force){return(notEmpty==false)?false:ret;}else{return(empty==true)?true:ret;}},updateFields:function(form,valid){if(!this.fields||this.fields.length==0)return true;var err="Invalid.Password".loc();var topField=this._field;this.fields.each(function(f){var msg=(valid)?null:((f==topField)?err:'');form.setErrorFor(f,msg);});return(valid)?SC.Validator.OK:err;},validateChange:function(form,field,oldValue){return this.updateFields(form,this.validate(false));},validateSubmit:function(form,field){return this.updateFields(form,this.validate(true));},validatePartial:function(form,field){var isInvalid=!this._field.get('isValid');if(isInvalid){return this.updateFields(form,this.validate(false));}else return SC.Validator.NO_CHANGE;}});Object.extend(SC,{minX:function(frame){return frame.x;},maxX:function(frame){return frame.x+frame.width;},midX:function(frame){return frame.x+(frame.width/2);},minY:function(frame){return frame.y;},maxY:function(frame){return frame.y+frame.height;},midY:function(frame){return frame.y+(frame.height/2);},centerX:function(innerFrame,outerFrame){return(outerFrame.width-innerFrame.width)/2;},centerY:function(innerFrame,outerFrame){return(outerFrame.width-innerFrame.width)/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==null)delta=0.1;if(Math.abs(r1.y-r2.y)>delta)return false;if(Math.abs(r1.x-r2.x)>delta)return false;if(Math.abs(r1.width-r2.width)>delta)return false;if(Math.abs(r1.height-r2.height)>delta)return false;return true;},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};},viewportOffset:function(el){var valueL=0;var valueT=0;var element=el;while(element){valueT+=(element.offsetTop||0)+(element.clientTop||0);valueL+=(element.offsetLeft||0)+(element.clientLeft||0);if(SC.Platform.Firefox){var overflow=Element.getStyle(element,'overflow');if(overflow!=='visible'){var left=parseInt(Element.getStyle(element,'borderLeftWidth'),0)||0;var top=parseInt(Element.getStyle(element,'borderTopWidth'),0)||0;if(el!==element){left*=2;top*=2;}
valueL+=left;valueT+=top;}}
if(element.offsetParent==document.body&&Element.getStyle(element,'position')=='absolute')break;element=element.offsetParent;}
element=el;while(element){if(!Prototype.Browser.Opera||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(range>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};},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);}});require('views/view');require('views/container');SC.TabView=SC.ContainerView.extend({nowShowing:'',lazyTabs:false,init:function(){arguments.callee.base.call(this);var tabs={};var buttons={};var view=this;var loc=(this.outlets)?this.outlets.length:0;while(--loc>=0){var outlet=this.outlets[loc];if(outlet.slice(outlet.length-3,outlet.length)=="Tab"){var key=outlet.slice(0,-3);var tab=view.get(outlet);var button=view.get(key+'Button');if(tab){var tabId=tab.get('tabId')||key;tabs[tabId]=tab;if(button)buttons[tabId]=button;if(tab.removeFromParent)tab.removeFromParent();}}}
this._tabs=tabs;this._buttons=buttons;this.nowShowingObserver();},nowShowingObserver:function(){var nowShowing=this.get('nowShowing');if(nowShowing==this._oldNowShowing)return;this._oldNowShowing=nowShowing;for(var tabId in this._tabs){var tab=this._tabs[tabId];var button=this._buttons[tabId];if(tabId==nowShowing){if(button)button.set('isSelected',true);}else{if(tab)tab.set('isVisible',false);if(button)button.set('isSelected',false);}}
var visibleTab=this._tabs[nowShowing];if(!visibleTab&&this.get('lazyTabs')){this._tabs[nowShowing]=visibleTab=SC.page.get('%@Tab'.fmt(nowShowing));}
this.set('content',visibleTab);if(visibleTab){visibleTab.set('isVisible',true);}}.observes('nowShowing'),childNodesForFormField:function(){return Object.values(this._tabs||{});}});require('validators/validator');SC.Validator.Date=SC.Validator.extend({format:'NNN d, yyyy h:mm:ss a',naturalLanguage:true,fieldValueForObject:function(object,form,field){var date;if(typeof(object)=="number"){date=new Date(object);}else if(object instanceof Date){date=object;}
if(date)object=date.format(this.get('format'),this.get('naturalLanguage'));return object;},objectForFieldValue:function(value,form,field){if(value){var date=Date.parseDate(value);value=(date)?date.getTime():null;}
return value;}});require('core');require('foundation/responder');require('panes/pane');SC.CAPTURE_BACKSPACE_KEY=NO;SC.window=SC.PaneView.extend({firstViewForEvent:function(evt){var el=Event.element(evt);while(el&&(el!=document)&&(!el._configured))el=el.parentNode;if(el)el=SC.View.findViewForElement(el);if(el==this)el=null;return el;},innerFrame:function(){return this.frame();}.property('frame'),clippingFrame:function(){return this.frame();}.property('frame'),scrollFrame:function(){return this.frame();}.property('frame'),frame:function(){var size=this.get('size');return{x:0,y:0,width:size.width,height:size.height};}.property('size'),size:function(){if(!this._size){if(window.innerHeight){this._size={width:window.innerWidth,height:window.innerHeight};}else if(document.documentElement&&document.documentElement.clientHeight){this._size={width:document.documentElement.clientWidth,height:document.documentElement.clientHeight};}else if(document.body){this._size={width:document.body.clientWidth,height:document.body.clientHeight};}}
return this._size;}.property(),autoresizesChildViews:true,_onresize:function(evt){SC.runLoop.beginRunLoop();var oldSize=Object.clone(this.get('size'));this._size=null;var newSize=this.get('size');if((newSize.width!=oldSize.width)||(newSize.height!=oldSize.height)){this.resizeChildrenWithOldSize(oldSize);}
SC.runLoop.endRunLoop();},_lastModifiers:null,_handleModifierChanges:function(evt)
{var 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;}
if(changed)
{evt._type='flagsChanged';evt._modifiers=m;SC.app.sendEvent(evt);}},_onkeydown:function(evt)
{if(SC.Platform.Firefox>0&&(evt.which===8)){return true;}
this._handleModifierChanges(evt);if(this._isModifierKey(evt))return false;if(!this._isFunctionOrNonPrintableKey(evt))return true;var ret=this._sendEvent('keyDown',evt);return ret;},_onkeypress:function(evt)
{if(SC.Platform.Firefox>0&&(evt.which===8)){var ret=this._sendEvent('keyDown',evt);}else{if(this._isFunctionOrNonPrintableKey(evt))return true;if(evt.charCode!=undefined&&evt.charCode==0)return true;var ret=this._sendEvent('keyDown',evt);}
return ret;},_onkeyup:function(evt)
{this._handleModifierChanges(evt);if(this._isModifierKey(evt))return;return this._sendEvent('keyUp',evt);},_sendEvent:function(sctype,evt)
{SC.runLoop.beginRunLoop();evt._type=sctype;evt._stopWhenHandled=(evt._stopWhenHandled!==undefined)?evt._stopWhenHandled:true;var handler=SC.app.sendEvent(evt);var ret=true;if(handler&&evt._stopWhenHandled){Event.stop(evt);ret=false;}
SC.runLoop.endRunLoop();return ret;},_isFunctionOrNonPrintableKey:function(evt)
{return!!(evt.altKey||evt.ctrlKey||SC.FUNCTION_KEYS[evt.keyCode]);},_isModifierKey:function(evt)
{return!!SC.MODIFIER_KEYS[evt.keyCode];},_mouseDownView:null,_clickCount:0,_lastMouseUpAt:null,dragDidStart:function(drag){this._mouseDownView=drag;},_onmousedown:function(evt)
{SC.runLoop.beginRunLoop();this._onfocus();this._clickCount=this._clickCount+1;if(!this._lastMouseUpAt||((Date.now()-this._lastMouseUpAt)>200)){this._clickCount=1;}
evt.clickCount=this._clickCount;evt._type='mouseDown';evt._stopWhenHandled=(evt._stopWhenHandled!==undefined)?evt._stopWhenHandled:true;this._mouseDownView=SC.app.sendEvent(evt);var ret=true;if(this._mouseDownView&&evt._stopWhenHandled)
{Event.stop(evt);ret=false;}
SC.runLoop.endRunLoop();return ret;},_onmouseup:function(evt)
{SC.runLoop.beginRunLoop();var handler=null;this._lastMouseUpAt=Date.now();evt.clickCount=this._clickCount;if(this._mouseDownView)
{evt._type='mouseUp';handler=SC.app.sendEvent(evt,this._mouseDownView);}
if(!handler&&(this._clickCount==2))
{evt._type='doubleClick';handler=SC.app.sendEvent(evt,this._mouseDownView);}
if(!handler)
{evt._type='click';handler=SC.app.sendEvent(evt,this._mouseDownView);}
this._mouseDownView=null;SC.runLoop.endRunLoop();},_lastHovered:null,_onmousemove:function(evt){SC.runLoop.beginRunLoop();this._onfocus();var lh=this._lastHovered||[];var nh=[];var view=this.firstViewForEvent(evt);while(view&&(view!=this)){var entered=view.mouseOver||view.didMouseOver||view.mouseEntered;var moved=view.mouseMoved||view.mouseDidMove;if(lh.include(view)){if(moved)moved.call(view,evt);nh.push(view);}else{if(entered)entered.call(view,evt);nh.push(view);}
view=view.get('nextResponder');}
for(var loc=0;loc<lh.length;loc++){view=lh[loc];var exited=view.mouseOut||view.didMouseOut||view.mouseExited;if(exited&&!nh.include(view))exited.call(view,evt);}
this._lastHovered=nh;if(this._mouseDownView&&this._mouseDownView.mouseDragged){this._mouseDownView.mouseDragged(evt);}
SC.runLoop.endRunLoop();},_onunload:function(){this._listenerCache.each(function(e){Event.stopObserving.apply(Event,e);});},_onfocus:function(){if(!this._hasFocus){this._hasFocus=YES;this.addClassName('focus');this.removeClassName('blur');}},_onblur:function(){if(this._hasFocus){this._hasFocus=NO;this.removeClassName('focus');this.addClassName('blur');}},_hasFocus:NO,_EVTS:['mousedown','mouseup','click','dblclick','keydown','keyup','keypress','mouseover','mouseout','mousemove','resize','unload','focus','blur'],_listenerCache:[],setup:function(){var win=this;win._EVTS.each(function(e){var func=win['_on'+e];var target=(e!='resize')?document:window;if(func){var f=func.bindAsEventListener(win);if(e==='keypress'&&SC.CAPTURE_BACKSPACE_KEY&&SC.Platform.Firefox>0){document.onkeypress=f;}else{Event.observe(target,e,f);}
win._listenerCache.push([target,e,f]);}});this.get('size');this.set('isVisibleInWindow',true);this._onfocus();}}).viewFor($tag('body'));require('views/view');SC.PaneManager=SC.View.extend({emptyElement:'<div id="panes"></div>',showPaneView:function(view,paneType,anchorView,triggerEvent){this.hidePaneView(view);var pane=this.getPaneFor(paneType);pane._managedPaneType=paneType;pane.set('anchorView',anchorView);pane.set('triggerEvent',triggerEvent);pane.set('isVisible',false);this._visiblePanes[view._guid]=pane;var child=this.get('firstChild');var layer=pane.get('layer');while(child&&(child.get('layer')<=layer)){child=child.get('nextSibling');}
this.insertBefore(pane,child);this.set('isVisible',true);pane.setStyle({visibility:'hidden'});pane.set('isVisible',true);this._setApplicationKeyPane();pane.set('content',view);},hidePaneView:function(view){var pane=this._visiblePanes[view._guid];if(!pane)return;pane.addObserver('displayIsVisible',this._boundPaneDidHide);pane.set('isVisible',false);},getPaneFor:function(paneType){var panes=this._paneCache[paneType];var pane=(panes)?panes.pop():null;if(pane)return pane;var paneClass=this._paneTypes[paneType];if(!paneClass)paneClass=SC[paneType.classify()+'PaneView'];if(!paneClass){throw"no matching class found for pane type '%@'".fmt(paneType);}
pane=paneClass.viewFor(null);return pane;},returnToCache:function(pane,paneType){var panes=this._paneCache[paneType]||[];panes.push(pane);this._paneCache[paneType]=panes;},_paneDidHide:function(pane){var visible=pane.get('displayIsVisible');if(visible)return;pane.removeObserver('displayIsVisible',this._boundPanelDidHide);pane.removeFromParent();pane.set('content',null);this.returnToCache(pane,pane._managedPaneType);if(this.get('firstChild')==null){this.set('isVisible',false);}
this._setApplicationKeyPane();},_setApplicationKeyPane:function()
{var frontMostPane=this.get('lastChild');if(frontMostPane&&frontMostPane.get('isVisible')){frontMostPane.makeKeyPane();}else{var pane=SC.app.get('mainPane');if(pane)pane.makeKeyPane();}},init:function(){arguments.callee.base.apply(this,arguments);var el=this.rootElement;if(!this.parentNode){$tag('body').insertBefore(el,null);SC.window.insertBefore(this,null);}
this.set('isVisible',false);this._boundPaneDidHide=this._paneDidHide.bind(this);},_paneTypes:{},_paneCache:{},_visiblePanes:{}});SC.PaneManager.registerPaneType=function(paneType,paneClass){SC.PaneManager.prototype._paneTypes[paneType]=paneClass;};SC.PaneManager.manager=function(){if(!this._manager)this._manager=SC.PaneManager.viewFor('panes');return this._manager;};require('views/button/button');SC.FilterButtonView=SC.ButtonView.extend({filterValue:null,filterOn:null,filterOff:null,action:function(){var val=this.get('filterValue');val=(val==this.get('filterOn'))?this.get('filterOff'):this.get('filterOn');this.set('filterValue',val);},filterValueObserver:function(){var sel=this.get('filterValue')==this.get('filterOn');if(sel!=this.get('isSelected'))this.set('isSelected',sel);}.observes('filterValue')});require('validators/validator');SC.Validator.Number=SC.Validator.extend({places:0,fieldValueForObject:function(object,form,field){switch($type(object)){case T_NUMBER:object=object.toFixed(this.get('places'));break;case T_NULL:case T_UNDEFINED:object='';break;}
return object;},objectForFieldValue:function(value,form,field){switch($type(value)){case T_STRING:if(value.length==''){value=null;}else if(this.get('places')>0){value=parseFloat(value);}else{value=parseInt(value,0);}
break;case T_NULL:case T_UNDEFINED:value=null;break;}
return value;},validate:function(form,field){var value=field.get('fieldValue');return(value=='')||!(isNaN(value)||isNaN(parseFloat(value)));},validateError:function(form,field){var label=field.get('errorLabel')||'Field';return $error("Invalid.Number(%@)".loc(label),label);}});require('validators/validator');SC.Validator.NotEmpty=SC.Validator.extend({validate:function(form,field){var value=field.get('fieldValue');var ret=!!value;if(ret&&value.length)ret=value.length>0;return ret;},validateError:function(form,field){var label=field.get('errorLabel')||'Field';return $error("Invalid.NotEmpty(%@)".loc(label.capitalize()),field.get('errorLabel'));}});require('views/view');SC.ProgressView=SC.View.extend({minimum:0,maximum:1.0,value:0.50,valueBindingDefault:SC.Binding.SingleNotEmpty,isIndeterminate:function(key,value){if(value!==undefined){this._isIndeterminate=value;}
return this._isIndeterminate&&(this.value!=SC.Binding.EMPTY_PLACEHOLDER);}.property(),isEnabled:function(key,value){if(value!==undefined){this._isEnabled=value;}
return this._isEnabled&&(this.value!=SC.Binding.MULTIPLE_PLACEHOLDER);}.property(),_isIndeterminate:false,_isEnabled:true,emptyElement:'<div class="progress outer"><div class="outer-head"></div><div class="inner"><div class="inner-head"></div><div class="inner-tail"></div></div><div class="outer-tail"></div></div>',outlets:['innerView'],innerView:SC.View.outletFor('.inner?'),propertyObserver:function(observing,target,key,value){if(['value','minimum','maximum','isIndeterminate','isEnabled'].include(key)){var isIndeterminate=this.get('isIndeterminate');var isEnabled=this.get('isEnabled');Element.setClassName(this,'indeterminate',isIndeterminate);Element.setClassName(this,'disabled',!isEnabled);var value;if(!isEnabled){value=0.0;}else if(isIndeterminate){value=1.0;}else{var minimum=this.get('minimum')||0.0;var maximum=this.get('maximum')||1.0;value=this.get('value')||0.0;value=(value-minimum)/(maximum-minimum);if(value>1.0)value=1.0;}
value=value*100;if(this.innerView)this.innerView.setStyle({width:(value+'%')});}}});require('views/view');SC.MenuItemView=SC.ButtonView.extend({emptyElement:['<li class="button menu-item">','<a href="javascript:;">','<span class="sel">&#x2713;</span>','<span class="mixed">-</span>','<span class="inner">','<span class="label"></span>','</span>','<span class="shortcut"></span>','</a>','</li>'].join(''),computedRequiredWidth:function(){var ret=0;var el=this.$sel('.inner');if(el){ret=el.offsetLeft;ret+=parseInt(Element.getStyle(el,'padding-left'),0);ret+=parseInt(Element.getStyle(el,'padding-right'),0);}
var img=Element.$sel(el,'img');if(img){ret+=Element.getDimensions(img).width;}
el=Element.$sel(el,'.label');if(el){ret+=Element.getDimensions(el).width;}
el=this.$sel('.shortcut');if(el){ret+=Element.getDimensions(el).width;}
return ret;},mouseMoved:function(evt)
{if(!this.get('isDefault'))this.get('parentNode').set('currentSelectedMenuItem',this);},mouseOut:function(evt)
{this.set('isDefault',false);this.setClassName('active',false);},mouseUp:function(evt)
{arguments.callee.base.apply(this,arguments);this._closeParentMenu();},didTriggerAction:function()
{this._closeParentMenu();},_closeParentMenu:function()
{var menu=this.get('parentNode');if(menu)menu.set('isVisible',false);}});SC.Toolbar=SC.View.extend({buttons:[],isEnabled:true,init:function(){arguments.callee.base.call(this);var toolbar=this;this.buttons=this.buttons.map(function(button){return button(toolbar);});},isEnabledObserver:function(){var e=this.get('isEnabled');this.get('buttons').each(function(button){button.set('isEnabled',e);});}.observes('isEnabled')});require('views/view');SC.SegmentedView=SC.View.extend({value:null,segments:null,isEnabled:true,allowsEmptySelection:false,init:function(){arguments.callee.base.call(this);if(!this.segments)this.segments=this.outlets.slice();var view=this;this.segments.each(function(key){var seg=view[key];var selectKey=key.slice(0,-6);if(seg&&(seg.action==SC.ButtonView.prototype.action))seg.action=function(){if(this.owner.get('allowsEmptySelection')){newKey=(this.owner.get('value')==selectKey)?null:selectKey;}else newKey=selectKey;this.owner.set('value',newKey);};});this._enabledObserver();this._valueObserver();},_valueObserver:function(){var value=this.get('value');if(value!=this._lastSelected){this._lastSelected=value;var view=this;this.segments.each(function(key){var isSelected=(value)?(key.slice(0,-6)==value):false;var button=view[key];if(button)button.set('isSelected',isSelected);});}}.observes('value'),_enabledObserver:function(){var isEnabled=this.get('isEnabled');if(isEnabled!=this._lastEnabled){var view=this;this.segments.each(function(key){view[key].set('isEnabled',isEnabled);});}}.observes('isEnabled')});require('views/view');require('views/split');SC.SplitDividerView=SC.View.extend({emptyElement:'<div class="sc-split-divider-view"></div>',targetView:function(){var splitView=this.get('parentNode');if(!splitView)return null;var flexibleView=splitView.computeFlexibleView();var views=splitView.get('childNodes');var myIndex=views.indexOf(this);var flexibleIndex=views.indexOf(flexibleView);if(myIndex<0)throw"SplitDividerView must belong to the SplitView";return(myIndex<=flexibleIndex)?this.get('previousSibling'):this.get('nextSibling');}.property(),mouseDown:function(evt){var splitView=this.get('parentNode');if(!splitView)return;this._mouseDownLocation=Event.pointerLocation(evt);this._targetView=this.get('targetView');this._originalThickness=splitView.thicknessForView(this._targetView);this._direction=splitView.get('layoutDirection');return true;},mouseDragged:function(evt){var loc=Event.pointerLocation(evt);if(this._direction==SC.HORIZONTAL){var offset=loc.x-this._mouseDownLocation.x;}else{var offset=loc.y-this._mouseDownLocation.y;}
var thickness=this._originalThickness+offset;var splitView=this.get('parentNode');splitView.setThicknessForView(this._targetView,thickness);return true;},mouseUp:function(evt){this._targetView=this._originalThickness=this._direction=this._mouseDownLocation=null;},doubleClick:function(evt){var splitView=this.get('parentNode');if(!splitView)return;var targetView=this.get('targetView');var isCollapsed=targetView.get('isCollapsed')||NO;if(!isCollapsed&&!splitView.canCollapseView(targetView))return;targetView.set('isCollapsed',!isCollapsed);splitView.layout();return true;}});require('views/view');require('mixins/control');SC.SliderView=SC.View.extend(SC.Control,{emptyElement:'<span class="sc-slider-view"><span class="inner"><img src="%@" class="sc-handle" /></span></span>'.fmt('/static/sproutcore/en/blank.gif'),outlets:['handleElement'],handleElement:'.sc-handle?',minimum:0,maximum:1.0,step:0.1,value:0.50,valueBindingDefault:SC.Binding.SingleNotEmpty,_valueDidChangeObserver:function(){if(!this.didChangeFor('value','value','minimum','maximum'))return;var min=this.get('minimum');var max=this.get('maximum');var value=this.get('value');var constrained=Math.min(Math.max(value,min),max);var step=this.get('step');if(step&&step!==0){constrained=Math.round(constrained/step)*step;}
if(Math.abs(value-constrained)>0.01)this.set('value',constrained);value=constrained;value=(value-min)/(max-min);var f=this.get('innerFrame');value=Math.round((f.width-18)*value);value-=(39);Element.setStyle(this.handleElement,{left:'%@px'.fmt(value)});}.observes('value','minimum','maximum'),mouseDown:function(evt){this.recacheFrames();if(!this.get('isEnabled'))return true;this.addClassName('active');var loc=this.convertFrameFromView(Event.pointerLocation(evt),null).x;var f=this.get('innerFrame');loc-=(f.x+9);var value=loc/(f.width-18);var min=this.get('minimum');var max=this.get('maximum');value=(value*(max-min))+min;value=Math.min(Math.max(value,min),max);this.setIfChanged('value',value);return true;},mouseDragged:function(evt){return this.mouseDown(evt);},mouseUp:function(evt){this.removeClassName('active');}});require('panes/overlay');SC.PICKER_PANE='picker';SC.PickerPaneView=SC.OverlayPaneView.extend({emptyElement:'<div class="pane picker-pane"><div class="shadow pane-wrapper picker-pane-wrapper"><div class="pane-root"></div><div class="top-left-edge"></div><div class="top-edge"></div><div class="top-right-edge"></div><div class="right-edge"></div><div class="bottom-right-edge"></div><div class="bottom-edge"></div><div class="bottom-left-edge"></div><div class="left-edge"></div></div></div>',layer:300,isModal:false,positionPane:function(){var anchor=this.anchorView;var picker=this.containerView;var origin;if(anchor){origin=picker.convertFrameFromView(anchor.get('frame'),anchor);origin.y+=origin.height;origin=this.fitPositionToScreen(origin,picker,anchor);}else{var wsize=SC.window.get('size');var psize=picker.get('size');origin.x=(wsize.width-psize.width)/2;origin.y=(wsize.height-psize.height)/2;}
picker.set('origin',origin);}});require('views/collection/collection');require('views/label');SC.GridView=SC.CollectionView.extend({emptyElement:'<div class="grid-view"></div>',rowHeight:48,columnWidth:64,exampleView:SC.LabelView,insertionOrientation:SC.HORIZONTAL_ORIENTATION,itemsPerRow:function(){var ret=this._computeItemsPerRow();return ret;}.property(),_computeItemsPerRow:function(){var f=this.get('innerFrame');var columnWidth=this.get('columnWidth')||0;return(columnWidth<=0)?1:Math.floor(f.width/columnWidth);},contentRangeInFrame:function(frame){var rowHeight=this.get('rowHeight')||48;var itemsPerRow=this._computeItemsPerRow();var min=Math.floor(SC.minY(frame)/rowHeight)*itemsPerRow;var max=Math.ceil(SC.maxY(frame)/rowHeight)*itemsPerRow;var ret={start:min,length:max-min};return ret;},layoutItemView:function(itemView,contentIndex,firstLayout){SC.Benchmark.start('SC.GridView.layoutItemViewsFor');var rowHeight=this.get('rowHeight')||0;var parentView=itemView.get('parentView');var frameWidth=this.get('innerFrame').width;var itemsPerRow=this._computeItemsPerRow();var columnWidth=Math.floor(frameWidth/itemsPerRow);var row=Math.floor(contentIndex/itemsPerRow);var col=contentIndex-(itemsPerRow*row);var f={x:col*columnWidth,y:row*rowHeight,height:rowHeight,width:columnWidth};if(firstLayout||!SC.rectsEqual(itemView.get('frame'),f)){itemView.set('frame',f);}
SC.Benchmark.end('SC.GridView.layoutItemViewsFor');},layoutItemViewsFor:function(parentView,startingView){SC.Benchmark.start('SC.GridView.layoutItemViewsFor');var rowHeight=this.get('rowHeight');var columnWidth=this.get('columnWidth');if((rowHeight==null)||(columnWidth==null))return false;parentView=parentView||this;var f=parentView.get('innerFrame');f.x=f.y=0;var itemsPerRow=Math.floor(f.width/(columnWidth||1));if(this.get('itemsPerRow')!=itemsPerRow)this.set('itemsPerRow',itemsPerRow);columnWidth=Math.floor((f.width-20)/itemsPerRow);var view=startingView||parentView.firstChild;var content=this.get('content')||[];var idx=(view)?content.indexOf(view.get('content')):0;f={x:0,y:0,height:rowHeight,width:columnWidth};while(view){var row=Math.floor(idx/itemsPerRow);var col=idx-(row*itemsPerRow);f.x=col*columnWidth;f.y=row*rowHeight;if(!SC.rectsEqual(view.get('frame'),f))view.set('frame',f);view=view.nextSibling;idx++;}
SC.Benchmark.end('SC.GridView.layoutItemViewsFor');return true;},computeFrame:function(){var content=this.get('content');var count=(content)?content.get('length'):0;var rowHeight=this.get('rowHeight')||0;var columnWidth=this.get('columnWidth')||0;var parent=this.get('parentNode');var f=(parent)?parent.get('innerFrame'):{width:0,height:0};var itemsPerRow=(columnWidth<=0)?1:(f.width/columnWidth);var rows=Math.ceil(count/itemsPerRow);f.x=f.y=0;f.height=Math.max(f.height,rows*rowHeight);return f;},insertionPointClass:SC.View.extend({emptyElement:'<div class="grid-insertion-point"><span class="anchor"></span></div>'}),showInsertionPoint:function(itemView,dropOperation){if(!itemView)return;if(dropOperation===SC.DROP_ON){if(itemView!==this._dropOnInsertionPoint){this.hideInsertionPoint();itemView.addClassName('drop-target');this._dropOnInsertionPoint=itemView;}}else{if(this._dropOnInsertionPoint){this._dropOnInsertionPoint.removeClassName('drop-target');this._dropOnInsertionPoint=null;}
if(!this._insertionPointView){this._insertionPointView=this.insertionPointClass.create();};var insertionPoint=this._insertionPointView;var itemViewFrame=itemView.get('frame');f={height:itemViewFrame.height-6,x:itemViewFrame.x,y:itemViewFrame.y+6,width:0};if(!SC.rectsEqual(insertionPoint.get('frame'),f)){insertionPoint.set('frame',f);}
if(insertionPoint.parentNode!=itemView.parentNode){itemView.parentNode.appendChild(insertionPoint);}}},hideInsertionPoint:function(){var insertionPoint=this._insertionPointView;if(insertionPoint)insertionPoint.removeFromParent();if(this._dropOnInsertionPoint){this._dropOnInsertionPoint.removeClassName('drop-target');this._dropOnInsertionPoint=null;}},insertionIndexForLocation:function(loc,dropOperation){var f=this.get('frame');var sf=this.get('scrollFrame');var itemsPerRow=this._computeItemsPerRow();var columnWidth=Math.floor(f.width/itemsPerRow);var row=Math.floor((loc.y-f.y-sf.y)/this.get('rowHeight'));var retOp=SC.DROP_BEFORE;var offset=(loc.x-f.x-sf.x);var col=Math.floor(offset/columnWidth);var percentage=(offset/columnWidth)-col;if(dropOperation===SC.DROP_ON){if(percentage>0.80)col++;if((percentage>=0.20)&&(percentage<=0.80)){retOp=SC.DROP_ON;}}else{if(percentage>0.45)col++;}
var ret=(row*itemsPerRow)+col;return[ret,retOp];}});