//@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(loc420)?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_format70){year=1900+(year-0);} else{year=2000+(year-0);}}} else if(token=="MMM"||token=="NNN"){month=0;for(var i=0;i11)){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;i12)){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&&m=="PM"){hh=hh-0+12;} else if(hh>11&&m=="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=minlength;x--){var token=str.substring(i,i+x);if(token.length12){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=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(loc1)?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;idx1){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;idx0){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)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');ithis.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=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;loc0)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;loc0)){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;idx0){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;i1){tuple=tuple.slice();var obj=tuple[0];tuple[1]=parts.pop();for(var loc=0;(obj&&(loc0):!!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;i0)){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&&i0&&ret){ret=ret.map(function(el){for(var iloc=0;el&&(iloc0)?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;loc0)?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:"
",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;olocwframe.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=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:'
'}),_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=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'+''+''+''+'
StatusTestMessage
';this.logsummary=$(this.logId+'-logsummary');this.loglines=$(this.logId+'-loglines');},_toHTML:function(txt){return txt.escapeHTML().replace(/\n/g,"
");},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.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;i0){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;i0)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:'',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:'',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:['
','
','','
'].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,"  ").replace(/\n/g,"
 ");sizer.set('innerHTML',text||" ");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:'',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

',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=0){var cur=content.objectAt(min);var curGroupValue=(cur)?cur.get(groupBy):null;if(curGroupValue!==groupValue)break;} min++;while(++max=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=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(selBottom0){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=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(currentMouseDownIndexselectionEndIndex){selectionEndIndex=currentMouseDownIndex;} if((currentMouseDownIndex>selectionBeginIndex)&&(currentMouseDownIndexpreviousMouseDownIndex){selectionBeginIndex=previousMouseDownIndex;selectionEndIndex=currentMouseDownIndex;}else if(currentMouseDownIndexb)?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=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)&&(oldloc.y){curSide=(SC.maxX(f)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)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:'',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:''.fmt('http://socialsprout.googlecode.com/svn/trunk/tmp/build/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:[''].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='http://socialsprout.googlecode.com/svn/trunk/tmp/build/sproutcore/en/blank.gif';SC.ImageView=SC.View.extend(SC.Control,{emptyElement:''.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',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='http://socialsprout.googlecode.com/svn/trunk/tmp/build/sproutcore/en/blank.gif';} html.push('');html=html.join('');return html;},renderLabelHtml:function(label){var html=[];html.push('');html.push(label||'');html.push('');return html.join('');},findLabelElement:function(){return this.$class('sc-label');},renderCountHtml:function(count){var html=[];html.push('');html.push(count.toString());html.push('');return html.join('');},renderActionHtml:function(actionClassName){var html=[];html.push('');return html.join('');},renderBranchHtml:function(hasBranch){var html=[];html.push(' ');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(targetLineHeight0));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=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=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="#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;i255)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;isection?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;i1){params.ids=[ids].flatten().join(',');}else if(ids.length==1){idPart='/'+ids[0];} var parameters=this._toQueryString(params);if(parameters&¶meters.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'.fmt('http://socialsprout.googlecode.com/svn/trunk/tmp/build/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=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;i0){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&&locb)?SC.Record.SORT_AFTER:SC.Record.SORT_SAME);}else{ret=(a>b)?SC.Record.SORT_BEFORE:((a0){var key;var loc=0;while(value&&(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;vloc0)?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(loc0){belongs=(working.compareTo(current[loc-1],order)>=0);} if(belongs&&(loc+10)&&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:'
',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'}),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',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:'',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('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:'
',layer:200});require('views/button/button');SC.RadioView=SC.ButtonView.extend({emptyElement:''.fmt('http://socialsprout.googlecode.com/svn/trunk/tmp/build/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:'
',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:'
'}),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('views/collection/collection');require('views/label');SC.TableView=SC.CollectionView.extend({emptyElement:'
',rowHeight:20,exampleView:SC.LabelView,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:'
'}),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:'
',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:'
    ',explanationTemplate:'
  • %@
  • ',_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:'
    ',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()=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()",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;irequiredWidth)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:'',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('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)||(nowpc)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();if(content.removeRecords){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')\ \ \ \ ',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:'
    '.fmt('http://socialsprout.googlecode.com/svn/trunk/tmp/build/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
    ',wrapperView:SC.ContainerView.extend({emptyElement:'
    ',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:'
    ',wrapperView:SC.ContainerView.extend({emptyElement:'',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:'
    ',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&¶m.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;i0)?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',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(ab)?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(''.fmt(emptyName));html.push('');} 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(''.fmt(disable,value,name));}else{html.push('');}}.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=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;loc0){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:'
    ',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:'
    ',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:[''].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:'
    ',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:''.fmt('http://socialsprout.googlecode.com/svn/trunk/tmp/build/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:'
    ',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:'
    ',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:'
    '}),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];}});