* @license Portions of this software are copyright Yahoo, Inc, used under the following license:
* Software License Agreement (BSD License)
* Copyright (c) 2009, Yahoo! Inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Sources of Intellectual Property Included in the YUI Library
* Where not otherwise indicated, all YUI content is authored by Yahoo! engineers and consists of Yahoo!-owned intellectual property. YUI is issued by Yahoo! under the BSD license above. In some specific instances, YUI will incorporate work done by developers outside of Yahoo! with their express permission.
*/
/*!
* jQuery JavaScript Library v1.8.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
()},hide:function(){this.options.orig[this.prop]=s._data(this.elem,"fxshow"+this.prop)||s.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(e){var t,n,r,i=Ht||Bt(),o=!0,u=this.elem,a=this.options;if(e||i>=a.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),a.animatedProperties[this.prop]=!0;for(t in a.animatedProperties)a.animatedProperties[t]!==!0&&(o=!1);if(o){a.overflow!=null&&!s.support.shrinkWrapBlocks&&s.each(["","X","Y"],function(e,t){u.style["overflow"+t]=a.overflow[e]}),a.hide&&s(u).hide();if(a.hide||a.show)for(t in a.animatedProperties)s.style(u,t,a.orig[t]),s.removeData(u,"fxshow"+t,!0),s.removeData(u,"toggle"+t,!0);r=a.complete,r&&(a.complete=!1,r.call(u))}return!1}return a.duration==Infinity?this.now=i:(n=i-this.startTime,this.state=n/a.duration,this.pos=s.easing[a.animatedProperties[this.prop]](this.state,n,0,1,a.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update(),!0}},s.extend(s.fx,{tick:function(){var e,t=s.timers,n=0;for(;n<t.length;n++)e=t[n],!e()&&t[n]===e&&t.splice(n--,1);t.length||s.fx.stop()},interval:13,stop:function(){clearInterval(Dt),Dt=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(e){s.style(e.elem,"opacity",e.now)},_default:function(e){e.elem.style&&e.elem.style[e.prop]!=null?e.elem.style[e.prop]=e.now+e.unit:e.elem[e.prop]=e.now}}}),s.each(Pt.concat.apply([],Pt),function(e,t){t.indexOf("margin")&&(s.fx.step[t]=function(e){s.style(e.elem,t,Math.max(0,e.now)+e.unit)})}),s.expr&&s.expr.filters&&(s.expr.filters.animated=function(e){return s
SC.Observers.isObservingSuspended&&this._notifyPropertyObservers(),this},propertyWillChange:function(e,t){return this},propertyDidChange:function(e,t,n){this._kvo_revision=(this._kvo_revision||0)+1;var r=this._kvo_changeLevel||0,i,s,o,u,a=SC.LOG_OBSERVERS&&this.LOG_OBSERVING!==NO,f=this._kvo_property_chains;if(f){var l=f[e];l&&(this.beginPropertyChanges(),l=SC.clone(l),l.forEach(function(e){e.notifyPropertyDidChange()}),this.endPropertyChanges())}var c=this._kvo_cache;if(c){n||(u=this[e],u&&u.isProperty&&(c[u.cacheKey]=c[u.lastSetValueKey]=undefined));if(this._kvo_cacheable){i=this._kvo_cachedep;if(!i||(i=i[e])===undefined)i=this._kvo_computeCachedDependentsFor(e);if(i){s=i.length;while(--s>=0)o=i[s],c[o.cacheKey]=c[o.lastSetValueKey]=undefined}}}var h=SC.Observers.isObservingSuspended;if(r>0||h){var p=this._kvo_changes;p||(p=this._kvo_changes=SC.CoreSet.create()),p.add(e),h&&(a&&SC.Logger.log("%@%@: will not notify observers because observing is suspended".fmt(SC.KVO_SPACES,this)),SC.Observers.objectHasPendingChanges(this))}else this._notifyPropertyObservers(e);return this},registerDependentKey:function(e,t){var n=this._kvo_dependents,r=this._kvo_chain_dependents,i=this[e],s,o,u,a,f;typeof t=="object"&&t instanceof Array?(s=t,u=0):(s=arguments,u=1),o=s.length,n||(this._kvo_dependents=n={});while(--o>=u)a=s[o],a.indexOf(".")>=0?SC._PropertyChain.createChain(a,this,e).activate():(f=n[a],f||(f=n[a]=[]),f.push(e))},registerDependentKeyWithChain:function(e,t){var n=this._chainsFor(e),r;n.add(t)},removeDependentKeyWithChain:function(e,t){var n=this._chainsFor(e),r;n.remove(t),n.get
("length")===0&&delete this._kvo_property_chains[e]},_chainsFor:function(e){this._kvo_property_chains=this._kvo_property_chains||{};var t=this._kvo_property_chains[e]||SC.CoreSet.create();return this._kvo_property_chains[e]=t,t},_kvo_addCachedDependents:function(e,t,n){var r=t.length,i,s,o;while(--r>=0)s=t[r],i=this[s],i&&i instanceof Function&&i.isProperty&&(i.isCacheable&&e.push(i),(o=n[s])&&o.length>0&&this._kvo_addCachedDependents(e,o,n))},_kvo_computeCachedDependentsFor:function(e){var t=this._kvo_cachedep,n=this._kvo_dependents,r=n?n[e]:null,i;return t||(t=this._kvo_cachedep={}),!r||r.length===0?t[e]=null:(i=t[e]=[],this._kvo_addCachedDependents(i,r,n),i.length===0&&(i=t[e]=null),i)},_kvo_for:function(e,t){var n=this[e];return this._kvo_cloned||(this._kvo_cloned={}),n?this._kvo_cloned[e]||(n=this[e]=n.copy(),this._kvo_cloned[e]=YES):(n=this[e]=t===undefined?[]:t.create(),this._kvo_cloned[e]=YES),n},addObserver:function(e,t,n,r){var i,s,o,u;n===undefined&&(n=t,t=this),t||(t=this),typeof n=="string"&&(n=t[n]);if(!n)throw"You must pass a method to addObserver()";return e=e.toString(),e.indexOf(".")>=0?(s=SC._ChainObserver.createChain(this,e,t,n,r),s.masterTarget=t,s.masterMethod=n,this._kvo_for(SC.keyFor("_kvo_chains",e)).push(s)):(this[e]===undefined&&e.indexOf("@")===0&&this.get(e),t===this&&(t=null),i=SC.keyFor("_kvo_observers",e),this._kvo_for(i,SC.ObserverSet).add(t,n,r),this._kvo_for("_kvo_observed_keys",SC.CoreSet).add(e)),this.didAddObserver&&this.didAddObserver(e,t,n),this},removeObserver:function(e,t,n){var r,i,s,o,u;n===undefined&&(n=t,t=this),t||(t=this),typeof
n=="string"&&(n=t[n]);if(!n)throw"You must pass a method to removeObserver()";e=e.toString();if(e.indexOf(".")>=0){r=SC.keyFor("_kvo_chains",e);if(i=this[r]){i=this._kvo_for(r),u=i.length;while(--u>=0)s=i[u],s&&s.masterTarget===t&&s.masterMethod===n&&(i[u]=s.destroyChain())}}else{t===this&&(t=null),r=SC.keyFor("_kvo_observers",e);if(o=this[r])o=this._kvo_for(r),o.remove(t,n),o.getMembers().length===0&&this._kvo_for("_kvo_observed_keys",SC.CoreSet).remove(e)}return this.didRemoveObserver&&this.didRemoveObserver(e,t,n),this},hasObserverFor:function(e){SC.Observers.flush(this);var t=this[SC.keyFor("_kvo_observers",e)],n=this[SC.keyFor("_kvo_local",e)],r;return n&&n.length>0?YES:t&&t.getMembers().length>0?YES:NO},initObservable:function(){if(this._observableInited)return;this._observableInited=YES;var e,t,n,r,i,s,o,u,a,f,l,c,h,p;if(t=this._observers){u=t.length;for(e=0;e<u;e++){n=t[e],i=this[n],s=i.propertyPaths,o=s?s.length:0;for(a=0;a<o;a++)f=s[a],this.addObservesHandler(i,f)}}this.bindings=[];if(t=this._bindings)for(e=0,p=t.length;e<p;e++)n=t[e],r=this[n],h=n.slice(0,-7),this[n]=this.bind(h,r);if(t=this._properties)for(e=0,p=t.length;e<p;e++){n=t[e];if(r=this[n])r.isCacheable&&(this._kvo_cacheable=YES),r.dependentKeys&&r.dependentKeys.length>0&&this.registerDependentKey(n,r.dependentKeys)}},addObservesHandler:function(e,t){return this._configureObservesHandler(SC.OBSERVES_HANDLER_ADD,e,t),this},removeObservesHandler:function(e,t){return this._configureObservesHandler(SC.OBSERVES_HANDLER_REMOVE,e,t),this},_configureObservesHandler:function(e,t,n){var r,i;switch(e){case SC.OBSERVES_HANDLER_ADD
:e="addObserver";break;case SC.OBSERVES_HANDLER_REMOVE:e="removeObserver";break;default:throw"invalid action provided: "+e}r=n.indexOf("."),r<0?this[e](n,this,t):n.indexOf("*")===0?this[e](n.slice(1),this,t):(i=null,r===0?(i=this,n=n.slice(1)):r===4&&n.slice(0,5)==="this."?(i=this,n=n.slice(5)):r<0&&n.length===4&&n==="this"?(i=this,n=""):r>0&&n[0]===n.charAt(0).toLowerCase()&&(i=this),SC.Observers[e](n,this,t,i))},observersForKey:function(e){SC.Observers.flush(this);var t=this[SC.keyFor("_kvo_observers",e)];return t?t.getMembers():[]},_notifyPropertyObservers:function(e){this._observableInited||this.initObservable(),SC.Observers.flush(this);var t=SC.LOG_OBSERVERS&&this.LOG_OBSERVING!==NO,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b;t&&(y=SC.KVO_SPACES=(SC.KVO_SPACES||"")+" ",SC.Logger.log('%@%@: notifying observers after change to key "%@"'.fmt(y,this,e))),s=this["_kvo_observers_*"],this._kvo_changeLevel=(this._kvo_changeLevel||0)+1;while((r=this._kvo_changes)&&r.length>0||e){a=++this.propertyRevision,r||(r=SC.CoreSet.create()),this._kvo_changes=null,e==="*"?(r.add("*"),r.addEach(this._kvo_for("_kvo_observed_keys",SC.CoreSet))):e&&r.add(e);if(i=this._kvo_dependents)for(o=0;o<r.length;o++){e=r[o],u=i[e];if(u&&(v=u.length)){t&&SC.Logger.log("%@...including dependent keys for %@: %@".fmt(y,e,u)),b=this._kvo_cache,b||(b=this._kvo_cache={});while(--v>=0){r.add(e=u[v]);if(m=this[e])this[m.cacheKey]=undefined,b[m.cacheKey]=b[m.lastSetValueKey]=undefined}}}while(r.length>0){e=r.pop(),n=this[SC.keyFor("_kvo_observers",e)];if(n){f=SC.clone(n.getMembers()),l=f.length;for(h=0;h<l;h++){c=f[h];if(
c[3]===a)continue;c[1]||SC.Logger.log(c),p=c[0]||this,d=c[1],g=c[2],c[3]=a,t&&SC.Logger.log('%@...firing observer on %@ for key "%@"'.fmt(y,p,e)),g!==undefined?d.call(p,this,e,null,g,a):d.call(p,this,e,null,a)}}f=this[SC.keyFor("_kvo_local",e)];if(f){l=f.length;for(h=0;h<l;h++)c=f[h],d=this[c],d&&(t&&SC.Logger.log('%@...firing local observer %@.%@ for key "%@"'.fmt(y,this,c,e)),d.call(this,this,e,null,a))}if(s&&e!=="*"){f=SC.clone(s.getMembers()),l=f.length;for(h=0;h<l;h++)c=f[h],p=c[0]||this,d=c[1],g=c[2],t&&SC.Logger.log('%@...firing * observer on %@ for key "%@"'.fmt(y,p,e)),g!==undefined?d.call(p,this,e,null,g,a):d.call(p,this,e,null,a)}this.propertyObserver&&(t&&SC.Logger.log('%@...firing %@.propertyObserver for key "%@"'.fmt(y,this,e)),this.propertyObserver(this,e,null,a))}r&&r.destroy(),e=null}return this._kvo_changeLevel=(this._kvo_changeLevel||1)-1,t&&(SC.KVO_SPACES=y.slice(0,-2)),YES},bind:function(e,t,n){var r,i;return n!==undefined&&(t=[t,n]),i=typeof t,i==="string"||i==="object"&&t instanceof Array?(r=this[e+"BindingDefault"]||SC.Binding,r=r.beget().from(t)):r=t.beget(),r=r.to(e,this).connect(),this.bindings.push(r),r},didChangeFor:function(e){var t,n,r,i,s,o,u,a,f;e=SC.hashFor(e),t=this._kvo_didChange_valueCache,t||(t=this._kvo_didChange_valueCache={}),n=this._kvo_didChange_revisionCache,n||(n=this._kvo_didChange_revisionCache={}),r=t[e]||{},i=n[e]||{},s=!1,o=this._kvo_revision||0,u=arguments.length;while(--u>=1)a=arguments[u],i[a]!=o&&(f=this.get(a),r[a]!==f&&(s=!0,r[a]=f)),i[a]=o;return t[e]=r,n[e]=i,s},setIfChanged:function(e,t){if(t===undefined&&SC.typeOf(e
.target,this.source,e,t,u,i||r,r)}},SC.OUT_OF_RANGE_EXCEPTION="Index out of range",SC.CoreArray={isSCArray:YES,replace:function(e,t,n){throw"replace() must be implemented to support SC.Array"},indexOf:function(e,t){var n,r=this.get("length");t===undefined?t=0:t=t<0?Math.ceil(t):Math.floor(t),t<0&&(t+=r);for(n=t;n<r;n++)if(this.objectAt(n,YES)===e)return n;return-1},lastIndexOf:function(e,t){var n,r=this.get("length");t===undefined?t=r-1:t=t<0?Math.ceil(t):Math.floor(t),t<0&&(t+=r);for(n=t;n>=0;n--)if(this.objectAt(n)===e)return n;return-1},objectAt:function(e){return e<0?undefined:e>=this.get("length")?undefined:this.get(e)},"[]":function(e,t){return t!==undefined&&this.replace(0,this.get("length"),t),this}.property(),insertAt:function(e,t){if(e>this.get("length"))throw SC.OUT_OF_RANGE_EXCEPTION;return this.replace(e,0,[t]),this},removeAt:function(e,t){var n=0,r=[];if(typeof e===SC.T_NUMBER){if(e<0||e>=this.get("length"))throw SC.OUT_OF_RANGE_EXCEPTION;if(t===undefined)return this.replace(e,1,r),this;e=SC.IndexSet.create(e,t)}return this.beginPropertyChanges(),e.forEachRange(function(e,t){e-=n,n+=t,this.replace(e,t,r)},this),this.endPropertyChanges(),this},removeObject:function(e){var t=this.get("length")||0;while(--t>=0){var n=this.objectAt(t);n==e&&this.removeAt(t)}return this},removeObjects:function(e){return this.beginPropertyChanges(),e.forEach(function(e){this.removeObject(e)},this),this.endPropertyChanges(),this},slice:function(e,t){var n=[],r=this.get("length");SC.none(e)&&(e=0);if(SC.none(t)||t>r)t=r;while(e<t)n[n.length]=this.objectAt(e++);return n},pushObject:function(
(e,t,i-t),this},unknownProperty:function(e,t){var n=this.reducedProperty(e,t);return t!==undefined&&n===undefined&&(n=this[e]=t),n}}),Array.prototype.indexOf===SC.CoreArray.indexOf&&(Array.prototype.indexOf=function(e,t){var n,r=this.length;t===undefined?t=0:t=t<0?Math.ceil(t):Math.floor(t),t<0&&(t+=r);for(n=t;n<r;n++)if(this[n]===e)return n;return-1}),Array.prototype.lastIndexOf===SC.CoreArray.lastIndexOf&&(Array.prototype.lastIndexOf=function(e,t){var n,r=this.length;t===undefined?t=r-1:t=t<0?Math.ceil(t):Math.floor(t),t<0&&(t+=r);for(n=t;n>=0;n--)if(this[n]===e)return n;return-1}),Date.now||(Date.now=function(){return(new Date).getTime()}),function(){var e=0,t=["ms","moz","webkit","o"],n;for(var r=0,i=t.length;r<i&&!window.requestAnimationFrame;++r)n=t[r],window.requestAnimationFrame=window[n+"RequestAnimationFrame"],window.cancelAnimationFrame=window[n+"CancelAnimationFrame"]||window[n+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(t,n){var r=SC.getCurrentTimeForPerformance(),i=Math.max(0,16-(r-e)),s=window.setTimeout(function(){t(r+i)},i);return e=r+i,s}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}(),SC.String={_scs_valueForKey:function(e,t,n){var r,i,s,o=e.indexOf(":");o>-1&&(r=e.substr(o+1),e=e.substr(0,o)),i=t[e],s=t[e+"Formatter"];if(s)i=s(i,r);else if(r)throw"String.fmt was given a formatting string, but key `"+e+"` has no formatter! String: "+n;return i},fmt:function(e,t){var n=0,r=undefined,i,s,o;return t&&(r=t[0]),s=e,o=e.replace(/%\{(.*?)\}/g,function(t,n){i=YES;if(!
r)throw"Cannot use named parameters with `fmt` without a data hash. String: '"+e+"'";return SC.String._scs_valueForKey(n,r,e)}),s.match(/%@/)&&(o=o.replace(/%@([0-9]+)?/g,function(r,s){if(i)throw"Invalid attempt to use both named parameters and indexed parameters. String: '"+e+"'";return s=s?parseInt(s,10)-1:n++,t[s]})),o},w:function(e){var t=[],n=e.split(" "),r=n.length,i,s=0;for(s=0;s<r;++s)i=n[s],i.length!==0&&t.push(i);return t}},SC.mixin(String.prototype,{fmt:function(){return SC.String.fmt(this,arguments)},w:function(){return SC.String.w(this)}}),SC.Comparable={isComparable:YES,compare:function(e,t){throw"%@.compare() is not implemented".fmt(this.toString())}},SC.Copyable={isCopyable:YES,copy:function(e){var t=SC._object_className(this.constructor);throw"%@.copy() is not implemented".fmt(t)},frozenCopy:function(){var e=this.get?this.get("isFrozen"):this.isFrozen;if(e===YES)return this;if(e===undefined)throw"%@ does not support freezing".fmt(this);return this.copy().freeze()}},SC.mixin(Array.prototype,SC.Copyable),Array.prototype.copy=function(e){var t=this.slice(),n;if(e){n=t.length;while(n--)t[n]=SC.copy(t[n],!0)}return t},SC.FROZEN_ERROR=new Error("Cannot modify a frozen object"),SC.Freezable={isFreezable:YES,isFrozen:NO,freeze:function(){return this.set?this.set("isFrozen",YES):this.isFrozen=YES,this}},SC.mixin(Array.prototype,SC.Freezable),SC.Set=SC.mixin({},SC.Enumerable,SC.Observable,SC.Freezable,{create:function(e){var t,n,r=SC.Set._pool,i=this.isObservable,s;if(!i&&e===undefined&&r.length>0)return r.pop();t=SC.beget(this),i&&t.initObservable();if(e&&e.isEnumerable&&
){this.isObservingSuspended++},resumePropertyObserving:function(){var e;if(--this.isObservingSuspended<=0){e=this._pending,this._pending=SC.CoreSet.create();var t,n=e.length;for(t=0;t<n;t++)e[t]._notifyPropertyObservers();e.clear(),e=null}}},SC.BENCHMARK_OBJECTS=NO,SC._detect_base=function(t,n,r){return function(){var i=n[r],s;if(!i)throw new Error("No '"+r+"' method was found on the superclass");return t.isEnhancement?s=Array.prototype.slice.call(arguments,1):s=arguments,i.apply(this,s)}},SC._object_extend=function(t,n,r){if(!n)throw"SC.Object.extend expects a non-null value. Did you forget to 'sc_require' something? Or were you passing a Protocol to extend() as if it were a mixin?";t._kvo_cloned=null;var i,s,o,u,a=t.concatenatedProperties,f=SC.K,l,c;s=a?a.length:0;var h=s>0?{}:null;while(--s>=0)i=a[s],l=t[i],c=n[i],l?(l instanceof Array||(l=SC.$A(l)),h[i]=c?l.concat(c):c):(c instanceof Array||(c=SC.$A(c)),h[i]=c);var p=t._bindings,d=NO,v=t._observers,m=NO,g=t._properties,y=NO,b,w,E,S,x=t.outlets,T=NO;n.outlets&&(x=(x||SC.EMPTY_ARRAY).concat(n.outlets),T=YES);for(i in n){if(i==="_kvo_cloned")continue;if(!n.hasOwnProperty(i))continue;S=(h.hasOwnProperty(i)?h[i]:null)||n[i];if(i.length>7&&i.slice(-7)==="Binding")d||(p=(p||SC.EMPTY_ARRAY).slice(),d=YES),p===null&&(p=(t._bindings||SC.EMPTY_ARRAY).slice()),p[p.length]=i;else if(S&&S instanceof Function){!S.superclass&&S!==(u=t[i])&&(S.superclass=u||f,S.base=r?SC._detect_base(S,r,i):u||f),S.propertyPaths&&(m||(v=(v||SC.EMPTY_ARRAY).slice(),m=YES),v[v.length]=i);if(b=S.localPropertyPaths){w=b.length;while(--w>=0)E=t._kvo_for(SC.
(e);else{if(!t.addObject)throw"%@.content does not support addObject".fmt(this);t.addObject(e)}return this},removeObject:function(e){if(!this.get("canRemoveContent"))throw"%@ cannot remove content".fmt(this);var t=this.get("content");return t.isEnumerable?t.removeObject(e):this.set("content",null),this.get("destroyOnRemoval")&&e.destroy&&e.destroy(),this},length:function(){var e=this._scac_observableContent();return e?e.get("length"):0}.property().cacheable(),objectAt:function(e){var t=this._scac_observableContent();return t?t.objectAt(e):undefined},replace:function(e,t,n){if(!n||n.get("length")===0){if(!this.get("canRemoveContent"))throw"%@ cannot remove objects from the current content".fmt(this)}else if(!this.get("canReorderContent"))throw"%@ cannot add or reorder the current content".fmt(this);var r=this.get("content"),i=[],s,o;if(this.get("destroyOnRemoval"))for(s=0;s<t;s++)i.push(r.objectAt(s+e));r&&r.replace(e,t,n);for(s=0,o=i.length;s<o;s++)i[s].destroy();return i=null,this},indexOf:function(e,t){var n=this._scac_observableContent();return n?n.indexOf(e,t):-1},init:function(){arguments.callee.base.apply(this,arguments),this._scac_contentDidChange()},_scac_cached:NO,_scac_observableContent:function(){var e=this._scac_cached;if(e)return e;var t=this.get("content"),n,r,i;if(SC.none(t))return this._scac_cached=[];if(!t.isEnumerable)return e=this.get("allowsSingleContent")?[t]:[],this._scac_cached=e;var s=this.get("orderBy");if(!s){if(t.isSCArray)return this._scac_cached=t;throw"%@.orderBy is required for unordered content".fmt(this)}var o=SC.typeOf(s);if(o===SC.T_STRING)
s=[s];else if(o===SC.T_FUNCTION)n=s;else if(o!==SC.T_ARRAY)throw"%@.orderBy must be Array, String, or Function".fmt(this);return n=n||function(e,t){var n,r,o,u;for(var a=0,f=s.get("length");a<f&&!n;a++)r=s.objectAt(a),o=r.match(/^(ASC )?(DESC )?(.*)$/),r=o[3],i=o[2]?-1:1,e&&(e=e.isObservable?e.get(r):e[r]),t&&(t=t.isObservable?t.get(r):t[r]),n=SC.compare(e,t)*i;return n},this._scac_cached=t.toArray().sort(n)},propertyWillChange:function(e){if(e!=="content")return arguments.callee.base.apply(this,arguments);this.arrayContentWillChange(0,this.get("length"),0)},_scac_arrayContentWillChange:function(e,t,n){this.arrayContentWillChange(e,t,n);if(this._kvo_enumerable_property_chains){var r=this.slice(e,e+t);this.teardownEnumerablePropertyChains(r)}},_scac_arrayContentDidChange:function(e,t,n){var r=this._scac_observableContent(),i=r?r.get("length"):0;this._scac_length=i,this._scac_cached=NO,this.notifyPropertyChange("length");if(this._kvo_enumerable_property_chains){var s=this.slice(e,e+n);this.setupEnumerablePropertyChains(s)}this.updateSelectionAfterContentChange(),this.arrayContentDidChange(e,t,n)},_scac_contentDidChange:function(){this._scac_cached=NO;var e=this.get("content"),t=!!this.get("orderBy"),n=this._scac_content,r=this._scac_length||0,i=this._scac_arrayContentDidChange,s=this._scac_arrayContentWillChange,o=this._scac_contentStatusDidChange,u=this._scac_enumerableDidChange,a;if(e===n)return this;this.arrayContentWillChange(0,r,a),n&&(n.isSCArray?n.removeArrayObservers({target:this,didChange:i,willChange:s}):n.isEnumerable&&n.removeObserver("[]",this,u),n.removeObserver("status"
).match(/^(ar|iw)-.*/)}.property("language").cacheable(),toString:function(){return this.language||SC.Locale._assignLocales(),"SC.Locale["+this.language+"]"+SC.guidFor(this)},locWithDefault:function(e,t){var n=this.strings[e];return SC.typeOf(n)===SC.T_STRING?n:SC.typeOf(t)===SC.T_STRING?t:e},locMetric:function(e){var t=this.metrics[e];return SC.typeOf(t)===SC.T_NUMBER?t:t===undefined?(SC.warn('No localized metric found for key "'+e+'"'),undefined):(SC.warn('Unexpected metric type for key "'+e+'"'),undefined)},locLayout:function(e,t){var n,r,i,s,o,u=SC.Locale.layoutKeys,a=this.metrics,f=SC.typeOf,l=SC.T_NUMBER,c={};t&&SC.mixin(c,t);for(n=0,r=u.length;n<r;++n){i=u[n],s=e+"."+i,o=a[s];if(f(o)===l){if(t&&t[i])throw"locLayout(): There is a localized value for the key '"+s+"' but a value for '"+i+"' was also specified in the non-localized hash";c[i]=o}}return c}}),SC.Locale.mixin(SC.Observable,{useAutodetectedLanguage:NO,preferredLanguage:null,layoutKeys:["left","top","right","bottom","width","height","minWidth","minHeight","centerX","centerY"],createCurrentLocale:function(){var e=String.useAutodetectedLanguage!==undefined?String.useAutodetectedLanguage:this.useAutodetectedLanguage,t=String.preferredLanguage!==undefined?String.preferredLanguage:this.preferredLanguage,n=(e?SC.browser.language:null)||t||SC.browser.language||"en";n=SC.Locale.normalizeLanguage(n);var r=this.localeClassFor(n);return n!=this.currentLanguage&&(this.currentLanguage=n,this.set("currentLocale",r.create({language:n}))),this.currentLocale},localeClassFor:function(e){e=SC.Locale.normalizeLanguage(e);var t,n=
this.locales[e];return!n&&(t=e.split("-")[0])!==e&&(n=this.locales[t])&&(n=this.locales[e]=n.extend()),n||(n=this.locales[e]=this.locales.en.extend()),n},define:function(e,t){var n;return t===undefined&&SC.typeOf(e)!==SC.T_STRING?(n=this,t=e):n=SC.Locale.localeClassFor(e),SC.mixin(n.prototype,t),n},options:function(){return this.prototype},addStrings:function(e){var t=this.prototype.strings;return t?this.prototype.hasOwnProperty("strings")||(this.prototype.strings=SC.clone(t)):t=this.prototype.strings={},e&&(this.prototype.strings=SC.mixin(t,e)),this.prototype.hasStrings=YES,this},addMetrics:function(e){var t=this.prototype.metrics;return t?this.prototype.hasOwnProperty(t)||(this.prototype.metrics=SC.clone(t)):t=this.prototype.metrics={},e&&(this.prototype.metrics=SC.mixin(t,e)),this},_map:{english:"en",french:"fr",german:"de",japanese:"ja",jp:"ja",spanish:"es"},normalizeLanguage:function(e){return e?SC.Locale._map[e.toLowerCase()]||e:"en"},_assignLocales:function(){for(var e in this.locales)this.locales[e].prototype.language=e},toString:function(){return this.prototype.language||SC.Locale._assignLocales(),"SC.Locale["+this.prototype.language+"]"},extend:function(){var e=SC.Object.extend.apply(this,arguments);return e.addStrings=SC.Locale.addStrings,e.define=SC.Locale.define,e.options=SC.Locale.options,e.toString=SC.Locale.toString,e}}),SC.Locale.locales={en:SC.Locale.extend({_deprecatedLanguageCodes:["English"]}),fr:SC.Locale.extend({_deprecatedLanguageCodes:["French"]}),de:SC.Locale.extend({_deprecatedLanguageCodes:["German"]}),ja:SC.Locale.extend({_deprecatedLanguageCodes
:function(e){if(!e)return"(No Responder)";if(e._scrc_name)return e._scrc_name;var t=this.NAMESPACE;return this._findResponderNamesFor(this,3,t?[this.NAMESPACE]:[]),e._scrc_name||e.toString()},_findResponderNamesFor:function(e,t,n){var r,i;for(r in e){if(r==="nextResponder")continue;i=e[r];if(i&&i.isResponder){if(i._scrc_name)continue;n.push(r),i._scrc_name=n.join("."),t>0&&this._findResponderNamesFor(i,t-1,n),n.pop()}}},makeFirstResponder:function(e,t){var n=this.get("firstResponder"),r=this.get("nextResponder"),i=this.get("trace"),s;if(this._locked){i&&SC.Logger.log("%@: AFTER ACTION: makeFirstResponder => %@".fmt(this,this.responderNameFor(e))),this._pendingResponder=e;return}i&&SC.Logger.log("%@: makeFirstResponder => %@".fmt(this,this.responderNameFor(e))),e&&e.set("becomingFirstResponder",YES),this._locked=YES,this._pendingResponder=null,s=e?e:null;while(s){if(s.get("hasFirstResponder"))break;s=s===r?null:this.nextResponderFor(s)}return s||(s=r),this._notifyWillLoseFirstResponder(n,n,s,t),n&&n.set("isFirstResponder",NO),this.beginPropertyChanges(),this.set("firstResponder",e),e&&e.set("isFirstResponder",YES),this._notifyDidBecomeFirstResponder(e,e,s),this.endPropertyChanges(),this._locked=NO,this._pendingResponder&&(this.makeFirstResponder(this._pendingResponder),this._pendingResponder=null),e&&e.set("becomingFirstResponder",NO),this},_notifyWillLoseFirstResponder:function(e,t,n,r){if(!t||t===n)return;t.willLoseFirstResponder(e,r),t.set("hasFirstResponder",NO);var i=this.nextResponderFor(t);i&&this._notifyWillLoseFirstResponder(e,i,n)},_notifyDidBecomeFirstResponder:function(
e,t,n){if(!t||t===n)return;var r=this.nextResponderFor(t);r&&this._notifyDidBecomeFirstResponder(e,r,n),t.set("hasFirstResponder",YES),t.didBecomeFirstResponder(e)},resetFirstResponder:function(){var e=this.get("firstResponder");if(!e)return;e.willLoseFirstResponder(),e.didBecomeFirstResponder()},sendAction:function(e,t,n){var r=this.get("firstResponder"),i=this.get("nextResponder"),s=this.get("trace"),o=NO,u;this._locked=YES,s&&SC.Logger.log("%@: begin action '%@' (%@, %@)".fmt(this,e,t,n)),!o&&!r&&this.tryToPerform&&(o=this.tryToPerform(e,t,n));while(!o&&r)r.tryToPerform&&(o=r.tryToPerform(e,t,n)),o||(r=r===i?null:this.nextResponderFor(r));s&&(o?SC.Logger.log("%@: action '%@' handled by %@".fmt(this,e,this.responderNameFor(r))):SC.Logger.log("%@: action '%@' NOT HANDLED".fmt(this,e))),this._locked=NO;if(u=this._pendingResponder)this._pendingResponder=null,this.makeFirstResponder(u);return r}},SC.RTLSupport={layoutRecipe:null,init:function(e){e();if(!this._isLayoutHashEqualToDefault())throw new Error('The layout value set for "%@" is neither null nor has the default value of {top: 0, left: 0, bottom: 0, right: 0}.'.fmt(this)+"While using this mixin the layout value should not be set. Instead layoutRecipe should be used.");this.layoutDirectionDidChange()}.enhance(),layoutDirectionDidChange:function(){if(!this._isLayoutRecipeValid())throw new Error('The layoutRecipe set for "%@" is not valid. Either it is null or it has "left" and "right" values.'.fmt(this));var e=this.get("layoutRecipe"),t=this._isPreviousLayoutDirectionRTL,n=SC.Locale.currentLocale.get("isRTL");if(t!==n){var r=
SC.clone(e),i=r.start,s=r.end,o,u;n?(u=i,o=s):(o=i,u=s),delete r.start,delete r.end,o!==undefined&&(r.left=o),u!==undefined&&(r.right=u),this.set("layout",r)}this._isPreviousLayoutDirectionRTL=n}.observes("SC.Locale.currentLocale"),_isPreviousLayoutDirectionRTL:null,_isLayoutHashEqualToDefault:function(){var e=this.get("layout"),t=!0,n;if(e){var r=SC.View.prototype.layout,i={};for(n in e){if(e[n]!==r[n]){t=!1;break}i[n]=!0}if(t)for(n in r)if(!i[n]){t=!1;break}}return t},_isLayoutRecipeValid:function(){var e=this.get("layoutRecipe"),t=!0;if(e){if(e.left!==undefined||e.right!==undefined)t=!1}else t=!1;return t}},SC.bodyOverflowArbitrator=SC.Object.create({requestHidden:function(e,t){this._makeRequest(e,-1-9*!!t)},requestVisible:function(e,t){this._makeRequest(e,1+9*!!t)},withdrawRequest:function(e){if(!e)return;var t=SC.guidFor(e);this._requests[t]&&delete this._requests[t],this.setOverflow()},setOverflow:function(){var e=this._decideOverflow();e!==undefined&&(document.body.style.overflow=e?"auto":"hidden")},_makeRequest:function(e,t){if(!e)return;var n=SC.guidFor(e);this._requests[n]=t,this.setOverflow()},_requests:{},_decideOverflow:function(){var e,t,n,r,i=this._requests,s;for(var o in i)(s=i[o])<0&&(e=YES),s<-1&&(n=YES),s>0&&(t=YES),s>1&&(r=YES);return r?YES:t&&n?NO:t?YES:e?NO:undefined}}),SC.mixin(SC.browser,{compareVersion:function(){if(this._versionSplit===undefined){var e=function(e){return Number(e.match(/^[0-9]+/))};this._versionSplit=SC.A(this.version.split(".")).map(e)}var t=SC.A(arguments).map(Number);for(var n=0;n<t.length;n++){var r=this._versionSplit[n]-t[n];if(
);return e&&e.removeChild(this),this},destroy:function(){return this.get("isDestroyed")?this:(this._destroy(),this.get("parentView")&&this.removeFromParent(),arguments.callee.base.apply(this,arguments))},_destroy:function(){this.destroyLayer();var e=this.get("childViews"),t=e.length,n;if(t){e=e.slice();for(n=0;n<t;++n)e[n].destroy()}return delete SC.View.views[this.get("layerId")],delete this._CQ,delete this.page,this.get("parentView")&&this.removeFromParent(),this.set("owner",null),this},createChildViews:function(){var e=this.get("childViews"),t=e.length,n,r,i,s;this.beginPropertyChanges();for(n=0;n<t;++n){if(r=s=e[n]){typeof r===SC.T_STRING?s=this[r]:r=null;if(!s){SC.Logger.error("No view with name "+r+" has been found in "+this.toString());continue}s=this.createChildView(s),r&&(this[r]=s)}e[n]=s}return this.endPropertyChanges(),this},createChildView:function(e,t){return e.isClass?t?t=SC.clone(t):t={}:t=e,t.owner=t.parentView=this,e.isClass&&e.prototype.hasVisibility&&(t.isVisibleInWindow=this.get("isVisibleInWindow")),t.page||(t.page=this.page),e.isClass&&(e=e.create(t)),e},isView:YES,selectStart:function(e){return this.get("isTextSelectable")},isContextMenuEnabled:SC.CONTEXT_MENU_ENABLED,contextMenu:function(e){return!this.get("isContextMenuEnabled")}}),SC.CoreView.mixin({isViewClass:YES,design:function(){if(this.isDesign)return this;var e=this.extend.apply(this,arguments);return e.isDesign=YES,e},extend:function(){var e=arguments[arguments.length-1];return e&&!SC.none(e.theme)&&typeof e.theme=="string"&&(e.themeName=e.theme,delete e.theme),SC.Object.extend.apply(this,arguments
]}),SC.browser.msie&&SC.Event.add(window,"unload",SC.View,SC.View.unload),SC.ANIMATABLE_PROPERTIES={top:YES,left:YES,bottom:YES,right:YES,width:YES,height:YES,centerX:YES,centerY:YES,opacity:YES,scale:YES,rotate:YES,rotateX:YES,rotateY:YES,rotateZ:YES},SC.View.reopen({didCreateLayerMixin:function(){SC.platform.supportsCSSTransitions&&this.resetAnimation()},animate:function(e,t,n,r){var i,s;typeof e===SC.T_STRING?(i={},i[e]=t,s=n):(i=e,s=t,r=n);var o=SC.typeOf(s);if(o===SC.T_NUMBER)s={duration:s};else if(o!==SC.T_HASH)throw"Must provide options hash or duration!";r&&(s.callback=r);var u=s.timing;u?typeof u!==SC.T_STRING&&(s.timing="cubic-bezier("+u[0]+", "+u[1]+", "+u[2]+", "+u[3]+")"):s.timing="linear";var a=SC.clone(this.get("layout")),f=NO,l,c,h,p,d;a.animate||(a.animate={});for(d in i){if(!i.hasOwnProperty(d)||!SC.ANIMATABLE_PROPERTIES[d])continue;l=i[d],c=a[d],p=a.animate[d];if(l==null)throw"Can only animate to an actual value!";if(c!==l||p&&p.duration!==s.duration)f=YES,a.animate[d]=s,a[d]=l}return f&&this.set("layout",a),this},resetAnimation:function(){var e=this.get("layout"),t=e.animate,n=NO,r;if(!t)return;var i;for(r in t)n=YES,delete t[r];return n&&(this.set("layout",e),this.notifyPropertyChange("layout")),this},transitionDidEnd:function(e){this.get("layoutStyleCalculator").transitionDidEnd(e)}}),SC.CSS_TRANSFORM_MAP={rotate:function(e){return null},rotateX:function(e){return SC.typeOf(e)===SC.T_NUMBER&&(e+="deg"),"rotateX("+e+")"},rotateY:function(e){return SC.typeOf(e)===SC.T_NUMBER&&(e+="deg"),"rotateY("+e+")"},rotateZ:function(e){return SC.typeOf(e)===SC.T_NUMBER&&
.opacity!=null?e.opacity.toString():null,this.backgroundPosition=e.backgroundPosition!=null?e.backgroundPosition:null,this.ret={marginTop:null,marginLeft:null}},_invalidAutoValue:function(e){var t=SC.Error.desc("%@.layout() you cannot use %@:auto if staticLayout is disabled".fmt(this.get("view"),e),"%@".fmt(this.get("view")),-1);throw SC.Logger.error(t.toString()),t},_handleMistakes:function(){var e=this.get("layout");this.staticLayout||(this.width===SC.LAYOUT_AUTO&&this._invalidAutoValue("width"),this.height===SC.LAYOUT_AUTO&&this._invalidAutoValue("height"));if(SC.platform.supportsCSSTransforms){var t=e.animate,n,r;if(t)for(r in t)if(SC.CSS_TRANSFORM_MAP[r]){if(this._pendingAnimations&&this._pendingAnimations["-"+SC.platform.cssPrefix+"-transform"])throw"Animations of transforms must be executed simultaneously!";n&&t[r].duration!==n&&(SC.Logger.warn("Can't animate transforms with different durations! Using first duration specified."),t[r].duration=n),n=t[r].duration}}},_calculatePosition:function(e){var t=null,n=this.get("turbo"),r=this.ret;if(!r)return t;var i,s,o,u,a,f,l,c,h,p,d,v,m,g;e==="x"?(i="left",s="right",o="width",u="maxWidth",a="marginLeft",p="borderLeft",v="borderRight",f=this.hasLeft,l=this.hasRight,c=this.hasWidth,h=this.hasMaxWidth):(i="top",s="bottom",o="height",u="maxHeight",a="marginTop",p="borderTop",v="borderBottom",f=this.hasTop,l=this.hasBottom,c=this.hasHeight,h=this.hasMaxHeight),r[i]=this._cssNumber(this[i]),r[s]=this._cssNumber(this[s]),d=this._cssNumber(this[p]),m=this._cssNumber(this[v]),r[p+"Width"]=d||null,r[v+"Width"]=m||null,g=this[o],g>=1&&
(g-=d+m),r[o]=this._cssNumber(g);if(f)n&&(t=r[i],r[i]=0),l&&c&&(r[s]=null);else if(!l||l&&!c&&!h)r[i]=0;return!c&&!l&&(r[s]=0),t},_calculateCenter:function(e){var t=this.ret,n,r,i,s,o,u,a,f,l;e==="x"?(n="width",r="centerX",i="left",s="right",o="marginLeft",u="borderLeft",f="borderRight"):(n="height",r="centerY",i="top",s="bottom",o="marginTop",u="borderTop",f="borderBottom"),t[i]="50%",a=this._cssNumber(this[u]),l=this._cssNumber(this[f]),t[u+"Width"]=a||null,t[f+"Width"]=l||null;var c=this[n],h=this[r],p=this[i],d=SC.isPercentage(c),v=SC.isPercentage(h,YES);c>1&&(c-=a+l);if(d&&v||!d&&!v){var m=h-c/2;t[o]=d?m*100+"%":m}else SC.Logger.warn("You have to set "+n+" and "+r+" using both percentages or pixels"),t[o]="50%";t[n]=this._cssNumber(c)||0,t[s]=null},_calculateTransforms:function(e,t){if(SC.platform.supportsCSSTransforms){var n=this.get("layout"),r=SC.platform.domCSSPrefix+"Transform",i=[];this.turbo&&(i.push("translateX("+(e||0)+"px)","translateY("+(t||0)+"px)"),SC.platform.supportsCSS3DTransforms&&i.push("translateZ(0px)"));var s=SC.CSS_TRANSFORM_MAP;for(var o in s){var u=n[o];u!=null&&i.push(s[o](u))}this.ret[r]=i.length>0?i.join(" "):null}},_calculateAnimations:function(e,t){var n=this.layout,r=n.animate,i;if(!r)return;if(this.getPath("view.isAnimatable"))return;var s=[],o;this._animatedTransforms=[],this._pendingAnimations||(this._pendingAnimations={});var u="-"+SC.platform.cssPrefix+"-transform";if(SC.platform.supportsCSSTransitions){for(i in r){o=r[i];var a=SC.CSS_TRANSFORM_MAP[i],f=i==="top"&&t!=null||i==="left"&&e!=null;SC.platform.supportsCSSTransforms&&(f||a)&&
(this._animatedTransforms.push(i),i=u),o.css=i+" "+o.duration+"s "+o.timing,this._pendingAnimations[i]||(this._pendingAnimations[i]=o,s.push(o.css))}this.ret[SC.platform.domCSSPrefix+"Transition"]=s.join(", ")}else for(i in r)this._pendingAnimations[i]=r[i];delete n.animate},_cssNumber:function(e){return e==null?null:e===SC.LAYOUT_AUTO?SC.LAYOUT_AUTO:SC.isPercentage(e)?e*100+"%":e},calculate:function(){var e=this.get("layout"),t=null,n=this.get("staticLayout"),r=null,i=null,s=this.get("turbo"),o=this.ret,u=this.dims,a=this.loc,f=this.get("view"),l,c;this._handleMistakes(e);if(n&&e===SC.View.prototype.layout)return{};this.hasLeft||this.hasRight||!this.hasCenterX?i=this._calculatePosition("x"):this._calculateCenter("x"),this.hasTop||this.hasBottom||!this.hasCenterY?r=this._calculatePosition("y"):this._calculateCenter("y"),o.minWidth=this.minWidth,o.maxWidth=this.maxWidth,o.minHeight=this.minHeight,o.maxHeight=this.maxHeight,o.zIndex=this.zIndex,o.opacity=this.opacity,o.backgroundPosition=this.backgroundPosition,this._calculateTransforms(i,r),this._calculateAnimations(i,r);for(l in o)c=o[l],typeof c===SC.T_NUMBER&&(o[l]=c+"px");return o},willRenderAnimations:function(){if(SC.platform.supportsCSSTransitions){var e=this.get("view"),t=e.get("layer"),n=t?t.style:null,r=e.get("layoutStyle"),i=this._activeAnimations,s,o=this._pendingAnimations,u,a=this._animatedTransforms,f=a?a.length:0,l=r[SC.platform.domCSSPrefix+"Transition"],c=e.get("layout"),h,p,d,v;if(o){i||(i={});for(h in o){if(!o.hasOwnProperty(h))continue;u=o[h],s=i[h],v=NO,r[h]!==(n?n[h]:null)&&(v=YES),s&&(s.duration!==u.duration||
s.timing!==u.timing)&&(v=YES);if(v&&s){if(p=s.callback)if(f>0){for(d=0;d<f;d++)this.runAnimationCallback(p,null,a[d],YES);this._animatedTransforms=null}else this.runAnimationCallback(p,null,h,YES);this.removeAnimationFromLayout(h,YES)}i[h]=u}}this._activeAnimations=i,this._pendingAnimations=null}},didRenderAnimations:function(){if(!SC.platform.supportsCSSTransitions){var e,t;for(e in this._pendingAnimations)t=this._pendingAnimations[e].callback,t&&this.runAnimationCallback(t,null,e,NO),this.removeAnimationFromLayout(e,NO,YES);this._activeAnimations=this._pendingAnimations=null}},runAnimationCallback:function(e,t,n,r){var i=this.get("view");e&&(SC.typeOf(e)!==SC.T_HASH&&(e={action:e}),e.source=i,e.target||(e.target=this)),SC.View.runCallback(e,{event:t,propertyName:n,view:i,isCancelled:r})},transitionDidEnd:function(e){var t=e.originalEvent.propertyName,n,r;n=this._activeAnimations?this._activeAnimations[t]:null;if(n){if(n.callback){SC.RunLoop.begin();if(this._animatedTransforms&&this._animatedTransforms.length>0)for(r=0;r<this._animatedTransforms.length;r++)this.invokeLater("runAnimationCallback",1,n.callback,e,this._animatedTransforms[r],NO);else this.invokeLater("runAnimationCallback",1,n.callback,e,t,NO);SC.RunLoop.end()}this.removeAnimationFromLayout(t,YES)}},removeAnimationFromLayout:function(e,t,n){if(t){var r=this.getPath("view.layer"),i=[],s;for(s in this._activeAnimations)s!==e&&i.push(this._activeAnimations[s].css);r&&(r.style[SC.platform.domCSSPrefix+"Transition"]=i.join(", "))}var o=this.getPath("view.layout"),u;if(e==="-"+SC.platform.cssPrefix+"-transform"&&this
._animatedTransforms&&this._animatedTransforms.length>0){for(u=0;u<this._animatedTransforms.length;u++)delete o["animate"+SC.String.capitalize(this._animatedTransforms[u])];this._animatedTransforms=null}delete o["animate"+SC.String.capitalize(e)],n||delete this._activeAnimations[e]}}),SC.CoreView.runCallback=function(e){var t=SC.$A(arguments).slice(1),n=SC.typeOf(e.action);if(n==SC.T_FUNCTION)e.action.apply(e.target,t);else if(n===SC.T_STRING&&e.action.indexOf(".")>=0){var r=e.action.split("."),i=r.pop(),s=SC.objectForPropertyPath(r,window),o=s.get?s.get(i):s[i];if(!o||SC.typeOf(o)!=SC.T_FUNCTION)throw"SC.runCallback could not find a function at %@".fmt(e.action);o.apply(s,t)}},SC.View.runCallback=SC.CoreView.runCallback,SC.View.reopen({wantsAcceleratedLayer:NO,hasAcceleratedLayer:function(){if(this.get("wantsAcceleratedLayer")&&SC.platform.supportsAcceleratedLayers){var e=this.get("layout"),t=e.animate,n=SC.LAYOUT_AUTO,r;if(t&&(t.top||t.left))for(r in t)if(SC.CSS_TRANSFORM_MAP[r]&&(t.top&&t.top.duration!==t[r].duration||t.left&&t.left.duration!==t[r].duration))return NO;if(e.left!=null&&!SC.isPercentage(e.left)&&e.left!==n&&e.top!=null&&!SC.isPercentage(e.top)&&e.top!==n&&e.width!=null&&!SC.isPercentage(e.width)&&e.width!==n&&e.height!=null&&!SC.isPercentage(e.height)&&e.height!==n)return YES}return NO}.property("wantsAcceleratedLayer").cacheable()}),SC.View.reopen({cursor:function(e,t){var n;return t&&(this._setCursor=t),this._setCursor!==undefined?this._setCursor:(n=this.get("parentView"),this.get("shouldInheritCursor")&&n?n.get("cursor"):null)}.property("parentView","shouldInheritCursor"
("layout").cacheable(),convertFrameToView:function(e,t){var n=0,r=0,i=0,s=0,o=this,u;while(o)u=o.get("frame"),n+=u.x,r+=u.y,o=o.get("layoutView");if(t){o=t;while(o)u=o.get("frame"),i+=u.x,s+=u.y,o=o.get("layoutView")}return n=e.x+n-i,r=e.y+r-s,{x:n,y:r,width:e.width,height:e.height}},convertFrameFromView:function(e,t){var n=0,r=0,i=0,s=0,o=this,u;while(o&&(u=o.get("frame")))n+=u.x,r+=u.y,o=o.get("parentView");if(t){o=t;while(o)u=o.get("frame"),i+=u.x,s+=u.y,o=o.get("parentView")}return n=e.x-n+i,r=e.y-r+s,{x:n,y:r,width:e.width,height:e.height}},scrollToVisible:function(){var e=this.get("parentView");while(e&&!e.get("isScrollable"))e=e.get("parentView");return e?(e.scrollToVisible(),e.scrollToVisible(this)):NO},_adjustForBorder:function(e,t){var n=(t.borderTop!==undefined?t.borderTop:t.border)||0,r=(t.borderLeft!==undefined?t.borderLeft:t.border)||0,i=(t.borderBottom!==undefined?t.borderBottom:t.border)||0,s=(t.borderRight!==undefined?t.borderRight:t.border)||0;return e.x+=r,e.y+=n,e.width-=r+s,e.height-=n+i,e},computeFrameWithParentFrame:function(e,t){var n,r=this.get("layout");if(this.get("useStaticLayout"))return n=e(),n?this._adjustForBorder(n,r):null;n={};var i,s,o=SC.LAYOUT_AUTO,u=this.get("parentView"),a,f,l=r.right,c=r.left,h=r.top,p=r.bottom,d=r.width,v=r.height,m=r.centerX,g=r.centerY;if(d===o)throw i=SC.Error.desc("%@.layout() cannot use width:auto if staticLayout is disabled".fmt(this),"%@".fmt(this),-1),SC.Logger.error(i.toString()),i;if(v===o)throw i=SC.Error.desc("%@.layout() cannot use height:auto if staticLayout is disabled".fmt(this),"%@".fmt(this),-1),SC.Logger
);this.destroyLayer(),e&&this.invokeLast(this.append)},init:function(){this.hasTouchIntercept===YES&&(SC.Logger.warn("Do not set hasTouchIntercept directly. Use wantsTouchIntercept instead."),this.hasTouchIntercept=SC.platform.touch);var e=!!this.get("layer");arguments.callee.base.apply(this,arguments),e&&this.paneDidAttach()},classNames:["sc-pane"]}),SC.Pane.reopen({performKeyEquivalent:function(e,t){var n=arguments.callee.base.apply(this,arguments);if(!n){var r=this.get("defaultResponder");r&&(r.performKeyEquivalent&&(n=r.performKeyEquivalent(e,t)),!n&&r.tryToPerform&&(n=r.tryToPerform(e,t)))}return n},keyDown:function(e){var t;if((e.which===9||SC.browser.mozilla&&e.keyCode===9)&&!this.get("firstResponder")){e.shiftKey?t=this.get("previousValidKeyView"):t=this.get("nextValidKeyView");if(t)return this.makeFirstResponder(t),YES;SC.TABBING_ONLY_INSIDE_DOCUMENT||e.allowDefault()}return NO},_forwardKeyChange:function(e,t,n,r){var i,s,o;e&&(s=this.get("firstResponder"))&&(o=n?n.get("firstResponder"):null,i=this.get("firstResponder"),i&&i[t]&&i[t](o),r!==undefined&&s&&s.set("isKeyResponder",r))}}),SC.Pane.reopen({currentWindowSize:null,computeParentDimensions:function(e){var t={x:0,y:0,width:1e3,height:1e3},n=this.get("layout");document&&document.body&&(t.width=document.body.clientWidth,t.height=document.body.clientHeight);if(n.minHeight||n.minWidth)n.minHeight&&(t.height=Math.max(t.height,n.minHeight)),n.minWidth&&(t.width=Math.max(t.width,n.minWidth));return t},frame:function(){return this.computeFrameWithParentFrame(null)}.property(),enforcesBodyOverflow:NO,windowSizeDidChange
:function(e,t){return this.set("currentWindowSize",t),this.setBodyOverflowIfNeeded(),this.parentViewDidResize(),this},setBodyOverflowIfNeeded:function(e){if(!this.get("enforcesBodyOverflow"))return;var t=this.get("layout"),n=this.get("currentWindowSize");if(!t||!n||!n.width||!n.height)return;var r=t.minWidth,i=t.minHeight;if(e===!0||r||i)i&&n.height<i||r&&n.width<r?SC.bodyOverflowArbitrator.requestVisible(this):SC.bodyOverflowArbitrator.requestHidden(this)},paneLayoutDidChange:function(){this.invokeOnce(this.updateLayout),this.setBodyOverflowIfNeeded()}.observes("layout"),recomputeDependentProperties:function(e){this.set("currentWindowSize",this.rootResponder.computeWindowSize()),e()}.enhance()}),SC.Pane.reopen({prependTo:function(e){return this.insert(function(t){jQuery(e).prepend(t)})},removeFromParent:function(){throw SC.Error.desc("SC.Pane cannot be removed from its parent, since it's the root. Did you mean remove()?")}}),SC.Pane.reopen({recomputeDependentProperties:function(e){this.recomputeIsVisibleInWindow(),e()}.enhance()}),SC.Application=SC.Responder.extend(SC.ResponderContext,{}),SC.BENCHMARK_LOG_READY=YES,SC.mixin({isReady:NO,suppressOnReady:SC.suppressOnReady?YES:NO,suppressMain:SC.suppressMain?YES:NO,ready:function(e,t){var n=SC._readyQueue;return t===undefined?(t=e,e=null):SC.typeOf(t)===SC.T_STRING&&(t=e[t]),SC.isReady?jQuery(document).ready(function(){t.call(e)}):(n||(SC._readyQueue=[]),SC._readyQueue.push(function(){t.call(e)})),this},onReady:{done:function(){if(SC.isReady)return;SC.isReady=!0,SC.RunLoop.begin(),SC.Locale.createCurrentLocale();var e=SC.Locale
.touchesForView(e),r=e._scrr_averagedTouches||(e._scrr_averagedTouches={});if((!n||n.length===0)&&!t)r.x=0,r.y=0,r.d=0,r.touchCount=0;else{var i=this._averagedTouches_touches||(this._averagedTouches_touches=[]),s;i.length=0;if(n){var o;s=n.length;for(o=0;o<s;o++)i.push(n[o])}t&&i.push(t);var u,a,f=0,l=0,c,h,p=0;s=i.length;for(u=0;u<s;u++)a=i[u],f+=a.pageX,l+=a.pageY;f/=s,l/=s;for(u=0;u<s;u++)a=i[u],c=Math.abs(a.pageX-f),h=Math.abs(a.pageY-l),p+=Math.pow(c*c+h*h,.5);p/=s,r.x=f,r.y=l,r.d=p,r.touchCount=s}return r},assignTouch:function(e,t){if(e.hasEnded)throw"Attemt to assign a touch that is already finished.";if(e.view===t)return;e.view&&this.unassignTouch(e),this._touchedViews[SC.guidFor(t)]||(this._touchedViews[SC.guidFor(t)]={view:t,touches:SC.CoreSet.create([]),touchCount:0},t.set("hasTouch",YES)),e.view=t,this._touchedViews[SC.guidFor(t)].touches.add(e),this._touchedViews[SC.guidFor(t)].touchCount++},unassignTouch:function(e){var t,n;if(!e.view)return;t=e.view,n=this._touchedViews[SC.guidFor(t)],n.touches.remove(e),n.touchCount--,n.touchCount<1&&(t.set("hasTouch",NO),n.view=null,delete this._touchedViews[SC.guidFor(t)]),e.view=undefined},_flushQueuedTouchResponder:function(){if(this._queuedTouchResponder){var e=this._queuedTouchResponder;this._queuedTouchResponder=null,this.makeTouchResponder.apply(this,e)}},makeTouchResponder:function(e,t,n,r){if(this._isMakingTouchResponder){this._queuedTouchResponder=[e,t,n,r];return}this._isMakingTouchResponder=YES;var i=e.touchResponders,s;if(e.touchResponder===t){this._isMakingTouchResponder=NO,this._flushQueuedTouchResponder();return}
var o;t?o=t.get("pane"):o=this.get("keyPane")||this.get("mainPane");if(i.indexOf(t)<0)if(r)try{t=o?o.sendEvent("touchStart",e,t):null}catch(u){SC.Logger.error("Error in touchStart: "+u),t=null}else t&&((t.get?t.get("acceptsMultitouch"):t.acceptsMultitouch)||!t.hasTouch)&&(t.touchStart(e)||(t=null));if(!n||i.indexOf(t)>-1&&i[i.length-1]!==t){this.unassignTouch(e);var a=i.length-1,f=i[a];while(f&&f!==t)s=this.touchesForView(f),((f.get?f.get("acceptsMultitouch"):f.acceptsMultitouch)||!s)&&f.touchCancelled&&f.touchCancelled(e),a--,f=i[a],i.pop(),e.touchResponder=i[a],e.nextTouchResponder=i[a-1]}t&&(this.assignTouch(e,t),t!==e.touchResponder&&(i.push(t),e.touchResponder=t,e.nextTouchResponder=i[i.length-2])),this._isMakingTouchResponder=NO,this._flushQueuedTouchResponder()},captureTouch:function(e,t,n){t||(t=this);var r=e.targetView,i=r,s=[],o,u;SC.LOG_TOUCH_EVENTS&&SC.Logger.info(" -- Received one touch on %@".fmt(r.toString()));while(i&&i!==t)s.unshift(i),i=i.get("nextResponder");for(u=s.length,o=0;o<u;o++){i=s[o],SC.LOG_TOUCH_EVENTS&&SC.Logger.info(" -- Checking %@ for captureTouch response…".fmt(i.toString()));if(i.tryToPerform("captureTouch",e)){SC.LOG_TOUCH_EVENTS&&SC.Logger.info(" -- Making %@ touch responder because it returns YES to captureTouch".fmt(i.toString())),this.makeTouchResponder(e,i,n,YES);return}}SC.LOG_TOUCH_EVENTS&&SC.Logger.info(" -- Didn't find a view that returned YES to captureTouch, so we're calling touchStart"),this.makeTouchResponder(e,r,n,YES)},endMissingTouches:function(e){var t,n=e.length,r={},i=[];for(t=0;t<n;t++)r[e[t].identifier]=YES;for(t in
;var t=this.get("interval"),n=this.get("lastFireTime");n<e&&(n=e);var r;this.get("repeats")?t===0?r=n:r=e+(Math.floor((n-e)/t)+1)*t:r=e+t;var i=this.get("until");return i&&i>0&&r>i&&(r=i),r}.property("interval","startTime","repeats","until","isValid","lastFireTime").cacheable(),schedule:function(){if(!this.get("isValid"))return this;this.beginPropertyChanges(),this.startTime||this.set("startTime",SC.RunLoop.currentRunLoop.get("startTime"));var e=this.get("fireTime"),t=this.get("lastFireTime");return e>=t&&(this.set("isScheduled",YES),SC.RunLoop.currentRunLoop.scheduleTimer(this,e)),this.endPropertyChanges(),this},invalidate:function(){this.beginPropertyChanges(),this.set("isValid",NO);var e=SC.RunLoop.currentRunLoop;return e&&e.cancelTimer(this),this.action=this.target=null,this.endPropertyChanges(),this.get("isPooled")&&SC.Timer.returnTimerToPool(this),this},fire:function(){var e=Date.now();this.set("lastFireTime",e);var t=this.get("fireTime");this.get("isPaused")||this.performAction(),t>e?this.schedule():this.invalidate()},performAction:function(){var e=SC.typeOf(this.action);if(e==SC.T_FUNCTION)this.action.call(this.target||this,this);else if(e===SC.T_STRING)if(this.action.indexOf(".")>=0){var t=this.action.split("."),n=t.pop(),r=SC.objectForPropertyPath(t,window),i=r.get?r.get(n):r[n];if(!i||SC.typeOf(i)!=SC.T_FUNCTION)throw"%@: Timer could not find a function at %@".fmt(this,this.action);i.call(r,this)}else SC.RootResponder.responder.sendAction(this.action,this.target,this)},init:function(){arguments.callee.base.apply(this,arguments),this.startTime instanceof Date&&(this
.startTime=this.startTime.getTime()),this.until instanceof Date&&(this.until=this.until.getTime())},RESET_DEFAULTS:{target:null,action:null,isPooled:NO,isPaused:NO,isScheduled:NO,isValid:YES,interval:0,repeats:NO,until:null,startTime:null,lastFireTime:0},reset:function(e){e||(e=SC.EMPTY_HASH),this.propertyWillChange("fireTime");var t=this.RESET_DEFAULTS;for(var n in t){if(!t.hasOwnProperty(n))continue;this[n]=SC.none(e[n])?t[n]:e[n]}return this.propertyDidChange("fireTime"),this},removeFromTimerQueue:function(e){var t=this._timerQueuePrevious,n=this._timerQueueNext;return!t&&!n&&e!==this?e:(t&&(t._timerQueueNext=n),n&&(n._timerQueuePrevious=t),this._timerQueuePrevious=this._timerQueueNext=null,e===this?n:e)},scheduleInTimerQueue:function(e,t){this._timerQueueRunTime=t;var n=e,r=null;while(n&&n._timerQueueRunTime<t)r=n,n=n._timerQueueNext;return r&&(r._timerQueueNext=this,this._timerQueuePrevious=r),n&&(n._timerQueuePrevious=this,this._timerQueueNext=n),n===e?this:e},collectExpiredTimers:function(e,t){if(this._timerQueueRunTime>t)return this;e.push(this);var n=this._timerQueueNext;return this._timerQueueNext=null,n&&(n._timerQueuePrevious=null),n?n.collectExpiredTimers(e,t):null}}),SC.Timer.schedule=function(e){var t;return!e||SC.none(e.isPooled)||e.isPooled?t=this.timerFromPool(e):t=this.create(e),t.schedule()},SC.Timer.timerFromPool=function(e){var t=this._timerPool;t||(t=this._timerPool=[]);var n=t.pop();return n||(n=this.create()),n.reset(e)},SC.Timer.returnTimerToPool=function(e){return this._timerPool||(this._timerPool=[]),this._timerPool.push(e),this},SC.mixin({normalizeURL
:function(e){return e.slice(0,1)=="/"?e=window.location.protocol+"//"+window.location.host+e:e.slice(0,5)!="http:"&&e.slice(0,6)!="https:"&&(e=window.location.href+"/"+e),e},isPercentage:function(e){return e<1&&e>0},minX:function(e){return e.x||0},maxX:function(e){return(e.x||0)+(e.width||0)},midX:function(e){return(e.x||0)+(e.width||0)/2},minY:function(e){return e.y||0},maxY:function(e){return(e.y||0)+(e.height||0)},midY:function(e){return(e.y||0)+(e.height||0)/2},centerX:function(e,t){return(t.width-e.width)/2},centerY:function(e,t){return(t.height-e.height)/2},offset:function(e,t){var n,r,i,s;t=t||"document";if(t==="parent")s=jQuery(e).position();else{s=jQuery(e).offset();if(SC.browser.mobileSafari){n=navigator.userAgent,r=n.indexOf("Mobile/"),i=n.substring(r+7,r+9);if(parseInt(SC.browser.mobileSafari,0)<=532||i<="8A")s.left-=window.pageXOffset,s.top-=window.pageYOffset}if(t==="viewport")if(SC.browser.isIE8OrLower){var o=SC.$(window);s.left-=o.scrollLeft(),s.top-=o.scrollTop()}else s.left-=window.pageXOffset,s.top-=window.pageYOffset}try{s.x=s.left,s.y=s.top}catch(u){s={x:s.left,y:s.top}}return delete s.left,delete s.top,s},viewportOffset:function(e){console.warn("SC.viewportOffset() has been deprecated in favor of SC.offset(). Please use SC.offset() from here on.");var t=SC.offset(e,"viewport");return{x:t.left,y:t.top}},isFunctionOrNonPrintableKey:function(e){return!!(e.altKey||e.ctrlKey||e.metaKey||e.charCode!==e.which&&SC.FUNCTION_KEYS[e.which])}}),SC.mixin({ZERO_POINT:{x:0,y:0},pointInRect:function(e,t){return e.x>=SC.minX(t)&&e.y>=SC.minY(t)&&e.x<=SC.maxX(t)&&e.y<=SC
this._headers,arguments.length===1?n?n[e]:null:(this.propertyWillChange("headers"),n||(n=this._headers={}),n[e]=t,this.propertyDidChange("headers"),this);if(t===undefined){n=e,this.beginPropertyChanges();for(e in n){if(!n.hasOwnProperty(e))continue;this.header(e,n[e])}return this.endPropertyChanges(),this}return this},clearHeaders:function(){this.propertyWillChange("headers"),this._headers={},this.propertyDidChange("headers")},async:function(e){return e===undefined&&(e=YES),this.set("isAsynchronous",e)},timeoutAfter:function(e){return this.set("timeout",e)},json:function(e){return e===undefined&&(e=YES),e&&this.set("isXML",NO),this.set("isJSON",e)},xml:function(e){return e===undefined&&(e=YES),e&&this.set("isJSON",NO),this.set("isXML",e)},_prep:function(){var e=!!this.header("Content-Type");return this.get("attachIdentifyingHeaders")&&(this.header("X-Requested-With","XMLHttpRequest"),this.header("X-SproutCore-Version",SC.VERSION)),this.get("isJSON")&&!e?this.header("Content-Type","application/json"):this.get("isXML")&&!e&&this.header("Content-Type","text/xml"),this},send:function(e){var t=this.get("timeout");if(t&&!this.get("isAsynchronous"))throw"Timeout values cannot be used with synchronous requests";if(t===0)throw"The timeout value must either not be specified or must be greater than 0";return e&&this.set("body",e),SC.Request.manager.sendRequest(this.copy()._prep())},resend:function(){var e=this.get("source")?this:this.copy()._prep();return SC.Request.manager.sendRequest(e)},notify:function(e,t,n,r){var i=YES;SC.typeOf(e)!==SC.T_NUMBER?(r=SC.A(arguments).slice(2),n=t,t=e
get("length"),a-=u-1},this),t=a-i;var f=this.get("children");if(!f)throw"cannot replace() tree item with no children";if(t<0||a>f.get("length"))throw"replace() range must lie within a single tree item";return f.replace(i,t,n,r),this},observerContentDidChange:function(e,t,n){this.invalidateBranchObserversAt(e),this._objectAtCache=this._outlineLevelCache=null,this._disclosureStateCache=null,this._contentGroupIndexes=NO,this.notifyPropertyChange("branchIndexes");var r=this.get("length"),i=this._computeLength(),s=this.get("parentObserver"),o;r!==i&&this.set("length",i);if(!this._notifyParent)return this;if(s)o=SC.IndexSet.create(this.get("index")),s._childrenRangeDidChange(s.get("children"),null,"[]",o);else{r===i?(t=this.expandChildIndex(e+t),e=this.expandChildIndex(e),t-=e,n=0):(e=this.expandChildIndex(e),t=i-e,n=i-r);var u=t,a=n+u;this.arrayContentDidChange(e,u,a)}},expandChildIndex:function(e){var t=e;this.get("isHeaderVisible")&&e++;var n=this.get("branchIndexes");return!n||n.get("length")===0?t:(n.forEachIn(0,e,function(e){t+=this.branchObserverAt(e).get("length")-1},this),t)},_contentGroupIndexes:NO,contentGroupIndexes:function(e,t){if(t!==this)return null;var n=this._contentGroupIndexes;if(n!==NO)return n;if(this.get("parentObserver"))return null;var r=this.get("item"),i,s,o,u;return r&&r.isTreeItemContent?i=r.get("treeItemIsGrouped"):i=!!this.delegate.get("treeItemIsGrouped"),i?(n=SC.IndexSet.create(),s=this.get("branchIndexes"),s&&(o=s.min(),u=0,s.forEach(function(e){n.add(e+u,1);var t=this.branchObserverAt(e);t&&(u+=t.get("length")-1,o+=u)},this))):n=null,this._contentGroupIndexes=
,"paddingRight","paddingTop","paddingBottom","fontFamily","fontSize","fontStyle","fontWeight","fontVariant","lineHeight","whiteSpace","letterSpacing","wordWrap","boxSizing","webkitBoxSizing","MozBoxSizing"],stringFromLayout:function(e){var t=["maxHeight","maxWidth","minHeight","minWidth","centerY","centerX","width","height","bottom","right","top","left"],n=[],r,i=t.length;while(--i>=0)r=t[i],e.hasOwnProperty(r)&&n.push(r+":"+e[r]);return"{"+n.join(", ")+"}"},heightForString:function(e,t,n,r,i,s){if(s){var o=this.bestStringMetricsForMaxWidth(e,t,s,r,i);return o.height}SC.debug("Warning: Use the element reference for the heightForString method. Just using class names may result in inaccurate values.");var s,u;u=r&&SC.typeOf(r)===SC.T_ARRAY?r.join(" "):"",elem=document.createElement("div"),document.body.insertBefore(elem,null),n=n+"; width: "+t+"px; left: "+ -1*t+"px; position: absolute;";var a=SC.$(elem);a.attr("style",n),u!==""&&a.attr("class",u),elem.innerHTML=e;var o=this.bestStringMetricsForMaxWidth(e,t,elem,r,i);return elem.parentNode.removeChild(elem),elem=null,o.height},prepareStringMeasurement:function(e,t){var n=this._metricsCalculationElement,r,i,s,o;r=SC.A(t).join(" ");if(!n){var u=document.createElement("div");u.style.cssText="position:absolute; left:-10010px; top:-10px;width:10000px; height:0px; overflow:hidden;visibility:hidden;",n=this._metricsCalculationElement=document.createElement("div"),u.appendChild(n),document.body.insertBefore(u,null)}o=SC.$(n);if(SC.typeOf(e)!=SC.T_STRING){var a=null;document.defaultView&&document.defaultView.getComputedStyle?a=document
.defaultView.getComputedStyle(e,null):a=e.currentStyle;var f=this._copy_computed_props;for(var l=0;l<f.length;l++){var c=f[l],h=a[c];n.style[c]=h}var p=n.style;if(p.font===""){var d="";p.fontStyle&&(d+=p.fontStyle+" "),p.fontVariant&&(d+=p.fontVariant+" "),p.fontWeight&&(d+=p.fontWeight+" "),p.fontSize?d+=p.fontSize:d+="10px",p.lineHeight&&(d+="/"+p.lineHeight),d+=" ",p.fontFamily?d+=p.fontFamily:p+="sans-serif",n.style.font=d}SC.mixin(n.style,{left:"0px",top:"0px",position:"absolute",bottom:"auto",right:"auto",width:"auto",height:"auto"}),a=null}else s=e,o.attr("style",s+"; position:absolute; left: 0px; top: 0px; bottom: auto; right: auto; width: auto; height: auto;");n.className=r,n=null},teardownStringMeasurement:function(){var e=this._metricsCalculationElement;e.innerHTML="",e.className="",e.setAttribute("style",""),e=null},measureString:function(e,t,n){var r=this._metricsCalculationElement,i=SC.browser,s=0;if(!r)throw"measureString requires a string measurement environment to be set up. Did you mean metricsForString?";t?r.innerHTML=e:typeof r.innerText!="undefined"?r.innerText=e:r.textContent=e;var o=r.getBoundingClientRect(),u=o.width,a=o.height,f={width:u,height:a};return i.isMozilla&&!n&&(f.width+=1),r=null,f},metricsForString:function(e,t,n,r,i){SC.prepareStringMeasurement(t,n);var s=SC.measureString(e,r,i);return SC.teardownStringMeasurement(),s}}),SC.AutoResize={shouldAutoResize:YES,shouldMeasureSize:YES,shouldCacheSizes:NO,shouldResizeWidth:YES,shouldResizeHeight:NO,measuredSize:{width:0,height:0},maxWidth:null,maxHeight:null,shouldAutoFitText:NO,autoFitDiscreteFontSizes
,displayProperties:["content"],contentDisplayProperties:[],initMixin:function(){this._display_contentDidChange()},destroyMixin:function(){if(!this._display_content)return;this._display_stopObservingContent(this._display_content),this._display_content=null},_display_beginObservingContent:function(e){var t=this._display_contentPropertyDidChange;SC.isArray(e)?e.invoke("addObserver","*",this,t):e.addObserver&&e.addObserver("*",this,t)},_display_stopObservingContent:function(e){var t=this._display_contentPropertyDidChange;SC.isArray(e)?e.invoke("removeObserver","*",this,t):e.removeObserver&&e.removeObserver("*",this,t)},_display_contentDidChange:function(e,t,n){if((n=this.get("content"))===this._display_content)return;var r=this._display_content;r&&this._display_stopObservingContent(r),r=this._display_content=n,r&&this._display_beginObservingContent(r),this.displayDidChange()}.observes("content","contentDisplayProperties"),_display_contentPropertyDidChange:function(e,t,n,r){if(t==="*")this.displayDidChange();else{var i=this.get("contentDisplayProperties");i&&i.indexOf(t)>=0&&this.displayDidChange()}}},SC.ContentValueSupport={hasContentValueSupport:YES,initMixin:function(){this._control_contentKeysDidChange()},value:null,content:null,contentKeys:null,_default_contentKeys:{contentValueKey:"value"},contentValueKey:null,contentPropertyDidChange:function(e,t){var n=this.get("contentKeys"),r;if(n){for(r in n)(t==="*"||t===this.getDelegateProperty(r,this,this.get("displayDelegate"),n))&&this.updatePropertyFromContent(n[r],t,r,e);return this}return this.updatePropertyFromContent("value",
t,"contentValueKey",e)},updatePropertyFromContent:function(e,t,n,r){var i,s;n===undefined&&(n="content"+e.capitalize()+"Key");if(this[n])n=this.get(n);else{if(!(i=this.get("displayDelegate"))||!(s=i[n]))return this;n=i.get?i.get(n):s}if(t==="*"||t===n)r===undefined&&(r=this.get("content")),r?s=r.get?r.get(n):r[n]:s=null,this.setIfChanged(e,s);return this},updateContentWithValueObserver:function(e,t){var n=this._reverseContentKeys;if(!t||t==="*")for(t in n)this.updateContentWithValueObserver(this,t);var r=this.get(t),i=this.get("content"),s=this.getDelegateProperty(n[t],this,this.displayDelegate);if(!s||!i)return this;typeof i.setIfChanged===SC.T_FUNCTION?i.setIfChanged(s,r):i[s]!==r&&(i[s]=r)},_control_content:null,_old_contentValueKeys:null,_old_contentKeys:null,_control_contentDidChange:function(e,t){var n=this.get("content"),r=this.get("contentKeys"),i,s=this._control_content,o=this._old_contentValueKeys,u=SC.typeOf(o),a=this.contentPropertyDidChange;if(s&&s.removeObserver&&o)if(u===SC.T_STRING)s.removeObserver(o,this,a),o=null;else{var f,l=o.get("length");for(f=0;f<l;f++)i=o[f],s.removeObserver(i,this,a);o.clear()}if(n&&n.addObserver)if(r){o||(o=SC.CoreSet.create());for(i in r)i=this.getDelegateProperty(i,this,this.get("displayDelegate")),i&&(n.addObserver(i,this,a),o.add(i))}else i=this.getDelegateProperty("contentValueKey",this,this.get("displayDelegate")),i&&(n.addObserver(i,this,a),o?o.add(i):o=i);this._control_content=n,this._old_contentValueKeys=o,t=!t||t==="content"?"*":this.get(t),t&&this.contentPropertyDidChange(n,t)}.observes("content"),_old_contentKeys:null,_control_contentKeysDidChange
:function(){var e,t={},n=this.get("contentKeys")||this._default_contentKeys,r,i=this._old_contentKeys,s=this._control_contentDidChange,o=this.updateContentWithValueObserver;for(e in i)r=i[e],this.removeObserver(r,this,o),this.removeObserver(e,this,s);for(e in n)r=n[e],t[r]=e,this.addObserver(r,this,o),this.addObserver(e,this,s);this._reverseContentKeys=t,this._old_contentKeys=n,this._control_contentDidChange()}.observes("contentKeys")},SC.AUTO_CONTROL_SIZE="__AUTO__",SC.JUMBO_CONTROL_SIZE="sc-jumbo-size",SC.HUGE_CONTROL_SIZE="sc-huge-size",SC.LARGE_CONTROL_SIZE="sc-large-size",SC.REGULAR_CONTROL_SIZE="sc-regular-size",SC.SMALL_CONTROL_SIZE="sc-small-size",SC.TINY_CONTROL_SIZE="sc-tiny-size",SC.CUSTOM_CONTROL_SIZE="sc-custom-size",SC.Control=SC.mixin(SC.clone(SC.ContentValueSupport),{isControl:YES,isSelected:NO,isSelectedBindingDefault:SC.Binding.oneWay().bool(),isActive:NO,isActiveBindingDefault:SC.Binding.oneWay().bool(),fieldKey:null,fieldLabel:null,errorLabel:function(){var e,t,n,r;return(e=this.get("fieldLabel"))?e:(t=this.get("fieldKey")||this.constructor.toString(),n=t?SC.String.capitalize(SC.String.humanize(t)):"",r=SC.String.locWithDefault("FieldKey."+t,n),SC.String.locWithDefault("ErrorLabel."+t,r))}.property("fieldLabel","fieldKey").cacheable(),controlSize:SC.REGULAR_CONTROL_SIZE,displayProperties:["isEnabled","isSelected","isActive","controlSize"],_CONTROL_TMP_CLASSNAMES:{},renderMixin:function(e,t){var n=this.get("isSelected"),r=!this.get("isEnabled"),i=this._CONTROL_TMP_CLASSNAMES;i.mixed=n===SC.MIXED_STATE,i.sel=n&&n!==SC.MIXED_STATE,i.active=this.get("isActive"
:function(e,t,n){},inlineEditorDidCommitEditing:function(e,t,n){},inlineEditorShouldDiscardEditing:function(e,t){},inlineEditorWillDiscardEditing:function(e,t){},inlineEditorDidDiscardEditing:function(e,t){},inlineEditorWillEndEditing:function(e,t,n){},inlineEditorDidEndEditing:function(e,t,n){}},SC.SCALE_NONE="none",SC.FILL="fill",SC.FILL_PROPORTIONALLY="fillProportionally",SC.BEST_FIT="fitBest",SC.BEST_FIT_DOWN_ONLY="fitBestDown",SC.InnerFrame={align:SC.ALIGN_CENTER,innerFrameForSize:function(e,t,n,r){var i=this.get("align"),s=this.get("scale"),o,u,a;a={x:0,y:0,width:n,height:r};if(s===SC.FILL)return a;o=n/e,u=r/t;switch(s){case SC.FILL_PROPORTIONALLY:s=o>u?o:u;break;case SC.BEST_FIT:s=o<u?o:u;break;case SC.BEST_FIT_DOWN_ONLY:e>n||t>r?s=o<u?o:u:s=1;break;case SC.SCALE_NONE:s=1;break;default:if(isNaN(window.parseFloat(s))||window.parseFloat(s)<=0)return SC.Logger.warn("SC.InnerFrame: The scale '%@' was not understood. Scale must be one of SC.FILL, SC.FILL_PROPORTIONALLY, SC.BEST_FIT, SC.BEST_FIT_DOWN_ONLY or a positive number greater than 0.00.".fmt(s)),a}e*=s,t*=s,a.width=Math.round(e),a.height=Math.round(t);switch(i){case SC.ALIGN_LEFT:a.x=0,a.y=r/2-t/2;break;case SC.ALIGN_RIGHT:a.x=n-e,a.y=r/2-t/2;break;case SC.ALIGN_TOP:a.x=n/2-e/2,a.y=0;break;case SC.ALIGN_BOTTOM:a.x=n/2-e/2,a.y=r-t;break;case SC.ALIGN_TOP_LEFT:a.x=0,a.y=0;break;case SC.ALIGN_TOP_RIGHT:a.x=n-e,a.y=0;break;case SC.ALIGN_BOTTOM_LEFT:a.x=0,a.y=r-t;break;case SC.ALIGN_BOTTOM_RIGHT:a.x=n-e,a.y=r-t;break;default:i!==SC.ALIGN_CENTER&&i!==SC.ALIGN_MIDDLE&&SC.Logger.warn("SC.InnerFrame: The align '%@' was not understood. Align must be one of SC.ALIGN_CENTER/SC.ALIGN_MIDDLE, SC.ALIGN_LEFT, SC.ALIGN_RIGHT, SC.ALIGN_TOP, SC.ALIGN_BOTTOM, SC.ALIGN_TOP_LEFT, SC.ALIGN_TOP_RIGHT, SC.ALIGN_BOTTOM_LEFT or SC.ALIGN_BOTTOM_RIGHT."
._imageEntryFor(e);s.status===this.IMAGE_LOADED?n&&n.call(t||s.image,s.url,s.image):((t||n)&&this._addCallback(s,t,n),s.retainCount++,this._scheduleImageEntry(s,r))},releaseImage:function(e,t,n){var r=this._imageEntryFor(e,NO);if(!r)return this;if(--r.retainCount<=0)this._deleteEntry(r);else if(t||n){var i=SC.typeOf(t);SC.none(n)&&SC.typeOf(t)===SC.T_FUNCTION&&(t=null,n=t),SC.typeOf(n)===SC.T_STRING&&(n=t[n]),this._removeCallback(r,t,n)}},reloadImage:function(e){var t=this._imageEntryFor(e,NO);t&&t.status===this.IMAGE_LOADED&&(t.status=this.IMAGE_WAITING)},loadNextImage:function(){var e=null,t;if(this.get("activeRequests")>=this.get("loadLimit"))return;t=this._foregroundQueue;while(t.length>0&&!e)e=t.shift();if(!e){t=this._backgroundQueue;while(t.length>0&&!e)e=t.shift()}this.set("isLoading",!!e);if(e){var n=e.image;if(!n)return;var r=SC.$(n);r.length!==0?(r.bind("abort",this._imageDidAbort),r.bind("error",this._imageDidError),r.bind("load",this._imageDidLoad),n.src=e.url,this._loading.push(e)):e.url?SC.error("Unable to load the image for url %@".fmt(e.url)):SC.error("entry does not contain any url. Its an invalid entry"),this.incrementProperty("activeRequests"),this.loadNextImage()}},_imageEntryFor:function(e,t){t===undefined&&(t=YES);var n=this._images[e];if(!n&&t){var r=new Image;n=this._images[e]={url:e,status:this.IMAGE_WAITING,callbacks:[],retainCount:0,image:r},r.entry=n}return n},_deleteEntry:function(e){this._unscheduleImageEntry(e),delete this._images[e.url]},_addCallback:function(e,t,n){var r=e.callbacks,i=r.find(function(e){return e[0]===t&&e[1]===n},this);return i||
e.image;i&&(i.onload=i.onerror=i.onabort=null,t!==this.LOADED&&(e.image=null)),this._loading[this._loading.indexOf(e)]=null,this._loading.length>this.loadLimit*2&&(this._loading=this._loading.compact()),this.decrementProperty("activeRequests"),this.loadNextImage()},init:function(){arguments.callee.base.apply(this,arguments),this._images={},this._loading=[],this._foregroundQueue=[],this._backgroundQueue=[]},IMAGE_LOADED:"loaded",IMAGE_QUEUED:"queued",IMAGE_WAITING:"waiting",ABORTED:"aborted",ERROR:"error",LOADED:"loaded"}),SC.Task=SC.Object.extend({run:function(e){}}),SC.LOG_MODULE_LOADING=YES,SC.Module=SC.Object.create({isModuleReady:function(e){var t=SC.MODULE_INFO[e];return t?!!t.isReady:NO},loadModule:function(e,t,n){var r=SC.MODULE_INFO[e],i,s,o=SC.A(arguments).slice(3),u=SC.LOG_MODULE_LOADING,a,f;n===undefined&&SC.typeOf(t)===SC.T_FUNCTION&&(n=t,t=null),u&&SC.debug("SC.Module: Attempting to load '%@'",e);if(!r)throw"SC.Module: could not find module '%@'".fmt(e);r.isPrefetching=NO;if(r.isLoaded&&!r.isWaitingForRunLoop)return u&&SC.debug("SC.Module: Module '%@' already loaded.",e),this._dependenciesMetForModule(e)?r.source?(u&&SC.debug("SC.Module: Evaluating JavaScript for module '%@'.",e),this._evaluateStringLoadedModule(r),this._addCallbackForModule(e,t,n,o),this.invokeLast(function(){r.isReady=YES,this._moduleDidBecomeReady(e)}),NO):(n&&(SC.isReady?SC.Module._invokeCallback(e,t,n,o):SC.ready(SC.Module,function(){SC.Module._invokeCallback(e,t,n,o)})),YES):(this._addCallbackForModule(e,t,n,o),this._loadDependenciesForModule(e),NO);if(!r.isWaitingForRunLoop)return u&&SC.debug
("SC.Module: Module '%@' is not loaded, loading now.",e),this._addCallbackForModule(e,t,n,o),r.isLoading||(this._loadDependenciesForModule(e),this._loadCSSForModule(e),this._loadJavaScriptForModule(e),r.isLoading=YES),NO;this._addCallbackForModule(e,t,n,o)},_addCallbackForModule:function(e,t,n,r){var i=SC.MODULE_INFO[e],s=i.callbacks||[];n&&s.push(function(){SC.Module._invokeCallback(e,t,n,r)}),i.callbacks=s},prefetchModule:function(e){var t=SC.MODULE_INFO[e];if(t.isLoading||t.isLoaded)return;SC.LOG_MODULE_LOADING&&SC.debug("SC.Module: Prefetching module '%@'.",e),this._loadDependenciesForModule(e),this._loadCSSForModule(e),this._loadJavaScriptForModule(e),t.isLoading=YES,t.isPrefetching=YES},_executeLazilyInstantiatedModule:function(e,t,n){var r=SC.LAZY_INSTANTIATION[e],i,s,o,u;SC.LOG_MODULE_LOADING&&SC.debug("SC.Module: Module '%@' is marked for lazy instantiation, instantiating it now…",e),u=r.length;for(o=0;o<u;o++)try{r[o]()}catch(a){SC.Logger.error("SC.Module: Failed to lazily instatiate entry for '%@'".fmt(e))}delete SC.LAZY_INSTANTIATION[e],i=this._targetForTargetName(t),s=this._methodForMethodNameInTarget(n,i);if(!s)throw"SC.Module: could not find callback for lazily instantiated module '%@'".fmt(e)},_evaluateStringLoadedModule:function(e){var t=e.source;jQuery.globalEval(t),delete e.source;if(e.cssSource){var n=this.getInlinedCSSFor(e),r=document.createElement("style");r.setAttribute("type","text/css");if(r.styleSheet)r.styleSheet.cssText=n;else{var i=document.createTextNode(n);r.appendChild(i)}document.getElementsByTagName("head")[0].appendChild(r)}e.isReady=YES}
o.open("GET",r),o.send(null);return}n=document.createElement("script"),n.setAttribute("type","text/javascript"),n.setAttribute("async","true"),n.setAttribute("src",r),SC.browser.isIE?n.onreadystatechange=function(){(this.readyState=="complete"||this.readyState=="loaded")&&SC.run(function(){SC.Module._moduleDidLoad(e)})}:n.onload=function(){SC.run(function(){SC.Module._moduleDidLoad(e)})},document.body.appendChild(n)}},_dependenciesMetForModule:function(e){var t=SC.MODULE_INFO[e].dependencies||[],n,r=t.length,i,s;for(n=0;n<r;n++){i=t[n],s=SC.MODULE_INFO[i];if(!s)throw"SC.loadModule: Unable to find dependency %@ for module %@.".fmt(i,e);if(!s.isReady)return NO}return YES},_loadDependenciesForModule:function(e){var t=SC.MODULE_INFO[e],n=SC.LOG_MODULE_LOADING,r=t.dependencies||[],i=YES,s=r.length,o,u,a,f;for(o=0;o<s;o++){u=r[o],a=SC.MODULE_INFO[u];if(!a)throw"SC.Module: could not find required module '%@' for module '%@'".fmt(u,e);if(a.isLoading)i=NO,f=a.dependents,f||(a.dependents=f=[]),f.push(e);else{if(a.isReady)continue;i=NO,f=a.dependents,f||(a.dependents=f=[]),f.push(e),n&&SC.debug("SC.Module: '%@' depends on '%@', loading dependency…",e,u),SC.Module.loadModule(u)}}},_invokeCallback:function(e,t,n,r){var i,s;s=this._targetForTargetName(t),i=this._methodForMethodNameInTarget(n,s);if(!i){if(!SC.LAZY_INSTANTIATION[e])throw"SC.Module: could not find callback for '%@'".fmt(e);this._executeLazilyInstantiatedModule(e,t,n),s=this._targetForTargetName(t),i=this._methodForMethodNameInTarget(n,s)}r||(r=[]),r.unshift(e);var o=!!SC.RunLoop.currentRunLoop;o?SC.run(function(){i.apply(s,r
)}):i.apply(s,r)},_invokeCallbacksForModule:function(e){var t=SC.MODULE_INFO[e],n;if(!t)return;SC.LOG_MODULE_LOADING&&SC.debug("SC.Module: Module '%@' has completed loading, invoking callbacks.",e),n=t.callbacks||[];for(var r=0,i=n.length;r<i;++r)n[r]()},_evaluateAndInvokeCallbacks:function(e){var t=SC.MODULE_INFO,n=t[e],r=SC.LOG_MODULE_LOADING;r&&SC.debug("SC.Module: Evaluating and invoking callbacks for '%@'.",e),n.source&&this._evaluateStringLoadedModule(n),n.isWaitingForRunLoop=YES,this.invokeLast(function(){n.isReady=YES,this._moduleDidBecomeReady(e)})},_moduleDidBecomeReady:function(e){var t=SC.MODULE_INFO,n=t[e],r=SC.LOG_MODULE_LOADING;n.isWaitingForRunLoop=NO,SC.isReady?(SC.Module._invokeCallbacksForModule(e),delete n.callbacks):SC.ready(SC,function(){SC.Module._invokeCallbacksForModule(e),delete n.callbacks});var i=n.dependents||[],s,o;for(var u=0,a=i.length;u<a;u++)s=i[u],o=t[s],o.isLoaded&&this._dependenciesMetForModule(s)&&(r&&SC.debug("SC.Module: Now that %@ has loaded, all dependencies for a dependent %@ are met.",e,s),this._evaluateAndInvokeCallbacks(s))},_moduleDidLoad:function(e){var t=SC.MODULE_INFO[e],n=SC.LOG_MODULE_LOADING,r,i,s;n&&SC.debug("SC.Module: Module '%@' finished loading.",e);if(!t){n&&SC.debug("SC._moduleDidLoad() called for unknown module '@'.",e),t=SC.MODULE_INFO[e]={isLoaded:YES,isReady:YES};return}if(t.isLoaded){n&&SC.debug("SC._moduleDidLoad() called more than once for module '%@'. Skipping.",e);return}delete t.isLoading,t.isLoaded=YES,t.isPrefetching?(delete t.isPrefetching,n&&SC.debug("SC.Module: Module '%@' was prefetched, not evaluating until needed."
,e)):(r=this._dependenciesMetForModule(e),r?this._evaluateAndInvokeCallbacks(e):n&&SC.debug("SC.Module: Dependencies for '%@' not met yet, waiting to evaluate.",e))},_targetForTargetName:function(e){return SC.typeOf(e)===SC.T_STRING?SC.objectForPropertyPath(e):e},_methodForMethodNameInTarget:function(e,t){return SC.typeOf(e)===SC.T_STRING?SC.objectForPropertyPath(e,t):e},methodsForSuspend:"loadModule _moduleDidLoad prefetchModule _moduleDidBecomeReady".w(),suspend:function(){this._suspendCount=(this._suspendCount||0)+1;if(this._suspendCount!==1)return;var e=this.get("methodsForSuspend"),t,n,r,i;for(i=0;r=e[i];i++)this[t="__replacement_"+r+"__"]||((this[t]=function(){(this._bufferedCalls||(this._bufferedCalls=[])).push({method:arguments.callee.methodName,arguments:arguments})}).methodName=r),this[n="__saved_"+r+"__"]||(this[n]=this[r]),this[r]=this[t]},resume:function(){this._suspendCount=(this._suspendCount||0)-1;if(this._suspendCount<0){SC.warn("SC.Module.resume() was called without SC.Module having been in a suspended state. Call aborted."),this._suspendCount=0;return}if(this._suspendCount>0)return;var e=this.get("methodsForSuspend"),t=this._bufferedCalls,n,r,i,s;for(r=0;n=e[r];r++)this[n]=this["__saved_"+n+"__"];for(r=0;s=t&&t[r];r++)this[s.method].apply(this,s.arguments);t&&(t.length=0)}}),SC.ready(function(){var e=SC.MODULE_INFO,t,n,r;for(t in e)n=e[t],n.isPrefetched&&(r=SC.Module.PrefetchModuleTask.create({prefetchedModuleName:t}),SC.backgroundTaskQueue.push(r))}),SC.Module.PrefetchModuleTask=SC.Task.extend({prefetchedModuleName:null,run:function(){SC.Module.prefetchModule
},cachedVersionOf:function(){var e=function(e){var t=function(){var e=SC.cacheSlotFor(arguments);return e.result||(e.result=arguments.callee.func.apply(this,arguments))};return t.func=e,t};return e(e)}()}),SC.didPreloadBundle=function(){},SC.PreloadBundleTask=SC.Task.extend({bundle:null,target:"SC",action:"preloaded",run:function(e){var t;if(t=this.get("bundle")){var n=Date.now();SC.Module.loadModule(this.get("bundle"),this.get("target"),this.get("action"))}}}),SC.VALIDATE_OK=YES,SC.VALIDATE_NO_CHANGE=NO,SC.Validator=SC.Object.extend({fieldValueForObject:function(e,t,n){return e},objectForFieldValue:function(e,t,n){return e},validate:function(e,t){return!0},validateError:function(e,t){return SC.$error(SC.String.loc("Invalid.General(%@)",t.get("fieldValue")),t.get("fieldKey"))},validateChange:function(e,t,n){return this.validate(e,t)?SC.VALIDATE_OK:this.validateError(e,t)},validateSubmit:function(e,t){return this.validate(e,t)?SC.VALIDATE_OK:this.validateError(e,t)},validatePartial:function(e,t){return t.get("isValid")?SC.VALIDATE_NO_CHANGE:this.validate(e,t)?SC.VALIDATE_OK:this.validateError(e,t)},validateKeyDown:function(e,t,n){return!0},attachTo:function(e,t){},detachFrom:function(e,t){}}),SC.Validator.mixin({OK:!0,NO_CHANGE:!1,findFor:function(e,t,n){var r;if(!n)return;if(n instanceof SC.Validator)r=n;else if(n.isClass)r=n.create();else if(SC.typeOf(n)===SC.T_STRING){var i=null,s=n.match(/^(.+)\[(.*)\]/);s&&(n=s[1],i=s[2]),n=SC.String.classify(n);var o=SC.Validator[n];if(SC.none(o))throw"validator %@ not found for %@".fmt(n,t);if(i){if(!e)throw"named validator (%@) could not be found for field %@ because the field does not belong to a form"
);return t!==null&&t!==undefined&&this.set("applyImmediately",t),arguments.callee.base.apply(this,arguments)},isEditable:YES,selection:function(e,t){var n=this.$input()[0],r,i,s;if(t===undefined){if(n){i=null,s=null;if(!n.value)i=s=0;else{try{"selectionStart"in n&&(i=n.selectionStart),"selectionEnd"in n&&(s=n.selectionEnd)}catch(o){return null}if(i===null||s===null){var u=document.selection;if(u){var a=u.type;if(a&&(a==="None"||a==="Text")){r=u.createRange();if(!this.get("isTextArea")){var f=r.text.length;i=Math.abs(r.moveStart("character",0-(n.value.length+1))),s=i+f}else{var l=r.duplicate();l.moveToElementText(n),l.setEndPoint("EndToStart",r),i=l.text.length,s=i+r.text.length}}}}}return SC.TextSelection.create({start:i,end:s})}return null}if(!t||!t.kindOf||!t.kindOf(SC.TextSelection))throw"When setting the selection, you must specify an SC.TextSelection instance.";if(n)if(n.setSelectionRange)n.setSelectionRange(t.get("start"),t.get("end"));else{r=n.createTextRange(),i=t.get("start"),r.move("character",i),r.moveEnd("character",t.get("end")-i);try{r.select()}catch(o){SC.Error("Failed selecting, this is a know bug with IE8, error 800a025e. Ignoring")}}return t}.property("fieldValue").cacheable(),displayProperties:["isBrowserFocusable","formattedHint","fieldValue","isEditing","isEditable","leftAccessoryView","rightAccessoryView","isTextArea"],createChildViews:function(){arguments.callee.base.apply(this,arguments),this.accessoryViewObserver()},acceptsFirstResponder:function(){return this.get("isEnabled")}.property("isEnabled"),accessoryViewObserver:function(){var e,t=["leftAccessoryView"
:function(e,t,n,r){this._oldOpacity=this.get("layout").opacity||1,this.adjust("opacity",0),e(t,n,r)}.enhance(),inlineEditorDidEndEditing:function(){this.adjust("opacity",this._oldOpacity),this._oldOpacity=null}}),SC.allowsBackspaceToPreviousPage=NO,SC.HORIZONTAL_ORIENTATION="horizontal",SC.VERTICAL_ORIENTATION="vertical",SC.BORDER_BEZEL="sc-bezel-border",SC.BORDER_BLACK="sc-black-border",SC.BORDER_GRAY="sc-gray-border",SC.BORDER_TOP="sc-top-border",SC.BORDER_BOTTOM="sc-bottom-border",SC.BORDER_NONE=null,SC.Border={borderTop:0,borderRight:0,borderBottom:0,borderLeft:0,borderStyle:SC.BORDER_GRAY,hasBorder:YES,displayProperties:["borderStyle"],_BORDER_REGEXP:/-border$/,initMixin:function(){console.warn("SC.Border is deprecated, please set border in your layout"),this._sc_border_borderStyleDidChange(),this._sc_border_borderDimensionsDidChange()},renderMixin:function(e,t){var n=this.get("borderStyle");n&&(this._BORDER_REGEXP.exec(n)?e.addClass(n):e.addStyle("border","1px "+n+" solid"))},_sc_border_borderStyleDidChange:function(){var e=this.get("borderStyle"),t=SC.Border.dimensions[e];t&&(this.beginPropertyChanges(),this.set("borderTop",t),this.set("borderRight",t),this.set("borderBottom",t),this.set("borderLeft",t),this.endPropertyChanges())},_sc_border_borderDimensionsDidChange:function(){var e=this.get("borderTop"),t=this.get("borderRight"),n=this.get("borderBottom"),r=this.get("borderLeft");this.adjust({borderTop:e,borderRight:t,borderBottom:n,borderLeft:r})}.observes("borderTop","borderRight","borderBottom","borderLeft")},SC.mixin(SC.Border,{dimensions:{"sc-bezel-border":1,"sc-black-border"
function(){return this.get("isVisibleInWindow")&&this.get("isPaneAttached")&&this._withdrawOverflowRequest(),this._removeScrollObservers(),arguments.callee.base.apply(this,arguments)},anchorElement:function(e,t){var n;if(t===undefined)return n=this._anchorView,n?n.get("layer"):this._anchorHTMLElement;if(!t)throw"You must set 'anchorElement' to either a view or a DOM element";t.isView?(this._anchorView=t,this._anchorHTMLElement=null):(this._anchorView=null,this._anchorHTMLElement=t)}.property("layer").cacheable(),_hideOverflow:function(){var e=SC.$(document.body),t=SC.$(".sc-main"),n=parseInt(t.css("minWidth"),0),r=parseInt(t.css("minHeight"),0),i=SC.RootResponder.responder.get("currentWindowSize");i.width>=n&&i.height>=r&&SC.bodyOverflowArbitrator.requestHidden(this)},_withdrawOverflowRequest:function(){SC.bodyOverflowArbitrator.withdrawRequest(this)},_getScrollViewOfView:function(e){var t=e;while(YES){if(!t)return null;if(t.isScrollable)return t;t=t.get("parentView")}},_setupScrollObservers:function(e){var t=this._getScrollViewOfView(e);t&&(t.addObserver("horizontalScrollOffset",this,this._scrollOffsetDidChange),t.addObserver("verticalScrollOffset",this,this._scrollOffsetDidChange),this._scrollView=t)},_removeScrollObservers:function(){var e=this._scrollView;e&&(e.removeObserver("horizontalScrollOffset",this,this._scrollOffsetDidChange),e.removeObserver("verticalScrollOffset",this,this._scrollOffsetDidChange))},_scrollOffsetDidChange:function(){this.positionPane()}}),SC.PickerPane.PICKER_POINTER_OFFSET=[9,-9,-18,18],SC.PickerPane.PICKER_EXTRA_RIGHT_OFFSET=20,SC.PickerPane.TINY_PICKER_MENU_POINTER_OFFSET=
:function(e){SC.Logger.warn("Support for Array-based menu items has been deprecated. Please update your menus to use a hash.");var t,n=SC._menu_fetchKeys,r=SC._menu_fetchItem,i,s=SC.Object.create(),o,u;return t=this.menuItemKeys.map(n,this),s[t[0]]=e[0],s[t[1]]=e[1],s[t[2]]=e[2],s[t[3]]=e[3],s[t[4]]=e[4],s[t[5]]=e[5],s[t[6]]=e[6],s[t[7]]=e[7],s[t[8]]=e[8],s[t[9]]=e[9],s[t[10]]=e[10],s[t[11]]=e[11],s[t[12]]=e[12],s},currentMenuItem:function(e,t){return t!==undefined?(this._currentMenuItem!==null&&this.set("previousMenuItem",this._currentMenuItem),this._currentMenuItem=t,(!this._isRemoving||!this.get("isSubMenu"))&&this.setPath("rootMenu.targetMenuItem",t),t):this._currentMenuItem}.property().cacheable(),_sc_menu_currentMenuItemDidChange:function(){var e=this.get("currentMenuItem"),t=this.get("previousMenuItem");t&&(!t.get("hasSubMenu")||e!==null)&&(t.resignFirstResponder(),this.closeOpenMenusFor(t)),e&&e.get("isEnabled")&&e.scrollToVisible()}.observes("currentMenuItem"),closeOpenMenusFor:function(e){if(!e)return;var t=e.get("parentMenu");while(t&&e)t=e.get("subMenu"),t&&(t.remove(),e.resignFirstResponder(),e=t.get("previousMenuItem"))},closeOpenMenus:function(){this.closeOpenMenusFor(this.get("previousMenuItem"))},mouseDown:function(e){return this.modalPaneDidClick(e),YES},mouseEntered:function(e){this.set("mouseHasEntered",YES)},keyUp:function(e){var t=this.interpretKeyEvents(e);return t?t:NO},moveUp:function(){var e=this.get("currentMenuItem"),t=this.get("menuItemViews"),n,r,i;if(!e)i=t.get("length")-1;else{n=e.getPath("content.contentIndex");if(n===0)return YES;i=n-1}while(
,s=this._findDropTarget(e),o=SC.DRAG_NONE;while(s&&s!==i&&o===SC.DRAG_NONE)s&&r&&r.dragSourceOperationMaskFor?o=r.dragSourceOperationMaskFor(this,s):o=SC.DRAG_ANY,o!==SC.DRAG_NONE&&s&&s.computeDragOperations?o&=s.computeDragOperations(this,e,o):o=SC.DRAG_NONE,this.allowedDragOperations=o,o===SC.DRAG_NONE&&(s=this._findNextDropTarget(s));s!==i?(i&&i.dragExited&&i.dragExited(this,e),s&&(s.dragEntered&&s.dragEntered(this,e),s.dragUpdated&&s.dragUpdated(this,e)),this._lastTarget=s):s&&s.dragUpdated&&s.dragUpdated(this,e),r&&r.dragDidMove&&r.dragDidMove(this,n),this.get("sourceIsDraggable")&&!this._ghostViewHidden&&this._positionGhostView(e)},touchesDragged:function(e){this.mouseDragged(e)},mouseUp:function(e){var t={x:e.pageX,y:e.pageY},n=this._lastTarget,r=this.allowedDragOperations;this.set("location",t);try{n&&n.acceptDragOperation&&n.acceptDragOperation(this,r)?r=n.performDragOperation?n.performDragOperation(this,r):SC.DRAG_NONE:r=SC.DRAG_NONE}catch(i){SC.Logger.error("Exception in SC.Drag.mouseUp(acceptDragOperation|performDragOperation): %@".fmt(i))}try{n&&n.dragExited&&n.dragExited(this,e)}catch(s){SC.Logger.error("Exception in SC.Drag.mouseUp(target.dragExited): %@".fmt(s))}var o=this._dropTargets();for(var u=0,a=o.length;u<a;u++)try{o[u].tryToPerform("dragEnded",this,e)}catch(f){SC.Logger.error("Exception in SC.Drag.mouseUp(dragEnded on %@): %@".fmt(o[u],f))}this.get("sourceIsDraggable")&&(this._destroyGhostView(),this.get("ghost")&&(this._dragViewWasVisible&&this._getDragView().set("isVisible",YES),this._dragViewWasVisible=null));var l=this.source;l&&l.dragDidEnd&&l.dragDidEnd
(this,t,r),this._lastTarget=null,this._dragInProgress=NO},touchEnd:function(e){this.mouseUp(e)},_getDragView:function(){if(!this.dragView){if(!this.source||!this.source.isView)throw"Source can't be used as dragView, because it's not a view.";this.dragView=this.source}return this.dragView},_createGhostView:function(){var e=this,t=this._getDragView(),n=t.get("frame"),r;r=this.ghostView=SC.Pane.create({classNames:["sc-ghost-view"],layout:{top:n.y,left:n.x,width:n.width,height:n.height},owner:this,didCreateLayer:function(){if(t){var e=t.get("layer");e&&(e=e.cloneNode(!0),e.style.top="0px",e.style.left="0px",this.get("layer").appendChild(e))}}}),r.append()},_positionGhostView:function(e){var t=this.get("location");t.x-=this.ghostOffset.x,t.y-=this.ghostOffset.y;var n=this.ghostView;n&&(n.adjust({top:t.y,left:t.x}),n.invokeOnce("updateLayout"))},_ghostViewHidden:NO,hideGhostView:function(){this.ghostView&&!this._ghostViewHidden&&(this.ghostView.remove(),this._ghostViewHidden=YES)},unhideGhostView:function(){this._ghostViewHidden&&(this._ghostViewHidden=NO,this._createGhostView())},_destroyGhostView:function(){this.ghostView&&(this.ghostView.remove(),this.ghostView=null,this._ghostViewHidden=NO)},_dropTargets:function(){if(this._cachedDropTargets)return this._cachedDropTargets;var e=[],t=SC.Drag._dropTargets;for(var n in t)t.hasOwnProperty(n)&&e.push(t[n]);var r={},i=SC.Drag._dropTargets,s=function(e){if(!e)return 0;var t=SC.guidFor(e),n=r[t];if(!n){n=1;while(e=e.get("parentView"))i[SC.guidFor(e)]!==undefined&&n++;r[t]=n}return n};return e.sort(function(e,t){return e===t?0:(e=s(e),
storeKey,s;s=r.readEditableDataHash(i);if(!s)throw SC.Record.BAD_STATE_ERROR;return t!==s[e]&&(n||this.beginEditing(),s[e]=t,e===this.get("primaryKey")&&(SC.Store.replaceIdFor(i,t),this.propertyDidChange("id")),n||this.endEditing(e)),this},propagateToAggregates:function(){var e=this.get("storeKey"),t=SC.Store.recordTypeFor(e),n=t.__sc_aggregate_keys,r,i,s,o,u,a;if(!n){n=[];for(s in this)o=this[s],o&&o.isRecordAttribute&&o.aggregate===YES&&n.push(s);t.__sc_aggregate_keys=n}var f=SC.Record,l=f.DIRTY,c=f.READY_NEW,h=f.DESTROYED,p=f.READY_CLEAN,d;d=function(e){var t,n,r,i;if(e){t=this.get("status");if(t&l||t&c||t&h)n=e.get("store"),r=e.get("storeKey"),i=n.peekStatus(r),i===p&&e.get("store").recordDidChange(e.constructor,null,e.get("storeKey"),null,YES)}};for(r=0,i=n.length;r<i;++r)s=n[r],u=this.get(s),a=SC.kindOf(u,SC.ManyArray)?u:[u],a.forEach(d,this)},storeDidChangeProperties:function(e,t){if(e)this.notifyPropertyChange("status");else{t?(this.beginPropertyChanges(),t.forEach(function(e){this.notifyPropertyChange(e)},this),this.notifyPropertyChange("status"),this.endPropertyChanges()):this.allPropertiesDidChange();var n=this.relationships,r=n?n.length:0;while(--r>=0)n[r].recordPropertyDidChange(t)}},normalize:function(e){var t=this.primaryKey,n=this.get("id"),r=this.get("store"),i=this.get("storeKey"),s={},o,u,a,f,l,c,h,p,d,v,m,g=r.readEditableDataHash(i)||{};g[t]=n,f=r.readDataHash(i);for(o in this)u=this[o],u&&(a=u.typeClass,a&&(v=u.get("key")||o,s[v]=YES,h=SC.typeOf(a.call(u))===SC.T_CLASS,p=u.isNestedRecordTransform,!h&&!p?(l=this.get(o),l===undefined||l===null&&!e?e||(s[v]=
NO):(m=this[o],SC.instanceOf(m,SC.RecordAttribute)&&(l=m.fromType(this,o,l)),g[v]=l)):p?(l=this.get(o),l&&l.normalize&&l.normalize()):h&&(l=f[v],l!==undefined?g[v]=l:(d=u.get("defaultValue"),SC.typeOf(d)===SC.T_FUNCTION?g[v]=d(this,o,d):g[v]=d))));for(o in g)s[o]||(SC.debug("%@: Deleting key from underlying data hash due to normalization: %@",this,o),delete g[o]);return this},unknownProperty:function(e,t){if(t!==undefined){var n=this.get("storeKey"),r=SC.Store.recordTypeFor(n);if(r.ignoreUnknownProperties===YES)return this[e]=t,t;var i=this.get("primaryKey");this.writeAttribute(e,t),e===i&&SC.Store.replaceIdFor(n,t)}return this.readAttribute(e)},commitRecord:function(e,t,n){var r=this.get("store"),i,s,o=this.get("storeKey"),u=r.parentStoreKeyExists();return s=t||SC.none(t)&&SC.none(u),s?r.commitRecord(undefined,undefined,this.get("storeKey"),e,n):u&&(i=r.materializeRecord(u),i.commitRecord(e,t,n)),this},isError:function(){return this.get("status")&SC.Record.ERROR}.property("status").cacheable(),errorValue:function(){return this.get("isError")?SC.val(this.get("errorObject")):null}.property("isError").cacheable(),errorObject:function(){if(this.get("isError")){var e=this.get("store");return e.readError(this.get("storeKey"))||SC.Record.GENERIC_ERROR}return null}.property("isError").cacheable(),set:function(e,t){var n=this[e];return n&&n.isProperty&&n.get&&!n.get("isEditable")?this:arguments.callee.base.apply(this,arguments)},toString:function(){var e=this.get("store").readDataHash(this.get("storeKey"));return"%@(%@) %@".fmt(this.constructor.toString(),SC.inspect(e),this.statusString
())},statusString:function(){var e=[],t=this.get("status");for(var n in SC.Record)n.match(/[A-Z_]$/)&&SC.Record[n]===t&&e.push(n);return e.join(" ")},registerNestedRecord:function(e,t,n){var r,i,s,o,u;return SC.none(n)&&(n=t),e&&e.get&&e.get("isRecord")?o=e:(u=this._materializeNestedRecordType(e,t),o=this.createNestedRecord(u,e)),o&&(this.isParentRecord=YES,r=this.get("store"),i=this.get("storeKey"),s=o.get("storeKey"),r.registerChildToParent(i,s,n)),o},_materializeNestedRecordType:function(e,t){var n,r,i;SC.typeOf(e)===SC.T_HASH&&(n=this.get("nestedRecordNamespace"),e.type&&!SC.none(n)&&(r=n[e.type])),!r&&t&&this[t]&&(r=this[t].get("typeClass"));if(!r||!SC.kindOf(r,SC.Record))throw"SC.Child: Error during transform: Invalid record type.";return r},createNestedRecord:function(e,t){var n,r,i,s,o=null,u=null;return SC.run(function(){t=t||{},u=t[e.prototype.primaryKey],n=this.get("store");if(SC.none(n))throw"Error: during the creation of a child record: NO STORE ON PARENT!";!r&&(s=e.prototype.primaryKey)&&(r=t[s],i=r?n.storeKeyExists(e,r):null,i?(n.writeDataHash(i,t),o=n.materializeRecord(i)):(o=n.createRecord(e,t),SC.none(r)&&(i=o.get("storeKey"),r="cr"+i,SC.Store.replaceIdFor(i,r),t=n.readEditableDataHash(i),t[s]=r))),SC.none(u)&&this.generateIdForChild&&this.generateIdForChild(o)},this),o},_nestedRecordKey:0,generateIdForChild:function(e){}}),SC.Record.mixin({ignoreUnknownProperties:NO,CLEAN:1,DIRTY:2,EMPTY:256,ERROR:4096,READY:512,READY_CLEAN:513,READY_DIRTY:514,READY_NEW:515,DESTROYED:1024,DESTROYED_CLEAN:1025,DESTROYED_DIRTY:1026,BUSY:2048,BUSY_LOADING:2052,BUSY_CREATING:2056
,BUSY_COMMITTING:2064,BUSY_REFRESH:2080,BUSY_REFRESH_CLEAN:2081,BUSY_REFRESH_DIRTY:2082,BUSY_DESTROYING:2112,BAD_STATE_ERROR:SC.$error("Internal Inconsistency"),RECORD_EXISTS_ERROR:SC.$error("Record Exists"),NOT_FOUND_ERROR:SC.$error("Not found "),BUSY_ERROR:SC.$error("Busy"),GENERIC_ERROR:SC.$error("Generic Error"),_nextChildKey:0,attr:function(e,t){return SC.RecordAttribute.attr(e,t)},fetch:function(e,t){return SC.FetchedAttribute.attr(e,t)},toMany:function(e,t){t=t||{};var n=t.nested||t.isNested,r;return n?r=SC.ChildrenAttribute.attr(e,t):r=SC.ManyAttribute.attr(e,t),r},toOne:function(e,t){t=t||{};var n=t.nested||t.isNested,r;return n?r=SC.ChildAttribute.attr(e,t):r=SC.SingleAttribute.attr(e,t),r},storeKeysById:function(){var e=SC.keyFor("storeKey",SC.guidFor(this)),t=this[e];return t||(t=this[e]={}),t},storeKeyFor:function(e){var t=this.storeKeysById(),n=t[e];return n||(n=SC.Store.generateStoreKey(),SC.Store.idsByStoreKey[n]=e,SC.Store.recordTypesByStoreKey[n]=this,t[e]=n),n},storeKeyExists:function(e){var t=this.storeKeysById(),n=t[e];return n},find:function(e,t){return e.find(this,t)},extend:function(){var e=SC.Object.extend.apply(this,arguments);return SC.Query&&SC.Query._scq_didDefineRecordType(e),e}}),SC.FixturesDataSource=SC.DataSource.extend({simulateRemoteResponse:NO,latency:50,cancel:function(e,t){return NO},fetch:function(e,t){if(t.get("location")!==SC.Query.LOCAL)throw SC.$error("SC.Fixture data source can only fetch local queries");if(!t.get("recordType")&&!t.get("recordTypes"))throw SC.$error("SC.Fixture data source can only fetch queries with one or more record types"
),i=0;for(s=0;i===0&&s<o;s++)i=SC.compare(e,t)}return i},recordPropertyDidChange:function(e){if(e&&!e.contains(this.get("propertyName")))return this;var t=this.get("readOnlyStoreIds"),n,r,i=this._prevStoreIds,s=this._storeIdsContentDidChange;if(t===i)return this;i?(i.removeArrayObservers({target:this,willChange:this.arrayContentWillChange,didChange:s}),n=i.get("length")):n=0,t?(t.addArrayObservers({target:this,willChange:this.arrayContentWillChange,didChange:s}),r=t.get("length")):r=0,this.arrayContentWillChange(0,n,r),this._prevStoreIds=t,this._storeIdsContentDidChange(0,n,r)},_storeIdsContentDidChange:function(e,t,n){this._records=null,this.arrayContentDidChange(e,t,n)},unknownProperty:function(e,t){var n;return SC.typeOf(e)===SC.T_STRING&&(n=this.reducedProperty(e,t)),n===undefined?arguments.callee.base.apply(this,arguments):n},init:function(){arguments.callee.base.apply(this,arguments),this.recordPropertyDidChange()}}),SC.ManyAttribute=SC.RecordAttribute.extend({inverse:null,isMaster:YES,orderBy:null,toType:function(e,t,n){var r=this.get("typeClass"),i=this.get("key")||t,s=SC.keyFor("__manyArray__",SC.guidFor(this)),o=e[s],u;return o||(o=SC.ManyArray.create({recordType:r,record:e,propertyName:i,manyAttribute:this}),e[s]=o,u=e.get("relationships"),u||e.set("relationships",u=[]),u.push(o)),o},fromType:function(e,t,n){var r=[];if(!SC.isArray(n))throw"Expects toMany attribute to be an array";var i=n.get("length");for(var s=0;s<i;s++)r[s]=n.objectAt(s).get("id");return r},inverseDidRemoveRecord:function(e,t,n,r){var i=e.get(t);i&&i.removeInverseRecord(n)},inverseDidAddRecord:
function(e,t,n,r){var i=e.get(t);i&&i.addInverseRecord(n)}}),SC.SingleAttribute=SC.RecordAttribute.extend({inverse:null,isMaster:YES,call:function(e,t,n){var r=this.get("key")||t,i,s,o,u,a,f;if(n!==undefined&&this.get("isEditable")){if(n&&!SC.kindOf(n,SC.Record))throw"%@ is not an instance of SC.Record".fmt(n);i=this.get("inverse"),i&&(o=this._scsa_call(e,t)),f=this.fromType(e,t,n),e.writeAttribute(r,f,!this.get("isMaster")),a=n,i&&o!==n&&(o&&(u=o[i])&&u.inverseDidRemoveRecord(o,i,e,t),n&&(u=n[i])&&u.inverseDidAddRecord(n,i,e,t))}else a=this._scsa_call(e,t,n);return a},_scsa_call:SC.RecordAttribute.prototype.call,inverseDidRemoveRecord:function(e,t,n,r){var i=this.get("inverse"),s=this._scsa_call(e,t),o=this.get("isMaster"),u;e.writeAttribute(t,null,!o),e.notifyPropertyChange(t),(s!==n||r!==i)&&s&&(u=s[i])&&u.inverseDidRemoveRecord(s,i,e,t)},inverseDidAddRecord:function(e,t,n,r){var i=this.get("inverse"),s=this._scsa_call(e,t),o=this.get("isMaster"),u,a;a=this.fromType(e,t,n),e.writeAttribute(t,a,!o),e.notifyPropertyChange(t),(s!==n||r!==i)&&s&&(u=s[i])&&u.inverseDidRemoveRecord(s,i,e,t)}}),SC.Store=SC.Object.extend({name:null,nestedStores:null,dataSource:null,isNested:NO,commitRecordsAutomatically:NO,from:function(e){return this.set("dataSource",e),this},_getDataSource:function(){var e=this.get("dataSource");return typeof e===SC.T_STRING&&(e=SC.requiredObjectForPropertyPath(e),e.isClass&&(e=e.create()),this.set("dataSource",e)),e},cascade:function(e){var t=SC.A(arguments);return e=SC.CascadeDataSource.create({dataSources:t}),this.from(e)},chain:function(e,t){e||(e={}),e.parentStore=
this;if(t){if(SC.typeOf(t)!=="class")throw new Error("%@ is not a valid class".fmt(t));if(!SC.kindOf(t,SC.NestedStore))throw new Error("%@ is not a type of SC.NestedStore".fmt(t))}else t=SC.NestedStore;e.childRecords=this.childRecords?SC.clone(this.childRecords):{},e.parentRecords=this.parentRecords?SC.clone(this.parentRecords):{};var n=t.create(e),r=this.nestedStores;return r||(r=this.nestedStores=[]),r.push(n),n},willDestroyNestedStore:function(e){return this.nestedStores&&this.nestedStores.removeObject(e),this},hasNestedStore:function(e){while(e&&e!==this)e=e.get("parentStore");return e===this},dataHashes:null,statuses:null,revisions:null,editables:null,changelog:null,recordErrors:null,queryErrors:null,childRecords:null,parentRecords:null,storeKeyEditState:function(e){var t=this.editables,n=this.locks;return t&&t[e]?SC.Store.EDITABLE:SC.Store.LOCKED},readDataHash:function(e){return this.dataHashes[e]},readEditableDataHash:function(e){var t=this.dataHashes[e];if(!t)return t;var n=this.editables;return n||(n=this.editables=[]),n[e]||(n[e]=1,t=this.dataHashes[e]=SC.clone(t,YES)),t},readEditableProperty:function(e,t){var n=this.readEditableDataHash(e),r=this.editables[e],i=n[t];return r===1&&(r=this.editables[e]={}),r[t]||(i=n[t],i&&i.isCopyable&&(i=n[t]=i.copy(YES)),r[t]=YES),i},writeDataHash:function(e,t,n){t&&(this.dataHashes[e]=t),n&&(this.statuses[e]=n);var r=this.editables;r||(r=this.editables=[]),r[e]=1;var i=this;return this._propagateToChildren(e,function(e){i.writeDataHash(e,null,n)}),this},removeDataHash:function(e,t){this.dataHashes[e]=null,this.statuses[e]=t||SC.
:function(e,t){SC.typeOf(e)===SC.T_STRING&&(e=SC.objectForPropertyPath(e));if(arguments.length===1&&!(e&&e.get&&e.get("isRecord"))){if(!e)throw new Error("SC.Store#find() must pass recordType or query");return e.isQuery||(e=SC.Query.local(e)),this._findQuery(e,YES,YES)}return this._findRecord(e,t)},findAll:function(e,t,n){SC.Logger.warn("SC.Store#findAll() will be removed in a future version of SproutCore. Use SC.Store#find() instead");if(!e||!e.isQuery)e=SC.Query.local(e,t,n);return this._findQuery(e,YES,YES)},_findQuery:function(e,t,n){var r=this._scst_recordArraysByQuery,i=SC.guidFor(e),s,o;return r||(r=this._scst_recordArraysByQuery={}),s=r[i],!s&&t&&(r[i]=s=SC.RecordArray.create({store:this,query:e}),o=this.get("recordArrays"),o||this.set("recordArrays",o=SC.Set.create()),o.add(s),n&&this.refreshQuery(e)),this.flush(),s},_findRecord:function(e,t){var n;return e&&e.get&&e.get("isRecord")?n=e.get("storeKey"):n=SC.none(t)?null:e.storeKeyFor(t),n&&this.readStatus(n)===SC.Record.EMPTY&&(n=this.retrieveRecord(e,t)),n?this.materializeRecord(n):null},recordArrayWillDestroy:function(e){var t=this._scst_recordArraysByQuery,n=this.get("recordArrays");return t&&delete t[SC.guidFor(e.get("query"))],n&&n.remove(e),this},refreshQuery:function(e){if(!e)throw new Error("refreshQuery() requires a query");var t=this._scst_recordArraysByQuery,n=t?t[SC.guidFor(e)]:null,r=this._getDataSource();return r&&r.fetch&&(n&&n.storeWillFetchQuery(e),r.fetch.call(r,this,e)),this},_notifyRecordArrays:function(e,t){var n=this.get("recordArrays");return n?(n.forEach(function(n){n&&n.storeDidChangeStoreKeys
s==i.READY_CLEAN||s==i.DESTROYED_CLEAN?(s=i.ERROR,n&&n.isError&&(o||(o=this.recordErrors=[]),o[r]=n),this.writeStatus(r,s),this.dataHashDidChange(r,null,YES),r):NO},loadQueryResults:function(e,t){if(e.get("location")===SC.Query.LOCAL)throw new Error("Cannot load query results for a local query");var n=this._findQuery(e,YES,NO);return n&&n.set("storeKeys",t),this.dataSourceDidFetchQuery(e),this},dataSourceDidFetchQuery:function(e){return this._scstore_dataSourceDidFetchQuery(e,YES)},_scstore_dataSourceDidFetchQuery:function(e,t){var n=this._findQuery(e,t,NO),r=this.get("nestedStores"),i=r?r.get("length"):0;n&&n.storeDidFetchQuery(e);while(--i>=0)r[i]._scstore_dataSourceDidFetchQuery(e,NO);return this},dataSourceDidCancelQuery:function(e){return this._scstore_dataSourceDidCancelQuery(e,YES)},_scstore_dataSourceDidCancelQuery:function(e,t){var n=this._findQuery(e,t,NO),r=this.get("nestedStores"),i=r?r.get("length"):0;n&&n.storeDidCancelQuery(e);while(--i>=0)r[i]._scstore_dataSourceDidCancelQuery(e,NO);return this},dataSourceDidErrorQuery:function(e,t){var n=this.queryErrors;return t&&t.isError&&(n||(n=this.queryErrors={}),n[SC.guidFor(e)]=t),this._scstore_dataSourceDidErrorQuery(e,YES)},_scstore_dataSourceDidErrorQuery:function(e,t){var n=this._findQuery(e,t,NO),r=this.get("nestedStores"),i=r?r.get("length"):0;n&&n.storeDidErrorQuery(e);while(--i>=0)r[i]._scstore_dataSourceDidErrorQuery(e,NO);return this},init:function(){arguments.callee.base.apply(this,arguments),this.reset()},toString:function(){var e=this.get("name");if(!e)return arguments.callee.base.apply(this,arguments);var t=
arguments.callee.base.apply(this,arguments);return"%@ (%@)".fmt(e,t)},idFor:function(e){return SC.Store.idFor(e)},recordTypeFor:function(e){return SC.Store.recordTypeFor(e)},storeKeyFor:function(e,t){return e.storeKeyFor(t)},storeKeyExists:function(e,t){return e.storeKeyExists(t)},storeKeysFor:function(e){var t=[],n=e&&e.isEnumerable,r,i,s;if(!this.statuses)return t;for(i in SC.Store.recordTypesByStoreKey)r=SC.Store.recordTypesByStoreKey[i],n?s=e.contains(r):s=r===e,s&&this.statuses[i]&&t.push(parseInt(i,10));return t},storeKeys:function(){var e=[],t;if(!this.statuses)return e;for(t in this.statuses)this.statuses[t]!=SC.Record.EMPTY&&e.push(parseInt(t,10));return e},statusString:function(e){var t=this.materializeRecord(e);return t.statusString()}}),SC.Store.mixin({CHAIN_CONFLICT_ERROR:new Error("Nested Store Conflict"),NO_PARENT_STORE_ERROR:new Error("Parent Store Required"),NESTED_STORE_UNSUPPORTED_ERROR:new Error("Unsupported In Nested Store"),NESTED_STORE_RETRIEVE_DIRTY_ERROR:new Error("Cannot Retrieve Dirty Record in Nested Store"),EDITABLE:"editable",LOCKED:"locked",INHERITED:"inherited",idsByStoreKey:[],recordTypesByStoreKey:{},queriesByStoreKey:[],nextStoreKey:1,generateStoreKey:function(){return this.nextStoreKey++},idFor:function(e){return this.idsByStoreKey[e]},queryFor:function(e){return this.queriesByStoreKey[e]},recordTypeFor:function(e){return this.recordTypesByStoreKey[e]},replaceIdFor:function(e,t){var n=this.idsByStoreKey[e],r,i;if(n!==t){r=this.recordTypeFor(e);if(!r)throw new Error("replaceIdFor: storeKey %@ does not exist".fmt(e));this.idsByStoreKey[e]=t,
i=r.storeKeysById(),delete i[n],i[t]=e}return this},replaceRecordTypeFor:function(e,t){return this.recordTypesByStoreKey[e]=t,this}}),SC.Store.prototype.nextStoreIndex=1,SC.Store._getDefaultStore=function(){var e=this._store;return e||(this._store=e=SC.Store.create()),e},SC.Store.updateRecords=function(e,t,n,r){SC.Logger.warn("SC.Store.updateRecords() is deprecated. Use loadRecords() instead");var i=this._getDefaultStore(),s=e.length,o,u;if(!n){n=[];for(o=0;o<s;o++)n[o]=e[o].recordType}u=i.loadRecords(n,e),s=u.length;for(o=0;o<s;o++)u[o]=i.materializeRecord(u[o]);return u},SC.Store.find=function(e,t){return this._getDefaultStore().find(t,e)},SC.Store.findAll=function(e,t){return this._getDefaultStore().findAll(e,t)},SC.NestedStore=SC.Store.extend({hasChanges:NO,parentStore:null,isNested:YES,lockOnRead:YES,locks:null,chainedChanges:null,find:function(e){if(e&&e.isQuery&&e.get("location")!==SC.Query.LOCAL)throw"SC.Store#find() can only accept LOCAL queries in nested stores";return arguments.callee.base.apply(this,arguments)},commitChanges:function(e){if(this.get("hasChanges")){var t=this.get("parentStore");t.commitChangesFromNestedStore(this,this.chainedChanges,e)}return this.reset(),this},discardChanges:function(){var e,t;if((e=this.records)&&(t=this.locks)){var n=this.get("parentStore"),r=n.revisions,i=this.revisions,s,o,u;for(s in e){if(!e.hasOwnProperty(s))continue;if(!(o=t[s]))continue;u=r[s],(u!==o||i[s]>u)&&this._notifyRecordPropertyChange(parseInt(s,10))}}return this.reset(),this.flush(),this},destroy:function(){this.discardChanges();var e=this.get("parentStore");return e&&
(),length:function(){this.flush();var e=this.get("storeKeys");return e?e.get("length"):0}.property("storeKeys").cacheable(),_scra_records:null,objectAt:function(e){this.flush();var t=this._scra_records,n=this.get("storeKeys"),r=this.get("store"),i,s;return!n||!r?undefined:t&&(s=t[e])?s:(t||(this._scra_records=t=[]),i=n.objectAt(e),i&&(r.peekStatus(i)===SC.Record.EMPTY&&r.retrieveRecord(null,null,i),t[e]=s=r.materializeRecord(i)),s)},forEach:function(e,t){this.flush();var n=this._scra_records,r=this.get("storeKeys"),i=this.get("store"),s=r?r.get("length"):0,o,u,a;if(!r||!i)return this;n||(n=this._scra_records=[]),t||(t=this);for(o=0;o<s;o++)a=n[o],a||(a=n[o]=i.materializeRecord(r.objectAt(o))),e.call(t,a,o,this);return this},replace:function(e,t,n){this.flush();var r=this.get("storeKeys"),i=n?n.get?n.get("length"):n.length:0,s,o;if(!r)throw"Unable to edit an SC.RecordArray that does not have its storeKeys property set.";if(!this.get("isEditable"))throw SC.RecordArray.NOT_EDITABLE;o=[];for(s=0;s<i;s++)o[s]=n.objectAt(s).get("storeKey");return r.replace(e,t,o),this},contains:function(e){return this.indexOf(e)>=0},indexOf:function(e,t){if(!SC.kindOf(e,SC.Record))return SC.Logger.warn("Using indexOf on %@ with an object that is not an SC.Record".fmt(e)),-1;this.flush();var n=e.get("storeKey"),r=this.get("storeKeys");return r?r.indexOf(n,t):-1},lastIndexOf:function(e,t){if(!SC.kindOf(e,SC.Record))return SC.Logger.warn("Using lastIndexOf on %@ with an object that is not an SC.Record".fmt(e)),-1;this.flush();var n=e.get("storeKey"),r=this.get("storeKeys");return r?r.lastIndexOf(n,t)
(),errorObject:function(){if(this.get("isError")){var e=this.get("store");return e.readQueryError(this.get("query"))||SC.Record.GENERIC_ERROR}return null}.property("isError").cacheable(),propertyWillChange:function(e,t){if(e==="storeKeys"){var n=this.get("storeKeys"),r=n?n.get("length"):0,i=t?t.get("length"):0;this.arrayContentWillChange(0,r,i)}return arguments.callee.base.apply(this,arguments)},_storeKeysDidChange:function(){var e=this.get("storeKeys"),t=this._prevStoreKeys,n,r,i=this._storeKeysContentDidChange,s=this._storeKeysStateDidChange;if(e===t)return;t?(t.removeArrayObservers({target:this,willChange:this.arrayContentWillChange,didChange:this._storeKeysContentDidChange}),n=t.get("length")):n=0,this._prevStoreKeys=e,e?(e.addArrayObservers({target:this,willChange:this.arrayContentWillChange,didChange:this._storeKeysContentDidChange}),r=e.get("length")):r=0,this._storeKeysContentDidChange(0,n,r)}.observes("storeKeys"),addArrayObservers:function(){return this.flush(),SC.Array.addArrayObservers.apply(this,arguments)},_storeKeysContentDidChange:function(e,t,n){this._scra_records&&(this._scra_records.length=0),this.arrayContentDidChange(e,t,n)},init:function(){arguments.callee.base.apply(this,arguments),this._storeKeysDidChange()}}),SC.RecordArray.mixin({NOT_EDITABLE:SC.Error.desc("SC.RecordArray is not editable"),QUERY_MATCHING_THRESHOLD:100}),Function.prototype.handleEvents=function(){return this.isEventHandler=YES,this.events=arguments,this},Function.prototype.stateObserves=function(){return this.isStateObserveHandler=YES,this.args=SC.A(arguments),this},SC.StatechartEventDelegate=
{isStatechartEventDelegate:YES,tryToPerform:function(e,t,n){if(!this.respondsTo(e))return NO;if(SC.typeOf(this[e])===SC.T_FUNCTION){var r=this[e](t,n);if(r!==NO)return YES}return!!this.sendEvent(e,t,n)},sendEvent:function(e,t,n){}},SC.StatechartRoutingDelegate={isStatechartDelegate:YES,isStatechartRoutingDelegate:YES,statechartUpdateLocationForState:function(e,t,n){SC.routes.set("location",t)},statechartAcquireLocationForState:function(e,t){return SC.routes.get("location")},statechartBindStateToRoute:function(e,t,n,r){SC.routes.add(n,t,r)},statechartShouldStateHandleTriggeredRoute:function(e,t,n){return YES},statechartStateCancelledHandlingTriggeredRoute:function(e,t,n){}},SC.StatechartDelegate=SC.StatechartRoutingDelegate,SC.StatePathMatcher=SC.Object.extend({state:null,expression:null,tokens:null,init:function(){arguments.callee.base.apply(this,arguments),this._parseExpression()},_parseExpression:function(){var e=this.expression?this.expression.split("."):[],t=e.length,n=0,r,i=null,s,o=[];for(;n<t;n+=1){r=e[n];if(r.indexOf("~")>=0){r=r.split("~");if(r.length>2)throw"Invalid use of '~' at part %@".fmt(n);s=SC.StatePathMatcher._ExpandToken.create({start:r[0],end:r[1]})}else if(r==="this"){if(o.length>0)throw"Invalid use of 'this' at part %@".fmt(n);s=SC.StatePathMatcher._ThisToken.create()}else s=SC.StatePathMatcher._BasicToken.create({value:r});s.owner=this,o.push(s)}this.set("tokens",o);var u=SC.clone(o);this._chain=i=u.pop();while(s=u.pop())i.nextToken=s,i=s},lastPart:function(){var e=this.get("tokens"),t=e?e.length:0,n=t>0?e[t-1]:null;return n.get("lastPart")}.property("tokens"
),e.removeObserver(n,this,"_statechartTraceDidChange"));var r=this.get("substates");r&&r.forEach(function(e){e.destroy()}),this._teardownAllStateObserveHandlers(),this.set("substates",null),this.set("currentSubstates",null),this.set("enteredSubstates",null),this.set("parentState",null),this.set("historyState",null),this.set("initialSubstate",null),this.set("statechart",null),this.notifyPropertyChange("trace"),this.notifyPropertyChange("owner"),this._registeredEventHandlers=null,this._registeredStringEventHandlers=null,this._registeredRegExpEventHandlers=null,this._registeredStateObserveHandlers=null,this._registeredSubstatePaths=null,this._registeredSubstates=null,arguments.callee.base.apply(this,arguments)},initState:function(){if(this.get("stateIsInitialized"))return;this._registerWithParentStates(),this._setupRouteHandling();var e=null,t=null,n=null,r=null,i=this.constructor,s=null,o=[],u=NO,a=this.get("initialSubstate"),f=this.get("substatesAreConcurrent"),l=this.get("statechart"),c=0,h=0,p=NO,d=null;this.set("substates",o),a&&a.isClass&&SC.kindOf(a,SC.HistoryState)&&(d=this.createSubstate(a),this.set("initialSubstate",d),SC.none(d.get("defaultState"))&&(this.stateLogError("Initial substate is invalid. History state requires the name of a default state to be set"),this.set("initialSubstate",null),d=null));for(e in this){t=this[e];if(!t)continue;r=t,n=t.isClass,p=!n&&t instanceof Function;if(p){if(t.isEventHandler){this._registerEventHandler(e,t);continue}if(t.isStateObserveHandler){this._registerStateObserveHandler(e,t);continue}t.statePlugin&&(t=t.apply(this))}t&&t.isClass&&
r!==i&&SC.kindOf(t,SC.State)&&(s=this._addSubstate(e,t),e===a?(this.set("initialSubstate",s),u=YES):d&&d.get("defaultState")===e&&(d.set("defaultState",s),u=YES))}!SC.none(a)&&!u&&this.stateLogError("Unable to set initial substate %@ since it did not match any of state's %@ substates".fmt(a,this)),o.length===0?SC.none(a)||this.stateLogWarning("Unable to make %@ an initial substate since state %@ has no substates".fmt(a,this)):o.length>0&&(s=this._addEmptyInitialSubstateIfNeeded(),!s&&a&&f&&(this.set("initialSubstate",null),this.stateLogWarning("Can not use %@ as initial substate since substates are all concurrent for state %@".fmt(a,this)))),this.notifyPropertyChange("substates"),this.set("currentSubstates",[]),this.set("enteredSubstates",[]),this.set("stateIsInitialized",YES)},_setupRouteHandling:function(){var e=this.get("representRoute"),t=this.get("statechart"),n=this.get("routingDelegate");if(!e)return;if(this.get("isConcurrentState")){this.stateLogError("State %@ cannot handle route '%@' since state is concurrent".fmt(this,e));return}n.statechartBindStateToRoute(t,this,e,this.routeTriggered)},routeTriggered:function(e){if(this._isEnteringState)return;var t=this.get("statechart"),n=this.get("routingDelegate"),r=this.get("location"),i={state:this,location:r,params:e,handler:this.routeTriggered},s=this.createStateRouteHandlerContext(i);n.statechartShouldStateHandleTriggeredRoute(t,this,s)?(this.get("trace")&&r&&this.stateLogTrace("will handle route '%@'".fmt(r)),this.handleTriggeredRoute(s)):n.statechartStateCancelledHandlingTriggeredRoute(t,this,s)},createStateRouteHandlerContext
:function(e){return SC.StateRouteHandlerContext.create(e)},handleTriggeredRoute:function(e){this.gotoState(this,e)},_addEmptyInitialSubstateIfNeeded:function(){var e=this.get("initialSubstate"),t=this.get("substatesAreConcurrent");if(e||t)return null;var n=this.createSubstate(SC.EmptyState);return this.set("initialSubstate",n),this.get("substates").push(n),this[n.get("name")]=n,n.initState(),this.stateLogWarning("state %@ has no initial substate defined. Will default to using an empty state as initial substate".fmt(this)),n},_addSubstate:function(e,t,n){var r=this.get("substates");return n=SC.clone(n)||{},n.name=e,t=this.createSubstate(t,n),r.push(t),this[e]=t,t.initState(),t},addSubstate:function(e,t,n){if(SC.empty(e))return this.stateLogError("Can not add substate. name required"),null;if(this[e]!==undefined)return this.stateLogError("Can not add substate '%@'. Already a defined property".fmt(e)),null;if(!this.get("stateIsInitialized"))return this.stateLogError("Can not add substate '%@'. this state is not yet initialized".fmt(e)),null;var r=arguments.length;r===1?t=SC.State:r===2&&SC.typeOf(t)===SC.T_HASH&&(n=t,t=SC.State);var i=t&&t.isClass&&SC.kindOf(t,SC.State);return i?(t=this._addSubstate(e,t,n),this._addEmptyInitialSubstateIfNeeded(),this.notifyPropertyChange("substates"),t):(this.stateLogError("Can not add substate '%@'. must provide a state class".fmt(e)),null)},createSubstate:function(e,t){return t=t||{},e.create({parentState:this,statechart:this.get("statechart")},t)},_registerEventHandler:function(e,t){var n=t.events,r=null,i=n.length,s=0;this._registeredEventHandlers
[e]=t;for(;s<i;s+=1){r=n[s];if(SC.typeOf(r)===SC.T_STRING){this._registeredStringEventHandlers[r]={name:e,handler:t};continue}if(r instanceof RegExp){this._registeredRegExpEventHandlers.push({name:e,handler:t,regexp:r});continue}this.stateLogError("Invalid event %@ for event handler %@ in state %@".fmt(r,e,this))}},_registerStateObserveHandler:function(e,t){var n=0,r=t.args,i=r.length,s,o=YES;for(;n<i;n+=1){s=r[n];if(SC.typeOf(s)!==SC.T_STRING||SC.empty(s))this.stateLogError("Invalid argument %@ for state observe handler %@ in state %@".fmt(s,e,this)),o=NO}if(!o)return;this._registeredStateObserveHandlers[e]=t.args},_registerWithParentStates:function(){var e=this.get("parentState");while(!SC.none(e))e._registerSubstate(this),e=e.get("parentState")},_registerSubstate:function(e){var t=e.pathRelativeTo(this);if(SC.none(t))return;this._registeredSubstates.push(e);var n=this._registeredSubstatePaths;n[e.get("name")]===undefined&&(n[e.get("name")]={});var r=n[e.get("name")];r[t]=e},pathRelativeTo:function(e){var t=this.get("name"),n=this.get("parentState");while(!SC.none(n)&&n!==e)t="%@.%@".fmt(n.get("name"),t),n=n.get("parentState");return n!==e&&e!==this?(this.stateLogError("Can not generate relative path from %@ since it not a parent state of %@".fmt(e,this)),null):t},getSubstate:function(e,t,n){if(!e)return null;var r=SC.typeOf(e);if(r===SC.T_OBJECT)return this._registeredSubstates.indexOf(e)>-1?e:null;if(r!==SC.T_STRING)return this.stateLogError("Can not find matching subtype. value must be an object or string: %@".fmt(e)),null;var i=SC.StatePathMatcher.create({state:this,expression
:e}),s=[],o;if(i.get("tokens").length===0)return null;var u=this._registeredSubstatePaths[i.get("lastPart")];if(!u)return this._notifySubstateNotFound(t,n,e);for(o in u)i.match(o)&&s.push(u[o]);if(s.length===1)return s[0];if(s.length>1){var a=[];for(o in u)a.push(o);if(t)return this._notifySubstateNotFound(t,n,e,a);var f="Can not find substate matching '%@' in state %@. Ambiguous with the following: %@";this.stateLogError(f.fmt(e,this.get("fullPath"),a.join(", ")))}return this._notifySubstateNotFound(t,n,e)},_notifySubstateNotFound:function(e,t,n,r){return e?e.call(t||this,this,n,r):null},getState:function(e){return e===this.get("name")?this:SC.kindOf(e,SC.State)?e:this.getSubstate(e,this._handleSubstateNotFound)},_handleSubstateNotFound:function(e,t,n){var r=this.get("parentState");if(r)return r.getState(t);if(n){var i="Can not find state matching '%@'. Ambiguous with the following: %@";this.stateLogError(i.fmt(t,n.join(", ")))}return null},gotoState:function(e,t){var n=this.getState(e);if(!n){var r="can not go to state %@ from state %@. Invalid value.";this.stateLogError(r.fmt(e,this));return}var i=this.findFirstRelativeCurrentState(n);this.get("statechart").gotoState(n,i,!1,t)},gotoHistoryState:function(e,t,n){var r=this.getState(e);if(!r){var i="can not go to history state %@ from state %@. Invalid value.";this.stateLogError(i.fmt(e,this));return}var s=this.findFirstRelativeCurrentState(r);this.get("statechart").gotoHistoryState(r,s,t,n)},resumeGotoState:function(){this.get("statechart").resumeGotoState()},stateIsCurrentSubstate:function(e){SC.typeOf(e)===SC.T_STRING&&(e=
this.get("statechart").getState(e));var t=this.get("currentSubstates");return!!t&&t.indexOf(e)>=0},stateIsEnteredSubstate:function(e){SC.typeOf(e)===SC.T_STRING&&(e=this.get("statechart").getState(e));var t=this.get("enteredSubstates");return!!t&&t.indexOf(e)>=0},isRootState:function(){return this.getPath("statechart.rootState")===this}.property(),isCurrentState:function(){return this.stateIsCurrentSubstate(this)}.property("currentSubstates").cacheable(),isConcurrentState:function(){return this.getPath("parentState.substatesAreConcurrent")}.property(),isEnteredState:function(){return this.stateIsEnteredSubstate(this)}.property("enteredSubstates").cacheable(),hasSubstates:function(){return this.getPath("substates.length")>0}.property("substates"),hasCurrentSubstates:function(){var e=this.get("currentSubstates");return!!e&&e.get("length")>0}.property("currentSubstates").cacheable(),hasEnteredSubstates:function(){var e=this.get("enteredSubstates");return!!e&&e.get("length")>0}.property("enteredSubstates").cacheable(),findFirstRelativeCurrentState:function(e){if(this.get("isCurrentState"))return this;var t=this.get("currentSubstates")||[],n=t.get("length"),r=this.get("parentState");if(n===0)return r?r.findFirstRelativeCurrentState():null;if(n>1){e=this.getSubstate(e);if(e)return e.findFirstRelativeCurrentState()}return t[0]},reenter:function(){this.get("isEnteredState")?this.gotoState(this):SC.Logger.error("Can not re-enter state %@ since it is not an entered state in the statechart".fmt(this))},tryToHandleEvent:function(e,t,n){var r=this.get("trace"),i=this.get("statechart"),s;
if(this._registeredEventHandlers[e])return this.stateLogWarning("state %@ can not handle event '%@' since it is a registered event handler".fmt(this,e)),NO;if(this._registeredStateObserveHandlers[e])return this.stateLogWarning("state %@ can not handle event '%@' since it is a registered state observe handler".fmt(this,e)),NO;if(SC.typeOf(this[e])===SC.T_FUNCTION)return r&&this.stateLogTrace("will handle event '%@'".fmt(e)),i.stateWillTryToHandleEvent(this,e,e),s=this[e](t,n)!==NO,i.stateDidTryToHandleEvent(this,e,e,s),s;var o=this._registeredStringEventHandlers[e];if(o)return r&&this.stateLogTrace("%@ will handle event '%@'".fmt(o.name,e)),i.stateWillTryToHandleEvent(this,e,o.name),s=o.handler.call(this,e,t,n)!==NO,i.stateDidTryToHandleEvent(this,e,o.name,s),s;var u=this._registeredRegExpEventHandlers.length,a=0;for(;a<u;a+=1){o=this._registeredRegExpEventHandlers[a];if(e.match(o.regexp))return r&&this.stateLogTrace("%@ will handle event '%@'".fmt(o.name,e)),i.stateWillTryToHandleEvent(this,e,o.name),s=o.handler.call(this,e,t,n)!==NO,i.stateDidTryToHandleEvent(this,e,o.name,s),s}return SC.typeOf(this.unknownEvent)===SC.T_FUNCTION?(r&&this.stateLogTrace("unknownEvent will handle event '%@'".fmt(e)),i.stateWillTryToHandleEvent(this,e,"unknownEvent"),s=this.unknownEvent(e,t,n)!==NO,i.stateDidTryToHandleEvent(this,e,"unknownEvent",s),s):NO},enterState:function(e){},stateWillBecomeEntered:function(e){this._isEnteringState=YES},stateDidBecomeEntered:function(e){this._setupAllStateObserveHandlers(),this._isEnteringState=NO},exitState:function(e){},stateWillBecomeExited:function(e){
this._isExitingState=YES,this._teardownAllStateObserveHandlers()},stateDidBecomeExited:function(e){this._isExitingState=NO},_setupAllStateObserveHandlers:function(){this._configureAllStateObserveHandlers("addObserver")},_teardownAllStateObserveHandlers:function(){this._configureAllStateObserveHandlers("removeObserver")},_configureAllStateObserveHandlers:function(e){var t,n,r,i,s,o,u,a;for(t in this._registeredStateObserveHandlers){n=this._registeredStateObserveHandlers[t];for(u=0;u<n.length;u+=1)s=n[u],o=t,i=s.indexOf("."),i<0?this[e](s,this,o):s.indexOf("*")===0?this[e](s.slice(1),this,o):(a=null,i===0?(a=this,s=s.slice(1)):i===4&&s.slice(0,5)==="this."?(a=this,s=s.slice(5)):i<0&&s.length===4&&s==="this"&&(a=this,s=""),SC.Observers[e](s,this,o,a))}},performAsync:function(e,t,n){return SC.Async.perform(e,t,n)},respondsToEvent:function(e){if(this._registeredEventHandlers[e])return!1;if(SC.typeOf(this[e])===SC.T_FUNCTION)return!0;if(this._registeredStringEventHandlers[e])return!0;if(this._registeredStateObserveHandlers[e])return!1;var t=this._registeredRegExpEventHandlers.length,n=0,r;for(;n<t;n+=1){r=this._registeredRegExpEventHandlers[n];if(e.match(r.regexp))return!0}return SC.typeOf(this.unknownEvent)===SC.T_FUNCTION},fullPath:function(){var e=this.getPath("statechart.rootState");return e?this.pathRelativeTo(e):this.get("name")}.property("name","parentState").cacheable(),toString:function(){return this.get("fullPath")},_enteredSubstatesDidChange:function(){this.notifyPropertyChange("enteredSubstates")}.observes("*enteredSubstates.[]"),_currentSubstatesDidChange:function(){this
.notifyPropertyChange("currentSubstates")}.observes("*currentSubstates.[]"),_statechartTraceDidChange:function(){this.notifyPropertyChange("trace")},_statechartOwnerDidChange:function(){this.notifyPropertyChange("owner")},stateLogTrace:function(e){var t=this.get("statechart");t.statechartLogTrace("%@: %@".fmt(this,e))},stateLogWarning:function(e){var t=this.get("statechart");t.statechartLogWarning(e)},stateLogError:function(e){var t=this.get("statechart");t.statechartLogError(e)}}),SC.State.plugin=function(e){var t=SC.A(arguments);t.shift();var n=function(){var n=SC.objectForPropertyPath(e);return n?!n.isClass||!n.kindOf(SC.State)?(console.error("SC.State.plugin: Unable to extend. %@ must be a class extending from SC.State".fmt(e)),undefined):n.extend.apply(n,t):(console.error("SC.State.plugin: Unable to determine path %@".fmt(e)),undefined)};return n.statePlugin=YES,n},SC.State.design=SC.State.extend,SC.EMPTY_STATE_NAME="__EMPTY_STATE__",SC.EmptyState=SC.State.extend({name:SC.EMPTY_STATE_NAME,enterState:function(){var e="No initial substate was defined for state %@. Entering default empty state";this.stateLogWarning(e.fmt(this.get("parentState")))}}),SC.HistoryState=SC.Object.extend({isRecursive:NO,defaultState:null,statechart:null,parentState:null,state:function(){var e=this.get("defaultState"),t=this.getPath("parentState.historyState");return t?t:e}.property().cacheable(),parentHistoryStateDidChange:function(){this.notifyPropertyChange("state")}.observes("*parentState.historyState")}),SC.StateRouteHandlerContext=SC.Object.extend({state:null,location:null,params:null,handler
),n=this.get("rootState"),r;t&&this.statechartLogTrace("BEGIN initialize statechart"),n?SC.typeOf(n)===SC.T_FUNCTION&&n.statePlugin&&(n=n.apply(this)):n=this._constructRootStateClass();if(!SC.kindOf(n,SC.State)||!n.isClass)throw r="Unable to initialize statechart. Root state must be a state class",this.statechartLogError(r),r;n=this.createRootState(n,{statechart:this,name:SC.ROOT_STATE_NAME}),this.set("rootState",n),n.initState();if(SC.kindOf(n.get("initialSubstate"),SC.EmptyState))throw r="Unable to initialize statechart. Root state must have an initial substate explicilty defined",this.statechartLogError(r),r;if(!SC.empty(this.get("initialState"))){var i="initialState";this.set(i,n.get(this.get(i)))}this.set("statechartIsInitialized",YES),this.gotoState(n),t&&this.statechartLogTrace("END initialize statechart")},createRootState:function(e,t){return t||(t={}),e=e.create(t),e},currentStates:function(){return this.getPath("rootState.currentSubstates")}.property().cacheable(),firstCurrentState:function(){var e=this.get("currentStates");return e?e.objectAt(0):null}.property("currentStates").cacheable(),currentStateCount:function(){return this.getPath("currentStates.length")}.property("currentStates").cacheable(),stateIsCurrentState:function(e){return this.get("rootState").stateIsCurrentSubstate(e)},enteredStates:function(){return this.getPath("rootState.enteredSubstates")}.property().cacheable(),stateIsEntered:function(e){return this.get("rootState").stateIsEnteredSubstate(e)},doesContainState:function(e){return!SC.none(this.getState(e))},getState:function(e){var t=this.get("rootState"
);return t===e?t:t.getSubstate(e)},gotoState:function(e,t,n,r){if(!this.get("statechartIsInitialized")){this.statechartLogError("can not go to state %@. statechart has not yet been initialized".fmt(e));return}if(this.get("isDestroyed")){this.statechartLogError("can not go to state %@. statechart is destroyed".fmt(this));return}var i=this._processGotoStateArgs(arguments);e=i.state,t=i.fromCurrentState,n=i.useHistory,r=i.context;var s=null,o=[],u=[],a=this.get("allowStatechartTracing"),f=this.get("rootState"),l=e,c=t,h;e=this.getState(e);if(SC.none(e)){this.statechartLogError("Can not to goto state %@. Not a recognized state in statechart".fmt(l));return}if(this._gotoStateLocked){this._pendingStateTransitions.push({state:e,fromCurrentState:t,useHistory:n,context:r});return}this._gotoStateLocked=YES;if(t){t=this.getState(t);if(SC.none(t)||!t.get("isCurrentState")){h="Can not to goto state %@. %@ is not a recognized current state in statechart",this.statechartLogError(h.fmt(l,c)),this._gotoStateLocked=NO;return}}else t=e.findFirstRelativeCurrentState(),t||(t=this.get("firstCurrentState"));a&&(this.statechartLogTrace("BEGIN gotoState: %@".fmt(e)),h="starting from current state: %@",h=h.fmt(t?t:"---"),this.statechartLogTrace(h),h="current states before: %@",h=h.fmt(this.getPath("currentStates.length")>0?this.get("currentStates"):"---"),this.statechartLogTrace(h)),SC.none(t)||(o=this._createStateChain(t)),u=this._createStateChain(e),s=this._findPivotState(o,u);if(s){a&&this.statechartLogTrace("pivot state = %@".fmt(s));if(s.get("substatesAreConcurrent")&&s!==e){this.statechartLogError
("Can not go to state %@ from %@. Pivot state %@ has concurrent substates.".fmt(e,t,s)),this._gotoStateLocked=NO;return}}var p=[];this._traverseStatesToExit(o.shift(),o,s,p),s!==e?this._traverseStatesToEnter(u.pop(),u,s,n,p):(this._traverseStatesToExit(s,[],null,p),this._traverseStatesToEnter(s,null,null,n,p)),this._gotoStateActions=p,this._executeGotoStateActions(e,p,null,r)},gotoStateActive:function(){return this._gotoStateLocked}.property(),gotoStateSuspended:function(){return this._gotoStateLocked&&!!this._gotoStateSuspendedPoint}.property(),resumeGotoState:function(){if(!this.get("gotoStateSuspended")){this.statechartLogError("Can not resume goto state since it has not been suspended");return}var e=this._gotoStateSuspendedPoint;this._executeGotoStateActions(e.gotoState,e.actions,e.marker,e.context)},_executeGotoStateActions:function(e,t,n,r){var i=null,s=t.length,o=null;n=SC.none(n)?0:n;for(;n<s;n+=1){this._currentGotoStateAction=i=t[n];switch(i.action){case SC.EXIT_STATE:o=this._exitState(i.state,r);break;case SC.ENTER_STATE:o=this._enterState(i.state,i.currentState,r)}if(SC.kindOf(o,SC.Async)){this._gotoStateSuspendedPoint={gotoState:e,actions:t,marker:n+1,context:r},o.tryToPerform(i.state);return}}this.beginPropertyChanges(),this.notifyPropertyChange("currentStates"),this.notifyPropertyChange("enteredStates"),this.endPropertyChanges(),this.get("allowStatechartTracing")&&(this.statechartLogTrace("current states after: %@".fmt(this.get("currentStates"))),this.statechartLogTrace("END gotoState: %@".fmt(e))),this._cleanupStateTransition()},_cleanupStateTransition:function(
){this._currentGotoStateAction=null,this._gotoStateSuspendedPoint=null,this._gotoStateActions=null,this._gotoStateLocked=NO,this._flushPendingStateTransition()},_exitState:function(e,t){var n;if(e.get("currentSubstates").indexOf(e)>=0){n=e.get("parentState");while(n)n.get("currentSubstates").removeObject(e),n=n.get("parentState")}n=e;while(n)n.get("enteredSubstates").removeObject(e),n=n.get("parentState");this.get("allowStatechartTracing")&&this.statechartLogTrace("<-- exiting state: %@".fmt(e)),e.set("currentSubstates",[]),e.stateWillBecomeExited(t);var r=this.exitState(e,t);return e.stateDidBecomeExited(t),this.get("monitorIsActive")&&this.get("monitor").pushExitedState(e),e._traverseStatesToExit_skipState=NO,r},exitState:function(e,t){return e.exitState(t)},_enterState:function(e,t,n){var r=e.get("parentState");r&&!e.get("isConcurrentState")&&r.set("historyState",e);if(t){r=e;while(r)r.get("currentSubstates").pushObject(e),r=r.get("parentState")}r=e;while(r)r.get("enteredSubstates").pushObject(e),r=r.get("parentState");this.get("allowStatechartTracing")&&this.statechartLogTrace("--> entering state: %@".fmt(e)),e.stateWillBecomeEntered(n);var i=this.enterState(e,n);return e.stateDidBecomeEntered(n),this.get("monitorIsActive")&&this.get("monitor").pushEnteredState(e),i},enterState:function(e,t){return e.enterStateByRoute&&SC.kindOf(t,SC.StateRouteHandlerContext)?e.enterStateByRoute(t):e.enterState(t)},gotoHistoryState:function(e,t,n,r){if(!this.get("statechartIsInitialized")){this.statechartLogError("can not go to state %@'s history state. Statechart has not yet been initialized"
.fmt(e));return}var i=this._processGotoStateArgs(arguments);e=i.state,t=i.fromCurrentState,n=i.useHistory,r=i.context,e=this.getState(e);if(!e){this.statechartLogError("Can not to goto state %@'s history state. Not a recognized state in statechart".fmt(e));return}var s=e.get("historyState");n?this.gotoState(e,t,YES,r):s?this.gotoState(s,t,r):this.gotoState(e,t,r)},sendEvent:function(e,t,n){if(this.get("isDestroyed")){this.statechartLogError("can send event %@. statechart is destroyed".fmt(e));return}var r=NO,i=this.get("currentStates").slice(),s={},o=[],u=NO,a=0,f=0,l=null,c=this.get("allowStatechartTracing");if(this._sendEventLocked||this._goStateLocked){this._pendingSentEvents.push({event:e,arg1:t,arg2:n});return}this._sendEventLocked=YES;var h=this.get("eventDelegate");h&&(r=h.sendEvent(e,t,n),r&&c&&this.statechartLogTrace("eventDelegate handled event: '%@'".fmt(e)));if(!r){c&&this.statechartLogTrace("BEGIN sendEvent: '%@'".fmt(e)),a=i.get("length");for(;f<a;f+=1){l=i[f];if(!l.get("isCurrentState"))continue;while(l){var p=SC.hashFor(l);if(l.get("substatesAreConcurrent")){s[p]?s[p]++:s[p]=1;if(s[p]<l.substates.length||o.indexOf(l)!=-1)break}u=l.tryToHandleEvent(e,t,n),r=r||u;var d=l.get("parentState");u&&d&&d.get("substatesAreConcurrent")&&o.push(d);if(u)break;l=l.get("parentState")}}c&&(r||this.statechartLogTrace("No state was able handle event %@".fmt(e)),this.statechartLogTrace("END sendEvent: '%@'".fmt(e)))}this._sendEventLocked=NO;var v=this._flushPendingSentEvents();return r?this:v?this:null},stateWillTryToHandleEvent:function(e,t,n){this._stateHandleEventInfo={state
.get("substatesAreConcurrent")&&this._traverseConcurrentStatesToEnter(e.get("substates"),f,r,i)}},respondsTo:function(e){var t=this.get("currentStates"),n=t.get("length"),r=0,i=null;for(;r<n;r+=1){i=t.objectAt(r);while(i){if(i.respondsToEvent(e))return!0;i=i.get("parentState")}}return SC.typeOf(this[e])===SC.T_FUNCTION},invokeStateMethod:function(e,t,n){if(e==="unknownEvent"){this.statechartLogError("can not invoke method unkownEvent");return}t=SC.A(arguments),t.shift();var r=t.length,i=r>0?t[r-1]:null,s=SC.typeOf(i)===SC.T_FUNCTION?t.pop():null,o=this.get("currentStates"),u=0,a=null,f={},l,c=undefined,h=0;r=o.get("length");for(;u<r;u+=1){a=o.objectAt(u);while(a){if(f[a.get("fullPath")])break;f[a.get("fullPath")]=YES,l=a[e];if(SC.typeOf(l)===SC.T_FUNCTION&&!l.isEventHandler){c=l.apply(a,t),s&&s.call(this,a,c),h+=1;break}a=a.get("parentState")}}return h===1?c:undefined},_traverseConcurrentStatesToEnter:function(e,t,n,r){var i=0,s=e.length,o=null;for(;i<s;i+=1)o=e[i],o!==t&&this._traverseStatesToEnter(o,null,null,n,r)},_flushPendingStateTransition:function(){if(!this._pendingStateTransitions){this.statechartLogError("Unable to flush pending state transition. _pendingStateTransitions is invalid");return}var e=this._pendingStateTransitions.shift();if(!e)return;this.gotoState(e.state,e.fromCurrentState,e.useHistory,e.context)},_flushPendingSentEvents:function(){var e=this._pendingSentEvents.shift();return e?this.sendEvent(e.event,e.arg1,e.arg2):null},_monitorIsActiveDidChange:function(){this.get("monitorIsActive")&&SC.none(this.get("monitor"))&&this.set("monitor",SC.StatechartMonitor
.create())}.observes("monitorIsActive"),_processGotoStateArgs:function(e){var t={state:null,fromCurrentState:null,useHistory:!1,context:null},n=null,r=null;e=SC.$A(e),e=e.filter(function(e){return e!==undefined}),n=e.length;if(n<1)return t;t.state=e[0];if(n===2){r=e[1];switch(SC.typeOf(r)){case SC.T_BOOL:t.useHistory=r;break;case SC.T_HASH:case SC.T_OBJECT:SC.kindOf(r,SC.State)||(t.context=r);break;default:t.fromCurrentState=r}}else n===3?(r=e[1],SC.typeOf(r)===SC.T_BOOL?(t.useHistory=r,t.context=e[2]):(t.fromCurrentState=r,r=e[2],SC.typeOf(r)===SC.T_BOOL?t.useHistory=r:t.context=r)):(t.fromCurrentState=e[1],t.useHistory=e[2],t.context=e[3]);return t},_constructRootStateClass:function(){var e="rootStateExample",t=this.get(e),n=this.get("initialState"),r=this.get("statesAreConcurrent"),i=0,s,o,u,a={};SC.typeOf(t)===SC.T_FUNCTION&&t.statePlugin&&(t=t.apply(this));if(!SC.kindOf(t,SC.State)||!t.isClass)return this._logStatechartCreationError("Invalid root state example"),null;if(r&&!SC.empty(n))this._logStatechartCreationError("Can not assign an initial state when states are concurrent");else if(r)a.substatesAreConcurrent=YES;else{if(SC.typeOf(n)!==SC.T_STRING)return this._logStatechartCreationError("Must either define initial state or assign states as concurrent"),null;a.initialSubstate=n}for(s in this){if(s===e)continue;o=this[s],u=SC.typeOf(o)===SC.T_FUNCTION,u&&o.statePlugin&&(o=o.apply(this)),SC.kindOf(o,SC.State)&&o.isClass&&this[s]!==this.constructor&&(a[s]=o,i+=1)}return i===0?(this._logStatechartCreationError("Must define one or more states"),null):t.extend(a)},_logStatechartCreationError
n[r].offset){var u=W(n[r-1].offset||0),a=0;for(var f=r+1;f<i;f++)if(n[f].offset){a=n[f].offset;break}a||(a=100,f=i),a=W(a);var l=(a-u)/(f-r+1);for(;r<f;r++)u+=l,n[r].offset=u+"%"}return n}),Tt=function(t,n,r,i){var s;if(!e.is(t,M)&&!e.is(t,"object"))return{container:1,x:t,y:n,width:r,height:i};s=e.is(t,M)?o.getElementById(t):t;if(s.tagName)return n==null?{container:s,width:s.style.pixelWidth||s.offsetWidth,height:s.style.pixelHeight||s.offsetHeight}:{container:s,width:n,height:r}},Nt=function(e,t){var n=this;for(var r in t)if(t[s](r)&&!(r in e))switch(typeof t[r]){case"function":(function(t){e[r]=e===n?t:function(){return t[h](n,arguments)}})(t[r]);break;case"object":e[r]=e[r]||{},Nt.call(this,e[r],t[r]);break;default:e[r]=t[r]}},Ct=function(e,t){e==t.top&&(t.top=e.prev),e==t.bottom&&(t.bottom=e.next),e.next&&(e.next.prev=e.prev),e.prev&&(e.prev.next=e.next)},kt=function(e,t){if(t.top===e)return;Ct(e,t),e.next=null,e.prev=t.top,t.top.next=e,t.top=e},Lt=function(e,t){if(t.bottom===e)return;Ct(e,t),e.next=t.bottom,e.prev=null,t.bottom.prev=e,t.bottom=e},At=function(e,t,n){Ct(e,n),t==n.top&&(n.top=e),t.next&&(t.next.prev=e),e.next=t.next,e.prev=t,t.next=e},Ot=function(e,t,n){Ct(e,n),t==n.bottom&&(n.bottom=e),t.prev&&(t.prev.next=e),e.prev=t.prev,t.prev=e,e.next=t},Mt=function(e){return function(){throw new Error("Raphaël: you are calling to method “"+e+"” of removed object")}};e.pathToRelative=vt;if(e.svg){l.svgns="http://www.w3.org/2000/svg",l.xlink="http://www.w3.org/1999/xlink",U=function(e){return+e+(~~e===e)*.5};var _t=function(e,t){if(!t)return e=o.createElementNS(l.svgns
this,this.paper),this.node.parentNode.removeChild(this.node),this.Group.parentNode.removeChild(this.Group),this.shape&&this.shape.parentNode.removeChild(this.shape);for(var e in this)delete this[e];this.removed=!0},qt.attr=function(t,n){if(this.removed)return this;if(t==null){var r={};for(var i in this.attrs)this.attrs[s](i)&&(r[i]=this.attrs[i]);return this._.rt.deg&&(r.rotation=this.rotate()),(this._.sx!=1||this._.sy!=1)&&(r.scale=this.scale()),r.gradient&&r.fill=="none"&&(r.fill=r.gradient)&&delete r.gradient,r}if(n==null&&e.is(t,"string"))return t=="translation"?kn.call(this):t=="rotation"?this.rotate():t=="scale"?this.scale():t==P&&this.attrs.fill=="none"&&this.attrs.gradient?this.attrs.gradient:this.attrs[t];if(this.attrs&&n==null&&e.is(t,_)){var o,u={};for(i=0,o=t[S];i<o;i++)u[t[i]]=this.attr(t[i]);return u}var a;n!=null&&(a={},a[t]=n),n==null&&e.is(t,"object")&&(a=t);if(a){for(var f in this.paper.customAttributes)if(this.paper.customAttributes[s](f)&&a[s](f)&&e.is(this.paper.customAttributes[f],"function")){var l=this.paper.customAttributes[f].apply(this,[][p](a[f]));this.attrs[f]=a[f];for(var c in l)l[s](c)&&(a[c]=l[c])}a.text&&this.type=="text"&&(this.node.string=a.text),Bt(this,a),a.gradient&&({circle:1,ellipse:1}[s](this.type)||g(a.gradient).charAt()!="r")&&Pt(this,a.gradient),(!en[s](this.type)||this._.rt.deg)&&this.setBox(this.attrs)}return this},qt.toFront=function(){return!this.removed&&this.Group.parentNode[c](this.Group),this.paper.top!=this&&kt(this,this.paper),this},qt.toBack=function(){return this.removed?this:(this.Group.parentNode.firstChild!=this.Group&&
function(t,n){if(t&&e.is(t,_)&&e.is(t[0],"object"))for(var r=0,i=t[S];r<i;r++)this.items[r].attr(t[r]);else for(var s=0,o=this.items[S];s<o;s++)this.items[s].attr(t,n);return this},On[i].animate=function(t,n,r,i){(e.is(r,"function")||!r)&&(i=r||null);var s=this.items[S],o=s,u,a=this,f;i&&(f=function(){!--s&&i.call(a)}),r=e.is(r,M)?r:f,u=this.items[--o].animate(t,n,r,f);while(o--)this.items[o]&&!this.items[o].removed&&this.items[o].animateWith(u,t,n,r,f);return this},On[i].insertAfter=function(e){var t=this.items[S];while(t--)this.items[t].insertAfter(e);return this},On[i].getBBox=function(){var e=[],t=[],n=[],r=[];for(var i=this.items[S];i--;){var s=this.items[i].getBBox();e[j](s.x),t[j](s.y),n[j](s.x+s.width),r[j](s.y+s.height)}return e=C[h](0,e),t=C[h](0,t),{x:e,y:t,width:N[h](0,n)-e,height:N[h](0,r)-t}},On[i].clone=function(e){e=new On;for(var t=0,n=this.items[S];t<n;t++)e[j](this.items[t].clone());return e},e.registerFont=function(e){if(!e.face)return e;this.fonts=this.fonts||{};var t={w:e.w,face:{},glyphs:{}},n=e.face["font-family"];for(var r in e.face)e.face[s](r)&&(t.face[r]=e.face[r]);this.fonts[n]?this.fonts[n][j](t):this.fonts[n]=[t];if(!e.svg){t.face["units-per-em"]=X(e.face["units-per-em"],10);for(var i in e.glyphs)if(e.glyphs[s](i)){var o=e.glyphs[i];t.glyphs[i]={w:o.w,k:{},d:o.d&&"M"+o.d[Q](/[mlcxtrv]/g,function(e){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[e]||"M"})+"z"};if(o.k)for(var u in o.k)o[s](u)&&(t.glyphs[i].k[u]=o.k[u])}}return e},l.getFont=function(t,n,r,i){i=i||"normal",r=r||"normal",n=+n||{normal:400,bold:700,lighter:300,bolder:800}[n]||400;if(!e.
fonts)return;var o=e.fonts[t];if(!o){var u=new RegExp("(^|\\s)"+t[Q](/[^\w\d\s+!~.:_-]/g,v)+"(\\s|$)","i");for(var a in e.fonts)if(e.fonts[s](a)&&u.test(a)){o=e.fonts[a];break}}var f;if(o)for(var l=0,c=o[S];l<c;l++){f=o[l];if(f.face["font-weight"]==n&&(f.face["font-style"]==r||!f.face["font-style"])&&f.face["font-stretch"]==i)break}return f},l.print=function(n,r,i,s,o,u,a){u=u||"middle",a=N(C(a||0,1),-1);var f=this.set(),l=g(i)[y](v),c=0,h=v,p;e.is(s,i)&&(s=this.getFont(s));if(s){p=(o||16)/s.face["units-per-em"];var d=s.face.bbox.split(t),m=+d[0],b=+d[1]+(u=="baseline"?d[3]-d[1]+ +s.face.descent:(d[3]-d[1])/2);for(var w=0,E=l[S];w<E;w++){var x=w&&s.glyphs[l[w-1]]||{},T=s.glyphs[l[w]];c+=w?(x.w||s.w)+(x.k&&x.k[l[w]]||0)+s.w*a:0,T&&T.d&&f[j](this.path(T.d).attr({fill:"#000",stroke:"none",translation:[c,0]}))}f.scale(p,p,m,b).translate(n-m,r-b)}return f},e.format=function(t,n){var i=e.is(n,_)?[0][p](n):arguments;return t&&e.is(t,M)&&i[S]-1&&(t=t[Q](r,function(e,t){return i[++t]==null?v:i[t]})),t||v},e.ninja=function(){return a.was?u.Raphael=a.is:delete Raphael,e},e.el=qt,e.st=On[i],a.was?u.Raphael=e:Raphael=e}(),SC.DateFormatter=function(e,t){if(!e)throw"No date passed to date formatter.";if(!e.getFullYear)throw"Object passed to date formatter was not a date!";if(!t)throw"No formatting string passed to date formatter. Date: "+e;var n=t.length,r=t[0],i;for(i=1;i<n;i++)if(t[i]!==r)throw"Invalid format string for a date; all characters must be the same: "+t+"; date: "+e;var s=SC.DateFormatter[r];if(!s)throw"No formatter `"+r+"` exists for date: "+e;return s(e,n)},SC.DateFormatter.
G=function(e,t){var n="SC.Date.Era.";n+=e.getFullYear()>=0?"AD":"BC";if(t<=3)return(n+".Abbreviated").loc();if(t===4)return(n+".Full").loc();if(t===5)return(n+".Letter").loc();throw"Invalid era format: expected at most 5 digits; found "+t+"."},SC.DateFormatter.y=function(e,t){var n=e.getFullYear();t===1&&(t=n.length);var r=Math.abs(n).toString();while(r.length<t)r="0"+r;return r=r.substr(r.length-t),r},SC.DateFormatter.Y=function(e,t){return SC.DateFormatter.y(e,t)},SC.DateFormatter.u=function(e,t){var n=e.getFullYear();t===1&&(t=n.length);var r=n<0,i=Math.abs(n).toString();while(i.length<t)i="0"+i;return i=i.substr(i.length-t),(r?"-":"")+i},SC.DateFormatter.Q=function(e,t,n){var r=e.getMonth(),i=Math.floor(r/3)+1,s="SC.Date.Quarter."+(n?"StandAlone.":"")+"Q"+i;if(t===1)return""+i;if(t===2)return"0"+i;if(t===3)return(s+".Abbreviated").loc();if(t==4)return(s+".Full").loc();throw"Unrecognized number of characters for quarter: "+t},SC.DateFormatter.q=function(e,t){return SC.DateFormatter.Q(e,t,YES)},SC.DateFormatter.ENGLISH_MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],SC.DateFormatter.M=function(e,t,n){var r=e.getMonth(),i=""+(r+1),s="SC.Date.Month."+(n?n:"")+SC.DateFormatter.ENGLISH_MONTH_NAMES[r];if(t===1)return i;if(t===2)return i.length<2&&(i="0"+i),i;if(t===3)return(s+".Abbreviated").loc();if(t===4)return(s+".Full").loc();if(t===5)return(s+".Letter").loc();throw"The number of Ms or Ls must be from 1 to 5. Supplied: "+t},SC.DateFormatter.L=function(e,t){var n="StandAlone.";return SC.DateFormatter
.M(e,t,n)},SC.DateFormatter.P=function(e,t){var n="Prepositional.";return SC.DateFormatter.M(e,t,n)},SC.DateFormatter.l=function(){throw"`l` date formatter not implemented."},SC.DateFormatter.w=function(e,t){throw"Week number currently not supported for date formatting."},SC.DateFormatter.W=function(e,t){throw"Week number currently not supported for date formatting."},SC.DateFormatter.d=function(e,t){var n=""+e.getDate();return t>n.length&&(n="0"+n),n},SC.DateFormatter.D=function(e,t){var n=new Date(e.getFullYear(),0,1),r=n.getTime(),i=e.getTime()-r,s=Math.floor(i/864e5)+1;s=""+s;while(s.length<t)s="0"+s;return s},SC.DateFormatter.F=function(e,t){throw"Day of week in month (F) is not supported in date formatting"},SC.DateFormatter.g=function(e,t){throw"Julian day not supported in date formatting."},SC.DateFormatter.ENGLISH_DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],SC.DateFormatter.E=function(e,t){return t<3&&(t=3),SC.DateFormatter.e(e,t)},SC.DateFormatter.e=function(e,t,n){var r=e.getDay(),i=""+(r+1),s="SC.Date.Day."+(n?"StandAlone.":"")+SC.DateFormatter.ENGLISH_DAY_NAMES[r];if(t===1)return i;if(t===2)return i="0"+i,i;if(t===3)return(s+".Abbreviated").loc();if(t===4)return(s+".Full").loc();if(t===5)return(s+".Letter").loc();throw"Unrecognized number of `e`s, `c`s, or `E`s in date format string."},SC.DateFormatter.c=function(e,t){return SC.DateFormatter.e(e,t,YES)},SC.DateFormatter.a=function(e,t){if(t!==1)throw"`a` can only be included in a date format string once.";var n="SC.Date.Period."+(e.getHours()>11?"PM":"AM");return n.loc()},SC
.DateFormatter._h=function(e,t,n,r){var i=e.getHours();n||(i%=12),r&&(n?i===0&&(i=24):i===0&&(i=12));var s=""+i;return s.length<t&&(s="0"+s),s},SC.DateFormatter.h=function(e,t){return SC.DateFormatter._h(e,t,NO,1)},SC.DateFormatter.H=function(e,t){return SC.DateFormatter._h(e,t,YES,0)},SC.DateFormatter.K=function(e,t){return SC.DateFormatter._h(e,t,NO,0)},SC.DateFormatter.k=function(e,t){return SC.DateFormatter._h(e,t,YES,1)},SC.DateFormatter.m=function(e,t){var n=""+e.getMinutes();return n.length<t&&(n="0"+n),n},SC.DateFormatter.s=function(e,t){var n=""+e.getSeconds();return n.length<t&&(n="0"+n),n},SC.DateFormatter.S=function(e,t){var n=e.getMilliseconds()/1e3,r=Math.pow(10,t);n=Math.round(n*r),n=""+n;while(n.length<t)n="0"+n;return n},SC.DateFormatter.A=function(e,t){var n=(new Date(e.getFullYear(),e.getMonth(),e.getDay())).getTime(),r=e.getTime()-n;r=""+r;while(r.length<t)r="0"+r;return r},SC.DateFormatter.z=SC.DateFormatter.Z=SC.DateFormatter.v=SC.DateFormatter.V=function(e,t){throw"Timezone not supported in date format strings."},function(e,t){"use strict";typeof module=="object"&&module.exports?module.exports=t():typeof define=="function"&&define.amd?define(t):e.SecondLevelDomains=t(e)}(this,function(e){"use strict";var t=e&&e.SecondLevelDomains,n={list:{cn:" com "},has:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return!1;var r=e.lastIndexOf(".",t-1);if(r<=0||r>=t-1)return!1;var i=n.list[e.slice(t+1)];return i?i.indexOf(" "+e.slice(r+1,t)+" ")>=0:!1},is:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return!1;var r=e.lastIndexOf(".",t-1);if(
r>=0)return!1;var i=n.list[e.slice(t+1)];return i?i.indexOf(" "+e.slice(0,t)+" ")>=0:!1},get:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return null;var r=e.lastIndexOf(".",t-1);if(r<=0||r>=t-1)return null;var i=n.list[e.slice(t+1)];return i?i.indexOf(" "+e.slice(r+1,t)+" ")<0?null:e.slice(r+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return n}),function(e,t){"use strict";typeof module=="object"&&module.exports?module.exports=t(require("./punycode"),require("./IPv6"),require("./SupportedSecondLevelDomains")):typeof define=="function"&&define.amd?define(["./punycode","./IPv6","./SupportedSecondLevelDomains"],t):e.URI=t(e.punycode,e.IPv6,e.SecondLevelDomains,e)}(this,function(e,t,n,r){"use strict";function s(e,t){var n=arguments.length>=1,r=arguments.length>=2;if(this instanceof s){if(e===undefined){if(n)throw new TypeError("undefined is not a valid argument for URI");typeof location!="undefined"?e=location.href+"":e=""}if(e===null&&n)throw new TypeError("null is not a valid argument for URI");return this.href(e),t!==undefined?this.absoluteTo(t):this}return n?r?new s(e,t):new s(e):new s}function o(e){return/^[0-9]+$/.test(e)}function f(e){return e.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function l(e){return e===undefined?"Undefined":String(Object.prototype.toString.call(e)).slice(8,-1)}function c(e){return l(e)==="Array"}function h(e,t){var n={},r,i;if(l(t)==="RegExp")n=null;else if(c(t))for(r=0,i=t.length;r<i;r++)n[t[r]]=!0;else n[t]=!0;for(r=0,i=e.length;r<i;r++){var s=n&&n[e[r]]!==undefined||!n&&t.test
(t+=e.protocol+":"),!e.urn&&(t||e.hostname)&&(t+="//"),t+=s.buildAuthority(e)||"",typeof e.path=="string"&&(e.path.charAt(0)!=="/"&&typeof e.hostname=="string"&&(t+="/"),t+=e.path),typeof e.query=="string"&&e.query&&(t+="?"+e.query),typeof e.fragment=="string"&&e.fragment&&(t+="#"+e.fragment),t},s.buildHost=function(e){var t="";return e.hostname?(s.ip6_expression.test(e.hostname)?t+="["+e.hostname+"]":t+=e.hostname,e.port&&(t+=":"+e.port),t):""},s.buildAuthority=function(e){return s.buildUserinfo(e)+s.buildHost(e)},s.buildUserinfo=function(e){var t="";return e.username&&(t+=s.encode(e.username)),e.password&&(t+=":"+s.encode(e.password)),t&&(t+="@"),t},s.buildQuery=function(e,t,n){var r="",i,o,u,f;for(o in e)if(a.call(e,o)&&o)if(c(e[o])){i={};for(u=0,f=e[o].length;u<f;u++)e[o][u]!==undefined&&i[e[o][u]+""]===undefined&&(r+="&"+s.buildQueryParameter(o,e[o][u],n),t!==!0&&(i[e[o][u]+""]=!0))}else e[o]!==undefined&&(r+="&"+s.buildQueryParameter(o,e[o],n));return r.substring(1)},s.buildQueryParameter=function(e,t,n){return s.encodeQuery(e,n)+(t!==null?"="+s.encodeQuery(t,n):"")},s.addQuery=function(e,t,n){if(typeof t=="object")for(var r in t)a.call(t,r)&&s.addQuery(e,r,t[r]);else{if(typeof t!="string")throw new TypeError("URI.addQuery() accepts an object, string as the name parameter");if(e[t]===undefined){e[t]=n;return}typeof e[t]=="string"&&(e[t]=[e[t]]),c(n)||(n=[n]),e[t]=(e[t]||[]).concat(n)}},s.setQuery=function(e,t,n){if(typeof t=="object")for(var r in t)a.call(t,r)&&s.setQuery(e,r,t[r]);else{if(typeof t!="string")throw new TypeError("URI.setQuery() accepts an object, string as the name parameter"
);e[t]=n===undefined?null:n}},s.removeQuery=function(e,t,n){var r,i,o;if(c(t))for(r=0,i=t.length;r<i;r++)e[t[r]]=undefined;else if(l(t)==="RegExp")for(o in e)t.test(o)&&(e[o]=undefined);else if(typeof t=="object")for(o in t)a.call(t,o)&&s.removeQuery(e,o,t[o]);else{if(typeof t!="string")throw new TypeError("URI.removeQuery() accepts an object, string, RegExp as the first parameter");n!==undefined?l(n)==="RegExp"?!c(e[t])&&n.test(e[t])?e[t]=undefined:e[t]=h(e[t],n):e[t]!==String(n)||!!c(n)&&n.length!==1?c(e[t])&&(e[t]=h(e[t],n)):e[t]=undefined:e[t]=undefined}},s.hasQuery=function(e,t,n,r){switch(l(t)){case"String":break;case"RegExp":for(var i in e)if(a.call(e,i)&&t.test(i)&&(n===undefined||s.hasQuery(e,i,n)))return!0;return!1;case"Object":for(var o in t)if(a.call(t,o)&&!s.hasQuery(e,o,t[o]))return!1;return!0;default:throw new TypeError("URI.hasQuery() accepts a string, regular expression or object as the name parameter")}switch(l(n)){case"Undefined":return t in e;case"Boolean":var u=Boolean(c(e[t])?e[t].length:e[t]);return n===u;case"Function":return!!n(e[t],t,e);case"Array":if(!c(e[t]))return!1;var f=r?p:d;return f(e[t],n);case"RegExp":if(!c(e[t]))return Boolean(e[t]&&e[t].match(n));if(!r)return!1;return p(e[t],n);case"Number":n=String(n);case"String":if(!c(e[t]))return e[t]===n;if(!r)return!1;return p(e[t],n);default:throw new TypeError("URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter")}},s.joinPaths=function(){var e=[],t=[],n=0;for(var r=0;r<arguments.length;r++){var i=new s(arguments[r]);e.push(i);var o=i.segment();for(var u=0
;u<o.length;u++)typeof o[u]=="string"&&t.push(o[u]),o[u]&&n++}if(!t.length||!n)return new s("");var a=(new s("")).segment(t);return(e[0].path()===""||e[0].path().slice(0,1)==="/")&&a.path("/"+a.path()),a.normalize()},s.commonPath=function(e,t){var n=Math.min(e.length,t.length),r;for(r=0;r<n;r++)if(e.charAt(r)!==t.charAt(r)){r--;break}if(r<1)return e.charAt(0)===t.charAt(0)&&e.charAt(0)==="/"?"/":"";if(e.charAt(r)!=="/"||t.charAt(r)!=="/")r=e.substring(0,r).lastIndexOf("/");return e.substring(0,r+1)},s.withinString=function(e,t,n){n||(n={});var r=n.start||s.findUri.start,i=n.end||s.findUri.end,o=n.trim||s.findUri.trim,u=n.parens||s.findUri.parens,a=/[a-z0-9-]=["']?$/i;r.lastIndex=0;for(;;){var f=r.exec(e);if(!f)break;var l=f.index;if(n.ignoreHtml){var c=e.slice(Math.max(l-3,0),l);if(c&&a.test(c))continue}var h=l+e.slice(l).search(i),p=e.slice(l,h),d=-1;for(;;){var v=u.exec(p);if(!v)break;var m=v.index+v[0].length;d=Math.max(d,m)}d>-1?p=p.slice(0,d)+p.slice(d).replace(o,""):p=p.replace(o,"");if(p.length<=f[0].length)continue;if(n.ignore&&n.ignore.test(p))continue;h=l+p.length;var g=t(p,l,h,e);if(g===undefined){r.lastIndex=h;continue}g=String(g),e=e.slice(0,l)+g+e.slice(h),r.lastIndex=l+g.length}return r.lastIndex=0,e},s.ensureValidHostname=function(t,n){var r=!!t,i=!!n,o=!1;i&&(o=p(s.hostProtocols,n));if(o&&!r)throw new TypeError("Hostname cannot be empty, if protocol is "+n);if(t&&t.match(s.invalid_hostname_characters)){if(!e)throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');if(e.toASCII(t).match(s.invalid_hostname_characters
))throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_]')}},s.ensureValidPort=function(e){if(!e)return;var t=Number(e);if(o(t)&&t>0&&t<65536)return;throw new TypeError('Port "'+e+'" is not a valid port')},s.noConflict=function(e){if(e){var t={URI:this.noConflict()};return r.URITemplate&&typeof r.URITemplate.noConflict=="function"&&(t.URITemplate=r.URITemplate.noConflict()),r.IPv6&&typeof r.IPv6.noConflict=="function"&&(t.IPv6=r.IPv6.noConflict()),r.SecondLevelDomains&&typeof r.SecondLevelDomains.noConflict=="function"&&(t.SecondLevelDomains=r.SecondLevelDomains.noConflict()),t}return r.URI===this&&(r.URI=i),this},u.build=function(e){if(e===!0)this._deferred_build=!0;else if(e===undefined||this._deferred_build)this._string=s.build(this._parts),this._deferred_build=!1;return this},u.clone=function(){return new s(this)},u.valueOf=u.toString=function(){return this.build(!1)._string},u.protocol=S("protocol"),u.username=S("username"),u.password=S("password"),u.hostname=S("hostname"),u.port=S("port"),u.query=x("query","?"),u.fragment=x("fragment","#"),u.search=function(e,t){var n=this.query(e,t);return typeof n=="string"&&n.length?"?"+n:n},u.hash=function(e,t){var n=this.fragment(e,t);return typeof n=="string"&&n.length?"#"+n:n},u.pathname=function(e,t){if(e===undefined||e===!0){var n=this._parts.path||(this._parts.hostname?"/":"");return e?(this._parts.urn?s.decodeUrnPath:s.decodePath)(n):n}return this._parts.urn?this._parts.path=e?s.recodeUrnPath(e):"":this._parts.path=e?s.recodePath(e):"/",this.build(!t),this},u.path=u.pathname,u.href=function(e,t){var n
;if(e===undefined)return this.toString();this._string="",this._parts=s._parts();var r=e instanceof s,i=typeof e=="object"&&(e.hostname||e.path||e.pathname);if(e.nodeName){var o=s.getDomAttribute(e);e=e[o]||"",i=!1}!r&&i&&e.pathname!==undefined&&(e=e.toString());if(typeof e=="string"||e instanceof String)this._parts=s.parse(String(e),this._parts);else{if(!r&&!i)throw new TypeError("invalid input");var u=r?e._parts:e;for(n in u){if(n==="query")continue;a.call(this._parts,n)&&(this._parts[n]=u[n])}u.query&&this.query(u.query,!1)}return this.build(!t),this},u.is=function(e){var t=!1,r=!1,i=!1,o=!1,u=!1,a=!1,f=!1,l=!this._parts.urn;this._parts.hostname&&(l=!1,r=s.ip4_expression.test(this._parts.hostname),i=s.ip6_expression.test(this._parts.hostname),t=r||i,o=!t,u=o&&n&&n.has(this._parts.hostname),a=o&&s.idn_expression.test(this._parts.hostname),f=o&&s.punycode_expression.test(this._parts.hostname));switch(e.toLowerCase()){case"relative":return l;case"absolute":return!l;case"domain":case"name":return o;case"sld":return u;case"ip":return t;case"ip4":case"ipv4":case"inet4":return r;case"ip6":case"ipv6":case"inet6":return i;case"idn":return a;case"url":return!this._parts.urn;case"urn":return!!this._parts.urn;case"punycode":return f}return null};var T=u.protocol,N=u.port,C=u.hostname;u.protocol=function(e,t){if(e){e=e.replace(/:(\/\/)?$/,"");if(!e.match(s.protocol_expression))throw new TypeError('Protocol "'+e+"\" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]")}return T.call(this,e,t)},u.scheme=u.protocol,u.port=function(e,t){return this._parts.urn?e===undefined?""
:this:(e!==undefined&&(e===0&&(e=null),e&&(e+="",e.charAt(0)===":"&&(e=e.substring(1)),s.ensureValidPort(e))),N.call(this,e,t))},u.hostname=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e!==undefined){var n={preventInvalidHostname:this._parts.preventInvalidHostname},r=s.parseHost(e,n);if(r!=="/")throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');e=n.hostname,this._parts.preventInvalidHostname&&s.ensureValidHostname(e,this._parts.protocol)}return C.call(this,e,t)},u.origin=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e===undefined){var n=this.protocol(),r=this.authority();return r?(n?n+"://":"")+this.authority():""}var i=s(e);return this.protocol(i.protocol()).authority(i.authority()).build(!t),this},u.host=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e===undefined)return this._parts.hostname?s.buildHost(this._parts):"";var n=s.parseHost(e,this._parts);if(n!=="/")throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},u.authority=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e===undefined)return this._parts.hostname?s.buildAuthority(this._parts):"";var n=s.parseAuthority(e,this._parts);if(n!=="/")throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},u.userinfo=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e===undefined){var n=s.buildUserinfo(this._parts);return n?n.substring(0,n.length-1):n}return e[e.length-1]!=="@"&&(e+="@"),s.parseUserinfo
(e,this._parts),this.build(!t),this},u.resource=function(e,t){var n;return e===undefined?this.path()+this.search()+this.hash():(n=s.parse(e),this._parts.path=n.path,this._parts.query=n.query,this._parts.fragment=n.fragment,this.build(!t),this)},u.subdomain=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e===undefined){if(!this._parts.hostname||this.is("IP"))return"";var n=this._parts.hostname.length-this.domain().length-1;return this._parts.hostname.substring(0,n)||""}var r=this._parts.hostname.length-this.domain().length,i=this._parts.hostname.substring(0,r),o=new RegExp("^"+f(i));e&&e.charAt(e.length-1)!=="."&&(e+=".");if(e.indexOf(":")!==-1)throw new TypeError("Domains cannot contain colons");return e&&s.ensureValidHostname(e,this._parts.protocol),this._parts.hostname=this._parts.hostname.replace(o,e),this.build(!t),this},u.domain=function(e,t){if(this._parts.urn)return e===undefined?"":this;typeof e=="boolean"&&(t=e,e=undefined);if(e===undefined){if(!this._parts.hostname||this.is("IP"))return"";var n=this._parts.hostname.match(/\./g);if(n&&n.length<2)return this._parts.hostname;var r=this._parts.hostname.length-this.tld(t).length-1;return r=this._parts.hostname.lastIndexOf(".",r-1)+1,this._parts.hostname.substring(r)||""}if(!e)throw new TypeError("cannot set domain empty");if(e.indexOf(":")!==-1)throw new TypeError("Domains cannot contain colons");s.ensureValidHostname(e,this._parts.protocol);if(!this._parts.hostname||this.is("IP"))this._parts.hostname=e;else{var i=new RegExp(f(this.domain())+"$");this._parts.hostname=this._parts.hostname.replace(i,e)}return this
.build(!t),this},u.tld=function(e,t){if(this._parts.urn)return e===undefined?"":this;typeof e=="boolean"&&(t=e,e=undefined);if(e===undefined){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.lastIndexOf("."),i=this._parts.hostname.substring(r+1);return t!==!0&&n&&n.list[i.toLowerCase()]?n.get(this._parts.hostname)||i:i}var s;if(!e)throw new TypeError("cannot set TLD empty");if(e.match(/[^a-zA-Z0-9-]/)){if(!n||!n.is(e))throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');s=new RegExp(f(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(s,e)}else{if(!this._parts.hostname||this.is("IP"))throw new ReferenceError("cannot set TLD on non-domain host");s=new RegExp(f(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(s,e)}return this.build(!t),this},u.directory=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(e===undefined||e===!0){if(!this._parts.path&&!this._parts.hostname)return"";if(this._parts.path==="/")return"/";var n=this._parts.path.length-this.filename().length-1,r=this._parts.path.substring(0,n)||(this._parts.hostname?"/":"");return e?s.decodePath(r):r}var i=this._parts.path.length-this.filename().length,o=this._parts.path.substring(0,i),u=new RegExp("^"+f(o));return this.is("relative")||(e||(e="/"),e.charAt(0)!=="/"&&(e="/"+e)),e&&e.charAt(e.length-1)!=="/"&&(e+="/"),e=s.recodePath(e),this._parts.path=this._parts.path.replace(u,e),this.build(!t),this},u.filename=function(e,t){if(this._parts.urn)return e===undefined?"":this;if(typeof e!="string"){if(!this._parts.path||this._parts
t._parts.path&&t._parts.path.charAt(0)!=="/"&&(n+="/"),n+=t.path(!0);if(t._parts.query){var r="";for(var i=0,o=t._parts.query.split("&"),u=o.length;i<u;i++){var a=(o[i]||"").split("=");r+="&"+s.decodeQuery(a[0],this._parts.escapeQuerySpace).replace(/&/g,"%26"),a[1]!==undefined&&(r+="="+s.decodeQuery(a[1],this._parts.escapeQuerySpace).replace(/&/g,"%26"))}n+="?"+r.substring(1)}return n+=s.decodeQuery(t.hash(),!0),n},u.absoluteTo=function(e){var t=this.clone(),n=["protocol","username","password","hostname","port"],r,i,o;if(this._parts.urn)throw new Error("URNs do not have any generally defined hierarchical components");e instanceof s||(e=new s(e));if(t._parts.protocol)return t;t._parts.protocol=e._parts.protocol;if(this._parts.hostname)return t;for(i=0;o=n[i];i++)t._parts[o]=e._parts[o];return t._parts.path?(t._parts.path.substring(-2)===".."&&(t._parts.path+="/"),t.path().charAt(0)!=="/"&&(r=e.directory(),r=r?r:e.path().indexOf("/")===0?"/":"",t._parts.path=(r?r+"/":"")+t._parts.path,t.normalizePath())):(t._parts.path=e._parts.path,t._parts.query||(t._parts.query=e._parts.query)),t.build(),t},u.relativeTo=function(e){var t=this.clone().normalize(),n,r,i,o,u;if(t._parts.urn)throw new Error("URNs do not have any generally defined hierarchical components");e=(new s(e)).normalize(),n=t._parts,r=e._parts,o=t.path(),u=e.path();if(o.charAt(0)!=="/")throw new Error("URI is already relative");if(u.charAt(0)!=="/")throw new Error("Cannot calculate a URI relative to another relative URI");n.protocol===r.protocol&&(n.protocol=null);if(n.username!==r.username||n.password!==r.password)return t
;r<i;r++)s=o[r],this.addQuery(s,n[s])}return this}}(window.URI),SC.stringsFor("English",{"Uploader.fileTooBigDescription":"The file was too big","Uploader.wrongFiletypeDescription":"The file type is not supported"}),CW=SC.Object.create({NAMESPACE:"CW",VERSION:"1.0.0"}),CW.mixin({upperCaseUUID:function(){return this.UUID().toString().toUpperCase()},UUID:function(){var e=new Array(36),t=0,n=["8","9","a","b"];if(window.crypto&&window.crypto.getRandomValues){var r=new Uint8Array(18);crypto.getRandomValues(r);for(t=0;t<18;t++)e[t*2+1]=(r[t]>>4).toString(16),e[t*2]=(r[t]&15).toString(16);e[19]=n[r[9]>>6]}else{while(t<36)e[t]=(Math.random()*16|0).toString(16),t++;e[19]=n[Math.random()*4|0]}return e[8]=e[13]=e[18]=e[23]="-",e[14]="4",e.join("")},invertArray:function(e){e||CW.fatalError("invertArray(): You must specify an array to invert");var t,n,r,i={};for(t=0,n=e.length;t<n;++t)r=e[t],i[r]=!0;return i},invertArrayWithOrder:function(e){e||CW.fatalError("invertArrayWithOrder(): You must specify an array to invert");var t,n,r,i={};for(t=0,n=e.length;t<n;++t)r=e[t],i[r]=t;return i},invertHash:function(e,t){e||CW.fatalError("invertHash(): You must specify an hash to invert");var n,r,i=[];if(t)for(n in e)r=e[n],r&&i.push(parseInt(n,10));else for(n in e)r=e[n],r&&i.push(n);return i},combineHashes:function(e,t){var n=SC.clone(e),r;for(r in t)n[r]=t[r];return n},hashDifferencesBreakdown:function(e,t,n){(!e||!t)&&CW.fatalError("hashDifferencesBreakdown() must be called with two hashes"),e===t&&CW.fatalError("hashDifferencesBreakdown() must be called with two different hashes");var r=[],i=
[],s=[],o=[],u,a,f,l;n&&(u=this.invertArray(n));var c=CW.getSimpleTypes(),h={},p,d,v,m;for(a in e){h[a]=!0;if(u&&u[a])continue;p=e[a],d=t[a],d===undefined?s.push(a):(v=p===d,v||(m=SC.typeOf(p),c[m]?v=!1:v=CW.valuesAreEqual(p,d,m)),v?r.push(a):i.push(a))}for(a in t)h[a]||o.push(a);return{equal:r,different:i,firstHashOnly:s,secondHashOnly:o}},valuesAreEqual:function(e,t,n,r){if(e===t)return!0;n||(n=SC.typeOf(e));var i=CW.getSimpleTypes();if(i[n])return!1;r||(r=SC.typeOf(t));if(n!==r)return!1;if(n===SC.T_DATE)return e.getTime()===t.getTime();if(n===SC.T_REGEXP)return e.toString()===t.toString();if(n===SC.T_HASH){var s=0,o,u,a,f;for(o in e){++s,u=e[o],a=t[o];if(u!==a){f=SC.typeOf(u);if(i[f])return!1;if(!CW.valuesAreEqual(u,a,f))return!1}}for(o in t)--s;return s===0}if(n===SC.T_ARRAY){var l=e.length,c=t.length;if(l!==c)return!1;for(var h=l-1;h>=0;--h){u=e[h],a=t[h];if(u!==a){f=SC.typeOf(u);if(i[f])return!1;if(!CW.valuesAreEqual(u,a,f))return!1}}return!0}CW.fatalError("Unsupported type for CW.valuesAreEqual: '%@'".fmt(n))},getSimpleTypes:function(){var e=CW._simpleTypes;return e||(e=CW._simpleTypes={},e[SC.T_STRING]=!0,e[SC.T_NUMBER]=!0,e[SC.T_BOOL]=!0,e[SC.T_UNDEFINED]=!0,e[SC.T_NULL]=!0),e},getUrlParameters:function(e){e||(e=location.search);var t=new URI.parse(e);return t.query?URI.parseQuery(t.query):{}},escapeRegexCharacters:function(e){return e.replace(/[-[\]{}()*+?.,\\^$|#]/g,"\\$&")},formatNumber:function(e,t,n){if(SC.none(e))return"";SC.none(t)&&(t=","),SC.none(n)&&(n="."),e=e.toString();var r=e.split("."),i=r[0],s=r[1],o=/(\d+?)(?=(?:\d{3})+$)/g,u="$1"+t;return i=i.replace
(o,u),s?i+n+s:i},preloadTargetImages:function(e){if(SC.APP_IMAGE_ASSETS)for(var t=0,n=SC.APP_IMAGE_ASSETS.length;t<n;t++)(!e||SC.APP_IMAGE_ASSETS[t].indexOf(e)!==-1)&&SC.imageQueue.loadImage(SC.APP_IMAGE_ASSETS[t])},guidForContents:function(e,t){var n=t|0,r="",i,s,o;if(CW.isArrayLike(e)){i=e.length;for(s=0;s<i;s++)s&&(r+=","),r+=CW.componentForValue(e[s],n);return"["+r+"]"}if(SC.kindOf(e,SC.Array)){i=e.get("length");for(s=0;s<i;s++)s&&(r+=","),r+=CW.componentForValue(e.objectAt(s),n);return"["+r+"]"}if(!CW.isPrimitive(e)){var u=[];for(o in e)e.hasOwnProperty(o)&&u.push(o);u.sort(),i=u.length;for(s=0;s<i;s++)o=u[s],s&&(r+=","),r+='"'+o+'":'+CW.componentForValue(e[o],n);return"{"+r+"}"}CW.fatalError("Object expected in call to `guidForContents`.",e)},componentForValue:function(e,t){return t>0&&!CW.isPrimitive(e)?CW.guidForContents(e,t-1):'"'+SC.guidFor(e)+'"'},isArrayLike:function(e){return Array.isArray(e)?!0:e&&""+e=="[object Arguments]"},isPrimitive:function(e){return e===null||typeof e!="object"&&typeof e!="function"},fontDetector:function(e,t){var n=t.delay||50,r=t.timeout||1e3,i=t.testString||"MMMMMMMIIIa%@!",s=t.testFontFamily||'"Comic Sans MS"',o=t.testFontSize||"300px",u=t.targetFontWeight||"500",a=t.fail,f=t.success,l=t.complete,c,h,p=document.createElement("canvas"),d=p.getContext("2d");d.font=u+" "+o+" "+s;var v=d.measureText(i).width;h=window.setInterval(function(){d.font=u+" "+o+' "'+e+'", '+s,d.measureText(i).width!==v&&v!==0&&(window.clearInterval(h),window.clearTimeout(c),f&&SC.run(f()),l&&SC.run(l(!0)))},n),c=window.setTimeout(function(){window.clearInterval(
h),a&&SC.run(a()),l&&SC.run(l(!1))},r)}}),SC.ready(function(){setTimeout(function(){CW.preloadTargetImages()},2e3)}),CW.mixin({fatalError:function(e,t){var n=this.recordStack(YES,YES),r;throw e instanceof Error?r=e:r=new Error(e),t&&SC.mixin(r,t),r.recordedStack=n,r},recordStack:function(e,t){if(t||!this.get("hasSymbolicated"))try{this.symbolicate()}catch(n){}var r=arguments.callee,i=r?r.caller:null,s=0,o=[],u={},a,f,l,c,h,p;i&&e&&(i=i.caller);while(i&&s<26){a=i.displayName,a||(a=i.name),a||(a=i.toString()),a.length>150&&(a=a.substring(0,150)),l={func:a},f=i.arguments;if(f){c=[];for(h=0;h<5;++h)p=f[h],p&&(p.toString?p=p.toString():p="(argument without .toString() method)"),c.push(p);l.args=c}o[s++]=l;if(u[a]){o[s++]="(Because "+a+" was called recursively, no more of the stack is available)";break}u[a]=!0,i=i.caller}return o},hasSymbolicated:NO,namespacesToSymbolicate:["SC"],symbolicate:function(){if(!SC.Object.toString()){SC.warn("Cannot yet properly symbolicate because SproutCore is not yet in a position to provide class names");return}this.hasSymbolicated||(this.hasSymbolicated=!0);if(!SC||!SC.typeOf)return;var e=SC.getCurrentTimeForPerformance();this._symbolicateClassAndSubclasses(SC.Object);var t=this.namespacesToSymbolicate,n=CW.invertArray(t),r,i,s,o,u,a,f,l,c,h;if(!t)return;for(r in window){if(n[r])continue;i=r.charAt(0);if(i.toUpperCase()===i)try{f=window[r],f&&f.isObject&&t.push(r)}catch(p){}}for(u=0,a=t.length;u<a;++u){s=t[u],o=window[s];for(r in o){if(!o.hasOwnProperty(r))continue;f=o[r];if(!f)continue;if(f instanceof Function)f.displayName||(l=s+"."+r,f.displayName=
l);else if(f instanceof Object&&!f.isClass)for(c in f){if(!f.hasOwnProperty(c))continue;try{h=f[c],h instanceof Function&&(h.displayName||(l=s+"."+r+"."+c,h.displayName=l))}catch(d){SC.warn("Can not symbolicate %@: %@",c,d)}}}}SC.info("Spent %@ ms symbolicating",SC.getCurrentTimeForPerformance()-e)},_symbolicateClassAndSubclasses:function(e){var t=e.toString(),n,r,i,s,o,u;if(!t)return;for(n in e){if(!e.hasOwnProperty(n))continue;r=e[n],r instanceof Function&&(r.displayName||(i=t+"."+n,r.displayName=i))}s=e.prototype;for(n in s){if(!s.hasOwnProperty(n))continue;r=s[n],r instanceof Function&&(r.displayName||(i=t+"#"+n,r.displayName=i))}o=e.subclasses;for(n in o)u=o[n],u&&u.isClass&&this._symbolicateClassAndSubclasses(u)}}),CW.FakeReply=SC.Object.extend({isFakeReply:YES,shouldProcessRequestNormally:NO,applyToBackgroundRequests:NO,status:undefined,statusText:undefined,responseText:undefined,urlFilter:undefined,delay:undefined,headers:undefined,readyState:undefined,_lowercaseHeaders:null,getAllResponseHeaders:function(){var e=this.get("headers"),t="";for(var n in e){var r=e[n];t+=n+": "+r+"\n"}return t},getResponseHeader:function(e){if(!e)return;var t=this._lowercaseHeaders;if(!t){t=this._lowercaseHeaders={};var n=this.get("headers");for(var r in n){var i=n[r];t[r.toLowerCase()]=i}}return t[e.toLowerCase()]},abort:function(){},toString:function(){if(this.get("shouldProcessRequestNormally"))return"will be sent normally";var e=[],t=CW.FakeReply.allowableCreationParams,n,r,i,s;for(n=0,r=t.length;n<r;++n){i=t[n],s=this.get(i);if(s!==undefined){if(i==="applyToBackgroundRequests"&&!s)continue;
SC.typeOf(s)===SC.T_STRING?e.push("%@=“%@”".fmt(i,s)):e.push("%@=%@".fmt(i,s))}}return e.join(", ")}}),SC.mixin(CW.FakeReply,{allowableCreationParams:["applyToBackgroundRequests","status","statusText","responseText","responseHash","urlFilter","delay","headers"],_allowableCreationParamsHash:null,createFakeReply:function(e){var t=CW.FakeReply,n=t._allowableCreationParamsHash,r,i,s,o;if(!n){n=t._allowableCreationParamsHash={},i=t.allowableCreationParams;for(s=0,o=i.length;s<o;++s)r=i[s],n[r]=YES}if(e===null)return t.create({shouldProcessRequestNormally:YES});e||CW.fatalError("You must specify params for the fake reply");var u=NO;for(r in e)n[r]||(console.error&&console.error("Fake reply has an unrecognized parameter “%@”:".fmt(r),e),u=YES);u&&CW.fatalError("Unrecognized parameter in fake reply");var a=0,f=e.status;f===undefined?(console.error&&console.error("Fake reply does not include a status:",e),++a):f||(console.error&&console.error("Fake reply has an invalid status of 0:",e),++a);var l=e.responseText,c=e.responseHash;l===undefined&&!c?l=e.responseText="Fake reply with status "+f:l!==undefined&&c?(console.error&&console.error("Fake reply has both a responseText and a responseHash:",e),++a):l!==undefined&&SC.typeOf(l)!==SC.T_STRING?(console.error&&console.error("Fake reply has an invalid responseText (it should be a string):",e),++a):c&&SC.typeOf(c)!==SC.T_HASH&&(console.error&&console.error("Fake reply has an invalid responseHash (it should be a hash):",e),++a);var h=e.urlFilter;h&&!(h instanceof RegExp)&&(SC.typeOf(h)===SC.T_STRING?e.urlFilter=new RegExp(h):(console.error&&
console.error("Fake reply has an invalid urlFilter (it should be a string or a RegExp instance):",e),++a));if(c&&a===0){delete e.responseHash;try{e.responseText=SC.json.encode(c)}catch(p){console.error&&console.error("There was an error encoding JSON from the responseHash: "+p+", fake reply:",e),++a}}if(a===1)CW.fatalError("There was one error with the fake reply parameters");else{if(!(a>0))return t.create(e);CW.fatalError("There were %@ errors with the fake reply parameters".fmt(a))}}}),CW.mixin({requestLoggingLevel:null,fakeReplyQueue:null,addFakeReply:function(e,t){SC.typeOf(e)!==SC.T_ARRAY&&(e=SC.$A(e));var n=CW.FakeReply,r=[],i,s,o,u;for(i=0,s=e.length;i<s;++i){o=e[i],u=null;try{u=n.createFakeReply(o)}catch(a){}u&&r.push(u)}var f=e.length,l=r.length;if(f!==l){var c=f-l;c===1?CW.fatalError("Errors prevented your fake reply from being added. The fake reply queue was not changed."):CW.fatalError("Errors prevented %@ of your %@ fake replies from being added. The fake reply queue was not changed.".fmt(c,f))}var h=this.get("fakeReplyQueue");h||(h=[],this.set("fakeReplyQueue",h)),h.beginPropertyChanges();for(i=0,s=r.length;i<s;++i)u=r[i],h.pushObject(u);h.endPropertyChanges(),t||(console.log("The fake reply queue is now:"),this.listFakeReplyQueue())},listFakeReplyQueue:function(){var e=this.get("fakeReplyQueue");if(!e)console.log("(no fake reply queue)");else{var t=[],n,r,i;for(n=0,r=e.length;n<r;++n)i=e[n],t.push("[%@] %@".fmt(n,i));console.log(t.join("\n"))}},_recordingCount:0,_logRequestIfAppropriateFor:function(e){e||CW.fatalError("_logRequestIfAppropriateFor(): A response must be specified"
);var t=this.get("requestLoggingLevel"),n=++this._recordingCount,r,i,s,o,u,a,f;t&&(e._recordingID=n,e._sentAt=SC.getCurrentTimeForPerformance(),r=e.get("request"),i=r.get("type"),s=r.getFullAddress(),o=this._sortAndStringifyHeaders(r.get("headers")),u=r.get("cookies"),r.get("bodyShouldBeLogged")?(a=r.get("encodedBody"),a||(a="(empty)")):a="(omitted)",f="--> Request "+n+": "+i+" to "+s+", headers: "+o+(u?", cookies: "+u:"")+", body: "+a,SC.Logger._handleMessage(t,NO,f))},_logResponseIfAppropriate:function(e){e||CW.fatalError("_logResponseIfAppropriateFor(): A response must be specified");var t=this.get("requestLoggingLevel"),n=SC.getCurrentTimeForPerformance(),r,i,s,o,u,a,f,l,c;if(t){r=e._recordingID,i=e._sentAt,s=e._receivedAtWhileSuspended,o=e.get("timedOut"),o?u=" (timed out)":s?u=i?" ("+(s-i)+"ms, suspended for "+(n-s)+"ms)":" (unknown)":u=i?" ("+(n-i)+"ms)":" (unknown)",a=e.get("status");try{f=this._sortAndStringifyHeaders(e.get("headers"))}catch(h){}e.get("bodyShouldBeLogged")?(l=e.get("encodedBody"),l||(l="(empty)")):l="(omitted)",c="<-- Response "+r+": "+a+u+", headers: "+f+" body: "+l,SC.Logger._handleMessage(t,NO,c)}},_sortAndStringifyHeaders:function(e){var t,n,r,i,s,o=[];for(t in e)o.push(t);o.sort(),r="";for(i=0,s=o.length;i<s;++i)t=o[i],n=e[t],i!==0&&(r+=", "),r+=t+"="+n;return r}}),CW.ButtonKeyHandlingHelpers={isDefault:NO,isCancel:NO,keyHandlersDidChange:function(){var e=null,t=this.get("isDefault"),n=this.get("isCancel");t?this.registerKeyboardShortcut("return",this,this.triggerActionFromKeyboardShortcut):this.deregisterKeyboardShortcut("return"
),n?this.registerKeyboardShortcut("escape",this,this.triggerActionFromKeyboardShortcut):this.deregisterKeyboardShortcut("escape")}.observes("isDefault","isCancel"),initMixin:function(){this.get("isDefault")&&this.registerKeyboardShortcut("return",this,this.triggerActionFromKeyboardShortcut),this.get("isCancel")&&this.registerKeyboardShortcut("escape",this,this.triggerActionFromKeyboardShortcut)},triggerActionFromKeyboardShortcut:function(e){return this.triggerAction(),YES}},CW.ViewKeyHandlingHelpers={keyboardShortcuts:null,initMixin:function(){this._cwvkh_paneDidChange()},_cwvkh_paneDidChange:function(){var e,t,n,r,i,s=this,o;if(this.keyboardShortcuts&&this._cwvkh_lastPane!==this.get("pane")){n=this.get("pane"),e=this.get("keyboardShortcuts"),r=this._cwvkh_lastPane;if(r)for(t in e)r.deregisterKeyboardShortcut(t);if(n)for(t in e)i=e[t],typeof i=="string"||typeof i=="function"?o=i:(s=i.target,o=i.action),n.registerKeyboardShortcut(t,s,o);this._cwvkh_lastPane=n}}.observes("pane"),registerKeyboardShortcut:function(e,t,n){n||(n=t,t=this);var r=this.keyboardShortcuts,i=this.get("pane");r||(r=this.keyboardShortcuts={}),r[e]={target:t,action:n},i&&i.registerKeyboardShortcut(e,t,n)},deregisterKeyboardShortcut:function(e){var t=this.keyboardShortcuts,n=this.get("pane");t&&(delete this.keyboardShortcuts[e],n&&n.deregisterKeyboardShortcut(e))}},SHA1=SC.Object.create({hexcase:1,b64pad:"",hex_sha1:function(e){return this.rstr2hex(this.rstr_sha1(this.str2rstr_utf8(e)))},b64_sha1:function(e){return this.rstr2b64(this.rstr_sha1(this.str2rstr_utf8(e)))},sha1_vm_test:function(){return this.hex_sha1
d]:n[d]=this.bit_rol(n[d-3]^n[d-8]^n[d-14]^n[d-16],1);var v=this.safe_add(this.safe_add(this.bit_rol(r,5),this.sha1_ft(d,i,s,o)),this.safe_add(this.safe_add(u,n[d]),this.sha1_kt(d)));u=o,o=s,s=this.bit_rol(i,30),i=r,r=v}r=this.safe_add(r,f),i=this.safe_add(i,l),s=this.safe_add(s,c),o=this.safe_add(o,h),u=this.safe_add(u,p)}return Array(r,i,s,o,u)},sha1_ft:function(e,t,n,r){return e<20?t&n|~t&r:e<40?t^n^r:e<60?t&n|t&r|n&r:t^n^r},sha1_kt:function(e){return e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514},safe_add:function(e,t){var n=(e&65535)+(t&65535),r=(e>>16)+(t>>16)+(n>>16);return r<<16|n&65535},bit_rol:function(e,t){return e<<t|e>>>32-t}}),CW.SpritePreloadEnforcement={hasSpritePreloadEnforcement:YES,extraRequiredSrcs:null,extraRequiredImages:null,didFinishWaitingForImages:function(){},initMixin:function(){this.didCreateLayer&&(this._user_didCreateLayer=this.didCreateLayer),this.didCreateLayer=function(){if(this._user_didCreateLayer)var e=this._user_didCreateLayer.apply(this,arguments);return this._preload_didCreateLayer(),e}},_preload_didCreateLayer:function(){if(this.constructor.prototype.__hasPreloadedSprites__){var e=this.constructor.prototype.__preloadedExtraRequiredImages__;e&&(this.extraRequiredImages=e),SC.debug("Creating another instance of "+this.constructor+": all sprite backgrounds are confirmed to have been downloaded. Performing no preload action."),this.hasPaneAnimationSupport&&(SC.debug("Because this is the first append, and this pane has PaneAnimationSupport, we now trigger animateShow() to perform the animation."),this._hasShownFromDidCreateLayer=!0
,this.animateShow());return}this.hideForPreload(),this.preloadBackgroundSprites(this.getPreloadElementList(),this.showForPreload,this)},getPreloadElementList:function(){return SC.$A(this.$("*"))},hideForPreload:function(){this.set("isVisible",NO)},showForPreload:function(){this.set("isVisible",YES),this.hasPaneAnimationSupport&&(this._hasShownFromDidCreateLayer=!0,this.animateShow())},preloadBackgroundSprites:function(e,t,n){this.__elements__=e,this.__callback__=t,this.__target__=n,this.invokeLast("_preloadBackgroundSprites",e,t,n)},_preloadBackgroundSprites:function(e,t,n){e=this.__elements__,t=this.__callback__,n=this.__target__,this.__target__=this.__callback__=this.__elements__=undefined;var r=CW._backgroundImageLoadedness||(CW._backgroundImageLoadedness={}),i,s=0,o=!1,u=this,a=undefined,f=this.get("extraRequiredSrcs"),l=this.extraRequiredImages=f?{}:null,c=function(){s--,SC.debug("Finished loading "+this._src_+". images remaining before callback: "+s),r[this._src_]=!0,l&&this._extraKey_&&(l[this._extraKey_]=this),s===0&&(SC.debug("All images are downloaded. Now running callback."),h())},h=function(e){a&&clearTimeout(a);if(o){SC.debug("Performing the callback for all images having finished loading, but it has already been performed. Aborting.");return}e||(u.constructor.prototype.__hasPreloadedSprites__=!0,l&&(u.constructor.prototype.__preloadedExtraRequiredImages__=l)),u.didFinishWaitingForImages(),o=!0,SC.run(function(){t.apply(n||u)})};e=SC.$A(e);for(var p=0,d,v,m,g;d=e[p];p++){m=jQuery(d).css("background-image");if(!m)continue;if(m.indexOf("http")===-1)continue;if(m.indexOf
("url(")===-1)continue;m=m.substring(4,m.length-1);if((v=m.charAt(0))==='"'||v==="'")m=m.substring(1);if((v=m.charAt(m.length-1))==='"'||v==="'")m=m.substring(0,m.length-1);if(r[m])continue;if(i&&i[m])continue;(i||(i={}))[m]=!0,s++,g=new Image,g.onload=c,SC.debug("Preloading "+m),g.src=g._src_=m}if(f)for(p in f){if(!f.hasOwnProperty(p))continue;m=f[p],s++,g=new Image,g.onload=c,SC.debug("Preloading explicitly-specified image "+m),g.src=g._src_=m,g._extraKey_=p}if(s===0)SC.debug("Preloading background images, but every image was already loaded. Running callback immediately."),h();else{var y=SC.buildMode==="debug"?3e3:1500;a=setTimeout(function(){SC.debug("Attempted to preload background images, but the loading is taking longer than "+y/1e3+" seconds. Now running callback regardless of image loadedness."),h(!0)},y)}}},CW.TouchApproximation={isTouchApproximationEnabled:YES,distanceThreshold:50,touchStart:function(e){var t=this.convertFrameFromView({x:e.pageX,y:e.pageY}),n=t.x,r=t.y,i,s,o=this.get("touchApproximationViews")||this.get("childViews"),u=this.get("distanceThreshold"),a=null,f=Infinity,l,c,h,p,d;p=o.get("length");for(h=0;h<p;h++){l=o[h];if(!l||!l.get("isVisible")||l.get("isDecorative"))continue;c=l.get("frame"),i=-1,s=-1,n<c.x?i=c.x-n:n>c.x+c.width&&(i=n-(c.x+c.width)),r<c.y?s=c.y-r:r>c.y+c.height&&(s=r-(c.y+c.height)),i!==-1&&s!==-1?i=(i+s)/2:s!==-1&&(i=s),i!==-1&&i<f&&i<u&&(a=l,f=i)}if(a){e.isProxied=YES,e.target=a.get("layer"),d=a.tryToPerform("touchStart",e);if(d)return this._foundChild=a,YES;this._foundChild=null}return NO},touchesDragged:function(e,t){var n=this
.Date._pool.length>0?(n=CW.Date._pool.pop(),n.value=null,n.dateType=CW.DATE_ONLY):n=SC.beget(CW.Date),n._dateObj=e,n.dateType=t||CW.DATE_ONLY,n},createFromDateComponent:function(e){e||CW.fatalError("createFromDateComponent(): No date component was specified");var t=Math.floor(e/1e4),n=Math.floor(e/100)-t*100,r=e-t*1e4-n*100,i=[e,t,n,r],s=CW.Date.create(i,CW.DATE_ONLY);return s},areDatesInRange:function(e,t,n,r){return!e||!t?NO:t[0]===n[0]&&t[6]===1440?NO:e[0]>=n[0]&&e[0]<=r[0]||t[0]>=n[0]&&t[0]<=r[0]||e[0]<=n[0]&&t[0]>=r[0]},compareDates:function(e,t,n){if(!e||!t)return e||t;var r,i,s,o;return r=e._dateObj?e.components():e,i=t._dateObj?t.components():t,r[0]<i[0]?n?t:e:r[0]===i[0]?(s=r[4]*60+r[5],o=i[4]*60+i[5],s<o?n?t:e:s>o?n?e:t:null):n?e:t},greaterThan:function(e,t){SC.typeOf(e)===SC.T_ARRAY&&(e=CW.Date.create(e)),SC.typeOf(t)===SC.T_ARRAY&&(t=CW.Date.create(t));var n=this.compareDates(e,t,YES);return n===e?YES:NO}}),CW.DateParser={parseDate:function(e,t,n,r){var i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w=["Sunday".loc().toLowerCase(),"Monday".loc().toLowerCase(),"Tuesday".loc().toLowerCase(),"Wednesday".loc().toLowerCase(),"Thursday".loc().toLowerCase(),"Friday".loc().toLowerCase()],E=e.toLowerCase(),S,x,T,N,C,k=SC.Locale.currentLocale.language,L;if(!isNaN(e)&&parseInt(e,10)>31)i=CW.Date.create(t),b=e.length,b===2?(n?(s=parseInt(e.charAt(1),10)-1,o=parseInt(e.charAt(0),10)):(s=parseInt(e.charAt(0),10)-1,o=parseInt(e.charAt(1),10)),u=(new Date).getFullYear()):b===3?(v=e,a=parseInt(e.charAt(0),10),c=parseInt(e.substr(0,2),10),h=parseInt(e.substr(1,2),10),l=parseInt(e.charAt(2),10),
),CW.LOG_KEYBOARD_SHORTCUTS&&SC.Logger.log("Responder attempting to find keyboard shortcut for %s",e);var n=this.keyboardShortcuts[e];if(n){var r=n,i=this;return typeof n=="object"&&(i=n.target,r=n.action),typeof r!="string"?r.call(i,e,t):SC.RootResponder.responder.sendAction(r,i,this,e,t)}return NO}},SC.mixin(CW,{LOG_KEYBOARD_SHORTCUTS:NO,registerKeyboardShortcut:function(e,t,n){CW.globalKeyResponder.registerKeyboardShortcut(e,t,n)},deregisterKeyboardShortcut:function(e){CW.globalKeyResponder.deregisterKeyboardShortcut(e)},keyResponders:[],globalKeyResponder:SC.Object.create(CW.KeyResponder),addKeyResponder:function(e){this.keyResponders.push(e)},removeKeyResponder:function(e){this.keyResponders.removeObject(e)},performKeyEquivalent:function(e,t){CW.LOG_KEYBOARD_SHORTCUTS&&SC.Logger.log("Attempting to find keyboard shortcut for %s",e);var n=this.keyResponders,r,i=n.length;for(r=i-1;r>=0;r--)if(n[r].performKeyEquivalent(e,t))return YES;return NO},installKeyResponder:function(){var e=SC.RootResponder.prototype.attemptKeyEquivalent;SC.RootResponder.reopen({attemptKeyEquivalent:function(t){var n=e.apply(this,arguments);if(n)return n;var r=t.commandCodes()[0];return r?CW.performKeyEquivalent(r,t):NO}}),SC.View.reopen(CW.ViewKeyHandlingHelpers),SC.Pane.reopen(CW.KeyResponder),SC.ButtonView.reopen(CW.ButtonKeyHandlingHelpers)}}),CW.keyResponders.push(CW.globalKeyResponder),CW.LOG_NOTIFICATIONS=NO,CW.notificationCenter=SC.Object.create({_subscriptions:{},postNotification:function(e){var t=this._subscriptions;if(!t[e]){CW.LOG_NOTIFICATIONS&&SC.info("Notification Center: Could not find any subscribers for %@, returning."
.fmt(e));return}var n=t[e],r=n.length,i=SC.A(arguments).slice(1);i||(i=[]),CW.LOG_NOTIFICATIONS&&SC.info("Notification Center: Posting notification %@".fmt(e));for(var s=0;s<r;s++){var o=n[s];if(o){var u=o.action,a=o.target;u.apply(a,i)}}},_targetForTargetName:function(e){return SC.typeOf(e)===SC.T_STRING?SC.objectForPropertyPath(e):e},_methodForMethodNameInTarget:function(e,t){return SC.typeOf(e)===SC.T_STRING?SC.objectForPropertyPath(e,t):e},subscribeToNotification:function(e,t,n){t=this._targetForTargetName(t),n=this._methodForMethodNameInTarget(n,t);if(!n)throw"You must pass a action to subscribeToNotification()";var r=this._subscriptions,i=r[e];i||(i=r[e]=[]);var s=!1,o=i.length;for(var u=0;u<o;u++){var a=i[u];a.action===n&&a.target===t&&(s=!0)}s||(CW.LOG_NOTIFICATIONS&&SC.info("Notification Center: Subscribed to %@".fmt(e)),r[e].push({action:n,target:t}),this._subscriptions=r)},unsubscribeFromNotification:function(e,t,n){var r=this._subscriptions;t=this._targetForTargetName(t),n=this._methodForMethodNameInTarget(n,t);if(!n)throw"You must pass a action to subscribeToNotification()";var i=r[e];if(!i)return;var s=i.length,o=-1;for(var u=0;u<s;u++){var a=i[u];a.action===n&&a.target===t&&(o=u)}o!==-1&&(CW.LOG_NOTIFICATIONS&&SC.info("Notification Center: Subscribed to %@".fmt(e)),r[e].splice(o,1),this._subscriptions=r)}}),CW.Request=SC.Request.extend({COPY_KEYS:SC.Request.prototype.COPY_KEYS.concat(["overallTimeout","addressPrefix","useCrossDomain","withCredentials","id","isCancelled","destinationDomain","cycle","action","isBackgroundRequest","_crossDomainMethod","_queryParameters"
,"_isRead","isRead","isWrite","_isPending","_cycleWhenPended","_cycleWhenSent"]),responseClass:undefined,timeout:3e4,overallTimeout:null,addressPrefix:null,useCrossDomain:NO,withCredentials:NO,iFrameScriptLocation:"ajax_sender.html",id:null,isCancelled:NO,cycle:null,action:null,isBackgroundRequest:NO,isRead:function(e,t){if(t!==undefined)return this._isRead=t,t;var n=this._isRead;if(n!==undefined)return n;var r=this.get("type");if(!!r)return r.toLowerCase()==="get";CW.fatalError("No type was specified, so we don’t know whether this request is a read or a write.")}.property("type").cacheable(),isWrite:function(e,t){return t===undefined?!this.get("isRead"):(this.set("isRead",!t),t)}.property("isRead").cacheable(),bodyShouldBeLogged:NO,queryParameter:function(e,t){var n;if(SC.typeOf(e)===SC.T_STRING)return n=this._queryParameters,arguments.length===1?n?n[e]:null:(this.propertyWillChange("queryParameters"),n||(n=this._queryParameters={}),n[e]=t,this.propertyDidChange("queryParameters"),this);if(t===undefined){n=e,this.beginPropertyChanges();for(e in n){if(!n.hasOwnProperty(e))continue;this.queryParameter(e,n[e])}return this.endPropertyChanges(),this}return CW.fatalError("queryParameter(): You must pass in either a key or a hash of query parameters",{target:this}),this},clearQueryParameters:function(){this.propertyWillChange("queryParameters"),this._queryParameters={},this.propertyDidChange("queryParameters")},queryParameters:function(){return this._queryParameters}.property().cacheable(),addressWithQueryParameters:function(){var e=URI(this.get("address")).addQuery(this.get("queryParameters"
)).sortQuery().normalize().toString();return e}.property("address","queryParameters").cacheable(),send:function(e,t){this._determineResponseClassAndMethod();var n;this.get("isAsynchronous")===NO&&(n=this._crossDomainMethod,n&&n!=="cors"&&CW.fatalError("You cannot send a synchronous request using iframes with postMessage",{target:this}));var r=CW.RequestManagement,i=r?r.sharedInstance():null,s,o,u,a;this._isPending=NO,this._cycleWhenPended=null,this._cycleWhenSent=this.get("cycle"),o=this._getFakeReply();var f=this.get("timeout");if(f&&!this.get("isAsynchronous"))throw"Timeout values cannot be used with synchronous requests";if(f===0)throw"The timeout value must either not be specified or must be greater than 0";e&&this.set("body",e);var l=SC.clone(this._queryParameters);return a=this.copy()._prep(),a._queryParameters=l,o&&(a._fakeReplyToUse=o),s=SC.Request.manager.sendRequest(a),s&&i&&i.addOutstandingResponse(s),t&&i&&i.removePendingRequest(this),s},sendAfterDelay:function(e,t){t||CW.fatalError("sendAfterDelay(): You must specify a delay",{target:this});var n=CW.RequestManagement,r=n?n.sharedInstance():null;this._isPending=YES,this._cycleWhenPended=this.get("cycle"),r&&r.addPendingRequest(this),this.invokeLater(this.send,t,e,YES)},resend:function(e,t){var n=this._getFakeReply(),r,i,s,o;return i=this.get("source")?this:this.copy()._prep(),n&&(i._fakeReplyToUse=n),r=SC.Request.manager.sendRequest(i,e),r&&(s=CW.RequestManagement,o=s?s.sharedInstance():null,o&&o.addOutstandingResponse(r)),t&&o&&o.removePendingRequest(this),r},resendAfterDelay:function(e,t){t||CW.fatalError("resendAfterDelay(): You must specify a delay"
n;if(this.get("useCrossDomain")){t=this.get("responseClass"),t||(XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?t=CW.Response:this._isAppropriateForXDomainRequest()?t=CW.XDRResponse:window.postMessage?t=CW.IFramePostMessageResponse:SC.browser.msie&&SC.browser.version<=7&&(t=CW.IFrameDocumentDomainResponse));if(!this._crossDomainMethod){if(e(t,CW.IFramePostMessageResponse))n="postMessage";else if(e(t,CW.IFrameDocumentDomainResponse))n="documentDomain";else if(e(t,CW.Response)||e(t,CW.XDRResponse))n="cors";n&&(this._crossDomainMethod=n)}}else t=CW.Response;!this.get("responseClass")&&t&&this.set("responseClass",t)},_isAppropriateForXDomainRequest:function(){var e=this.get("headers"),t=YES,n;if(e)for(n in e)if(n.toLowerCase()!=="content-type"||e[n]!=="text/plain")t=NO;return t&&SC.browser.msie&&SC.browser.version<=9&&!this.get("withCredentials")?YES:NO},_getFakeReply:function(){var e=CW.get("fakeReplyQueue"),t=e?e.length:0,n=null,r,i,s,o,u,a;if(t>0){r=this.get("isBackgroundRequest"),i=null;for(s=0;s<t;++s){o=e[s];if(r&&!o.get("applyToBackgroundRequests"))continue;u=o.get("urlFilter");if(u){a=this.get("address");if(!a||!u.test(a))continue}e.removeAt(s,1),i=o;break}i&&(i.get("shouldProcessRequestNormally")||(n=i))}return n}}),CW.Request.mixin({suspendResponses:function(){++this._responseSuspendCount},resumeResponses:function(){var e=--this._responseSuspendCount,t,n,r,i,s,o;e<0&&(SC.warn("CW.Response.resumeResponses() was called without a paired suspendResponses() invocation; ignoring…"),this._responseSuspendCount=0);var u=function(){i.get("isCancelled")&&i._receivedWhenSuspended&&
(i.set("isCancelled",NO),s=i.get("request"),o=s.get("source"),o&&o.didReceive&&o.didReceive(s,i),i.get("isCancelled")||i.notify())};t=this._suspendedResponses,r=t?t.length:0;for(n=0;n<r;++n)i=t[n],SC.run(u)},_responseSuspendCount:0,_suspendedResponses:null}),SC.Request.manager.mixin({crossDomainIFrames:{},_requestId:0,_crossDomainXHRLoaderURL:"",shouldFireRequest:null,_createCrossDomainIFrame:function(e,t){e||CW.fatalError("_createCrossDomainIFrame(): A destination domain must be specified",{target:this}),t||CW.fatalError("_createCrossDomainIFrame(): An AJAX sender URL must be specified",{target:this,destinationDomain:e});var n=document.createElement("iframe"),r=this;t[0]!=="/"&&(t="/"+t),n.loaded=!1,n.onload=n.onreadystatechange=function(){!n.loaded&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")&&(n.loaded=!0,r.fireRequestIfNeeded())},e[e.length-1]==="/"&&(e=e.substr(0,e.length-1)),n.src=e+t,n.style.display="none",document.body.appendChild(n),n.className="crossdomain-iframe",SC.Event.add(window,"message",this,SC.RunLoop.wrapFunction(this._messageWasReceived),null,!0),this.get("crossDomainIFrames")[e]=n,this.notifyPropertyChange("crossDomainIFrames")},_messageWasReceived:function(e){var t=e.originalEvent,n=t.data,r;try{r=SC.json.decode(n)}catch(i){SC.warn("CW.Request cannot parse received message from iframe support: %@",n);return}if(!r.isIFramePostMessageResponse)return;var s=r.headers,o=this.get("inflight"),u,a,f;for(f=0,u=o.length;f<u;f++){a=o[f];if(a.requestId===r.requestId){if(!URI(t.origin).baseEquals(URI(a.get("destinationDomain")))){CW
.fatalError("Potential cross domain attack, postMessage from unknown origin, %@",t.origin);return}a.set("rawResponse",r),a.set("rawRequest",r),a.finishRequest();return}}},sendRequest:function(e,t){if(!e)return null;var n=this._requestId,r=e.get("responseClass").create({request:e,requestId:n}),i,s,o,u;if(r.get("isCrossDomain")){var a=e.get("destinationDomain"),f=e._crossDomainMethod;(f==="postMessage"||f==="documentDomain")&&!this.get("crossDomainIFrames")[a]&&this._createCrossDomainIFrame(a,e.get("iFrameScriptLocation")),r.set("destinationDomain",a)}return t&&r.set("retryOf",t),this._requestId=++n,r.set("addedToOutgoingQueueTimestamp",SC.getCurrentTimeForPerformance()),i=e._fakeReplyToUse,i&&(r.set("fakeReply",i),delete e._fakeReplyToUse),s=e.get("timeout"),o=e.get("overallTimeout"),o===null&&s&&(o=s,e.set("overallTimeout",s)),o&&(u=SC.Timer.schedule({target:r,action:"timeoutReached",interval:o,repeats:NO}),r.set("overallTimeoutTimer",u)),this.get("pending").pushObject(r),this.fireRequestIfNeeded(),r},fireRequestIfNeeded:function(){var e=this.get("pending"),t=this.get("inflight"),n=this.get("maxRequests"),r=e.length,i,s,o,u;if(r>0&&t.length<n){i=this.shouldFireRequest;if(i)for(u=0;u<r;++u){s=e.objectAt(u);if(i(s)){o=s,e.removeAt(u);break}}else o=e.shiftObject();if(!o)return;if(o.get("isCrossDomain")){var a=this.get("crossDomainIFrames")[o.get("destinationDomain")];if(!a||!a.loaded){SC.debug("CW.Request.manager: postponing the sending of %@ since the necessary iframe is not loaded…",o),e.unshift(o);return}}t.pushObject(o),this.set("inflight",t);var f=o.get("requestId");o.fire
.M=u,L.MM=LZ(u),L.MMM=MONTH_NAMES[u-1],L.NNN=MONTH_NAMES[u+11],L.d=a,L.dd=LZ(a),L.E=DAY_NAMES[f+7],L.EE=DAY_NAMES[f],L.H=l,L.HH=LZ(l),l===0?L.h=12:l>12?L.h=l-12:L.h=l,L.hh=LZ(L.h),l>11?L.K=l-12:L.K=l,L.k=l+1,L.KK=LZ(L.K),L.kk=LZ(L.k),l>11?L.a="PM":L.a="AM",L.m=c,L.mm=LZ(c),L.s=h,L.ss=LZ(h);while(r<e.length){i=e.charAt(r),s="";while(e.charAt(r)==i&&r<e.length)s+=e.charAt(r++);SC.none(L[s])?n+=s:n+=L[s]}return n},utcFormat:function(){var e=new Date(this.getTime()+this.getTimezoneOffset()*60*1e3);return e.format("E NNN dd HH:mm:ss UTC yyyy")}}),CW.UPLOADER_READY=0,CW.UPLOADER_INCOMPATIBLE_FILE_TYPE=1,CW.UPLOADER_FILE_TOO_BIG=2,CW.UPLOADER_MISSING_XHR=3,CW.Uploader=SC.Object.extend({isUploader:YES,uploadURL:null,maximumFileSize:2048e3,allowedFileTypes:"png jpeg bmp jpg gif".w(),shouldUploadFile:function(e){return YES},encloseFileWithinForm:NO,formFieldName:"X-data",withCredentials:NO,willUploadFile:function(e,t){var n=this;t.upload.onprogress=function(e){SC.run(function(){this.logIfRawRequestEvtNotNull(t,e,"rawRequest:upload:progess - ");if(!this.uploadProgressDidChange){SC.warn("No function called uploadProgressDidChange found in %@ object",this.toString());return}this.uploadProgressDidChange(t,e)},n)},t.onload=function(e){SC.run(function(){this.logIfRawRequestEvtNotNull(t,e,"rawRequest:onload - ");if(!this.didUploadFile){SC.warn("No function called didUploadFile found in %@ object",this.toString()),this.uploadDidFail&&this.uploadDidFail(t,e);return}this.didUploadFile(t,e)},n)},t.onerror=function(e){SC.run(function(){this.logIfRawRequestEvtNotNull(t,e,"rawRequest:onerror - ");if(!
this.uploadDidFail){SC.warn("No function called uploadDidFail found in %@ object",this.toString());return}this.uploadDidFail(t,e)},n)},t.onreadystatechange=function(e){t.readyState===4&&t.status!==200&&SC.run(function(){n.uploadDidFail(t,e)})}},logIfRawRequestEvtNotNull:function(e,t,n){var r=NO;n||(n=""),e||(n+="Raw Request was not found.",r=YES),t||(n+="Evt was not found.",r=YES),r&&SC.warn(n)},setRequestHeaders:function(e,t){t.setRequestHeader("X-File-Name",encodeURIComponent(e.fileName)),t.setRequestHeader("X-File-Size",e.fileSize);var n=this.get("_xhrHeaders");for(var r in n)n.hasOwnProperty(r)&&t.setRequestHeader(r,n[r])},uploadProgressDidChange:function(e,t){},didUploadFile:function(e,t){},uploadDidFail:function(e,t){},uploadFiles:function(e){var t=[];for(var n=e.length-1;n>=0;n--){var r=e[n],i=this._fileIsAcceptableToUpload(r);if(i!==CW.UPLOADER_READY)t.push(this._errorForFile(r,i));else if(this.shouldUploadFile(r))try{this._createAndSendUploadRequest(r)}catch(s){console.warn(s.toString())}}return t},_xhrHeaders:function(){var e={"If-Modified-Since":"Mon, 26 Jul 1997 05:00:00 GMT","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"};return this.get("encloseFileWithinForm")||(e["Content-Type"]="text/plain"),e}.property("encloseFileWithinForm").cacheable(),_fileTooBigDescription:"Uploader.fileTooBigDescription".loc(),_wrongFileTypeDescription:"Uploader.wrongFiletypeDescription".loc(),_createAndSendUploadRequest:function(e){var t=this.get("uploadURL");if(!t)throw"%@: Can't upload file if uploadURL is not set.".fmt(this);var n=this.get("encloseFileWithinForm"),
.freevars[t]=e=this[e]),e=this.makeFreevarFromHash(e),e!==this&&(this.freevars[t]=e,e.key&&(this[e.key]=e))},makeFreevarFromHash:function(e){if(e._isFreevar)return e;var t=CW.Animation.defaultFreevar,n,r,i,s,o,u,a,f=e===this?this:{};for(i in e){if(!e.hasOwnProperty(i))continue;(s=e[i])&&s.isInitRandom===!0?(a=s.round,s=Math.random()*(s.hi-s.lo)+s.lo,a&&(s=Math.round(s/a)*a),f[i]=s):f!==e&&(f[i]=e[i])}if(f===this)for(i in t)f[i]===undefined&&(f[i]=t[i]);else for(i in t)f.hasOwnProperty(i)||(f[i]=t[i]);if(f.signal)f.tween=undefined,n=this._returnExtendedFreevar(f,CW.Animation._signalFreevar),n._unsignaledCurrent=n.from;else if(f.inertia){f.tween=undefined,n=this._returnExtendedFreevar(f,CW.Animation._inertiaFreevar),n._undampedCurrent=n.from,n.inertia!==!0||(n.inertia=CW.Animation._inertiaFreevar.prototype.inertia),r=[];for(i=0;i<f.inertia-1;i++)r[i]=n._undampedCurrent;n.inertiaChain=r}else n=this._returnExtendedFreevar(f,CW.Animation._tweenFreevar),n._untweenedCurrent=f.from,typeof n.speed=="number"&&(n.duration=undefined);return n._isFreevar=!0,n.freevarRun(0),n},_returnExtendedFreevar:function(e,t){if(e===this){for(var n in t.prototype)this[n]===undefined&&(this[n]=t.prototype[n]);return this}return new t(e)},addFreevar:function(e){if(!e)return;return e.key&&this[e.key]?!1:(e=this.makeFreevarFromHash(e),e.key&&(this[e.key]=e),(this.freevars||(this.freevars=[])).push(e),this)},removeFreevar:function(e){typeof e=="string"&&(e=this[e]);if(!e||!e._isFreevar)return null;if(!this.freevars||!this.freevars.length)return null;e.key&&(this[e.key]=undefined);for(var t=0;t<this.freevars
{ENABLE_OLD_IE:YES,hasAnimatability:!0,mustKeepLayoutSync:YES,isAnimating:NO,isAnimatingInWindow:NO,isAnimatingWithParent:NO,recomputeIsAnimatingBooleans:function(){var e=this.get("isAnimatingInWindow"),t=!1,n=this,r=this._animCount>0,i;while(n=n.get("parentView"))if(n.hasAnimatability&&n.get("isAnimating")){t=!0;break}i=t||r,this.isAnimating!==r&&this.set("isAnimating",r),this.isAnimatingInWindow!==i&&this.set("isAnimatingInWindow",i),this.isAnimatingWithParent!==t&&this.set("isAnimatingWithParent",t),i!==e&&this._recomputeChildrenIsAnimatingBooleans()},_recomputeChildrenIsAnimatingBooleans:function(){for(var e=0,t=this.get("childViews"),n;n=t[e];e++)n.hasAnimatability?n.recomputeIsAnimatingBooleans():CW.Animatability._recomputeChildrenIsAnimatingBooleans.apply(n)},incrementAnimationCount:function(){this._animCount=(this._animCount||0)+1,this.recomputeIsAnimatingBooleans()},decrementAnimationCount:function(){this._animCount=Math.max(this._animCount-1,0),this.recomputeIsAnimatingBooleans()},animateProperty:function(e,t,n){return this.animateProperties.apply(this,arguments)},animateProperties:function(e,t){var n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N,C,k,L=SC.A(arguments),A=this._currentlyAnimatingProperties,O=this.get("mustKeepLayoutSync");if(o=typeof e=="string")(s={})[e]=t,e=s,t=L[2];if(!e){SC.warn("When using .animateProperties(, either a property name (string)or a hash, keyed by property name, full of destinations (or full freevar optionshashes) must be supplied as the first argument. Aborting the call.");return}e=SC.clone(e);if(t)for((n=o?2:1)&&(i=L.length)&&!(t=
undefined);n<i;n++){if(typeof (N=L[n])!="object")continue;for(r in N)(t||(t={}))[r]=N[r]}t||(t=this.___emptyHash),typeof (u=t.duration)=="number"&&delete t.duration,(a=t.tween)&&delete t.tween,(f=t.speed)&&delete t.speed,(l=t.inertia)&&delete t.inertia,(c=t.headStart)&&delete t.headStart,(globalDiscreteness=t.discreteness)&&delete t.discreteness,m=!0;for(n in t){if(!t.hasOwnProperty(n))continue;y=t[n],b=typeof y;if(b==="object"||b==="function")m=!1;(g||(g=[])).push(n)}t.canReuse=m=m||t.canReuse,g&&(t.extraKeys=g);for(n in e){if(SC.none(h=e[n]))continue;p=(d=A[n])?((S||(S={}))[n]=d).removeProperty(n,!0):undefined,typeof h=="number"&&(h=e[n]={to:h}),h.from===undefined&&(h.isLayoutProperty?(p?h.from=p.current:h.from=(this._previousLayout||this.get("layout"))[n],typeof h.from!="number"&&(h.from=this._DEFAULT_LAYOUT_FROMS[n]||0)):h.from=this.getPath(n)),typeof u=="number"&&h.duration===undefined&&h.inertia===undefined&&h.speed===undefined&&(h.duration=u),a&&h.tween===undefined&&h.inertia===undefined&&(h.tween=a),f&&h.speed===undefined&&h.duration===undefined&&h.tween===undefined&&(h.speed=f),l&&h.inertia===undefined&&h.tween===undefined&&(h.inertia=l),c&&h.headStart===undefined&&(h.headStart=c),globalDiscreteness&&h.discreteness===undefined&&(h.discreteness=globalDiscreteness),p&&p.inertia&&h.inertia===p.inertia&&(h.speed&&(p.speed=h.speed),h.headStart&&(p.headStart=h.headStart),p.from=h.from,p.to=h.to,h.discreteness!==undefined&&(p.discreteness=h.discreteness),e[n]=h=p),e[n].propertyName=n}E=0,T=0,C=!this.get("animateOldIE")&&SC.browser.msie&&SC.browser.msie<=8;for(n in e){if(!(
h=e[n]))continue;C&&(!h.duration||(h.duration=0),!h.speed||(h.speed=Infinity)),(h.duration||0)>E&&(E=h.duration),O||this.adjust(h.propertyName,h.to),h.to===h.from?(O&&this.adjust(h.propertyName,h.to),delete e[n]):T++}if(T===0)m||(k=CW.Animation.create({view:this,duration:E||u||0},t).start());else if(m&&(w=this._bestMatchAnimationForProperties(e)||this._animationFromPool())){for(n in e)w.addProperty(e[n]);for(n in t)w[n]=t[n];k=w.start()}else{v={freevars:[],properties:[]};for(n in e)v.freevars.push(n),v.properties.push(n);v.view=this,w=CW.MultiPropertyAnimation.create(v,e,t);for(n in e)A[n]=w;k=w.start()}if(S){for(n in S){if(!S.hasOwnProperty(n))continue;x=S[n];if(x.__checked__)continue;x.__checked__=!0,x.stopIfNoProperties()}for(n in S){if(!S.hasOwnProperty(n))continue;S[n].__checked__=!1}}return k},_bestMatchAnimationForProperties:function(e){var t,n,r,i,s,o,u=this._currentlyAnimatingProperties;for(t in u){if(!(i=u[t])||i.___matchCheck)continue;i.___matchCheck=!0,r=i.properties.length,s=0;for(n=0;n<r;n++)s+=e[i.properties[n]]?2:1;i.___matchCount=s}s=0;for(t in u){if(!(i=u[t])||!i.matchCheck)continue;i.___matchCheck=undefined,i.___matchCount>s&&(s=i.___matchCount,o=i),i.___matchCount=undefined}return o||this._animationFromPool()},_propertyAnimPool:null,_addAnimationToPool:function(e){if(!e)return;var t=this._propertyAnimPool;for(var n=0,r=t.length;n<r;n++)if(t[n]===e)return;t.push(e)},_animationFromPool:function(){var e=this._propertyAnimPool,t=e.length,n=e[t-1];return n&&(e.length=t-1),n},animate:function(e,t){var n,r,i,s,o,u,a,f=SC.A(arguments);if(u=typeof e=="string")(n={
})[e]=t,e=n,t=f[2];if(!e){SC.warn("When using .animate(, either a property name (string)or a hash, keyed by property name, full of destinations (or full freevar optionshashes) must be supplied as the first argument. Aborting the call.");return}e=SC.clone(e);if(t)for((i=u?2:1)&&(s=f.length)&&!(t=undefined);i<s;i++){if(typeof (a=f[i])!="object")continue;for(r in a)(t||(t={}))[r]=a[r]}typeof (n=e.duration)=="number"&&((t||(t={})).duration=n,delete e.duration);if(n=e.tween)(t||(t={})).tween=n,delete e.tween;if(n=e.speed)(t||(t={})).speed=n,delete e.speed;if(n=e.inertia)(t||(t={})).inertia=n,delete e.inertia;if(n=e.headStart)(t||(t={})).headStart=n,delete e.headStart;t||(t=this.___emptyHash);for(i in e)o=e[i],typeof o=="number"&&(o=e[i]={to:o}),o.isLayoutProperty=!0;return this.animateProperties(e,t)},adjust:function(e){return SC.View.prototype.adjust.apply(this,arguments)},stopAnimation:function(){this._forSaidPropertyAnimationsDo("removeProperty",arguments)},finishAnimation:function(){this._forSaidPropertyAnimationsDo("finishProperty",arguments)},updateToAnimation:function(){this._forSaidPropertyAnimationsDo("updateToProperty",arguments)},_forSaidPropertyAnimationsDo:function(e,t){var n=this._currentlyAnimatingProperties;if(!e||!n)return;var r=this.___keysForDoAll||(this.___keysForDoAll=[]),i=t[0],s,o,u,a;r.length=0,i||(i=n);if(i instanceof Array){o=i.length;for(s=0;s<o;s++)r[s]=i[s]}else if(typeof i=="object")for(s in i)i.hasOwnProperty(s)&&i[s]!==undefined&&r.push(s);else if(typeof i=="string"){o=t.length;for(s=0;s<o;s++)r[s]=t[s]}o=r.length;for(s=0;s<o;s++){a=n[u=r[s]];if(!a
)continue;a[e](u)}},_canAvoidAdjust:function(){return this.get("mustKeepLayoutSync")?!1:!0},_quickAdjust:function(e,t){if(!this._isQuickAdjusting)return this.adjust.apply(this,arguments)},_isQuickAdjusting:!1,_quickAdjustment:null,_beginQuickAdjustment:function(){this._isQuickAdjusting=!0;var e=this._quickAdjustment||(this._quickAdjustment={}),t=this._previousLayout||this.get("layout");for(var n in e)t.hasOwnProperty(n)||delete e[n];for(n in t)e[n]=t[n]},_commitQuickAdjustment:function(){this._isQuickAdjusting=!1},_renderQuickAdjustment:function(){},_currentlyAnimatingProperties:null,___emptyHash:{},initMixin:function(){this._currentlyAnimatingProperties={},this._propertyAnimPool=[],this.hasOwnProperty("animateOldIE")||this.set("animateOldIE",CW.Animatability.ENABLE_OLD_IE)},_DEFAULT_LAYOUT_FROMS:{opacity:1,scale:1},discreteForOutsideUnitInterval:{left:YES,top:YES,width:YES,height:YES,right:YES,bottom:YES,centerX:YES,centerY:YES}},CW.MultiPropertyAnimation=CW.Animation.extend({view:null,properties:null,ticked:SC.platform.touch?5:0,stopIfNoProperties:function(){this.properties.length===0&&this.stop()},finishProperty:function(e,t){var n=this.freevarForProperty(e);if(!n)return;n.force(),t||this.update(),this.removeProperty(e)},removeProperty:function(e,t){for(var n=0,r;r=this.properties[n];n++)r===e&&(this.properties.splice(n,1),n--);this.view._currentlyAnimatingProperties[e]=undefined,t||this.stopIfNoProperties();var i=this.removeFreevar(this.freevarForProperty(e));return i},addProperty:function(e){var t;if(!e||!(t=e.propertyName))return;e.key=e.propertyName;for(var n=0,r;r=this
.properties[n];n++)r===t&&(this.removeProperty(t,!0),n--);this.properties.push(t),this.view._currentlyAnimatingProperties[t]=this,this.addFreevar(e)},updateToProperty:function(e){var t=CW.Animatability.discreteForOutsideUnitInterval,n=e,r=this.view;r._updatingAnimatedProperty=!0,typeof n=="string"&&(n=this.freevarForProperty(n)),e=n.propertyName,n.isLayoutProperty?(n.discreteness||(n.discreteness=t[e]&&(n.to>1||n.from>1||n.to<0||n.from<0)?1:1e-6),r.get("mustKeepLayoutSync")?r.adjust(e,n.current):r.$().css(e,n.current)):this.view[e]!==n.current&&r.set(e,n.current),r._updatingAnimatedProperty=!1},freevarForProperty:function(e){return this[e]},update:function(){for(var e=0,t,n;t=this.freevars[e];e++)this.updateToProperty(t)},releaseProperties:function(){for(var e=0,t;t=this.properties[e];e++)this.view._currentlyAnimatingProperties[t]=undefined}.listens("stop"),poolAnimation:function(){if(!this.canReuse)return;while(this.properties.length)this.removeProperty(this.properties[0],!0);this.properties.length=0;if(this.extraKeys){for(var e in this.extraKeys)delete this[e];delete this.extraKeys}this.recycle(),this.view._addAnimationToPool(this)}.listens("stop"),markView:function(){this.view.incrementAnimationCount()}.listens("start"),unmarkView:function(){this.view.decrementAnimationCount()}.listens("stop")}),CW.PaneAnimationSupport={hasPaneAnimationSupport:YES,hiddenState:{opacity:0},showingState:{opacity:1},duration:350,showDuration:null,hideDuration:null,tween:CW.Anim.tweens.WEBKIT_EASE,showTween:null,hideTween:null,firstShowDelay:0,hideDelay:0,append:function(e){(!this.hasSpritePreloadEnforcement||
(),showingState:function(){return{opacity:this.get("paneOpacity")||1}}.property("paneOpacity").cacheable(),paneDidHide:function(){return this.paneDidFadeOut()},paneDidFadeOut:function(){}}),SC.stringsFor("en-us",{monthHeading:"%@1 %@2",year:"%@",Month:"Month",January:"January",February:"February",March:"March",April:"April",May:"May",June:"June",July:"July",August:"August",September:"September",October:"October",November:"November",December:"December",Jan:"Jan",Feb:"Feb",Mar:"Mar",Apr:"Apr",Jun:"Jun",Jul:"Jul",Aug:"Aug",Sep:"Sep",Oct:"Oct",Nov:"Nov",Dec:"Dec",Sunday:"Sunday",Monday:"Monday",Tuesday:"Tuesday",Wednesday:"Wednesday",Thursday:"Thursday",Friday:"Friday",Saturday:"Saturday",Sun:"Sun",Mon:"Mon",Tue:"Tue",Wed:"Wed",Thu:"Thu",Fri:"Fri",Sat:"Sat",Yesterday:"Yesterday",Today:"Today",Tomorrow:"Tomorrow",Midnight:"Midnight",Now:"Now",Noon:"Noon",Next:"Next",Last:"Last",English:"English",French:"French",German:"German",Japanese:"Japanese","Button.OK":"OK","Button.Cancel":"Cancel","Button.Reload":"Reload","Button.Save":"Save","Button.Accept":"Accept","Button.Decline":"Decline","Button.Maybe":"Maybe","Button.TryAgain":"Try Again","Status.Loading":"Loading…","Status.Sharing":"Sharing…","Toolbar.Message.Actions":"Actions","Dialog.Error.Details":"Details","Color.Picker.Custom.Color":"Custom color…","CW.DropTarget.SafariWindowsNotSupported.Title":"Drag and drop not supported.","CW.DropTarget.SafariWindowsNotSupported.Description":"Drag and drop of files into this browser is not currently supported."}),CW.CANVAS_BUTTON_HEIGHT=26,CW.TOOLBAR_BUTTON_HEIGHT=26,CW.SQUARE_BUTTON_REGULAR_HEIGHT=27
),arguments.callee.base.apply(this,arguments)},modalPane:SC.ModalPane.extend(CW.Animatability,CW.PaneFadingSupport,{classNames:"cw-modal".w(),paneFadeInDuration:350,paneFadeOutDuration:function(){return this.get("paneFadeInDuration")}.property(),paneOpacity:1,init:function(){arguments.callee.base.apply(this,arguments);var e=SC.RootResponder.responder.mainPane;if(e){var t=e.layout.minWidth,n=e.layout.minHeight;t&&this.adjust("minWidth",t),n&&this.adjust("minHeight",n)}}}),contentView:SC.View.design({layout:{left:0,right:0,top:0,bottom:0},escapeHTMLBinding:"*parentView.escapeHTML",separatorView:SC.View.design({layout:{height:1,right:0,left:0,bottom:52},classNames:["separator"]}),createChildViews:function(){SC.Binding.flushPendingChanges();var e=this.get("escapeHTML"),t=this.get("pane"),n=t.get("message"),r=t.get("description"),i=t.get("caption"),s=t.get("image"),o=t.get("extraView"),u=t.get("rightButton"),a=t.get("middleButton"),f=t.get("leftButton"),l=t.get("isCompact"),c=this.childViews,h=CW.Alert,p="Trying to create a CW.Alert with a %@ button that is neither a string, nor a button view.",d,v,m,g,y,b,w;return s&&(SC.typeOf(s)===SC.T_STRING?this.iconView=h.IconView.extend({classNames:s.w()}):s.value?this.iconView=h.IconView.extend({classNames:s.value.w()}):CW.fatalError("Trying to create a CW.Alert with improper an invalid image hash."),c.push("iconView")),n||CW.fatalError("Trying to create a CW.Alert without a message."),this.messageView=h.MessageView.extend({value:n,escapeHTML:e}),c.push("messageView"),r&&(this.descriptionView=h.DescriptionView.extend({value:r,escapeHTML:e
}),c.push("descriptionView")),i&&(this.captionView=h.CaptionView.extend({value:i,escapeHTML:e}),c.push("captionView")),o&&(this.extraView=o,c.push("extraView")),f&&(SC.typeOf(f)===SC.T_STRING?d={title:f,action:"remove",target:t}:SC.typeOf(f)===SC.T_HASH?d=f:CW.fatalError(p.fmt("left")),this.leftButtonView=h.LeftButtonView.extend(d),c.push("separatorView"),c.push("leftButtonView")),a&&(SC.typeOf(a)===SC.T_STRING?(v=a,m="remove",g=t):SC.typeOf(a)===SC.T_HASH?(v=a.title?a.title:"Cancel",m=a.action?a.action:null,g=a.target?a.target:t):CW.fatalError(p.fmt("middle"))),u||CW.fatalError("Trying to create a CW.Alert without a right button."),SC.typeOf(u)===SC.T_STRING?(y=u,b="remove",w=t):SC.typeOf(u)===SC.T_HASH?(y=u.title?u.title:"OK",b=u.action?u.action:null,w=u.target?u.target:t):CW.fatalError(p.fmt("right")),this.mainButtonsView=h.MainButtonsView.extend({middleButtonIsVisible:a?YES:NO,middleButtonTitle:v,middleButtonAction:m,middleButtonTarget:g,rightButtonTitle:y,rightButtonAction:b,rightButtonTarget:w}),c.push("mainButtonsView"),arguments.callee.base.apply(this,arguments)},extraViewFrameDidChange:function(){if(this._resizingExtraView){this._resizingExtraView=NO;return}this.performLayout()},didCreateLayer:function(){var e=this.get("pane"),t=this.get("extraView");t&&t.isAutoResizingExtraView&&t.addObserver("frame",this,this.extraViewFrameDidChange);var n=this;requestAnimationFrame(function(){SC.run(function(){n.performLayout()})})},performLayout:function(){var e=this.get("pane"),t=this.messageView,n=this.descriptionView,r=e.get("descriptionViewMinHeight")||0,i=this.captionView,s=
e.get("captionViewMinHeight")||0,o=this.extraView,u=e.get("extraViewMinHeight")||0,a=this.iconView,f=e.get("image"),l=t.getPath("layout.top"),c=e.get("isCompact"),h=c?25:106,p=this.mainButtonsView,d=CW.Alert,v=d.MIN_ALERT_HEIGHT,m=e.getPath("layout.maxHeight"),g,y,b,w=0,E,S,x,T,N,C,k,L,A,O=SC.Locale.getPath("currentLocale.isRTL")?"right":"left";a&&a.set("isVisible",c?NO:YES),t&&t.adjust(O,h),n&&n.adjust(O,h),i&&i.adjust(O,h),o&&o.adjust(O,h),e.set("ariaLabelledBy",SC.guidFor(t)),e.set("ariaDescribedBy",SC.guidFor(n)),g=t.get("value"),y=t.get("layer"),S=t.get("frame").width+"px",y.style.maxWidth=S,b=SC.metricsForString(g,y,null,!this.get("escapeHTML")).height,t.adjust("height",b),l+=b,A=e.get("messageViewPaddingBottom"),A&&(l+=A),n?(k=e.get("descriptionViewPadding"),k&&(L=k.top)&&(l+=L),n.adjust("top",l),g=n.get("value"),y=n.get("layer"),y.style.maxWidth=S,b=SC.metricsForString(g,y,null,!this.get("escapeHTML")).height,b<r&&(b=r),n.adjust("height",b),l+=b,k&&(A=k.bottom)&&(l+=A)):l+=r,i?(k=i.get("padding"),k&&(L=k.top)&&(l+=L),i.adjust("top",l),g=i.get("value"),y=i.get("layer"),y.style.maxWidth=S,b=SC.metricsForString(g,y,null,!this.get("escapeHTML")).height,b<s&&(b=s),i.adjust("height",b),l+=b,k&&(A=k.bottom)&&(l+=A)):l+=s,o?(this._resizingExtraView=YES,k=e.get("extraViewPadding"),k&&(L=k.top)&&(l+=L),o.adjust("top",l),b=undefined,o.isAutoResizingExtraView&&(b=o.computeHeight()),SC.none(b)&&(b=o.get("frame").height),SC.none(b)&&CW.fatalError("Trying to create a CW.Alert with an extraView which does not have its height specified."),b<u&&(b=u),l+=b,k&&(A=k.bottom)&&(l+=A)):l+=u
),n=this.get("autoResizeText")||"",r=this.get("autoResizePadding")||0,i;return SC.none(e)||SC.empty(n)?0:(e.style.maxWidth=t+"px",i=SC.metricsForString(n,e,this.get("classNames"),!this.get("escapeHTML")),i.height+r)}},CW.Alert.show=function(e){if(SC.typeOf(e)===SC.T_HASH){var t=this.create(e);return t.append(),t}return CW.fatalError("Attempted to show a CW.Alert without options."),null},CW.ErrorPicker=SC.PickerPane.extend({layout:{left:0,top:0,height:20,right:0,minWidth:36},classNames:["error-picker"],errorText:"Please fill in required info",escapeHTML:YES,pointerOffset:[10,20,-17,19],preferType:SC.PICKER_POINTER,acceptsKeyPane:NO,acceptsFirstResponder:NO,isModal:NO,contentView:SC.LabelView.extend(SC.AutoResize,{displayProperties:["value"],layout:{bottom:0,top:0,minWidth:36,centerX:0},classNames:["error-picker-label"],valueBinding:"*parentView.errorText",escapeHTMLBinding:"*parentView.escapeHTML",textAlign:SC.ALIGN_CENTER,measuredSizeDidChange:function(e){e();var t=this.get("measuredSize"),n=this.get("calculatedWidth")||t.width,r=this.get("calculatedHeight")||t.height,i=this.get("parentView");i.adjust({width:n+20,height:r}).updateLayout(),i.positionPane()}.enhance()}),preferMatrix:[2,3,2,2,2],render:function(e,t){var n=this.get("pointerPos");if(e.needsContent)this.renderChildViews(e,t),e.push("<div class='top-left-edge'></div>","<div class='top-edge'></div>","<div class='top-right-edge'></div>"),n.indexOf(SC.POINTER_LAYOUT[2])!==-1?e.push('<div class="top-middle-edge" style="margin-top: '+this.get("pointerPosY")+'px"></div>'):n.indexOf(SC.POINTER_LAYOUT[3])!==-1&&e.push('<div class="bottom-middle-edge" style="margin-top: '+
.getPath("pane.rootResponder"),s&&s.sendAction(i,r,this,this.get("pane"),{region:n,coords:t})),this.setIfChanged("selectedRegion",n),YES):NO},touchEnd:function(e){return this.set("hoveredRegion",null),this.mouseUp(e)},mouseMoved:function(e){var t=this.convertFrameFromView({x:e.pageX,y:e.pageY});this.setIfChanged("hoveredRegion",this.regionForPoint(t))},touchesDragged:function(e){this.mouseMoved(e)},mouseExited:function(e){this.set("hoveredRegion",null)},regionForPoint:function(e){var t=this.get("regions"),n=0,r=t.get("length"),i,s=this.get("regionCoordinatesKey");this._coordinatesCache=this._coordinatesCache||[];for(;n<r;n++){i=t[n].get?t[n].get(s):t[n][s],SC.typeOf(i)===SC.T_STRING&&(this._coordinatesCache[n]?i=this._coordinatesCache[n]:i=this._coordinatesCache[n]=this._coordinateObjectForString(i));if(this._pointInPoly(e,i))return t[n]}return null},_pointInPoly:function(e,t){var n=t.length,r=e.x,i=e.y,s,o=n-1,u=NO;for(s=0;s<n;s++)(t[s][1]<i&&t[o][1]>=i||t[o][1]<i&&t[s][1]>=i)&&t[s][0]+(i-t[s][1])/(t[o][1]-t[s][1])*(t[o][0]-t[s][0])<r&&(u=!u),o=s;return u},_coordinateObjectForString:function(e){var t=e.split(","),n=0,r=t.length,i=[];if(r%2!==0){var s=SC.Error.desc("SC.ImageMapView: Unable to parse coordinates string because there were an odd number of values.");throw console.error(s.toString()),s}for(;n<r;n+=2)i.push([parseInt(t[n],10),parseInt(t[n+1],10)]);return i}}),CW.MiniFadingCaplessScrollerView=CW.FadingCaplessScrollerView.extend({minimumThumbLength:16,classNames:"sc-mini-fading-capless-scroller-view".w()}),CW.MiniFadingCaplessScrollerViewSupport=CW.FadingCaplessScrollerViewSupport
n)),this.renderSize(),this._startStopSpin(),SC.browser.isIE8OrLower&&s===3&&SC.warn("Warning: IE8 cannot use three-framed spinner images, because it cannot rotate. Please provide a 12-framed spinner for IE8."),s!==3&&s!==12&&SC.warn("Warning: CW.SpinnerView:"+SC.guidFor(this)+" has an invalid assetFrameCount of "+s+". It must resolve to either 3 or 12 instead. Unpredictable rendering may occur.")},_startStopSpin:function(){var e=this.get("layout"),t=this.get("isVisibleInWindow")&&this._imageLoaded&&(SC.none(e.opacity)||e.opacity>0);t?this._startSpin():this._stopSpin()}.observes("isVisibleInWindow","layout"),_renderSizeObserver:function(){this.renderSize()}.observes("size"),renderSize:function(e,t,n,r){e||(e=this.get("size")),t||(t=this.get("assetFrameCount")),n||(n=this.get("innerElement"));if(isNaN(e))return;r?r.style.width=r.style.height=e+"px":this.adjust({width:e,height:e}),n.style.width=e+"px",n.style.height=e*t+"px",r||this.renderPosition()},_startSpin:function(){if(this._interval)return;var e=this;this._interval=setInterval(function(){e._rotateStep()},1e3/this.get("frequency")/12)},_stopSpin:function(){if(!this._interval)return;clearInterval(this._interval),this._interval=null},_rotateStep:function(){this._pos=((this._pos||0)+1)%12,this.renderPosition()},renderPosition:function(e,t,n,r){e===undefined&&(e=this._pos||0),t||(t=this.get("size")||0),n||(n=this.get("assetFrameCount"));var i=(r||this.get("innerElement")).style,s=e%n,o,u,a,f,l;if(n===12){i.top=-t*s+"px";return}o=Math.floor(e/3),f=o%2!==0,l=Math.floor(o/2)===1?1:-1,u=f?t*-l*s+l*t:0,a=(f?0:t*l*s)-(o!==0?t:0)-(o===2?
)return n;var r=n.lastIndexOf("-");if(r<0)return;r>=2&&n.charAt(r-2)=="-"&&(r-=2),n=n.substring(0,r)}},r=function(e){return e.replace(/_/g,"-").toLowerCase()},i=r(t),s=CK.SUPPLEMENTARY_LOCALE_DATA.likelySubtags;for(var o in s){var u=r(o);if(i===u){i=r(s[o]);break}}var a=CK.SUPPLEMENTARY_LOCALE_DATA.metadata.alias.languageAlias;for(var f in a){var l=r(f);i.indexOf(l)===0&&(i=a[f]._replacement+i.substr(l.length))}var c=e.map(r),h=n(c,i);if(h===undefined)return;var p=e[c.indexOf(h)];return p},displayNameFor:function(e,t,n,r,i){var s;return e&&t?CW.stringIsCJK(e)&&CW.stringIsCJK(t)?s=t+e:s="Name.Display.FirstAndFamilyNames".loc({firstName:e,familyName:t}):e?s=e:t?s=t:r?s=r:i&&(s=i),s||(s=n||""),s},matchesFormatOfAppleId:function(e){return CK.matchesFormatOfEmailAddress(e)||CK.matchesFormatOfPhoneNumberAppleId(e)},matchesFormatOfEmailAddress:function(e){return/^([A-Z0-9\.\-\_\+])*([A-Z0-9\+\-\_])+\@[A-Z0-9]+([\-][A-Z0-9]+)*([\.][A-Z0-9\-]+){1,8}$/i.test(e)},matchesFormatOfPhoneNumberAppleId:function(e){return/^\+?[0-9]{5,}$/.test(e)},matchesFormatOfPhoneNumber:function(e){var t=this._phoneNumberRegex;if(!t){var n="0-9\\uff10-\\uff19\\u0660-\\u0669\\u06F0-\\u06F9\\u0966-\\u096F\\u09E6-\\u09FF\\u0E50-\\u0E59",r="\\(\\)\\s\\-\\+\\.\\,\\#";this._phoneNumberRegexAllDigits=new RegExp("^s*\\+?(["+n+"]+)s*$","gi"),t=this._phoneNumberRegex=new RegExp("^s*([+\\(])?((["+n+"]+)(["+r+"]{1,3}|x|ext))+(["+n+"]+)s*$","gi")}var i=this._phoneNumberRegexAllDigits;return t.lastIndex=0,i.lastIndex=0,t.test(e)||i.test(e)},normalizePhoneNumber:function(e){return e&&e.replace(/[^0-9]/g,"")},redirectTo:function(
e){window.location.href=e},readCookie:function(e,t){var n=document.cookie,r,i,s;if(n.length>0){t&&(s=n.match(new RegExp("("+e+")=")),s&&(e=s[1])),r=n.indexOf(e+"=");if(r!==-1)return r=r+e.length+1,i=n.indexOf(";",r),i===-1&&(i=n.length),window.unescape(n.substring(r,i))}return null},writeCookie:function(e,t,n,r,i,s){var o,u,a;if(!e)return undefined;if(t===undefined||t===null)t="",u="expires=Thu, 01-Jan-1970 00:00:01 GMT;";return i&&(a=i*1e3*60*60,u="expires="+(new Date((new Date).getTime()+a)).toGMTString()),s&&(u+=";Secure"),n||(n="/"),r||(r="."+window.location.hostname),o=document.cookie=e+"="+t+";path="+n+";domain="+r+";"+u,o||SC.info('Not able to set cookie "%@" with "%@"',e,t),o},formatNumberWithLocale:function(e){return CW.formatNumber(e,"Numbers.ThousandsSeparator".loc(),"Numbers.DecimalSeparator".loc())},getLegacyLprojNameForLocale:function(e){var t={"en-us":"English","ja-jp":"Japanese","fr-fr":"French","de-de":"German","es-es":"Spanish","zh-cn":"zh_CN","nl-nl":"Dutch","it-it":"Italian","ko-kr":"ko","zh-tw":"zh_TW","pt-pt":"pt_PT","pt-br":"pt","sv-se":"sv","pl-pl":"pl","cs-cz":"cs","da-dk":"da","hu-hu":"hu","no-no":"no","fi-fi":"fi","tr-tr":"tr","ru-ru":"ru","uk-ua":"uk"},n=t[e];return n||(n="English"),n+".lproj"},hasLocalizedStringForKey:function(e){return e&&e.loc()!==e?YES:NO},addRootDomainQueryParameterHackAsAppropriate:function(e){e||CW.fatalError("You must specify a URL");var t;window.CloudOS&&(CloudOS.isBeta&&(t="beta"),CloudOS.isCarry&&(t="carry"),CloudOS.isFuture&&(t="future"));var n;return CK.get("isBeta")&&(n="beta"),CK.get("isCarry")&&(n="carry"),CK.get("isFuture"
)&&(n="future"),e instanceof URI||(e=new URI(e)),t&&t!==n&&e.addQuery("rootDomain",t),e.href()},persistAfterLogoutSuffix:".persist",getValueFromSessionStorage:function(e){return this._getValueFromStorage("sessionStorage",e)},setValueInSessionStorage:function(e,t){return this._setValueInStorage("sessionStorage",e,t)},removeValueInSessionStorage:function(e){return this._removeValueInStorage("sessionStorage",e)},getKeysInSessionStorage:function(){return this._getKeysInStorage("sessionStorage")},clearSessionStorage:function(){return this._clearStorage("sessionStorage")},getValueFromLocalStorage:function(e,t){return this._getValueFromStorage("localStorage",e,t)},setValueInLocalStorage:function(e,t,n){return this._setValueInStorage("localStorage",e,t,n)},removeValueInLocalStorage:function(e,t){return t&&(e+=this.get("persistAfterLogoutSuffix")),this._removeValueInStorage("localStorage",e)},getKeysInLocalStorage:function(){return this._getKeysInStorage("localStorage")},clearLocalStorage:function(){return this._clearStorage("localStorage",YES)},_getStorageObject:function(e){try{return window[e]}catch(t){SC.warn("Could not get storage object for %@: %@",e,t)}},_getValueFromStorage:function(e,t,n){var r=null,i=this._getStorageObject(e),s,o;if(i&&i.getItem){o=CK.currentApplication,s=o?o.get("name"):"iCloud",s&&(t=s+"."+t),n&&(t+=this.get("persistAfterLogoutSuffix"));try{r=i.getItem(t)}catch(u){SC.warn('Could not get value for key "%@" in %@: %@',t,e,u)}}return r},_setValueInStorage:function(e,t,n,r){var i=NO,s=this._getStorageObject(e),o,u;if(s&&s.setItem){u=CK.currentApplication,o=u?u
.get("name"):"iCloud",o&&(t=o+"."+t),r&&(t+=this.get("persistAfterLogoutSuffix"));try{s.setItem(t,n),i=YES}catch(a){}}return i},_getKeysInStorage:function(e){var t=[],n=this._getStorageObject(e),r,i,s,o;if(n){r=CK.currentApplication,i=r?r.get("name"):"iCloud",i&&(i+="."),s=i?i.length:0;for(o in n)o.indexOf(i)===0&&t.push(o.substring(s))}return t},_removeValueInStorage:function(e,t){var n=NO,r=this._getStorageObject(e),i,s;if(r&&r.removeItem){s=CK.currentApplication,i=s?s.get("name"):"iCloud",i&&(t=i+"."+t);try{r.removeItem(t),n=YES}catch(o){}}return n},_clearStorage:function(e,t){var n=YES,r=this._getStorageObject(e),i,s,o,u,a,f,l;if(r&&t)try{i={},s=this.get("persistAfterLogoutSuffix"),o=s.length;for(u=0,a=r.length;u<a;++u){try{f=r.key(u),l=f.indexOf(s),l!==-1&&l===f.length-o&&(i[f]=r.getItem(f))}catch(c){}r.length!==a&&(i={},u=-1,a=r.length)}}catch(h){}if(r)if(!r.clear)n=NO;else try{r.clear()}catch(p){n=NO}if(t)try{for(f in i)r.setItem(f,i[f])}catch(d){}return n},isStringBase64Encoded:function(e){return e.match(new RegExp("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"))}}),CK.servicesController=SC.Object.create({getServiceInfoFor:function(e){e||SC.warn("getServiceInfoFor(): A service name must be specified");var t=this._servicesInfo;return t?t[e]:null},getServiceUrlFor:function(e,t){var n=this.getServiceInfoFor(e),r=null,i;return n?(r=n.get("url")||null,r||(i="getServiceUrlFor(): Could not find the URL for “%@”".fmt(e))):i="getServiceUrlFor(): Could not find service information for “%@”".fmt(e),i&&(t?CW.fatalError(i):SC.error(i)),r},getServiceStatusFor
:function(e,t){var n=this.getServiceInfoFor(e),r=null,i;return n?(r=n.get("status")||null,r||(i="getServiceStatusFor(): Could not find the status for “%@”".fmt(e))):i="getServiceStatusFor(): Could not find service information for “%@”".fmt(e),i&&(t?CW.fatalError(i):SC.error(i)),r},servicesInfoHasBeenReceived:function(){return this._servicesInfo!==null}.property("_servicesInfo"),_setupFromBag:function(e){e||CW.fatalError("_parseInformationFromBag(): The bag must be supplied");var t=e.webservices,n,r,i;if(t){n={};for(r in t)i=SC.clone(t[r],YES),i.name=r,n[r]=CK.ServiceInfo.create(i);this.set("_servicesInfo",n)}else SC.error("CK.servicesController: The bag does not contain any services information")},_servicesInfo:null}),CK.errorCatcher=SC.Object.create({enabledInDevMode:NO,bubbleErrorsToCloudOS:YES,callback:null,namespacesToSymbolicate:null,isReporting:NO,shouldReloadIfFatal:NO,init:function(){arguments.callee.base.apply(this,arguments),this.get("enabledInDevMode")||SC.buildMode==="production"?(this.set("enabled",YES),SC.ExceptionHandler=this):SC.ExceptionHandler=null},reportBadRequest:function(e){return e||(e={}),e.type="badRequest",this._handleError(e)},reportServerError:function(e,t){e||(e={}),e.type="server";if(SC.kindOf(t,SC.Response)){var n=["server error"],r=t.get("request");r._getServiceName&&n.push("service: "+r._getServiceName()),n.push("status: "+t.get("status")),e.error=n.join(", "),e.serverHostname=URI(t.getFullAddress()).hostname(),e.urlPath=t.getPath("request.reportPath")}return this._handleError(e)},report:function(e){return e||(e={}),e.type||(e.type="generic"
),this._handleError(e)},mostCommonErrorMessages:["null","undefined","Syntax","defined"],handleException:function(e){try{e.recordedStack=e.recordedStack||CW.recordStack(YES,YES)}catch(t){}var n=e.message,r=e.stack,i=e.recordedStack,s=this.get("mostCommonErrorMessages"),o=s.length,u,a="";if(r&&r.length>0){var f=r.toString().split("http")[0];a=f.replace(n,"").replace("\n","")}else i&&i.length>0&&(a=i[1].func);if(n)for(u=0;u<o;u++)if(n.indexOf(s[u])!==-1){n+=". The calling function is "+a;break}return e.message=n,this._handleError({exception:e,isFatal:YES,type:"exception"})},_handleError:function(e){if(!e)return SC.error("Warning: No parameters were specified in _handleError"),YES;if(this.get("isReporting"))return YES;SC.debug("CloudKit: ErrorCatcher dialog invoked.");var t=CK.currentApplication,n=e.applicationName,r,i,s=window.CloudOS&&CloudOS.getUser?CloudOS.getUser():null,o;n||(t?n=t.get("name"):n="cloudos"),e.applicationName||(e.applicationName=n);if(s&&(o=s._auth_bag)){var u=o.requestInfo,a,f;u&&(a=u.region,f=u.country,f&&(e.userRegion=a?a+", "+f:f))}if(!e.appStatechart){var l,c;n==="cloudos"?c=CloudOS.get("statechartPath"):t&&(c=t.get("statechartPath")),c&&(l=SC.getPath(c))&&l.toStringWithDetails&&(e.appStatechart=l.toStringWithDetails())}r=e.exception,r&&(i=this._hashForException(r),e=SC.mixin(i,e));var h=this.get("callback")||this.get("exceptionCallback");if(h)try{h.call(this,e)}catch(p){}if(e.isFatal&&t&&this.get("bubbleErrorsToCloudOS")===YES&&CloudOS&&!CloudOS.isSimulator&&!CloudOS.isCloudOSLite){var d=SC.Logger.stringifyRecordedLogMessages();return e.applicationBuildNumber=
;s++){o=e.objectAt(s);if(!o)continue;u=SC.typeOf(o),u===SC.T_STRING?o=SC.Object.create({title:o,value:o,isEnabled:YES}):u===SC.T_HASH?o=SC.Object.create(o):u===SC.T_ARRAY&&(o=this.convertArrayMenuItemToObject(o)),o.contentIndex=s,i.push(o)}return i}.property("items").cacheable(),_sc_menu_itemsDidChange:function(){var e=this.get("menuItemViews");this._menuView.replaceAllChildren(e),this._menuView.adjust("height",this.get("menuHeight"))}.observes("menuItemViews"),convertArrayMenuItemToObject:function(e){SC.Logger.warn("Support for Array-based menu items has been deprecated. Please update your menus to use a hash.");var t,n=CW._menu_fetchKeys,r=CW._menu_fetchItem,i,s=SC.Object.create(),o,u;return t=this.menuItemKeys.map(n,this),s[t[0]]=e[0],s[t[1]]=e[1],s[t[2]]=e[2],s[t[3]]=e[3],s[t[4]]=e[4],s[t[5]]=e[5],s[t[6]]=e[6],s[t[7]]=e[7],s[t[8]]=e[8],s[t[9]]=e[9],s[t[10]]=e[10],s[t[11]]=e[11],s[t[12]]=e[12],s},currentMenuItem:function(e,t){return t!==undefined?(this._currentMenuItem!==null&&this.set("previousMenuItem",this._currentMenuItem),this._currentMenuItem=t,this.setPath("rootMenu.targetMenuItem",t),t):this._currentMenuItem}.property().cacheable(),_sc_menu_currentMenuItemDidChange:function(){var e=this.get("currentMenuItem"),t=this.get("previousMenuItem");t&&(!t.get("hasSubMenu")||e!==null)&&(t.resignFirstResponder(),this.closeOpenMenusFor(t)),e&&e.get("isEnabled")&&e.scrollToVisible()}.observes("currentMenuItem"),closeOpenMenusFor:function(e){if(!e)return;var t=e.get("parentMenu");while(t&&e)t=e.get("subMenu"),t&&(t.remove(),e.resignFirstResponder(),e=t.get("previousMenuItem"))
}),button:SC.ImageButtonView.extend({layout:{top:7,height:30,right:5,width:30},image:"info_button",targetBinding:"*parentView.parentView.target",actionBinding:"*parentView.parentView.action"})}),didCreateLayer:function(){this.invokeLater(this.recomputeDesiredSize,0)},recomputeDesiredSize:function(){var e=this.$(".title")[0],t=this.$(".detail")[0];if(SC.none(e)||SC.none(t))return;var n=SC.metricsForString(this.get("titleValue"),e,null,NO),r=SC.metricsForString(this.get("detailValue"),t,null,NO),i=(n.width>r.width?n.width:r.width)+55;i=i%2?i-1:i,this.adjustDesiredSize({width:Math.max(this.get("minimumSize").width,i)})},showCalloutInContainer:function(e){this._hideOverflow(),this.appendTo(e)},valuesObserver:function(){this.recomputeDesiredSize()}.observes("detailValue","titleValue","layer"),modalPaneDidClick:function(){return NO}}),CW.ErrorCalloutPicker=CW.PickerPane.extend({themeName:"errorCallout",renderStyle:"errorCallout",minimumSize:{width:120,height:29},errorText:"Please fill in required info",layouts:["onTop","onBottom"],acceptsFirstResponder:NO,acceptsKeyPane:NO,isModal:NO,contentView:SC.LabelView.extend(SC.AutoResize,{classNames:["error-picker-label"],valueBinding:".parentView.errorText",measuredSizeDidChange:function(){var e=this.get("measuredSize");e&&e.width&&e.height&&this.parentView.set("desiredSize",{width:e.width,height:e.height})}.observes("measuredSize")})}),CW.SelectMenuLayout={Aligned:CW.PickerLayout.extend({renderDelegateName:"cwPickerBackgroundRenderDelegate",distanceFromEdge:SC.propertyFromRenderDelegate("distanceFromEdge",15),desiredPosition:{left:0,top:0
get("frame"),h=e.get("value");o&&a.css(s?"top":"left",null),s?(f.css("width",h+"%"),l.css("left",h+"%"),a.css("left",h+"%")):(f.css("height",h+"%"),l.css("top",h+"%"),a.css("top",100-h+"%"))}}}),CK.meCardController=SC.Object.create({NO_PHOTO_SRC:window.devicePixelRatio>1?"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/foundation/1812Project43/en-us/source/resources/images/no_photo@2x.png":"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/foundation/1812Project43/en-us/source/resources/images/no_photo.png",photoChanged:NO,meCardUrl:function(){var e=CK.servicesController.getServiceUrlFor("contacts")+"/co/mecard/";return e}.property(),meCard:null,meCardRequirementSatisfied:NO,imgLoadError:NO,shouldCreateMeCard:NO,getMeCard:function(e){if(!CK.servicesController.getServiceInfoFor("contacts")){SC.debug("meCardController: not requesting me-card since contacts is disabled."),this.set("meCardRequirementSatisfied",YES),e instanceof Function&&e(1);return}var t=this.get("meCardUrl"),n=CK.Request.getUrl(t,null),r=this;n.set("reportRequest",YES),n.notify(200,this,function(t){var n=t.get("body");return typeof n=="string"&&(n=JSON.parse(n)),!n||!n.contacts?(SC.debug("no me-card is set"),r.set("shouldCreateMeCard",YES),r.set("meCard",{})):(SC.debug("meCardController: me-card received"),r.set("meCard",n.contacts[0])),e instanceof Function&&e(0),r.set("meCardRequirementSatisfied",YES),YES}),n.notify(0,this,function(t){SC.debug("meCardController: problem receiving me-card");if(CloudOS.getEnvironment()==="DEMO"){SC.debug("meCardController: using appleseed me-card in DEMO");var n="/system/cloudos/1812Project43/cloudkit/foundation/1812Project43/en-us/source/resources/images/appleseed_small.jpg"
;r.set("meCard",{photo:{url:n,crop:{height:165,width:165,y:22,x:11}}})}else r.set("shouldCreateMeCard",YES);return e instanceof Function&&e(1),r.set("meCardRequirementSatisfied",YES),YES}),SC.debug("Sending me card GET request to %@",t),n.send()},storeMeCard:function(e,t){var n=this.get("meCard");if(!CK.servicesController.getServiceInfoFor("contacts")){SC.debug("meCardController: not storing me-card since contacts is disabled.");return}var r=this.get("shouldCreateMeCard"),i=r?"POST":"PUT",s=this.get("meCardUrl")+"?method="+i,o=CK.Request.postUrl(s,null),u=this,a,f;o.set("isJSON",YES),o.set("reportRequest",YES),a=n?n:{};if(e)for(f in e){if(!e.hasOwnProperty(f))continue;a[f]=e[f]}o.notify(200,this,function(e){var n=e.get("body");return n.contacts?(u.set("shouldCreateMeCard",NO),SC.debug("me-card received"),this.set("meCard",n.contacts[0])):SC.debug("no me-card is set"),t instanceof Function&&t(0),YES}),o.notify(0,this,function(e){return SC.debug("problem storing me-card"),t instanceof Function&&t(1),YES});if(r){a.contactId=CW.upperCaseUUID();var l=CloudOS.authController,c=l.get("user"),h=c.get("isPrimaryAppleIdTypeEmail"),p=c.get("isPrimaryAppleIdTypePhoneNumber"),d=c.get("displayablePrimaryAppleId"),v=[{field:d}];a.firstName=c.get("firstName"),a.lastName=c.get("lastName"),h?(v[0].label="home",a.emailAddresses=v):p&&(v[0].label="mobile",a.phones=v)}var m={contacts:[a]};SC.debug("Sending me card GET request to %@",s),o.send(m)},completePhotoPicker:function(e){var t={url:e.photoUrl,crop:e.photoCrop,signature:e.photoSignature};this.set("photo",t),this.set("photoChanged",YES)},meCardPosted
:function(){this.getMeCard()},photoUrl:function(e,t){if(t===undefined)return this.getPath("photo.url")||null;var n=this.get("photo");n.url=t}.property("photo"),photoCrop:function(e,t){if(t===undefined)return this.getPath("photo.crop")||null;var n=this.get("photo");n.crop=t}.property("photo"),photoSignature:function(e,t){if(t===undefined)return this.getPath("photo.signature");var n=this.get("photo");n.signature=t}.property("photo"),photo:function(e,t){if(t===undefined)return this.getPath("meCard.photo");var n=this.get("meCard");n&&(n.photo=t)}.property("meCard"),isPhotoUrlValid:function(){return!this.get("imgLoadError")&&!!this.get("photoUrl")}.property("photoUrl","imgLoadError"),deletePhoto:function(){this.set("photo",null),this.set("photoChanged",YES)},reset:function(){this.set("meCard",null),this.set("meCardRequirementSatisfied",NO)}}),CK.StatsController=SC.Object.extend({_statsQueue:[],statSessionId:null,STAT_COALESCING_WINDOW:8e3,includedParams:{},recordStat:function(e,t,n){var r,i,s=this.get("includedParams"),o=e+t,u=window.CloudOS&&!CloudOS.isCloudOSClient,a=u&&CloudOS.getClientId?CloudOS.getClientId():this.get("statSessionId");r={statName:o,statSessionId:a,hostname:window.location.hostname,buildNumber:SC.buildNumber,platform:window.CloudOSBootstrap&&CloudOSBootstrap.isOnSupportedMobile?"mobile":"desktop"};if(!n||!n.appName)r.appName=e;for(var f in s)r[f]=s[f];i=SC.merge(n,r);try{SC.json.encode(i)}catch(l){CW.fatalError("'%@' stat from '%@' cannot be encoded, possibly a circular reference.".fmt(t,e))}this._statsQueue.push(i),this.invokeOnceLater(this.sendStats,this.STAT_COALESCING_WINDOW
)},_benchmarkStats:{},getStat:function(e,t){return this._getBenchmark(e,t)},beginStat:function(e,t,n){if(this.getStat(e,t)){SC.warn("%@ stat already exists for %@",t,e);return}n=n||{},n._startTime=SC.getCurrentTimeForPerformance(),this._recordBenchmark(e,t,n)},endStat:function(e,t,n,r){var i=this.getStat(e,t),s,o,u;r&&(s=r.durationKeyName,o=r.includeLocationAndLocale,u=r.includeLocationUrlDetails);if(!i){SC.warn("%@ stat does not exist for %@",t,e);return}s=s?s:"duration",i[s]=SC.getCurrentTimeForPerformance()-i._startTime,delete i._startTime;var a=SC.merge(n,i);o&&(a=this.includeLocationAndBrowserLocale(a)),u&&(a=this.includeLocationUrlDetails(a)),this.recordStat(e,t,a),this._clearBenchmark(e,t)},cancelStat:function(e,t){var n=this._getBenchmark(e,t);n&&this._clearBenchmark(e,t)},_getBenchmark:function(e,t){var n=this._benchmarkStats;if(!n[e]||!n[e][t])return;return n[e][t]},_clearBenchmark:function(e,t){var n=this._benchmarkStats;delete n[e][t]},_recordBenchmark:function(e,t,n){var r=this._benchmarkStats;r[e]||(r[e]={}),r[e][t]=n},endAllBenchmarkStats:function(e){var t=this._benchmarkStats,n,r,i;for(n in t){if(e&&n!==e)continue;for(r in t[n])i=t[n][r],this.endStat(n,r,i)}},sendStats:function(e,t){var n=this._statsQueue;if(!n||n.length===0)return;var r=CW.Request.postUrl("/reportStats");r.set("addressPrefix","https://feedbackws.%{currentDomain}".fmt({currentDomain:COS.authController.get("currentDomain")})),r.set("useCrossDomain",YES),r.set("isJSON",YES),r.set("attachIdentifyingHeaders",NO),r.set("isAsynchronous",e===undefined?YES:e),r.set("timeout",null),r.header("Content-Type"
,"text/plain"),r.notify(200,this,function(e){return SC.info("Successfully sent stats to feedbackws"),t&&t.call(undefined,e),YES}),r.notify(0,this,function(e){return SC.warn("Error sending stats to feedbackws"),t&&t.call(undefined,e),YES}),SC.debug("Sending stats to feedbackws"),r.send({stats:n}),this._statsQueue=[]},flushStats:function(){this.endAllBenchmarkStats(),this.sendStats(NO)},recordLocationStat:function(e,t,n){n||(n={}),this.recordStat(e,t,this.includeLocationAndBrowserLocale(n))},includeLocationAndBrowserLocale:function(e){var t=window.COS;if(!t)return SC.warn("includeLocationAndBrowserLocale() is only available to icloud authenticated applications."),e;var n=t.authController.get("requestInfo");n&&(e.region=n.region,e.country=n.country),e.time=(new Date).toString()+" ("+Math.floor(new Date)+")";var r=(new Date).toString().match(/.*?\((.*?)\).*/);return r&&r.length===2&&(e.timezone=r[1]),e.browserLocale=(navigator.language||navigator.browserLanguage).toLowerCase(),e},recordLocationAndWindowUrlStat:function(e,t,n){n||(n={});var r=window.CloudOSBootstrap;if(!r){SC.warn("recordLocationAndWindowUrlStat() is only available to stats originating from CloudOS app.");return}this.recordStat(e,t,this.includeLocationUrlDetails(this.includeLocationAndBrowserLocale(n)))},recordWindowUrlStat:function(e,t,n){n||(n={});var r=window.CloudOSBootstrap;if(!r){SC.warn("recordWindowUrlStat() is only available to stats originating from CloudOS app.");return}this.recordStat(e,t,this.includeLocationAndBrowserLocale(n))},includeLocationUrlDetails:function(e){if(!e)return;return window.
:r?t.photo.crop:null,photoSignature:r?t.photo.signature:null};if(n)return i;e.receiveMeCard(i)},s,o;t?(s=r.get("meCard"),s?o=!1:o=!0):n?(s=e._cloudOSState.meCard,s||(s=r.get("meCard")),s?o=!1:o=!0):(s=e._cloudOSState.meCard,o=!1);if(!!s)return i(s,t);if(!o)return;r.getMeCard(function(){s=r.get("meCard");if(!!s)return i(s,t);SC.debug("requestMeCard: No meCard present")})},windowApplicationHasInitialized:function(e,t,n){CK.windowApplicationDidInitialize(e);if(!n){var r;if(CK.currentApplication){var i=this.get("appInstance"),s=CK.currentApplication;r=i._cloudOSState}else r=COS.cloudOSStateForApp(t);CK.passWindowApplicationMessage(e,"_applicationShouldInvokeMain",CloudOS._cloudOSAPIMethodNames,r)}CK.passPendingWindowApplicationMessages(e)},windowApplicationIsKnown:function(e){return CK.windowApplicationIsRegistered(e)},windowApplicationWillClose:function(e){var t=CK.getBackwardCompatibleInstanceId(e);CK.windowApplication[t]=null},exit:function(e,t){var n;if(CK.currentApplication)e=arguments[0],t=arguments[1],n=this.getPath("appInstance.name"),!t&&e!==CK.EXIT_NON_FATAL&&(t=SC.Logger.stringifyRecordedLogMessages());else{var r=arguments[0];e=arguments[2],t=arguments[3],n=r.get("name")}if(e===undefined||n===undefined){SC.warn("statusCode and appName must be provided for exit()");return}this.invokeLast(function(){CK.currentApplication?this.get("appInstance").invokeMethodOnCloudOS(n,"exit",[e,t]):this.appController.exitApplication(n,e,t)})},passMessageToOpenerApplication:function(e){var t=CloudOS.getOpenerWithCloudOS();if(t){var n=this.get("appInstance"),r=SC.$A(arguments);r.shift(),n
.invokeMethodOnCloudOS(n.get("name"),e,r,t)}},getOpenerWithCloudOS:function(){var e,t;CK.currentApplication?e=this.getPath("appInstance.cloudOSWindow"):e=window;try{e&&e.opener&&e.opener.CloudOS&&(t=e.opener,SC.info("Found an openers CloudOS instance"))}catch(n){SC.info("No opener found, or not allow to get reference to its CloudOS")}return t},hasOpenerWithCloudOS:function(){return!!CloudOS.getOpenerWithCloudOS()},setAppBanner:function(){var e=SC.$A(arguments);if(CK.currentApplication){var t=this.getPath("appInstance.name");if(e.length!==1){SC.warn("setAppBanner expects exactly 1 argument.");return}e.push(t),this.get("appInstance").invokeMethodOnCloudOS(this.getPath("appInstance.name"),"setAppBanner",e)}else{if(e.length<4){SC.warn("There are not enough arguments for function setAppBanner.");return}CloudOS.bannerManager.setAppBanner(e[2],e[3])}},currentAppName:function(){var e;return CK.currentApplication?e=this.getPath("appInstance.name"):e=CloudOS.appController.getPath("currentApp.name"),e},getQuotaData:function(){var e=this.get("appInstance");if(!e||!e._cloudOSState)return window.COS&&COS.authController?COS.authController.get("quotaInfo"):null;var t=e._cloudOSState.quotaData;return!e._cos_quota_cache&&t?(SC.debug("Creating local CK.QuotaInfo object"),e._cos_quota_cache=CK.QuotaInfo.create(t)):t||SC.warn("Cannot set Quota Data."),e._cos_quota_cache},isUserOverQuota:function(){var e=this.getQuotaData();return e?e.get("overQuota"):null},refreshQuotaData:function(){CK.currentApplication?this.get("appInstance").invokeMethodOnCloudOS(this.getPath("appInstance.name"),"refreshQuotaData"
(YES),i.removeOmittedApps(s)):o())}),i.detectAndLoadAdditionalApps(s))}},getWindowMinimumSize:function(){if(window.COS)return{minWidth:COS.MIN_WIDTH,minHeight:COS.MIN_HEIGHT};var e=this.get("appInstance");if(e&&e._cloudOSState)return e._cloudOSState.mininumWindowSize},isOnSupportedMobile:function(){if(window.CloudOSBootstrap)return CloudOSBootstrap.isOnSupportedMobile;var e=this.get("appInstance");if(e&&e._cloudOSState)return e._cloudOSState.isOnSupportedMobile},getSecureChannelInfo:function(){var e=this.get("appInstance"),t=e?e._cloudOSState:null;if(!e||!t)return window.COS&&COS.authController?COS.authController.get("secureChannelInfo"):null;var n=t.secureChannelInfoData;return!e._secure_channel_info_cache&&n?(SC.debug("Creating local CK.SecureChannelInfo object"),e._secure_channel_info_cache=CK.SecureChannelInfo.create(n)):n||SC.warn("No secure Channel Info object. The user might not have used the secure channel route for logging in."),e._secure_channel_info_cache},getDefaultAssetHostname:function(){var e=this.get("appInstance"),t=e?e._cloudOSState:null;if(!e||!t)return window.COS&&COS.authController?COS.authController.get("defaultAssetHostname"):null;if(e&&e._cloudOSState)return e._cloudOSState.defaultAssetHostname}},CK.MicroResourceContainer={_cacheSizeHighWaterMark:200,_cacheSizeLowWaterMark:150,containerInit:function(){this._queue=[],this._status={},this._cache={},this._cacheSize=0,this._cacheLRU={},this._alreadyPendingCallbacks={},this._cacheLRUCounter=0},containerLoad:function(e,t){if(e===null||e===undefined)return t(undefined,undefined);if(e in this._cache)return t(
this._cache[e]},containerFlush:function(e){CW.fatalError("Developer must provide a containerFlush method")}},CK.MicroResourceContainer.LoadStatus={NOT_LOADED:undefined,PENDING:"pending",LOADED:"loaded",FAILED:"failed"},CK.MicroResourceContainerServerError=SC.Object.extend({message:"",failedInputs:[]}),CK.RequestDelegate={isCKRequestDelegate:YES,getUrlForServiceName:function(e){return null},didReceiveSpecialResponse:function(e,t,n){}},CK.CKJSRequest={},CK.CKJSRequest.fetch=function(e,t){var n=e.substr(0,7),r=n==="http://"||n==="https:/",i=t.method||"GET",s=t.headers||{},o=t.body||"",u=CK.CKJSRequest._createQueryParamMapForUrl(e),a,f=e.split("?");f.length>1&&(e=f[0]);var l={withCredentials:YES,type:i,headers:s,address:e,body:o,reportRequest:YES};t&&t.credentials&&t.credentials.toLowerCase()==="omit"&&(l.withCredentials=NO),r||(l.serviceName="ckdatabasews"),window.CloudOS&&CloudOS.isUserAuthenticated()?a=CK.Request.create(l):(a=CW.Request.create(l),a.set("useCrossDomain",!0),a.set("attachIdentifyingHeaders",!1),a.set("contentType","text/plain"),a.header("Content-Type","text/plain"),a.set("addressPrefix","https://ckdatabasews.%{currentDomain}:443".fmt({currentDomain:URI(window.location.href).domain()})));var c=Object.keys(u);for(var h=0;h<c.length;h++){var p=c[h];a.queryParameter(p,u[p])}var d=new Promise(function(e,t){a.notify(200,this,function(n){return CK.CKJSRequest.handleSuccess(n,e,t),YES}.bind(this)),a.notify(0,this,function(n){return CK.CKJSRequest.handleFailure(n,e,t),YES}.bind(this)),a.send()}.bind(this));return d},CK.CKJSRequest.handleSuccess=function(e,t,n){var r=e.getPath
("request.addressPrefix")+e.getPath("request.address"),i={status:e.get("status"),type:"default",headers:e.get("headers"),url:r,text:function(){var t=e.get("encodedBody"),n=Promise.resolve(t);return n},json:function(){var t=e.get("encodedBody"),n=JSON.parse(t),r=Promise.resolve(n);return r}};t(i)},CK.CKJSRequest.handleFailure=function(e,t,n){var r=e.get("encodedBody"),i=new TypeError(r);n(i)},CK.CKJSRequest._createQueryParamMapForUrl=function(e){var t={},n=e.split("?");if(n.length>1){var r=n[1].split("&");for(var i=0;i<r.length;i++){var s=r[i],o=s.split("="),u=o[0],a=o[1];t[u]=a}}return t},CK.HelpUtils={open:function(e,t){var n=CloudOS.getUser(),r=n?n.isLiteAccount():NO,i=this.getHelpLanguageCodeForLocale(String.preferredLanguage),s=i==="en"?"":"?lang="+i,o="https://help.apple.com/"+(r?"icloudwebonly":"icloud")+"/"+s,u=SC.browser.chrome?705:675;t&&(o+="#"+t),window.open(o,"help","height="+u+",width=875,location=0,status=0,scrollbars=0")},getHelpLanguageCodeForLocale:function(e){var t=e.split("-"),n=["zh","pt"],r;return n.indexOf(t[0])!==-1?r=e:r=t[0],r}},CK.Request=CW.Request.extend(SC.DelegateSupport,CK.RequestReporting,{serviceName:null,useCrossDomain:YES,withCredentials:YES,attachIdentifyingHeaders:NO,contentType:undefined,delegate:null,requestDelegate:function(){var e=this.get("delegate")||window.CloudOS;return e||CW.fatalError("A CK.Request must have a delegate",{target:this}),e}.property("delegate").cacheable(),addressPrefix:function(){var e=null,t,n,r;return this.get("useCrossDomain")&&(t=this.get("requestDelegate"),n=this.get("address")||"",r=this._getServiceName(),n.
toLowerCase().indexOf("http")<0&&(e=t.getUrlForServiceName(r,NO),e&&(e[e.length-1]==="/"?n[0]==="/"&&(e=e.slice(0,-1)):n[0]!=="/"&&(e+="/")))),e}.property("useCrossDomain"),COPY_KEYS:CW.Request.prototype.COPY_KEYS.concat(["serviceName","delegate"]),init:function(){var e,t,n,r,i,s;arguments.callee.base.apply(this,arguments);if(!this.get("source")){this.get("useCrossDomain")&&(e=this.get("contentType"),e===undefined&&(e="text/plain",this.set("contentType",e))),e||(e=this.get("contentType")),e&&this.header("Content-Type",e),t=this._specialResponseStatuses;if(t){s=this._specialResponseWasReceived;for(n=0,r=t.length;n<r;++n)i=t[n],this.notify(i,this,s)}}},willSend:function(e,t){var n=window.CloudOS&&!CloudOS.isCloudOSClient,r=n&&CloudOS.getUser?CloudOS.getUser():COS.authController.get("user"),i=r?r.get("dsid"):null;i&&e.queryParameter("dsid",i),e.queryParameter("clientId",n&&CloudOS.getClientId?CloudOS.getClientId():COS.CLIENT_ID),e.queryParameter("clientBuildNumber",SC.buildNumber),e.queryParameter("clientMasteringNumber",SC.masteringNumber)},_specialResponseStatuses:[330,401,403,421,503],_specialResponseWasReceived:function(e){SC.debug("Received special response: %@",e);var t=this.get("requestDelegate"),n=e.get("status"),r=e.get("request"),i=r._getServiceName(),s=r.get("overallTimeout"),o=e.get("addedToOutgoingQueueTimestamp"),u=YES,a=NO,f=NO,l=e.get("body"),c,h,p,d,v;if(SC.typeOf(l)===SC.T_STRING)try{var m=SC.json.decode(l);l=m}catch(g){}if(n===330){var y=this.get("address");if(i&&i!=="keyvalue"){var b=URI(y);b.protocol()&&(SC.info("Removing hostname from %@ so we can pick up the new location"
,b),this.set("address",b.path()+b.search()+b.hash())),SC.Request.manager.suspendService(i)}else SC.error("We received a response with status 330 but the request (%@) was not annotated with a service name",r);a=YES}else if(n===403){v=NO;for(c in l)if(c.match(/^auth[ _\-]?mismatch$/i)){v=YES;break}v||(u=NO)}else if(n===503){if(l)for(c in l)if(c.match(/^retry[ _\-]?after$/i)){h=l[c];break}h&&(h=parseInt(h,10)),h&&(h*=1e3,s&&o&&(p=SC.getCurrentTimeForPerformance()-o,SC.debug("The server is telling us to retry after %@ms, it has been %@ms, and our overall timeout is %@ms",h,p,s),p+h+5e3<s?(SC.debug(" - it looks like we can make it so automatically retrying request %@…",r),a=YES,u=NO):(SC.debug(" - it doesn’t look like we can make it so not automatically retrying request %@",r),a=NO,u=YES,d={retryAfter:h/1e3})))}return a&&(s&&o&&(p=SC.getCurrentTimeForPerformance()-o,p<s&&(r=r.copy()._prep(),r.set("overallTimeout",s-p))),this.invokeLater(function(){r.resend(e)},h),f=YES),d||(d={}),d.serviceName=i,u&&t.didReceiveSpecialResponse(n,e.get("encodedBody"),d),f},_getServiceName:function(){var e=this.get("serviceName"),t;return e||(t=CK.currentApplication,e=t?t.get("primaryServiceName")||t.get("name"):null),e}}),SC.Request.manager.mixin({serviceIsSuspended:function(e){e||CW.fatalError("serviceIsSuspended(): A service name must be specified",{target:this});var t=this._suspendedServices;return t&&t[e]},suspendService:function(e){e||CW.fatalError("suspendService(): A service name must be specified",{target:this});var t=this._suspendedServices;t||(t=this._suspendedServices={}),t[e]||SC.
debug("Suspending requests to “%@” service…",e),t[e]=YES},resumeService:function(e){e||CW.fatalError("resumeService(): A service name must be specified",{target:this});var t=this._suspendedServices;t&&(t[e]&&SC.debug("Resuming requests to “%@” service…",e),delete t[e]),SC.Request.manager.fireRequestIfNeeded()},resumeAllServices:function(){var e=this._suspendedServices,t;if(e)for(t in e)e[t]&&this.resumeService(t);SC.Request.manager.fireRequestIfNeeded()},_suspendedServices:null}),SC.Request.manager.mixin({shouldFireRequest:function(e){e||CW.fatalError("shouldFireRequest(): A response must be specified",{target:this});var t=e.get("request"),n=t._getServiceName?t._getServiceName():null;return n?!SC.Request.manager.serviceIsSuspended(n):YES}}),CK.AccountButtonView=CW.PopupButtonView.extend({themeName:"borderless",classNames:["account-menu","large-display-text"],attributeBindings:["aria-owns"],menuId:null,"aria-owns":function(){return this.get("menuId")}.property("menuId"),controlSize:SC.HUGE_CONTROL_SIZE,shouldAutoResize:NO,escapeHTML:YES,itemsOverride:null,availableTitles:function(){var e=[],t,n,r=window.CloudOS&&CloudOS.getUser?CloudOS.getUser():null;if(r){t=r.get("displayName");var i=r.get("firstName"),s=r.get("lastName");!CW.stringIsCJK(i)&&!CW.stringIsCJK(s)&&(n=r.get("firstName"))}return t=t||"AccountMenu.FallbackTitle".loc(),n&&e.push(n),e.push(t),e}.property().cacheable(),title:function(){var e=this.get("frame"),t=e.width,n=this.get("availableTitles"),r=this.get("measuredSizes"),i,s,o,u=n.length;for(o=0;o<u;o++){i=n[o],s=r[i];if(!s)return i;if(s.width<=t)return i}return i
,SC.RTLSupport,{autoResizePadding:0,controlSize:SC.CUSTOM_CONTROL_SIZE,layoutRecipe:{start:105,end:10},title:"HSA.SignoutDialog.CheckboxTitle".loc(),valueBinding:"*pane.hsaTrustedBrowser"})})},function(){var e="cloudkit/error_catcher";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/stylesheet.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/",isPrefetched:YES})}(),CW.HashAttributeCommon={isOrphan:NO,parent:null,parentKey:null,parentIsRecord:function(){var e=this.get("parent");return e?e.kindOf(SC.Record):NO}.property("parent").cacheable(),readAttribute:function(e){var t=this.peekAttributes();return t?t[e]:undefined},attributes:function(){if(this.get("isOrphan"))return SC.warn("%@: Requesting 'attributes' on orphaned instance",this),null;var e=this.get("parent"),t=this.get("parentKey"),n;return e||CW.fatalError("Cannot access 'attributes' because there is no parent",{hashAttributeOrArray:this}),SC.none(t)&&CW.fatalError("Cannot access 'attributes' because there is no parentKey",{hashAttributeOrArray:this}),this.get("parentIsRecord")?n=e.get("store").readEditableDataHash(e.get("storeKey")):n=e.get("attributes"),n?n[t]:null}.property("parent","isOrphan"
),hashAttributeDidChange:function(e,t,n){this.childHashDidChange(e,t,n)},destroy:function(){var e=this.get("parent"),t,n;e&&(t=this.get("parentKey"),t||CW.fatalError("There is a parent but no parentKey",{target:this,parent:e}),n=e.get("attributes"),n&&(delete n[t],this.hashAttributeDidChange(),this.orphan())),arguments.callee.base.apply(this,arguments)},getAncestorRecord:function(){var e=this.get("parent"),t;return e&&(this.get("parentIsRecord")?t=e:t=e.getAncestorRecord()),t},orphan:function(){this._orphan&&this._orphan(),this.beginPropertyChanges(),this.set("isOrphan",YES),this.set("parent",null),this.parentDidChange&&this.parentDidChange(),this.set("parentKey",null),this.destroy(),this.allPropertiesDidChange(),this.endPropertyChanges()},peekAttributes:function(e){var t=this.get("parent"),n=this.get("parentKey"),r;return t&&!SC.none(n)&&(r=t.readAttribute(n)),r}},CW.HashAttributeSupport={hashAttributeFor:function(e){var t=this._hashAttributes,n=null,r;return t&&(r=t[e],r&&(n=r)),n},childHashDidChange:function(e,t,n){t||(e?this.notifyPropertyChange(e):this.allPropertiesDidChange());var r=this.get("parent"),i=this.get("parentKey");this._ignoreChangePropogation=YES,r.childHashDidChange(i,YES,n),this._ignoreChangePropogation=NO},attributeIsDefault:function(e){var t=this[e],n=this.readAttribute(e),r;return!t||!t.isRecordAttribute?n===undefined:(r=t.getDefaultValue(this,e),n===r||SC.none(r)&&SC.none(n))},normalize:function(e,t){var n={},r,i,s,o,u,a,f,l,c,h,p,d=this.get("attributes");for(r in this)i=this[r],i&&(s=i.typeClass,s&&(h=i.get("key")||r,p=s.call(i),o=undefined,n[h]=YES,
f=SC.typeOf(s.call(i))===SC.T_CLASS,l=i.isNestedRecordTransform||p.isHashAttribute,!f&&!l?o=d[h]:l?(u=this.get(r),u&&(u.normalize&&u.normalize(e,t),!t&&u.isEmpty&&u.isEmpty()?o=null:o=u.get("attributes"))):f&&(u=this.get(r),u&&(o=d[h])),SC.none(o)&&(o=i.getDefaultValue(this,r)),o===null&&!e&&(o=undefined),o===undefined?delete d[h]:d[h]=o,u&&(u.isHashAttribute?u.underlyingContentDidChange():u.isHashAttributeArray&&u.recordPropertyDidChange())));for(r in d)n[r]||(SC.debug("%@: Deleting key from underlying data hash due to normalization: %@",this,r),delete d[r]);return this},registerHashAttribute:function(e,t){var n=this._hashAttributes,r,i;n||(n=this._hashAttributes={}),r=t.get("parent"),i=t.get("parentKey"),this!==r&&CW.fatalError("registerChildHashAttribute(): The specified child hash attribute does not have the proper parent",{key:e,target:this,parent:r}),e!==i&&CW.fatalError("registerChildHashAttribute(): The specified child hash attribute does not have the proper parentKey",{target:this,key:e,parentKey:i}),n[e]=t},unregisterHashAttribute:function(e,t){var n=this._hashAttributes,r;n||CW.fatalError("unregisterChildHashAttribute(): There is no “child hash attributes” structure",{target:this}),r=n[e],r||CW.fatalError("unregisterChildHashAttribute(): There is no registered child hash attribute for the specified key",{target:this,key:e}),delete n[e]},_hashAttributes:null},CW.StoreCommon={delegate:null,chain:function(e,t){return t||(t=CW.NestedStore),arguments.callee.base.call(this,e,t)},storageManager:null,getCurrentCommitCycle:function(){var e=null,t=this.getPath("storageManager.currentCycle"
);return t&&t.get("type")===CW.StorageCycle.COMMIT_CYCLE&&(e=t),e},commitAgentsFor:function(e){var t=this.commitAgents;return t?t[e]:null},lastCommitAgentWithParam:function(e,t){var n=this.commitAgents,r=null,i,s,o,u;if(n){n=n[e];if(n)for(s=n.length,i=s-1;i>=0;--i){o=n[i],u=o.get("params");if(u&&u.hasOwnProperty(t)){r=o;break}}}return r},notifyCommitAgents:function(e,t,n){var r=this.commitAgentsFor(e),i,s,o,u;if(r)for(i=0,s=r.length;i<s;++i)o=r[i],o&&(u=o[t],u&&u.call(o,e,n))},previousDataHashesForNotify:null,commitAgents:null,_notifyRecordPropertyChange:function(e,t,n){var r=this.records,i=this.get("nestedStores"),s=SC.Store,o,u,a,f,l,c,h;a=i?i.length:0;for(f=0;f<a;f++){l=i[f],c=l.peekStatus(e),u=l.storeKeyEditState(e);if(u===s.INHERITED)l._notifyRecordPropertyChange(e,t,n);else if(c&SC.Record.BUSY){if(l.get("hasChanges"))throw s.CHAIN_CONFLICT_ERROR;l.reset()}else if(!l._isCommitting){var p=l.get("delegate");p?l.invokeDelegateMethod(p,"parentStoreRecordPropertyDidChange",this,l,e,t,n):SC.warn("%@: Record with storeKey %@ changed underneath us, but since we have no merge delegate set, we won’t inherit the changes",l,e)}!t&&!this.get("parentStore")&&(delete this.previousDataHashesForNotify[e],this._savePreviousDataHashForNotify(e))}var d=this.recordPropertyChanges;return d||(d=this.recordPropertyChanges={storeKeys:SC.CoreSet.create(),records:SC.CoreSet.create(),hasDataChanges:SC.CoreSet.create(),propertyForStoreKeys:{}}),d.storeKeys.add(e),r&&(o=r[e])&&(d.records.push(e),t||d.hasDataChanges.push(e),n?((h=d.propertyForStoreKeys[e])||(h=d.propertyForStoreKeys[e]=SC.CoreSet.create
()),h!=="*"&&h.add(n)):d.propertyForStoreKeys[e]="*"),this.invokeOnce(this.flush),this},_verifyLockRevisions:function(e,t,n){var r=this._mergedProperties,i=this._mergedDataHashes,s=!!n.getPath("delegate.shouldMergeOutdatedChangesWhenCommitting"),o,u,a,f,l=SC.Record,c=CW.StorageCycleAction,h=e.length,p=this.revisions,d,v,m,g;if(t&&p)for(d=0;d<h;d++){v=e[d],m=t[v]||1,g=p[v]||1;if(m<g){var y=SC.Store.recordTypeFor(v);SC.debug("Potential conflict while committing from %@ down to %@: storeKey %@, of type %@:",n,this,v,y);var b=n.peekStatus(v),w=this.peekStatus(v),E=SC.Record.DESTROYED,S=SC.Record.READY_NEW,x=b&E?c.STORAGE_OPERATION_DESTROY:c.STORAGE_OPERATION_UPDATE,T=NO,N,C,k;if(!s)throw SC.Store.CHAIN_CONFLICT_ERROR;SC.debug(" > lock=%@, current revision=%@",m,g),SC.debug("Version in %@:",n),SC.debug("%@",n.materializeRecord(v)),SC.debug("Version in %@:",this),SC.debug("%@",this.materializeRecord(v)),w&E?b&E?SC.debug("This record was destroyed in both stores, so ignoring it in the commit…"):C=c.ERROR_NOT_FOUND:b&E?C=c.ERROR_CONFLICT:(b===S&&w!==S&&n.writeStatus(v,SC.Record.READY_DIRTY),C=c.ERROR_CONFLICT);if(C){var L=n.get("delegate");L&&(T=n.invokeDelegateMethod(L,"mergeConflictDuringCommit",this,n,v,C,x))}if(T===NO)SC.debug("Removing this commit from %@’s changelog…",this.get("name")),k=n.changelog,k&&k.remove(v),k=n.chainedChanges,k&&k.remove(v),a=this.getCurrentCommitCycle(),a&&(f=a.get("changelog"),f&&f.remove(v)),this.notifyCommitAgents(v,"commitWasUnnecessaryAtStore");else if(T!==YES)throw SC.Store.CHAIN_CONFLICT_ERROR}}return this}},CW.HashAttribute=SC.Object.extend
(CW.HashAttributeCommon,CW.HashAttributeSupport,{isHashAttribute:YES,normalize:function(e,t,n){this.get("isOrphan")&&CW.fatalError("normalize(): Cannot write to an orphan hash attribute",{target:this});var r=this.get("attributes"),i,s,o;r||(this._neverHadAHash||CW.fatalError("normalize(): We once had a hash but no longer do",{target:this}),i=this.get("parent"),s=this.get("parentKey"),i?s?i.isHashAttributeArray&&CW.fatalError("normalize(): There are no attributes but the parent is a hash attribute array",{target:this,parent:i}):CW.fatalError("normalize(): There is no parentKey",{target:this,parent:i}):CW.fatalError("normalize(): There is no parent",{target:this}),r={},i.writeAttribute(s,r),this._neverHadAHash=NO),e(t,n)}.enhance(),_checkedKeys:SC.CoreSet.create(),isEmpty:function(){var e,t,n,r=this._checkedKeys.clear();for(e in this){t=this[e];if(!t||!t.isRecordAttribute)continue;n=this.get("key");if(n&&n.isEmpty&&n.isEmpty()||!this.attributeIsDefault(e))return NO;r.add(e)}var i=this.get("attributes");for(e in i)if(!r.contains(e))return NO;return YES},beginEditing:function(){return this._editLevel++,this},endEditing:function(e){return--this._editLevel<=0&&(this._editLevel=0,this.hashAttributeDidChange(e)),this},writeAttribute:function(e,t,n){if(this.get("isOrphan"))return SC.debug("writeAttribute(): Cannot write to an orphan hash attribute"),this;var r=this.get("attributes"),i,s,o;return r?t!==r[e]&&(n||this.beginEditing(),r[e]=t,n||this.endEditing(e)):(this._neverHadAHash||CW.fatalError("writeAttribute(): We once had a hash but no longer do",{target:this}),i=this.get("parent"
),s=this.get("parentKey"),i?s?i.isHashAttributeArray&&CW.fatalError("writeAttribute(): There are no attributes but the parent is a hash attribute array",{target:this,parent:i}):CW.fatalError("writeAttribute(): There is no parentKey",{target:this,parent:i}):CW.fatalError("writeAttribute(): There is no parent",{target:this}),r={},r[e]=t,i.writeAttribute(s,r),this._neverHadAHash=NO),this},storeDidChangeProperties:function(e,t){t?(this.beginPropertyChanges(),t.forEach(function(e){this.notifyPropertyChange(e)},this),this.endPropertyChanges()):this.allPropertiesDidChange();var n=this.relationships,r=n?n.length:0;while(--r>=0)n[r].recordPropertyDidChange(t)},unknownProperty:function(e,t){var n;return t!==undefined?(n=this.constructor,n.ignoreUnknownProperties===YES?this[e]=t:this.writeAttribute(e,t),t):this.readAttribute(e)},toString:function(){var e=arguments.callee.base.apply(this,arguments),t=this.peekAttributes();return e+=" "+SC.inspect(t),e},parentDidChange:function(){var e=this._previousParent,t=this.get("parent"),n=this.get("parentKey"),r;if(SC.none(n))return;e!==t&&(r=this.underlyingContentDidChange,e&&(e.unregisterHashAttribute&&e.unregisterHashAttribute(n,this),e.removeObserver(n,this,r)),t&&(t.registerHashAttribute&&t.registerHashAttribute(n,this),t.addObserver(n,this,r)),this._previousParent=t,r.call(this))}.observes("parent"),underlyingContentDidChange:function(){if(this._ignoreChangePropogation){this._ignoreChangePropogation=NO;return}if(this.get("isOrphan"))return;!this._neverHadAHash&&!this.peekAttributes()?this.orphan():this.allPropertiesDidChange()},init:function(
){arguments.callee.base.apply(this,arguments);var e=this.get("parent");e||CW.fatalError("A hash attribute must have a parent",{hashAttribute:this}),!e.isRecord&&!e.isHashAttribute&&!e.isHashAttributeArray&&CW.fatalError("A hash attribute array’s parent must either be a record, a hash attribute, or a hash attribute array",{hashAttribute:this,parent:e}),this.peekAttributes()||(this._neverHadAHash=YES),this.parentDidChange()},_editLevel:0,_neverHadAHash:NO}),CW.HashAttribute.mixin({instantiateHashAttribute:function(e,t,n){return SC.kindOf(e,CW.HashAttribute)||CW.fatalError("%@ is not a kind of CW.HashAttribute".fmt(e)),e.create({parent:t,parentKey:n})},isComplex:YES,isHashAttribute:YES}),SC.RecordAttribute.registerTransform(CW.HashAttribute,{to:function(e,t,n,r,i){var s;return r?!r.kindOf(CW.Record)&&!r.kindOf(CW.HashAttribute)?CW.fatalError("The parent must be either an instance of subclass of either CW.Record or CW.HashAttribute",{parent:r,parentKey:i}):(s=r.hashAttributeFor(i),s||(s=CW.HashAttribute.instantiateHashAttribute(n,r,i))):CW.fatalError("Error during transform: A parent must be specified"),s},from:function(e){e&&e.isHashAttribute&&CW.fatalError("You should never set a hash attribute directly",{target:this,instance:e})}}),CW.ManyHashAttribute=SC.RecordAttribute.extend({toType:function(e,t,n){var r=this.get("typeClass"),i=this.get("key")||t,s=SC.keyFor("__cw__hashAttributeArray__",SC.guidFor(this)),o=e[s],u,a;return e&&e.isRecord&&(u=e.get("store"),u&&!u.isCoreWebStore&&CW.fatalError("Hash attribute arrays require the ancestor record to belong to a CoreWeb store rather than an SC.Store"
,{target:this,parent:e,store:u})),o||(o=CW.HashAttributeArray.create({objectType:r,parent:e,parentKey:i,manyAttribute:this}),e[s]=o,a=e.get("relationships"),a?(a.push(o),a.enumerableContentDidChange()):e.set("relationships",[o])),o},fromType:function(e,t,n){var r=[],i,s;SC.isArray(n)||CW.fatalError("CW.ManyHashAttribute#fromType: The toMany attribute should be an array");for(i=0,s=n.get("length");i<s;++i)r[i]=SC.clone(n.objectAt(i).get("attributes"),YES);return r}}),CW.Record=SC.Record.extend(CW.HashAttributeSupport,{typeString:function(){var e=this.get("store");if(!e)return null;var t=this.get("storeKey");if(!t)return null;var n=e.recordTypeFor(this.get("storeKey"));return n?n.typeString:null}.property("store","storeKey").cacheable(),childHashDidChange:function(e,t,n){var r=this.get("store");r.recordDidChange(null,null,this.get("storeKey"),e,YES),this.propagateToAggregates(),n||r.flush()},shortTypeString:function(){var e=this.get("store");if(!e)return null;var t=this.get("storeKey");if(!t)return null;var n=e.recordTypeFor(this.get("storeKey"));return n?n.shortTypeString():null}.property("store","storeKey").cacheable(),shortString:function(){var e=this.get("shortTypeString"),t;return e?(e=e.toLowerCase(),t=this.get("title"),t?e+=" “%@”".fmt(t):e+=" with ID %@".fmt(this.get(this.get("primaryKey")))):e=this.toString(),e},ownerProperty:null,owner:function(){var e=this.get("ownerProperty");return e?this.get("property"):null}.property("ownerProperty"),rootOwner:function(){var e=this.get("owner");return e?e.get("rootOwner"):this}.property("owner"),isAggregate:function(){var e=this
.get("ownerProperty"),t=NO,n;return e&&(n=this[e],t=n&&n.aggregate),t}.property("ownerProperty"),aggregates:function(){var e=[],t,n,r,i,s,o,u,a,f,l,c,h,p,d,v;for(t in this){n=this[t];if(n){r=n.typeClass;if(r){r=r.call(n),i=SC.typeOf(r)===SC.T_CLASS;if(i){s=n.inverse;if(s){o=r.prototype[s];if(o){u=o.aggregate;if(u){a=this.get(t);if(a)for(f=0,l=a.get("length");f<l;++f){c=a.objectAt(f),e.push(c),h=c.get("aggregates");if(h)for(p=0,d=h.length;p<d;++p)v=h[p],e.push(v)}}}}}}}}return e.length?e:null}.property(),usesHashAttributes:function(){var e=NO,t=this._hashAttributes,n,r,i,s;t&&t.length>0&&(e=YES);if(!e){n=this.relationships;if(n)for(r=0,i=n.length;r<i;++r){s=n[r];if(SC.kindOf(s,CW.HashAttributeArray)){e=YES;break}}}return e}.property().cacheable()}),SC.mixin(CW.Record,{toMany:function(e,t){return SC.kindOf(e,CW.HashAttribute)?CW.ManyHashAttribute.attr(e,t):SC.Record.toMany(e,t)},shortTypeString:function(){var e=this.typeString;return e&&(e=e.split("."),e=e[e.length-1]),e},storeKeyIfValid:function(e,t){e||CW.fatalError("storeKeyIfValid(): You must specify an ID."),t||CW.fatalError("storeKeyIfValid(): You must specify a store.");var n=this.storeKeyExists(e),r;return n&&(r=t.peekStatus(n),r===this.DESTROYED_CLEAN&&(n=null)),n}}),CW.HashAttributeArray=SC.Object.extend(CW.HashAttributeCommon,CW.HashAttributeSupport,SC.Enumerable,SC.Array,{isHashAttributeArray:YES,objectType:null,manyAttribute:null,normalize:function(e,t){var n=this._getReadOnlyUnderlyingArray(),r=n?n.get("length"):0,i,s;for(i=0;i<r;i++)s=this.objectAt(i),s.normalize(e,t);return this},length:function(){var e=this.
_getReadOnlyUnderlyingArray();return e?e.length:0}.property("parent","parentKey"),objectAt:function(e){var t=this._hashAttributes,n,r,i,s;return t&&(s=t[e]),s||(n=this._getReadOnlyUnderlyingArray(),n&&(r=n[e],r&&(SC.typeOf(r)!==SC.T_HASH&&CW.fatalError("objectAt(): The object in the array is not a hash",{hashAttributeArray:this,index:e}),i=this.get("objectType"),s=CW.HashAttribute.instantiateHashAttribute(i,this,e),t||(t=this._hashAttributes=[]),t[e]=s))),s},replace:function(e,t,n){var r=this._getEditableUnderlyingArray(),i=[],s=n?n.get?n.get("length"):n.length:0,o,u;this.arrayContentWillChange(e,t,s);for(o=0;o<s;++o)u=n.objectAt(o),SC.kindOf(u,CW.HashAttribute)?u=SC.clone(u.get("attributes"),YES):SC.typeOf(u)!==SC.T_HASH&&CW.fatalError("Illegal type of item specified in replace()",{target:this,index:o,items:n}),i.push(u);r.replace(e,t,i);var a=this._hashAttributes;if(a){var f=r?r.length:0,l=e+t,c=e+s;for(o=e;o<l;++o)u=a[o],u&&u.orphan();a.splice(e,t);for(o=e;o<f;++o)o<c?a.splice(o,0,null):(u=a[o])&&u.set("parentKey",o);f!==a.length&&CW.fatalError("Hash attribute array length is different from underlying array length",{target:this})}return this.arrayContentDidChange(e,t,s),this.enumerableContentDidChange(),this.hashAttributeDidChange(null,YES),this},isEmpty:function(){var e=this._getReadOnlyUnderlyingArray();return!e||e.get("length")===0},_getReadOnlyUnderlyingArray:function(){var e=this.get("parent"),t=this.get("parentKey");return e||CW.fatalError("No parent defined"),t||CW.fatalError("No parentKey defined"),e.readAttribute(t)},_getEditableUnderlyingArray:function(){var e=
this.get("parent"),t=this.get("parentKey"),n,r;return e||CW.fatalError("No parent defined"),t||CW.fatalError("No parentKey defined"),n=e.get("attributes"),r=n[t],r||(r=n[t]=[],this.recordPropertyDidChange(SC.Set.create([t])),this.hashAttributeDidChange(null,YES,YES)),r},recordPropertyDidChange:function(e){if(e&&!e.contains(this.get("parentKey")))return this;var t=this._previousUnderlyingArray,n=this._getReadOnlyUnderlyingArray(),r=0,i=0;t&&(r=t.get("length")),this._previousUnderlyingArray=n,n&&(i=n.get("length"));var s=Math.max(0,r-i),o=Math.max(0,i-r),u=Math.min(i,r);this.arrayContentWillChange(u,s,o);var a=this._hashAttributes;if(a){var f,l,c=Math.max(r,i);for(f=0;f<c;f++)l=a[f],l&&(f<i?l.allPropertiesDidChange():l.orphan());a.length=i}this.arrayContentDidChange(u,s,o),this.enumerableContentDidChange()},_orphan:function(){var e=this._hashAttributes,t,n,r;if(e){for(t=0,n=e.length;t<n;++t)r=e[t],r&&r.orphan();this._hashAttributes=null}},init:function(){arguments.callee.base.apply(this,arguments);var e=this.get("parent");e||CW.fatalError("A hash attribute array must have a parent",{hashAttributeArray:this}),!e.isRecord&&!e.isHashAttribute&&CW.fatalError("A hash attribute array’s parent must either be a record or a hash attribute",{hashAttributeArray:this}),this.recordPropertyDidChange()},_hashAttributes:null,_previousUnderlyingArray:null}),CW.HashAttributeArray.mixin({isComplex:YES,isHashAttributeArray:YES}),CW.Store=SC.Store.extend(CW.StoreCommon,SC.DelegateSupport,{isCoreWebStore:YES,readEditableDataHash:function(e){return this._savePreviousDataHashForNotify(e),arguments.callee
.base.apply(this,arguments)},writeDataHash:function(e,t,n){return t&&this._savePreviousDataHashForNotify(e),arguments.callee.base.apply(this,arguments)},placeHolderRecord:function(e,t,n){var r=e.storeKeyFor(t),i;return i=this.materializeRecord(r),r&&(this.writeDataHash(r,n?n:{}),this.writeStatus(r,SC.Record.READY_CLEAN),i.allPropertiesDidChange()),i},pushRetrieve:function(e,t,n,r,i){var s=SC.Record,o;r===undefined&&(r=e.storeKeyFor(t)),o=this.readStatus(r);if(o==s.EMPTY||o==s.ERROR||o==s.READY_CLEAN||o==s.DESTROYED_CLEAN){o=s.READY_CLEAN;if(n===undefined)this.writeStatus(r,s.EMPTY),this.dataHashDidChange(r);else{var u=this.getCurrentCommitCycle(),a=u?u.get("changelog"):null;if(a&&a.contains(r)){var f=SC.clone(this.readDataHash(r),YES),l=u.dataHashesCheckpointBeforeCycleStage[r],c=this.mergeHashesAsPossible;if(f&&l&&c){SC.debug("pushRetrieve(): Merging newly-loaded data for storeKey %@ into main store…",r);var h=c.call(this,n,f,l,e.propertyMergeGroups,YES,"server-retrieved data",this.get("name")),p=h.changedKeys.concat(h.addedKeys,h.removedKeys),d=h.mergeConflictKeys;if(p.length||d.length)this.writeDataHash(r,f,o),this.dataHashDidChange(r);if(d.length>0){var v=this.get("delegate"),m=NO;v&&(m=this.invokeDelegateMethod(v,"mergeConflictDuringNotify",this,null,r,p,d))}}else this.writeDataHash(r,n,o),this.dataHashDidChange(r)}else this.writeDataHash(r,n,o),this.dataHashDidChange(r)}return r}return NO},_savePreviousDataHashForNotify:function(e,t){var n=this.get("nestedStores");n&&n.length>0&&(this.previousDataHashesForNotify[e]||(this.previousDataHashesForNotify[e]=SC.clone(this.dataHashes
),this.set("_oldNavigationView",e)))}.observes("navigationView"),navigationViewFrameDidChange:function(){var e,t=this.getPath("navigationView.frame.width"),n=this.viewStack;for(var r=0,i=n.length;r<i;++r)e=n[r],e.adjust("width",t),this.barStack[r].adjust("width",t)},push:function(e,t,n){t===undefined&&(t=YES),e.isNavigatable||SC.error("Tried to push a view which doesn't mix-in the CW.NavigationSupport mixin.");var r=this.get("viewStack"),i=this.get("barStack"),s=-1*this.getPath("navigationView.frame").width,o=r[r.length-1],u=i[i.length-1];this._pushViewAndBarToStack(e,YES),this.getPath("navigationView.pane").makeFirstResponder(e);var a=r[r.length-1],f=i[i.length-1];a&&this._moveBarAndViewTo(a,f,t,0,1,NO),o&&this._moveBarAndViewTo(o,u,t,s,0,NO,n)},pop:function(e,t,n){e===undefined&&(e=YES),t===undefined&&(t=1);var r=this.get("viewStack"),i=this.get("barStack"),s=r.pop(),o=i.pop(),u,a,f,l,c;for(var h=0;h<t-1;h++)u=r.pop(),a=i.pop(),u.removeFromParent(),a.removeFromParent();f=r[r.length-1],l=i[i.length-1],c=this.get("navigationView").get("frame").width,this.getPath("navigationView.pane").makeFirstResponder(f),t>1&&f&&l&&(f.adjust({left:-1*c}),l.adjust({left:-1*c})),s&&this._moveBarAndViewTo(s,o,e,c,0,YES),f&&this._moveBarAndViewTo(f,l,e,0,1,NO,n)},_moveBarAndViewTo:function(e,t,n,r,i,s,o){var u=this.get("navigationView"),a=1,f=e.get("frame").x;if(n){e.adjust({left:f,height:u.get("frame").height-t.get("frame").height,bottom:null}),t.adjust({left:f,opacity:a}),e.set("wantsAcceleratedLayer",YES),t.set("wantsAcceleratedLayer",YES);var l=Math.max(CW.VIEW_LEFT_DURATION,CW.BAR_LEFT_DURATION
;e.forEach(function(e){if(e==="content")throw"Can not proxy the content property";var r=this.computedDisplayProxyPropertyKey(e),i=this[r];if(i===undefined)this[r]=null,t.push(r),n[r]=e;else{if(SC.typeOf(i)!==SC.T_FUNCTION||!i.isProperty)throw"'%@' is already defined. Can not proxy property '%@'".fmt(r,e);t.push(r)}},this);var r=this.get("displayProperties");r=r.concat(t),this.set("displayProperties",r)},_cwps_addContentKeyComputedDisplayProxyPropertyMapping:function(e){var t=this._cwps_contentKeys,n=this._cwps_contentKeyToComputedProxyPropertyMap,r=this._cwps_computedProxyPropertyToContentKeyMap;e.forEach(function(e){var i=this._cwps_computedContentKey(e),s=this.computedDisplayProxyPropertyKey(e);t.push(i),n[i]=s,r[s]=i},this)},_cwps_contentDidChange:function(){this._cwps_tearDownContentPropertiesObserving(),this._cwps_setupContentPropertiesObserving(),this._cwps_contentPropertiesDidChange(this,"*")}.observes("content"),_cwps_setupContentPropertiesObserving:function(){var e=this.get("content");this._cwps_content=e;if(!e)return;e.addObserver("*",this,"_cwps_contentPropertiesDidChange")},_cwps_tearDownContentPropertiesObserving:function(){var e=this._cwps_content;this._cwps_content=null;if(!e)return;e.removeObserver("*",this,"_cwps_contentPropertiesDidChange")},_cwps_propertiesDidChange:function(e,t){var n=this.get("proxyDisplayProperties")||[],r=null;t==="*"?r=n:n.indexOf(t)>=0&&(r=[t]);if(!r)return;this.beginPropertyChanges(),r.forEach(function(e){var t=this.computedDisplayProxyPropertyKey(e);this._cwps_notifyComputedDisplayProxyPropertyChanged(t)},this),this.endPropertyChanges
]}),CW.SectionedViewBlock=SC.Object.extend({sectionedView:null,views:[],height:0,top:0,hasViews:function(){var e=this.get("views");return e&&e.length>0}.property("view").cacheable(),setup:function(){},tearDown:function(){var e=this.get("views")||[];e.forEach(function(e){e.destroy()}),this.set("views",[])},reload:function(){},readjustFromTop:function(e){this.set("top",e),this.doReadjustFromTop(e)},doReadjustFromTop:function(e){},readjustViewFromTop:function(e,t){return e.adjust({top:t,bottom:null}),e.get("frame").height},updateHeightIfNeeded:function(){var e=this.get("views")||[],t=NO;e.forEach(function(e){if(e.isSectionedViewAutoResizingView&&e.shouldAutoResize){var n=e.computeHeight();n&&(e.adjust("height",n),t=YES)}}),t&&this.updateHeight()},updateHeight:function(){}}),CW.SectionedViewFooterBlock=CW.SectionedViewBlock.extend({setup:function(){var e=this.get("sectionedView"),t=e.get("styleValue"),n=t.get("contentLayout"),r=e.get("footerView"),i=e.get("footerHeight");if(!r)return;if(!r.isClass||!SC.kindOf(r,SC.View)){SC.Logger.error("%@: sectioned view footer is not a view class".fmt(e));return}r=e.get("contentView").createChildView(r,{layerId:"%@-footer".fmt(e.get("layerId")),classNames:"cw-sectioned-footer",layout:{left:0,right:0,top:0,height:i}}),this.set("views",[r]),this.set("height",i)},doReadjustFromTop:function(e){var t=this.get("views");t&&t.length>0&&this.readjustViewFromTop(t[0],e)},updateHeight:function(){this.set("height",this.get("views")[0].get("frame").height)}}),CW.SectionedViewHeaderBlock=CW.SectionedViewBlock.extend({setup:function(){var e=this.get("sectionedView"
),t=e.get("styleValue"),n=t.get("contentLayout"),r=e.get("headerView"),i=e.get("headerHeight");if(!r)return;if(!r.isClass||!SC.kindOf(r,SC.View)){SC.Logger.error("%@: sectioned view header is not a view class".fmt(e));return}r=e.get("contentView").createChildView(r,{layerId:"%@-header".fmt(e.get("layerId")),classNames:"cw-sectioned-header",layout:{left:0,right:0,top:0,height:i}}),this.set("views",[r]),this.set("height",i)},doReadjustFromTop:function(e){var t=this.get("views");t&&t.length>0&&this.readjustViewFromTop(t[0],e)},updateHeight:function(){this.set("height",this.get("views")[0].get("frame").height)}}),CW.SectionedViewSectionBlock=CW.SectionedViewBlock.extend({sectionIndex:null,headerView:null,footerView:null,rows:null,height:function(){var e=this.get("sectionedView"),t=this.get("sectionIndex"),n=e.get("sectionedViewDataSource"),r=n.numberOfSectionsInSectionedView(e),i=this.get("views")||[],s=this.rowsContainerView,o=0;i.forEach(function(e){e!=s&&(o+=e.get("frame").height)});var u=e.get("styleValue"),a=u.get("contentLayout"),f=u.get("sectionSpacing");return t<r-1&&o>0&&(o+=f),o}.property("views","sectionIndex").cacheable(),includeSectionRowsContainer:function(){return SC.browser.isIE8OrLower}.property().cacheable(),setup:function(){var e=this.get("sectionedView"),t=[];this.headerView=this._createHeaderView(),this.rows=this._createRowCells(),this.footerView=this._createFooterView(),this.rowsContainerView=this._createRowsContainer(),this.rowsContainerView&&t.push(this.rowsContainerView),this.headerView&&t.push(this.headerView),this.rows&&t.pushObjects(this.rows),this.footerView&&
.Logger.error("%@: cell for index path %@ is not a sectioned view core cell class".fmt(n,s)),null;h={classNames:f,layerId:"%@-section-%@-row-%@".fmt(n.get("layerId"),e,t),isSectionedViewCell:YES,indexPath:s,layout:{top:0,left:0,right:0,height:a},displayDelegate:c},u&&(h.content=u);var p=n.get("contentView");return o=p.createChildView(o,h),o.owner=n,o},_createHeaderView:function(){var e=this.get("sectionedView"),t=this.get("sectionIndex"),n=e.get("sectionedViewDataSource"),r=e.get("sectionedViewDelegate"),i=n.sectionedViewTitleForHeaderInSection(e,t),s=n.sectionedViewShouldAutoResizeHeaderTitleInSection(e,t),o=r.sectionedViewViewForHeaderInSection(e,t),u=r.sectionedViewHeightForHeaderInSection(e,t);u=u||e.get("sectionHeaderHeight"),!SC.empty(i)&&!o&&(o=e.get("sectionHeaderViewExample").extend({value:i}),s&&(o=o.extend(CW.SectionedViewAutoResizingViewSupport,{heightPadding:6})));if(!o)return null;if(!o.isClass||!SC.kindOf(o,SC.View))return SC.Logger.error("%@: header view for section %@ is not a view class".fmt(e,t)),null;var a=e.get("contentView");return o=a.createChildView(o,{layerId:"%@-section-header-%@".fmt(e.get("layerId"),t),classNames:"cw-section-header",layout:{left:0,right:0,top:0,height:u},displayDelegate:e}),o.owner=e,o},_createFooterView:function(){var e=this.get("sectionedView"),t=this.get("sectionIndex"),n=e.get("sectionedViewDataSource"),r=e.get("sectionedViewDelegate"),i=n.sectionedViewTitleForFooterInSection(e,t),s=n.sectionedViewShouldAutoResizeFooterTitleInSection(e,t),o=r.sectionedViewViewForFooterInSection(e,t),u=r.sectionedViewHeightForFooterInSection(e,
t);u=u||e.get("sectionFooterHeight"),!SC.empty(i)&&!o&&(o=e.get("sectionFooterViewExample").extend({value:i}),s&&(o=o.extend(CW.SectionedViewAutoResizingViewSupport)));if(!o)return null;if(!o.isClass||!SC.kindOf(o,SC.View))return SC.Logger.error("%@: footer view for section %@ is not a view class".fmt(e,t)),null;var a=e.get("contentView");return o=a.createChildView(o,{layerId:"%@-section-footer-%@".fmt(e.get("layerId"),t),classNames:"cw-section-footer",layout:{left:0,right:0,top:0,height:u},displayDelegate:e}),o.owner=e,o}}),CW.SectionedViewSectionBlock.mixin({sectionRowsContainerViewExample:SC.View.extend({classNames:"cw-section-rows-container",render:function(e,t){SC.RenderDelegate.includeSlices(this,e,SC.NINE_SLICE)}})}),CW.SectionedViewCoreCellRenderDelegate=SC.RenderDelegate.extend({className:"cw-sectioned-view-cell",styleKey:"styleValue",selectionStyleKey:"selectionStyleValue",highlightStyleKey:"highlightStyle",isEnabledKey:"isEnabledValue",render:function(e,t){var n=e.get("isSelected"),r=e.get("isHighlighted"),i=e.get(this.get("isEnabledKey")),s=e.get(this.get("styleKey")),o=e.get(this.get("selectionStyleKey")),u=e.get(this.get("highlightStyleKey"));n&&t.addClass("cw-selected"),r&&t.addClass("cw-highlighted"),i||t.addClass("cw-disabled"),r&&t.addClass(u.get("classNames")),n&&o&&t.addClass(o.get("classNames")),s&&t.addClass(s.get("classNames")),this.willRenderCellBody(e,t),this.renderCellBody(e,t),this.didRenderCellBody(e,t)},renderCellBody:function(e,t){},willRenderCellBody:function(e,t){},didRenderCellBody:function(e,t){},update:function(e,t){var n=e.get(this.get("styleKey"
,this,e)?(t.cellHandlingRowTap=YES,YES):(this.rowTapStartAtIndexPath(n.get("indexPath")),YES)):(this._tapStartInfo=null,NO)},_handleTapEndForEvent:function(e){if(!this._tapStartInfo)return NO;var t=this._tapStartInfo,n=t.cell,r;return this._tapStartInfo=null,t.cellHandlingRowTap&&n.sectionedViewTapEndForEvent?n.sectionedViewTapEndForEvent(this,e):(n=this.cellForEvent(e),n&&(r=n.get("indexPath")),this.rowTapEndAtIndexPath(r),YES)},_cw_sv_isEnabledChanged:function(){var e=this._sectionBlocks||[],t=this.get("isEnabled");e.forEach(function(e){var n=e.rows||[];n.forEach(function(e){e.set("isEnabledInSectionedView",t)})})}.observes("isEnabled")}),CW.IndexPath=SC.Object.extend(SC.Copyable,{section:null,row:null,copy:function(e){return CW.IndexPath.create({section:this.get("section"),row:this.get("row")})},equals:function(e){return!e||!SC.kindOf(e,CW.IndexPath)?NO:CW.IndexPath.compare(this,e)===0},toString:function(){var e=this.get("row"),t=this.get("section");return"IndexPath(row: %@, section: %@)".fmt(e,t)}}),CW.IndexPath.mixin(SC.Comparable,{compare:function(e,t){var n=SC.kindOf(e,CW.IndexPath),r=SC.kindOf(t,CW.IndexPath);if(!n&&!r)throw"Can not compare. a and b must both be of type CW.IndexPath";return e.get("section")==t.get("section")?e.get("row")===t.get("row")?0:e.get("row")<t.get("row")?-1:1:e.get("section")<t.get("section")?-1:1}}),CW.BorderView=SC.View.extend({classNames:"cw-border-view",renderDelegateName:"borderRenderDelegate"}),CW.iOSPickerPane=SC.PickerPane.extend(CW.Animatability,CW.PaneFadingSupport,{paneFadeInDuration:0,fitPositionToScreenPointer:function(e,t,n){var r=
.TouchScrollerView.extend({touchScrollDidStart:function(){arguments.callee.base.apply(this,arguments),this.$(".thumb").css("opacity",.5)},touchScrollDidEnd:function(){arguments.callee.base.apply(this,arguments),this.$(".thumb").css("opacity",0)}}),SC.ScrollView.prototype.verticalTouchScrollerView=CW.TouchScrollerView,SC.ScrollView.prototype.horizontalTouchScrollerView=CW.TouchScrollerView,function(){var e="cloudkit/first_run";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:["coreweb/timezone_picker","cloudkit/photo"],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="coreweb/timezone_picker";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/"
,isPrefetched:YES})}(),function(){var e="cloudkit/photo";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:[],styles2x:[],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/photo/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/photo/1812Project43/en-us/",isPrefetched:YES})}(),COS=SC.Object.create({NAMESPACE:"COS",VERSION:"1.0.0",init:function(){arguments.callee.base.apply(this,arguments),this.setupMinWidthAndHeight(),this.statsController=CK.StatsController.create({statSessionId:this.statSessionId,includedParams:function(){var e=COS.authController,t=e.getPath("user.isLiteAccount"),n=e.get("signupOriginApp"),r={},i=window.CloudOSBootstrap&&CloudOSBootstrap.isTermsAndConditionUrl&&URI(window.location.href).hash().split("/").lastObject()==="gc";return SC.none(t)||(r.isLiteAccount=t),SC.none(n)||(r.originApp=n),i&&(r.isGameCenterTermsUrl=!0),r}.property("COS.authController.user")}),CK.errorCatcher.exceptionCallback=function(e){COS.statsController.recordStat(e.applicationName,"ErrorReport",{errorType:e.origin})},this.scheduleStatSessionIdUpdateTimer()},CLIENT_ID:CW.upperCaseUUID(),statSessionId:CW.upperCaseUUID(),REVALIDATE_INTERVAL:1800,REFRESH_WEB_AUTH_INTERVAL:1500,STAT_SESSION_ID_UPDATE_INTERVAL:28800,PUSH_RETRY_WAIT:10,MIN_WIDTH:null,DESKTOP_MIN_WIDTH:950,MOBILE_MIN_WIDTH:320,MIN_HEIGHT:null,DESKTOP_MIN_HEIGHT:700,MOBILE_MIN_HEIGHT:460,MAX_VALIDATE_RETRIES:1,MAX_LOGIN_RETRIES:1,MAX_PREFERENCES_RETRIES:1,setupMinWidthAndHeight:function(
:t.get("environment"),route:function(){if(CloudOS.appManagerFor)return CloudOS.appManagerFor(e).get("route");var t=window.location.hash,n=t?t.substring(1):null;return n}(),displayName:function(){if(CloudOS.appManagerFor)return CloudOS.appManagerFor(e).get("displayName")}(),currentlyActiveApplication:e,hostname:CloudOS.get("hostname")||window.location.hostname,clientId:this.CLIENT_ID,userAuthenticationState:t.get("userAuthenticationState"),appsInfo:function(){var e=COS.apps,t=[],n,r;for(n in e){r=COS.appsController.getAppInfoFor(n);if(!r){SC.warn("No appInfo for %@",n);continue}t.push(CK.AppInfo.serializeAsHash(r))}return t}(),userStatusCode:t.getPath("user.statusCode"),isBeta:CK.get("isBeta"),isFuture:CK.get("isFuture"),isCarry:CK.get("isCarry"),isCarryUser:t.get("isCarryUser"),availableLocales:this.filterLocales(COS.get("availableLocales")),localesSupportedByAllApps:this.filterLocales(COS.get("localesSupportedByAllApps")),pushToken:COS.pushController?COS.pushController.get("pushToken"):null,mininumWindowSize:{minWidth:COS.MIN_WIDTH,minHeight:COS.MIN_HEIGHT},isOnSupportedMobile:window.CloudOSBootstrap&&CloudOSBootstrap.isOnSupportedMobile,secureChannelInfoData:o,additionalClassNamesForBody:function(){var e,t;if(CloudOS.getUser&&CloudOS.getUser().get("isChineseAccount")||COS.authController&&COS.authController.getPath("user.isChineseAccount"))e="cn";return e}(),defaultAssetHostname:t.get("defaultAssetHostname")};return u},filterLocales:function(e){if(!e)return e;var t=[];for(var n=e.length;n--;){var r=e[n];t[n]={locale:r.locale,dispName:r.dispName}}return t},lastBenchmarkDurationFor
:function(e){var t=SC.Benchmark._statFor(e);if(!t||!t._times||t._times.length===0){SC.warn("Cannot find stats for %@",e);return}return t._times[t._times.length-1].dur},localeMap:[{dispName:"English (U.S.)",locale:"en-us"},{dispName:"Español",locale:"es-es"},{dispName:"Français",locale:"fr-fr"},{dispName:"Deutsch",locale:"de-de"},{dispName:"简体中文",locale:"zh-cn"},{dispName:"日本語",locale:"ja-jp"},{dispName:"Nederlands",locale:"nl-nl"},{dispName:"Italiano",locale:"it-it"},{dispName:"한국어",locale:"ko-kr"},{dispName:"繁體中文",locale:"zh-tw"},{dispName:"Português (Brasil)",locale:"pt-br"},{dispName:"Português (Portugal)",locale:"pt-pt"},{dispName:"Svenska",locale:"sv-se"},{dispName:"Polski",locale:"pl-pl"},{dispName:"Dansk",locale:"da-dk"},{dispName:"Suomi",locale:"fi-fi"},{dispName:"Norsk bokmål",locale:"no-no"},{dispName:"Русский",locale:"ru-ru"},{dispName:"العربية",locale:"ar-sa"},{dispName:"Türkçe",locale:"tr-tr"},{dispName:"ภาษาไทย",locale:"th-th"},{dispName:"Українська",locale:"uk-ua"},{dispName:"Hrvatski",locale:"hr-hr"},{dispName:"Čeština",locale:"cs-cz"},{dispName:"Ελληνικά",locale:"el-gr"},{dispName:"עברית",locale:"iw-il"},{dispName:"Română",locale:"ro-ro"},{dispName:"Slovenčina",locale:"sk-sk"},{dispName:"Magyar",locale:"hu-hu"},{dispName:"Bahasa Indonesia",locale:"id-id"},{dispName:"Bahasa Melayu",locale:"ms-my"},{dispName:"English (Australia)",locale:"en-au"},{dispName:"English (Canada)",locale:"en-ca"},{dispName:"English (New Zealand)",locale:"en-nz"},{dispName:"English (U.K.)",locale:"en-gb"},{dispName:"Català",locale:"ca-es"},{dispName:"Tiếng Việt",locale:"vi-vi"},{dispName
:"हिन्दी",locale:"hi-in"},{dispName:"Français (Canada)",locale:"fr-ca"},{dispName:"Español (México)",locale:"es-mx"}],localesSupportedByAllApps:function(){var e=window.supportedLocales,t=this.get("localeMap"),n=t.getEach("locale"),r=[];return e.map(function(e){var i=n.indexOf(e);i!=-1&&r.push(SC.Object.create(t[i]))}),r}.property("localeMap"),localesSupportedByCloudOSOnly:function(){return window.supportedLocales.concat(["ar-sa","iw-il"]).uniq()}.property(),availableLocales:function(){var e=window.supportedLocales,t=this.get("localesSupportedByAllApps"),n,r,i=this.get("localeMap"),s=COS.authController.getPath("accountPreferences"),o=s?s.get("locale"):null,u=s?s.get("secondaryLocale"):null,a=COS.apps,f;for(f in COS.apps){var l=COS.appsController.getAppInfoFor(f);if(!l){SC.warn("No appInfo for %@",f);continue}var c=l.get("supportedLocales"),h=t.getEach("locale");if(c)for(n=0,r=i.length;n<r;n++){var p=i[n].locale;c.indexOf(p)!==-1&&h.indexOf(p)===-1&&t.push(SC.Object.create(i[n]))}}var d=t.getEach("locale"),v=i.getEach("locale"),m;return o&&d.indexOf(o)==-1&&(m=v.indexOf(o),t.push(SC.Object.create(i[m]))),u&&d.indexOf(u)==-1&&(SC.warn("There is something wrong here as secondaryLocale '%@' is not part of window.supportedLocales already.",u),m=v.indexOf(u),t.push(SC.Object.create(i[m]))),t}.property("localesSupportedByAllApps","COS.apps").cacheable(),checkBodyFontsAvailability:function(e,t){var n=SC.$("body").css("font-family"),r=n?n.replace(/, /g,",").replace(/['"]/g,"").split(","):null;if(!r){SC.warn("Unable to detect font family of the body");return}this.checkFontAvailability(
r,0,e,t,this,this.checkFontAvailability)},checkFontAvailability:function(e,t,n,r,i,s){var o=e[t];SC.info("Trying to load font %@",o),SC.Benchmark.start("Loading Font %@".fmt(o)),CW.fontDetector(o,{success:function(){var e="Loading Font %@".fmt(o),t;SC.debug("%@ font is loaded",o),SC.Benchmark.end(e),t={fontName:o,fontAvailable:YES,loadDuration:COS.lastBenchmarkDurationFor(e)},COS.statsController.recordStat("cloudos","BodyFontAvailable",t),r.call(n)},fail:function(){var u="Loading Font %@".fmt(o),a;SC.warn("%@ font failed to load",o),SC.Benchmark.end(u),a={fontName:o,fontAvailable:NO,loadDuration:COS.lastBenchmarkDurationFor(u)},COS.statsController.recordStat("cloudos","BodyFontNotAvailable",a),++t<e.length?s.call(i,e,t,n,r,i,s):(SC.warn("Unable to load any of the required fonts in the time frame given. Continuing to load…"),r.call(n))},timeout:COS.FONT_CHECK_DURATION*1e3,testFontFamily:"Arial"})},scheduleStatSessionIdUpdateTimer:function(){this._statSessionUpdateTimer||(this._statSessionUpdateTimer=SC.Timer.schedule({target:this,action:function(){this.statSessionId=CW.upperCaseUUID()},interval:this.STAT_SESSION_ID_UPDATE_INTERVAL*1e3,repeats:!0}))}}),function(){COS.ENABLE_TRANSFORM_ANIMATIONS=!0,COS.ENABLE_SCALE_ANIMATION=!0,COS.ENABLE_APP_ANIMATION=!0,COS.ANIMATE_SPRINGBOARD_LAYOUT=!0,CW.Animator.ENABLE_OLD_IE=NO}(),COS.apps={contacts:{path:"contacts/",requiredServices:["contacts","keyvalue"],pushTopic:"73f7bfc9253abaaa423eba9a48e9f187994b7bd9",isBeta:!1,isWWW:!0,supportsLite:!0},calendar:{path:"calendar/",requiredServices:["calendar","keyvalue"],pushTopic:"dce593a0ac013016a778712b850dc2cf21af8266"
))return YES}return NO}.property("requiredServices").cacheable(),isHSALocked:function(){return this.get("isLocked")&&this.get("lockType")===COS.AppInfo.LOCKED_HSA}.property("isLocked","lockType").cacheable(),isPCSKeysDeletedLocked:function(){return this.get("isLocked")&&this.get("lockType")===COS.AppInfo.LOCKED_PCS_DELETED}.property("isLocked","lockType").cacheable(),canBeRemoved:function(){var e=COS.authController.getPath("user.isManagedAppleID"),t=this.get("supportsMAID"),n=this.get("isHidden");return e&&!t||!this.get("isHidden")}.property("COS.authController.user","supportsMAID","isHidden"),localizedDisplayNames:function(){return this.getPath("localized.displayName")}.property("localized").cacheable(),localizedTitleNames:function(){return this.getPath("localized.titleName")}.property("localized").cacheable(),countrySpecificDisplayNameOverrides:function(){return this.getPath("localized.countrySpecificDisplayNameOverrides")}.property("localized").cacheable(),countrySpecificTitleNameOverrides:function(){return this.getPath("localized.countrySpecificTitleNameOverrides")}.property("localized").cacheable(),calculateAndSetLocalizedNames:function(e,t){e||CW.fatalError("cannot calculate the displayName and titleName as locale has not been provided");var n=this.get("name"),r=("AppTitle."+n).loc(),i=("AppTitleBar."+n).loc(),s=this.get("localizedDisplayNames"),o=this.get("localizedTitleNames");s&&s&&s[e]&&(r=s[e]),o&&o&&o[e]&&(i=o[e]);if(t){var u=this.get("countrySpecificDisplayNameOverrides"),a=this.get("countrySpecificTitleNameOverrides");u&&u[t]&&u[t][e]&&(r=u[t][e]),a&&a[t]&&a[t]
[e]&&(i=a[t][e])}this.set("displayName",r),this.set("titleName",i)}}),COS.AppInfo.mixin({LOCKED_HSA:1,LOCKED_PCS_DELETED:2}),window.supportedLocales=["ca-es","cs-cz","da-dk","de-de","de-lu","el-gr","en-au","en-ca","en-gb","en-nz","en-us","es-es","es-mx","fi-fi","fr-ca","fr-fr","hi-in","hr-hr","hu-hu","id-id","it-it","ja-jp","ko-kr","ms-my","nl-be","nl-nl","no-no","pl-pl","pt-br","pt-pt","ro-ro","ru-ru","sk-sk","sv-se","th-th","tr-tr","uk-ua","vi-vi","zh-cn","zh-hk","zh-tw"],COS.appsController=SC.Object.create({getAppInfoFor:function(e){e||CW.fatalError("getAppInfoFor(): An application name must be specified");var t=this._appsInfo;return t[e]||null},removeAppInfoFor:function(e){e||CW.fatalError("removeAppInfoFor(): An application name must be specified");var t=this._appsInfo;delete t[e]},init:function(){var e=arguments.callee.base.apply(this,arguments),t=COS.apps,n={},r,i;this._appsInfo=n;for(r in t)i=t[r],i?this.createAppInfo(r,SC.clone(i,YES)):SC.warn("COS.appsController: Ignoring application “%@” because it has no hash information in COS.apps",r);return e},createAppInfo:function(e,t){if(!e||!t||SC.typeOf(t)!==SC.T_HASH)return null;t.path||(t.path=e+"/");var n=this._appsInfo;t.name=e;var r=COS.AppInfo.create(t),i=window.supportedLocales,s=t.additionalSupportedLocales;n[e]=r,i&&s&&(r.supportedLocales=i.slice().concat(s));var o=this._prefsForDynamicApps[e];return o&&(r.set("preferences",o),r.set("preferencesVersion",this._prefsVersionForDynamicApps[e])),r},_appsInfo:null,_prefsForDynamicApps:{},_prefsVersionForDynamicApps:{},storePrefsForDynamicApp:function(e,t,n){this._prefsForDynamicApps
null,this._lastDsidCookie=null,this._validateUserTimer&&(this._validateUserTimer.invalidate(),this._validateUserTimer=null),window.CloudOS&&!CloudOS.isCloudOSClient&&CK.currentApplication._clearUserState(),CK.writeCookie("X-APPLE-WEB-ID",null,null,this.get("currentDomain"),null,YES),CK.removeValueInSessionStorage("redirectedToCarry"),CK.removeValueInSessionStorage("pushToken"),CK.removeValueInSessionStorage("username"),CK.tryToPerform("clearLocalStorage"),this.set("userAuthenticationState",CK.AuthenticationStateEnum.NOT_AUTHENTICATED),this.set("isLoggingIn",NO),this.set("isLoggingOut",NO),this.set("isExtendedLogin",NO),this.set("authBagLoadedFromOpenerWindow",NO),this.set("accountTermsUpdateRequired",NO),this.set("repairPayload",null)},scheduleValidateUserTimer:function(){this._validateUserTimer||(this._validateUserTimer=SC.Timer.schedule({target:this,action:function(){var e=COS.authController;e.set("isRevalidatingUser",YES),e.validateUser(function(){e.set("isRevalidatingUser",NO)},YES)},interval:COS.REVALIDATE_INTERVAL*1e3,repeats:YES}))},validateUser:function(e,t){var n=this.get("delegate"),r=this,i=this.get("validateUrl"),s;s=COS.Request.postUrl(i,null),s.set("reportRequest",YES),s.notify(200,this,function(i){var s=i.get("body"),o=r._processReceivedBag(s),u;if(!o||!o.dsInfo||!o.webservices)return SC.debug("Missing critial information in bag: %@",s),SC.debug("COS: invoking validateDidFail"),r.invokeDelegateMethod(n,"validateDidFail",i,o),YES;if(o.termsUpdateNeeded)return SC.debug("Terms update is still required, hence marking this validate call as failure"),NO;var a=o.configBag
;a&&CW.notificationCenter.postNotification("configBagReceived",a),u=o.dsInfo,u.dsid||(u.dsid=u.dsPrsID,delete u.dsPrsID);var f=SC.clone(r._auth_bag);return r._auth_bag=o,r._user_cache=null,r.notifyPropertyChange("user"),r.set("isLoggingIn",NO),r.setUserAuthenticationStatus(o.hsaChallengeRequired,o.dsInfo.isManagedAppleID,YES),r._authCompleted(o,e,NO,i)&&(SC.debug("COS: invoking validateDidSucceed with body %@",o),r.invokeDelegateMethod(n,"validateDidSucceed",o,f,t),r.monitorForUsernameChange()),YES}),s.notify(0,this,function(i){var s=i.get("body"),o=i.get("status"),u=r._processReceivedBag(s),a=u&&u.configBag,f=u&&u.hsaChallengeRequired,l=u&&u.dsInfo&&u.dsInfo.isManagedAppleID;return u&&!u.termsUpdateNeeded&&!f&&!l&&o===200?NO:(a&&CW.notificationCenter.postNotification("configBagReceived",a),r.set("isLoggingIn",NO),r.setUserAuthenticationStatus(f,l,NO),r.set("accountTermsUpdateRequired",NO),SC.debug("COS: invoking validateDidFail"),r.invokeDelegateMethod(n,"validateDidFail",i,u,t),e instanceof Function&&e(NO,NO,s,o),r.monitorForUsernameChange(),YES)}),this.set("isLoggingIn",YES),SC.debug("COS: Sending validate POST request to %@",i),this.invokeDelegateMethod(n,"validateRequestWillBeSent"),s.send()},loginUser:function(e,t,n,r,i){var s=this.get("loginUrl"),o=COS.Request.postUrl(s,null),u=this.get("delegate"),a=this;o.set("reportRequest",YES),i||o.queryParameter("dsid",null),o.notify(200,this,this.loginUserDidSucceed,u,r,i),o.notify(0,this,this.loginUserDidFail,u,r,i),a.set("isLoggingIn",YES);var f=SC.clone(this.get("customLoginBody"));f.apple_id=e,f.password=t,SC.none(n)||(f.extended_login=
n),this.set("isLoggingIn",YES),SC.debug("CloudKit: Sending login POST request to %@",s),this.invokeDelegateMethod(u,"loginRequestWillBeSent"),o.send(f)},loginUserDidSucceed:function(e,t,n,r){var i=e.get("body"),s=this._processReceivedBag(i),o;if(!s||!s.dsInfo||!s.webservices)return SC.debug("Missing critial information in bag: %@",i),SC.debug("COS: invoking loginDidFail"),this.invokeDelegateMethod(t,"loginDidFail",e,s),YES;o=s.dsInfo,o.dsid||(o.dsid=o.dsPrsID,delete o.dsPrsID);var u=SC.clone(this._auth_bag);return u&&!r&&o.dsid===u.dsInfo.dsid&&s.hsaChallengeRequired&&u.hsaChallengeRequired===s.hsaChallengeRequired?(SC.debug("Same auth bag as before completing HSA flow: %@",i),SC.debug("COS: invoking loginDidFail"),this.invokeDelegateMethod(t,"loginDidFail",e,s),YES):(this._auth_bag=s,this.notifyPropertyChange("user"),this.set("isLoggingIn",NO),this.setUserAuthenticationStatus(s.hsaChallengeRequired,s.dsInfo.isManagedAppleID,YES),this.set("repairPayload",s.isRepairNeeded&&s.repairPayload),this.set("accountTermsUpdateRequired",s.termsUpdateNeeded),this._authCompleted(s,n,YES,e)&&(SC.debug("COS: invoking loginDidSucceed"),this.invokeDelegateMethod(t,"loginDidSucceed",s),this.monitorForUsernameChange()),r&&this.set("secondaryLoginAttemptsCount",0),YES)},loginUserDidFail:function(e,t,n,r){var i=e.get("body"),s=this._processReceivedBag(i),o=s&&s.hsaChallengeRequired,u=s&&s.dsInfo&&s.dsInfo.isManagedAppleID;return this.set("isLoggingIn",NO),r?this.secondaryLoginAttemptsCount>=3?(SC.info("CloudKit: More than three invalid secondary auth attempts, make sure we log out"),this.logoutUser
(function(){CK.reloadWithReason("more than 3 secondaryLoginAttemptsCount")},YES)):r&&n instanceof Function&&n(NO,YES,e):(this.setUserAuthenticationStatus(o,u,NO),this.set("accountTermsUpdateRequired",NO),SC.debug("COS: invoking loginDidFail"),this.invokeDelegateMethod(t,"loginDidFail",e,s)),YES},logoutUser:function(e,t,n){if(this.get("isLoggingOut")){SC.warn("User is already being logged out. Ignoring new logout call.");return}CK.get("isCarry")&&!e&&(e=function(){CK.reloadWithReason("Logging Out From Carry")});if(t&&COS.pushController){var r=this;COS.pushController.unInitializePush(function(){r.sendLogoutRequest(e,t,n)})}else this.sendLogoutRequest(e,t,n);CW.notificationCenter.postNotification("logoutUser")},sendLogoutRequest:function(e,t,n){var r=this.get("logoutUrl"),i=this.get("delegate"),s=this,o,u={};t||(r=URI(r).addSearch("onunload","true").toString()),n&&(u.allBrowsers=!0),this.getPath("user.hsaEnabled")&&(u.trustBrowser=this.get("hsaTrustedBrowser")),this.set("isLoggingOut",YES),o=COS.Request.postUrl(r,null),o.set("timeout",null),o.set("useCrossDomain",YES),this._shouldRetryLogout&&COS.statsController.recordStat("cloudos","LogoutRetry",{isExplicit:t}),o.notify(200,this,function(t){return s.set("isLoggingIn",NO),s.setUserAuthenticationStatus(null,null,NO),s.set("accountTermsUpdateRequired",NO),SC.debug("CloudKit: invoking logoutDidSucceed"),s.invokeDelegateMethod(i,"logoutDidSucceed"),s.clearUserState(),s.invokeDelegateMethod(s.get("delegate"),"userDidLogout",YES),e instanceof Function&&e(t),YES}),o.notify(0,this,function(r){s.set("isLoggingIn",NO),s.setUserAuthenticationStatus
(null,null,NO),s.set("accountTermsUpdateRequired",NO);if(!s._shouldRetryLogout){SC.debug("CloudKit: Logging out did fail, will retry once"),s._shouldRetryLogout=YES,s.sendLogoutRequest(e,t,n);return}return SC.debug("CloudKit: invoking logoutDidFail"),s.invokeDelegateMethod(i,"logoutDidFail",r),s.clearUserState(),e instanceof Function&&e(r),YES}),SC.debug("CloudKit: Sending logout POST request to %@",r),this.invokeDelegateMethod(i,"logoutRequestWillBeSent"),o.send(u)},secondaryLoginAttemptsCount:0,secondaryLogin:function(e,t,n,r,i){this.secondaryLoginAttemptsCount++,this.loginUser(e,t,n,function(e,t,n){if(i instanceof Function){i(e,t,n);return}if(!r)return;var s=e?"secondaryAuthDidSucceed":"secondaryAuthDidFail",o,u=CK.currentApplication;u?(o=u.get("delegate"),u.invokeDelegateMethod(o||u,s)):CloudOS.appManagerFor(r).passMessage(s)},YES)},getQuotaData:function(e){var t=this.get("quotaUrl"),n=COS.Request.postUrl(t,null),r=this;n.set("reportRequest",YES),n.notify(200,this,function(t){var n=t.get("body"),i={},s,o={familyStorageUsageInfo:!0,storageUsageByMedia:!0};for(s in n){var u=n[s];if(SC.typeOf(u)===SC.T_HASH&&!o[s]){var a;for(a in u)i[a]=u[a]}else i[s]=n[s]}return r._quota_data=i,r._quotaInfo_cache=null,CW.notificationCenter.postNotification("quotaDataFetched",r.get("quotaInfo"),i),e&&e instanceof Function&&e(n),YES}),n.notify(0,this,function(e){return SC.warn("Could not get Quota Data"),YES}),n.send()},getConfigBagUrlForKey:function(e){var t=this._auth_bag,n=t.configBag,r=n.urls;return r[e]},monitorForUsernameChange:function(){var e=this,t=this.get("user"),n;SC.debug("Check if X-APPLE-WEB-ID can be created"
),t&&(!this.shouldShowFirstRun(this.get("accountPreferences"),CW.getUrlParameters())||this.get("isAuthenticated"))&&(n=SHA1.hex_sha1(t.get("dsid")+this.get("userAuthenticationState")),n!==this._lastDsidCookie&&(CK.writeCookie("X-APPLE-WEB-ID",n,null,this.get("currentDomain"),this.get("isExtendedLogin")?336:null,YES),this._lastDsidCookie=n));if(this._usernameMonitorTimer)return;SC.debug("Creating the _usernameMonitorTimer"),this._usernameMonitorTimer=SC.Timer.schedule({target:this,action:function(){if(!COS.authController._usernameMonitorTimer)return;var t=e.get("user"),n=CK.readCookie("X-APPLE-WEB-ID"),r=e.get("isAtLeastPartiallyAuthenticated"),i=e.get("isAuthenticated");r&&t&&t.get("dsid")&&e._lastDsidCookie&&!n?(e.clearUserState(),e.invokeDelegateMethod(e.get("delegate"),"userDidLogout",NO),e._lastDsidCookie=null):!i&&n&&n!==e._lastDsidCookie&&(e.validateUser(function(t){if(t){var n;e.get("isAuthenticated")&&(n="userDidAuthenticate"),e.get("isPartiallyAuthenticated")&&(n="userDidPartiallyAuthenticate"),n&&e.invokeDelegateMethod(e.get("delegate"),n,NO)}}),e._lastDsidCookie=n)},interval:1e3,repeats:YES})},clearMonitorForUsernameChange:function(){if(!this._usernameMonitorTimer)return;this._usernameMonitorTimer.invalidate(),this._usernameMonitorTimer=null},sendAccountCreateRequest:function(e,t){var n=this.get("repairPayload");this._sendAccountCreateRepairRequest(CloudOS.initializationController.get("accountCreateEndpointURL"),n?{createPayload:n}:{},e,t,YES)},sendAccountRepairRequest:function(e,t){var n=this.get("repairPayload");this._sendAccountCreateRepairRequest(CloudOS.initializationController
.get("repairDoneEndpointURL"),n?{repairPayload:n}:{},e,t,NO)},_sendAccountCreateRepairRequest:function(e,t,n,r,i){COS.Request.create({type:"POST",address:e,body:SC.merge(t,CloudOS.tosController.get("acceptedVersions"))}).notify(this,function(e){var t=CloudOS.statechart,s=i?"AppleID_NewAccountCreation":"AppleID_ExistingAccountRepair",o;if(e.get("status")===200){var u={referrer:document.referrer},a;n&&(o=n),i&&(a={},a.includeLocationUrlDetails=!0),COS.statsController.endStat("cloudos",s,u,a)}else r&&(o=r);o&&t.sendAction(o)}).send()},windowWillClose:function(){this.get("isAtLeastPartiallyAuthenticated")&&COS.statsController.endStat("cloudos","Session",{isRefresh:YES},{durationKeyName:"sessionDuration"}),this.cancelAppleIdFlowStats(),COS.statsController.flushStats()},_authCompleted:function(e,t,n,r){CK.servicesController._setupFromBag(e);var i=this.get("user"),s=i.get("statusCode"),o=this.get("delegate");if(this.invokeDelegateMethod(o,"redirectPostAuthenticationIfRequired",e))return;if(s===CK.User.PAID_ACTIVE)return SC.debug("The user is a MobileMe user, %@. Invoking delegate userIsMobileMe()",s),this.invokeDelegateMethod(o,"userIsMobileMe"),this.logoutUser(),NO;if(s!==CK.User.FREE_QUALIFIED&&s!==CK.User.LITE)return SC.debug("The user is not signed up to iCloud, %@. Invoking delegate userIsNotSignedUp()",s),this.invokeDelegateMethod(o,"userIsNotSignedUp"),this.logoutUser(),NO;if(i.isLiteAccount()&&SC.browser.isIE9OrLower)return SC.debug("The user is has an iCloud Lite account but is using IE9 (or earlier)."),this.invokeDelegateMethod(o,"iCloudLiteUnsupportedBrowser"),this.logoutUser
(),NO;this.set("isExtendedLogin",e.isExtendedLogin),this.set("hsaChallengeRequired",e.hsaChallengeRequired),this.set("hsaTrustedBrowser",e.hsaTrustedBrowser),this.set("pcsEnabled",e.pcsEnabled),this.set("isCarryUser",e.isCarryUser);var u=e.pcsDeleted||!!CW.getUrlParameters().deletePCSKeys;this.set("pcsDeleted",u);var a=COS.appsController,f=a._appsInfo,l=i.get("hasICloudQualifyingDevice"),c=i.get("isLiteAccount"),h=i.get("isManagedAppleId"),p=i.get("hsaEnabled"),d=NO,v=this.get("hsaChallengeRequired"),m,g=this.get("authBagApps"),y,b,w,E,S,x,T,N,C;g.photos===undefined&&!c&&(g.photos={});for(y in f){b=f[y],C=g[y];if(C)for(N in C)b.set(N,C[N]);a.setAppLockInfo(b,u,p,v),S=b.get("requiredServices");if(!S)continue;for(w=0,E=S.length;w<E;w++)x=S[w],(T=CK.servicesController.getServiceInfoFor(x))||(SC.debug("Auth bag did not contain service %@, disabling app %@",x,y),b.set("isDisabled",YES),!l&&!m&&(b.set("isUnqualified",YES),d=YES))}c&&(l=YES),this.set("isUserUnqualified",!l&&d),!l&&d&&this.invokeDelegateMethod(o,"userIsUnqualified"),this.invokeDelegateMethod(o,"userHasLoggedIn");if(CK.get("isReloading")){SC.info("Waiting to reload…");return}this.serviceIdentitiesAreMissing()&&COS.statsController.recordStat("cloudos","MissingServiceIdentities",{hsaEnabled:e.dsInfo?e.dsInfo.hsaEnabled:NO});var k=COS.prefsController,L=this.get("accountRepairRequired");if((!this.getPath("accountPreferences.hasInitialized")||this.get("isRevalidatingUser"))&&!L&&this.get("isAuthenticated"))if(window.CloudOS&&CloudOS.hasOpenerWithCloudOS&&CloudOS.hasOpenerWithCloudOS()){var A=k.getRequestedApps(),O=CloudOS
),e.cancelStat("cloudos","AppleID_ExistingAccountRepair"),e.cancelStat("cloudos","AppleID_NewAccountTerms"),e.cancelStat("cloudos","AppleID_ExistingAccountTerms")},shouldShowFirstRun:function(e,t){return!e||!e.get("locale")||!this.get("isUserUnqualified")&&!e.get("timeZone")?(SC.debug("Missing account preferences; let's show first run"),YES):t.firstRun?(SC.debug("First run flag is on, let's show it"),YES):NO},setUserAuthenticationStatus:function(e,t,n){n?e?t?this.set("userAuthenticationState",CK.AuthenticationStateEnum.PARTIALLY_AUTHENTICATED_MANAGED_APPLE_ID):this.set("userAuthenticationState",CK.AuthenticationStateEnum.PARTIALLY_AUTHENTICATED_HSA):this.set("userAuthenticationState",CK.AuthenticationStateEnum.AUTHENTICATED):this.set("userAuthenticationState",CK.AuthenticationStateEnum.NOT_AUTHENTICATED)},sendAccountLoginRequest:function(){SC.Benchmark.start("AUTH_DURATION");var e=CloudOS.initializationController.get("accountLoginEndpointURL"),t=COS.Request.postUrl(e,null),n=this.get("delegate"),r=this.get("trustToken"),i={dsWebAuthToken:this.get("dsWebAuthToken"),extended_login:this.get("isExtendedLogin"),accountCountryCode:this.get("accountCountryCode")},s=function(e,t,n,r){var i=CloudOS.get("authPane"),s=COS.authController;s.validatePreferences(e,t,n,r)};r&&(i.trustToken=r),t.queryParameter("dsid",null),t.set("reportRequest",YES),t.notify(200,this,this.loginUserDidSucceed,n,s,NO),t.notify(0,this,this.loginUserDidFail,n,s,NO),this.set("isLoggingIn",YES),SC.debug("CloudKit: Sending login POST request to %@",e),this.invokeDelegateMethod(n,"loginRequestWillBeSent"),t.send(i)}
}),COS.AuthUIController=COS.AuthController.extend({init:function(){arguments.callee.base.apply(this,arguments),COS.authController=this,COS.authUIController=this,CW.notificationCenter.subscribeToNotification("relocalize",this,"relocalize");var e=this,t=this.validatePreferences;this.validatePreferences=function(){return t.apply(e,arguments)}},isSpinning:NO,areFieldsEditable:YES,_validateRetriesSentCount:0,_loginRetriesSentCount:0,_preferencesRetriesSentCount:0,_prefsWrongPartitionCheckDone:NO,relocalize:function(){var e=this.get("user");e&&e.notifyPropertyChange("displayName")},logoutUser:function(e,t){return t&&COS.statsController.endStat("cloudos","Session",{isRefresh:NO},{durationKeyName:"sessionDuration"}),arguments.callee.base.apply(this,arguments)},cloudOSAuthCompleted:function(e,t){var n=this.get("secondaryLoginAttemptsCount"),r=this.get("user"),i=e.iCloudInfo;for(var s in i)r.set(s,i[s]);n===0&&!this.get("hsaChallengeRequired")&&!this.get("accountRepairRequired")&&CK.meCardController.getMeCard(function(e){if(e){SC.warn("The me-card was not retrieved. (The network request may have failed or a necessary service may be unavailable.)");return}var t=CK.meCardController.meCard,n=!!t.photo,r={prefix:t.prefix,firstName:t.firstName,lastName:t.lastName,suffix:t.suffix,photoUrl:n?t.photo.url:null,photoCrop:n?t.photo.crop:null,photoSignature:n?t.photo.signature:null};CloudOS.passMessageToAllApps("receiveMeCard",r)})},validateDidSucceed:function(e,t,n){var r=COS.getCredentialsFromHash(),i=e.dsInfo,s=CloudOS.getUser(),o=this;if(r&&s&&!s.isMyEmailAddressOrPhoneNumber(r.username)){SC.
warn("Username provided in URL is NOT the same as the one that was validated, logging in..."),this.clearUserState(),SC.Request.manager.cancelAll(),this.get("statechart").sendAction("authDidNotConnect","InvalidUser"),this.loginUser(r.username,r.password,r.extendedLogin,this.validatePreferences);return}if(t&&i.dsid!==t.dsInfo.dsid){window.location.hash="#:showlogin",CK.reloadWithReason("dsid is not the same as previous dsid");return}this.cloudOSAuthCompleted(e,"validate")},validateDidFail:function(e,t,n){var r=COS.getCredentialsFromHash(),i=r&&r.username?r.username:null,s=COS.authUIState;i||(i=CK.getValueFromSessionStorage("username"));if(r){this.loginUser(r.username,r.password,r.extendedLogin,this.validatePreferences);return}n||(this.clearUserState(),this.userDidNotAuthenticate(YES));var o=e.status;o===401||o===421?s.sendAction("authDidNotValidate"):e.status===200&&t.hsaChallengeRequired?(SC.warn("Auth: In the middle of HSA validation. Need to show the Login UI."),s.sendAction("incompleteHSAFlow")):(SC.warn("validate call failed with %@ status code",o),this._validateRetriesSentCount>=COS.MAX_VALIDATE_RETRIES?(SC.warn("Already exceeded the maximum number of validate request attempts. Hence marking the request as failure."),s.sendAction("authDidNotConnect","validateDidFail"),this._validateRetriesSentCount=0):(this._validateRetriesSentCount++,s.sendAction("resendLoginOrValidateRequest",n)))},loginDidSucceed:function(e){this.cloudOSAuthCompleted(e,"login")},loginDidFail:function(e,t){var n=COS.authUIState,r=t?t.error:null,i=e.status;this.userDidNotAuthenticate(YES),!t||i!==401&&i!==421?
e.status===403?r===17?n.sendAction("authDidNotCompleteSetup"):r===16?n.sendAction("authPartitionLocked"):r===14?n.sendAction("authDidNotValidateExpiredPassword"):r===10?n.sendAction("authDidNotValidateAccountClosed"):r===9?n.sendAction("authDidNotValidateSupportLocked"):r===8?n.sendAction("authDidNotValidateLocked"):r===7?n.sendAction("authDidNotValidateLocked"):r===6?n.sendAction("authDidNotValidateNotICloudUser"):r===5?n.sendAction("authDidNotValidateNotICloudUser"):r===4?n.sendAction("authDidNotValidateNotICloudUser"):r===3?n.sendAction("authDidNotValidateNotICloudUser"):r===2?n.sendAction("authDidNotValidateNotICloudUser"):(SC.warn("Auth: 403 response but no recognized error code"),n.sendAction("authDidNotConnect","loginDidFail")):e.status===503?this.handle503(e.get("body")):SC.device.get("isOffline")?n.sendAction("authDidNotValidateOffline"):(SC.warn("Auth: No auth bag or recognized status code"),this._loginRetriesSentCount>=COS.MAX_LOGIN_RETRIES?(SC.warn("Already exceeded the maximum number of login request attempts. Hence marking the request as failure."),n.sendAction("authDidNotConnect","loginDidFail")):(this._loginRetriesSentCount++,n.sendAction("resendLoginOrValidateRequest"))):r===1?n.sendAction("authDidNotValidate"):r===11?(SC.info("Login id sent does not match, sending validate before re-sending login"),this.validateUser(function(){e.get("request").resend(e)},YES)):r===15?n.sendAction("authDidNotValidateAccountTypeNotSupported"):(SC.warn("Auth: 401 response but no recognized error code"),n.sendAction("authDidNotConnect","loginDidFail"))},userIsMobileMe:function(
){COS.authUIState.sendAction("authDidNotValidateNotICloudUser")},userIsNotSignedUp:function(){COS.authUIState.sendAction("authDidNotValidateNotICloudUser")},userIsNotVerified:function(){COS.authUIState.sendAction("authDidNotValidateNotVerified")},iCloudLiteUnsupportedBrowser:function(){COS.authUIState.sendAction("iCloudLiteUnsupportedBrowser")},userIsUnqualified:function(){this.set("userRequiresUnqualifiedNotification",YES)},handle503:function(e){var t,n;if(e)for(t in e)if(t.match(/^retry[ _\-]?after$/i)){n=e[t];break}n&&(n=parseInt(n,10)),COS.authUIState.sendAction("authDRLocked",{retryAfter:n})},validatePreferences:function(e,t,n,r,i){var s=COS.authUIState;if(this.get("accountRepairRequired")){SC.debug("Account requires repair, no need to check preferences");var o;return CloudOSBootstrap.isTermsAndConditionUrl&&(o=function(){var e=CloudOS.authController;e.redirectToPostLoginRedirectUrl()||e.set("userHasAcceptedTerms",!0)}),s.sendAction("accountRequiresRepair",o),YES}if(this.get("hsaChallengeRequired"))return SC.debug("HSA challenge required, no need to check preferences"),e?s.sendAction("authDidValidate"):s.sendAction("authDidNotValidate"),YES;SC.debug("Validating Preferences");if(t!==undefined&&!e)return NO;var u=this.get("statechart"),a=r===330;if(!i){var f=YES;if(r===503)this.handle503(n),f=NO;else if(n&&n.status!==0){SC.warn("responseBody status of KVS response was = ",n.status);if(this._preferencesRetriesSentCount>=COS.MAX_PREFERENCES_RETRIES)SC.warn("Already exceeded the maximum number of get preferences request attempts. Hence marking the request as failure."),s.sendAction
("authDidNotConnect","KVSFailed"),f=NO;else{if(!a){this._preferencesRetriesSentCount++,u.sendAction("resendGetPrefsRequest");return}if(!this._prefsWrongPartitionCheckDone||!a){this._prefsWrongPartitionCheckDone=a,this._preferencesRetriesSentCount=0,u.sendAction("resendLoginOrValidateRequest");return}SC.warn("The response status is %@",r),this._prefsWrongPartitionCheckDone&&SC.warn("We have already done the re-login once to get the correct partition information. Since we are still getting wrong partition information, we mark the login as failure."),s.sendAction("authDidNotConnect","KVSFailed Wrong Partition"),f=NO}}else if(!n||r!==200){SC.warn("KVS returned invalid response.");if(!(this._preferencesRetriesSentCount>=COS.MAX_PREFERENCES_RETRIES)){this._preferencesRetriesSentCount++,u.sendAction("resendGetPrefsRequest");return}SC.warn("Already exceeded the maximum number of get preferences request attempts. Hence marking the request as failure."),s.sendAction("authDidNotConnect","KVSFailed"),f=NO}if(!f)return NO}var l=this.get("accountPreferences"),c=CW.getUrlParameters();if(c.clearPrefs)return window.confirm("Are you sure you want to clear all preferences?")?COS.prefsController.clearPreferences(function(){document.location=document.location.href.replace("clearPrefs","firstrun")}):s.sendAction("authDidValidate"),YES;if(this.shouldShowFirstRun(l,c)){if(!window.CloudOSBootstrap||!CloudOSBootstrap.isOnSupportedMobile)return SC.debug("Missing account preferences; Lets show first run"),s.sendAction("showFirstRun"),NO;l.get("locale")||l.set("locale",CloudOSBootstrap.getLocale())}return SC
w].keys.length>0,T=E!==-1,N=T&&y[E].keys.length>0;for(h=0,p=y.length;h<p;h++){f=y[h],a=f["app-id"],m=f.keys,this._appsRemainingToFetch.removeObject(a),s.push(a);if(f["registry-status"]!==1){var C="Unexpected KVS response for %@".fmt(a);SC.info(C+":"+r),CK.errorCatcher.reportServerError({error:C});continue}g=f["registry-version"];if(a==="account")d=COS.authController.get("accountPreferences"),d&&m&&(d.set("preferencesVersion",g),m.forEach(function(e){e.name.toLowerCase().indexOf("locale")!==-1&&CK.setValueInLocalStorage(e.name,e.data),d.set(e.name,e.data)}),this._lastKnownAccountPrefs=SC.clone(d.prefsHash(),YES),d.set("hasInitialized",YES),this.fetchRegionSettings());else{if(a==="gilligan"&&!o.getAppInfoFor(a))continue;a==="iw"&&(x||(m=y[E].keys)),v={},m&&m.forEach(function(e){v[e.name]=e.data}),l=o.getAppInfoFor(a),l?(l.set("preferencesVersion",g),a==="iw"&&!x&&this.savePreferences(a,v,null),l.set("preferences",v),this.invokeDelegateMethod(u,"passMessageToAllApps","_cloudOSStateChange",{appPreferences:function(){var e={};return e[a]=v,e}()})):o.storePrefsForDynamicApp(a,v,g)}}return s.indexOf("account")!==-1&&(COS.authController.monitorForUsernameChange(),CW.notificationCenter.postNotification("accountPreferencesLoaded")),this.didFetchAllApps(s,n)?(SC.debug("COS: Successfully retrieved all preferences"),t instanceof Function&&t.call(this,YES,undefined,r,e.get("status"))):(SC.info("COS: Fetching preferences for the remaining apps"),this.getPreferences(null,t)),YES},didFetchAllApps:function(e,t){var n=YES,r,i,s;for(i=0,s=t.length;i<s;i++)r=t[i],e.contains(r)||(this._appsRemainingToFetch
.push(r),n=NO);return n},getPreferencesDidFail:function(e,t){var n=e.getPath("request.applicationName"),r=e.get("body"),i="COS: There was an exception while getting the preferences";this.set("currentPrefsResponse",null);if(SC.kindOf(r,SC.Error))SC.error(i+". %@ (%@)".fmt(r.get("message"),r.get("code")));else{var s=r?r.status:null;SC.debug(i+", status “%@”, body “%@”, preferencesStatus '%@'",e.get("status"),r,s)}return this._appsRemainingToFetch=[],t instanceof Function&&t.call(this,NO,undefined,e.get("body"),e.get("status")),YES},savePreferences:function(e,t,n,r){if(SC.typeOf(t)!==SC.T_HASH){SC.debug("COS: Preferences to save is not a hash");return}if(COS.authController.get("isNotAuthenticated")){SC.info("COS: Cannot savePreferences since we are no longer logged In.");return}var i=COS.appsController,s=i.getAppInfoFor(e),o=this.get("delegate"),u,a,f,l=CW.notificationCenter;r=r?r:0;if(s){a=s.get("preferences"),u=s.get("preferencesVersion");if(CW.valuesAreEqual(t,a)){SC.debug("COS: Preferences did not change for “%@”, so will not send to server.",e);return}var c=SC.merge(a,t);s.set("preferences",c),this.invokeDelegateMethod(o,"passMessageToAllApps","_cloudOSStateChange",{appPreferences:function(){var t={};return t[e]=c,t}()})}else{if(e!=="account"){SC.debug("COS: cannot save preferences for unknown app “%@”",e);return}a=COS.authController.get("accountPreferences"),u=a&&a.get("preferencesVersion"),a||CW.fatalError("COS: Account Preferences object not found!");var h=a.get("prefsList"),p=[],d,v,m,g;for(d=0,v=h.length;d<v;d++)m=h[d],t[m]!==undefined&&!CW.valuesAreEqual(this._lastKnownAccountPrefs
[m],t[m])&&(p.push(m),this._lastKnownAccountPrefs[m]=SC.clone(t[m]));if(p.length===0){SC.debug("COS: No account preferences changed"),l.postNotification("accountPreferencesLoaded");return}p.indexOf("regionFormat")!==-1&&(this._isRegionSettingsFetched=NO),p.indexOf("locale")===-1&&p.indexOf("secondaryLocale")===-1&&this.invokeDelegateMethod(o,"passMessageToAllApps","_cloudOSStateChange",{accountPreferences:t})}var y=COS.Request.create({type:"POST",address:"/json/sync",applicationName:e,COPY_KEYS:COS.Request.prototype.COPY_KEYS.concat(["applicationName","newPrefs"])});y.set("reportRequest",YES),f=this.hashToPrefKeys(t);var b={"service-id":"appleprefs",apps:[{"app-id":e,"registry-version":u||"",keys:f}]},w=y.get("address"),E=CK.servicesController.getServiceUrlFor("keyvalue",YES);y.set("address",E+w),y.set("body",b),y.notify(200,this,this.savePreferencesDidSucceed,n,r),y.notify(0,this,this.savePreferencesDidFail,n),SC.debug("COS: Saving preferences for “%@”",e),this.invokeDelegateMethod(o,"savePreferencesRequestWillBeSent"),y.send(),e==="account"&&(COS.authController.monitorForUsernameChange(),l.postNotification("accountPreferencesLoaded"))},clearPreferences:function(e){var t=COS.Request.create({type:"POST",address:"/json/wipe"});t.set("reportRequest",YES);var n=COS.appsController,r,i,s,o,u,a={"service-id":"appleprefs",apps:[]};a.apps.push("account");for(u in COS.apps)COS.apps.hasOwnProperty(u)&&a.apps.push(u);var f=t.get("address"),l=CK.servicesController.getServiceUrlFor("keyvalue",YES);t.set("address",l+f),t.set("body",a),t.notify(200,this,this.clearPreferencesDidSucceed,e),t
.notify(0,this,this.clearPreferencesDidFail,e),SC.debug("COS: Clearing all preferences..."),t.send(a)},clearPreferencesDidSucceed:function(e,t){var n=e.get("body"),r=n.status,i=COS.appsController,s,o,u;if(SC.none(r)||r!==0)return NO;(u=COS.authController.get("user"))&&u.set("preferences",{});for(s in COS.apps)o=i.getAppInfoFor(s),o&&o.set("preferences",{});return t instanceof Function&&t(),YES},clearPreferencesDidFail:function(e,t){return SC.error("COS: There was an error clearing all preferences, status %@",e.get("status")),t instanceof Function&&t(),YES},savePreferencesDidSucceed:function(e,t,n){var r=[],i=[],s=e.getPath("request.applicationName"),o=e.get("body"),u,a,f,l,c,h=NO,p=this.get("delegate");if(!o)return this.savePreferencesDidFail(e);this.fetchRegionSettings();var d=o;if(!d||d.status!==0)return this.savePreferencesDidFail(e,t);f=d.apps[0]["registry-version"],c=d.apps[0].keys,c.forEach(function(e){l=e["update-status"];if(l!==undefined&&l!==0)switch(l){case 3:SC.debug("COS: KVS update status 3 for key:",e.name),r.push(e.name);break;case 4:SC.debug("COS: KVS update status 4 for key:",e.name),i.push(e.name);break;default:SC.debug("COS: error updating preferences key “%@”, update-status is %@",e.name,l),h=YES}});if(h)return this.savePreferencesDidFail(e);(i.length>0||r.length>0)&&n++,r.length>0&&this.invokeLater(function(){var e=this._getPreferencesForKeys(s,r);n<=3&&this.savePreferences(s,e,null,n)}.bind(this),this._waitToRetrySavingPrefs);if(i.length>0){var v=this._getPreferencesForKeys(s,i);n<=3&&this.savePreferences(s,v,null,n)}return u=COS.appsController.getAppInfoFor
(s),u?(a=u.get("preferences"),u.set("preferencesVersion",f),this.invokeDelegateMethod(p,"passMessageToAllApps","_cloudOSStateChange",{appPreferences:function(){var e={};return e[s]=a,e}()})):s==="account"&&(a=COS.authController.get("accountPreferences"),a.set("preferencesVersion",f),this.invokeDelegateMethod(p,"passMessageToAllApps","_cloudOSStateChange",{accountPreferences:a.prefsHash(YES)})),a?(t instanceof Function&&t(),SC.debug("COS: successfully saved preferences for “%@”",s),YES):this.savePreferencesDidFail(e)},savePreferencesDidFail:function(e,t){var n=e.getPath("request.applicationName");return SC.error("COS: There was an error saving the preferences for “%@”, status %@",n,e.get("status")),t instanceof Function&&t(),this.getPreferences(),YES},hashToPrefKeys:function(e){var t=[],n,r;for(n in e)r=e[n],r!==undefined&&t.push({name:n,data:r});return t},allAppPreferencesHash:function(){var e={},t=COS.appsController,n,r;for(r in COS.apps)if(COS.apps.hasOwnProperty(r)){n=t.getAppInfoFor(r);if(!n)continue;e[r]=n.get("preferences")||{},e[r].preferencesVersion=n.get("preferencesVersion")||""}return e},notifyAccountPreferencesDidChange:function(){var e=this.get("delegate");this.invokeDelegateMethod(e,"passMessageToAllApps","accountPreferencesDidChange")},setPreferences:function(e,t,n){var r=COS.authController.get("accountPreferences"),i=COS.appsController,s=this.get("delegate"),o;if(e)for(var u in e)e.hasOwnProperty(u)&&r.set(u,e[u]);this._lastKnownAccountPrefs=SC.clone(r.prefsHash(),YES),r.set("hasInitialized",YES);if(t){for(var a in t){var f=COS.appsController.getAppInfoFor(a)
;f?(o=t[a].preferencesVersion,f.set("preferencesVersion",o),t[a].preferencesVersion&&delete t[a].preferencesVersion,f.set("preferences",t[a])):i.storePrefsForDynamicApp(a,t,o)}this.invokeDelegateMethod(s,"passMessageToAllApps","_cloudOSStateChange",{appPreferences:t})}n&&n.call&&n.call(this,YES,undefined,undefined,undefined,YES)},_getPreferencesForKeys:function(e,t){var n={},r=this._getPreferencesForApp(e);for(var i=0;i<t.length;i++){var s=t[i];n[s]=r[s]}return n},_getPreferencesForApp:function(e){var t;return e==="account"?(t=COS.authController.accountPreferences(),t):(t=this.allAppPreferencesHash(),t[e])},fetchRegionSettings:function(){!this._isRegionSettingsFetched&&COS.regionController&&(COS.regionController.fetchRegionSettings(),this._isRegionSettingsFetched=YES)}}),COS.PushController=SC.Object.extend({webCourierURL:null,pushToken:null,delegate:null,cosPushTopics:[],hasPushConnection:null,registeredPushTopics:null,pushTTL:43200,appsMissingPushTopic:null,missingPushTopics:null,registeredCloudKitContainers:{},init:function(){var e=COS.appsController._appsInfo,t=[],n=[],r;for(r in e)e[r].get("pushTopic")?t.push(r):n.push(r);return this.set("appsMissingPushTopic",n),this.set("pushApps",t),arguments.callee.base.apply(this,arguments)},registerPushTopic:function(e){var t=this.get("registeredPushTopics");if(!t||t.indexOf(e)!==-1)return;var n=this.get("missingPushTopics");SC.typeOf(n)!==SC.T_ARRAY&&(n=[]),n.indexOf(e)===-1&&n.push(e),this.set("missingPushTopics",n),this.registerMissingTopics()},pushTopics:function(){var e=COS.appsController._appsInfo,t,n,r,i;t={};for(i in e)r=e[
i],n=r.get("pushTopic"),n&&r.get("hasAccessToRequiredServices")&&(t[n]=!0);return t=CW.invertHash(t).concat(this.get("cosPushTopics")),t}.property().cacheable(),pushApps:null,isRegisteredToAllTopics:function(){var e=this.get("pushTopics"),t=this.get("registeredPushTopics"),n,r;if(!t||!this.get("pushToken"))return NO;for(n=0,r=e.length;n<r;n++)if(t.indexOf(e[n])===-1)return NO;return YES}.property("registeredPushTopics","pushToken"),initiatePushConnection:function(e,t){e&&this.set("delegate",e),this.startRefreshWebAuthTimer();if(!CK.servicesController.getServiceInfoFor("push")){SC.debug("initiatePushConnection(): PushWS is not available.");return}var n=CK.getValueFromSessionStorage("pushToken");if(n){SC.debug("initiatePushConnection(): Found pushToken from existing session"),this.set("pushToken",n),this.set("missingPushTopics",this.get("pushTopics")),this.registerMissingTopics();return}this.get("pushToken")?this.parkConnectionIfAppropriate():this.initializePush(t)},increaseAttemptCount:function(e){var t="_attemptCount_"+e,n=this[t],r;return this[t]=r=n?n+1:1,SC.info("COS.pushController: Attempt #%@ for '%@'",r,e),r},resetAttemptCount:function(e){var t="_attemptCount_"+e;this[t]=0},scheduleAttempt:function(e){var t="_attemptCount_"+e,n=this[t];n||(this[t]=n=1);var r="_attemptTimer_"+e,i=this[r];if(i){SC.warn("COS.pushController: There is already an attemptTimer for %@",e);return}var s=COS.PUSH_RETRY_WAIT*Math.pow(2,n-1);SC.debug("COS.pushController: Scheduling '%@' in %@ seconds",e,s),this[r]=this.invokeLater(function(){this[r]=null;if(COS.authController.get("isNotAuthenticated"
))return;this[e]()},s*1e3)},parkConnectionIfAppropriate:function(){var e=this.get("pushToken"),t=this;if(!e)SC.info("COS.pushController: Missing pushToken, cannot park a connection without it");else if(this.get("hasPushConnection")===YES){SC.info("COS.pushController: A connection is already parked with pushToken=%@",e);return}if(!window.CloudOS||!CloudOS.isCloudOSClient){this.invokeLater(function(){COS.pushController.parkConnection()},500);return}CloudOS.runWhenReady(function(){t.invokeLater(function(){COS.pushController.parkConnection()},1e3)})},initializePush:function(e){if(this.get("hasPushConnection")===YES&&this.get("pushToken")){SC.warn("We already have an established push connection");return}if(this._isInitiatingPushConnection){SC.warn("Already initiating push connection");return}var t=this.get("pushTTL"),n=this.increaseAttemptCount("initializePush"),r,i=CK.Request.postUrl("/getToken");i.set("serviceName","push"),i.set("isJSON",YES),i.set("reportRequest",YES),i.notify(200,this,function(e){var t=e.get("body"),n=t.pushToken,r=t.pushTokenTTL,i=t.errors,s=this.get("delegate"),o=t.registeredTopics,u,a,f,l;if(i){var c=this.get("missingPushTopics");for(u=0,a=i.length;u<a;u++){f=i[u],l=f.pushTopic,SC.info("COS.pushController: initializePush error - "+f.errorMessage+" - "+l);if(o&&o.indexOf(l)!==-1)continue;SC.typeOf(c)!==SC.T_ARRAY&&(c=[]),c.indexOf(l)===-1&&c.push(l)}this.set("missingPushTopics",c),c.length>0&&this.scheduleAttempt("registerMissingTopics")}return SC.debug("Push token acquired: %@",n),this.set("pushToken",n),this.set("webCourierURL",t.webCourierURL),r&&this.set
("pushTTL",r),CK.setValueInSessionStorage("pushToken",n),s&&s.invokeDelegateMethod(s,"didInitializePush",t),this.set("registeredPushTopics",o),this._isInitiatingPushConnection=NO,this.parkConnectionIfAppropriate(),YES}),i.notify(400,this,function(e){return SC.debug("%@ received from pushws. Reverting to polling for this session.",e.get("status")),this._isInitiatingPushConnection=NO,YES}),i.notify(0,this,function(e){return SC.debug("Failed to aquire push token."),this.set("hasPushConnection",NO),this.set("pushToken",null),this._isInitiatingPushConnection=NO,this.scheduleAttempt("initializePush"),YES}),i.queryParameter("attempt",n),r={pushTopics:e?[e]:this.get("pushTopics"),pushTokenTTL:t},this._isInitiatingPushConnection=YES,i.send(r)},parkConnection:function(e){if(this.get("hasPushConnection")===YES&&!e){SC.warn("We already have an established push connection");return}var t=this.get("webCourierURL")+"?tok=%@&ttl=%@".fmt(this.get("pushToken"),this.get("pushTTL")),n=COS.Request.postUrl(t),r=this.increaseAttemptCount("parkConnection");n.set("timeout",this.get("pushTTL")*1e3),n.set("withCredentials",NO),n.willSend=null,n.willReceive=null,n.notify(200,this,function(e){var t=e.get("body"),n=this.get("delegate");return SC.debug("Received push notification: %@",t),n&&n.invokeDelegateMethod(n,"handlePushNotification",t),this.resetAttemptCount("parkConnection"),this.invokeLater(function(){COS.pushController.parkConnection(YES)},500),YES}),n.notify(408,this,function(e){return SC.debug("409: Request Time-out"),this.set("hasPushConnection",NO),this.scheduleAttempt("parkConnection"),YES})
,n.notify(409,this,function(e){return SC.debug("409: Re-parked multiple connections with the same pushToken"),this.set("hasPushConnection",NO),this.scheduleAttempt("parkConnection"),YES}),n.notify(403,this,function(e){SC.debug("403: The pushToken has expired");var t=this;return SC.info("Unregistering the topics before trying again..."),this.unInitializePush(function(){t.scheduleAttempt("initializePush")}),COS.statsController.recordStat("cloudos","APNS_403_Response"),this.set("hasPushConnection",NO),this.set("pushToken",null),YES}),n.notify(0,this,function(e){return SC.debug("Unknown error: The park push connection closed unexpectedly"),this.set("hasPushConnection",NO),this.scheduleAttempt("parkConnection"),YES}),n.clearQueryParameters(),n.send(),this._pushConnection=n,this.set("hasPushConnection",YES)},registerMissingTopics:function(){var e=this.get("missingPushTopics"),t=this.get("pushToken");if(!e||e.length===0){SC.info("COS.pushController: No missing pushTopics found.");return}if(!t){SC.warn("COS.pushController: You need a pushToken before you can call registerMissingTopics"),this.scheduleAttempt("initializePush");return}var n=this.get("pushTTL"),r=this.increaseAttemptCount("registerMissingTopics"),i=CK.Request.postUrl("/registerTopics");i.set("serviceName","push"),i.set("isJSON",YES),i.set("reportRequest",YES),i.notify(200,this,function(e){var t=e.get("body"),n=t.errors,r=t.registeredTopics,i=this.get("missingPushTopics"),s,o,u,a,f;if(n){SC.typeOf(i)!==SC.T_ARRAY&&(i=[]);for(s=0,o=n.length;s<o;s++)a=n[s],f=a.pushTopic,SC.info("COS.pushController: registerTopics error - "+
:"MMMM d, y",yMMMd:"MMM d, y",yMd:"M/d/yy"},timeFormats:{hmmsszzzz:"h:mm:ss a zzzz",hmsz:"h:mm:ss a z",hms:"h:mm:ss a",hm:"h:mm a"}},calendars:{generic:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],"short":["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"],"long":["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"]},days:{narrow:["S","M","T","W","T","F","S"],"short":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"long":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},eras:{narrow:["ERA0","ERA1"],"short":["ERA0","ERA1"],"long":["ERA0","ERA1"]},dayPeriods:{am:"AM",pm:"PM"}},gregory:{months:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],"short":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"long":["January","February","March","April","May","June","July","August","September","October","November","December"]},days:{narrow:["S","M","T","W","T","F","S"],"short":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"long":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},eras:{narrow:["B","A","BCE","CE"],"short":["BC","AD","BCE","CE"],"long":["Before Christ","Anno Domini","Before Common Era","Common Era"]},dayPeriods:{am:"AM",pm:"PM"}}}},number:{nu:["latn"],patterns:{decimal:{positivePattern:"{number}",negativePattern:"{minusSign}{number}"},currency:{positivePattern:"{currency}{number}",negativePattern:"{minusSign}{currency}{number}"},percent:{positivePattern:"{number}{percentSign}",negativePattern:"{minusSign}{number}{percentSign}"}},symbols:
{latn:{decimal:".",group:",",nan:"NaN",plusSign:"+",minusSign:"-",percentSign:"%",infinity:"∞"}},currencies:{AUD:"A$",BRL:"R$",CAD:"CA$",CNY:"CN¥",EUR:"€",GBP:"£",HKD:"HK$",ILS:"₪",INR:"₹",JPY:"¥",KRW:"₩",MXN:"MX$",NZD:"NZ$",TWD:"NT$",USD:"$",VND:"₫",XAF:"FCFA",XCD:"EC$",XOF:"CFA",XPF:"CFPF"}}};var REGION_FALLBACKS={no:"nb","no-NO":"nb-NO","iw-IL":"he-IL","vi-VI":"vi","zh-CN":"zh-Hans-CN","zh-TW":"zh-Hant-TW","zh-Hant-CN":"zh-Hant"};COS.regionController=SC.Object.create({localeVersion:4,localeURL:function(){var e=COS.authController.get("defaultAssetHostname");return"https://"+e+"/locales/"}.property("COS.authController.defaultAssetHostname"),regionFormattingRules:null,defaultRules:null,_retries:null,init:function(){this.set("defaultRules",COS.defaultRegionFormattingRules)},load:function(e,t){var n=this._getISOnameForRegion(e),r=this.get("localeURL")+this.get("localeVersion")+"/"+n+".json",i=COS.Request.create({type:"GET",address:r,isJSON:YES,withCredentials:NO});i.notify(200,this,this.loadRulesDidSucceed,t),i.notify(0,this,this.loadRulesDidFail,t),i.send()},loadRulesDidSucceed:function(e,t){var n=e.get("body");return t(n),YES},loadRulesDidFail:function(e,t){var n=this.defaultRules;return t(n),YES},fetchRegionSettings:function(){this._retries=1;var e=COS.authController.get("accountPreferences"),t=e.get("regionFormat");if(!t){var n=e.get("locale"),r;n?(e.set("regionFormat",n),r="Setting missing 'regionFormat' for user to '"+n+"'"):(n="en-us",r="Defaulting to 'en-us' because there is no region format set for this user"),t=n,SC.Logger.info(r)}if(t==="en-us"){this.useFallbackRules
),r;if(n){r=n.get("startupUrls");if(t&&!this._isValidStartupUrl(t)){SC.warn("Startup url %@ for %@ is not valid",t,e);return}t=CK.removeQueryParamsToOmitForStartupCaching(t),r[e]!==t&&(SC.debug("Storing new startup url %@ for %@",t,e),r[e]=t,n.set("startupUrls",r),n.commitStartupUrls())}},setStartupInfo:function(e,t){var n=COS.authController.get("accountPreferences");if(n){var r=n.get("startupUrls");if(t===null)r[e]=null,n.set("startupUrls",r),n.commitStartupUrls();else{var i=this._isValidStartupUrl(t.url),s=this._isValidMethod(t.method);if(i&&s){t.url=CK.removeQueryParamsToOmitForStartupCaching(t.url);var o=JSON.stringify(t);o!==r[e]&&(SC.debug("Storing new startup info %@ for %@",t.url,e),r[e]=o,n.set("startupUrls",r),n.commitStartupUrls())}else SC.warn("Startup info for %@ is not valid",e)}}},requestStartup:function(e){var t=COS.appsController.getAppInfoFor(e),n,r=this.getStartupInfo(e),i=r?r.url:null;t||SC.error("COS: Cannot find application information for application “%@”",e);if(!this._isValidStartupUrl(i))return;r&&r.loadCoreTypes&&SC.Module.loadModule("cloudkit/core_types");var s,o=r.method.toLowerCase();o==="get"?(this.setStartupUrl(e,i),s=CK.Request.getUrl(i),t.set("requestedStartupUrl",i)):o==="post"?(this.setStartupInfo(e,r),s=CK.Request.postUrl(i,r.requestPayload).json(),t.set("requestedStartupInfo",r)):o==="put"?(this.setStartupInfo(e,r),s=CK.Request.putUrl(i,r.requestPayload).json(),t.set("requestedStartupInfo",r)):o==="delete"&&(this.setStartupInfo(e,r),s=CK.Request.deleteUrl(i),t.set("requestedStartupInfo",r));if(!s)return;s.set("serviceName",e),s.set("reportRequest"
,YES);var u=r.timeout;u||(u=3e4),s.set("timeout",u),s.notify(200,this,this.fetchStartupDidSucceed,e),s.notify(0,this,this.fetchStartupDidFail,e),s.send(),SC.debug("COS: Requesting startup for “%@” with url %@",e,i)},_isValidStartupUrl:function(e){if(!e)return NO;var t=URI(e);return e&&t.protocol()==="https"&&t.domain()===COS.authController.get("currentDomain")?YES:NO},_isValidMethod:function(e){var t=e.toLowerCase();return t==="get"||t==="post"||t==="put"||t==="delete"},fetchStartupDidSucceed:function(e,t){var n=COS.appsController.getAppInfoFor(t);return n||SC.error("COS: No application info found for application “%@”".fmt(t)),n.set("startupResponse",e),this.notifyStartup(n),YES},fetchStartupDidFail:function(e,t){var n=COS.appsController.getAppInfoFor(t);return n||SC.error("COS: No application info found for application “%@”".fmt(applicationName)),SC.warn("COS: There was an error requesting startup URL for application “%@”".fmt(t)),this.setStartupUrl(t,null),n.set("startupResponse",e),this.notifyStartup(n),YES},notifyStartup:function(e,t){var n=e.get("startupResponse"),r,i,s;if(n){i=n.get("body"),s=n.get("status"),SC.kindOf(i,SC.Object)&&i.get("isError")&&(i=null);var o=CK.currentApplication;if(o)o.invokeDelegateMethod(o.get("delegate"),"didFetchStartup",i,s);else{r=CloudOS.appManagerFor(e.get("name"));if(!r||!r.get("isLoaded")){SC.debug("COS: We received a response to 'startup' for “%@” but cannot notify it yet, as we’re waiting for it to be running",e.get("name"));return}r.passMessage("didFetchStartup",i,s,r.benchmarks())}SC.debug("COS: Gave startup response to the app"),e
){CloudOS.workspaceController.showCentralSpinner(function(){this.gotoState("appleIdLogin")}.bind(this))}}),authDidCancel:function(){CloudOS.get("authPane").remove(),CloudOS.authController.logoutUser(function(){CK.reloadWithReason("Resetting due to auth cancellation message from Auth Widget.")},YES)},appleIdLogin:SC.State.design({enterState:function(){CloudOS.authController.clearUserState(),CloudOS.showAuthPane(),CloudOS.noticeController.setupNotices()},appleWidgetLoaded:function(){SC.debug("Apple Widget has loaded"),CloudOS.get("authPane").set("nowShowing","authBadge");var e=CloudOS.authController.get("showSignup");e&&CloudOS.initializationController.get("accountCreationEnabled")&&(window.location.hash="",this.gotoState("accountCreation"))},appleAuthPaneFailedToLoad:function(){var e=COS.authUIController;CW.Alert.show({message:"Error.AuthDidNotConnect.Title".loc(),description:"Error.AuthDidNotConnect.Description".loc(),middleButton:{title:"Error.AuthDidNotConnect.Support".loc(),action:"support"},rightButton:{title:"Button.OK".loc(),action:function(){this.get("pane").remove(),CloudOS.authController.logoutUser(function(){CK.reloadWithReason("Auth Pane failed to load")},YES)}},leftButton:{title:"Error.Button.Report".loc(),action:function(){this.get("pane").remove(),SC.run(function(){CW.fatalError("The Apple ID auth widget failed to load within the expected timeframe.")})}},remove:function(){this.getPath("pane.modalPane").set("paneFadeOutDuration",0),arguments.callee.base.apply(this,arguments)},fromState:this,support:function(){window.open("Error.AuthDidNotConnect.Support.URL".loc
())}}),e.reportAuthError("login","authDidNotLoad")},loginCompleted:function(e){this.gotoState("appleWidgetLoginCompleted",e)},loginFailed:function(){SC.debug("Login Failed"),COS.authUIController.reportAuthError("login","authDidNotValidate")},repairStarted:function(){SC.debug("Repair Started"),this.gotoState("active.authUI.appleIdRepair")},authDidNotConnect:function(e){SC.debug("Login Failed due to %@".fmt(e)),COS.authUIController.reportAuthError("login",e),CloudOS.UnableToProceedAlert.show({failureReason:e})}}),appleIdRepair:SC.State.design({loginCompleted:function(e){this.gotoState("appleWidgetLoginCompleted",e)},repairFailed:function(){COS.statsController.recordStat("cloudos","AuthWidget_Repair_Failed"),CK.errorCatcher.reportServerError({title:"Error.RepairFailed.Title".loc(),dismissCallback:function(){CloudOS.get("authPane").remove(),CloudOS.authController.invokeLater("logoutUser",400,function(){CK.reloadWithReason("Logged out because Apple ID repair flow was exited due to an error.")})}})},repairDidCancel:function(){var e=COS.authController,t=e.get("isPartiallyAuthenticated"),n=e.get("isPartiallyAuthenticatedForManagedAppleId");t||n?e.logoutUser(function(){var e=t?"HSA":"MAID";CK.reloadWithReason("Cancelling repair for a partially authenticated '%@' account.".fmt(e))},YES):this.gotoState("appleIdLogin")},showApp:function(e){var t=e.appName,n=e.route,r=CloudOS.appManagerFor(t),i=CloudOS.authController,s=CloudOS.appController;s.set("pendingApp",r),r.set("loadInBackground",NO),n&&r.set("route",n),SC.RootResponder.responder.set("defaultResponder",CloudOS.statechart),this.gotoState
{centerX:0,width:570,centerY:-10,height:181},descriptionViewPadding:{top:0,bottom:0},fromState:this,remove:function(){arguments.callee.base.apply(this,arguments),this.fromState.gotoState("appleIdLogin")}})},iCloudLiteUnsupportedBrowser:function(){this._reportAuthError("authDidNotCompleteSetup"),CW.Alert.show({message:"Error.iCloudLiteUnsupportedBrowser.Title".loc(),description:"Error.iCloudLiteUnsupportedBrowser.Description".loc(),rightButton:"Button.OK".loc(),fromState:this,remove:function(){arguments.callee.base.apply(this,arguments),this.fromState.gotoState("appleIdLogin")}})},accountRequiresRepair:function(e){COS.authController.get("repairPayload")?this.accountNeedsAppleIdRepair(e):this.accountNeedsTermsUpdate(e)},accountNeedsAppleIdRepair:function(e){this.gotoState("appleIDAndTermsPane.appleIdRepair",{postValidateCallback:e})},accountNeedsTermsUpdate:function(e){this.gotoState("termsEnforcementAndSubmission",{isForAccountRepair:!0,postValidateCallback:e})},resendLoginOrValidateRequest:function(){SC.debug("sending accountLogin request again."),COS.authController.sendAccountLoginRequest()},resendGetPrefsRequest:function(){SC.debug("sending get preferences request again."),COS.prefsController.getPreferences(null,COS.authController.validatePreferences)},gotoShowTermsAndConditionConfirmation:function(){this.gotoState("termsAndConditionConfirmation")}}),waitForAuthWidgetCompletion:SC.State.extend({enterState:function(){CloudOS.get("authPane").hideSpinnerAndShowAuthPane()},loginCompleted:function(e){var t=CloudOS.authController;t.userDidAuthenticate()}}),signUp:function(){this
.gotoState("accountCreation")},appleIDAndTermsPane:SC.State.extend({initialSubstate:"dummyInitialState",enterState:function(){var e=CloudOS.authController,t=e.get("iCloudLiteAdjustablePane");t||(t=CloudOS.AdjustablePane.create(),e.set("iCloudLiteAdjustablePane",t))},dummyInitialState:SC.State.design(),accountCreation:SC.State.design({enterState:function(){CloudOS.authController.set("iCloudLiteSignUp",YES),CloudOS.appleCreateWidgetController||(CloudOS.appleCreateWidgetController=CloudOS.AppleCreateWidgetController.create());var e=COS.statsController;e.beginStat("cloudos","AppleID_NewAccountCreation"),e.recordWindowUrlStat("cloudos","AppleID_NewAccountCreationStarted");var t=CloudOS.authController.get("iCloudLiteAdjustablePane");CloudOS.appleCreateWidgetController.show(t,CloudOS.initializationController.get("createFrameURL")),t.append(),this._beforeUnloadListener=function(e){var t="Alert.CreateAppleID.BeforeUnloadConfirmation".loc(),n=e||window.event;return n.returnValue=t,t},window.addEventListener("beforeunload",this._beforeUnloadListener)},appleIDPaneFailedToLoad:function(){window.removeEventListener("beforeunload",this._beforeUnloadListener),SC.run(function(){CW.fatalError("The Apple ID create widget failed to load within the expected timeframe.")})},appleIDPaneCompletedWithPayload:function(e){e&&CloudOS.authController.set("repairPayload",e),this.gotoState("termsEnforcementAndSubmission",{isForAccountCreate:!0})},appleIDPaneExited:function(){var e=COS.statsController;e.cancelStat("cloudos","AppleID_NewAccountCreation"),e.recordWindowUrlStat("cloudos","AppleID_NewAccountCreationCancelled"
);var n=e.get("iCloudLiteAdjustablePane");CloudOS.appleCreateWidgetController.show(n,CloudOS.initializationController.get("repairFrameURL"),e.get("repairPayload")),n.append()},appleIDPaneFailedToLoad:function(){SC.run(function(){CW.fatalError("The Apple ID repair widget failed to load within the expected timeframe.")})},appleIDPaneCompletedWithPayload:function(e){e&&CloudOS.authController.set("repairPayload",e),this.gotoState("termsEnforcementAndSubmission",{isForAccountRepair:!0,postValidateCallback:this._postValidateCallback})},appleIDPaneExited:function(){CloudOS.get("authPane").remove(),CloudOS.authController.invokeLater("logoutUser",400,function(){CK.reloadWithReason("Logged out because Apple ID repair flow was exited prematurely by the user.")})},appleIDPaneExitedForError:function(){COS.statsController.recordStat("cloudos","AppleId_RepairExitedForError"),CK.errorCatcher.reportServerError({title:"Error.RepairFailed.Title".loc(),dismissCallback:function(){CloudOS.get("authPane").remove(),CloudOS.authController.invokeLater("logoutUser",400,function(){CK.reloadWithReason("Logged out because Apple ID repair flow was exited due to an error.")})}})},appleIDPaneExitedForPasswordChange:function(){CloudOS.get("authPane").remove(),CloudOS.authController.get("iCloudLiteAdjustablePane").remove(),CW.Alert.show({message:"Alert.RepairAppleID.PasswordChanged.Title".loc(),description:"Alert.AppleIDRepair.PasswordChanged.Description".loc(),rightButton:"Button.OK".loc(),remove:function(){arguments.callee.base.apply(this,arguments),CloudOS.authController.logoutUser(function(){CK.reloadWithReason
("Logged out because the user's password was updated during Apple ID repair.")})}})},reloadAppleIDFlow:function(){this.gotoState(this,{alreadyShownAlert:!0,postValidateCallback:this._postValidateCallback})},exitState:function(){this._cleanUpState(),CloudOS.authController.set("iCloudLiteSignUp",NO)}}),termsEnforcementAndSubmission:SC.State.design({enterState:function(e){var t=COS.statsController,n=CloudOS.authController;this._postValidateCallback=e.postValidateCallback,this._isForAccountCreate=!!e.isForAccountCreate,this._isForAccountRepair=!!e.isForAccountRepair;var r=CloudOS.getUser();(this._isForAccountCreate||r&&r.isLiteAccount())&&CloudOS.authController.set("iCloudLiteSignUp",YES);var i;if(e.isForAccountCreate)t.beginStat("cloudos","AppleID_NewAccountTerms"),t.recordWindowUrlStat("cloudos","AppleID_NewAccountTermsStarted"),i=n.get("repairPayload"),CloudOS.tosController.show(n.get("iCloudLiteAdjustablePane"),i&&{createPayload:i});else if(n.get("accountTermsUpdateRequired")){t.beginStat("cloudos","AppleID_ExistingAccountTerms"),t.recordStat("cloudos","AppleID_ExistingAccountTermsStarted"),i=n.get("repairPayload"),CloudOS.tosController.show(CloudOS.authController.get("iCloudLiteAdjustablePane"),i&&{repairPayload:i});var s=n.get("iCloudLiteAdjustablePane");s&&!s.get("isPaneAttached")&&s.append()}else this.userHasAcceptedTerms()},userHasRejectedTerms:function(){this.updateStatsForTermsUpdateError("Rejected"),this.goBackToAuthUI("user disagreed with terms of service.")},showAlertDialog:function(e,t,n,r){CW.Alert.show({message:e,description:t,fromState:this,rightButton:{title:"Button.OK"
.loc(),action:"goBackToAuth"},goBackToAuth:function(){this.remove(),this.fromState.goBackToAuthUI(n)},middleButton:{title:"Error.Button.Report".loc(),action:function(){var e=this.get("pane");e.get("modalPane").set("paneFadeOutDuration",0),e.remove(),CK.errorCatcher.reportServerError({applicationName:"cloudos",error:r,dismissCallback:function(){e.goBackToAuth()}})}}})},termsUpdateFailed:function(){this.updateStatsForTermsUpdateError("UpdateFailed"),this.showAlertDialog("Error.TermsUpdateFailed.Title".loc(),"Error.TermsUpdateFailed.Description".loc(),"An error occurred while attempting to display terms for user.","Terms display failed")},updateStatsForTermsUpdateError:function(e){var t,n=COS.statsController;this._isForAccountCreate&&(t="AppleID_NewAccountTerms"),this._isForAccountRepair&&(t="AppleID_ExistingAccountTerms"),t&&(n.cancelStat("cloudos",t),e&&n.recordStat("cloudos",t+"_"+e))},userHasAcceptedTerms:function(){var e=COS.statsController,t=CloudOS.authController;CloudOS.blockUserInput(0),t.set("accountTermsUpdateRequired",!1),this._isForAccountCreate&&(e.endStat("cloudos","AppleID_NewAccountTerms",null,{includeLocationUrlDetails:!0}),t.sendAccountCreateRequest("createOrRepairDidComplete","createDidFail")),this._isForAccountRepair&&(e.endStat("cloudos","AppleID_ExistingAccountTerms"),t.sendAccountRepairRequest("createOrRepairDidComplete","repairDidFail"))},createOrRepairDidComplete:function(){var e=CloudOS.authController,t=e.get("user"),n=this._postValidateCallback;e.setDomainSpecificClassNames(),e.get("isPartiallyAuthenticated")?(CloudOS.unblockUserInput(),CloudOS.statechart
.sendAction("showHSA")):(e.clearUserState(),this.gotoState("validatingAuth",{showOnlyLiteApps:this._isForAccountCreate||t&&t.isLiteAccount(),successCallback:function(){CloudOS.unblockUserInput(),n&&n()},failureCallback:function(){CloudOS.unblockUserInput(),CW.fatalError("Validate failed after a create or repair was successfully completed.")}}))},createDidFail:function(){var e=COS.statsController;CloudOS.unblockUserInput(),e.cancelStat("cloudos","AppleID_NewAccountCreation"),e.recordStat("cloudos","AppleID_NewAccountCreationFailed",{includeLocationUrlDetails:!0}),this.showAlertDialog("Error.TermsAcceptFailed.Title".loc(),"Error.TermsAcceptFailed.Description".loc(),"After account Creation Terms update request failed.","Accepting Terms After Account Creation Failed")},repairDidFail:function(){var e=COS.statsController;CloudOS.unblockUserInput(),e.cancelStat("cloudos","AppleID_ExistingAccountRepair"),e.recordStat("cloudos","AppleID_ExistingAccountRepairFailed"),this.showAlertDialog("Error.RepairFailed.Title".loc(),"Error.RepairFailed.Description".loc(),"Terms update request failed.","Accepting Terms After Account Repair Failed")},goBackToAuthUI:function(e){var t=CloudOS.authController;t.cancelAppleIdFlowStats(),t.invokeLater("logoutUser",400,function(){CK.reloadWithReason("Logged out because "+e)})},exitState:function(){this._isForAccountCreate=this._isForAccountRepair=!1,this._postValidateCallback=undefined,CloudOS.authController.set("iCloudLiteSignUp",NO)}}),exitState:function(){var e=CloudOS.authController;e.get("iCloudLiteAdjustablePane").remove(),e.set("iCloudLiteAdjustablePane"
,null)}}),loadFirstRun:SC.State.design({enterState:function(){CW.notificationCenter.postNotification("springboardMayProceed"),SC.Module.loadModule("cloudkit/first_run",this,"moduleDidBecomeReady")},moduleDidBecomeReady:function(){var e=this.statechart.getState("firstRun");if(e&&CK.Photo){var t=e.get("substates").getEach("name");t.indexOf("accountPhotoPicker")===-1&&e.addSubstate("accountPhotoPicker",CK.Photo.photoPicker),this.gotoState("firstRun")}else SC.error("first Run State not found")}}),firstRun:SC.State.design({substatesAreConcurrent:YES,enterState:function(){CloudOS.authController.set("isFirstRunLoaded",YES)},exitState:function(){CloudOS.authController.set("isFirstRunLoaded",NO)},defaultState:SC.State.design({enterState:function(){COS.FirstRun.languagePickerViewController.set("_languages",COS.get("availableLocales")),COS.authUIController.clearMonitorForUsernameChange(),COS.FirstRun.loadFirstRunView();var e=CloudOS.appController.get("isAllAppInfoLoaded");e||(CloudOS.blockUserInput(0),CW.notificationCenter.subscribeToNotification("receivedInfoForAllDynamicApps",this,function(){COS.FirstRun.languagePickerViewController.set("_languages",COS.get("availableLocales")),CloudOS.unblockUserInput()}))},userDidSubmit:function(){COS.FirstRun&&CloudOS.authPane.remove(function(){CloudOS.workspaceController.showCentralSpinner(function(){COS.FirstRun.submitPrefsAndMeCard();if(CloudOS.authController.shouldUsePostLoginRedirectUrl()){CK.reloadWithReason("postLoginRedirectUrl",CloudOS.authController.get("postLoginRedirectUrl"));return}CW.notificationCenter.postNotification("userDidCompleteFirstRun"
("appleWidgetLoginCompleted",e)},loginFailed:function(){SC.debug("HSA Login Failed"),COS.statsController.recordLocationStat("cloudos","AuthWidget_"+this.get("accountType")+"_Flow_Failed"),COS.authUIController.reportAuthError("login","authDidNotValidate")},repairStarted:function(){SC.debug("Repair Started for a HSA account"),this.gotoState("active.authUI.appleIdRepair")},appleWidgetLoaded:function(){this.gotoState("appleIdLogin"),CloudOS.get("authPane").set("nowShowing","authBadge")}}),managedAppleId:SC.State.design({enterState:function(){var e=CloudOS.get("authPane");e||this.gotoState("appleIdLogin"),e&&(e.get("isPaneAttached")?e.show():e.append()),COS.statsController.recordLocationStat("cloudos","AuthWidget_ManagedAppleId_Flow_Started"),e.set("nowShowing","managedAppleIdBadge"),CW.notificationCenter.postNotification("authModuleDidLoad")},loginCompleted:function(e){COS.statsController.recordLocationStat("cloudos","AuthWidget_ManagedAppleId_Flow_Completed"),this.gotoState("appleWidgetLoginCompleted",e)},loginFailed:function(){COS.statsController.recordLocationStat("cloudos","AuthWidget_ManagedAppleId_Flow_Failed"),SC.debug("Managed Apple Id Login Failed"),COS.authUIController.reportAuthError("login","authDidNotValidate")},showAccountSettings:function(){CloudOS.get("authPane").hide(),CloudOS.openApp("settings")},globalAppSwitchWasRequested:function(){var e=CloudOS.appController.get("pendingApp");e&&!e.get("isHSALocked")&&this.gotoState("active.authUI.waitingForApp")},authDidNotConnect:function(){CloudOS.authController.logoutUser(function(){CK.reloadWithReason("validateFailed")
},YES)},repairStarted:function(){SC.debug("Repair Started for a MAID account"),this.gotoState("active.authUI.appleIdRepair")},appleWidgetLoaded:function(){this.gotoState("appleIdLogin"),CloudOS.get("authPane").set("nowShowing","authBadge")}}),exitState:function(){var e=CloudOS.get("authPane");e&&e.hide()}}),COS.CloudOSLite=SC.Object.extend(SC.DelegateSupport,{isCloudOSLite:YES,init:function(){arguments.callee.base.apply(this,arguments);var e=CK.currentApplication,t=CK.currentApplication.get("name");COS.apps[t]||(COS.appsController.createAppInfo(t,{}),COS.apps[t]={});var n=SC.Logger,r=n.get("outputMessagePrefix"),i;r&&r===CK.currentApplication.get("capitalizedName")+": "&&SC.Logger.set("outputMessagePrefix",null);if(e.get("usesAuth")){SC.debug("CloudOSLite: setting the authController delegate to %@",this),COS.authController=i=COS.AuthController.create({delegate:this});if(!i.get("isLoadedFromSiteURL")){SC.error("CloudOSLite: Application was NOT loaded from valid site domain. Exiting here.");return}}},setAppPreferences:function(e){var t=CK.currentApplication,n=t.get("name");t._cos_app_preferences_cache=e,COS.prefsController.savePreferences(n,e)},refreshAppPreferences:function(){var e=CK.currentApplication,t=e.get("name");COS.prefsController.getPreferences(t)},getStartupUrl:function(){var e=CK.currentApplication,t=e.get("name");return COS.startupController.getStartupUrl(t)},requestStartup:function(){var e=CK.currentApplication;return e&&COS.startupController.requestStartup(e.get("name")),this},setStartupUrl:function(e){var t=CK.currentApplication,n=t.get("name");COS.startupController
.setStartupUrl(n,e)},setTitle:function(e){window.document.title=e},reload:function(){CK.reloadWithReason("call to reload")},exit:function(e){CK.errorCatcher.reportServerError({isFatal:!!e,error:"CloudOSLite exit()"})},setRoute:function(e){e&&(window.location.hash=e)},showHelp:function(e){COS.HelpUtils.open(CK.currentApplication,e)},showAppSwitcher:function(){},showSpringBoard:function(){},meCardUpdated:function(){},applicationIsReady:function(){var e=CK.currentApplication,t=e.get("name");SC.debug("CloudOSLite: applicationIsReady() called from %@",t);if(!e.isCloudKitApplication)throw"Application passed to applicationIsReady is not a CK.Application";COS.appsController.getAppInfoFor(t).set("isReady",YES);var n=e.get("delegate");SC.debug("CloudOSLite: Invoking applicationWillBecomeActive and applicationDidBecomeActive"),e.invokeDelegateMethod(n,"applicationWillBecomeActive"),e.invokeDelegateMethod(n,"applicationDidBecomeActive")},startupDataIsLoaded:function(){},didReceiveSpecialResponse:function(e,t,n){},showLocalNotification:function(){},setBadgeCount:function(){},recordStat:function(e,t){var n=CK.currentApplication,r=n.get("name");COS.statsController.recordStat(r,e,t)},beginStat:function(e,t){var n=CK.currentApplication,r=n.get("name");COS.statsController.beginStat(r,e,t)},endStat:function(e,t){var n=CK.currentApplication,r=n.get("name");COS.statsController.endStat(r,e,t)},requestSent:function(){this._outstandingRequests===undefined&&(this._outstandingRequests=0),this._outstandingRequests++},requestReceived:function(e){this._outstandingRequests--;var t=CK.currentApplication,n=
t.get("name");COS.statsController.recordLocationStat(n,"RequestInfo",e)},appWillUnload:function(){},isReadyToTerminateDidChange:function(e){},relayKeyboardShortcut:function(e,t,n){return CW.LOG_KEYBOARD_SHORTCUTS&&SC.info("CloudOSLite: Ignoring keyboard shortcut “%@”",n),NO},relayMouseMove:function(e,t){},performLogin:function(){this._createAuthState()},performLogout:function(){var e=COS.authController,t=e.get("isNotAuthenticated"),n=e.get("isLoggingOut"),r=e.currentLogoutAlert;if(t||n||r){SC.warn("Either the user is not logged in or logout process has already started. Ignoring new logout call.");return}SC.info("COS.CloudOSLite.performLogout");var i=function(e){var t=COS.authController;t.currentLogoutAlert=null,t.set("hsaTrustedBrowser",e),t.logoutUser(null,YES)},s=function(){var e=COS.authController;e.currentLogoutAlert=null},o=e.get("hsaTrustedBrowser");o?e.currentLogoutAlert=CK.logoutAlert(i,s,o):i()},userIsMobileMe:function(){this.loginDidFail()},userIsNotSignedUp:function(){this.loginDidFail()},userIsNotVerified:function(){this.loginDidFail()},userIsUnqualified:function(){this.loginDidFail()},loginDidSucceed:function(e){},loginDidFail:function(e,t){this.userDidNotAuthenticate(YES)},validateDidSucceed:function(e){},validateDidFail:function(e){this._initializeApp(NO)},logoutDidSucceed:function(){},logoutDidFail:function(){},userDidLogout:function(){},userDidNotAuthenticate:function(e){},userDidPartiallyAuthenticate:function(e){},userDidAuthenticate:function(e){var t=CK.currentApplication,n=t.get("name"),r=COS.appsController._appsInfo[n];if(COS.authController.get("isAuthenticated"
.postUrl("/ws/v1/autocomplete/canonicalizePhoneNumbers");return s.set("serviceName","cksharews"),s.set("withCredentials",YES),s.set("isJSON",!0),s.set("timeout",3e4),s.notify(200,null,function(n){var r=n&&n.get("body"),i=r&&r.results;if(i&&i.forEach){var s=i.map(function(e){return e.canonicalized});t(null,s)}else t(CK.MicroResourceContainerServerError.create({message:"Server response to canonicalizePhoneNumbers returned data in an invalid format.",failedKeys:e}),[]);return YES}),s.notify(0,null,function(n){return t(CK.MicroResourceContainerServerError.create({message:"Server request to canonicalizePhoneNumbers failed.",failedKeys:e}),[]),YES}),s.send(i)},normalizePhoneNumber:function(e){e=(e||"").toLowerCase();var t=this;return e=e.replace(/./g,function(e){return t.phoneDigitsToRoman[e]||e}),e&&e.replace(/[^0-9+]/g,"")},phoneDigitsToRoman:{"0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","٠":"0","١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","۰":"0","۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9","०":"0","१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","০":"0","১":"1","২":"2","৩":"3","৪":"4","৫":"5","৬":"6","৭":"7","৮":"8","":"9","๐":"0","๑":"1","๒":"2","๓":"3","๔":"4","๕":"5","๖":"6","๗":"7","๘":"8","๙":"9"}}),CK.PhoneNumbers.CanonicalizationController.sharedInstance=function(){var e=CK.PhoneNumbers.CanonicalizationController;return e._sharedInstance||(e._sharedInstance=e.create())},CK.PhoneNumbers.countryDataController=SC.ObjectController.create({countryPhoneFormats:{},loadCountryData
.get("countryCode"),r=this.get("phoneFormat"),i=this.getInternationalPrefix(e);r&&SC.typeOf(r)===SC.T_HASH&&(t=CK.PhoneNumbers.formatEntryforDigits(e,i,n,r))}return t||(t=CK.PhoneNumbers.normalizeString(e)),t}},CK.PhoneNumbers.PhoneTextFieldUpdater={_deleteKeyPressed:NO,updateOnEachKeyStroke:YES,validateAction:function(){this.set("value",this.get("formattedValue"))},validateTarget:null,inputTextFieldElement:function(){var e=this.$("input:text")[0];return e?e:null}.property().cacheable(),valueObserver:function(){this.invokeLater(function(){var e=this.get("inputTextFieldElement");if(!e){SC.warn("%@ view doesn't have a text input element",this);return}var t=this.get("value"),n=this.get("updateOnEachKeyStroke"),r=this.get("validateAction"),i=this.get("validateTarget")||this,s=this.get("_deleteKeyPressed");if(!n||!r){SC.warn("Since the 2 required parameters updateOnEachKeyStroke and validateAction are not provided we cannot proceed further.");return}if(!t)return;if(!s)if(this.getPath("formattedValue")!==t){this.getCursorPosition(e);if(r&&i){var o=r;SC.typeOf(o)!==SC.T_FUNCTION&&(o=i[r]),SC.typeOf(o)===SC.T_FUNCTION&&o.call(i)}}else this.setCursorPosition(e);this.set("_deleteKeyPressed",NO)},5)}.observes("value"),getCursorPosition:function(e){if(!e)return;var t=e.selectionStart,n=this.get("value"),r;n&&(this.set("_tempCursorPos",t),t===n.length?r=null:r=n.charAt(t),this.set("_tempCharAtCursor",r))},setCursorPosition:function(e){if(!e)return;var t=this.get("_tempCursorPos"),n=this.get("_tempCharAtCursor"),r=this.get("value");if(t){while(r.charAt(t)!==n&&t<r.length)t++;t&&e.setSelectionRange
,420:"cz",421:"sk",423:"li",500:"fk",501:"bz",502:"gt",503:"sv",504:"hn",505:"ni",506:"cr",507:"pa",508:"pm",509:"ht",590:"gp",591:"bo",592:"gy",593:"ec",594:"gf",595:"py",596:"mq",597:"sr",598:"uy",599:"cw",672:"aq",673:"bn",674:"nr",675:"pg",676:"to",677:"sb",678:"vu",679:"fj",680:"pw",681:"wf",682:"ck",683:"nu",685:"ws",686:"ki",687:"nc",688:"tv",689:"pf",690:"tk",691:"fm",692:"mh",800:"xt",850:"kp",852:"hk",853:"mo",855:"kh",856:"la",880:"bd",886:"tw",960:"mv",961:"lb",962:"jo",963:"sy",964:"iq",965:"kw",966:"sa",967:"ye",968:"om",970:"ps",971:"ae",972:"il",973:"bh",974:"qa",975:"bt",976:"mn",977:"np",992:"tj",993:"tm",994:"az",995:"ge",996:"kg",998:"uz"},function(){function t(t,n){var r=e,i=n.lastIndexOf(".");i<0&&CW.fatalError("Property path is not a path (has no `.`): `"+n+"`",{propertyPath:n});var s=n.substr(i+1),o=n.substr(0,i),u=t.getChild(o);return r.child=u,r.property=s,r}var e={child:null,property:null};CW.ChildLayoutPlan=SC.Object.extend({children:null,initMixin:function(){this.children={}},getChild:function(e){var t=this.children,n=t[e];return n||(n=t[e]={name:e,left:0,width:0,right:0,top:0,height:0,bottom:0,centerX:0,centerY:0}),n},get:function(e){var n=t(this,e);return n.child[n.property]},move:function(e,n){var r=t(this,e);this.moveChildProperty(r.child,r.property,n)},resize:function(e,n){var r=t(this,e);this.resizeChildProperty(r.child,r.property,n)},moveUntil:function(e,n,r){var i=t(this,e),s=i.child,o=i.property,u=s[o];switch(n){case">=":u<r&&this.moveChildProperty(s,o,r);break;case"<=":u>r&&this.moveChildProperty(s,o,r);break;default:CW.fatalError("Operator not supported by `moveUntil`: "+
n+"; only <= and >= supported.",{operator:n,propertyPath:e})}},resizeUntil:function(e,n,r){var i=t(this,e),s=i.child,o=i.property,u=s[o];switch(n){case">=":u<r&&this.resizeChildProperty(s,o,r);break;case"<=":u>r&&this.resizeChildProperty(s,o,r);break;default:CW.fatalError("Operator not supported by `moveUntil`: "+n+"; only <= and >= supported.",{operator:n,propertyPath:e})}},moveChildProperty:function(e,t,n){n===undefined&&CW.fatalError("No value passed to `moveChildProperty`",{child:e,property:t});switch(t){case"left":this.moveLeft(e,n);break;case"right":this.moveRight(e,n);break;case"top":this.moveTop(e,n);break;case"bottom":this.moveBottom(e,n);break;case"centerX":this.moveCenterX(e,n);break;case"centerY":this.moveCenterY(e,n);break;default:CW.fatalError("Cannot move property `"+t+"` of `"+e.name+"` in plan",{child:e,plan:this,property:t})}},resizeChildProperty:function(e,t,n){n===undefined&&CW.fatalError("No value passed to `moveChildProperty`",{child:e,property:t});switch(t){case"left":this.resizeLeft(e,n);break;case"right":this.resizeRight(e,n);break;case"width":this.resizeWidth(e,n);break;case"top":this.resizeTop(e,n);break;case"bottom":this.resizeBottom(e,n);break;case"height":this.resizeHeight(e,n);break;default:CW.fatalError("Cannot resize property `"+t+"` of `"+e.name+"` in plan",{child:e,plan:this,property:t})}},moveLeft:function(e,t){var n=e.width;e.left=t,e.right=t+n,e.centerX=t+n/2},resizeLeft:function(e,t){var n=e.right-t;e.left=t,e.width=n,e.centerX=t+n/2},resizeWidth:function(e,t){var n=e.left;e.width=t,e.right=n+t,e.centerX=n+t/2},moveRight:function(e,t){var n=
n.resizeChildProperty(l,"height",p.height),v!==undefined&&n.moveChildProperty(l,"top",h.y+p.top),d!==undefined&&n.moveChildProperty(l,"left",h.x+p.left),y!==undefined&&(d!==undefined?n.resizeChildProperty(l,"right",h.x+h.width-p.right):n.moveChildProperty(l,"right",h.x+h.width-p.right)),b!==undefined&&(v!==undefined?n.resizeChildProperty(l,"bottom",h.y+h.height-p.bottom):n.moveChildProperty(l,"bottom",h.y+h.height-p.bottom)),w!==undefined&&n.moveChildProperty(l,"centerX",h.x+h.width/2),E!==undefined&&n.moveChildProperty(l,"centerY",h.y+h.height/2)}},applyChildLayoutPlanToViews:function(e,n){var r=n.length,i,s,o,u,a,f;for(i=0;i<r;i++)s=n[i],o=this.getPath(s),u=e.getChild(s),a=o.get("parentView"),f=a.convertFrameToView(t,this),o.beginPropertyChanges(),o.adjust("left",u.left-f.x),o.adjust("top",u.top-f.y),o.adjust("width",u.width),o.adjust("height",u.height),o.endPropertyChanges()}}}(),SC.stringsFor("en-us",{"ErrorPage.Message.JavaScriptRequired.Title":"JavaScript is required.","ErrorPage.Message.JavaScriptRequired.Caption":"Please double check and try again.","IndexFile.Title":"Sign in to iCloud - Apple","IndexFile.Meta.Description":"Sign in to iCloud to access your photos, videos, documents, notes, contacts, and more. Use your Apple ID or create a new account to start using Apple services."}),CW.installKeyResponder(),window.devicePixelRatio=window.devicePixelRatio||1,CloudOS=SC.Application.create(SC.DelegateSupport,{NAMESPACE:"CloudOS",VERSION:"2.0.0",isCloudOSClient:YES,isCloudOSMini:CloudOSBootstrap.isCloudOSMini,hostname:window.location.hostname,SPINNER_IMAGE_SRC:window._rhtmlSpinnerSrc
)){SC.warn("CloudOS.run() has been called, but has already been called once.");return}SC.debug("CloudOS window is %@ initially",document.hidden?"hidden":"visible"),SC.Event.add(window,"visibilitychange",SC.RunLoop.wrapFunction(function(){document.hidden?SC.debug("CloudOS window is hidden"):SC.debug("CloudOS window is visible")})),CloudOS.loadLocalizedStrings(),CloudOS.localizationController.relocalizeIfNeeded("CloudOS.run() wants the initial relocalize call"),CloudOS.appController.initializeAppManagers(),CloudOS.statechart.initStatechart();var e=SC.RootResponder.responder,t=CloudOS.workspaceController,n=COS.statsController;e.set("defaultResponder",CloudOS.statechart),e.listenFor("resize".w(),window,t),t.updateTitle(),COS.prefsController.set("delegate",CloudOS),CW.notificationCenter.subscribeToNotification("configBagReceived",CloudOS.initializationController,CloudOS.initializationController.handleConfigBag),SC.Event.add(window,"message",this,SC.RunLoop.wrapFunction(this._messageWasReceived),null,!0),n.recordStat("cloudos","DidLoad",{duration:SC.getCurrentTimeForPerformance()-SC.benchmarkPreloadEvents.headStart});var r=window.location.search;if(r&&(r.indexOf("?sc")===0||r.indexOf("&sc")!==-1)){var i=window.location,s=i.href,o=URI(s),u=CloudOS.appController.getDefaultApp();n.recordStat("cloudos","BookmarkDetection",{hostname:window.location.hostname,buildNumber:SC.buildNumber,masteringNumber:SC.masteringNumber,referrer:function(){var e=document.referrer,t;return e?(t=URI(e),t.hostname()+"/"+t.path()):""}(),defaultApp:u?u.get("name"):""});var a=function(e){i.href="https://"+o.hostname
()+"/not_found/"},f=SC.browser.msie?YES:NO;n.sendStats(f,a)}},loadAlarms:function(){var e=YES;COS.authController&&COS.authController.getPath("user.isLiteAccount")&&(e=NO),e&&CloudOS.runWhenReady(function(){SC.Module.loadModule("cloudos_foundation/alarms","CloudOS.Alarms","initializeAlarmControllers")})},_messageWasReceived:function(e){var t=e.originalEvent,n=URI(t.origin),r=this.get("supportedDomainsToReceiveMessagesFrom"),i=n.domain();if(n.protocol()!=="https"||!r.contains(i)){SC.warn("Ignoring message from invalid domain "+i);return}var s=t.data,o=SC.typeOf(s),u,a,f,l,c,h=NO,p=NO,d=COS.statsController;if(o===SC.T_STRING){var v=CloudOS.APPLE_ID_WIDGET_POST_MESSAGE_PREFIX,m=CloudOS.APPLE_AUTH_WIDGET_POST_MESSAGE_PREFIX,g=NO,y=NO;s.indexOf(v)===0&&(h=YES,s=s.substring(v.length)),s.indexOf(m)===0&&(p=YES,s=s.substring(m.length))}try{o===SC.T_STRING?(u=SC.json.decode(s),t=SC.clone(t),t.data=u):u=s}catch(b){SC.warn(b);return}if(h){CloudOS.appleCreateWidgetController?CloudOS.appleCreateWidgetController.handleMessage(u):(SC.debug("No appleCreateWidgetController to handle message with data "+s),d.recordStat("cloudos","InvalidAppleIdCreateMessage",u));return}if(p){CloudOS.appleAuthWidgetController?CloudOS.appleAuthWidgetController.handleMessage(u):(SC.debug("No appleAuthWidgetController to handle message with data "+s),d.recordStat("cloudos","InvalidAppleIdAuthMessage",u));return}if(!u||!u.isCloudOSMessage)return;if(u.isWindowApplicationMessage){f=CloudOS._applicationWithOpener,f&&f.get("contentWindow").CK.currentApplication._messageWasReceived(e);return}if(u.widgetName==="NewLogin"
){CloudOS.newLoginController.handleMessage(u);return}a=u.appName,f=CloudOS.appManagerFor(a),l=u.methodName,c=u.args||[];if(!f){SC.warn("Could not find an appManager for %@ from %@",a,t.origin);return}f.setIfChanged("buildNumber",u.buildNumber),f.setIfChanged("masteringNumber",u.masteringNumber),c.unshift(t),c.unshift(f),this.respondsTo(l)?this[l].apply(this,c):d.recordStat("cloudos","InvalidCloudOSMessage",u)},_windowMessageWasReceived:function(e){SC.RunLoop.end(),SC.run(function(){this._messageWasReceived(e)},this)},passMessageToAllApps:function(e,t,n){var r=CloudOS.appController.get("loadedApps");if(r){var i=r.length;for(var s=0;s<i;s++){var o=r[s];o.passMessage(e,t,n)}}},focus:function(){try{window.focus()}catch(e){SC.debug("Failed to focus CloudOS client window. Exception text: "+e)}},localeDidLoad:window.localeDidLoad,_ldl:window.localeDidLoad,localeDidLoadDidChange:function(){if(!this.get("localeDidLoad")||!this.get("mainHasCompleted"))return;SC.debug("Got localized strings back AFTER app is loaded and CloudOS.main() has run. Running CloudOS.run() now, because CloudOS.localeDidLoad changed from "+this._ldl+" to "+this.localeDidLoad),CloudOS.run()}.observes("localeDidLoad"),loadLocalizedStrings:function(){SC.debug("Loading localized strings and metrics");var e=window.localizedStrings,t=window.localizedMetrics,n;for(n in e)SC.stringsFor(n,e[n]);for(n in t)SC.metricsFor(n,t[n])},getAppFromURL:function(){var e;if(CloudOS.get("isCloudOSMini"))e=window.location.pathname.match(/([A-z0-9]+)/)[0];else{var t=window.location.hash.match(/(\w+)/);if(t){var n=t[1];if(COS.apps[n])e=n
;else for(var r in COS.apps){var i=COS.apps[r].alternateAppName;i===n&&(e=r,window.location.hash=window.location.hash.replace(n,r))}}}return e},getAppRouteFromHash:function(){var e=window.location.hash,t;return CloudOS.get("isCloudOSMini")?t=0:t=e.indexOf("/"),t===-1?null:e.substring(t+1,e.length)},getShareDetailsFromUrl:function(){var e=window.location.hash,t,n,r,i,s;e=e.length>1?e.substr(1):"",t=/v\/([^\/]+)(\/updated)?/,n=e.match(t);if(n)s={},s.vettingToken=n[1],s.isVettingTokenVetted=!!n[2];else{r=/([^\/]+)\/([a-zA-Z0-9_\-]+)/,i=e.match(r);if(i){var o=i[1],u=i[2],a=o==="share",f,l=CloudOS.authController.get("performedLoginFlow"),c=this.isUserAuthenticated();o==="notes"&&CloudOS.appManagerFor("notes2")&&(o="notes2"),f=COS.appsController.getAppInfoFor(o);if(a||f&&f.get("isCloudOSInterceptingShareUrls"))s={},u.length<=25||c&&!l&&!CK.get("isCarry")?s.shortGUID=u:s.longGUID=u,s.appNameFromUrl=a?null:o}}return s},handleShareDetails:function(e,t){if(e){var n=e.shortGUID,r=e.longGUID,i=e.appNameFromUrl,s=i==="keynote"||i==="numbers"||i==="pages",o=e.vettingToken,u=this.get("statechart"),a=this.isUserAuthenticated();if(n)t&&t.get("isLoaded")?t.passMessage("ckShortGUIDDidChange",n):u.sendAction("goToSharingState",e);else if(r&&s&&a){var f=CloudOS.appManagerFor(i).getAppDomain();window.location.href=URI(f+"/"+i+"/"+r).addSearch("redirectReason","off").toString()+"#:nooverride"}else o&&u.sendAction("goToVettingState",e)}},appManagerFor:function(e){var t=arguments.callee.apps||(arguments.callee.apps=CloudOS.appController.get("apps")),n=arguments.callee.appsList||(arguments.callee.appsList=
CloudOS.appController.get("appList"));if(typeof e=="number")return n&&n[e];if(typeof e=="string")return t&&t[e];if(e&&e.isAppManager)return e;if(!e)return;return t&&t[e.get("name")]},appManagersForPushTopic:function(e){var t=CloudOS.appController.get("apps"),n,r,i=[];for(r in t)n=t[r],n.getPath("appInfo.pushTopic")===e&&i.push(n);return i},appManagersForContainerIdentifier:function(e){var t=CloudOS.appController.get("apps"),n,r,i=[];for(r in t)n=t[r],n.getPath("appInfo.containerIdentifier")===e&&i.push(n);return i},openApp:function(e){var t=CloudOS.workspaceController.get("nowShowing"),n=CloudOS.statechart,r=CloudOS.authController,i=r.get("isPartiallyAuthenticated"),s=r.get("isPartiallyAuthenticatedForManagedAppleId");if(t<CloudOS.AUTH)return;if(!e){if(t===CloudOS.SPRINGBOARD)return;i?n.stateIsEntered("hsa")||n.sendEvent("showHSA"):s?n.stateIsEntered("managedAppleId")||n.sendEvent("gotoManagedAppleId"):n.gotoState("active.springboard")}else CloudOS.appController.set("pendingApp",e=CloudOS.appManagerFor(e)),CW.notificationCenter.postNotification("preparingForAppTransition"),n.sendAction("globalAppSwitchWasRequested")},_userInputBlocked:0,blockUserInput:function(e){this._userInputBlocked||CloudOS.blockInputController.block(e),this._userInputBlocked++},unblockUserInput:function(){if(this._userInputBlocked<=0){SC.warn("User input already unblocked. unblockUserInput has no effect.");return}this._userInputBlocked--,this._userInputBlocked===0&&CloudOS.blockInputController.unblock()},shouldAppHaveFocus:function(){return CloudOS.workspaceController.nowShowing!==CloudOS.APP?NO:CloudOS
:1,POST_LOGIN_REDIRECT:2},CloudOS.API={requestStartup:function(){var e=arguments[0];return e&&COS.startupController.requestStartup(e.get("name")),this},getCurrentlyActiveApplication:function(){},userIsAuthenticated:function(){return CloudOS.authController.get("isAuthenticated")},sessionIsExtendedLogin:function(){},getUser:function(){},getUrlForServiceName:function(e,t){},getStatusForServiceName:function(e,t){},applicationIsReady:function(){var e=arguments[0];e.didBecomeReady()},startupDataIsLoaded:function(){var e=arguments[0];e.startupDataDidLoad()},showAccountSettings:function(){CloudOS.statechart.sendEvent("showAccountSettings")},showAppSwitcher:function(e,t,n){CloudOS.statechart.sendAction("appCalledShowAppSwitcher",n)},showSpringBoard:function(){CloudOS.statechart.sendAction("appCalledShowSpringBoard")},exit:function(e,t){},performSecondaryAuth:function(e){var t=arguments[0],n=t.get("name");e=arguments[2];var r=CloudOS.authController;r.secondaryLogin(r.getPath("user.appleId"),e,null,n)},performLogin:function(){if(COS.authController.get("isAtLeastPartiallyAuthenticated"))return;CloudOS.statechart.gotoState("active.authUI")},performLogout:function(){var e=COS.authController,t=e.get("isNotAuthenticated"),n=e.get("isLoggingOut"),r=e.currentLogoutAlert;if(t||n||r){SC.warn("Either the user is not logged in or logout process has already started. Ignoring new logout call.");return}var i=arguments[0],s=i.get("name"),o=function(e){var t=CloudOS.authController,n=CloudOS.get("isCloudOSMini")?null:function(){CK.reloadWithReason("application "+s+" called performLogout")};t.currentLogoutAlert=
null,t.set("hsaTrustedBrowser",e),i.set("route",null),t.logoutUser(n,YES)},u=function(){var e=COS.authController;e.currentLogoutAlert=null},a=COS.authController.get("hsaTrustedBrowser");a?e.currentLogoutAlert=CK.logoutAlert(o,u,a):o()},revalidateUser:function(){var e=arguments[0],t=arguments[1],n=t.data.id;n?COS.revalidateController.performRevalidate(function(){e.passMessage(CK.RPC_RESPONSE,n)}):COS.revalidateController.performRevalidate(function(){CloudOS.appController.userDidRevalidate()})},showHelp:function(e){},switchToApplication:function(e,t){var n=arguments[0],r=CloudOS.appManagerFor(arguments[2]);t=arguments[3];if(!n||!n.get("isActive")){SC.debug("%@ is not allowed to switch to a different app while in background",n.get("name"));return}if(!r){SC.debug("Cannot switch to unknown app %@",e);return}r.set("route",t),r.set("loadReason",CK.LOAD_REASON_APP_SWITCH),CloudOS.appController.set("pendingApp",r),CloudOS.statechart.sendAction("appCalledSwitchToApplication")},getAppLoadReason:function(){},mailTo:function(e,t,n,r,i){},setRoute:function(e){var t=arguments[0];e=arguments[2];if(!t)return;t.set("route",e)},getRoute:function(){},getAccountPreferences:function(){},getAppPreferences:function(e){},setAppPreferences:function(e){var t=arguments[0],n=t.get("name");e=SC.clone(arguments[2],YES),t._cos_app_preferences_cache=e,COS.prefsController.savePreferences(n,e)},refreshAppPreferences:function(){var e=arguments[0],t=e.get("name");COS.prefsController.getPreferences(t)},setStartupUrl:function(e){var t=arguments[0],n=t.get("name");e=arguments[2],COS.startupController.setStartupUrl
(n,e)},setStartupInfo:function(e){var t=arguments[0],n=t.get("name");e=arguments[2],COS.startupController.setStartupInfo(n,e)},getRequestedStartupUrl:function(){},getEnvironment:function(){},setTitle:function(e){var t=arguments[0];e=arguments[2],t&&t.set("title",e)},reload:function(){var e=arguments[0];e.reloadInPlaceIfAppropriate()},reloadWhenCanTerminate:function(){var e=arguments[0],t=arguments[1];e.reloadInPlaceIfAppropriateWhenCanTerminate(t)},showLocalNotification:function(){SC.warn("showLocalNotification has been deprecated. Use sendLocalNotification() instead."),this.sendLocalNotification.apply(this,arguments)},sendLocalNotification:function(e,t,n,r){var i=arguments[0],s=i.get("name"),o,u,a,f,l,c,h;e=arguments[2],t=arguments[3],n=arguments[4],r=arguments[5],n&&CloudOS.appManagerFor(n)&&(s=n),SC.typeOf(e)===SC.T_STRING?(o=arguments[2],u=arguments[3],a=arguments[4],f=arguments[5],l=arguments[6],h=YES,c=NO):e&&(o=e.alertTitle,u=e.alertDescription,a=e.actionPayload,f=e.badgeCount,l=e.soundPath,c=e.isDismissable!==undefined?!!e.isDismissable:YES,h=e.omitWhenActive!==undefined?!!e.omitWhenActive:YES);var p=u||o||f||l?{alert:u,alertTitle:o,badge:f,sound:l}:undefined;CloudOS.notificationsController.handlePushNotification(SC.merge(t,{aps:p,icloud:a,omitWhenActive:h,isDismissable:c}),YES,s,r)},setBadgeCount:function(e){var t=arguments[0];e=arguments[2],SC.typeOf(e)===SC.T_NUMBER&&e>-1&&t.set("badgeCount",e)},recordStat:function(e,t){var n,r;arguments.length>=3?(n=arguments[0],r=n.get("name"),e=arguments[2],t=arguments[3]):r=t&&t.appName?t.appName:"cloudos",SC.empty(t)?t={appName
(e,NO):{},e.applicationName=r,t&&(e.applicationLog=t),COS.handleApplicationCrash(e)},recordApplicationMessage:function(e,t){var n=arguments[0],r=n.get("name");e=arguments[2],t=arguments[3];var i=t?": "+JSON.stringify(t):"";SC.info('applicationMessage "%@" received from %@%@',e,r,i),COS.statsController.recordLocationStat(r,e,t),e==="OnErrorException"&&n.recordException("OnErrorException: "+i)},didReceiveSpecialResponse:function(e,t,n){SC.typeOf(e)!==SC.T_NUMBER&&(e=arguments[2],t=arguments[3],n=arguments[4]);var r;switch(e){case 330:this._suspendedCount=this._suspendedCount?++this._suspendedCount:1;if(this._suspendedCount>3){SC.warn("Have reached suspendCount max for 330 responses. Will stop retrying."),this.invokeLater(function(){CloudOS._suspendedCount=0},1e4);return}CloudOS.authController.validateUser(function(){CloudOS.appController.userDidRevalidate()});break;case 421:case 401:try{r=SC.json.decode(t)}catch(i){SC.info("Cannot decode response: "+t)}CloudOS.authController.logoutUser(function(){CK.reloadWithReason("received a "+e+" in didReceiveSpecialResponse")},YES);break;case 403:window.location.hash="#:showlogin",CK.reloadWithReason("received 403 in didReceiveSpecialResponse");break;case 503:CloudOS.statechart.sendAction("showServiceLocked",n)}},requestSent:function(){this._outstandingRequests===undefined&&(this._outstandingRequests=0),this._outstandingRequests++},requestReceived:function(e,t,n,r){this._outstandingRequests--;var i;e&&SC.typeOf(e)!==SC.T_HASH?(i=arguments[0].get("name"),e=arguments[2],t=arguments[3],n=arguments[4],r=arguments[5]):i="cloudos",e&&COS.statsController
.recordLocationStat(i,"RequestInfo",e);if(t===undefined||t===null)return;var s=String(t)[0];if(s==="5"||s==="0"){var o=CK.isURLInCarryPartition(n)?"ServerErrorOrTimeoutInCarry":"ServerErrorOrTimeout",u=URI(n),a=u.hostname(),f=(a+u.path()).replace(/[0-9]{3}/g,"…");COS.statsController.recordStat(i,o,{status:t,sanitizedUrl:f,serverHostname:a,responseBody:r})}},relayKeyboardShortcut:function(e,t,n){CW.performKeyEquivalent(n)},relayMouseMove:function(e,t,n){CloudOS._lastActivityEpoch=(new Date).getTime()},meCardUpdated:function(){SC.debug("meCardUpdated(), will grab latest version..."),CK.meCardController.getMeCard()},getClientId:function(){},isReadyToTerminateDidChange:function(){var e=arguments[0],t=arguments[2];e.set("isReadyToTerminate",t)},windowApplicationHasInitialized:function(){},appWillUnload:function(e){var t=arguments[0],n=t.get("name");e=arguments[2],e&&(SC.info("appWillUnload log from %@:",n),SC.info(e));if(!CloudOS._receivedBeforeUnload){if(t.get("loadReason")===CK.LOAD_REASON_RELOAD)return;CloudOS.appController.get("currentApp")===t&&t.get("isLoaded")?(SC.info("appWillUnload: Reloading application, most likely because user chose to Reload Frame"),CloudOS.appController.reloadApplication(n)):t.teardown()}},setAppBanner:function(e,t){},currentAppName:function(){},getQuotaData:function(){},isUserOverQuota:function(){},refreshQuotaData:function(){},fetchIcon:function(e,t,n,r){var i=null,s=null;if(typeof e=="string"){n||(n=window.devicePixelRatio);if(window.CoreTypes){var o=window.CoreTypes.API.fetchIcon(e,t,n,r);return o}return{}}i=arguments[0],s=arguments[1],e=arguments
[2],t=arguments[3],n=arguments[4],r=arguments[5];var u=s.data.id;n||(n=window.devicePixelRatio);if(!window.CoreTypes)SC.Module.loadModule("cloudkit/core_types",this,function(){var s=window.CoreTypes.API.fetchIcon(e,t,n,r);i.passMessage(CK.RPC_RESPONSE,u,s)}.bind(this));else{var a=window.CoreTypes.API.fetchIcon(e,t,n,r);i.passMessage(CK.RPC_RESPONSE,u,a)}},getConformingTypes:function(e,t,n){var e=arguments[0],r=t.data.id;if(!window.CoreTypes)SC.Module.loadModule("cloudkit/core_types",this,function(){var t=window.CoreTypes.API.getConformingTypes(n);e.passMessage(CK.RPC_RESPONSE,r,t)}.bind(this));else{var i=window.CoreTypes.API.getConformingTypes(n);e.passMessage(CK.RPC_RESPONSE,r,i)}},fetchAppUrl:function(e,t,n,r){var i=CloudOS.appManagerFor(r),s=i&&i.get("path");e.passMessage("didFetchAppUrl",n,s)},completeAuthentication:function(e,t,n){var r=CloudOS.appManagerFor(n)||e,i=e.get("name");if(CloudOS.authController.get("userAuthenticationState")!==CK.AuthenticationStateEnum.PARTIALLY_AUTHENTICATED_HSA){SC.info("completeAuthentication(): User is not partially authenticated, nothing to do here.");return}CloudOS.appController.exitApplication(i,CK.EXIT_NON_FATAL,null,r)},loadRulesForRegions:function(e,t,n){var r=t.data.id;COS.regionController.load(n,function(t){e.passMessage(CK.RPC_RESPONSE,r,t)}.bind(this))},resolveCKShortGUID:function(){},replaceCurrentApp:function(e){},getWindowMinimumSize:function(){},isOnSupportedMobile:function(){},getSecureChannelInfo:function(){},getDefaultAssetHostname:function(){}},CloudOS._cloudOSAPIMethodNames=function(){var e=[],t;for(t in CloudOS.API)CloudOS
.preferredLanguage)&&(o=String.preferredLanguage);var u=CW.getUrlParameters(),a=u.locale;return a&&n.contains(a)&&(o=a),o||(r?SC.debug("Neither Primary Locale “%@” or Secondary Locale “%@” is supported by app “%@”. Hence using “en-us” as the locale for this app.",i,s,e):SC.debug("Since there is no account prefs yet, we will set the locale of “%@” as en-us",e),o="en-us"),o},locationHash:function(){var e="",t=this.get("route");return CloudOS.get("isCloudOSMini")||(e=this.get("name")),e+=CloudOS.workspaceController.retainedHash(),t&&(e&&(e+="/"),e+="%@".fmt(t)),e}.property("route"),route:null,routeDidChange:function(){var e=this.get("route");this.passMessage("_cloudOSStateChange",{route:e}),this.passMessage("routeDidChange",e)}.observes("route"),contentWindow:function(){var e=this.get("view");return e?e.get("contentWindow"):null}.property("view"),isFailed:NO,isActive:NO,isWaiting:NO,isLoaded:NO,isIntermediateFailedToLoad:NO,startupDataHasBeenLoaded:NO,loadInBackground:NO,isReadyToTerminate:YES,title:null,view:null,loadReason:null,shareInfo:null,preDisplayAction:null,preDisplayActionArgs:null,postDisplayAction:null,postLoadAction:null,getReady:function(){if(this._view)return;var e=this.get("name"),t=YES,n=this.get("appInfo");n.preloadCoreTypes&&SC.Module.loadModule("cloudkit/core_types"),SC.debug("Beginning to load %@",e),COS.startupController.requestStartup(e);var r=CloudOS.AppFrameView.create({minWidth:this.get("minWidth"),minHeight:this.get("minHeight"),app:this});this.set("view",this._view=r),r.get("usingPrevCreatedIframe")||CloudOS.getPath("mainPage.mainPane.appsView").addAppFrame
(r),this.set("isReadyToTerminate",YES),this.set("isWaiting",YES),CloudOS.get("isCloudOSMini")&&(t=NO),t&&(this._checkLoadFailureTimer=this.invokeLater("_checkLoadFailure",CloudOS.APP_LOAD_TIMEOUT*1e3),this._checkIntermediateLoadFailureTimer=this.invokeLater("_checkIntermediateLoadFailure",CloudOS.APP_LOAD_INTERMEDIATE_TIMEOUT*1e3)),this._iframeWasCreated=YES;var i=n.containerIdentifier;i&&COS.pushController.registerForCloudKitSubscriptions(i,e)},getReadyInBackground:function(){CloudOS.appController.get("loadingApp")!==this?(this.set("loadInBackground",YES),this.getReady()):SC.info("%@ is already being loaded, hence no need to load it in the background.",this.get("name"))},isLoadedObserver:function(){var e=this.get("isLoaded"),t=CloudOS.appController.get("loadedApps");t||(t=[]),e?t.push(this):t.indexOf(this)!==-1&&t.removeObject(this),CloudOS.appController.set("loadedApps",t)}.observes("isLoaded"),shouldRelocalize:function(e,t){var n=this.preferredLocale(),r=this._currentAppLocale,i=n!==r||t,s=this.get("name");return this.get("view")&&SC.debug("Language check for app '%@': "+r+" -> "+this.preferredLocale()+". We "+(i?"WILL":"WILL NOT")+" relocalize '%@.'",s,s),i},relocalize:function(e,t){this.get("appInfo").calculateAndSetLocalizedNames(String.preferredLanguage,CloudOS.authController.getPath("user.countryCode"));if(!this.shouldRelocalize(e,t))return;this.reloadInPlaceIfAppropriateWhenCanTerminate()},reloadInPlaceIfAppropriate:function(){var e=this.get("isActive"),t=this.get("view"),n=e&&t!==null,r=CloudOS.appController.get("pendingApp"),i=this._view,s=this.get("name");if(n){var o=
CloudOS.authController;if(r&&!this.get("canLaunchWithOneFactor")&&COS.authController.getPath("user.hsaEnabled")&&!o.get("delayedTearDownUsed")){o.set("delayedTearDownApp",this),o.set("delayedTearDownUsed",!0);return}i.get("usingPrevCreatedIframe")&&(i.get("layer").oldIframe=YES),this.set("view",this._view=null),this.teardown(YES),this._isReloadingInPlaceFromOldView=t,this.set("loadReason",CK.LOAD_REASON_RELOAD),CloudOS.blockUserInput(10),this.invokeLater(function(){this.set("loadInBackground",NO),this.getReady()},1e3)}else this.teardown()},teardown:function(e){if(!this._iframeWasCreated)return;var t=this.get("appInfo"),n=this.get("name");SC.debug("Ensuring that %@ is torn down.",n),t&&CloudOS.appController.applicationWillClose(t);var r=this.get("view");r&&r.destroy(),this.set("view",this._view=null),this._checkLoadFailureTimer&&this._checkLoadFailureTimer.invalidate(),this.invalidateIntermediateLoadFailureTimer(),this.get("isFailed")&&this.set("hasFailedOnce",YES),this.set("isFailed",NO),this.set("isWaiting",NO),e||this.set("isActive",NO),this.set("loadReason",null),this.set("isLoaded",NO),this._messageState=this._DID_SUSPEND,this._iframeWasCreated=NO,this._currentAppLocale=null,t&&(t.set("requestedStartupUrl",null),t.set("requestedStartupInfo",null),t.set("startupResponse",null),t.set("isReady",NO)),this.set("isReady",NO),COS.statsController.endAllBenchmarkStats(n)},teardownWhenCanTerminate:function(e){this._invokeWhenCanTerminate("teardown",e)},reloadInPlaceIfAppropriateWhenCanTerminate:function(e){this._invokeWhenCanTerminate("reloadInPlaceIfAppropriate",e)},_invokeWhenCanTerminate
(CloudOS.bannerManager.setAppBanner(null),this._showingSlowConnectionMsg=NO,COS.statsController.endStat("cloudos","ShowSlowConnectionBannerDuration",{wasCancelled:!!e}))},invalidateIntermediateLoadFailureTimer:function(e){this._checkIntermediateLoadFailureTimer&&(this._checkIntermediateLoadFailureTimer.invalidate(),this._removeIntermediateLoadFailureBanner(e))},_didFailToBecomeReady:function(){this.set("isWaiting",NO),this.get("isActive")&&this.set("isActive",NO),this.invalidateIntermediateLoadFailureTimer(),this._isReloadingInPlaceFromOldView&&CloudOS.unblockUserInput(),this._isReloadingInPlaceFromOldView=null,CloudOS.appController.get("pendingApp")===this&&CloudOS.statechart.sendAction("applicationDidFailToBecomeReady"),CloudOS.getPath("mainPage.mainPane.appsView").removeAppFrame(this._view)},didBecomeReady:function(){this.invalidateIntermediateLoadFailureTimer();var e=SC.Benchmark,t=this.get("name");e.end("Waiting for application to become visible",t);if(!this.get("isLoaded")){SC.debug("Received didBecomeReady for "+this.get("name")+", which is no longer loaded. Ignoring call.");return}if(this.get("isFailed"))return;COS.startupController.notifyStartup(this.get("appInfo"),YES),window[t.substr(0,2)]=this.get("contentWindow");var n=function(){var e=CloudOS.appController,n=this._isReloadingInPlaceFromOldView;this._isReloadingInPlaceFromOldView=null,n&&CloudOS.unblockUserInput();if(!this.get("isLoaded")){this.get("isActive")&&!n&&this.set("isActive",NO),SC.debug("Finishing didBecomeReady for "+this.get("name")+", which was unloaded since didBecomeReady was called. Aborting.");
return}this.set("isReady",YES),this.set("isWaiting",NO),e.get("pendingApp")===this&&!this.get("loadInBackground")&&CloudOS.statechart.sendAction("applicationDidBecomeReady");var r=this.get("postLoadAction");if(r){var i=[],s=this.get("shareInfo");s&&i.push(s),r.apply(this,i)}this.set("postLoadAction",null),e.set("loadingApp",null),n&&(n._shouldBeDestroyedAfterNextSwitch=YES,this.show(YES));if(CloudOS.get("isCloudOSMini")&&!CloudOS._applicationWithOpener)try{var o=CloudOS.getOpenerWithCloudOS();o&&o.CloudOS.windowApplicationIsKnown(window)&&(SC.info("main(): Found parent CloudOS application"),o.CloudOS.windowApplicationHasInitialized(window,t,YES),CloudOS._applicationWithOpener=this)}catch(u){SC.warn("didBecomeReady: There was a problem finding or communicating with the opener"),SC.warn(u)}};CloudOS.APP_POST_READY_DELAY?this.invokeLater(n,CloudOS.APP_POST_READY_DELAY):n.call(this)},startupDataDidLoad:function(){this.set("startupDataHasBeenLoaded",YES),this.get("isWaiting")||SC.Benchmark.end("Waiting for startup data",this.get("name"))},show:function(e,t){if(!this.get("isReady"))return;this.notifyPropertyChange("title");var n=CloudOS.getPath("mainPage.mainPane.appsView");n.showApp(this,e,t)},hide:function(e){if(!this.get("isReady"))return;var t=CloudOS.getPath("mainPage.mainPane.appsView");t.hideApp(this,e)},init:function(){this.get("displayName")||this.get("appInfo").set("displayName",this.getPath("appInfo.capitalizedName")),arguments.callee.base.apply(this,arguments),CW.notificationCenter.subscribeToNotification("relocalize",this,"relocalize")},benchmarks:function(){var e=SC.
Benchmark._statFor(this.get("name"));return e&&e._times&&e._times[0]?e._times[0]._subStats:null},focus:function(){var e=this.get("view");if(!e)return;e.focus()},_validatePostMessageData:function(e){if(!e||typeof e!="object")return!0;if(e.isObservable&&SC.kindOf(e,SC.Object))return SC.error("_validatePostMessageData: Attempt to serialize SC.Object in:"+e.toString()),!1;for(var t in e)if(e.hasOwnProperty(t)&&!this._validatePostMessageData(e[t]))return!1;return!0},passMessage:function(e){var t=this.get("contentWindow");if(!t)return;var n=SC.$A(arguments);n.shift();var r=this.getPath("view.layer.src"),i=URI(r),s="https://"+i.hostname();this._callCloudOSMethod(t,s,e,n)},_callCloudOSMethod:function(e,t,n,r){var i={isCloudOSMessage:!0,methodName:n,args:r};this._validatePostMessageData(i)||SC.error("Attempt to serialize invalid data in: "+JSON.stringify(i));var s=this.get("name"),o=s+n;this._lastMessageSignature!==o&&(SC.info('_callCloudOSMethod: "%@" to %@',n,s),this._lastMessageSignature=o);var i=JSON.stringify(i,function(e,t){return this.hasOwnProperty(e)?t:undefined});e.postMessage(i,t)},sleep:function(){this.passMessage("_sleep")},wake:function(){this.passMessage("_wake")},ensureWillSuspend:function(){this.ensureDidBecomeActive();if(this._messageState!==this._DID_BECOME_ACTIVE)return;this._messageState=this._WILL_SUSPEND,this.passMessage("applicationWillSuspend"),CloudOS.appController.applicationWillClose(this)},ensureDidSuspend:function(){if(this._messageState!==this._WILL_SUSPEND)return;this._messageState=this._DID_SUSPEND,this.passMessage("applicationDidSuspend")},ensureWillBecomeActive
(),t=e.showApps;return t?t.split(","):null}.property().cacheable(),removeInvalidIframes:function(){var e=SC.$("iframe");e.forEach(function(e){if(e.id=="auth-frame")return;COS.apps[e.name]||(e.parentNode?(SC.info("Removing iframe for invalid app %@",e.name),e.parentNode.removeChild(e)):SC.warn("Unable to remove invalid iframe for app %@",e.name))})},initializeAppManagers:function(){var e={},t=CloudOS.appController.getDefaultAppName(),n=CloudOS.getAppRouteFromHash(),r=[],i=this.get("showApps"),s,o,u,a,f,l,c,h;for(f=0,l=CloudOS.displayApps.length;f<l;f++){a=CloudOS.displayApps[f],s=a.name,u=COS.appsController.getAppInfoFor(s),u||CW.fatalError("There is no appInfo for app “%@”".fmt(s));if(u.isBeta&&!CK.get("isBeta")&&!u.isWWW)continue;i&&i.indexOf(s)!==-1&&(a.isHidden=NO),c=s===t?n:null;if(u.get("isDynamicallyLoaded")){this.requestInfoJSONForApp(s,CK.get("isCarry"),c);continue}r.push(e[s]=CloudOS.AppManager.create(a,{appInfo:u,index:r.length,route:c}))}this.set("appList",r),this.set("apps",e)},detectAndLoadAdditionalApps:function(e){var t=this.get("apps"),n,r=this.get("showApps"),i=COS.appsController;if(r)for(var s=0;s<r.length;s++){var o=r[s];if(!COS.authController.get("isRevalidatingUser")){var u=i.getAppInfoFor(o);if(u){var a=u.get("preferences"),f=u.get("preferencesVersion");i.storePrefsForDynamicApp(o,a,f),this.removeApp(o,YES)}}e[o]={isFuture:CK.get("isFuture"),isBeta:CK.get("isBeta")}}for(n in e){var l=t[n];if(l){if(l.get("isHidden")){var c=!e[n].isHidden;c&&SC.debug("Existing app “%@” is now made visible",n),l.set("isHidden",!c),this.notifyPropertyChange("appList")}continue}
var u=i.getAppInfoFor(n);if(u&&u.get("isBeta")&&!CK.get("isBeta")&&!u.get("isWWW"))continue;COS.apps[n]=SC.merge(e[n],COS.apps[n]),this.requestInfoJSONForApp(n)}this.removeInvalidIframes()},requestInfoJSONForApp:function(e,t,n){var r=this.get("pendingInfoJSONRequests");if(r[e]||CloudOS.appManagerFor(e))return;var i=COS.apps[e],s="https://"+window.location.hostname,o,u;if(CloudOS.get("isCloudOSMini")&&this.getDefaultAppName()!==e)return;CK.get("isBeta")||CK.get("isCarry")?t?(s="https://"+CloudOS.authController.get("defaultAssetHostname"),SC.debug("Application %@ is not marked to appear in beta or future, loading www",e)):o=YES:CK.get("isFuture")&&t&&(u=YES);var a=s+"".fmt(e);CW.notificationCenter.postNotification("requestedInfoForDynamicApp",e);var f=CW.Request.getUrl(a+"").set("isJSON",YES).set("attachIdentifyingHeaders",NO).header("Content-Type","text/plain").notify(this,"appInfoDidLoad",e,a,o,u,n);CloudOS.get("isCloudOSMini")&&f.set("timeout",null);var l=URI(f.getFullAddress()).host();l&&l!==window.location.hostname&&(f.set("withCredentials",NO),f.set("useCrossDomain",YES)),f.send(),r[e]=f},appInfoDidLoad:function(e,t,n,r,i,s){var o=e.get("status")===200?e.get("body"):null,u,a,f=COS.appsController,l=CloudOS.authController,c=l.get("hsaChallengeRequired"),h=l.get("pcsDeleted"),p=l.getPath("user.hsaEnabled");delete this.pendingInfoJSONRequests[t];if(o&&SC.typeOf(o)===SC.T_HASH){u=f.getAppInfoFor(t);if(u){SC.debug("Adding additional data for "+t);for(a in o)SC.none(u.get(a))&&u.set(a,o[a])}else o=SC.merge(o,COS.apps[t]),SC.debug("Setting up appInfo for "+
t),u=f.createAppInfo(t,o),f.setAppLockInfo(u,h,p,c);r&&u.set("isBeta",YES),i&&u.set("isFuture",YES)}if(!u||!o){e.get("status")!==404&&SC.warn("There was a problem loading the info.json for %@",t),r||i?(SC.info("Could not find info.json for %@ on %@. Attempting www.",t,r?"beta":"future"),this.requestInfoJSONForApp(t,YES,s)):(CW.notificationCenter.postNotification("receivedInfoForDynamicApp",t,YES),this.checkIfAllDynamicAppsAreLoaded());return}if(CloudOS.authController.get("isAtLeastPartiallyAuthenticated")&&!u.get("hasAccessToRequiredServices")){SC.info("User does not have access to the requiredServices for %@",t);return}var d=SC.merge(CloudOS.displayInfoFor(t),{name:t,isDynamicallyLoaded:YES,appInfo:u,route:s,isBeta:r?YES:NO}),v=CloudOS.AppManager.create(d);this.getPath("pendingApp.name")==="notes"&&t==="notes2"&&this.set("pendingApp",v),n+=v.preferredLocale()+"/",CK.get("isBeta")&&(n=n.replace("https://www.icloud.com/","https://beta.icloud.com/www/")),CK.get("isFuture")&&(n=n.replace("https://www.icloud.com/","https://future.icloud.com/www/")),CK.get("isCarry")&&(n=n.replace("https://www.icloud.com/","https://carry.icloud.com/www/")),v.set("appIconType","image"),v.set("appIconUrl",n+"icon.png"),v.set("appIconUrl2x",n+"icon@2x.png"),o.showsPushNotifications&&!v.get("notificationIcon")&&v.set("notificationIcon",n+(window.devicePixelRatio>1?"icon_notification@2x.png":"icon_notification.png"));var m="AppTitle."+t,g=m.loc();if(g===m){var y={};y["AppTitle."+t]=o.displayName,y["AppTitleBar."+t]=o.titleName||o.displayName,SC.stringsFor(SC.Locale.currentLocale.language,y)}else v.set
("displayName",g);var b=o.pushTopic;COS.pushController&&b&&(SC.info("Registering pushTopic %@ for dynamic app %@",b,t),COS.pushController.registerPushTopic(b)),this.addAppManager(v),CW.notificationCenter.postNotification("receivedInfoForDynamicApp",t),this.checkIfAllDynamicAppsAreLoaded()},checkIfAllDynamicAppsAreLoaded:function(){this.get("isAllAppInfoLoaded")&&(this.set("pendingInfoJSONRequests",{}),CW.notificationCenter.postNotification("receivedInfoForAllDynamicApps"))},addAppManager:function(e){var t=this.get("apps"),n=this.get("appList");n.pushObject(e),e.set("index",n.length),t[e.get("name")]=e,this.notifyPropertyChange("appList")},iCloudLiteObserver:function(){var e=CloudOS.authController;(e.get("iCloudLiteSignUp")||e.getPath("user.isLiteAccount"))&&this.notifyPropertyChange("appList")}.observes("CloudOS.authController.iCloudLiteSignUp","CloudOS.authController.user"),removeApp:function(e,t){if(CloudOS.get("isCloudOSMini"))return;COS.appsController.removeAppInfoFor(e);var n=CloudOS.appManagerFor(e);if(!n)return;delete this.get("apps")[e];var r=COS.apps[e].alternateAppName;t||delete COS.apps[e],this.get("appList").removeObject(n),this.notifyPropertyChange("apps"),this.notifyPropertyChange("appList")},removeOmittedApps:function(e){var t=this.get("apps"),n;for(n in t){var r=t[n];if(!r)continue;!e[n]&&r.get("canBeRemoved")&&this.removeApp(n)}for(n in COS.apps)!t[n]&&!this.pendingInfoJSONRequests[n]&&delete COS.apps[n]},replaceOrAddApp:function(e,t,n){var r=COS.authController,i=r.get("appsOrder"),s=i.indexOf(t),o=this.get("showApps");e[n]={},!o||o.indexOf(t)===-1?delete e[
t]:i.push(t),i[s]=n,this.invokeLast(function(){this.notifyPropertyChange("appIndices")}),this.appReplacementDidComplete(n)},reloadApplication:function(e){var t=CloudOS.appController,n=CloudOS.appManagerFor(e),r=this,i=CloudOS.authController.get("user"),s=t.get("currentApp");if(!n){SC.warn("reloadApplication(): Application “%@” does not exist",e);return}s&&s.get("name")===e?CloudOS.statechart.sendAction("appMustReload",function(){n.teardown(),r.invokeLater(function(){t.set("pendingApp",n),n.set("loadReason",CK.LOAD_REASON_RELOAD),CloudOS.statechart.sendAction("userDidChooseApp")},500)}):n.teardown()},exitApplication:function(e,t,n,r){var i=CloudOS.appController,s=CloudOS.appManagerFor(e),o=NO;if(!s){SC.warn("application %@ does not exist".fmt(e));return}if(!s.get("isLoaded")){SC.warn("application %@ is already unloaded.".fmt(e));return}s.set("isFailed",YES),t===CK.EXIT_FATAL_ERROR&&(o=YES);var u=i.get("currentApp"),a=i.get("pendingApp");u&&u.get("name")===e||a&&a.get("name")===e?CloudOS.statechart.sendAction("appMustExit",{statusCode:t,applicationLog:n,appToLoadAfterAuthentication:r}):(s.teardown(),o&&this.showErrorReporter(s,n))},exitApplicationSilently:function(e){CloudOS.statechart.sendAction("appMustExitSilently");var t=CloudOS.appManagerFor(e);t&&t.teardown(),this.get("loadingApp")===t&&this.set("loadingApp",null)},switchToApplicationWithNotification:function(e,t,n){var r=CloudOS.appManagerFor(e);this.get("currentApp")===r&&r.get("isReady")?(SC.debug("Handing notification off to active app %@ immediately",e),r.passMessage("didReceiveNotification",t),n&&n.dismiss()):(r.set
("loadInBackground",NO),CloudOS.appController.set("pendingApp",r),n&&n.set("automaticallyDismiss",NO),r.set("postDisplayAction",function(){n&&n.dismiss(),r.passMessage("didLaunchWithNotification",t)}),CloudOS.statechart.sendAction("appCalledSwitchToApplication"))},reset:function(){var e=this.get("apps"),t,n;for(n in e)t=e[n],t.teardown()},currentApp:null,pendingApp:null,activateCurrentApp:function(e){var t=this.get("currentApp");if(!t){SC.debug("No app is ready to be activated yet, waiting for it to call back when ready");return}t.set("isActive",YES),t.show(e)},deactivateCurrentApp:function(){var e=this.get("currentApp");if(!e){SC.debug("No app is ready to be deactivated yet.");return}CK.currentApplication=null,e.set("isActive",NO),this.set("currentApp",null)},applicationDidOpen:function(e){COS.statsController.beginStat("cloudos","AppVisibleTime",{appName:e.get("name")})},applicationWillClose:function(e){var t=e?e.get("name"):this.getPath("currentApp.name");if(!t)return;e&&e.get("isReady")&&COS.statsController.endStat("cloudos","AppVisibleTime",null,{durationKeyName:"visibilityDuration"})},userDidRevalidate:function(){var e=this.get("apps"),t,n;for(t in e)n=e[t],n.passMessage("_cloudOSStateChange",{authBag:COS.authController._auth_bag}),n.passMessage("userDidRevalidate");SC.Request.manager.resumeAllServices()},getDefaultApp:function(){var e=this.getDefaultAppName();if(!e)return null;var t=CloudOS.appManagerFor(e);if(t&&!t.get("isDisabled"))return t},getDefaultAppName:function(){return CloudOS.getAppFromURL()},showErrorReporter:function(e,t,n,r){var i=e.get("name");n=n===NO?NO
:YES,r||(r="server");var s=e.get("recordedExceptions");s&&r==="loadFailure"&&(r="loadFailureLikelyException"),CK.errorCatcher.report({isFatal:n,applicationName:i,type:r,statSessionId:COS.statSessionId,title:"Error.AppLoading.Title".loc("AppTitle.%@".fmt(i).loc()),message:"Error.AppLoading.Description".loc(),applicationLog:t,recordedExceptions:s?s.join("\n"):null})},showNotes2AppIfNeeded:function(e){var t=CloudOS.authController.get("appsOrder").indexOf("notes2")!==-1;if(t){this.appReplacementDidComplete("notes2");return}var n=CK.servicesController.getServiceInfoFor("ckdatabasews");if(!n){SC.info("CloudKit web service does not exist for this account"),this.removeNotes2App();return}SC.info("Account has CloudKit web service, checking the state");var r=COS.Request.getUrl(n.get("url")+"/database/1/com.apple.notes/production/private/users/current");r.set("reportRequest",YES),r.notify(200,this,function(t){var r=t.get("body");if(r&&r.userRecordName){var i=COS.Request.postUrl(n.get("url")+"/database/1/com.apple.notes/production/private/records/lookup",{records:[{recordName:r.userRecordName}]});i.notify(200,this,function(t){var n=t.get("body"),r=NO,i;return n&&n.records&&n.records[0]&&n.records[0].fields&&n.records[0].fields.DidChooseToMigrate&&n.records[0].fields.DidChooseToMigrate.value===1?(this.replaceOrAddApp(e,"notes","notes2"),SC.info("Account is notes migrated in CK, but not in iCloud Account. Setting account flag…"),i=COS.Request.postUrl("https://setup.icloud.com/setup/ws/1/updateAccount",null),i.set("reportRequest",YES),i.notify(200,this,function(e){return SC.info("Successfully marked account notesMigrated"
),COS.statsController.recordStat("cloudos","NotesMigratedStateSuccess"),YES}),i.notify(0,this,function(e){return SC.info("Error marking account notesMigrated"),COS.statsController.recordStat("cloudos","NotesMigratedStateFailure"),YES}),i.send({notesMigrated:!0})):(SC.debug("Account is not notes migrated in CK."),this.removeNotes2App()),YES}),i.notify(0,this,function(e){return SC.debug("There was a problem fetching the user record."),this.removeNotes2App(),YES}),i.send()}return YES}),r.notify(400,this,function(e){return SC.debug("Account does not have this CloudKit container."),this.removeNotes2App(),YES}),r.notify(0,this,function(e){return SC.debug("There was a problem fetching the user id."),this.removeNotes2App(),YES}),r.send()},removeNotes2App:function(){this.removeApp("notes2"),this.removeInvalidIframes(),this.appReplacementDidComplete("notes2")},setNewReplacementApps:function(e){this._newReplacementApps=e},appReplacementDidComplete:function(e){var t=this._newReplacementApps;t&&t.length>0&&t.contains(e)&&(t.removeObject(e),t.length===0&&(CW.notificationCenter.postNotification("appReplacementsCompleted"),this._newReplacementApps=[]))},addAppsReplaced:function(e,t){this._replacedAppsMapping[e]=t},replaceApps:function(e){var t=this._replacedAppsMapping,n;for(n in t)e[n]&&this.replaceOrAddApp(e,n,t[n])}}),CloudOS.AppleWidgetCommonMethods={_floworigin:null,_pane:null,_url:null,_contentViewClass:null,_messagesReceived:[],_rpcMethodHandlers:{},init:function(){arguments.callee.base.apply(this,arguments),this.addCommonRPCMethods(this._rpcMethodHandlers)},addCommonRPCMethods:function(
e){var t=this.get("_rpcCommonMethodHandlers");if(t)for(var n in t)e[n]||(e[n]=t[n])},handleMessage:function(e){var t=e&&e.method,n=t&&this._rpcMethodHandlers[t],r=e&&e.params,i=this.toString();this._messageReceived(t);if(n){var s,o=SC.clone(r,!0);try{s=JSON.stringify(o,this._replacer.bind(this))}catch(u){s="(cannot stringify)"}SC.debug(i+" RPC: Received invocation for method `"+e.method+"`. (id: "+e.id+" params:"+s+")");var a=r&&SC.clone(r),f=this,l=function(t,n){f._frameMethodCallback(e,t,n)};a?(a.unshift(l),n.apply(this,a)):n.call(this,l)}else SC.warn(i+" RPC: Received invocation for non-existant method `"+e.method+"`. (id: "+e.id+")");typeof e=="object"&&(typeof e.result!="undefined"||typeof e.error!="undefined")&&SC.debug(i+" RPC: Received response. (id: "+e.id+")")},_paneContentView:function(){var e=this.__contentView,t=this.get("_contentViewClass");if(!t)return;if(!e||!e.kindOf(t))e=this.__contentView=t.create();return e}.property("_contentViewClass"),resetContentView:function(){this.__contentView=null},_removePane:function(){this._failureTimer&&this._failureTimer.invalidate()},_generateURL:function(e){var t=window.URI(e);return t.addQuery("locale",CK.getCurrentLocaleInISOFormat()),t.addQuery("font","sf"),t.toString()},_frameMethodCallback:function(e,t,n){var r={jsonrpc:"2.0",id:e.id};typeof t!="undefined"?r.result=t:typeof n!="undefined"?r.error=n:r.error="No response.",this._sendAppleIdWidgetMessage(r)},_keysNotToLog:["src","accountName","session","trustTokens"],_replacer:function(e,t){var n=SC.typeOf(t);if(n===SC.T_HASH){for(e in t)SC.typeOf(t[e])===SC.T_HASH?t[e]=this
._replacer(e,t[e]):this._keysNotToLog.contains(e)&&(t[e]="(omitted)");return t}return this._keysNotToLog.contains(e)?"(omitted)":t},_sendAppleIdWidgetMessage:function(e){var t=this.get("_paneContentView"),n=t.getFrame(),r=n&&n.contentWindow,i=this.toString();if(r){if(typeof e.result!="undefined"){var s=SC.clone(e.result,!0)||"";if(s){try{s=JSON.stringify(s,this._replacer.bind(this))}catch(o){s="(cannot stringify)"}s=" & params = %@ ".fmt(s)}SC.debug(i+" RPC: Responding with result. (id: "+e.id+s+")")}else typeof e.error!="undefined"?SC.debug(i+" RPC: Responding with error. (id: "+e.id+")"):SC.debug(i+" RPC: Calling `"+e.method+"`. (id: "+e.id+")");r.postMessage(this.get("prefix")+JSON.stringify(e),this._flowOrigin)}else SC.warn(i+" RPC: A message was not sent because the Apple widget frame could not be found. (id: "+e.id+")")},_rpcCommonMethodHandlers:{receivePingRequest:function(e,t){e(!!this._rpcMethodHandlers[t])},log:function(e){for(var t=0;t<arguments.length;t++){if(SC.typeOf(arguments[t])!==SC.T_STRING)continue;SC.Logger.debug(this.toString()+arguments[t])}e(YES)},reportStat:function(e,t){e(YES)}},_messageReceived:function(e){this._messagesReceived.push(e)},clearMessagesReceived:function(){this._messagesReceived=[]}},CloudOS.AdjustViewLayoutOnMobile={_windowSize:null,adjustLayoutOnMobile:function(e,t){if(CloudOSBootstrap.isOnSupportedMobile){t=t?t:["layout"];var n,r=this._windowSize?this._windowSize:SC.RootResponder.responder.currentWindowSize;for(var i=0,s=t.length;i<s;i++)n=t[i],e.indexOf("width")>-1&&this[n].width>r.width&&(this[n].width=r.width),e.indexOf("height")>-1&&
_iframeView=this.createChildView(CloudOS.iFrameView,{src:this._url,title:"Apple Id Sign-In",toString:function(){return"CloudOS.AppleAuthWidgetFrameView"}}),this.appendChild(t),this.invokeLast(function(){var e=t.$();e.attr("id","auth-frame"),e.attr("width","100%"),e.attr("height","100%"),e.attr("frameborder","0"),e.attr("scrolling","no"),e.attr("tabindex","-1")})},resetUrl:function(e){var t=this._iframeView;t&&t.set("src",e)},hide:function(){var e=this._iframeView;e&&e.destroy()},getFrame:function(){return this.getPath("_iframeView.layer")},shakeAuthFrame:function(){this._shaker&&this._shaker.finish();var e=15;this._shaker=this.animate("centerX",{to:this.get("layout").centerX+e,importants:[1,2,3,4,5,6].map(function(t){return t*e/7}),tween:CW.Anim.tweens.make("linearInterpolation",[0,1,-1,1,-1,.7,-0.7,0]),duration:400})}}),CloudOS.APPLE_AUTH_WIDGET_READY_TIMEOUT=45e3,CloudOS.APPLE_AUTH_WIDGET_POST_MESSAGE_PREFIX="pmrpc.",CloudOS.AppleAuthWidgetController=SC.Object.extend(CloudOS.AppleWidgetCommonMethods,{_contentViewClass:CloudOS.AppleAuthWidgetFrameView,prefix:CloudOS.APPLE_AUTH_WIDGET_POST_MESSAGE_PREFIX,_isRepairStarted:NO,isShowing:YES,hideRememberMeBinding:"CloudOS.authController.hideRememberMe",isFederatedFlowUIStarted:NO,configUI:function(){return{logo:{src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANgAAADYCAYAAACJIC3tAAAgAElEQVR4nOy9Z3Bc15muyzpV98eZqjl10j11Z+bM2B7b4yhblonQjRwIgCQYJVGUqGglK1qWFZlEijkTJEiCRGDOOYHIIJgDCJIgAIIgbTlqxpZtEb1z6H7uj7V29wYIUZJHFESqv6q3dkv6s9Hdj973+9baqwcM+IIX8HfAPwM/AjKBB4BXgJlAMbAO2AvUA8eB88Bl4ArQBfwO+IO8fgB0x9Wv+qDXZ9IlP6vL8rM7Lj/LvfKzLZaf9Svys89EfBf+Gfi7/v5+3nYFfFe+ke8AG+Qb/nviFa+e9XvEd2MD4rvyAPDd/v7+fuEK+J/AaKAUOA38uZ8+sHjd/vVnxHeoFPGd+p/9/f3ulwL+NzAY8X+fD/rv84jXHV4fAOsR37X/3d/f+1tewL8h7LyjH9/0eH05qwPx3fu3/ubgMy/gLqAE+I/+fIfjFS/Ed7AEuKu/ufhPF/APwFzE9Che8foiVTfiu/kP/c3J31TAc8Snf/H64tfvgef6m5dPXMAPgYZ+ftPiFa9PWw3AD/ubn5sW8DJwvZ/fqHjF62+t68DL/c3RDQX8N2BtP7858YrXZ1Vrgf/W31wNGDBgwADgW8C5fn5D4hWvz7rOAd/qb7hSgd/28xsRr3jdqvotkNpfcKUBf+znNyBe8brV9Ucg7fOGK0h8mBGvL09dB4KfF1zJQKif/+B4xevzrhCQfKvh+r/AL/v5D41XvPqrfgl85VbB9feIB+LiFa8vc7UC//1WAFba339ZvOL1Ban1nzVcz/b3XxSveH3B6qefFVzfBtT+/mviFa8vWCnAtz8LwBr7+Q+JV7y+qNX4n4UrHg3jFa+b17N/K1z/SPwJ5HjF6+PqP4B//FsAW9bfdx6veN0mtezTwvVdwOzvu45XvG6TMoHvfRrASvr7juMVr9usSj4pXF8hvpE3XvH6tHWdT7KNCpjc33car3jdpjX54+D6e+Baf99lvOJ1m9Yvgb+/GWCD+/sO4xWv27wG3wywDf19d/GK121eGz4Krv9B/JdN4hWv/2z9mb5+1QV4sL/vLF7xukNqbF+Are7vu4pXvO6QqugN138hfrZhvOL1WdU54L/4Afs+8V9AiVe8PqvqBr7vB+yh/r6jeMXrDquH/IBN7e+7iVe87rCa4gdsc3/fTbzidYfVZg+uvwNO9ffdxCted1idBv7O2z3/p/69l3jF646rD4CvDgDu7u87iVe87tC6ewCQ1d93Ea//fNlh+JMW4VfXw7R9EObcv7s0/7vLyT+4nP6DeN36R5euv4T5fSiCYvX3HX8pKmsAMLa/7yJen67+qEVo/qPLxss2U0+YjDugMnSHSt42lezNCukbFFLWhQiuUwisUQiuDhFco5C2NkTmOoXc9QoFm1RGb9X4WZXO0jMmNb9y+M31MKod6e8/706qsQOAn/f3XcTr4+viBy6bOm3eOGKQs03h+2u6+f7qEN9dHeLbZd18uzTEd8pCfK+0m++XhbirtJu7SkNCq7q5a2WI75d0870V3Xx3WYhvL+vmW8UhvlPczfeWhfhecYiBJSEe3qWy6KRJ43sOfzbisP0n6+cDgJn9fRfx6rt+p4ZZecnkuXqDwOYQX1l1nW9VhLhnnULChpDQ+hAJ6xQS1oVIWBsiYY1Cwmp5rZCvK0IklCtCZSGh0hAJq4QGrhT68YoQ3yvu5p/nX+fri7oZsUllSoNB46+d/n4rbteaOQBY3t93Ea9YuRFo/pPD+BM6ebsUvrU2xNcrQtyzIURgs0LSJoWkDSESNygkbFAkYCES1ipCa6RWS8AqJGBlPrh6AZaw0pNCQolCYomA7ZsLu/mnOde5Z3mIsds0NrRa/DXuap+mlsUfsvwC1en/cHjlqE7SFoUfbFD4kYQqZYtCYHOI5ChgComeg60LkbDeg0u62Gqfc1WESCiXKpOglSoCsNIQCasUH2AhEkoUqRAJK4TuWiJg+9aibvJWK1S0WPxJj4P2CWrDAGB/f9/Fl73Of+Dy+nGdgVtC/GhTiLTtCmnbFVK2qqRsUQhuUUjerJC8OUTyphBJG6WDrfdprYTL72IVPsjKQr6IqPR0sFVK1L0SSkIxrfBpeYiBy0L8YEmIf5nTTf4ahfUXLML9/eZ9sWv/AKC+v+/iy1rddoRFF0yydil8b2OI1B0qmTsUMnYopG1TSN2qkLJVIbhVIbBZiTpY4kalJ2DrZB/WIyL64Krw+i8JWKl0sWg89LlYb8CW94QsYXmIhGUhvjGvm6/M6eah7RpHfxPv0T6i6gcAJ/r7Lr6M1fi+w8O1KglbFYLbQ+TsUsjaKeBK36GQtl0ldVsMsOBmheRNMiL2AEzGRK8PW+OPiIovIvZyLw8wfw/WAy7FpxhY3jVxWYgfLQ3x9Xnd/LAoxPTDBt1WPDb2qhMDgJb+vosvU2lOhCWtFqm7QqTsCJG3R2HQHpWc3SpZu6SDbVdI3y7gStkqImJgi4iISZsUkjaFYj3YeiXmXt4U0YOst4OV+3uvUC8X80Om9HSw5SESliskLFMEZMtCJBSHoq/vLgrxldnXGb5B4ez7bn+/xV+kahkAdPT3XXxZqqs7zItHNZK2K+TtVRmyXyF/r8Kg3Sq5uxWyd6lk7lRFRNyukLZVjQG2OdTTwTYqPQFb5wEWisXD1dK9KpTYkKO3e/VwMNmH+SOh372WhQRkxT7IikMkSv3rnG5+tDTEmpb4NhFZ7QOAq/19F1+GOvlHh7G1KsFdIYYcUBl6QKVgn
,width:"100px",height:"100px"},signInLabel:"Auth.Title.SignInToICloud".loc()}}.property(),_maxNumberOfRetries:1,_numberOfRetries:0,isRepairStarted:function(e,t){return t!==undefined&&(this._isRepairStarted=t),this._isRepairStarted}.property("_isRepairStarted"),show:function(e,t){this.set("_pane",e),this.set("_url",t),this.set("isShowing",YES),this._loadURLInFrameWithTimeout(t)},destroy:function(){this._pane.remove(),this.set("_pane",null),this.set("_url",null),this.set("isShowing",NO),this._failureTimer&&this._failureTimer.invalidate(),arguments.callee.base.apply(this,arguments)},_authLoginCompleted:function(e,t,n,r){var i=CloudOS.statechart;if(!e)i.sendAction("loginFailed"),this.get("_paneContentView").shakeAuthFrame();else if(!t)this.get("isRepairStarted")?(SC.debug("Repair Failed"),i.sendAction("repairFailed")):(SC.debug("No dsWebAuthToken found"),i.sendAction("authDidNotConnect","loginDidFail - No dsWebAuthToken"));else if(e){var s={dsWebAuthToken:t};n&&(s.trustToken=n),r&&(s.accountCountryCode=r),i.sendAction("loginCompleted",s)}this._removePane()},_loadURLInFrameWithTimeout:function(e){var t=CloudOS.APPLE_AUTH_WIDGET_READY_TIMEOUT,n;try{n=URI.parse(e)}catch(r){throw r.message="Failed to parse the Apple Auth widget URL:\n"+r.message,r}this._flowOrigin=n.protocol+"://"+n.hostname,this._frameHasCalledReady=NO;var i=this.get("_pane"),s=this.get("_paneContentView"),o=i.get("childViews"),u=COS.statsController;i.set("authWidgetFrame",s),this.clearMessagesReceived(),this.get("_numberOfRetries")===0&&u.beginStat("cloudos","AuthWidget_TotalLoadTime"),u.beginStat("cloudos","AuthWidget_Loading_Successful"
),u.beginStat("cloudos","AuthWidget_Loading_Failed"),i.insertBefore(s,o&&o.objectAt(0)),this.invokeLast(function(){s.show(this._generateURL(e))}),SC.debug("Starting timer to track time taken by auth widget to load. Attempt Number %@",this.get("_numberOfRetries")+1),this._failureTimer=this.invokeLater(this._didFailToLoad,t)},_recordAuthLoadStats:function(){var e=SC.getCurrentTimeForPerformance()-SC.benchmarkPreloadEvents.headStart,t={renderDuration:e},n=window.screen,r,i=COS.statsController;i.cancelStat("cloudos","AuthWidget_Loading_Failed"),i.endStat("cloudos","AuthWidget_Loading_Successful",{retryAttemptNumber:this.get("_numberOfRetries")},{durationKeyName:"widgetLoadDuration",includeLocationAndLocale:YES}),i.endStat("cloudos","AuthWidget_TotalLoadTime",{retryAttempts:this.get("_numberOfRetries"),loadSuccessful:YES},{durationKeyName:"widgetLoadDuration",includeLocationAndLocale:YES});for(r in n)t["screen_"+r]=n[r];t.innerHeight=window.innerHeight,t.innerWidth=window.innerWidth,t.outerHeight=window.outerHeight,t.outerWidth=window.outerWidth,i.recordLocationStat("cloudos","DisplayLogin",t)},_didLoad:function(){var e=CW.getUrlParameters().retryWidgetLoginAttempts,t=this.get("_numberOfRetries"),n=this.get("_maxNumberOfRetries");if(e&&t<e&&e<=n)return;this._recordAuthLoadStats(),this._frameHasCalledReady=YES,this._failureTimer.invalidate(),CloudOS.workspaceController.hideCentralSpinner(function(){var e=CloudOS.authController,t=this.get("_paneContentView");t.animate("opacity",1,200,{onstop:function(){this.view.set("isLoaded",!0)}}),e.set("isAuthWidgetLoaded",YES),CloudOS.statechart
.sendAction("appleWidgetLoaded"),CloudOSBootstrap.isOnSupportedMobile||CW.notificationCenter.postNotification("springboardMayProceed"),e.clearUserState()}.bind(this))},_didFailToLoad:function(){if(this._frameHasCalledReady)return;SC.debug("Auth Widget failed to load"),this._retryReloadWidget()},_retryReloadWidget:function(){var e=this.get("_maxNumberOfRetries"),t=this.get("_numberOfRetries"),n=this.get("_pane"),r=COS.statsController;if(!n){SC.debug("Pane has already been removed.");return}r.cancelStat("cloudos","AuthWidget_Loading_Successful"),r.endStat("cloudos","AuthWidget_Loading_Failed",{retryAttempts:t,messagesReceivedFromIframe:this._messagesReceived.toString()},"widgetLoadDuration",YES),t===e?(r.endStat("cloudos","AuthWidget_TotalLoadTime",{retryAttempts:t,loadSuccessful:NO},{durationKeyName:"widgetLoadDuration",includeLocationAndLocale:YES}),SC.debug("Failed to load Auth Widget even after %@ retries",t),this._resetPaneContentView(n,YES),CloudOS.statechart.sendAction("appleAuthPaneFailedToLoad")):(t++,this.set("_numberOfRetries",t),SC.debug("Retrying to load the Auth Widget with attempt number %@",t+1),r.recordLocationStat("cloudos","AuthWidget_Retry_Loading_Started",{retryAttemptNumber:t}),this._resetPaneContentView(n),this.show(n,this.get("_url")))},_resetPaneContentView:function(e,t){var n=this.get("_paneContentView");e.removeChild(n),e.set("authWidgetFrame",null),this.resetContentView(),n.destroy(),this._failureTimer.invalidate(),t&&this.destroy()},_clearState:function(){this.set("isRepairStarted",NO)},_rpcMethodHandlers:{ready:function(e){e(YES)},config:function(
e){var t,n,r,i=CloudOS.authController.get("trustTokens");try{n=URI.parse(CloudOS.initializationController.get("accountLoginUrl")),r=URI.parseQuery(n.query).widgetKey}catch(s){CW.fatalError("No serviceKey to load the Apple Auth Widget.")}if(r){t={data:this.get("configUI")};var o=this.get("hideRememberMe");t.data.features={createLink:NO,rememberMe:!o};var u=t.data;u.rememberMeLabel="keep-me-signed-in",u.theme="lite",u.serviceKey=r,u.trustTokens=i,u.defaultAccountNameAutoFillDomain="icloud.com",e(t),this.invokeLater(this._didLoad,40)}else CW.fatalError("No serviceKey to load the Apple Auth Widget.")},passwordAuthDone:function(e,t,n){var r,i,s,o=this,u=CloudOS.get("authPane"),a=CloudOS.authController,f=COS.statsController;e(YES),n&&(r=n.rememberMe,i=n.dsWebAuthToken||n.session,s=n.accountType,accountCountryCode=n.accountCountry),a.set("loginAttempts",a.get("loginAttempts")+1);if(t){if(this.get("isRepairStarted"))return;if(s){var l=s.toLowerCase();f.recordLocationStat("cloudos","AuthWidget_AccountType",{accountType:s}),(l.indexOf("hsa")===0||l==="managed")&&this._pane.hideAuthPaneAndShowSpinner(function(){t&&a.set("isExtendedLogin",r),this._authLoginCompleted(t,i,null,accountCountryCode)}.bind(this),!0)}else SC.warn("No accountType value received from the widget")}else this._authLoginCompleted(t,i)},repairDidStart:function(e){var t=COS.statsController;this.set("isRepairStarted",YES),t.recordLocationStat("cloudos","AuthWidget_Repair_Started"),t.beginStat("cloudos","AuthWidget_Repair"),CloudOS.statechart.sendAction("repairStarted"),e(YES)},authDidCancel:function(e){var t=COS.statsController
,n=CloudOS.statechart;this.get("isRepairStarted")?(t.cancelStat("cloudos","AuthWidget_Repair"),t.recordLocationStat("cloudos","AuthWidget_Repair_Cancelled"),n.sendAction("repairDidCancel")):(t.recordLocationStat("cloudos","AuthWidget_Login_Cancelled"),n.sendAction("authDidCancel")),this._clearState(),e(YES)},complete:function(e,t){e(YES),this.get("isRepairStarted")&&COS.statsController.endStat("cloudos","AuthWidget_Repair",null,{durationKeyName:"duration",includeLocationAndLocale:YES});var n=CloudOS.authController,r,i,s,o;t&&(r=t.rememberMe,i=t.session,s=t.trustToken,o=t.accountCountry),n.set("userAuthenticationState",CK.AuthenticationStateEnum.AUTHENTICATED),n.set("isExtendedLogin",r),this._clearState(),this._pane.remove(function(){CloudOS.workspaceController.showCentralSpinner(function(){this._authLoginCompleted(YES,i,s,o)}.bind(this))}.bind(this))},authFailedToLoad:function(e){e(YES),this._didFailToLoad()},authWidgetWillChangeFlow:function(e,t){if(t&&t.to){var n=t.to;SC.debug("Auth UI flow is changing to -> '%@'",n),n==="INTERSTITIAL"&&this.set("isFederatedFlowUIStarted",YES),n==="SIGNIN"&&this.set("isFederatedFlowUIStarted",NO)}e(YES)},authWidgetDidChangeFlow:function(e,t){if(t&&t.to){var n=t.to;SC.debug("Auth UI flow has changed to -> '%@'",n)}e(YES)}}}),CloudOS.AppleIDWidgetFrameView=SC.View.extend({classNames:["apple-id-frame","iframe-pane"],adjustablePane:null,show:function(e){this._url=e},getFrame:function(){return this.getPath("_iframeView.layer")},paneDidShow:function(){var e=this.get("childViews"),t;if(e.length>0)return;t=this._iframeView=this.createChildView(CloudOS
.iFrameView,{src:this._url,toString:function(){return"CloudOS.AppleIDWidgetFrameView"}}),this.insertBefore(t,e&&e.objectAt(0))},paneDidHide:function(){var e=this._iframeView;e&&e.destroy()},_url:null,_iframeView:null}),CloudOS.APPLE_ID_WIDGET_READY_TIMEOUT=3e4,CloudOS.APPLE_ID_WIDGET_POST_MESSAGE_PREFIX="AppleID.",CloudOS.APPLE_ID_WIDGET_EXIT_REASON_NO_REPAIR_NEEDED=1,CloudOS.APPLE_ID_WIDGET_EXIT_REASON_TIMEOUT=2,CloudOS.APPLE_ID_WIDGET_BUTTON_INDEX_TO_PROPERTY_MAP=["rightButton","middleButton","leftButton"],CloudOS.AppleCreateWidgetController=SC.Object.extend(CloudOS.AppleWidgetCommonMethods,{_contentViewClass:CloudOS.AppleIDWidgetFrameView,prefix:CloudOS.APPLE_ID_WIDGET_POST_MESSAGE_PREFIX,minWidth:400,minHeight:200,configPayload:null,show:function(e,t,n){this.set("_pane",e),this.set("_url",t),n&&this._storeConfigPayload(n),this._loadURLInFrameWithTimeout(t)},_generateURL:function(e,t){t=e(t);var n=window.URI(t);return n.addQuery("v","2"),n.toString()}.enhance(),_loadURLInFrameWithTimeout:function(e){var t=CloudOS.APPLE_ID_WIDGET_READY_TIMEOUT,n=COS.statsController,r,i,s;try{r=URI.parse(e)}catch(o){throw o.message="Failed to parse the Apple ID widget URL:\n"+o.message,o}this._flowOrigin=r.protocol+"://"+r.hostname,this._frameHasCalledReady=NO,i=this.get("_pane"),i.set("isLoading",YES),i.set("maxWidth",i.constructor.prototype.maxWidth),i.set("maxHeight",i.constructor.prototype.maxHeight),s=this.get("_paneContentView"),s.set("adjustablePane",i),i.set("paneContentView",s),i.set("delegate",s),n.beginStat("cloudos","AppleID_CreateWidget_Loading_Successful"),n.beginStat("cloudos"
,"AppleID_CreateWidget_Loading_Failed"),i.show(this._generateURL(e)),SC.debug("Starting timer to track time taken by create widget to load."),this._failureTimer=this.invokeLater(this._didFailToLoad,t)},_didLoad:function(){var e=COS.statsController;this._frameHasCalledReady=YES,this.setPath("_pane.isLoading",NO),e.cancelStat("cloudos","AppleID_CreateWidget_Loading_Failed"),e.endStat("cloudos","AppleID_CreateWidget_Loading_Successful")},_didFailToLoad:function(){if(this._frameHasCalledReady)return;var e=COS.statsController;SC.debug("Create Widget failed to load"),CloudOS.statechart.sendAction("appleIDPaneFailedToLoad"),e.cancelStat("cloudos","AppleID_CreateWidget_Loading_Successful"),e.endStat("cloudos","AppleID_CreateWidget_Loading_Failed")},_storeConfigPayload:function(e){var t={language:CK.getCurrentLocaleInISOFormat(),customAlerts:!0};SC.mixin(t,e),this.set("configPayload",t)},_alertsByGUID:{},_createAlertForAppleIdWidget:function(e){var t={message:e.title,description:e.description},n=CloudOS.APPLE_ID_WIDGET_BUTTON_INDEX_TO_PROPERTY_MAP,r=e.buttons;for(var i=0,s=r.length;i<s;i++){var o=r[i],u=n[i];o&&u&&(t[u]={title:o,index:i,action:e.action.bind(null,i,o)})}var a=CW.Alert.create(t);return this._alertsByGUID[SC.guidFor(a)]=a,a.append(),a},_updateAlertForAppleIdWidget:function(e,t){var n=this._alertsByGUID[e];if(!n)return NO;var r=t.title;typeof r=="string"&&n.setPath("contentView.messageView.value",r);var i=t.description;return typeof i=="string"&&n.setPath("contentView.descriptionView.value",i),YES},_hideAlertForAppleIdWidget:function(e){var t=this._alertsByGUID[e];return!
)},authBadgeDidAnimate:function(){this.invokeLater(function(){this._sleptApp&&(this._sleptApp.wake(),this._sleptApp=null)},300)},authPaneWasInitialized:function(e){e.beginPropertyChanges(),e.bind("nowShowing","CloudOS.workspaceController.nowShowing"),e.set("displayKey",CloudOS.AUTH),e.endPropertyChanges()},accountPrefsChanged:function(e,t){var n;e!==t&&(CloudOS.blockUserInput(),n=YES);var r=CloudOS.moduleLocalizer.setLocale(),i=this._envSashPane;r?(n||CloudOS.blockUserInput(),i&&i.set("isVisible",NO),CW.notificationCenter.subscribeToNotification("relocalize",this,"_showEnvSash"),SC.Module.loadModule("cloudos_foundation/language",this,"_didReloadLanguageModule")):(n&&CloudOS.unblockUserInput(),CW.notificationCenter.postNotification("relocalize","User Changed Language and maybe we need to reload certain apps."))},_didReloadLanguageModule:function(){CloudOS.localizationController.relocalizeIfNeeded("User Changed Language and Language Loaded"),CloudOS.unblockUserInput(),CloudOS.authController.get("isAuthenticated")&&CloudOS.loadAlarms()},_showEnvSash:function(){this._envSashPane&&this.invokeLater(function(){this._envSashPane.set("isVisible",null)},200)}}),CloudOS.authController=COS.AuthUIController.create({postLoginRedirectUrl:null,hsaUserAction:CloudOS.HSASourceEnum.NONE,delayedTearDownApp:null,delayedTearDownUsed:!1,iCloudLiteSignUp:NO,isAuthWidgetLoaded:NO,isFirstRunLoaded:NO,performedLoginFlow:NO,_appReplacementsCompleted:NO,init:function(){arguments.callee.base.apply(this,arguments),CW.notificationCenter.subscribeToNotification("authModuleDidLoad",this,"authModuleDidLoad"),
this.invokeLast(function(){CW.notificationCenter.unsubscribeFromNotification("appReplacementsCompleted",this,s)});if(t){var n=t.apps;e.replaceApps(n),e.detectAndLoadAdditionalApps(n),CloudOS.appController.get("isAllAppInfoLoaded")?this.removeUnsupportedApps():CW.notificationCenter.subscribeToNotification("receivedInfoForAllDynamicApps",this,"removeUnsupportedApps")}else SC.warn("No auth bag available. We might be in logout mode")}.bind(this);CW.notificationCenter.subscribeToNotification("appReplacementsCompleted",this,s),this.get("accountRepairRequired")||(this.get("isAtLeastPartiallyAuthenticated")&&!this._appReplacementsCompleted&&(this._appReplacementsCompleted=YES,e.setNewReplacementApps(["notes2"]),e.showNotes2AppIfNeeded(n)),this.get("isAuthenticated")&&(CloudOS.appController.notifyPropertyChange("appList"),COS.PushController.initiatePushConnection(CloudOS.notificationsController),CloudOS.notificationsController.getBadgeState(),this.measureLoadPerformance()))},removeUnsupportedApps:function(){var e,t=this._auth_bag.apps,n=CloudOS.appController;for(e in t){var r=CloudOS.getAppInfo(e);r&&(this.getPath("user.isLiteAccount")&&!r.get("supportsLite")&&delete t[e],this.getPath("user.isPrimaryAppleIdTypePhoneNumber")&&!r.get("supportsPhoneNumberBasedAppleId")&&delete t[e])}n.removeOmittedApps(t),n.notifyPropertyChange("appList")},measureLoadPerformance:function(){this.invokeLater(SC.run(function(){var e=this.get("currentDomain"),t=SC.buildMode==="debug"?"/system/cloudos/1812Project43/cloudos_foundation/1812Project43/en-us/source/resources/images/blank.png":"https://%{currentDomain}/blank.png"
.fmt({currentDomain:e});CloudOS.loadImageUrlAndRecordStat(t,"OriginLoad");var n=SC.buildMode==="debug"?"/system/cloudos/1812Project43/cloudos_foundation/1812Project43/en-us/source/resources/images/blank.png":"https://www.%{currentDomain}/blank.png".fmt({currentDomain:e});CloudOS.loadImageUrlAndRecordStat(n,"CDNLoadICloud");var r=SC.buildMode==="debug"?"/system/cloudos/1812Project43/cloudos_foundation/1812Project43/en-us/source/resources/images/blank.png":"https://icloud.cdn-apple.com/blank.png";CloudOS.loadImageUrlAndRecordStat(r,"CDNLoadApple"),CloudOS.reportEdgePerformance()}.bind(this)),5e3)},shouldUsePostLoginRedirectUrl:function(){var e=this.get("postLoginRedirectUrl");if(e){var t=URI(e);if(t.domain()===this.get("currentDomain")&&t.protocol()==="https")return YES}return NO},authModuleDidLoad:function(){CloudOS.workspaceController.hideCentralSpinner(function(){CloudOS.get("isCloudOSMini")?CloudOS.authPane.show():CloudOS.workspaceController.set("nowShowing",CloudOS.AUTH)}.bind(this))},_firstRunViewDidChange:function(){CloudOS.appSwitcherController.hideAppSwitcher()},languageDidLoad:function(){CloudOS.localizationController.relocalizeIfNeeded("Signin Submission Succeeded and Language Loaded"),CloudOS.appController.get("areAllAppReplacementsCompleted")?this.checkIfDefaultAppIsCreated():CW.notificationCenter.subscribeToNotification("appReplacementsCompleted",this,"checkIfDefaultAppIsCreated")},checkIfDefaultAppIsCreated:function(){var e=CloudOS.appController,t=e.getDefaultAppName(),n=e.getDefaultApp(),r=e.getPath("pendingInfoJSONRequests."+t);this.invokeLast(function(){CW.notificationCenter
(this)):c.gotoState(h,null,null,v):c.gotoState(h)}a||CloudOS.loadAlarms()},userDidCompleteFirstRun:function(){this.userDidAuthenticate()},logoutUser:function(e,t){var n=CloudOS.appController.get("appsNotReadyToTerminate"),r=this;if(!n||!t)return e&&CloudOS.blockUserInput(0),arguments.callee.base.apply(this,arguments);var i=n.pop(),s=i.get("displayName");this._unsavedDialog||(this._unsavedDialog=CW.Alert.show({message:"Dialog.UnsavedChanges.Title".loc(),description:"Dialog.UnsavedChanges.Description".loc(s),superClassMethod:arguments.callee.base,superClassMethodDelegate:this,middleButton:{title:"Dialog.UnsavedChanges.DontSignOutButton".loc(),action:"logoutCancelled"},rightButton:{title:"Dialog.UnsavedChanges.SignOutButton".loc(),action:"continueLogout"},logoutCancelled:function(){SC.info("logout is cancelled"),this.remove();return},continueLogout:function(){return this.remove(),e&&CloudOS.blockUserInput(0),this.superClassMethod.apply(this.superClassMethodDelegate,[e,t])},remove:function(){r._unsavedDialog=null,arguments.callee.base.apply(this,arguments)}}))},userDidAuthenticate:function(e){var t=CloudOS.authController,n=CloudOS.appController,r=t._auth_bag,i=t.get("hsaChallengeRequired");this.set("performedLoginFlow",YES),i||CloudOS.moduleLocalizer.setLocale(),CloudOS.authController.setDomainSpecificClassNames(),t.get("isRevalidatingUser")||SC.Module.loadModule("cloudos_foundation/language",this,"languageDidLoad");if(!CloudOS.get("isCloudOSMini"))return;var s=t.get("accountPreferences");CloudOS.passMessageToAllApps("_cloudOSStateChange",{authBag:r,accountPreferences:s?s.prefsHash
():null,appPreferences:COS.prefsController.allAppPreferencesHash()}),t.get("isRevalidatingUser")||(t.get("isAuthenticated")?(this.showTermsNotificationIfRequired(),CloudOS.passMessageToAllApps("userDidAuthenticate",e)):(t.get("isPartiallyAuthenticated")&&CloudOS.passMessageToAllApps("userDidPartiallyAuthenticate",e),this._fromCurrentWindow=e))},userDidNotAuthenticate:function(e){CloudOS.passMessageToAllApps("userDidNotAuthenticate",e)},userDidLogout:function(e){if(!CloudOS.get("isCloudOSMini")){e||(window.location.hash="#:showlogin",CK.reloadWithReason("userDidLogout, fromCurrentWindow: "+e));return}CloudOS.passMessageToAllApps("userDidLogout",e)},redirectPostAuthenticationIfRequired:function(e){var t=window.location.href,n=e.isCarryUser,r=this.shouldUsePostLoginRedirectUrl();if(!r){if(CK.get("isCarry")&&!n)return window.location.href=t.replace("carry.","www."),YES;var i=CW.getUrlParameters(),s=i.carry,o=i.skipCarryRedirect;if(!s&&e&&!e.hsaChallengeRequired&&!this.accountTermsUpdateRequired&&CK.get("isWWW")&&n&&!o)return window.location.href=t.replace("www.","carry."),YES}return NO},validateUserIfNeeded:function(){this.serviceIdentitiesAreMissing()&&(COS.statsController.recordStat("cloudos","ValidatedUserForMissingServiceIdentities"),this.validateUser())},quotaDataFetched:function(e,t){if(!t){SC.warn("No quotaData found to send _cloudOSStateChange and quotaDataDidChange messages");return}CloudOS.passMessageToAllApps("_cloudOSStateChange",{quotaData:t}),CloudOS.passMessageToAllApps("quotaDataDidChange")},showPCSDeletedErrorMessage:function(e){if(!e)return;if(this._lastPCSAlertAppDisplayName===
e){SC.debug("PCS Deleted alert for %@ is already being shown.",e);return}this._lastAlert&&this._lastAlert.remove(),this._lastPCSAlertAppDisplayName=e;var t=this;this._lastAlert=CW.Alert.show({message:"Error.AppPCSDeleted.Title".loc(e),description:"Error.AppPCSDeleted.Description".loc(),rightButton:"Button.OK".loc(),remove:function(){arguments.callee.base.apply(this,arguments),t._lastAlert=null,t._lastPCSAlertAppDisplayName=null}})},setDomainSpecificClassNames:function(){this.getPath("user.isChineseAccount")&&CloudOSBootstrap.setChinaClassName(!0)}}),CloudOS.autoUpdateController=SC.Object.create({init:function(){return this.createOrReuseAutoUpdateTimer(),arguments.callee.base.apply(this,arguments)},autoUpdateTimer:null,createOrReuseAutoUpdateTimer:function(e){var t=this.get("autoUpdateTimer");if(t){if(!e)return;t.invalidate()}else e||(e=CloudOS.AUTO_UPDATE_INTERVAL);t=SC.Timer.schedule({target:this,action:"checkVersion",interval:e*1e3,repeats:YES}),this.set("autoUpdateTimer",t)},checkVersion:function(e){var t=(new Date).getTime(),n=CW.getUrlParameters(),r=this.get("autoUpdateTimer"),i=r.get("interval"),s=t-CloudOS._lastActivityEpoch,o;if(e!==YES&&this._lastCheck+(i-1e4)>t){SC.info("autoUpdate: Already checked %@ms ago, ignoring",t-this._lastCheck);return}this._lastCheck=t,o=s>CloudOS.AUTO_UPDATE_INACTIVITY_INTERVAL*1e3?CloudOS.AUTO_UPDATE_DELAYED_INTERVAL:CloudOS.AUTO_UPDATE_INTERVAL,o*1e3!==i&&this.createOrReuseAutoUpdateTimer(o);var u=SC.Request.getUrl("https://"+window.location.hostname+"/system/cloudos/current/version.json").json();u.notify(0,this,function(e){if(n.autoUpdate
)return SC.warn("autoUpdate: Will simulate response since autoUpdate flag is set."),this.handleVersionResponse("override",parseInt(n.autoUpdate,10)),YES;if(e.get("status")!==200)return SC.warn("autoUpdate: Could not fetch version.json"),YES;var t=e.get("body"),r,i;return t&&(r=t.buildNumber,i=t.autoUpdate,!SC.none(r)&&!SC.none(i)&&this.handleVersionResponse(r,parseInt(i,10))),YES}),u.send()},handleVersionResponse:function(e,t){if(t===CloudOS.UPDATE_IGNORE){SC.debug("autoUpdate: Update flag for %@ is UPDATE_IGNORE",e);return}if(SC.buildNumber===e){SC.debug("autoUpdate: Running latest build, %@",e);return}var n=CK.getValueFromLocalStorage("didReloadToBuild",YES);if(n===e){SC.warn("autoUpdate: We already reloaded the user to try an update to %@, so will not do it again!",e);return}var r=this;if(t===CloudOS.UPDATE_PROMPT){SC.debug("autoUpdate: Prompt the user to reload to %@",e);if(this._reloadPane&&this._reloadPane.get("isVisibleInWindow")){SC.info("autoUpdate: There is already an auto update alert pane showing, so ignoring request for a second one.");return}var i=CloudOS.authController.get("displayableCurrentDomain");this._reloadPane=CW.Alert.show({message:"AutoUpdate.Title".loc({currentDomain:i}),description:"AutoUpdate.Description".loc(),image:"me-icon-alert-68",rightButton:{title:"AutoUpdate.Reload".loc(),action:function(){r.reloadToBuildNumber(e)}},middleButton:{title:"AutoUpdate.Later".loc(),action:function(){this.get("pane").remove()}}})}t===CloudOS.UPDATE_FORCE&&(SC.debug("autoUpdate: Force the user to reload to %@",e),r.reloadToBuildNumber(e)),t===CloudOS.UPDATE_DELAYED_FORCE&&
(SC.debug("autoUpdate: Delay force the user to reload to %@",e),this.reloadIfAppropriate(e),this.invokeLater(function(){this.reloadToBuildNumber(e)},CloudOS.AUTO_UPDATE_DELAYED_FORCE_WAIT*1e3))},reloadIfAppropriate:function(e){var t=CloudOS._lastActivityEpoch,n=(new Date).getTime()-CloudOS._lastActivityEpoch;!t||n>6e4?this.reloadToBuildNumber(e):this.invokeLater(function(){this.reloadIfAppropriate(e)},6e4)},reloadToBuildNumber:function(e){CK.setValueInLocalStorage("didReloadToBuild",e,YES),CK.reloadWithReason("reloadToBuildNumber "+e)}}),CloudOS.mixin({UPDATE_IGNORE:0,UPDATE_PROMPT:1,UPDATE_FORCE:2,UPDATE_DELAYED_FORCE:3}),CloudOS.SINGLE_LINE_BANNER_HEIGHT=38,CloudOS.MULTI_LINE_BANNER_HEIGHT=58,CloudOS.BANNER_ANIMATION_DURATION=500,CloudOS.bannerManager=SC.Object.create({_bannerHeight:CloudOS.SINGLE_LINE_BANNER_HEIGHT,_currentQuotaBannerShowingType:null,init:function(){arguments.callee.base.apply(this,arguments),CW.notificationCenter.subscribeToNotification("quotaDataFetched",this,"quotaDataFetched"),CW.notificationCenter.subscribeToNotification("relocalize",this,"relocalize")},bannerHeight:function(e,t){return t!==undefined?(this._bannerHeight=t,this._bannerHeight):this.get("isBannerVisible")?this._bannerHeight:0}.property("isBannerVisible"),isBannerVisible:function(){return!!this.get("_currentBanner")}.property("_currentBanner"),_appsBannerHash:{},_currentBanner:null,findBannerToShowForApp:function(e){var t=this._appsBannerHash[e];if(!t||t.length===0)return null;var n=t[0];for(var r=1,i=t.length;r<i;r++)n.get("priority")<=t[r].get("priority")&&(n=t[r]);return n},setAppBanner
:function(e,t){var n=SC.typeOf(e),r=n===SC.T_HASH,i=n===SC.T_NULL;if(!r&&!i){SC.warn("bannerHash provided to setAppBanner function either has to be null or of type Hash.");return}t||(t="CloudOS"),e&&!e.localize&&(e.localize=NO);if(r){var s=this._appsBannerHash[t],o;if(s&&s.length!==0)if(t==="CloudOS")o=CloudOS.CloudOSBannerView.create(e),s.push(o);else{var u=s[0];this.updateBanner(u,e)}else o=CloudOS.CloudOSBannerView.create(e),this._appsBannerHash[t]=[o]}else this.removeBanner(t);this.selectBannerAndShow()},selectBannerAndShow:function(){var e=this.get("_currentBanner"),t=CloudOS.getPath("mainPage.mainPane.bannerContainer"),n=CloudOS.appController.getPath("currentApp.name")||"CloudOS",r=this.findBannerToShowForApp(n)||this.findBannerToShowForApp("CloudOS");if(e&&r===e)return;r||(e&&e.hide(),this.set("_currentBanner",null)),r&&(this.set("_currentBanner",r),t.addBannerView(r),e&&e.hide())},removeAllBanners:function(){var e=this.get("_appsBannerHash"),t=CloudOS.getPath("mainPage.mainPane.bannerContainer"),n;for(n in e){var r=e[n];t.childViews.indexOf(r)!==-1?t.removeBannerView(r):r.destroy()}this.set("_appsBannerHash",{}),this.set("_currentBanner",null)},updateBanner:function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&e.set(n,t[n])},removeBanner:function(e){var t=this.findBannerToShowForApp(e);t&&(this._appsBannerHash[e].removeObject(t),this.invokeLater(function(){t.destroy()},CloudOS.BANNER_ANIMATION_DURATION))},quotaDataFetched:function(e,t){if(CloudOSBootstrap.isOnSupportedMobile)return;if(!e){SC.warn("No quotaData found to show/hide the quota banner");return}var n=e.get("overQuota"
),r=e.get("isAlmostOverQuota");n?this.showQuotaBanner():r?this.showQuotaBanner(CloudOS.BANNER_TYPE_QUOTA_ALMOST_EXCEEDED):this.removeQuotaBanner()},showQuotaBanner:function(e){e||(e=CloudOS.BANNER_TYPE_QUOTA_EXCEEDED);var t=this._currentQuotaBannerShowingType,n=COS.authController;if(!n||!n.get("user"))return;var r=n.get("user"),i=r.get("isLiteAccount")?"LiteAccount":"FullAccount",s=r.get("isManagedAppleID");if(t!==e){t&&this.removeQuotaBanner();var o={title:"Banner.%@.%@.Title".fmt(e,i),description:"Banner.%@.%@.Description".fmt(e,i),localize:YES};s||(o.optionalLink={text:"Banner.QuotaExceeded.OptionalLink.Text",url:"Banner.QuotaExceeded.OptionalLink.Url"}),this.setAppBanner(o),this._currentQuotaBannerShowingType=e}},removeQuotaBanner:function(){this._currentQuotaBannerShowingType&&(this.setAppBanner(null),this._currentQuotaBannerShowingType=null)},relocalize:function(){this.removeAllNonLocalizedBanners()},removeAllNonLocalizedBanners:function(){var e=this.get("_appsBannerHash"),t=CloudOS.getPath("mainPage.mainPane.bannerContainer"),n;for(n in e){var r=e[n];for(var i=0,s=r.length;i<s;i++){var o=r[i];if(o.get("localize"))return;t.childViews.indexOf(o)!==-1?t.removeBannerView(o):o.destroy(),e[n].removeObject(o),o===this.get("_currentBanner")&&this.set("_currentBanner",null)}}}}),CloudOS.blockInputController=SC.Object.create({showFeedbackAfter:1e3,shouldShowFeedback:NO,_userInputWasBlockedAt:0,block:function(e){e===undefined&&(e=this.get("showFeedbackAfter")),this.set("shouldShowFeedback",NO),this._userInputWasBlockedAt=SC.getCurrentTimeForPerformance()-this.get("showFeedbackAfter"
)+e,CloudOS.blockInputModalPane.get("modalPane").append(),this.invokeLater("showFeedback",e)},unblock:function(){this._userInputWasBlockedAt=0,CloudOS.blockInputModalPane.get("modalPane").remove()},showFeedback:function(){var e=this._userInputWasBlockedAt;e>0&&this.get("showFeedbackAfter")+e<=SC.getCurrentTimeForPerformance()&&(this._userInputWasBlockedAt=0,this.set("shouldShowFeedback",YES))}}),CloudOS.initializationController=SC.Object.create({createFrameURL:null,createFrameOrigin:null,repairFrameURL:null,repairFrameOrigin:null,accountLoginUrl:null,repairDoneEndpointURL:null,accountCreateEndpointURL:null,getICloudTermsEndpointURL:null,accountLoginEndpointURL:null,accountCreationEnabled:!1,extractOrigin:function(e){var t=URI.parse(e);return t.protocol+"://"+t.hostname+(t.port!==null?":"+t.port:"")},handleConfigBag:function(e){try{var t=e.urls,n=CW.getUrlParameters(),r=n.useUATLoginUI,i=n.useStableLoginUI;if(t){var s=t.accountLoginUI;this.set("createFrameURL",t.accountCreateUI),this.set("repairFrameURL",t.accountRepairUI),r?s=s.replace("stable","uat"):i&&(s=s.replace("uat","stable")),this.set("accountLoginUrl",s),this.set("accountLoginEndpointURL",t.accountLogin),this.set("repairDoneEndpointURL",t.repairDone),this.set("accountCreateEndpointURL",t.accountCreate),this.set("getICloudTermsEndpointURL",t.getICloudTerms)}var o=e.accountCreateEnabled;o&&!SC.browser.isIE9OrLower&&this.set("accountCreationEnabled",o)}catch(u){SC.Logger.warn("Failed to parse or extract properties from the config bag!")}}}),CloudOS.localizationController=SC.Object.create({_lastPreferredLanguage:null,relocalizeIfNeeded
:function(e,t){e=e||"unknown reason"+(t?" that was forced":""),this._reasons||(this._reasons=[]),this._reasons.push(e),this.invokeOnce(t?"_forceReloc":"_relocalizeIfNeeded")},_forceReloc:function(){this._relocalizeIfNeeded(!0)},_relocalizeIfNeeded:function(e){var t=this._reasons.join(", ")||"no reasons known";this._reasons.length=0;var n=e||String.preferredLanguage!==this._lastPreferredLanguage;SC.debug("Language check for CloudOS: "+this._lastPreferredLanguage+" -> "+String.preferredLanguage+". We "+(n?"WILL":"WILL NOT")+" relocalize cloudOS."),this._lastPreferredLanguage=String.preferredLanguage,CK.setValueInLocalStorage("locale",String.preferredLanguage),CW.notificationCenter.postNotification("relocalize",(e?"FORCED: ":"")+t,e)}}),CloudOS.NotificationsController=SC.Object.extend(SC.DelegateSupport,{getBadgeState:function(){if(!CK.servicesController.getServiceInfoFor("push")){SC.debug("getBadgeState(): PushWS is not available.");return}var e=CK.Request.postUrl("/getState");e.set("serviceName","push"),e.set("isJSON",YES),e.queryParameter("pcsEnabled",COS.authController.get("pcsEnabled")),e.notify(200,this,function(e){var t=e.get("body"),n=t?t.states:null;if(!n||n.length===0){SC.warn("There was a problem reading the badge state response.");return}var r,i,s,o,u,a;for(u=0,a=n.length;u<a;u++){i=n[u],r=i.pushTopic,s=CloudOS.appManagersForPushTopic(r)[0];if(!s)continue;o=i.data?i.data.badge:null,s&&SC.typeOf(o)===SC.T_NUMBER&&o>-1&&s.set("badgeCount",o)}return YES}),e.notify(0,this,function(e){return SC.warn("%@ received from pushws. Will not retry.",e.get("status")),YES}),e.send
({pushTopics:COS.pushController.get("pushTopics")})},didInitializePush:function(e){CloudOS.passMessageToAllApps("_cloudOSStateChange",{pushToken:e.pushToken})},handlePushNotification:function(e,t,n,r){var i,s,o;if(SC.typeOf(e)===SC.T_HASH)i=e;else try{i=SC.json.decode(e)}catch(u){SC.warn("handlePushNotification(): Exception parsing push notification");return}s=i.apsTopic,!s&&i.ck&&(o=i.ck.cid);if(!i||!t&&!s&&!o){SC.warn("Push notification has missing body, topic or container identifier");return}var a;t?a=[CloudOS.appManagerFor(n)]:s?a=CloudOS.appManagersForPushTopic(s):o&&(a=CloudOS.appManagersForContainerIdentifier(o)),a.forEach(function(n){this.handlePushNotificationForAppManager(i,e,n,t,r)},this),a.length===0&&SC.warn("Push notification has unknown topic or container identifier"),CW.notificationCenter.postNotification("didReceivePushNotification",a.getEach("name"),e)},handlePushNotificationForAppManager:function(e,t,n,r,i){var s=n.get("name"),o,u,a,f,l;if((!n.get("isActive")||e.omitWhenActive===NO)&&e.aps){u=e.aps.alert,a=e.aps.alertTitle,f=e.aps.badge,l=e.aps.sound;if(u||a)e.sessionID===COS.CLIENT_ID?SC.info("Not showing notification for %@ as it originated from this client session",s):this.displayNotification(n,e);SC.typeOf(f)===SC.T_NUMBER&&f>-1&&n.set("badgeCount",f)}i=i===undefined?n.get("awakesInBackgroundFromPush"):i;if(n.get("isReady"))SC.debug("Handing notification off to %@",s),n.passMessage("didReceiveNotification",t);else if(!n.get("isReady"))if(i){if(n.get("isDisabled")){SC.info("Cannot start app %@ since it's disabled",s);return}SC.debug("Starting application %@ as it might need to create a local notification"
,s),n.set("loadReason",CK.LOAD_REASON_NOTIFICATION);var c=n.get("notificationQueue")||[];c.push(t),n.set("notificationQueue",c),n.set("postDisplayAction",function(){c.forEach(function(e){n.passMessage("didReceiveNotification",t)})}),n.invokeLast("getReadyInBackground")}else SC.debug("Ignoring notification for %@ as it does not awakesInBackground",s)},shouldDisplayNotification:function(e){var t=CW.getUrlParameters();return t.suppressNotifications?NO:YES},displayNotification:function(e,t){var n=e.get("name"),r="Notification.PlaceholderDescription.",i=NO,s,o,u,a,f;if(!this.shouldDisplayNotification(n)){SC.info("Skipping visual notification for %@",n);return}u=t.aps.alert;if(SC.typeOf(u)===SC.T_HASH){o=u["loc-args"];if(!o||SC.typeOf(o)!==SC.T_ARRAY){SC.warn("loc-args array is missing or malformed: %@",o);return}s=("PushNotification."+n+"."+u["loc-key"]).loc(o[0],o[1],o[2])}else!u&&CK.hasLocalizedStringForKey(r+n)?(s=(r+n).loc(),i=YES):s=u;a=t.aps.alertTitle||e.get("displayName"),f=t.isDismissable!==undefined?!!t.isDismissable:YES;var l=CloudOS.iOSNotification.create({appDisplayName:e.get("displayName"),message:SC.RenderContext.escapeHTML(a),description:SC.RenderContext.escapeHTML(s),isDismissable:f,icon:e.get("notificationIcon"),classNames:function(){return i?["placeholder-description"]:[]}(),action:function(r){CloudOS.appController.switchToApplicationWithNotification(n,t,r),e.set("loadReason",CK.LOAD_REASON_NOTIFICATION),r.invokeLater(function(){r.dismiss()},CloudOS.MAX_NOTIFICATION_DISMISSAL_WAIT*1e3),r._wasAlreadyDismissed=YES,COS.statsController.recordStat("cloudos","Notification"
,CloudOS.NewLoginController=SC.Object.extend(CloudOS.AppleWidgetCommonMethods,{_contentViewClass:CloudOS.NewLoginFrameView,show:function(e,t){this.set("_pane",e),this.set("_url",t),this._loadURLInFrameWithTimeout(t)},_loadURLInFrameWithTimeout:function(e){var t=CloudOS.NEW_LOGIN_READY_TIMEOUT,n;try{n=URI.parse(e)}catch(r){throw r.message="Failed to parse the new Login URL:\n"+r.message,r}this._flowOrigin=n.protocol+"://"+n.hostname,this._frameHasCalledReady=NO;var i=this.get("_pane"),s=this.get("_paneContentView"),o=i.get("childViews"),u=COS.statsController;i.set("authWidgetFrame",s),this.clearMessagesReceived(),this.get("_numberOfRetries")===0&&u.beginStat("cloudos","NewLogin_TotalLoadTime"),u.beginStat("cloudos","NewLogin_Loading_Successful"),u.beginStat("cloudos","NewLogin_Loading_Failed"),i.insertBefore(s,o&&o.objectAt(0)),this.invokeLast(function(){s.show(this._generateURL(e))}),SC.debug("Starting timer to track time taken by new Login to load. Attempt Number %@",this.get("_numberOfRetries")+1),this._failureTimer=this.invokeLater(this._didFailToLoad,t)},_didLoad:function(){this._frameHasCalledReady=YES,CloudOS.workspaceController.hideCentralSpinner(function(){this.get("_paneContentView").animate("opacity",1,350),CW.notificationCenter.postNotification("springboardMayProceed"),CloudOS.statechart.sendAction("newLoginLoaded")}.bind(this))},_didFailToLoad:function(){if(this._frameHasCalledReady)return;SC.debug("new Login failed to load"),CloudOS.statechart.sendAction("newLoginFailedToLoad")},_resetPaneContentView:function(e,t){var n=this.get("_paneContentView");e.removeChild
(n),e.set("authWidgetFrame",null),this.resetContentView(),n.destroy(),this._failureTimer.invalidate(),t&&this.destroy()},_rpcMethodHandlers:{ready:function(){this._didLoad()},complete:function(e,t){if(t){t.isNewLoginLogin=YES,this._resetPaneContentView(this.get("_pane"),YES);var n=t.completionMessage,r=t.channelInfo;if(r)try{CK.isStringBase64Encoded(r)&&(r=CW.decodeBase64(r)),r=JSON.parse(r),CloudOS.authController.set("secureChannelInfoData",r)}catch(i){CW.fatalError("secureChannelInfo is not in a JSON format which can be parsed.")}if(n)try{t.completionMessage=JSON.parse(n)}catch(s){CW.fatalError("Unable to read the payload in the complete message")}CloudOS.statechart.sendAction("loginCompleted",t)}},switchOverToAuth:function(e){this._resetPaneContentView(this.get("_pane"),YES),CloudOS.statechart.sendAction("gotoAppleIdLogin")}}});var FIRST_PARTY_ICON_MAP={keynote:"key",numbers:"numbers",pages:"pages"},ICLOUD_APPLE_ZONE="com.apple.icloud.applecorporate";CloudOS.ShareController=SC.ObjectController.extend({database:null,shortGUID:null,vettingToken:null,recordInfo:null,isVettingTokenVetted:NO,appNameFromUrl:null,containerIdentifier:null,isPublicShare:NO,didShowAcceptUIPreLogin:NO,_appWasReady:null,appName:function(){var e=this.get("appNameFromUrl"),t=e;if(!t){var n=this.containerIdentifier;if(n==="com.apple.clouddocs"){var r=this.recordInfo;if(!r)return;var i=r.rootRecord,s=i.fields.extension.value;switch(s){case"key":t="keynote";break;case"numbers":t="numbers";break;case"pages":t="pages";break;default:t="iclouddrive"}}else n&&(t=this.getAppNameForContainerId(n))}return t}.property
("appNameFromUrl","containerIdentifier","recordInfo").cacheable(),fileExtensionOrUTI:function(){var e=this.get("appName");if(e in FIRST_PARTY_ICON_MAP)return FIRST_PARTY_ICON_MAP[e]}.property("appName").cacheable(),isAppSupportedOnMobile:function(){var e=this.get("appNameFromUrl");if(e){var t=CloudOS.getAppInfo(e);return t?t.get("isSupportedOnMobile"):undefined}return YES}.property("appNameFromUrl").cacheable(),hasAppUIForAcceptedSharesOnMobile:function(){var e=this.get("appNameFromUrl");if(e){var t=CloudOS.getAppInfo(e);return t?t.get("hasUIForAcceptedSharesOnMobile"):undefined}return NO}.property("appNameFromUrl").cacheable(),init:function(){CW.notificationCenter.subscribeToNotification("sharingCancelled",this,"sharingCancelled"),SC.Logger.info("Loading CloudKit JS in CloudOS"),SC.Event.add(window,"cloudkitloadfailure",SC.RunLoop.wrapFunction(function(){CW.fatalError("Error resolving share: Unable to load CloudKitJS.")}.bind(this))),CK.loadCloudKitJS();var e=this.get("vettingToken"),t=this.get("isVettingTokenVetted"),n=this.get("shortGUID");this.resolveURL()},isShareThirdParty:function(){return this.get("recordInfo")&&!this.get("appNameFromUrl")&&!this.get("isGameCenterShare")}.property("recordInfo","appNameFromUrl").cacheable(),isGameCenterShare:function(){return this.getPath("recordInfo.containerIdentifier")==="com.apple.socialgaming.sessions"}.property("recordInfo").cacheable(),updateShareDetails:function(e){var t=e.vettingToken,n=e.isVettingTokenVetted,r=e.shortGUID,i=e.appNameFromUrl;this.set("vettingToken",t||null),this.set("isVettingTokenVetted",n||null),this.set("shortGUID"
,r||null),this.set("appNameFromUrl",i||null),this.set("recordInfo",null),this.resolveURL()},resolveURL:function(){window.CloudKit?(SC.Logger.info("CloudKit JS is already loaded"),this.cloudKitJSDidLoad()):SC.Event.add(window,"cloudkitloaded",function(){SC.Logger.info("Loaded CloudKit JS in CloudOS"),this.cloudKitJSDidLoad()}.bind(this))},cloudKitJSDidLoad:function(){window.Promise||(window.Promise=CloudKit.Promise),this.get("database")||this.set("database",CloudOS.Database.create({environment:"production",containerIdentifier:"com.apple.cloudkit",databaseType:CloudOS.DatabaseType.Public,partition:"",services:{fetch:CK.CKJSRequest.fetch}})),this.get("shortGUID")?this.retrieveShare():this.get("vettingToken")&&CloudOS.statechart.sendAction("completedShareControllerSetup")},retrieveShare:function(e){var t=this.get("shortGUID");if(!t)return;this.passMessageToApp("willResolveCKShortGUID",t);var n=window.CloudKit.getDefaultContainer();n.fetchRecordInfos({value:t}).then(SC.RunLoop.wrapFunction(function(t){var n=t.errors;if(n.length>0)this.retrieveShareDidFail(t);else{if(e){e(t);return}this.retrieveShareDidSucceed(t)}}.bind(this))).catch(SC.RunLoop.wrapFunction(function(e){this.passMessageToApp("didFailToResolveCKShortGUID",t,e),CW.fatalError("Error resolving share: "+e)}.bind(this)))},retrieveShareDidSucceed:function(e){SC.Logger.info("retrieveShare succeeded");var t=e.results[0];this.set("recordInfo",t);var n=t.rootRecord,r=t.share,i=t.participantStatus,s=this.get("shortGUID"),o=CloudOS.statechart,u=CloudOSBootstrap.isOnSupportedMobile,a=this.get("appName");if(r){SC.Logger.info("Share Record found"
);if(!this.get("appNameFromUrl"))CloudOS.statechart.sendAction("retrieveShareSucceeded",YES);else if(i===CloudKit.ShareParticipantAcceptanceStatus.ACCEPTED)if(u){if(this.redirectToIWorkIfRequired(a))return;this.get("hasAppUIForAcceptedSharesOnMobile")?o.sendAction("showAlreadyAcceptedState"):CK.reloadWithReason("Sharing: No UI for an already accepted share.","/")}else SC.Logger.info("Share already accepted. Launching app."),this.launchApp();else u&&!this.get("isAppSupportedOnMobile")?o.sendAction("appIsUnsupportedOnMobile"):r.publicPermission!=="NONE"?(this.set("isPublicShare",YES),this.get("isAppleCorporateZone")?o.sendAction("retrieveShareSucceeded"):this.isIWorkApp(a)?this.launchApp():o.sendAction("showPublicAcceptance")):(SC.Logger.info("Share not yet accepted. Launching acceptance flow."),o.sendAction("retrieveShareSucceeded"))}else n?(SC.Logger.info("No share record found. Launching app."),this.launchApp()):(SC.Logger.info("Invalid shortGUID or deleted share. Showing sharing error."),o.sendAction("retrieveShareFailed"));return YES},retrieveShareDidFail:function(e){SC.Logger.info("retrieveShare failed, showing sharing error.");var t=this.get("shortGUID");return this.passMessageToApp("didFailToResolveCKShortGUID",t,e.errors),CloudOS.statechart.sendAction("retrieveShareFailed"),YES},isIWorkApp:function(e){return e==="keynote"||e==="numbers"||e==="pages"},redirectToIWorkIfRequired:function(e){return this.isIWorkApp(e)?(window.location.href=URI(CloudOS.authController.get("defaultOrigin")+"/"+e+"/"+this.get("shortGUID")).addSearch("redirectReason","off").toString()+"#:nooverride"
,YES):NO},launchApp:function(){var e=this.get("appName");if(this.redirectToIWorkIfRequired(e))return;var t=CloudOS.appManagerFor(e);CloudOS.appController.set("pendingApp",t),this.set("_appWasReady",t.get("isReady")),t.set("loadReason",CK.LOAD_REASON_SHARE_ACCEPTED),t.set("route",this.get("shortGUID")),CW.notificationCenter.subscribeToNotification("App Loaded",this,"appDidLaunch"),CloudOS.statechart.sendAction("globalAppSwitchWasRequested")},appDidLaunch:function(e){var t=this.get("appName"),n=this.get("shortGUID");if(e!==t)return;this._appWasReady||this.passMessageToApp("willResolveCKShortGUID",n),this.passMessageToApp("didResolveCKShortGUID",n,this.get("recordInfo")),CW.notificationCenter.unsubscribeFromNotification("App Loaded",this,"appDidLaunch")},getAppNameForContainerId:function(e){var t;for(t in COS.apps){var n=COS.appsController.getAppInfoFor(t),r=n.get("containerIdentifier");if(r===e)return t}CW.fatalError("shareController: cannot find app for requested container name.")},passMessageToApp:function(){var e=this.get("appName"),t=CloudOS.appManagerFor(e);t&&t.get("isReady")&&(SC.debug("Passing %@ message to %@",arguments[0],e),t.passMessage.apply(t,arguments))},sharingCancelled:function(){CloudOS.statechart.sendAction("sharingCancelled")},resetProperties:function(){this.set("shortGUID",null),this.set("vettingToken",null),this.set("recordInfo",null),this.set("isVettingTokenVetted",null),this.set("appNameFromUrl",null),this.set("database",null),this.set("fileExtensionOrUTI",null),this.set("containerIdentifier",null),this.set("_appWasReady",null),this.set("isPublicShare",
NO),this.set("didShowAcceptUIPreLogin",NO)},isAppleCorporateZone:function(){var e=this.get("recordInfo");return e?e.zoneID&&e.zoneID.zoneName===ICLOUD_APPLE_ZONE:!1}.property("recordInfo")}),CloudOS.SharingAppleAuthWidgetController=CloudOS.AppleAuthWidgetController.extend({configUI:function(){var e,t="Auth.Title.SignInToICloud".loc(),n="Auth.Description.Share.",r=CloudOS.shareController,i=r.get("appName"),s=r.get("recordInfo");if(!s)return{signInLabel:"Auth.Title.SignInToICloud".loc()};var o=s.share.owner.userIdentity.nameComponents,u=o.givenName,a=o.familyName,f;return o&&(u||a)?CW.stringIsCJK(u)&&CW.stringIsCJK(a)?f=a+u:f=u+" "+a:CW.fatalError("No sharer name details in share details"),i==="notes"||i==="notes2"?(n+="notes2",e=n.loc({ownerName:f})):i?(n+=i,e=n.loc({ownerName:f})):(e="Auth.Title.SignInToICloud".loc(),t=null),{appName:t,signInLabel:e}}.property()}),CloudOS.DatabaseType={Public:"Public",Private:"Private",Shared:"Shared"},CloudOS.Database=SC.Object.extend({environment:null,containerIdentifier:null,databaseType:null,partition:null,services:null,databaseInstance:function(){var e=this.get("_databaseInstance");if(e)return e;var t=this.get("containerIdentifier"),n=this.get("databaseType"),r=window.CloudKit.getContainer(t);return n===Sharing.DatabaseType.Public?e=r.publicCloudDatabase:n===Sharing.DatabaseType.Private?e=r.privateCloudDatabase:n===Sharing.DatabaseType.Shared&&(e=r.sharedCloudDatabase),this.set("_databaseInstance",e),e}.property(),bootstrapConfiguration:function(){var e=this.get("partition"),t={containerIdentifier:this.get("containerIdentifier"),environment
:String.preferredLanguage,_locale:"en-us",_previousLocale:null,setLocale:function(e){e||(CW.getUrlParameters().locale&&COS.get("localesSupportedByCloudOSOnly").indexOf(e)!==-1?e=String.preferredLanguage:e=CloudOS.authController.getPath("accountPreferences.localeForCloudOS"));if(this._locale===e||!e)return NO;this._previousLocale=this._locale,this._locale=e,String.preferredLanguage=e;var t=this._monkeyPatchModules();return this._replaceOldStyles(),SC.$(document.body).removeClass(this._defaultLocale).removeClass(this._previousLocale).addClass(this._locale),t},_monkeyPatchModules:function(){var e=SC.MODULE_INFO,t=this.localizedModules,n,r=t.length,i,s,o,u,a=NO;for(n=0;n<r;n++){i=t[n],s=SC.MODULE_INFO[i];if(!s)continue;o=this._updateURL(s.stringURL);if(o!==s.stringURL){s.stringURL=o,s.scriptURL=this._updateURL(s.scriptURL);var f=s.styles;for(var l=0;l<f.length;l++)u=f[l],this._removeOldStyle(i,u),f[l]=this._updateURL(u);f=s.styles2x;for(l=0;l<f.length;l++)u=f[l],this._removeOldStyle(i,u),f[l]=this._updateURL(u);this._unloadModule(i,s),a=YES}}return a},_unloadModule:function(e,t){t.isLoaded=NO,t.isReady=NO,t.isWaitingForRunLoop=NO,t.source=undefined;if(t.isPrefetched){var n=SC.Module.PrefetchModuleTask.create({prefetchedModuleName:e});SC.backgroundTaskQueue.push(n)}},_updateURL:function(e){return e.replace(this._defaultLocale,this._locale).replace(this._previousLocale,this._locale)},_removeOldStyle:function(e,t){var n=$('link[href$="%@"]'.fmt(t));if(n.length>0){var r=n[0];SC.LOG_MODULE_LOADING&&SC.debug("SC.Module: Removing old CSS file in '%@' -> '%@'",e,t),r.parentNode.removeChild
(r)}},_replaceOldStyles:function(){var e=window.BUILD_INFO,t=e.styles,n=e.stylesDPIUsed;if(t){var r=0,i=n===2?t.x2:t.normal,s=document.getElementsByTagName("head")[0]||document.documentElement,o=this;o.pendingStylesToLoad=i.length;for(var u=0;u<i.length;++u){var a=i[u],f=this._updateURL(a),l=$('link[href$="%@"]'.fmt(a)),c;if(l.length>0){var h=l[0];c=document.createElement("link"),c.setAttribute("href",f),c.setAttribute("rel","stylesheet"),c.setAttribute("type","text/css"),c.setAttribute("oldStyle",a),c.onload=function(){var e=this.getAttribute("oldStyle"),t=this.getAttribute("href"),n=$('link[href$="%@"]'.fmt(e));o._updatePendingStylesToLoad(),n.length>0&&(SC.debug("Removing old link tag with href = '%@'.",e),s.removeChild(n[0]))},s.appendChild(c),SC.debug("Adding new link tag with href = '%@'.",f),i[u]=f}c.onerror=function(){o._updatePendingStylesToLoad(),CW.fatalError("Unable to load link tag with href = '%@'.",this.getAttribute("href"))}}}},_updatePendingStylesToLoad:function(){--this.pendingStylesToLoad,this.pendingStylesToLoad===0&&SC.Locale.createCurrentLocale()}},CloudOS.blockInputModalPane=SC.Page.design({modalPane:SC.Pane.design({layout:{zIndex:1e3},childViews:"feedback".w(),shouldShowFeedback:NO,shouldShowFeedbackBinding:"CloudOS.blockInputController.shouldShowFeedback",shouldShowFeedbackDidChange:function(){var e=this.get("shouldShowFeedback"),t=this.get("feedback"),n=e?250:0;t.animate({opacity:e?1:0,duration:n}),t.set("isVisible",e)}.observes("shouldShowFeedback"),feedback:SC.View.design(CW.Animatability,{layout:{opacity:0},isVisible:NO,classNames:"block-input-feedback"
,childViews:"spinner".w(),spinner:CW.SpinnerView.design({asset:CloudOS.SPINNER_IMAGE_SRC,assetIsAlways2x:YES,layout:{centerX:0,centerY:0}})})})}),CloudOS.WaitingForAppState=SC.State.extend({succeededState:"active.application",disabledState:"active.desiredAppDisabled",failedState:"active.appLoadFailure",abortedState:"active.springboard",shouldForceDelegateMethods:NO,enterState:function(){var e=CloudOS.appController,t=e.get("loadingApp"),n=e.get("pendingApp"),r=n.get("name"),i=this;this._app=n;if(n&&t===n){SC.info("We are already waiting for %@ to load",n.get("name"));return}t&&e.loadingApp.teardown();if(n&&n.requiresMailAndIsMissing()){CW.Alert.show({message:"Error.MailNotEnabled.%@.Title".fmt(r).loc(),description:"Error.MailNotEnabled.%@.Description".fmt(r).loc(),rightButton:{title:"Button.OK".loc(),action:function(){this.get("pane").remove(),i.gotoState(i.get("abortedState")),e.set("pendingApp",null)}}});return}if(!n||n.get("isDisabled")){this.gotoState(this.get("disabledState"));return}if(n.get("isFailed")){this.applicationDidFailToBecomeReady();return}COS.statsController.beginStat("cloudos","LoadApplication",{appName:r,previouslyLoaded:n.get("isReady")});var s=function(){CW.notificationCenter.unsubscribeFromNotification("didFetchRegionFormattingSettings",null,this),CW.notificationCenter.unsubscribeFromNotification("receivedInfoForAllDynamicApps",null,this),n.get("isReady")?i.applicationDidBecomeReady(!0):(e.set("loadingApp",n),n.invokeLast("getReady"))},o=!!COS.regionController.regionFormattingRules;r==="settings"&&!e.get("isAllAppInfoLoaded")&&o?(n.set("isWaiting",YES),CW
,this._app),t.endPropertyChanges(),i&&o&&n.set("notificationId",null),CW.notificationCenter.postNotification("App Loaded",r,YES),CloudOS.authPane&&CloudOS.authPane.hide(),t.activateCurrentApp(this.get("shouldForceDelegateMethods")),this.gotoState(this.get("succeededState"))},gotoState:function(){return this._gotoStateTimer&&this._gotoStateTimer.invalidate(),this._gotoStateTimer=null,arguments.callee.base.apply(this,arguments)},appMustExit:function(e){var t=this._app,n=e.statusCode,r=e.applicationLog;if(n===CK.EXIT_NON_FATAL){this.gotoState(this.get("abortedState")),t.teardown();return}if(t&&t.get("loadInBackground")){SC.info("Not showing error dialog since app would load in background"),t.teardown();return}var i=t.get("name"),s=t.get("displayName"),o,u;CloudOS.authController.validateUserIfNeeded();if(n===CK.EXIT_PCS_MISSING||n===CK.EXIT_PCS_INVALID){o="Error.AppPCSRequired.Title".loc(s),u="Error.AppPCSRequired.Description".loc();var a=n===CK.EXIT_PCS_MISSING?"Missing PCS":"Invalid PCS";CloudOS.recordStat("PCS Error: "+a)}else n===CK.EXIT_STARTUP_ERROR?(o="Error.AppNotLoading.Title".loc(s),u="Error.AppNotLoading.Description".loc()):(o="Error.AppCrashed.Title".loc(s),u="Error.AppCrashed.Description".loc());this.gotoState(this.get("abortedState")),CW.Alert.show({message:o,description:u,middleButton:{title:"Error.Button.Report".loc(),action:function(){this.getPath("pane.modalPane").set("paneFadeOutDuration",0),this.get("pane").remove(),CloudOS.appController.showErrorReporter(t,r),t.teardown()}},rightButton:{title:"Button.OK".loc(),action:function(){this.getPath("pane.modalPane")
.set("hideDelay",10),this.get("pane").remove(),t.teardown()}}}),CloudOS.appController.set("loadingApp",null),COS.statsController.recordStat("cloudos","AppMustExitWaitingForApp",{appName:i,statusCode:n})},showServiceLocked:function(e){var t=CloudOS.appController.get("loadingApp"),n=COS.appsController.getAppInfoFor(t.get("name")),r=e.serviceName;if(!r||n.isServiceRequired(r))e.appToDisable=t,this.gotoState("serviceLocked",e)},init:function(){var e="appCalledShowAppSwitcher appCalledSwitchToApplication appMustReload appMustExit appMustExitSilently".w(),t,n,r;for(n=0;t=e[n];n++)r=function(){var e=arguments.callee.state._app;if(!e)return;e.set("preDisplayAction",arguments.callee.actionName),e.set("preDisplayActionArgs",SC.$A(arguments))},r.actionName=t,r.state=this,this[t]||(this[t]=r);arguments.callee.base.apply(this,arguments)}}),CloudOS.WaitingForDefaultAppState=CloudOS.WaitingForAppState.extend({disabledState:"active.allAppsDisabled"}),CloudOS.ApplicationState=SC.State.extend({initialSubstate:"displayingCurrentApp",isReentering:NO,enterState:function(){CW.notificationCenter.postNotification("springboardMayProceed"),CloudOS.workspaceController.hideCentralSpinner(null,!0),CloudOS.workspaceController.set("nowShowing",CloudOS.APP)},displayingCurrentApp:SC.State.design({enterState:function(){this.get("parentState").set("isReentering",NO);var e=CloudOS.appController.get("currentApp");if(!e){SC.info("currentApp is not set! Return to springboard."),this.gotoState("active.springboard");return}var t=e.get("preDisplayAction"),n=e.get("preDisplayActionArgs");e.set("preDisplayAction",undefined
),e.set("preDisplayActionArgs",undefined),t&&this[t].apply(this,n),e.focus(),CloudOS.bannerManager.selectBannerAndShow(),CloudOS._executeReadyQueue()},appCalledShowAppSwitcher:function(e){e||(this.invokeLater(function(){CloudOS.autoUpdateController.checkVersion()},1e3),e={x:8,y:8,width:37,height:29},e.left=e.x,e.top=e.y),this.gotoState("showingSpringboardMini",e)},appCalledShowSpringBoard:function(){this.gotoState("active.springboard")},appCalledSwitchToApplication:function(){this.gotoState("active.application.waitingForNewApp")},globalAppSwitchWasRequested:function(){if(CloudOS.appController.get("currentApp")===CloudOS.appController.get("pendingApp")){SC.info("The new app is same as the current app and it is already loaded.");return}this.gotoState("active.application.waitingForNewApp")},appMustReload:function(e){this.gotoState("active.springboard",e)},appMustExit:function(e){var t=e.statusCode,n=e.applicationLog,r=e.appToLoadAfterAuthentication;if(this._exitPane&&this._exitPane.get("isVisibleInWindow")){SC.warn("There is already an app exit alert pane showing, so ignoring request for a second one.");return}var i=CloudOS.authController,s=CloudOS.appController,o=s.get("currentApp"),u=s.get("pendingApp"),a=CloudOS.statechart;if(t===CK.EXIT_NON_FATAL){r?i.get("isPartiallyAuthenticated")?(o.teardown(),s.set("pendingApp",r),a.sendAction("showHSA",CloudOS.HSASourceEnum.USER_SELECTED_APP)):i.get("isAuthenticated")&&o!==r&&(o.teardown(),a.sendAction("userDidChooseApp")):(this.gotoState("active.springboard"),o.teardown());return}if(o&&o.get("loadInBackground")){SC.info("Not showing error dialog since app would load in background"
("pendingApp");e?(e.set("loadInBackground",NO),this.gotoState("active.application.showingSpringboardMini.waitingForApp")):this.gotoState("active.springboard")},appCalledSwitchToApplication:function(){this.gotoState("active.application.showingSpringboardMini.waitingForApp")},globalAppSwitchWasRequested:function(){if(CloudOS.appController.get("pendingApp")===this._app){SC.info("Already waiting for app to load");return}this.gotoState("active.application.showingSpringboardMini.waitingForApp")},didDismiss:function(){this.abortLoad(),CloudOS.appController.set("pendingApp",null),CloudOS.appController.set("loadingApp",null),this.getPath("parentState.parentState").set("isReentering",YES)},userDidBeginAnimatingHome:function(){this.abortLoad(),CloudOS.appController.set("pendingApp",null),CloudOS.appController.set("loadingApp",null),this.gotoState("animatingHome")},exitState:function(){arguments.callee.base.apply(this,arguments),this.getPath("parentState.parentState").set("isReentering",YES)}}),animatingHome:SC.State.design({appSwitcherFinishedHiding:function(){CloudOS.authController.get("isPartiallyAuthenticated")?this.gotoState("active.authUI.hsa"):this.gotoState("active.springboard")}})}),waitingForNewApp:CloudOS.WaitingForAppState.design({shouldForceDelegateMethods:YES,enterState:function(){arguments.callee.base.apply(this,arguments),CloudOS.blockUserInput(0)},appCalledSwitchToApplication:function(){this.gotoState("active.application.waitingForNewApp")},globalAppSwitchWasRequested:function(){if(CloudOS.appController.get("pendingApp")===this._app){SC.info("Already waiting for app to load"
.gotoState("downloadingSharingModule")}.handleEvents("retrieveShareSucceeded","retrieveShareFailed","showPublicAcceptance","showAlreadyAcceptedState"),completedShareControllerSetup:function(){this.gotoState("downloadingSharingModule")},appIsUnsupportedOnMobile:function(){this.gotoState("downloadingSharingModule")}}),downloadingSharingModule:SC.State.design({enterState:function(){SC.Module.loadModule("cloudos_foundation/sharing",this,"moduleDidBecomeReady")},moduleDidBecomeReady:function(e,t){this.gotoState("displayingSharingUI")}}),displayingSharingUI:SC.State.design({enterState:function(){var e=CloudOS.shareController,t=e.get("shortGUID"),n=e.get("vettingToken"),r=e.get("isVettingTokenVetted"),i=e.get("isShareThirdParty"),s=e.get("isGameCenterShare"),o=e.get("isPublicShare"),u=CloudOS.authController.getPath("user.appleId"),a=CloudOS.isUserAuthenticated(),f=o&&a&&e.get("didShowAcceptUIPreLogin");CloudOS.workspaceController.set("nowShowing",CloudOS.SHARING),t?Sharing.showPane(t,u,i,s,o,f):n?Sharing.acceptVettingToken(n,r):CW.fatalError("Wrong State as there is no vettingToken or shortGUID")},sharingCancelled:function(){var e=CloudOS.isUserAuthenticated();if(CloudOS.shareController.get("isPublicShare")&&!e)return NO;CloudOSBootstrap.isOnSupportedMobile?CK.reloadWithReason("Sharing: Cancelled","/"):e&&this.gotoState("active.springboard")}}),exitState:function(){window.Sharing&&Sharing.sharingPane&&Sharing.removePane(YES),CloudOS.shareController.resetProperties()}}),CloudOS.TermsAndConditionConfirmationState=SC.State.extend({enterState:function(){var e=CloudOS.TermsAndConditionsAcceptanceConfirmationPane
)&&(e.invokeDelegateMethod(e.get("delegate"),"loginDidSucceed",i),e.monitorForUsernameChange())):(SC.warn("No authbag in opener cloudos. Re validating Auth"),f.gotoState("validatingAuth"))};a&&!u?CW.notificationCenter.subscribeToNotification("receivedInfoForDynamicApp",this,function(e,t){var n=CloudOS.appController,r;if(e!==n.getDefaultAppName())return;t?l():(r=n.getDefaultApp(),r.set("loadReason",CK.LOAD_REASON_LOCATION_HASH),CloudOS.appController.set("pendingApp",r),l())}):l()}else SC.warn("Opener window is either not a CloudOS window or the user is not authenticated in the Opener window."),this.gotoState("validatingAuth")}},authDidValidate:function(){COS.authUIController.userDidAuthenticate()},showFirstRun:function(){this.gotoState("active.authUI.loadFirstRun")},goToSharingState:function(e){this.gotoState("active.sharingState",e)}}),validatingAuth:SC.State.design({initialSubstate:"gettingReply",enterState:function(e){e&&!!e.showOnlyLiteApps&&CloudOS.authController.set("iCloudLiteSignUp",YES)},goToSharingState:function(e){this.gotoState("active.sharingState",e)},goToVettingState:function(e){this.gotoState("active.vettingState",e)},gettingReply:SC.State.design({initialSubstate:"parsingReply",parsingReply:SC.State.design({enterState:function(e){e=e||{};var t=e.successCallback;this._successCallback=typeof t=="function"?t:SC.K;var n=e.failureCallback;this._failureCallback=typeof n=="function"?n:SC.K;var r=window.location.hash,i=CloudOS.authController;if(r==="#:showlogin"){window.location.hash="",CloudOS.authController.logoutUser(function(){CK.reloadWithReason("Need to show the Login Screen"
)},YES);return}r=r.length>1?r.substr(1):null;if(r){var s=URI.parseQuery(r),o=s.postLoginRedirectUrl;try{o=atob(s.postLoginRedirectUrl)}catch(u){SC.Logger.info("Non-base64 postLoginRedirectUrl was specified")}var a=s.hideRememberMe;a&&JSON.parse(a)===!0&&CloudOS.authController.set("hideRememberMe",YES);var f=r.match(/(signup)\?origin=(.*)/),l,c=YES,h,p;f&&f.length===3?(h=f[1],p=f[2]):(h=s.signup,p=s.origin),h!==undefined&&(i.set("showSignup",YES),p&&i.set("signupOriginApp",p));if(o){var d=o.match(/(.*)\?origin=(.*)/);d&&d.length===3&&(o=d[1],p=d[2],i.set("signupOriginApp",p)),o=URI.decode(o),i.set("postLoginRedirectUrl",o);for(l in s){if(["postLoginRedirectUrl","signup","origin","terms","hideRememberMe"].indexOf(l)!==-1)continue;s.hasOwnProperty(l)&&(c=NO)}c&&(window.location.hash="")}}SC.Benchmark.start("AUTH_DURATION"),i.statechart=CloudOS.statechart,i.validateUser(i.validatePreferences)},authDidValidate:function(){var e=CloudOS.authController,t=e.get("isAuthenticated");this._successCallback();if(e.shouldUsePostLoginRedirectUrl())return;t&&CloudOS.moduleLocalizer.setLocale(),SC.Module.loadModule("cloudos_foundation/language",this,"languageDidLoad"),e.reportAuthSuccess("validate"),COS.statsController.beginStat("cloudos","Session")},languageDidLoad:function(){CloudOS.localizationController.relocalizeIfNeeded("Signin Submission Succeeded and Language Loaded"),CloudOS.appController.get("areAllAppReplacementsCompleted")?this.checkIfDefaultAppIsCreated():CW.notificationCenter.subscribeToNotification("appReplacementsCompleted",this,"checkIfDefaultAppIsCreated")},checkIfDefaultAppIsCreated
authController.reportAuthError("validate","authDidNotValidateAccountClosed"),this._failureCallback(),this.gotoPreAuthSharingOrAuthUIState()},authDidNotValidateExpiredPassword:function(){CloudOS.authController.reportAuthError("validate","authDidNotValidateExpiredPassword"),this._failureCallback(),this.gotoPreAuthSharingOrAuthUIState()},authDidNotValidateOffline:function(){CloudOS.authController.reportAuthError("validate","authDidNotValidateOffline"),this._failureCallback(),this.gotoPreAuthSharingOrAuthUIState()},authDidNotConnect:function(e){e?e="authDidNotConnect-"+e:e="authDidNotConnect",CloudOS.authController.reportAuthError("validate",e),this._failureCallback(),this.gotoState("validateFailureWithoutUsableData",e)},authDRLocked:function(){CloudOS.authController.reportAuthError("validate","authDRLocked"),this._failureCallback(),this.gotoPreAuthSharingOrAuthUIState()},authPartitionLocked:function(){CloudOS.authController.reportAuthError("validate","authPartitionLocked"),this._failureCallback(),this.gotoPreAuthSharingOrAuthUIState()},incompleteHSAFlow:function(){CloudOS.authController.logoutUser(function(){CK.reloadWithReason("Incomplete HSA flow. Need to start afresh.")},YES)},showFirstRun:function(){this.gotoState("active.authUI.loadFirstRun"),this._successCallback()},showHSA:function(){this.gotoState("active.authUI.hsa")},gotoManagedAppleId:function(){this.gotoState("active.authUI.managedAppleId")},resendGetPrefsRequest:function(){SC.debug("sending get preferences request again."),COS.prefsController.getPreferences(null,COS.authController.validatePreferences)},gotoShowTermsAndConditionConfirmation
:function(){this.gotoState("active.termsAndConditionConfirmation")}}),validateFailureWithoutUsableData:SC.State.design({enterState:function(e){e||(e="No usable info in the validate call response."),CloudOS.UnableToProceedAlert.show({failureReason:e})}})}),waitingForApp:CloudOS.WaitingForDefaultAppState.design({}),gotoWaitingForAppState:function(){this.gotoState("validatingAuth.waitingForApp")},exitState:function(){CloudOS.authController.set("iCloudLiteSignUp",NO)}}),preAuthSharingState:SC.State.design({initialSubstate:"defaultState",defaultState:SC.State.design({enterState:function(){var e=CloudOS.getShareDetailsFromUrl();CloudOS.setupShareController(e),CloudOS.workspaceController.showCentralSpinner(function(){CloudOS.appleAuthWidgetController&&(CloudOS.appleAuthWidgetController.destroy(),CloudOS.appleAuthWidgetController=null)}.bind(this))},retrieveShareSucceeded:function(e){e?this.gotoState("thirdPartySharingState"):this.gotoState("active.authUI")},completedShareControllerSetup:function(){this.gotoState("active.authUI")},retrieveShareFailed:function(){CloudOSBootstrap.isOnSupportedMobile&&CK.reloadWithReason("Sharing: Invalid Share","/"),this.gotoState("active.authUI")},showPublicAcceptance:function(){this.gotoState("publicSharingState")},appIsUnsupportedOnMobile:function(){this.gotoState("active.sharingState")}}),publicSharingState:CloudOS.SharingState.design({sharingCancelled:function(){CloudOS.workspaceController.showCentralSpinner(function(){this.gotoState("active.authUI")}.bind(this))},exitState:function(){window.Sharing&&Sharing.sharingPane&&Sharing.removePane(YES),CloudOS
.loc(t);CW.Alert.show({message:"Error.AppUnqualified.Title".loc(t),description:n,rightButton:"Button.OK".loc()})}}this.gotoState("active.springboard")}}),appLoadFailure:SC.State.design({enterState:function(){var e=CloudOS.authController,t=CloudOS.appController,n=t.get("pendingApp"),r=n.get("name"),i=n.get("displayName"),s,o;e.get("hsaChallengeRequired")?this.gotoState("active.authUI.hsa"):this.gotoState("active.springboard"),e.validateUserIfNeeded(),n.set("isWaiting",NO);var u=n.get("postDisplayAction");n.set("postDisplayAction",undefined),u&&u.apply(this);if(n.get("loadInBackground")){SC.info("Not showing error dialog since app would load in background"),n.teardown();return}if(n.get("isIntermediateFailedToLoad")){n.set("isIntermediateFailedToLoad",NO),n.teardown(),t.set("pendingApp",null);return}var a="Error.AppNotLoading.Title".loc(i);CW.stringIsCJK(i)&&(a=a.replace(/ /g,""));var f=this,l;CloudOS.get("isCloudOSMini")?l={title:"Button.TryAgain".loc(),action:function(){this.getPath("pane.modalPane").set("hideDelay",10),this.get("pane").remove(),n.teardown(),t.set("pendingApp",null),f.gotoState("active.springboard.waitingForApp")}}:l={title:"Button.OK".loc(),action:function(){this.getPath("pane.modalPane").set("hideDelay",10),this.get("pane").remove(),n.teardown(),t.set("pendingApp",null)}},CW.Alert.show({message:a,description:"Error.AppNotLoading.Description".loc(),middleButton:{title:"Error.Button.Report".loc(),action:function(){this.getPath("pane.modalPane").set("paneFadeOutDuration",0),this.get("pane").remove(),CloudOS.appController.showErrorReporter(n,null,NO,"loadFailure"
),n.teardown(),t.set("pendingApp",null)}},rightButton:l}),COS.statsController.recordStat("cloudos","AppLoadFailure",{appName:r})}}),reloadApp:function(){this.gotoState("active.springboard.waitingForApp")},authDidValidate:function(){var e=COS.authUIController;e.userDidAuthenticate(),e.reportAuthSuccess("validate")},authDidNotValidate:function(){window.location.hash="",CloudOS.authController.logoutUser(function(){CK.reloadWithReason("Intermediate validate call failed with 401/421 response")},YES)},authDidNotConnect:function(e){SC.warn('Intermediate validate call failed with failureReason as "%@"',e)}})})}),CloudOS.ServiceLockedState=SC.State.design({enterState:function(e){var t=this,n=e?e.retryAfter:null,r=CloudOS.appController,i=e.appToDisable||r.get("currentApp")||r.get("pendingApp"),s=i.get("name"),o=i.get("displayName"),u="Service.Locked.Title".loc({appName:o}),a=COS.authUIController.lockedAlertDescription("Service.Locked.Description.",n,o);CloudOS.notifyDialogAboveApp(),this.gotoState("active.springboard"),i.teardown(),CW.Alert.show({message:u,description:a,rightButton:{title:"Button.OK".loc(),action:function(){this.get("pane").remove(),CloudOS.notifyRemovalOfDialogAboveApp(),i.set("isDisabled",YES),n&&i.invokeLater(function(){this.set("isDisabled",NO)},n*1e3)}}})}}),CloudOS.SpringboardState=SC.State.extend({initialSubstate:"waitingForSpringBoardModule",enterState:function(e){SC.Module.loadModule("cloudos_foundation/springboard",this,function(){this.gotoState("springBoardDidLoad",e)})},waitingForSpringBoardModule:SC.State.design(),springBoardDidLoad:SC.State.design({enterState
.reloadWithReason("logout from springboard",e.substring(0,e.length-1)):CK.reloadWithReason("logout from springboard")},YES)}catch(e){SC.Logger.error("Error during Signout: "+e)}},showPCSDeletedMessage:function(e){CloudOS.authController.showPCSDeletedErrorMessage(e)}})}),waitingForApp:CloudOS.WaitingForAppState.design({userDidChooseApp:function(){var e=CloudOS.appController.get("pendingApp");e?(e.set("loadInBackground",NO),this.gotoState("active.springboard.waitingForApp")):this.gotoState("active.springboard")},globalAppSwitchWasRequested:function(){if(CloudOS.appController.get("pendingApp")===this._app){SC.info("Already waiting for app to load");return}this.gotoState("active.springboard.waitingForApp")},appCalledSwitchToApplication:function(){this.gotoState("active.springboard.waitingForApp")},logout:function(){this.abortLoad(),CloudOS.statechart.sendAction("logout")},showAccountSettings:function(){this.abortLoad(),CloudOS.statechart.sendAction("showAccountSettings")}}),exitState:function(){}}),window.VERSIONS={fonts:SC.buildNumber,cloudkitjs:2},CloudOS.AdjustablePane=CW.PanelPane.extend(CW.Animatability,CW.PaneAnimationSupport,COS.AnimatedPane,{classNames:["adjustable-pane"],classNameBindings:["isFullScreen:full-screen"],layout:{centerX:0,centerY:0},modalPane:COS.AnimatedPane.modalPane.extend({classNames:["adjustable-pane-modal"],showingState:{opacity:1}}),delegate:null,show:function(){var e=this.get("delegate");e&&typeof e.show=="function"&&e.show.apply(e,arguments)},paneDidShow:function(){var e=this.get("delegate"),t=this.get("layer");e&&typeof e.paneDidShow=="function"&&
,this.maxOpacity=e.maxOpacity,this.color=e.color,this.randomizedTrace=Math.random(),this.age=e.age},rand:function(e,t,n){return(t-e)*(n||Math.random())+e},setAge:function(e){var t=this.age=e,n=this.lifespan,r=t/n,i=l(r*s)*-0.5+.5;this.x=this.sx+r*this.dx,this.y=this.sy+r*this.dy,this.z=this.sz+r*this.dz,this.blur=this.camera.circleOfConfusionRadiusAtPoint(this.x,this.y,this.z)+this.additionalStaticBlur;var o=Math.min(1,Math.max(0,t/(this.birthTime*n))),u=Math.min(1,Math.max(0,(n-t)/(this.deathTime*n))),a=this.fadeInStartAge?Math.min(1,Math.max(0,(t-this.fadeInStartAge)/this.fadeInTime)):1,c=this.fadeOutStartAge?Math.min(1,Math.max(0,1-(t-this.fadeOutStartAge)/this.fadeOutTime)):1,h=1+this.opacityAmplitude*f(t*s*this.opacityFrequency)*i;this.opacity=this.maxOpacity*o*u*a*c*h,this.aspectModifier=1+this.aspectAmplitude*f(t*s*this.aspectFrequency)*i,this.rotation=(this.initialRotation+this.rotationSpeed*360*t)%360},fadeIn:function(){this.fadeInStartAge=this.age},fadeOut:function(){this.fadeOutStartAge=this.age},appendTo:function(e){e!==this.element.parentNode&&this.remove(),e.appendChild(this.element)},remove:function(){if(!this.element.parentNode)return;this.element.parentNode.removeChild(this.element)}};var p=CloudOS.CircleAnim=CW.Animation.extend({speedMultiplier:n?1.3:1,maxCircles:n?100:24,authMaxCircles:24,mode:null,camera:null,circles:null,container:null,freevars:"cameraX cameraY cameraZ time timeSpeed".w(),cameraXMouseSensitivity:n?1:.2,cameraYMouseSensitivity:n?1:.2,wantsFPSEvaluation:YES,wantsFastFPSEvaluation:YES,stopAnimatingAfter:n?12e4:6e4,_lastActivityTime:0,shouldEverForceGPU
:!SC.browser.isIE9OrLower,shouldForceGPU:NO,cameraX:{inertia:3,speed:1,current:0,to:0},cameraY:{inertia:3,speed:1,current:0,to:0},cameraZ:{inertia:n?8:3,speed:n?1.5:4,current:-1.4,to:-1.4},time:{from:0,to:31536e6,speed:1,tween:CW.Anim.tweens.LINEAR},timeSpeed:{from:1,current:1,to:1,inertia:2,speed:.7,headStart:.2,redirectTo:function(e){e===1?this.speed=3:this.speed=1,CW.Animation._inertiaFreevar.prototype.redirectTo.apply(this,arguments)}},modes:{blurred:{additionalStaticBlur:.011},normal:{additionalStaticBlur:.011}},setWindowSize:function(e,t){this.windowWidth=e,this.windowHeight=t,this.camera.setWindowSize(e,t);if(!this.running)for(var n=0,r;r=this.circles[n];n++)r.update()},init:function(){r&&(this.maxCircles*=2),i&&(this.maxCircles*=6),this.camera=new c,this.circles=[];var e=this.modes,t,n,s,o=this.modes={};for(t in e){s=o[t]={options:e[t]},s.guidForAppearance="",s.optionKeys=[];for(n in s.options)s.guidForAppearance+=n+":"+s.options[n]+",",s.optionKeys.push(n)}arguments.callee.base.apply(this,arguments)},setShouldForceGPU:function(e){this.shouldForceGPU=this.shouldEverForceGPU&&e,this.running||this.update()},update:function(){var e=this.time.current,t,r;this.camera.x=this.cameraX.current,this.camera.y=this.cameraY.current,this.camera.z=this.cameraZ.current,this.frameCount%2===0&&this.frameCount>10&&this.mode&&this.circles.length<this.maxCircles&&(this.circles.length<this.authMaxCircles||CloudOS.workspaceController.nowShowing===CloudOS.SPRINGBOARD)&&(t=new h(this.camera),t.owner=this,this.applyModeToCircle(this.mode,t),t.appendTo(this.container),t._startTime=e,this.circles
).cacheable(),marginBetweenImageAndAppName:8,autoResizeText:function(){return CK.get("isBeta")?"Beta":CK.get("isFuture")?"Future":CK.get("isCarry")?"Carry":""}.property(),autoResizePadding:function(){var e=parseInt(window.getComputedStyle(document.querySelector(".icloud-text"),":before").width);return this.getPath("autoResizeText.length")>0?{width:e+this.get("marginBetweenImageAndAppName")}:{width:e}}.property("autoResizeText").cacheable(),render:function(e){var t="";CK.get("isBeta")&&(t=" beta"),CK.get("isFuture")&&(t=" future"),CK.get("isCarry")&&(t=" carry"),e.push('<span class="icloud-text'+t+'"></span>'),arguments.callee.base.apply(this,arguments)},click:function(){window.location.hash=""}}),CloudOS.iFrameView=SC.View.extend({attributeBindings:["src","title"],tagName:"iframe",title:null,src:null,init:function(){arguments.callee.base.apply(this,arguments),COS.statsController.beginStat("cloudos",this+"_load_time")},didAppendToDocument:function(){var e=this.get("layer");e?COS.statsController.endStat("cloudos",this+"_load_time",null,{durationKeyName:"duration",includeLocationAndLocale:YES}):SC.warn("Failed to Load iframe %@"+this)}}),CloudOS.UnableToProceedAlert=CW.Alert.extend({init:function(){arguments.callee.base.apply(this,arguments),this.get("failureReason")||CW.fatalError("Cannot show `UnableToProceed Alert` without value for failureReason property")}}),CloudOS.UnableToProceedAlert.mixin({show:function(e){var t={failureReason:null,message:"Error.AuthDidNotConnect.Title".loc(),description:"Error.AuthDidNotConnect.Description".loc(),middleButton:{title:"Error.AuthDidNotConnect.Support"
.loc(),action:"support"},rightButton:{title:"Button.OK".loc(),action:function(){var e=this.get("pane");e.remove(),e.clearUserStateAndLogoutUser()}},leftButton:{title:"Error.Button.Report".loc(),action:function(){var e=this.get("pane"),t=e.get("failureReason");e.get("modalPane").set("paneFadeOutDuration",0),e.remove(),CK.errorCatcher.reportServerError({applicationName:"cloudos",error:t,dismissCallback:function(){e.clearUserStateAndLogoutUser()}})}},clearUserStateAndLogoutUser:function(){var e=CloudOS.authController;e.clearUserState(),e.logoutUser(function(){CK.reloadWithReason("Restart the session due to authDidNotConnect error.")},YES)},support:function(){window.open("Error.AuthDidNotConnect.Support.URL".loc())}};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);var r=this.create(t);return r.append(),r}}),CloudOS.mainPage=SC.Page.design({mainPane:SC.MainPane.extend(CW.DropTarget,CloudOS.AdjustViewLayoutOnMobile,{layout:{left:0,right:0,top:0,bottom:0,zIndex:2,minHeight:COS.MIN_HEIGHT,minWidth:COS.MIN_WIDTH},init:function(){this.adjustLayoutOnMobile(["minWidth","minHeight"]),arguments.callee.base.apply(this,arguments),CW.notificationCenter.subscribeToNotification("activateMinimumSize",this,"activateMinimumSize"),CW.notificationCenter.subscribeToNotification("deactivateMinimumSize",this,"deactivateMinimumSize"),CW.notificationCenter.subscribeToNotification("icloudNoticeVisibilityChanged",this,"icloudNoticeVisibilityChanged")},activateMinimumSize:function(){this.set("layout",{left:0,right:0,top:0,bottom:0,zIndex:2,minHeight:COS.MIN_HEIGHT,minWidth:COS.MIN_WIDTH}),this.invokeLast(function(
){window.localeDidLoad=!0,SC.Event.add(document,"mousemove",function(e){var t=CloudOS.appController.getPath("currentApp"),n={clientX:e.clientX,clientY:e.clientY},r;if(!t||!t.get("contentWindow")||!t.get("isReady"))return YES;t.passMessage("_mouseMove",n)}),SC.Event.add(document,"mouseup",function(e){var t=CloudOS.appController.getPath("currentApp"),n={clientX:e.clientX,clientY:e.clientY},r;if(!t||!t.get("contentWindow")||!t.get("isReady"))return YES;t.passMessage("_mouseUp",n)});if(CloudOS.get("isCloudOSMini")){var e=CloudOS.appController.getDefaultAppName();CloudOS.displayApps.push({name:e,isDynamicallyLoaded:YES})}else CloudOSBootstrap.isOnSupportedMobile||SC.Module.loadModule("cloudos_foundation/springboard",this,function(){CloudOS.configureSpringboard()});CloudOS.getPath("mainPage.mainPane").append(),SC.debug("CloudOS.main() already has localized strings, proceeding to run CloudOS.run() now."),CloudOS.run(),CloudOS.invokeDelegateMethod(t,"applicationDidStart"),CloudOS.set("mainHasCompleted",YES)})},function(){var e="cloudkit/error_catcher";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/stylesheet.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/error_catcher/1812Project43/en-us/"
,isPrefetched:YES})}(),function(){var e="cloudkit/core_types";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:[],styles2x:[],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/core_types/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/core_types/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="cloudos_foundation/language";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/language/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/language/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/language/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/language/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="cloudkit/first_run";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:["coreweb/timezone_picker","cloudkit/photo"],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/first_run/1812Project43/en-us/"
,isPrefetched:YES})}(),function(){var e="cloudkit/photo";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:[],styles2x:[],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/photo/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudkit/photo/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="coreweb/date_formatter";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:[],styles2x:[],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/date_formatter/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/date_formatter/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="coreweb/timezone_picker";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/coreweb/timezone_picker/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="cloudos_foundation/alarms";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;
SC.MODULE_INFO[e]=SC.Object.create({dependencies:["coreweb/date_formatter"],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/alarms/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/alarms/1812Project43/en-us/stylesheet.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/alarms/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/alarms/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="cloudos_foundation/sharing";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:["cloudkit/core_types"],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/sharing/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/sharing/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/sharing/1812Project43/en-us/",stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/sharing/1812Project43/en-us/",isPrefetched:YES})}(),function(){var e="cloudos_foundation/springboard";if(!SC.MODULE_INFO)throw"SC.MODULE_INFO is not defined!";if(SC.MODULE_INFO[e])return;SC.MODULE_INFO[e]=SC.Object.create({dependencies:[],styles:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/springboard/1812Project43/en-us/stylesheet.css"],styles2x:["https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/springboard/1812Project43/en-us/stylesheet@2x.css"],scriptURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/springboard/1812Project43/en-us/"
,stringURL:"https://icloud.cdn-apple.com/system/cloudos/1812Project43/cloudos_foundation/springboard/1812Project43/en-us/",isLoaded:YES,source:'CloudOS.mixin({configureSpringboard:function(){if(this._hasConfiguredSpringBoard)return;var e={isShowingObserver:function(){CloudOS.workspaceController.get("nowShowing")<=CloudOS.AUTH?(this.$(".springboard-button-view").attr("tabindex","-1"),this.$().attr("aria-hidden","true")):(this.$(".springboard-button-view").attr("tabindex","0"),this.$().removeAttr("aria-hidden"))},springboardView:CloudOS.SpringboardView.design(COS.IsShowingSupport,{isAllowedToGenerateButtons:NO,init:function(){arguments.callee.base.apply(this,arguments);var e=CW.notificationCenter;e.subscribeToNotification("springboardMayProceed",this,"springboardMayProceed"),e.subscribeToNotification("requestedInfoForDynamicApp",this,"springboardMustWaitForDynamicApp"),e.subscribeToNotification("receivedInfoForDynamicApp",this,"springboardMayProceedFromDynamicApp"),e.subscribeToNotification("calendarIconWillRedraw",this,"springboardMustWaitForCalendarIconDrawing"),e.subscribeToNotification("calendarIconFinishedDrawing",this,"springboardMayProceedFromCalendarIconDrawing"),window.sv=this},displayKeys:[CloudOS.SPRINGBOARD,CloudOS.AUTH,CloudOS.SHARING],nowShowingBinding:"CloudOS.workspaceController.nowShowing",appIndicesBinding:"CloudOS.appController.appIndices",wantsAcceleratedLayer:!0,willShow:function(){CloudOS.workspaceController.hideCentralSpinner(null,!0)},springboardMayProceed:function(){this.set("isAllowedToGenerateButtons",YES)},springboardMustWaitForDynamicApp:function(e){this.addShowCondition("dynamic app "+e)},springboardMayProceedFromDynamicApp:function(e,t){this.metShowCondition("dynamic app "+e)},springboardMustWaitForCalendarIconDrawing\n:function(e,t){this.addShowCondition("Calendar icon must be drawn for correct language")},springboardMayProceedFromCalendarIconDrawing:function(e,t){this.metShowCondition("Calendar icon must be drawn for correct language")},childViews:CloudOS.SpringboardView.prototype.childViews.concat("accountMenu blurOverlay iCloudText".w()),blurOverlay:SC.View.extend(CW.Animatability,{classNames:"blur-overlay".w(),shouldShow:!0,shouldShowBinding:".parentView.isDecorativeDimmed",layout:{left:0,top:0,right:0,bottom:0,zIndex:2,opacity:1},shouldShowDidChange:function(){if(this.get("shouldShow"))this.animate("opacity",1,250),this.set("isVisible",!0);else{var e=this;this.animate("opacity",0,{duration:250,_updateVisibility:function(){e.set("isVisible",!1)}.listens("finish")})}}.observes("shouldShow")}),iCloudText:CloudOS.iCloudTextView.design({isEnabled:NO}),accountMenu:CloudOS.AccountMenuView.design(),isOffscreen:YES,isDecorativeDimmed:function(){var e=this.get("nowShowing");return e===CloudOS.AUTH||e===CloudOS.SHARING||!!this.get("wantsDD")}.property("nowShowing","wantsDD"),_setWantsDD:function(){var e=this.get("nowShowing")===CloudOS.AUTH;e?(this.set("wantsDD",YES),this._ddSetter&&this._ddSetter.invalidate(),this._ddSetter=null):this._ddSetter=this.invokeLater(function(){this.set("wantsDD",NO)},200)}.observes("nowShowing"),toggleChrome:function(){var e=this.get("isDecorativeDimmed");if(this.__lastToggleChromeDim__===(this.__lastToggleChromeDim__=e))return;this.accountMenu.animate("opacity",1-e,{duration:e?0:500,mustKeepLayoutSync:NO})}.observes("isDecorativeDimmed"),__lastToggleChromeDim__:NO\n,didShow:function(){this.showNotificationsIfNeeded()},didUndim:function(){this.showNotificationsIfNeeded()},showNotificationsIfNeeded:function(){this.notifyUnqualified()},notifyUnqualified:function(){var e=CloudOS.authController;if(!this._hasNotifiedUnqualified&&e.get("userRequiresUnqualifiedNotification")){var t=e.get("displayableCurrentDomain");CloudOS.iOSNotificationForSpringboard.enqueue({message:"Auth.Notification.Unqualified.Title".loc({currentDomain:t}),description:"Auth.Notification.Unqualified.Description".loc()}),this._hasNotifiedUnqualified=YES}}})},t=CloudOS.mainPage.mainPane,n={owner:t};t.appendChild(e.springboardView.create(n)),t.addObserver("CloudOS.workspaceController.nowShowing",e.isShowi