/*!
 * infusion - v4.8.0
 *
 * Build Info:
 *  branch: main
 *  revision: 60d89fe69
 *  build date: 2025-02-16T09:56:42-05:00Z
 *  includes: fluid-framework
 *  excludes: jquery, jquery-ui
*/
/*!
 * Fluid Infusion v4.8.0
 *
 * Infusion is distributed under the Educational Community License 2.0 and new BSD licenses:
 * http://wiki.fluidproject.org/display/fluid/Fluid+Licensing
 *
 * Copyright The Infusion copyright holders
 * See the AUTHORS.md file at the top-level directory of this distribution and at
 * https://github.com/fluid-project/infusion/raw/main/AUTHORS.md
 */
"use strict";var fluid=fluid||{};fluid.version="Infusion 4.8.0";fluid.Error=Error;fluid.environment={fluid:fluid};fluid.global=fluid.global||typeof window!=="undefined"?window:typeof self!=="undefined"?self:{};fluid.invokeLater=function(func){return setTimeout(func,0)};fluid.defeatLogging=true;fluid.activityTracing=false;fluid.activityTrace=[];var activityParser=/(%\w+)/g;fluid.renderActivityArgument=function(arg){if(fluid.isComponent(arg)){return fluid.dumpComponentAndPath(arg)}else{return arg}};fluid.renderOneActivity=function(activity,nowhile){var togo=nowhile===true?[]:["    while "];var message=activity.message;var index=activityParser.lastIndex=0;while(true){var match=activityParser.exec(message);if(match){var key=match[1].substring(1);togo.push(message.substring(index,match.index));togo.push(fluid.renderActivityArgument(activity.args[key]));index=activityParser.lastIndex}else{break}}if(index<message.length){togo.push(message.substring(index))}return togo};fluid.renderActivity=function(activityStack,renderer){renderer=renderer||fluid.renderOneActivity;return fluid.transform(activityStack,renderer)};fluid.singleThreadLocal=function(initFunc){var value=initFunc();return function(newValue){return newValue===undefined?value:value=newValue}};fluid.threadLocal=fluid.singleThreadLocal;fluid.globalThreadLocal=fluid.threadLocal((function(){return{}}));fluid.getActivityStack=function(){var root=fluid.globalThreadLocal();if(!root.activityStack){root.activityStack=[]}return root.activityStack};fluid.describeActivity=fluid.getActivityStack;fluid.logActivity=function(activity){activity=activity||fluid.describeActivity();var rendered=fluid.renderActivity(activity).reverse();if(rendered.length>0){fluid.log("Current activity: ");fluid.each(rendered,(function(args){fluid.log.apply(null,args)}))}};fluid.pushActivity=function(type,message,args){var record={type:type,message:message,args:args,time:(new Date).getTime()};if(fluid.activityTracing){fluid.activityTrace.push(record)}if(fluid.passLogLevel(fluid.logLevel.TRACE)){fluid.log.apply(null,fluid.renderOneActivity(record,true))}var activityStack=fluid.getActivityStack();activityStack.push(record)};fluid.popActivity=function(popframes){popframes=popframes||1;if(fluid.activityTracing){fluid.activityTrace.push({pop:popframes})}var activityStack=fluid.getActivityStack();var popped=activityStack.length-popframes;activityStack.length=popped<0?0:popped};fluid.FluidError=function(){var togo=Error.apply(this,arguments);this.message=togo.message;try{throw togo}catch(togo){this.stack=togo.stack}return this};fluid.FluidError.prototype=Object.create(Error.prototype);fluid.logFailure=function(args,activity){fluid.log.apply(null,[fluid.logLevel.FAIL,"ASSERTION FAILED: "].concat(args));fluid.logActivity(activity)};fluid.renderLoggingArg=function(arg){return arg===undefined?"undefined":fluid.isPrimitive(arg)||!fluid.isPlainObject(arg)?arg:JSON.stringify(arg)};fluid.builtinFail=function(args){var message=fluid.transform(args,fluid.renderLoggingArg).join("");throw new fluid.FluidError("Assertion failure - check console for more details: "+message)};fluid.fail=function(...messages){var activity=fluid.makeArray(fluid.describeActivity());fluid.popActivity(activity.length);if(fluid.failureEvent){fluid.failureEvent.fire(messages,activity)}else{fluid.logFailure(messages,activity);fluid.builtinFail(messages,activity)}};fluid.notrycatch=false;fluid.tryCatch=function(tryfun,catchfun,finallyfun){finallyfun=finallyfun||fluid.identity;if(fluid.notrycatch){var togo=tryfun();finallyfun();return togo}else{try{return tryfun()}catch(e){if(catchfun){catchfun(e)}else{throw e}}finally{finallyfun()}}};fluid.expect=function(name,target,members){fluid.transform(fluid.makeArray(members),(function(key){if(target[key]===undefined){fluid.fail(name+" missing required member "+key)}}))};fluid.isLogging=function(){return logLevelStack[0].priority>fluid.logLevel.IMPORTANT.priority};fluid.isLogLevel=function(arg){return fluid.isMarker(arg)&&arg.priority!==undefined};fluid.passLogLevel=function(testLogLevel){return testLogLevel.priority<=logLevelStack[0].priority};fluid.setLogging=function(enabled){var logLevel;if(typeof enabled==="boolean"){logLevel=fluid.logLevel[enabled?"INFO":"IMPORTANT"]}else if(fluid.isLogLevel(enabled)){logLevel=enabled}else{fluid.fail("Unrecognised fluid logging level ",enabled)}logLevelStack.unshift(logLevel);fluid.defeatLogging=!fluid.isLogging()};fluid.setLogLevel=fluid.setLogging;fluid.popLogging=function(){var togo=logLevelStack.length===1?logLevelStack[0]:logLevelStack.shift();fluid.defeatLogging=!fluid.isLogging();return togo};fluid.doBrowserLog=function(args){if(typeof console!=="undefined"){if(console.debug){console.debug.apply(console,args)}else if(typeof console.log==="function"){console.log.apply(console,args)}}};fluid.log=function(){var directArgs=fluid.makeArray(arguments);var userLogLevel=fluid.logLevel.INFO;if(fluid.isLogLevel(directArgs[0])){userLogLevel=directArgs.shift()}if(fluid.passLogLevel(userLogLevel)){fluid.loggingEvent.fire(directArgs)}};fluid.isValue=function(value){return value!==undefined&&value!==null};fluid.isPrimitive=function(value){var valueType=typeof value;return!value||valueType==="string"||valueType==="boolean"||valueType==="number"||valueType==="function"};fluid.isJQuery=function(totest){return Boolean(totest&&totest.jquery&&totest.constructor&&totest.constructor.prototype&&totest.constructor.prototype.jquery)};fluid.isArrayable=function(totest){return Boolean(totest)&&(Object.prototype.toString.call(totest)==="[object Array]"||fluid.isJQuery(totest))};fluid.isPlainObject=function(totest,strict){var string=Object.prototype.toString.call(totest);if(string==="[object Array]"){return!strict}else if(string!=="[object Object]"){return false}return!totest.constructor||!totest.constructor.prototype||Object.prototype.hasOwnProperty.call(totest.constructor.prototype,"isPrototypeOf")};fluid.typeCode=function(totest){return fluid.isPrimitive(totest)||!fluid.isPlainObject(totest)?"primitive":fluid.isArrayable(totest)?"array":"object"};fluid.isIoCReference=function(ref){return typeof ref==="string"&&ref.charAt(0)==="{"};fluid.isReferenceOrExpander=function(ref){return ref&&(fluid.isIoCReference(ref)||ref.expander)};fluid.isDOMNode=function(obj){return obj&&typeof obj.nodeType==="number"};fluid.isComponent=function(obj){return obj&&obj.constructor===fluid.componentConstructor};fluid.isUncopyable=function(totest){return fluid.isPrimitive(totest)||!fluid.isPlainObject(totest)};fluid.isApplicable=function(totest){return totest.apply&&typeof totest.apply==="function"};fluid.identity=function(arg){return arg};fluid.notImplemented=function(){fluid.fail("This operation is not implemented")};fluid.firstDefined=function(a,b){return a===undefined?b:a};fluid.freshContainer=function(tocopy){return fluid.isArrayable(tocopy)?[]:{}};fluid.testStrategyRecursion=function(funcName,segs){if(segs.length>fluid.strategyRecursionBailout){fluid.fail("Runaway recursion encountered in "+funcName+" - reached path depth of "+fluid.strategyRecursionBailout+" via path of "+segs.join(".")+"this object is probably circularly connected. Either adjust your object structure to remove the circularity or increase fluid.strategyRecursionBailout")}};fluid.copyRecurse=function(tocopy,segs){fluid.testStrategyRecursion("fluid.copy",segs);if(fluid.isUncopyable(tocopy)){return tocopy}else{return fluid.transform(tocopy,(function(value,key){segs.push(key);var togo=fluid.copyRecurse(value,segs);segs.pop();return togo}))}};fluid.copy=function(tocopy){return fluid.copyRecurse(tocopy,[])};fluid.extend=$.extend;fluid.makeArray=function(arg){var togo=[];if(arg!==null&&arg!==undefined){if(fluid.isPrimitive(arg)||fluid.isPlainObject(arg,true)||typeof arg.length!=="number"){togo.push(arg)}else{for(var i=0;i<arg.length;++i){togo[i]=arg[i]}}}return togo};fluid.pushArray=function(holder,member,topush){var array=holder[member]?holder[member]:holder[member]=[];if(Array.isArray(topush)){array.push.apply(array,topush)}else{array.push(topush)}};function transformInternal(source,togo,key,transformations){var transit=source[key];for(var j=0;j<transformations.length;++j){transit=transformations[j](transit,key)}if(transit!==fluid.NO_VALUE){togo[key]=transit}}fluid.transform=function(source,...transformations){if(fluid.isPrimitive(source)){return source}var togo=fluid.freshContainer(source);if(fluid.isArrayable(source)){for(var i=0;i<source.length;++i){transformInternal(source,togo,i,transformations)}}else{for(var key in source){transformInternal(source,togo,key,transformations)}}return togo};fluid.forEachInRange=function(array,start,end,func){for(var i=start;i<end;++i){func(array[i],i)}};fluid.peek=function(array){return array.length===0?undefined:array[array.length-1]};fluid.each=function(source,func){if(fluid.isArrayable(source)){for(var i=0;i<source.length;++i){func(source[i],i)}}else{for(var key in source){func(source[key],key)}}};fluid.make_find=function(find_if){var target=find_if?false:undefined;return function(source,func,deffolt){var disp;if(fluid.isArrayable(source)){for(var i=0;i<source.length;++i){disp=func(source[i],i);if(disp!==target){return find_if?source[i]:disp}}}else{for(var key in source){disp=func(source[key],key);if(disp!==target){return find_if?source[key]:disp}}}return deffolt}};fluid.find=fluid.make_find(false);fluid.find_if=fluid.make_find(true);fluid.remove_if=function(source,fn,target){if(fluid.isArrayable(source)){for(var i=source.length-1;i>=0;--i){if(fn(source[i],i)){if(target){target.unshift(source[i])}source.splice(i,1)}}}else{for(var key in source){if(fn(source[key],key)){if(target){target[key]=source[key]}delete source[key]}}}return target||source};fluid.generate=function(n,generator,applyFunc){var togo=[];for(var i=0;i<n;++i){togo[i]=applyFunc?generator(i):generator}return togo};fluid.iota=function(count,first){first=first||0;var togo=[];for(var i=0;i<count;++i){togo[togo.length]=first++}return togo};fluid.getMembers=function(holder,name){return fluid.transform(holder,(function(member){return fluid.get(member,name)}))};fluid.filterKeys=function(toFilter,keys,exclude){return fluid.remove_if($.extend({},toFilter),(function(value,key){return exclude^keys.indexOf(key)===-1}))};fluid.censorKeys=function(toCensor,keys){return fluid.filterKeys(toCensor,keys,true)};fluid.keys=function(obj){var togo=[];for(var key in obj){togo.push(key)}return togo};fluid.values=function(obj){var togo=[];for(var key in obj){togo.push(obj[key])}return togo};fluid.keyForValue=function(obj,value){return fluid.find(obj,(function(thisValue,key){if(value===thisValue){return key}}))};fluid.arrayToHash=function(array){var togo={};fluid.each(array,(function(el){togo[el]=true}));return togo};fluid.hashToArray=function(hash,keyName,func){var togo=[];fluid.each(hash,(function(el,key){var newEl=el;if(keyName!==undefined){newEl={};newEl[keyName]=key}if(func){newEl=func(newEl,el,key)||newEl}else if(newEl!==el){$.extend(true,newEl,el)}togo.push(newEl)}));return togo};fluid.flatten=function(array){var togo=[];fluid.each(array,(function(element){if(fluid.isArrayable(element)){togo=togo.concat(element)}else{togo.push(element)}}));return togo};fluid.clear=function(target){if(fluid.isArrayable(target)){target.length=0}else{for(var i in target){delete target[i]}}};fluid.compareStringLength=function(ascending){return ascending?function(a,b){return a.length-b.length}:function(a,b){return b.length-a.length}};fluid.parseInteger=function(string){return isFinite(string)&&string%1===0?Number(string):NaN};fluid.roundToDecimal=function(num,scale,method){scale=scale&&scale>=0?Math.round(scale):0;if(method==="ceil"||method==="floor"){return Number(Math[method](num+"e"+scale)+"e-"+scale)}else{var sign=num>=0?1:-1;return Number(sign*(Math.round(Math.abs(num)+"e"+scale)+"e-"+scale))}};fluid.debounce=function(func,wait,immediate){var timeout,result;return function(){var context=this,args=arguments;var later=function(){timeout=null;if(!immediate){result=func.apply(context,args)}};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow){result=func.apply(context,args)}return result}};fluid.freezeRecursive=function(tofreeze,segs){segs=segs||[];fluid.testStrategyRecursion("fluid.freezeRecursive",segs);if(fluid.isPlainObject(tofreeze)){fluid.each(tofreeze,(function(value,key){segs.push(key);fluid.freezeRecursive(value,segs);segs.pop()}));return Object.freeze(tofreeze)}else{return tofreeze}};fluid.marker=function(){};fluid.makeMarker=function(value,extra){var togo=Object.create(fluid.marker.prototype);togo.value=value;fluid.extend(togo,extra);return Object.freeze(togo)};fluid.NO_VALUE=fluid.makeMarker("NO_VALUE");fluid.EXPAND=fluid.makeMarker("EXPAND");fluid.isMarker=function(totest,type){if(!(totest instanceof fluid.marker)){return false}if(!type){return true}return totest.value===type.value};fluid.logLevelsSpec={FATAL:0,FAIL:5,WARN:10,IMPORTANT:12,INFO:15,TRACE:20};fluid.logLevel=fluid.transform(fluid.logLevelsSpec,(function(value,key){return fluid.makeMarker(key,{priority:value})}));var logLevelStack=[fluid.logLevel.IMPORTANT];fluid.model={};fluid.model.copyModel=function(target,source){fluid.clear(target);$.extend(true,target,source)};fluid.model.parseEL=function(EL){return EL===""?[]:String(EL).split(".")};fluid.model.composePath=function(prefix,suffix){return prefix===""?suffix:suffix===""?prefix:prefix+"."+suffix};fluid.model.composeSegments=function(){return fluid.makeArray(arguments).join(".")};fluid.lastDotIndex=function(path){return path.lastIndexOf(".")};fluid.model.getToTailPath=function(path){var lastdot=fluid.lastDotIndex(path);return lastdot===-1?"":path.substring(0,lastdot)};fluid.model.getTailPath=function(path){var lastdot=fluid.lastDotIndex(path);return path.substring(lastdot+1)};fluid.path=fluid.model.composeSegments;fluid.composePath=fluid.model.composePath;fluid.requireDataBinding=function(){fluid.fail("Please include DataBinding.js in order to operate complex model accessor configuration")};fluid.model.setWithStrategy=fluid.model.getWithStrategy=fluid.requireDataBinding;fluid.model.resolvePathSegment=function(root,segment,create,origEnv){if(!origEnv&&root.resolvePathSegment){var togo=root.resolvePathSegment(segment);if(togo!==undefined){return togo}}if(create&&root[segment]===undefined){return root[segment]={}}return root[segment]};fluid.model.parseToSegments=function(EL,parseEL,copy){return typeof EL==="number"||typeof EL==="string"?parseEL(EL):copy?fluid.makeArray(EL):EL};fluid.model.pathToSegments=function(EL,config){var parser=config&&config.parser?config.parser.parse:fluid.model.parseEL;return fluid.model.parseToSegments(EL,parser)};fluid.model.accessImpl=function(root,EL,newValue,config,initSegs,returnSegs,traverser){var segs=fluid.model.pathToSegments(EL,config);var initPos=0;if(initSegs){initPos=initSegs.length;segs=initSegs.concat(segs)}var uncess=newValue===fluid.NO_VALUE?0:1;root=traverser(root,segs,initPos,config,uncess);if(newValue===fluid.NO_VALUE){return returnSegs?{root:root,segs:segs}:root}else{root[fluid.peek(segs)]=newValue}};fluid.model.accessSimple=function(root,EL,newValue,environment,initSegs,returnSegs){return fluid.model.accessImpl(root,EL,newValue,environment,initSegs,returnSegs,fluid.model.traverseSimple)};fluid.model.traverseSimple=function(root,segs,initPos,environment,uncess){var origEnv=environment;var limit=segs.length-uncess;for(var i=0;i<limit;++i){if(!root){return undefined}var segment=segs[i];if(environment&&environment[segment]){root=environment[segment]}else{root=fluid.model.resolvePathSegment(root,segment,uncess===1,origEnv)}environment=null}return root};fluid.model.setSimple=function(root,EL,newValue,environment,initSegs){fluid.model.accessSimple(root,EL,newValue,environment,initSegs,false)};fluid.model.getSimple=function(root,EL,environment,initSegs){if(EL===null||EL===undefined||EL.length===0){return root}return fluid.model.accessSimple(root,EL,fluid.NO_VALUE,environment,initSegs,false)};fluid.getImmediate=function(root,segs,i){var limit=i===undefined?segs.length:i+1;for(var j=0;j<limit;++j){root=root?root[segs[j]]:undefined}return root};fluid.decodeAccessorArg=function(arg3){return!arg3||arg3===fluid.model.defaultGetConfig||arg3===fluid.model.defaultSetConfig?null:arg3.type==="environment"?arg3.value:undefined};fluid.set=function(root,EL,newValue,config,initSegs){var env=fluid.decodeAccessorArg(config);if(env===undefined){fluid.model.setWithStrategy(root,EL,newValue,config,initSegs)}else{fluid.model.setSimple(root,EL,newValue,env,initSegs)}};fluid.get=function(root,EL,config,initSegs){var env=fluid.decodeAccessorArg(config);return env===undefined?fluid.model.getWithStrategy(root,EL,config,initSegs):fluid.model.accessImpl(root,EL,fluid.NO_VALUE,env,null,false,fluid.model.traverseSimple)};fluid.getGlobalValue=function(path,env){if(path){env=env||fluid.environment;return fluid.get(fluid.global,path,{type:"environment",value:env})}};fluid.bind=function(obj,fnName,args){return obj[fnName].apply(obj,fluid.makeArray(args))};fluid.proxyComponentArgs=fluid.identity;fluid.invokeGlobalFunction=function(functionPath,args,environment){var func=fluid.getGlobalValue(functionPath,environment);if(!func){fluid.fail("Error invoking global function: "+functionPath+" could not be located")}else{var argsArray=fluid.isArrayable(args)?args:fluid.makeArray(args);fluid.proxyComponentArgs(argsArray);return func.apply(null,argsArray)}};fluid.registerGlobalFunction=function(functionPath,func,env){env=env||fluid.environment;fluid.set(fluid.global,functionPath,func,{type:"environment",value:env})};fluid.setGlobalValue=fluid.registerGlobalFunction;fluid.registerNamespace=function(path,env){env=env||fluid.environment;var existing=fluid.getGlobalValue(path,env);if(!existing){existing={};fluid.setGlobalValue(path,existing,env)}return existing};fluid.dumpEl=fluid.identity;fluid.renderTimestamp=fluid.identity;fluid.generateUniquePrefix=function(){return Math.floor(Math.random()*1e12).toString(36)+"-"};var fluid_prefix=fluid.generateUniquePrefix();fluid.fluidInstance=fluid_prefix;var fluid_guid=1;fluid.allocateGuid=function(){return fluid_prefix+fluid_guid++};fluid.registerNamespace("fluid.event");fluid.extremePriority=4e9;fluid.priorityTypes={first:-1,last:1,before:0,after:0};fluid.extremalPriorities={none:0,transaction:10,testing:20,authoring:30};fluid.parsePriorityConstraint=function(constraint,fixedOnly,site){var segs=constraint.split(":");var type=segs[0];var lookup=fluid.priorityTypes[type];if(lookup===undefined){fluid.fail("Invalid constraint type in priority field "+constraint+": the only supported values are "+fluid.keys(fluid.priorityTypes).join(", ")+" or numeric")}if(fixedOnly&&lookup===0){fluid.fail("Constraint type in priority field "+constraint+" is not supported in a "+site+" record - you must use either a numeric value or first, last")}return{type:segs[0],target:segs[1]}};fluid.parsePriority=function(priority,count,fixedOnly,site){priority=priority||0;var togo={count:count||0,fixed:null,constraint:null,site:site};if(typeof priority==="number"){togo.fixed=-priority}else{togo.constraint=fluid.parsePriorityConstraint(priority,fixedOnly,site)}var multiplier=togo.constraint?fluid.priorityTypes[togo.constraint.type]:0;if(multiplier!==0){var target=togo.constraint.target||"none";var extremal=fluid.extremalPriorities[target];if(extremal===undefined){fluid.fail("Unrecognised extremal priority target "+target+": the currently supported values are "+fluid.keys(fluid.extremalPriorities).join(", ")+": register your value in fluid.extremalPriorities")}togo.fixed=multiplier*(fluid.extremePriority+extremal)}if(togo.fixed!==null){togo.fixed+=togo.count/1024}return togo};fluid.renderPriority=function(parsed){return parsed.constraint?parsed.constraint.target?parsed.constraint.type+":"+parsed.constraint.target:parsed.constraint.type:Math.floor(parsed.fixed)};fluid.compareByPriority=function(recA,recB){if(recA.priority.fixed!==null&&recB.priority.fixed!==null){return recA.priority.fixed-recB.priority.fixed}else{return(recA.priority.fixed===null)-(recB.priority.fixed===null)}};fluid.honourConstraint=function(array,firstConstraint,c){var constraint=array[c].priority.constraint;var matchIndex=fluid.find(array,(function(element,index){return element.namespace===constraint.target?index:undefined}),-1);if(matchIndex===-1){return true}else if(matchIndex>=firstConstraint){return false}else{var offset=constraint.type==="after"?1:0;var target=matchIndex+offset;var temp=array[c];for(var shift=c;shift>=target;--shift){array[shift]=array[shift-1]}array[target]=temp;return true}};fluid.sortByPriority=function(array){array.sort(fluid.compareByPriority);var firstConstraint=fluid.find(array,(function(element,index){return element.priority.constraint&&fluid.priorityTypes[element.priority.constraint.type]===0?index:undefined}),array.length);while(true){if(firstConstraint===array.length){return array}var oldFirstConstraint=firstConstraint;for(var c=firstConstraint;c<array.length;++c){var applied=fluid.honourConstraint(array,firstConstraint,c);if(applied){++firstConstraint}}if(firstConstraint===oldFirstConstraint){var holders=array.slice(firstConstraint);fluid.fail("Could not find targets for any constraints in "+holders[0].priority.site+" ",holders,": none of the targets ("+fluid.getMembers(holders,"priority.constraint.target").join(", ")+") matched any namespaces of the elements in (",array.slice(0,firstConstraint),") - this is caused by either an invalid or circular reference")}}};fluid.parsePriorityRecords=function(records,name){var array=fluid.hashToArray(records,"namespace",(function(newElement,oldElement){$.extend(newElement,oldElement);newElement.priority=fluid.parsePriority(oldElement.priority,0,false,name)}));fluid.sortByPriority(array);return array};fluid.event.identifyListener=function(listener,soft){if(typeof listener!=="string"&&!listener.$$fluid_guid&&!soft){listener.$$fluid_guid=fluid.allocateGuid()}return listener.$$fluid_guid};fluid.event.impersonateListener=function(origListener,newListener){fluid.event.identifyListener(origListener);newListener.$$fluid_guid=origListener.$$fluid_guid};fluid.event.sortListeners=function(listeners){var togo=[];fluid.each(listeners,(function(oneNamespace){var headHard;for(var i=0;i<oneNamespace.length;++i){var thisListener=oneNamespace[i];if(!thisListener.softNamespace&&!headHard){headHard=thisListener}}if(headHard){togo.push(headHard)}else{togo=togo.concat(oneNamespace)}}));return fluid.sortByPriority(togo)};fluid.event.resolveListener=function(listener){var listenerName=listener.globalName||(typeof listener==="string"?listener:null);if(listenerName){var listenerFunc=fluid.getGlobalValue(listenerName);if(!listenerFunc){fluid.fail("Unable to look up name "+listenerName+" as a global function")}else{listener=listenerFunc}}return listener};fluid.nameComponent=function(that){return that?fluid.dumpComponentAndPath(that):"[unknown component]"};fluid.event.nameEvent=function(that,eventName){return eventName+" of "+fluid.nameComponent(that)};fluid.event.firer=function(){};fluid.makeEventFirer=function(options){options=options||{};var name=options.name||"<anonymous>";var that;var lazyInit=function(){that.listeners={};that.byId={};that.sortedListeners=[];that.onDestroy=null;that.addListener=function(listener,namespace,priority,softNamespace,listenerId){var record;if(that.destroyed){fluid.fail("Cannot add listener to destroyed event firer "+that.name)}if(!listener){return}if(fluid.isPlainObject(listener,true)&&!fluid.isApplicable(listener)){record=listener;listener=record.listener;namespace=record.namespace;priority=record.priority;softNamespace=record.softNamespace;listenerId=record.listenerId}if(typeof listener==="string"){listener={globalName:listener}}var id=listenerId||fluid.event.identifyListener(listener);namespace=namespace||id;record=$.extend(record||{},{namespace:namespace,listener:listener,softNamespace:softNamespace,listenerId:listenerId,priority:fluid.parsePriority(priority,that.sortedListeners.length,false,"listeners")});that.byId[id]=record;var thisListeners=that.listeners[namespace]=fluid.makeArray(that.listeners[namespace]);thisListeners[softNamespace?"push":"unshift"](record);that.sortedListeners=fluid.event.sortListeners(that.listeners)};that.addListener.apply(null,arguments)};that=Object.create(fluid.event.firer.prototype);fluid.extend(that,{eventId:fluid.allocateGuid(),name:name,ownerId:options.ownerId,typeName:"fluid.event.firer",destroy:function(){that.destroyed=true;fluid.each(that.onDestroy,(function(func){func()}))},addListener:function(){lazyInit.apply(null,arguments)},removeListener:function(listener){if(!that.listeners){return}var namespace,id,record;if(typeof listener==="string"){namespace=listener;record=that.listeners[namespace];if(!record){id=namespace;namespace=null}}else if(typeof listener==="function"){id=fluid.event.identifyListener(listener,true);if(!id){fluid.fail("Cannot remove unregistered listener function ",listener," from event "+that.name)}}var rec=that.byId[id];var softNamespace=rec&&rec.softNamespace;namespace=namespace||rec&&rec.namespace||id;delete that.byId[id];record=that.listeners[namespace];if(record){if(softNamespace){fluid.remove_if(record,(function(thisLis){return thisLis.listener.$$fluid_guid===id||thisLis.listenerId===id}))}else{record.shift()}if(record.length===0){delete that.listeners[namespace]}}that.sortedListeners=fluid.event.sortListeners(that.listeners)},fire:function(){var listeners=that.sortedListeners;if(options.promise){that.promisePayload=arguments[0]}if(!listeners||that.destroyed){return}for(var i=0;i<listeners.length;++i){var lisrec=listeners[i];if(typeof lisrec.listener!=="function"){lisrec.listener=fluid.event.resolveListener(lisrec.listener)}var listener=lisrec.listener;var ret=listener.apply(null,arguments);var value;if(options.preventable&&ret===false||that.destroyed){value=false}if(value!==undefined){return value}}}});if(options.promise){that.then=function(func){if("promisePayload"in that){func(that.promisePayload)}else{that.addListener(func)}}}return that};fluid.event.addPrimitiveListener=function(holder,name,func){var existing=holder[name];if(!existing){existing=holder[name]=[]}existing.push(func)};fluid.fireEvent=function(component,eventName,args){var firer=component.events&&component.events[eventName];if(firer){firer.fire.apply(null,fluid.makeArray(args))}};fluid.event.addListenerToFirer=function(firer,value,namespace,wrapper){wrapper=wrapper||fluid.identity;if(fluid.isArrayable(value)){for(var i=0;i<value.length;++i){fluid.event.addListenerToFirer(firer,value[i],namespace,wrapper)}}else if(typeof value==="function"||typeof value==="string"){wrapper(firer).addListener(value,namespace)}else if(value&&typeof value==="object"){wrapper(firer).addListener(value.listener,namespace||value.namespace,value.priority,value.softNamespace,value.listenerId)}};fluid.event.resolveListenerRecord=function(records){return{records:records}};fluid.expandImmediate=function(material){fluid.fail("fluid.expandImmediate could not be loaded - please include FluidIoC.js in order to operate IoC-driven event with descriptor "+material)};fluid.mergeListeners=function(that,events,listeners){fluid.each(listeners,(function(value,key){var firer,namespace;if(fluid.isIoCReference(key)){firer=fluid.expandImmediate(key,that);if(!firer){fluid.fail("Error in listener record: key "+key+' could not be looked up to an event firer - did you miss out "events." when referring to an event firer?')}}else{var keydot=key.indexOf(".");if(keydot!==-1){namespace=key.substring(keydot+1);key=key.substring(0,keydot)}if(!events[key]){fluid.fail("Listener registered for event "+key+" which is not defined for this component")}firer=events[key]}var record=fluid.event.resolveListenerRecord(value,that,key,namespace,true);fluid.event.addListenerToFirer(firer,record.records,namespace,record.adderWrapper)}))};fluid.eventFromRecord=function(eventSpec,eventKey,that){var isIoCEvent=eventSpec&&(typeof eventSpec!=="string"||fluid.isIoCReference(eventSpec));var event;if(isIoCEvent){if(!fluid.event.resolveEvent){fluid.fail("fluid.event.resolveEvent could not be loaded - please include FluidIoC.js in order to operate IoC-driven event with descriptor ",eventSpec)}else{event=fluid.event.resolveEvent(that,eventKey,eventSpec)}}else{event=fluid.makeEventFirer({name:fluid.event.nameEvent(that,eventKey),preventable:eventSpec==="preventable",promise:eventSpec==="promise",ownerId:that.id})}return event};fluid.mergeListenerPolicy=function(target,source,key){if(typeof key!=="string"){fluid.fail("Error in listeners declaration - the keys in this structure must resolve to event names - got "+key+" from ",source)}var hasNamespace=!fluid.isIoCReference(key)&&key.indexOf(".")!==-1;return hasNamespace?source||target:fluid.arrayConcatPolicy(target,source)};fluid.makeMergeListenersPolicy=function(merger,modelRelay){return function(target,source){target=target||{};if(modelRelay&&(fluid.isArrayable(source)||"target"in source&&(typeof source.target==="string"||source.target.segs))){target[""]=merger(target[""],source,"")}else{fluid.each(source,(function(listeners,key){target[key]=merger(target[key],listeners,key)}))}return target}};fluid.validateListenersImplemented=function(that){var errors=[];fluid.each(that.events,(function(event,name){fluid.each(event.sortedListeners,(function(lisrec){if(lisrec.listener===fluid.notImplemented||lisrec.listener.globalName==="fluid.notImplemented"){errors.push({name:name,namespace:lisrec.namespace,componentSource:fluid.model.getSimple(that.options.listeners,[name+"."+lisrec.namespace,0,"componentSource"])})}}))}));return errors};fluid.arrayConcatPolicy=function(target,source){return fluid.makeArray(target).concat(fluid.makeArray(source))};fluid.loggingEvent=fluid.makeEventFirer({name:"logging event"});fluid.addTimestampArg=function(args){var arg0=fluid.renderTimestamp(new Date)+":  ";args.unshift(arg0)};fluid.loggingEvent.addListener(fluid.doBrowserLog,"log");fluid.loggingEvent.addListener(fluid.identity,"filterArgs","before:log");fluid.loggingEvent.addListener(fluid.addTimestampArg,"addTimestampArg","after:filterArgs");fluid.upgradeError=function(originError,whileMsg){var error=originError instanceof Error?originError:fluid.isPrimitive(originError)?{message:originError}:fluid.extend({},originError);error.message=error.message+whileMsg;return error};fluid.failureEvent=fluid.makeEventFirer({name:"failure event"});fluid.failureEvent.addListener(fluid.builtinFail,"fail");fluid.failureEvent.addListener(fluid.logFailure,"log","before:fail");fluid.componentConstructor=function(){};Object.defineProperty(fluid.componentConstructor,"name",{value:"fluid.componentConstructor"});fluid.typeTag=function(type,id){var that=Object.create(fluid.componentConstructor.prototype);that.typeName=type;that.id=id||fluid.allocateGuid();return that};var gradeTick=1;var gradeTickStore={};fluid.defaultsStore={};fluid.flattenGradeName=function(gradeName){return typeof gradeName==="string"?gradeName:JSON.stringify(gradeName)};fluid.resolveGradesImpl=function(gs,gradeNames){gradeNames=fluid.makeArray(gradeNames);for(var i=gradeNames.length-1;i>=0;--i){var gradeName=gradeNames[i];var flatGradeName=fluid.flattenGradeName(gradeName);if(gradeName&&!gs.gradeHash[flatGradeName]){var isDynamic=fluid.isReferenceOrExpander(gradeName);var options=(isDynamic?null:fluid.rawDefaults(gradeName))||{};var thisTick=gradeTickStore[gradeName]||gradeTick-1;gs.lastTick=Math.max(gs.lastTick,thisTick);gs.gradeHash[flatGradeName]=true;gs.gradeChain.push(gradeName);var oGradeNames=fluid.makeArray(options.gradeNames);for(var j=oGradeNames.length-1;j>=0;--j){fluid.resolveGradesImpl(gs,oGradeNames[j])}}}return gs};fluid.resolveGradeStructure=function(defaultName,gradeNames){var gradeStruct={lastTick:0,gradeChain:[],gradeHash:{}};fluid.resolveGradesImpl(gradeStruct,[defaultName].concat(fluid.makeArray(gradeNames)));gradeStruct.gradeChain.reverse();return gradeStruct};fluid.hasGrade=function(options,gradeName){return!options||!options.gradeNames?false:options.gradeNames.includes(gradeName)};fluid.resolveGrade=function(defaults,defaultName,gradeNames){var gradeStruct=fluid.resolveGradeStructure(defaultName,gradeNames);var mergeArgs=fluid.transform(gradeStruct.gradeChain,fluid.rawDefaults,fluid.copy);fluid.remove_if(mergeArgs,(function(options){return!options}));var mergePolicy={};for(var i=0;i<mergeArgs.length;++i){if(mergeArgs[i]&&mergeArgs[i].mergePolicy){mergePolicy=$.extend(true,mergePolicy,mergeArgs[i].mergePolicy)}}mergeArgs=[mergePolicy,{}].concat(mergeArgs);var mergedDefaults=fluid.merge.apply(null,mergeArgs);mergedDefaults.gradeNames=gradeStruct.gradeChain;fluid.freezeRecursive(mergedDefaults);return{defaults:mergedDefaults,lastTick:gradeStruct.lastTick}};fluid.mergedDefaultsCache={};fluid.gradeNamesToKey=function(defaultName,gradeNames){return defaultName+"|"+gradeNames.join("|")};fluid.getMergedDefaults=function(defaultName,gradeNames){gradeNames=fluid.makeArray(gradeNames);var key=fluid.gradeNamesToKey(defaultName,gradeNames);var mergedDefaults=fluid.mergedDefaultsCache[key];if(mergedDefaults){var lastTick=0;var searchGrades=mergedDefaults.defaults.gradeNames;for(var i=0;i<searchGrades.length;++i){lastTick=Math.max(lastTick,gradeTickStore[searchGrades[i]]||0)}if(lastTick>mergedDefaults.lastTick){if(fluid.passLogLevel(fluid.logLevel.TRACE)){fluid.log(fluid.logLevel.TRACE,"Clearing cache for component "+defaultName+" with gradeNames ",searchGrades)}mergedDefaults=null}}if(!mergedDefaults){var defaults=fluid.rawDefaults(defaultName);if(!defaults){return defaults}mergedDefaults=fluid.mergedDefaultsCache[key]=fluid.resolveGrade(defaults,defaultName,gradeNames)}return mergedDefaults.defaults};fluid.NO_ARGUMENTS=fluid.makeMarker("NO_ARGUMENTS");fluid.upgradePrimitiveFunc=function(rec,key){if(rec&&fluid.isPrimitive(rec)){var togo={};togo[key||(typeof rec==="string"&&rec.charAt(0)!=="{"?"funcName":"func")]=rec;togo.args=fluid.NO_ARGUMENTS;return togo}else{return rec}};fluid.annotateListeners=function(componentName,options){options.listeners=fluid.transform(options.listeners,(function(record){var togo=fluid.makeArray(record);return fluid.transform(togo,(function(onerec){onerec=fluid.upgradePrimitiveFunc(onerec,"listener");onerec.componentSource=componentName;return onerec}))}));options.invokers=fluid.transform(options.invokers,(function(record){record=fluid.upgradePrimitiveFunc(record);if(record){record.componentSource=componentName}return record}))};fluid.workflowCache={};fluid.workflowCacheSorted=[];fluid.resortWorkflows=function(workflowType,baseIndex){var thisCache=fluid.workflowCache[workflowType];var parsed=fluid.parsePriorityRecords(thisCache,workflowType+" workflows");parsed.forEach((function(oneParsed,index){thisCache[oneParsed.namespace].index=index+baseIndex}));return parsed};fluid.indexOneWorkflows=function(gradeName,workflowType,workflows,baseIndex){fluid.each(workflows,(function(oneWorkflow,workflowKey){fluid.model.setSimple(fluid.workflowCache,[workflowType,workflowKey],{workflowType:workflowType,workflowName:workflowKey,priority:oneWorkflow.priority,gradeName:gradeName,workflowOptions:oneWorkflow})}));return fluid.resortWorkflows(workflowType,baseIndex)};fluid.clearGradeWorkflows=function(gradeName,workflowType){var cacheForType=fluid.workflowCache[workflowType];fluid.each(cacheForType,(function(oneWorkflow,workflowKey){if(oneWorkflow.gradeName===gradeName){delete cacheForType[workflowKey]}}))};fluid.indexGradeWorkflows=function(gradeName,options){fluid.clearGradeWorkflows(gradeName,"global");fluid.clearGradeWorkflows(gradeName,"local");var sortedGlobal=fluid.indexOneWorkflows(gradeName,"global",fluid.getImmediate(options,["workflows","global"]),0);var globalWorkflowCount=sortedGlobal.length;var sortedLocal=fluid.indexOneWorkflows(gradeName,"local",fluid.getImmediate(options,["workflows","local"]),globalWorkflowCount);fluid.workflowCacheSorted=sortedGlobal.concat(sortedLocal)};fluid.rawDefaults=function(componentName){var entry=fluid.defaultsStore[componentName];return entry&&entry.options};fluid.registerRawDefaults=function(componentName,options){fluid.pushActivity("registerRawDefaults","registering defaults for grade %componentName with options %options",{componentName:componentName,options:options});var optionsCopy=fluid.expandCompact?fluid.expandCompact(options):fluid.copy(options);fluid.annotateListeners(componentName,optionsCopy);fluid.indexGradeWorkflows(componentName,optionsCopy);delete optionsCopy.workflows;var callerInfo=fluid.getCallerInfo&&fluid.getCallerInfo(6);fluid.freezeRecursive(optionsCopy);fluid.defaultsStore[componentName]={options:optionsCopy,callerInfo:callerInfo};gradeTickStore[componentName]=gradeTick++;fluid.popActivity()};fluid.doIndexDefaults=function(defaultName,defaults,index,indexSpec){var requiredGrades=fluid.makeArray(indexSpec.gradeNames);for(var i=0;i<requiredGrades.length;++i){if(!fluid.hasGrade(defaults,requiredGrades[i])){return}}var indexFunc=typeof indexSpec.indexFunc==="function"?indexSpec.indexFunc:fluid.getGlobalValue(indexSpec.indexFunc);var keys=indexFunc(defaults)||[];for(var j=0;j<keys.length;++j){fluid.pushArray(index,keys[j],defaultName)}};fluid.indexDefaults=function(indexName,indexSpec){var index={};for(var defaultName in fluid.defaultsStore){var defaults=fluid.getMergedDefaults(defaultName);fluid.doIndexDefaults(defaultName,defaults,index,indexSpec)}return index};fluid.defaults=function(componentName,options){if(options===undefined){return fluid.getMergedDefaults(componentName)}else{if(options&&options.options){fluid.fail("Probable error in options structure for "+componentName+' with option named "options" - perhaps you meant to write these options at top level in fluid.defaults? - ',options)}fluid.registerRawDefaults(componentName,options);var gradedDefaults=fluid.getMergedDefaults(componentName);if(!fluid.hasGrade(gradedDefaults,"fluid.function")){fluid.makeComponentCreator(componentName)}}};fluid.validateCreatorGrade=function(message,componentName){var defaults=fluid.getMergedDefaults(componentName);if(!defaults||!defaults.gradeNames||defaults.gradeNames.length===0){fluid.fail(message+" type "+componentName+" which does not have any gradeNames defined")}else if(!defaults.argumentMap){var blankGrades=[];for(var i=0;i<defaults.gradeNames.length;++i){var gradeName=defaults.gradeNames[i];var rawDefaults=fluid.rawDefaults(gradeName);if(!rawDefaults){blankGrades.push(gradeName)}}if(blankGrades.length===0){fluid.fail(message+" type "+componentName+" which is not derived from fluid.component")}else{fluid.fail("The grade hierarchy of component with type "+componentName+" is incomplete - it inherits from the following grade(s): "+blankGrades.join(", ")+" for which the grade definitions are corrupt or missing. Please check the files which might include these "+"grades and ensure they are readable and have been loaded by this instance of Infusion")}}};fluid.makeComponentCreator=function(componentName){var creator=function(){fluid.validateCreatorGrade("Cannot make component creator for",componentName);return fluid.initFreeComponent(componentName,arguments)};var existing=fluid.getGlobalValue(componentName);if(existing){$.extend(creator,existing)}fluid.setGlobalValue(componentName,creator)};fluid.emptyPolicy=fluid.freezeRecursive({});fluid.derefMergePolicy=function(policy){return(policy?policy["*"]:fluid.emptyPolicy)||fluid.emptyPolicy};fluid.compileMergePolicy=function(mergePolicy){var builtins={},defaultValues={};var togo={builtins:builtins,defaultValues:defaultValues};if(!mergePolicy){return togo}fluid.each(mergePolicy,(function(value,key){var parsed={},builtin=true;if(typeof value==="function"){parsed.func=value}else if(typeof value==="object"){parsed=value}else if(!fluid.isDefaultValueMergePolicy(value)){var split=value.split(/\s*,\s*/);for(var i=0;i<split.length;++i){parsed[split[i]]=true}}else{fluid.set(defaultValues,key,"{that}.options."+value);togo.hasDefaults=true;builtin=false}if(builtin){fluid.set(builtins,fluid.composePath(key,"*"),parsed)}}));return togo};fluid.isDefaultValueMergePolicy=function(policy){return typeof policy==="string"&&(policy.indexOf(",")===-1&&!/replace|nomerge|noexpand/.test(policy))};fluid.mergeOneImpl=function(thisTarget,thisSource,j,sources,newPolicy,newPolicyHolder,i,segs){var togo=thisTarget;var primitiveTarget=fluid.isPrimitive(thisTarget);if(thisSource!==undefined){if(!newPolicy.func&&thisSource!==null&&fluid.isPlainObject(thisSource)&&!newPolicy.nomerge){if(primitiveTarget){togo=thisTarget=fluid.freshContainer(thisSource)}}else{sources[j]=undefined;if(newPolicy.func){togo=newPolicy.func.call(null,thisTarget,thisSource,newPolicyHolder,segs,i)}else{togo=thisSource}}}return togo};fluid.regenerateCursor=function(source,segs,limit,sourceStrategy){for(var i=0;i<limit;++i){source=sourceStrategy(source,segs[i],i,fluid.makeArray(segs))}return source};fluid.regenerateSources=function(sources,segs,limit,sourceStrategies){var togo=[];for(var i=0;i<sources.length;++i){var thisSource=fluid.regenerateCursor(sources[i],segs,limit,sourceStrategies[i]);togo.push(thisSource)}return togo};fluid.fetchMergeChildren=function(target,i,segs,sources,mergePolicy,options){var thisPolicy=fluid.derefMergePolicy(mergePolicy);for(var j=sources.length-1;j>=0;--j){var source=sources[j];if(source!==undefined){fluid.each(source,(function(newSource,name){var childPolicy=fluid.concreteTrundler(mergePolicy,name);if(!(name in target)||options.evaluateFully&&childPolicy===undefined&&!fluid.isPrimitive(target[name])){segs[i]=name;options.strategy(target,name,i+1,segs,sources,mergePolicy)}}));if(thisPolicy.replace){break}}}return target};fluid.inEvaluationMarker=Object.freeze({__CURRENTLY_IN_EVALUATION__:true});fluid.strategyRecursionBailout=50;fluid.makeMergeStrategy=function(options){var strategy=function(target,name,i,segs,sources,policy){if(i>fluid.strategyRecursionBailout){fluid.fail("Overflow/circularity in options merging, current path is ",segs," at depth ",i,' - please protect components from merging using the "nomerge" merge policy')}if(fluid.isPrimitive(target)){return undefined}if(fluid.isTracing){fluid.tracing.pathCount.push(fluid.path(segs.slice(0,i)))}var oldTarget;if(name in target||options.fullyEvaluated){oldTarget=target[name];if(!options.evaluateFully){return oldTarget}}if(sources===undefined){segs=fluid.makeArray(segs);sources=fluid.regenerateSources(options.sources,segs,i-1,options.sourceStrategies);policy=fluid.regenerateCursor(options.mergePolicy,segs,i-1,fluid.concreteTrundler)}var newPolicyHolder=fluid.concreteTrundler(policy,name);var newPolicy=fluid.derefMergePolicy(newPolicyHolder);var start,limit,mul;if(newPolicy.replace){start=1-sources.length;limit=0;mul=-1}else{start=0;limit=sources.length-1;mul=+1}var newSources=[];var thisTarget;for(var j=start;j<=limit;++j){var k=mul*j;var thisSource=options.sourceStrategies[k](sources[k],name,i,segs);if(thisSource!==undefined){if(!fluid.isPrimitive(thisSource)){newSources[k]=thisSource}if(oldTarget===undefined){if(mul===-1){thisTarget=target[name]=thisSource;break}else{thisTarget=fluid.mergeOneImpl(thisTarget,thisSource,j,newSources,newPolicy,newPolicyHolder,i,segs,options);target[name]=thisTarget}}}}if(oldTarget!==undefined){thisTarget=oldTarget}if(newSources.length>0){if(fluid.isPlainObject(thisTarget)){fluid.fetchMergeChildren(thisTarget,i,segs,newSources,newPolicyHolder,options)}}return thisTarget};options.strategy=strategy;return strategy};fluid.driveStrategy=function(root,pathSegs,strategy){pathSegs=fluid.makeArray(pathSegs);for(var i=0;i<pathSegs.length;++i){if(!root){return undefined}root=strategy(root,pathSegs[i],i+1,pathSegs)}return root};fluid.concreteTrundler=function(source,seg){return!source?undefined:source[seg]};fluid.merge=function(policy,...sources){var compiled=fluid.compileMergePolicy(policy).builtins;var options=fluid.makeMergeOptions(compiled,sources,{});options.initter();return options.target};fluid.makeMergeOptions=function(policy,sources,userOptions){var options={mergePolicy:policy,sources:sources};options=$.extend(options,userOptions);options.target=options.target||fluid.freshContainer(options.sources[0]);options.sourceStrategies=options.sourceStrategies||fluid.generate(options.sources.length,fluid.concreteTrundler);options.initter=function(){options.evaluateFully=true;fluid.fetchMergeChildren(options.target,0,[],options.sources,options.mergePolicy,options);options.fullyEvaluated=true};fluid.makeMergeStrategy(options);return options};fluid.transformOptions=function(options,transRec){fluid.expect("Options transformation record",transRec,["transformer","config"]);var transFunc=fluid.getGlobalValue(transRec.transformer);return transFunc.call(null,options,transRec.config)};fluid.findMergeBlocks=function(mergeBlocks,recordType){return fluid.remove_if(fluid.makeArray(mergeBlocks),(function(block){return block.recordType!==recordType}))};fluid.transformOptionsBlocks=function(mergeBlocks,transformOptions,recordTypes){fluid.each(recordTypes,(function(recordType){var blocks=fluid.findMergeBlocks(mergeBlocks,recordType);fluid.each(blocks,(function(block){var source=block.source?"source":"target";block[block.simple||source==="target"?"target":"source"]=fluid.transformOptions(block[source],transformOptions)}))}))};fluid.dedupeDistributionNamespaces=function(mergeBlocks){var byNamespace={};fluid.remove_if(mergeBlocks,(function(mergeBlock){var ns=mergeBlock.namespace;if(ns){if(byNamespace[ns]&&byNamespace[ns]!==mergeBlock.contextThat.id){return true}else{byNamespace[ns]=mergeBlock.contextThat.id}}}))};fluid.mergeRecordTypes={defaults:1e3,defaultValueMerge:900,lensedComponents:800,subcomponentRecord:700,user:600,distribution:100};fluid.model.applyChangeRequest=function(model,request){var segs=request.segs;if(segs.length===0){if(request.type==="ADD"){$.extend(true,model,request.value)}else{fluid.clear(model)}}else if(request.type==="ADD"){fluid.model.setSimple(model,request.segs,request.value)}else{for(var i=0;i<segs.length-1;++i){model=model[segs[i]];if(!model){return}}var last=fluid.peek(segs);delete model[last]}};fluid.destroyValue=function(target,segs){if(target){fluid.model.applyChangeRequest(target,{type:"DELETE",segs:segs})}};fluid.mergeComponentOptions=function(that,potentia,lightMerge){fluid.validateCreatorGrade("Cannot construct component of",lightMerge.type);var sharedMergePolicy={};var mergeBlocks=fluid.expandComponentOptions(sharedMergePolicy,potentia,lightMerge,that);var options={};var sourceStrategies=[],sources=[];var baseMergeOptions={target:options,sourceStrategies:sourceStrategies};var updateBlocks=function(){fluid.each(mergeBlocks,(function(block){if(fluid.isPrimitive(block.priority)){block.priority=fluid.parsePriority(block.priority,0,false,block.recordType)}}));fluid.sortByPriority(mergeBlocks);fluid.dedupeDistributionNamespaces(mergeBlocks);sourceStrategies.length=0;sources.length=0;fluid.each(mergeBlocks,(function(block){sourceStrategies.push(block.strategy);sources.push(block.target)}))};updateBlocks();var mergeOptions=fluid.makeMergeOptions(sharedMergePolicy,sources,baseMergeOptions);mergeOptions.mergeBlocks=mergeBlocks;mergeOptions.updateBlocks=updateBlocks;mergeOptions.destroyValue=function(segs){for(var i=0;i<mergeBlocks.length;++i){if(!mergeBlocks[i].immutableTarget){fluid.destroyValue(mergeBlocks[i].target,segs)}}fluid.destroyValue(baseMergeOptions.target,segs)};var compiledPolicy;var mergePolicy;function computeMergePolicy(){mergePolicy=fluid.driveStrategy(options,"mergePolicy",mergeOptions.strategy);mergePolicy=$.extend({},fluid.rootMergePolicy,mergePolicy);compiledPolicy=fluid.compileMergePolicy(mergePolicy);$.extend(true,sharedMergePolicy,compiledPolicy.builtins)}computeMergePolicy();mergeOptions.computeMergePolicy=computeMergePolicy;if(compiledPolicy.hasDefaults){mergeBlocks.push(fluid.generateExpandBlock({options:compiledPolicy.defaultValues,recordType:"defaultValueMerge",priority:fluid.mergeRecordTypes.defaultValueMerge},that,{}));updateBlocks()}that.options=options;fluid.driveStrategy(options,"gradeNames",mergeOptions.strategy);fluid.deliverOptionsStrategy(that,options,mergeOptions);fluid.computeComponentAccessor(that,potentia.localRecord);var transformOptions=fluid.driveStrategy(options,"transformOptions",mergeOptions.strategy);if(transformOptions){fluid.transformOptionsBlocks(mergeBlocks,transformOptions,["user","subcomponentRecord"]);updateBlocks()}if(!baseMergeOptions.target.mergePolicy){computeMergePolicy()}return mergeOptions};fluid.defaults("fluid.function",{});fluid.invokeGradedFunction=function(name,spec){var defaults=fluid.defaults(name);if(!defaults||!defaults.argumentMap||!fluid.hasGrade(defaults,"fluid.function")){fluid.fail("Cannot look up name "+name+" to a function with registered argumentMap - got defaults ",defaults)}var args=[];fluid.each(defaults.argumentMap,(function(value,key){args[value]=spec[key]}));return fluid.invokeGlobalFunction(name,args)};fluid.noNamespaceDistributionPrefix="no-namespace-distribution-";fluid.mergeOneDistribution=function(target,source,key){var namespace=source.namespace||key||fluid.noNamespaceDistributionPrefix+fluid.allocateGuid();source.namespace=namespace;target[namespace]=$.extend(true,{},target[namespace],source)};fluid.distributeOptionsPolicy=function(target,source){target=target||{};if(fluid.isArrayable(source)){for(var i=0;i<source.length;++i){fluid.mergeOneDistribution(target,source[i])}}else if(typeof source.target==="string"){fluid.mergeOneDistribution(target,source)}else{fluid.each(source,(function(oneSource,key){fluid.mergeOneDistribution(target,oneSource,key)}))}return target};fluid.mergingArray=function(){};fluid.mergingArray.prototype=[];fluid.deferringMergePolicy=function(target,source,mergePolicyHolder){target=target||{};fluid.each(source,(function(oneSource,key){if(!target[key]){target[key]=new fluid.mergingArray}if(fluid.derefMergePolicy(mergePolicyHolder[key]).replace&&oneSource!==undefined){target[key].length=0}if(oneSource instanceof fluid.mergingArray){target[key].push.apply(target[key],oneSource)}else if(oneSource!==undefined){target[key].push(oneSource)}}));return target};fluid.invokerStrategies=fluid.arrayToHash(["func","funcName","listener","this","method","changePath","value"]);fluid.invokersMergePolicy=function(target,source){target=target||{};fluid.each(source,(function(oneInvoker,name){if(!oneInvoker){target[name]=oneInvoker;return}else{oneInvoker=fluid.upgradePrimitiveFunc(oneInvoker)}var oneT=target[name];if(!oneT){oneT=target[name]={}}for(var key in fluid.invokerStrategies){if(key in oneInvoker){for(var key2 in fluid.invokerStrategies){oneT[key2]=undefined}}}$.extend(oneT,oneInvoker)}));return target};fluid.rootMergePolicy=fluid.freezeRecursive({gradeNames:fluid.arrayConcatPolicy,distributeOptions:fluid.distributeOptionsPolicy,members:{noexpand:true,func:fluid.deferringMergePolicy},invokers:{noexpand:true,func:fluid.invokersMergePolicy},components:{noexpand:true,func:fluid.deferringMergePolicy},dynamicComponents:{noexpand:true,func:fluid.deferringMergePolicy},transformOptions:"replace",listeners:fluid.makeMergeListenersPolicy(fluid.mergeListenerPolicy)});fluid.defaults("fluid.component",{mergePolicy:fluid.rootMergePolicy,argumentMap:{options:0},workflows:{local:{concludeComponentObservation:{funcName:"fluid.concludeComponentObservation",priority:"first"},concludeComponentInit:{funcName:"fluid.concludeComponentInit",waitIO:true,priority:"last"}}},events:{onCreate:"promise",onDestroy:"promise",afterDestroy:"promise"}});fluid.computeNickName=function(typeName){var segs=fluid.model.parseEL(typeName);return fluid.peek(segs)};fluid.isDestroyed=function(that,strict){return that.lifecycleStatus==="destroyed"||!strict&&that.lifecycleStatus==="destroying"};fluid.computeGlobalMemberName=function(type,id){var nickName=fluid.computeNickName(type);return nickName+"-"+id};fluid.adaptTransactionFailure=function(transRec){var returned=false;transRec.promise.then(null,(function(e){if(!returned){throw e}else{if(transRec.promise.onReject.length===0){fluid.fireUnhandledRejection(transRec.promise,e)}}}));returned=true};fluid.initFreeComponent=function(type,initArgs){var id=fluid.allocateGuid();var path=[fluid.computeGlobalMemberName(type,id)];var userRecord={recordType:"user",type:type};var upDefaults=fluid.defaults(type);var argMap=fluid.defaults(upDefaults.argumentMap.container!==undefined?"fluid.viewComponent":"fluid.component").argumentMap;fluid.each(argMap,(function(index,name){var arg=initArgs[index];userRecord[name]=name==="options"?fluid.expandCompact(arg,true):arg}));var potentia={type:"create",path:path,componentId:id,records:[userRecord]};var transRec=fluid.registerPotentia(potentia);var shadow=fluid.commitPotentiae(transRec.transactionId);fluid.adaptTransactionFailure(transRec);return shadow&&shadow.that};var charStart="(?:[\\w\\u00c0-\\uFFFF*_-";fluid.simpleCSSMatcher={regexp:new RegExp("([#.]?)("+charStart+"]|\\\\.)+)","g"),charToTag:{"":"tag","#":"id",".":"clazz"}};fluid.IoCSSMatcher={regexp:new RegExp("([&#]?)("+charStart+"]|\\.|\\/)+)","g"),charToTag:{"":"context","&":"context","#":"id"}};var childSeg=new RegExp("\\s*(>)?\\s*","g");fluid.parseSelector=function(selstring,strategy){var togo=[];selstring=selstring.trim();var regexp=strategy.regexp;regexp.lastIndex=0;var lastIndex=0;while(true){var atNode=[];var first=true;while(true){var segMatch=regexp.exec(selstring);if(!segMatch){break}if(segMatch.index!==lastIndex){if(first){fluid.fail("Error in selector string - cannot match child selector expression starting at "+selstring.substring(lastIndex))}else{break}}var thisNode={};var text=segMatch[2];var targetTag=strategy.charToTag[segMatch[1]];if(targetTag){thisNode[targetTag]=text}atNode[atNode.length]=thisNode;lastIndex=regexp.lastIndex;first=false}childSeg.lastIndex=lastIndex;var fullAtNode={predList:atNode};var childMatch=childSeg.exec(selstring);if(!childMatch||childMatch.index!==lastIndex){fluid.fail("Error in selector string - can not match child selector expression at "+selstring.substring(lastIndex))}if(childMatch[1]===">"){fullAtNode.child=true}togo[togo.length]=fullAtNode;if(childSeg.lastIndex>=selstring.length){break}lastIndex=childSeg.lastIndex;regexp.lastIndex=childSeg.lastIndex}return togo};fluid.flattenObjectPaths=function(originalObject){var flattenedObject={};fluid.each(originalObject,(function(value,key){if(value!==null&&typeof value==="object"){var flattenedSubObject=fluid.flattenObjectPaths(value);fluid.each(flattenedSubObject,(function(subValue,subKey){flattenedObject[key+"."+subKey]=subValue}));if(typeof fluid.get(value,"toString")==="function"){flattenedObject[key]=value.toString()}}else{flattenedObject[key]=value}}));return flattenedObject};fluid.stringTemplate=function(template,values){var flattenedValues=fluid.flattenObjectPaths(values);var keys=fluid.keys(flattenedValues);keys=keys.sort(fluid.compareStringLength());for(var i=0;i<keys.length;++i){var key=keys[i];var templatePlaceholder="%"+key;var replacementValue=flattenedValues[key];var indexOfPlaceHolder=-1;while((indexOfPlaceHolder=template.indexOf(templatePlaceholder))!==-1){template=template.slice(0,indexOfPlaceHolder)+replacementValue+template.slice(indexOfPlaceHolder+templatePlaceholder.length)}}return template};
/*!
 Copyright 2011 unscriptable.com / John Hann
 Copyright The Infusion copyright holders
 See the AUTHORS.md file at the top-level directory of this distribution and at
 https://github.com/fluid-project/infusion/raw/main/AUTHORS.md.

 License MIT
*/
"use strict";fluid.promise=function(){var that={onResolve:[],onReject:[],onCancel:[]};that.then=function(onResolve,onReject,onCancel){fluid.promise.pushHandler(that,onResolve,"onResolve","resolve");fluid.promise.pushHandler(that,onReject,"onReject","reject");fluid.promise.pushHandler(that,onCancel,"onCancel","cancel");return that};that.resolve=function(value){if(that.disposition){if(that.disposition!=="cancel"){fluid.fail("Error: resolving promise ",that,' which has already received "'+that.disposition+'"')}}else{that.complete("resolve",that.onResolve,value)}return that};that.reject=function(reason){if(that.disposition){if(that.disposition!=="cancel"){fluid.fail("Error: rejecting promise ",that,'which has already received "'+that.disposition+'"')}}else{if(that.onReject.length===0){fluid.armUnhandledRejection(that,reason)}that.complete("reject",that.onReject,reason)}return that};that.cancel=function(reason){if(!that.disposition){that.complete("cancel",that.onCancel,reason)}};that.complete=function(which,queue,arg){that.disposition=which;that.value=arg;for(var i=0;i<queue.length;++i){queue[i](arg)}delete that.onResolve;delete that.onReject;delete that.onCancel};return that};fluid.promise.pushHandler=function(promise,handler,eventName,disposition){if(handler){if(promise.disposition){if(promise.disposition===disposition){handler(promise.value);promise.directHandle=disposition}}else{promise[eventName].push(handler)}}};fluid.armUnhandledRejection=function(promise,reason){fluid.invokeLater((function(){if(promise.directHandle!=="reject"){fluid.fireUnhandledRejection(promise,reason)}}))};fluid.fireUnhandledRejection=function(promise,reason){fluid.unhandledRejectionEvent.fire(reason,promise)};fluid.unhandledRejectionEvent=fluid.makeEventFirer({name:"Global unhandled rejection handler"});fluid.logUnhandledRejection=function(reason){fluid.log(fluid.logLevel.WARN,"Unhandled promise rejection: ",reason)};fluid.unhandledRejectionEvent.addListener(fluid.logUnhandledRejection,"log");fluid.isPromise=function(totest){return totest&&typeof totest.then==="function"};fluid.toPromise=function(promiseOrValue){if(fluid.isPromise(promiseOrValue)){return promiseOrValue}else{var togo=fluid.promise();togo.resolve(promiseOrValue);return togo}};fluid.promise.follow=function(source,target){source.then(target.resolve,target.reject);target.then(null,null,source.cancel)};fluid.promise.map=function(source,func){var promise=fluid.toPromise(source);var togo=fluid.promise();promise.then((function(value){var mapped=func(value);if(fluid.isPromise(mapped)){fluid.promise.follow(mapped,togo)}else{togo.resolve(mapped)}}),(function(error){togo.reject(error)}));return togo};fluid.promise.makeSequencer=function(sources,options,strategy){if(!fluid.isArrayable(sources)){fluid.fail("fluid.promise sequence algorithms must be supplied an array as source")}var sequencer={sources:sources,resolvedSources:[],index:0,strategy:strategy,options:options,returns:[],sequenceStarted:false,sequenceCancelled:false,promise:fluid.promise()};sequencer.promise.then(null,null,(function(){fluid.promise.cancelSequencer(sequencer)}));sequencer.promise.sequencer=sequencer;return sequencer};fluid.promise.cancelSequencer=function(sequencer){sequencer.sequenceCancelled=true;sequencer.resolvedSources.forEach((function(source){if(fluid.isPromise(source)){source.cancel()}}))};fluid.promise.progressSequence=function(that,retValue){that.returns.push(retValue);that.index++;fluid.promise.resumeSequence(that)};fluid.promise.processSequenceReject=function(that,error){for(var i=that.index-1;i>=0;--i){var resolved=that.resolvedSources[i];var accumulator=fluid.isPromise(resolved)&&typeof resolved.accumulateRejectionReason==="function"?resolved.accumulateRejectionReason:fluid.identity;error=accumulator(error)}that.promise.reject(error)};fluid.promise.resumeSequence=function(that){that.sequenceStarted=true;if(that.sequenceCancelled){return}else if(that.index===that.sources.length){that.promise.resolve(that.strategy.resolveResult(that))}else{var value=that.strategy.invokeNext(that);that.resolvedSources[that.index]=value;if(fluid.isPromise(value)){value.then((function(retValue){fluid.promise.progressSequence(that,retValue)}),(function(error){fluid.promise.processSequenceReject(that,error)}))}else{fluid.promise.progressSequence(that,value)}}};fluid.promise.makeSequenceStrategy=function(){return{invokeNext:function(that){var source=that.sources[that.index];return typeof source==="function"?source(that.options):source},resolveResult:function(that){return that.returns}}};fluid.promise.sequence=function(sources,options){var sequencer=fluid.promise.makeSequencer(sources,options,fluid.promise.makeSequenceStrategy());fluid.promise.resumeSequence(sequencer);return sequencer.promise};fluid.promise.makeTransformerStrategy=function(){return{invokeNext:function(that){var lisrec=that.sources[that.index];lisrec.listener=fluid.event.resolveListener(lisrec.listener);var value=lisrec.listener.apply(null,[that.returns[that.index],that.options]);return value},resolveResult:function(that){return that.returns[that.index]}}};fluid.promise.makeTransformer=function(listeners,payload,options){listeners.unshift({listener:function(){return payload}});var sequencer=fluid.promise.makeSequencer(listeners,options,fluid.promise.makeTransformerStrategy());sequencer.returns.push(null);return sequencer};fluid.promise.filterNamespaces=function(listeners,namespaces){if(!namespaces){return listeners}return fluid.remove_if(fluid.makeArray(listeners),(function(element){return element.namespace&&!element.softNamespace&&!namespaces.includes(element.namespace)}))};fluid.promise.fireTransformEvent=function(event,payload,options){options=options||{};var listeners=options.reverse?fluid.makeArray(event.sortedListeners).reverse():fluid.makeArray(event.sortedListeners);listeners=fluid.promise.filterNamespaces(listeners,options.filterNamespaces);var sequencer=fluid.promise.makeTransformer(listeners,payload,options);var canceller=sequencer.promise.cancel;var remover=function(){fluid.remove_if(event.onDestroy,(function(func){return func===canceller}))};fluid.event.addPrimitiveListener(event,"onDestroy",canceller);sequencer.promise.then(remover,remover,remover);fluid.promise.resumeSequence(sequencer);return sequencer.promise};"use strict";fluid.defaults("fluid.dataSource.encoding.JSON",{gradeNames:"fluid.component",invokers:{parse:"fluid.dataSource.parseJSON",render:"fluid.dataSource.stringifyJSON"},contentType:"application/json"});fluid.defaults("fluid.dataSource.encoding.none",{gradeNames:"fluid.component",invokers:{parse:"fluid.identity",render:"fluid.identity"},contentType:"text/plain"});fluid.dataSource.parseJSON=function(string){var togo=fluid.promise();if(!string){togo.resolve(undefined)}else{try{togo.resolve(JSON.parse(string))}catch(err){togo.reject(err)}}return togo};fluid.dataSource.stringifyJSON=function(obj){return obj===undefined?"":JSON.stringify(obj,null,4)};fluid.defaults("fluid.dataSource",{gradeNames:["fluid.component","fluid.contextAware"],contextAwareness:{writable:{checks:{writableValue:{contextValue:"{fluid.dataSource}.options.writable",gradeNames:"{fluid.dataSource}.options.writableGrade"}}}},writable:false,events:{onRead:null,onError:null},components:{encoding:{type:"fluid.dataSource.encoding.JSON"}},listeners:{"onRead.impl":{func:"fluid.notImplemented",priority:"first"},"onRead.encoding":{func:"{encoding}.parse",priority:"after:impl"}},invokers:{get:{funcName:"fluid.dataSource.get",args:["{that}","{arguments}.0","{arguments}.1"]}}});fluid.defaults("fluid.dataSource.writable",{gradeNames:["fluid.component"],events:{onWrite:null,onWriteResponse:null},listeners:{"onWrite.encoding":{func:"{encoding}.render"},"onWrite.impl":{func:"fluid.notImplemented",priority:"after:encoding"},"onWriteResponse.encoding":{func:"{encoding}.parse"}},invokers:{set:{funcName:"fluid.dataSource.set",args:["{that}","{arguments}.0","{arguments}.1","{arguments}.2"]}}});fluid.dataSource.registerStandardPromiseHandlers=function(that,promise,requestOptions){promise.then(requestOptions.callback,requestOptions.onError?requestOptions.onError:that.events.onError.fire)};fluid.dataSource.defaultiseOptions=function(componentOptions,directOptions,directModel,isSet){var options=typeof directOptions==="function"?{callback:directOptions}:fluid.copy(directOptions)||{};options.directModel=directModel;options.operation=isSet?"set":"get";options.notFoundIsEmpty=options.notFoundIsEmpty||componentOptions.notFoundIsEmpty;return options};fluid.dataSource.get=function(that,directModel,directOptions){var requestOptions=fluid.dataSource.defaultiseOptions(that.options,directOptions,directModel);var promise=fluid.promise.fireTransformEvent(that.events.onRead,undefined,requestOptions);fluid.dataSource.registerStandardPromiseHandlers(that,promise,requestOptions);return promise};fluid.dataSource.set=function(that,directModel,model,directOptions){var requestOptions=fluid.dataSource.defaultiseOptions(that.options,directOptions,directModel,true);var transformPromise=fluid.promise.fireTransformEvent(that.events.onWrite,model,requestOptions);var togo=fluid.promise();transformPromise.then((function(setResponse){var options2=fluid.dataSource.defaultiseOptions(that.options,fluid.copy(requestOptions),directModel);var retransformed=fluid.promise.fireTransformEvent(that.events.onWriteResponse,setResponse,options2);fluid.promise.follow(retransformed,togo)}),(function(error){togo.reject(error)}));fluid.dataSource.registerStandardPromiseHandlers(that,togo,requestOptions);return togo};fluid.defaults("fluid.dataSource.URL",{gradeNames:["fluid.dataSource"],writableGrade:"fluid.dataSource.URL.writable",invokers:{resolveUrl:"fluid.dataSource.URL.resolveUrl",handleHttp:"fluid.dataSource.URL.handleHttp"},listeners:{"onRead.impl":{funcName:"fluid.dataSource.URL.handle",args:["{that}","{that}.options.permittedRequestOptions","{arguments}.0","{arguments}.1"]}},permittedRequestOptions:"fluid.dataSource.URL.requestOptions",components:{cookieJar:"{cookieJar}"},termMap:{}});fluid.defaults("fluid.dataSource.URL.writable",{gradeNames:["fluid.dataSource.writable"],listeners:{"onWrite.impl":{funcName:"fluid.dataSource.URL.handle",args:["{that}","{that}.options.permittedRequestOptions","{arguments}.0","{arguments}.1"]}}});fluid.dataSource.URL.resolveUrl=function(url,termMap,directModel,noencode){var map=fluid.transform(termMap,(function resolve(entry){entry=String(entry);var encode=!noencode;if(entry.indexOf("noencode:")===0){encode=false;entry=entry.substring("noencode:".length)}var value=entry.charAt(0)==="%"?fluid.get(directModel,entry.substring(1)):entry;if(encode){value=encodeURIComponent(value)}return value}));var replaced=fluid.stringTemplate(url,map);return replaced};fluid.dataSource.URL.urlFields=fluid.freezeRecursive(["protocol","username","password","hostname","port","pathname","search"]);fluid.dataSource.URL.condenseUrl=function(requestOptions){var togo=new fluid.resourceLoader.UrlClass("http://localhost/");fluid.dataSource.URL.urlFields.forEach((function(field){if(requestOptions[field]){togo[field]=requestOptions[field]}}));return togo};fluid.dataSource.URL.requestOptions=fluid.dataSource.URL.urlFields.concat(["url","method","headers","termMap"]);fluid.dataSource.URL.prepareRequestOptions=function(componentOptions,cookieJar,userOptions,permittedOptions,directModel,userStaticOptions){var staticOptions=fluid.filterKeys(componentOptions,permittedOptions);var requestOptions=fluid.extend(true,{headers:{}},userStaticOptions,staticOptions,userOptions);if(fluid.contextAware.isNode()){if(requestOptions.hostname==="localhost"){requestOptions.hostname="127.0.0.1"}}requestOptions.writeMethod=requestOptions.writeMethod||componentOptions.writeMethod||"PUT";requestOptions.pathname=fluid.dataSource.URL.resolveUrl(requestOptions.pathname,requestOptions.termMap,directModel);if(cookieJar&&cookieJar.cookie&&componentOptions.storeCookies){requestOptions.headers.Cookie=cookieJar.cookie}return requestOptions};fluid.dataSource.URL.parse=function(url,permittedOptions){var parsed=fluid.filterKeys(new fluid.resourceLoader.UrlClass(url,typeof window!=="undefined"&&window.location||undefined),fluid.dataSource.URL.urlFields);permittedOptions.forEach((function(oneOption){if(!parsed[oneOption]){delete parsed[oneOption]}}));return parsed};fluid.dataSource.URL.isErrorStatus=function(statusCode){return statusCode<200||statusCode>=300};fluid.dataSource.URL.handle=function(that,permittedRequestOptions,model,userOptions){var permittedOptions=fluid.getGlobalValue(permittedRequestOptions);permittedOptions.forEach((function(oneOption){fluid.getForComponent(that,["options",oneOption])}));var directModel=userOptions.directModel;var url=that.resolveUrl(that.options.url,that.options.termMap,directModel);var parsed=fluid.dataSource.URL.parse(url,permittedOptions);var finalRequestOptions=fluid.dataSource.URL.prepareRequestOptions(that.options,that.cookieJar,userOptions,permittedOptions,directModel,parsed);return that.handleHttp(that,finalRequestOptions,model)};fluid.extractHtmlError=function(received){var matches=/<pre>(.*)<\/pre>/gm.exec(received);return matches?matches[1]:received};fluid.dataSource.URL.relayError=function(statusCode,received,whileMsg){var rejectPayload;try{rejectPayload=JSON.parse(received)}catch(e){var message=typeof received==="string"&&received.indexOf("<html")!==-1?fluid.extractHtmlError(received):received;rejectPayload={message:message}}rejectPayload.message=rejectPayload.message||rejectPayload.error;delete rejectPayload.error;rejectPayload.isError=true;rejectPayload.statusCode=statusCode;return fluid.upgradeError(rejectPayload,whileMsg)};"use strict";var fluid=fluid||{};fluid.uaMatch=function(ua){ua=ua.toLowerCase();var match=/(chrome)[ \/]([\w.]+)/.exec(ua)||/(webkit)[ \/]([\w.]+)/.exec(ua)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua)||/(msie) ([\w.]+)/.exec(ua)||ua.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua)||[];return{browser:match[1]||"",version:match[2]||"0"}};fluid.assignJQueryBrowser=function($){if(!$.browser){var matched=fluid.uaMatch(navigator.userAgent);var browser={};if(matched.browser){browser[matched.browser]=true;browser.version=matched.version}if(browser.chrome){browser.webkit=true}else if(browser.webkit){browser.safari=true}$.browser=browser}};fluid.assignJQueryBrowser(jQuery);fluid.getScopedData=function(target,key){var data=$(target).data("fluid-scoped-data");return data?data[key]:undefined};fluid.setScopedData=function(target,key,value){$(target).each((function(){var data=$.data(this,"fluid-scoped-data")||{};data[key]=value;$.data(this,"fluid-scoped-data",data)}))};fluid.lastFocusedElement=null;$(document).on("focusin",(function(event){fluid.lastFocusedElement=event.target}));fluid.enabled=function(target,state){target=$(target);if(state===undefined){return fluid.getScopedData(target,"enablement")!==false}else{$("*",target).add(target).each((function(){if(fluid.getScopedData(this,"enablement")!==undefined){fluid.setScopedData(this,"enablement",state)}else if(/select|textarea|input/i.test(this.nodeName)){$(this).prop("disabled",!state)}}));fluid.setScopedData(target,"enablement",state)}};fluid.initEnablement=function(target){fluid.setScopedData(target,"enablement",true)};fluid.resolveEventTarget=function(event){while(event.originalEvent&&event.originalEvent.target){event=event.originalEvent}return event.target};async function applyOp(node,func){node=$(node)[0];if(node){var promise=new Promise((function(resolve){node.addEventListener(func,resolve,{once:true})}));node[func]();return promise}}$.each(["focus","blur"],(function(i,name){fluid[name]=function(elem){return applyOp(elem,name)}}));"use strict";fluid.dom=fluid.dom||{};fluid.dom.getNextNode=function(iterator){if(iterator.node.firstChild){iterator.node=iterator.node.firstChild;iterator.depth+=1;return iterator}while(iterator.node){if(iterator.node.nextSibling){iterator.node=iterator.node.nextSibling;return iterator}iterator.node=iterator.node.parentNode;iterator.depth-=1}return iterator};fluid.dom.iterateDom=function(node,acceptor,allNodes){var currentNode={node:node,depth:0};var prevNode=node;var condition;while(currentNode.node!==null&&currentNode.depth>=0&&currentNode.depth<fluid.dom.iterateDom.DOM_BAIL_DEPTH){condition=null;if(currentNode.node.nodeType===1||allNodes){condition=acceptor(currentNode.node,currentNode.depth)}if(condition){if(condition==="delete"){currentNode.node.parentNode.removeChild(currentNode.node);currentNode.node=prevNode}else if(condition==="stop"){return currentNode.node}}prevNode=currentNode.node;currentNode=fluid.dom.getNextNode(currentNode)}};fluid.dom.iterateDom.DOM_BAIL_DEPTH=256;"use strict";fluid.unUnicode=/(\\u[\dabcdef]{4}|\\x[\dabcdef]{2})/g;fluid.unescapeProperties=function(string){string=string.replace(fluid.unUnicode,(function(match){var code=match.substring(2);var parsed=parseInt(code,16);return String.fromCharCode(parsed)}));var pos=0;while(true){var backpos=string.indexOf("\\",pos);if(backpos===-1){break}if(backpos===string.length-1){return[string.substring(0,string.length-1),true]}var replace=string.charAt(backpos+1);if(replace==="n"){replace="\n"}if(replace==="r"){replace="\r"}if(replace==="t"){replace="\t"}string=string.substring(0,backpos)+replace+string.substring(backpos+2);pos=backpos+1}return[string,false]};fluid.breakPos=/[^\\][\s:=]/;fluid.parseJavaProperties=function(text){var togo={};text=text.replace(/\r\n/g,"\n");text=text.replace(/\r/g,"\n");var lines=text.split("\n");var contin,key,valueComp,valueRaw,valueEsc;for(var i=0;i<lines.length;++i){var line=lines[i].trim();if(!line||line.charAt(0)==="#"||line.charAt(0)==="!"){continue}if(!contin){valueComp="";var breakpos=line.search(fluid.breakPos);if(breakpos===-1){key=line;valueRaw=""}else{key=line.substring(0,breakpos+1).trim();valueRaw=line.substring(breakpos+2).trim();if(valueRaw.charAt(0)===":"||valueRaw.charAt(0)==="="){valueRaw=valueRaw.substring(1).trim()}}key=fluid.unescapeProperties(key)[0];valueEsc=fluid.unescapeProperties(valueRaw)}else{valueEsc=fluid.unescapeProperties(line)}contin=valueEsc[1];if(!valueEsc[1]){togo[key]=valueComp+valueEsc[0]}else{valueComp+=valueEsc[0]}}return togo};fluid.formatMessage=function(messageString,args){if(!args){return messageString}if(typeof args==="string"){args=[args]}for(var i=0;i<args.length;++i){messageString=messageString.replace("{"+i+"}",args[i])}return messageString};"use strict";fluid.renderTimestamp=function(date){var zeropad=function(num,width){if(!width){width=2}var numstr=num===undefined?"":num.toString();return"00000".substring(5-width+numstr.length)+numstr};return zeropad(date.getHours())+":"+zeropad(date.getMinutes())+":"+zeropad(date.getSeconds())+"."+zeropad(date.getMilliseconds(),3)};fluid.isTracing=false;fluid.registerNamespace("fluid.tracing");fluid.tracing.pathCount=[];fluid.tracing.summarisePathCount=function(pathCount){pathCount=pathCount||fluid.tracing.pathCount;var togo={};for(var i=0;i<pathCount.length;++i){var path=pathCount[i];if(!togo[path]){togo[path]=1}else{++togo[path]}}var toReallyGo=[];fluid.each(togo,(function(el,path){toReallyGo.push({path:path,count:el})}));toReallyGo.sort((function(a,b){return b.count-a.count}));return toReallyGo};fluid.tracing.condensePathCount=function(prefixes,pathCount){prefixes=fluid.makeArray(prefixes);var prefixCount={};fluid.each(prefixes,(function(prefix){prefixCount[prefix]=0}));var togo=[];fluid.each(pathCount,(function(el){var path=el.path;if(!fluid.find(prefixes,(function(prefix){if(path.indexOf(prefix)===0){prefixCount[prefix]+=el.count;return true}}))){togo.push(el)}}));fluid.each(prefixCount,(function(count,path){togo.unshift({path:path,count:count})}));return togo};fluid.obtainException=function(){return new Error("Trace exception")};fluid.registerNamespace("fluid.exceptionDecoders");fluid.decodeStack=function(){var e=fluid.obtainException();return fluid.exceptionDecoders.standard(e)};fluid.exceptionDecoders.standard=function(e){var delimiter="at ";var lines=e.stack.replace(/(?:\n@:0)?\s+$/m,"").replace(/^\(/gm,"{anonymous}(").split("\n");return fluid.transform(lines,(function(line){line=line.replace(/\)/g,"");var atind=line.indexOf(delimiter);return atind===-1?[line]:[line.substring(atind+delimiter.length),line.substring(0,atind)]}))};fluid.getCallerInfo=function(atDepth){atDepth=atDepth||3;var stack=fluid.decodeStack();var element=stack&&stack[atDepth]&&stack[atDepth][0];if(element){var lastslash=element.lastIndexOf("/");if(lastslash===-1){lastslash=0}var nextColon=element.indexOf(":",lastslash);return{path:element.substring(0,lastslash),filename:element.substring(lastslash+1,nextColon),index:element.substring(nextColon+1)}}else{return null}};fluid.generatePadding=function(c,count){var togo="";for(var i=0;i<count;++i){togo+=c}return togo};fluid.SYNTHETIC_PROPERTY=Object.freeze({});fluid.getSafeProperty=function(obj,key){var desc=Object.getOwnPropertyDescriptor(obj,key);return desc&&!desc.get?obj[key]:fluid.SYNTHETIC_PROPERTY};fluid.prettyPrintJSONImpl=function(obj,small,options){function out(str){options.output+=str}var big=small+options.indentChars,isFunction=typeof obj==="function";if(options.maxRenderChars!==undefined&&options.output.length>options.maxRenderChars){return true}if(obj===null){out("null")}else if(obj===undefined){out("undefined")}else if(obj===fluid.SYNTHETIC_PROPERTY){out("[Synthetic property]")}else if(fluid.isPrimitive(obj)&&!isFunction){out(JSON.stringify(obj))}else{if(options.stack.indexOf(obj)!==-1){out("(CIRCULAR)");return}options.stack.push(obj);var i;if(fluid.isArrayable(obj)){if(obj.length===0){out("[]")}else{out("[\n"+big);for(i=0;i<obj.length;++i){if(fluid.prettyPrintJSONImpl(obj[i],big,options)){return true}if(i!==obj.length-1){out(",\n"+big)}}out("\n"+small+"]")}}else{out("{"+(isFunction?" Function":"")+"\n"+big);var keys=fluid.keys(obj);for(i=0;i<keys.length;++i){var key=keys[i];var value=fluid.getSafeProperty(obj,key);out(JSON.stringify(key)+": ");if(fluid.prettyPrintJSONImpl(value,big,options)){return true}if(i!==keys.length-1){out(",\n"+big)}}out("\n"+small+"}")}options.stack.pop()}return};fluid.prettyPrintJSON=function(obj,options){options=$.extend({indent:4,stack:[],output:""},options);options.indentChars=fluid.generatePadding(" ",options.indent);fluid.prettyPrintJSONImpl(obj,"",options);return options.output};fluid.dumpEl=function(element){var togo;if(!element){return"null"}if(element.nodeType===3||element.nodeType===8){return"[data: "+element.data+"]"}if(element.nodeType===9){return"[document: location "+element.location+"]"}if(!element.nodeType&&fluid.isArrayable(element)){togo="[";for(var i=0;i<element.length;++i){togo+=fluid.dumpEl(element[i]);if(i<element.length-1){togo+=", "}}return togo+"]"}element=$(element);togo=element.get(0).tagName;if(element.id){togo+="#"+element.id}if(element.attr("class")){togo+="."+element.attr("class")}return togo};fluid["debugger"]=function(){debugger};fluid.defaults("fluid.debuggingProbe",{gradeNames:["fluid.component"]});fluid.probeToDistribution=function(probe){var instantiator=fluid.globalInstantiator;var parsed=fluid.parseContextReference(probe.target);var segs=fluid.model.parseToSegments(parsed.path,instantiator.parseEL,true);if(segs[0]!=="options"){segs.unshift("options")}var parsedPriority=fluid.parsePriority(probe.priority);if(parsedPriority.constraint&&!parsedPriority.constraint.target){parsedPriority.constraint.target="authoring"}return{target:"{/ "+parsed.context+"}."+instantiator.composeSegments.apply(null,segs),record:{func:probe.func,funcName:probe.funcName,args:probe.args,priority:fluid.renderPriority(parsedPriority)}}};fluid.registerProbes=function(probes){var probeDistribution=fluid.transform(probes,fluid.probeToDistribution);var memberName="fluid_debuggingProbe_"+fluid.allocateGuid();fluid.construct([memberName],{type:"fluid.debuggingProbe",distributeOptions:probeDistribution});return memberName};fluid.deregisterProbes=function(probeName){fluid.destroy([probeName])};"use strict";fluid.visitComponentChildren=function(that,visitor,options,segs){segs=segs||[];var shadow=fluid.shadowForComponent(that);for(var name in shadow.childComponents){var component=shadow.childComponents[name];if(options.visited&&options.visited[component.id]){continue}segs.push(name);if(options.visited){options.visited[component.id]=true}if(visitor(component,name,segs,segs.length-1)){return true}if(!options.flat){fluid.visitComponentChildren(component,visitor,options,segs)}segs.pop()}};fluid.getContextHash=function(instantiator,that){var shadow=instantiator.idToShadow[that.id];return shadow&&shadow.contextHash};fluid.componentHasGrade=function(that,gradeName){var contextHash=fluid.getContextHash(fluid.globalInstantiator,that);return!!(contextHash&&contextHash[gradeName])};fluid.visitComponentsForMatching=function(that,options,visitor){var instantiator=fluid.getInstantiator(that);options=$.extend({visited:{},instantiator:instantiator},options);var thatStack=[that];var contextHashes=[fluid.getContextHash(instantiator,that)];var visitorWrapper=function(component,name,segs){thatStack.length=1;contextHashes.length=1;for(var i=0;i<segs.length;++i){var child=thatStack[i][segs[i]];thatStack[i+1]=child;contextHashes[i+1]=fluid.getContextHash(instantiator,child)||{}}return visitor(component,thatStack,contextHashes,segs,segs.length)};fluid.visitComponentChildren(that,visitorWrapper,options,[])};fluid.getMemberNames=function(instantiator,thatStack){if(thatStack.length===0){return[]}else{var path=instantiator.idToPath(fluid.peek(thatStack).id);var segs=instantiator.parseEL(path);segs.unshift.apply(segs,fluid.generate(thatStack.length-segs.length,""));return segs}};fluid.visitComponentsForVisibility=function(instantiator,thatStack,visitor,options){options=options||{visited:{},flat:true,instantiator:instantiator};var memberNames=fluid.getMemberNames(instantiator,thatStack);for(var i=thatStack.length-1;i>=0;--i){var that=thatStack[i];options.visited[that.id]=true;if(visitor(that,memberNames[i],memberNames,i)){return}if(fluid.visitComponentChildren(that,visitor,options,memberNames)){return}memberNames.pop()}};fluid.mountStrategy=function(prefix,root,toMount){var offset=prefix.length;return function(target,name,i,segs){if(i<=prefix.length){return}for(var j=0;j<prefix.length;++j){if(segs[j]!==prefix[j]){return}}return toMount(target,name,i-prefix.length,segs.slice(offset))}};fluid.invokerFromRecord=function(invokerec,name,that){fluid.pushActivity("makeInvoker","beginning instantiation of invoker with name %name and record %record as child of %that",{name:name,record:invokerec,that:that});var invoker=invokerec?fluid.makeInvoker(that,invokerec,name):undefined;fluid.popActivity();return invoker};fluid.memberFromRecord=function(memberrecs,name,that){var shadow=fluid.shadowForComponent(that);var togo;for(var i=0;i<memberrecs.length;++i){var expanded=fluid.expandImmediate(memberrecs[i],that,shadow.localRecord);if(!fluid.isPlainObject(togo)){togo=expanded}else{togo=$.extend(true,togo,expanded)}}return togo};fluid.resourceFromRecord=function(resourceRec,name,that){var resourceFetcher=fluid.getForComponent(that,"resourceFetcher");var resourceSpec=resourceFetcher.resourceSpecs[name];var oneFetcher=new fluid.fetchResources.FetchOne(resourceSpec,resourceFetcher);var existing=that.resources[name];if(existing&&existing!==fluid.inEvaluationMarker){return existing}else{var promise=oneFetcher.resourceSpec.promise;if(!promise.disposition){var transRec=fluid.currentTreeTransaction();transRec.pendingIO.push(promise)}return oneFetcher}};fluid.recordStrategy=function(that,options,optionsStrategy,recordPath,recordMaker,prefix,exceptions){prefix=prefix||[];var fullyEvaluated=false;return{strategy:function(target,name,i){if(i!==1||fullyEvaluated){return}var record=fluid.driveStrategy(options,[recordPath,name],optionsStrategy);if(record===undefined){if(prefix.length>0){fluid.fail("Reference to "+recordPath+" record with name "+name+" which is not registered for component "+fluid.dumpComponentAndPath(that))}else{return}}fluid.set(target,[name],fluid.inEvaluationMarker);var member=recordMaker(record,name,that);fluid.set(target,[name],member);return member},initter:function(){var records=fluid.driveStrategy(options,recordPath,optionsStrategy)||{};for(var name in records){if(!exceptions||!exceptions[name]){fluid.getForComponent(that,prefix.concat([name]))}}fullyEvaluated=true}}};fluid.makeDistributionRecord=function(contextThat,sourceRecord,sourcePath,targetSegs,exclusions,sourceType){sourceType=sourceType||"distribution";fluid.pushActivity("makeDistributionRecord","Making distribution record from source record %sourceRecord path %sourcePath to target path %targetSegs",{sourceRecord:sourceRecord,sourcePath:sourcePath,targetSegs:targetSegs});var source=fluid.copy(fluid.get(sourceRecord,sourcePath));fluid.each(exclusions,(function(exclusion){fluid.model.applyChangeRequest(source,{segs:exclusion,type:"DELETE"})}));var record={options:{}};fluid.model.applyChangeRequest(record,{segs:targetSegs,type:"ADD",value:source});fluid.checkComponentRecord(record,fluid.componentRecordExpected);fluid.popActivity();return $.extend(record,{contextThat:contextThat,recordType:sourceType})};fluid.filterBlocks=function(contextThat,sourceBlocks,sourceSegs,targetSegs,exclusions,removeSource){var togo=[];fluid.each(sourceBlocks,(function(block){var source=fluid.get(block.source,sourceSegs);if(source!==undefined){togo.push(fluid.makeDistributionRecord(contextThat,block.source,sourceSegs,targetSegs,exclusions,"distribution"));var rescued=$.extend({},source);if(removeSource){fluid.model.applyChangeRequest(block.source,{segs:sourceSegs,type:"DELETE"})}fluid.each(exclusions,(function(exclusion){var orig=fluid.get(rescued,exclusion);fluid.set(block.source,sourceSegs.concat(exclusion),orig)}))}}));return togo};fluid.noteCollectedDistribution=function(parentShadow,memberName,distribution){fluid.model.setSimple(parentShadow,["collectedDistributions",memberName,distribution.id],true)};fluid.isCollectedDistribution=function(parentShadow,memberName,distribution){return fluid.model.getSimple(parentShadow,["collectedDistributions",memberName,distribution.id])};fluid.clearCollectedDistributions=function(parentShadow,memberName){fluid.model.applyChangeRequest(parentShadow,{segs:["collectedDistributions",memberName],type:"DELETE"})};fluid.collectDistributions=function(distributedBlocks,parentShadow,distribution,thatStack,contextHashes,memberNames,i){var lastMember=fluid.peek(memberNames);if(!fluid.isCollectedDistribution(parentShadow,lastMember,distribution)&&fluid.matchIoCSelector(distribution.selector,thatStack,contextHashes,memberNames,i)){distributedBlocks.push.apply(distributedBlocks,fluid.copy(distribution.blocks));fluid.noteCollectedDistribution(parentShadow,lastMember,distribution)}};fluid.registerCollectedClearer=function(shadow,parentShadow,memberName){if(!shadow.collectedClearer&&parentShadow){shadow.collectedClearer=function(){fluid.clearCollectedDistributions(parentShadow,memberName)}}};fluid.receiveDistributions=function(parentThat,gradeNames,memberName,that){var instantiator=fluid.getInstantiator(parentThat||that);var thatStack=instantiator.getThatStack(parentThat||that);thatStack.unshift(fluid.rootComponent);var memberNames=fluid.getMemberNames(instantiator,thatStack);var shadows=fluid.transform(thatStack,(function(thisThat){return instantiator.idToShadow[thisThat.id]}));var parentShadow=shadows[shadows.length-(parentThat?1:2)];var contextHashes=fluid.getMembers(shadows,"contextHash");if(parentThat){memberNames.push(memberName);contextHashes.push(fluid.gradeNamesToHash(gradeNames));thatStack.push(that)}else{fluid.registerCollectedClearer(fluid.peek(shadows),parentShadow,fluid.peek(memberNames))}var distributedBlocks=[];for(var i=0;i<thatStack.length-1;++i){fluid.each(shadows[i].distributions,(function(distribution){fluid.collectDistributions(distributedBlocks,parentShadow,distribution,thatStack,contextHashes,memberNames,i)}))}return distributedBlocks};fluid.computeTreeDistance=function(path1,path2){var i=0;while(i<path1.length&&i<path2.length&&path1[i]===path2[i]){++i}return path1.length+path2.length-2*i};fluid.computeDistributionPriority=function(targetThat,distributedBlock){if(!distributedBlock.priority){var instantiator=fluid.getInstantiator(targetThat);var targetStack=instantiator.getThatStack(targetThat);var targetPath=fluid.getMemberNames(instantiator,targetStack);var sourceStack=instantiator.getThatStack(distributedBlock.contextThat);var sourcePath=fluid.getMemberNames(instantiator,sourceStack);var distance=fluid.computeTreeDistance(targetPath,sourcePath);distributedBlock.priority=fluid.mergeRecordTypes.distribution-distance}return distributedBlock};fluid.applyDistributions=function(that,preBlocks,targetShadow){var distributedBlocks=fluid.transform(preBlocks,(function(preBlock){return fluid.generateExpandBlock(preBlock,that,targetShadow.mergePolicy)}),(function(distributedBlock){return fluid.computeDistributionPriority(that,distributedBlock)}));var mergeOptions=targetShadow.mergeOptions;mergeOptions.mergeBlocks.push.apply(mergeOptions.mergeBlocks,distributedBlocks);mergeOptions.updateBlocks();return distributedBlocks};fluid.matchIoCSelector=function(selector,thatStack,contextHashes,memberNames,i){var thatpos=thatStack.length-1;var selpos=selector.length-1;while(true){var isChild=selector[selpos].child;var mustMatchHere=thatpos===thatStack.length-1||isChild;var that=thatStack[thatpos];var selel=selector[selpos];var match=true;for(var j=0;j<selel.predList.length;++j){var pred=selel.predList[j];var context=pred.context;if(context&&context!=="*"&&!(contextHashes[thatpos][context]||memberNames[thatpos]===context)){match=false;break}if(pred.id&&that.id!==pred.id){match=false;break}}if(selpos===0&&thatpos>i&&mustMatchHere&&isChild){match=false}if(match){if(selpos===0){return true}--thatpos;--selpos}else{if(mustMatchHere){return false}else{--thatpos}}if(thatpos<i){return false}}return false};fluid.queryIoCSelector=function(root,selector,flat){var parsed=fluid.parseSelector(selector,fluid.IoCSSMatcher);var togo=[];fluid.visitComponentsForMatching(root,{flat:flat},(function(that,thatStack,contextHashes){if(fluid.matchIoCSelector(parsed,thatStack,contextHashes,[],1)){togo.push(that)}}));return togo};fluid.isIoCSSSelector=function(context){return context.indexOf(" ")!==-1};fluid.pushDistributions=function(targetHead,selector,target,blocks){var targetShadow=fluid.shadowForComponent(targetHead);var id=fluid.allocateGuid();var distribution={id:id,target:target,selector:selector,blocks:blocks};Object.freeze(distribution);Object.freeze(distribution.blocks);distribution.blocks.forEach((function(block){fluid.freezeRecursive(block.options)}));fluid.pushArray(targetShadow,"distributions",distribution);return id};fluid.clearDistribution=function(targetHeadId,id){var targetHeadShadow=fluid.globalInstantiator.idToShadow[targetHeadId];if(targetHeadShadow){fluid.remove_if(targetHeadShadow.distributions,(function(distribution){return distribution.id===id}))}};fluid.clearDistributions=function(shadow){fluid.each(shadow.outDistributions,(function(outDist){fluid.clearDistribution(outDist.targetHeadId,outDist.distributionId)}))};fluid.extractSelectorHead=function(parsedSelector){var predList=parsedSelector[0].predList;var context=predList[0].context;predList.length=0;return context};fluid.parseExpectedOptionsPath=function(path,role){var segs=fluid.model.parseEL(path);if(segs[0]!=="options"){fluid.fail("Error in options distribution path ",path," - only "+role+' paths beginning with "options" are supported')}return segs.slice(1)};fluid.replicateProperty=function(source,property,targets){if(source[property]!==undefined){fluid.each(targets,(function(target){target[property]=source[property]}))}};fluid.undistributableOptions=["gradeNames","distributeOptions","argumentMap","mergePolicy"];fluid.distributeOptionsOne=function(that,record,targetRef,selector,context){fluid.pushActivity("distributeOptions","parsing distributeOptions block %record %that ",{that:that,record:record});var targetHead=fluid.resolveContext(context,that);if(!targetHead){fluid.fail("Error in options distribution record ",record," - could not resolve context {"+context+"} to a head component")}var thatShadow=fluid.shadowForComponent(that);var targetSegs=fluid.model.parseEL(targetRef.path);var preBlocks;if(record.record!==undefined){preBlocks=[fluid.makeDistributionRecord(that,record.record,[],targetSegs,[])]}else{var source=fluid.parseContextReference(record.source);if(source.context!=="that"){fluid.fail("Error in options distribution record ",record," only a source context of {that} is supported")}var sourceSegs=fluid.parseExpectedOptionsPath(source.path,"source");var fullExclusions=fluid.makeArray(record.exclusions).concat(sourceSegs.length===0?fluid.undistributableOptions:[]);var exclusions=fluid.transform(fullExclusions,(function(exclusion){return fluid.model.parseEL(exclusion)}));preBlocks=fluid.filterBlocks(that,thatShadow.mergeOptions.mergeBlocks,sourceSegs,targetSegs,exclusions,record.removeSource);thatShadow.mergeOptions.updateBlocks()}fluid.replicateProperty(record,"priority",preBlocks);fluid.replicateProperty(record,"namespace",preBlocks);if(selector){var distributionId=fluid.pushDistributions(targetHead,selector,record.target,preBlocks);thatShadow.outDistributions=thatShadow.outDistributions||[];thatShadow.outDistributions.push({targetHeadId:targetHead.id,distributionId:distributionId})}else{var targetShadow=fluid.shadowForComponent(targetHead);fluid.applyDistributions(that,preBlocks,targetShadow)}fluid.popActivity()};fluid.distributeOptions=function(that,optionsStrategy){var records=fluid.driveStrategy(that.options,"distributeOptions",optionsStrategy);fluid.each(records,(function distributeOptionsOne(record){if(typeof record.target!=="string"){fluid.fail("Error in options distribution record ",record,' a member named "target" must be supplied holding an IoC reference')}if(typeof record.source==="string"^record.record===undefined){fluid.fail("Error in options distribution record ",record,': must supply either a member "source" holding an IoC reference or a member "record" holding a literal record')}var targetRef=fluid.parseContextReference(record.target);var selector,context;if(fluid.isIoCSSSelector(targetRef.context)){selector=fluid.parseSelector(targetRef.context,fluid.IoCSSMatcher);context=fluid.extractSelectorHead(selector)}else{context=targetRef.context}if(context==="/"||context==="that"){fluid.distributeOptionsOne(that,record,targetRef,selector,context)}else{var transRec=fluid.currentTreeTransaction();transRec.deferredDistributions.push({that:that,record:record,targetRef:targetRef,selector:selector,context:context})}}))};fluid.contextName=1;fluid.memberName=2;fluid.gradeNamesToHash=function(gradeNames){var contextHash={};fluid.each(gradeNames,(function(gradeName){if(!fluid.isReferenceOrExpander(gradeName)){contextHash[gradeName]=fluid.contextName;contextHash[fluid.computeNickName(gradeName)]=fluid.contextName}}));return contextHash};fluid.applyToContexts=function(hash,key,disposition){var existing=hash[key];hash[key]=(existing||0)|disposition};fluid.applyToScope=function(scope,key,value,disposition){var existing=scope[key];if(!existing||disposition&fluid.memberName){scope[key]=value}};fluid.cacheShadowGrades=function(that,shadow){var contextHash=fluid.gradeNamesToHash(that.options&&that.options.gradeNames||[that.typeName]);fluid.applyToContexts(contextHash,shadow.memberName,fluid.memberName);shadow.contextHash=contextHash;fluid.each(contextHash,(function(disposition,context){shadow.ownScope[context]=that;if(shadow.parentShadow&&shadow.parentShadow.that.typeName!=="fluid.rootComponent"){fluid.applyToScope(shadow.parentShadow.childrenScope,context,that,disposition)}}))};fluid.deliverOptionsStrategy=function(that,target,mergeOptions){var shadow=fluid.shadowForComponent(that,shadow);fluid.cacheShadowGrades(that,shadow);shadow.mergeOptions=mergeOptions};fluid.collectDistributedGrades=function(rec){var distributedBlocks=fluid.receiveDistributions(null,null,null,rec.that);if(distributedBlocks.length>0){var readyBlocks=fluid.applyDistributions(rec.that,distributedBlocks,rec.shadow);var gradeNamesList=fluid.transform(fluid.getMembers(readyBlocks,["source","gradeNames"]),fluid.makeArray);fluid.accumulateDynamicGrades(rec,fluid.flatten(gradeNamesList))}};fluid.applyDynamicGrades=function(rec){rec.oldGradeNames=fluid.makeArray(rec.gradeNames);var newDefaults=fluid.copy(fluid.getMergedDefaults(rec.that.typeName,rec.gradeNames));rec.gradeNames.length=0;rec.gradeNames.push.apply(rec.gradeNames,newDefaults.gradeNames);fluid.each(rec.gradeNames,(function(gradeName){if(!fluid.isReferenceOrExpander(gradeName)){rec.seenGrades[gradeName]=true}}));var shadow=rec.shadow;fluid.cacheShadowGrades(rec.that,shadow);shadow.mergeOptions.destroyValue(["mergePolicy"]);shadow.mergeOptions.destroyValue(["components"]);shadow.mergeOptions.destroyValue(["invokers"]);rec.defaultsBlock.source=newDefaults;shadow.mergeOptions.updateBlocks();shadow.mergeOptions.computeMergePolicy();fluid.accumulateDynamicGrades(rec,newDefaults.gradeNames)};fluid.accumulateDynamicGrades=function(rec,newGradeNames){fluid.each(newGradeNames,(function(gradeName){var flatGradeName=fluid.flattenGradeName(gradeName);if(!rec.seenGrades[flatGradeName]){if(fluid.isReferenceOrExpander(gradeName)){rec.rawDynamic.push(gradeName);rec.seenGrades[flatGradeName]=true}else if(!rec.oldGradeNames.includes(gradeName)){rec.plainDynamic.push(gradeName)}}}))};fluid.accumulateContextAwareGrades=function(that,rec){var newContextAware=[];if(rec.gradeNames.includes("fluid.contextAware")){var contextAwarenessOptions=fluid.getForComponent(that,["options","contextAwareness"]);newContextAware=fluid.contextAware.check(that,contextAwarenessOptions);var lostGrade=fluid.find_if(rec.contextAware,(function(gradeName){return!newContextAware.includes(gradeName)}));if(lostGrade){fluid.fail("Failure operating contextAwareness definition ",contextAwarenessOptions," for component "+fluid.dumpComponentAndPath(that)+": grade name "+lostGrade+" returned by an earlier round of checks was lost through a context change caused by a raw dynamic grade")}rec.contextAware=newContextAware}return newContextAware};fluid.computeDynamicGrades=function(that,shadow,strategy){delete that.options.gradeNames;var gradeNames=fluid.driveStrategy(that.options,"gradeNames",strategy);gradeNames.length=0;var defaultsBlock=fluid.findMergeBlocks(shadow.mergeOptions.mergeBlocks,"defaults")[0];var rec={that:that,shadow:shadow,defaultsBlock:defaultsBlock,gradeNames:gradeNames,seenGrades:{},plainDynamic:[],contextAware:[],rawDynamic:[]};fluid.each(shadow.mergeOptions.mergeBlocks,(function(block){gradeNames.push.apply(gradeNames,fluid.makeArray(block.target&&block.target.gradeNames));fluid.applyDynamicGrades(rec)}));fluid.collectDistributedGrades(rec);var checkContextAware=true;while(true){while(rec.plainDynamic.length>0){gradeNames.push.apply(gradeNames,rec.plainDynamic);rec.plainDynamic.length=0;fluid.applyDynamicGrades(rec);fluid.collectDistributedGrades(rec)}if(checkContextAware){var newContextAware=fluid.accumulateContextAwareGrades(that,rec);rec.plainDynamic=rec.plainDynamic.concat(newContextAware);checkContextAware=false}else if(rec.rawDynamic.length>0){var toexpand=rec.rawDynamic.shift();var expanded=fluid.expandImmediate(toexpand,that,shadow.localRecord);if(typeof expanded==="function"){expanded=expanded()}if(expanded){rec.plainDynamic=rec.plainDynamic.concat(expanded)}checkContextAware=true}else{break}}fluid.remove_if(gradeNames,fluid.isReferenceOrExpander);if(shadow.collectedClearer){shadow.collectedClearer();delete shadow.collectedClearer}};fluid.computeComponentAccessor=function(that,localRecord){var instantiator=fluid.globalInstantiator;var shadow=fluid.shadowForComponent(that);shadow.localRecord=localRecord;var options=that.options;var strategy=shadow.mergeOptions.strategy;var optionsStrategy=fluid.mountStrategy(["options"],options,strategy);shadow.invokerStrategy=fluid.recordStrategy(that,options,strategy,"invokers",fluid.invokerFromRecord);shadow.eventStrategyBlock=fluid.recordStrategy(that,options,strategy,"events",fluid.eventFromRecord,["events"]);var eventStrategy=fluid.mountStrategy(["events"],that,shadow.eventStrategyBlock.strategy);shadow.memberStrategy=fluid.recordStrategy(that,options,strategy,"members",fluid.memberFromRecord,null,{model:true,modelRelay:true});shadow.getConfig={strategies:[fluid.concreteStrategy,fluid.model.funcResolverStrategy,optionsStrategy,shadow.invokerStrategy.strategy,shadow.memberStrategy.strategy,eventStrategy]};fluid.computeDynamicGrades(that,shadow,strategy,shadow.mergeOptions.mergeBlocks);if(shadow.contextHash["fluid.resourceLoader"]){shadow.resourceStrategyBlock=fluid.recordStrategy(that,options,strategy,"resources",fluid.resourceFromRecord,["resources"]);var resourceStrategy=fluid.mountStrategy(["resources"],that,shadow.resourceStrategyBlock.strategy);shadow.getConfig.strategies.push(resourceStrategy);that.resources={}}fluid.distributeOptions(that,strategy);if(shadow.contextHash["fluid.resolveRoot"]){var memberName;if(shadow.contextHash["fluid.resolveRootSingle"]){var singleRootType=fluid.getForComponent(that,["options","singleRootType"]);if(!singleRootType){fluid.fail("Cannot register object with grades "+Object.keys(shadow.contextHash).join(", ")+" as fluid.resolveRootSingle since it has not defined option singleRootType")}memberName=fluid.typeNameToMemberName(singleRootType)}else{memberName=fluid.computeGlobalMemberName(that.typeName,that.id)}var parent=fluid.resolveRootComponent;if(parent[memberName]){instantiator.clearComponent(parent,memberName)}instantiator.recordKnownComponent(parent,that,memberName,false)}return shadow.getConfig};fluid.shadowForComponent=function(component){var instantiator=fluid.getInstantiator(component);return instantiator&&component?instantiator.idToShadow[component.id]:null};fluid.pathInEvaluation=function(path,paths){var index=paths.indexOf(path);return index!==-1&&index!==paths.length-1};fluid.getForComponent=function(component,path){var segs=fluid.model.pathToSegments(path);if(segs.length===0){return component}var instantiator=fluid.globalInstantiator;var shadow=fluid.shadowForComponent(component);if(shadow){var next=fluid.get(component,segs[0],shadow.getConfig);if(fluid.isComponent(next)){return fluid.getForComponent(next,segs.slice(1))}else{var inEvaluationPaths=instantiator.inEvaluationPaths;var inEvaluationPath=component.id+":"+path;if(fluid.pathInEvaluation(inEvaluationPath,inEvaluationPaths)){fluid.fail("Error in component configuration - a circular reference was found during evaluation of path "+path+" for component "+fluid.dumpComponentAndPath(component)+": a circular set of references was found - for more details, see the activity records following this message in the console")}else{inEvaluationPaths.push(inEvaluationPath);var togo=fluid.get(component,path,shadow.getConfig);inEvaluationPaths.pop();return togo}}}else{return fluid.get(component,path)}};fluid.concreteStrategy=function(component,thisSeg,index,segs){var atval=component[thisSeg];if(atval===fluid.inEvaluationMarker){fluid.fail('Error in component configuration - a circular reference was found during evaluation of path segment "'+thisSeg+" of path ",segs,'": for more details, see the activity records following this message in the console, or issue fluid.setLogging(fluid.logLevel.TRACE) when running your application')}if(index>1){return atval}if(atval===undefined&&component.hasOwnProperty(thisSeg)){return fluid.NO_VALUE}return atval};fluid.frameworkGrades=["fluid.component","fluid.modelComponent","fluid.viewComponent","fluid.rendererComponent"];fluid.filterBuiltinGrades=function(gradeNames){return fluid.remove_if(fluid.makeArray(gradeNames),(function(gradeName){return fluid.frameworkGrades.indexOf(gradeName)!==-1}))};fluid.dumpGradeNames=function(that){return that.options&&that.options.gradeNames?" gradeNames: "+JSON.stringify(fluid.filterBuiltinGrades(that.options.gradeNames)):""};fluid.dumpThat=function(that){return'{ typeName: "'+that.typeName+" id: "+that.id+'"'+fluid.dumpGradeNames(that)+"}"};fluid.dumpThatStack=function(thatStack,instantiator){var togo=fluid.transform(thatStack,(function(that){var path=instantiator.idToPath(that.id);return fluid.dumpThat(that)+(path?" - path: "+path:"")}));return togo.join("\n")};fluid.dumpComponentPath=function(that){var path=fluid.pathForComponent(that);return path?fluid.pathUtil.composeSegments.apply(null,path):"** no path registered for component **"};fluid.dumpComponentAndPath=function(that){return"component "+fluid.dumpThat(that)+" at path "+fluid.dumpComponentPath(that)};fluid.resolveContext=function(context,that,fast){if(context==="that"){return that}else if(context==="/"){return fluid.rootComponent}if(typeof context==="object"){var innerContext=fluid.resolveContext(context.context,that,fast);if(!fluid.isComponent(innerContext)){fluid.triggerMismatchedPathError(context.context,that)}var rawValue=fluid.getForComponent(innerContext,context.path);var expanded=fluid.expandOptions(rawValue,that);if(!fluid.isComponent(expanded)){fluid.fail("Unable to resolve recursive context expression "+fluid.renderContextReference(context)+": the directly resolved value of "+rawValue+" did not resolve to a component in the scope of "+fluid.dumpComponentAndPath(that)+": got ",expanded)}return expanded}else{var foundComponent;var instantiator=fluid.globalInstantiator;if(fast){var shadow=instantiator.idToShadow[that.id];return shadow.ownScope[context]}else{var thatStack=instantiator.getFullStack(that);fluid.visitComponentsForVisibility(instantiator,thatStack,(function(component,memberName){var shadow=fluid.shadowForComponent(component);var scopeValue=shadow.contextHash[context];if(scopeValue&&scopeValue!==fluid.memberName||context===memberName){foundComponent=component;return true}}));return foundComponent}}};fluid.triggerMismatchedPathError=function(parsed,parentThat){var ref=fluid.renderContextReference(parsed);fluid.fail("Failed to resolve reference "+ref+" - could not match context with name "+parsed.context+" from "+fluid.dumpComponentAndPath(parentThat))};fluid.makeStackFetcher=function(parentThat,localRecord,fast){var fetcher=function(parsed){if(parentThat&&parentThat.lifecycleStatus==="destroyed"){fluid.fail("Cannot resolve reference "+fluid.renderContextReference(parsed)+" from component "+fluid.dumpComponentAndPath(parentThat)+" which has been destroyed")}var context=parsed.context;if(localRecord&&context in localRecord){return fluid.get(localRecord[context],parsed.path)}var foundComponent=fluid.resolveContext(context,parentThat,fast);if(!foundComponent&&parsed.path!==""){fluid.triggerMismatchedPathError(parsed,parentThat)}return fluid.getForComponent(foundComponent,parsed.path)};return fetcher};fluid.makeStackResolverOptions=function(parentThat,localRecord,fast){return $.extend(fluid.copy(fluid.rawDefaults("fluid.makeExpandOptions")),{ELstyle:"{}",localRecord:localRecord||{},fetcher:fluid.makeStackFetcher(parentThat,localRecord,fast),contextThat:parentThat,exceptions:{members:{model:true,modelRelay:true}}})};fluid.clearListeners=function(shadow){fluid.each(shadow.listeners,(function(rec){rec.event.removeListener(rec.listenerId||rec.listener)}));delete shadow.listeners};fluid.recordListener=function(event,listener,shadow,listenerId){if(event.ownerId!==shadow.that.id){fluid.pushArray(shadow,"listeners",{event:event,listener:listener,listenerId:listenerId})}};fluid.constructScopeObjects=function(instantiator,parent,child,childShadow){var parentShadow=parent?instantiator.idToShadow[parent.id]:null;childShadow.childrenScope=parentShadow?Object.create(parentShadow.ownScope):{};childShadow.ownScope=Object.create(childShadow.childrenScope);childShadow.parentShadow=parentShadow;childShadow.childComponents={};fluid.cacheShadowGrades(child,childShadow)};fluid.clearChildrenScope=function(parentShadow,child,childShadow,memberName){var keys=fluid.keys(childShadow.contextHash);keys.push(memberName);keys.forEach((function(context){if(parentShadow.childrenScope[context]===child){delete parentShadow.childrenScope[context]}}))};fluid.clearComponentIndexes=function(instantiator,destroyRec){var shadow=destroyRec.shadow;fluid.clearChildrenScope(shadow,destroyRec.child,destroyRec.childShadow,destroyRec.name);delete instantiator.pathToComponent[destroyRec.childPath];delete shadow.childComponents[destroyRec.name]};fluid.doDestroy=function(instantiator,destroyRec){var shadow=destroyRec.childShadow,that=destroyRec.child;fluid.each(shadow.injectedPaths,(function(troo,injectedPath){var parentPath=fluid.model.getToTailPath(injectedPath);var otherParent=instantiator.pathToComponent[parentPath];instantiator.clearComponent(otherParent,fluid.model.getTailPath(injectedPath),that)}));fluid.clearComponentIndexes(instantiator,destroyRec);fluid.clearDistributions(shadow);fluid.clearListeners(shadow);for(var key in that.events){if(key!=="afterDestroy"&&typeof that.events[key].destroy==="function"){that.events[key].destroy()}}if(that.applier){that.applier.destroy()}that.lifecycleStatus="destroyed";fluid.fireEvent(destroyRec.child,"afterDestroy",[destroyRec.child,destroyRec.name,destroyRec.component]);delete instantiator.idToShadow[destroyRec.child.id]};fluid.instantiator=function(){var that=fluid.typeTag("instantiator");$.extend(that,{lifecycleStatus:"constructed",pathToComponent:{},idToShadow:{},modelTransactions:{},treeTransactions:{},inEvaluationPaths:[],currentTreeTransactionId:null,composePath:fluid.model.composePath,composeSegments:fluid.model.composeSegments,parseEL:fluid.model.parseEL,events:{onComponentAttach:fluid.makeEventFirer({name:"instantiator's onComponentAttach event"}),onComponentClear:fluid.makeEventFirer({name:"instantiator's onComponentClear event"}),onBeginTreeTransaction:fluid.makeEventFirer({name:"instantiator's onBeginTransaction event"}),onEndTreeTransaction:fluid.makeEventFirer({name:"instantiator's onEndTransaction event"})}});that.parseToSegments=function(path){return fluid.model.parseToSegments(path,that.parseEL,true)};that.idToPath=function(id){var shadow=that.idToShadow[id];return shadow?shadow.path:""};that.getThatStack=function(component){var shadow=that.idToShadow[component.id];if(shadow){var path=shadow.path;var parsed=that.parseEL(path);var root=that.pathToComponent[""],togo=[];for(var i=0;i<parsed.length;++i){root=root[parsed[i]];togo.push(root)}return togo}else{return[]}};that.getFullStack=function(component){var thatStack=component?that.getThatStack(component):[];thatStack.unshift(fluid.resolveRootComponent);return thatStack};function recordComponent(parent,component,path,name,created){var shadow;if(created){shadow=that.idToShadow[component.id]={};shadow.that=component;shadow.path=path;shadow.memberName=name;fluid.constructScopeObjects(that,parent,component,shadow)}else{shadow=that.idToShadow[component.id];shadow.injectedPaths=shadow.injectedPaths||{};shadow.injectedPaths[path]=true;var parentShadow=that.idToShadow[parent.id];var keys=fluid.keys(shadow.contextHash);fluid.remove_if(keys,(function(key){return shadow.contextHash&&shadow.contextHash[key]===fluid.memberName}));keys.push(name);keys.forEach((function(context){if(!parentShadow.childrenScope.hasOwnProperty(context)){parentShadow.childrenScope[context]=component}}))}if(that.pathToComponent[path]){fluid.fail("Error during instantiation - path "+path+" which has just created component "+fluid.dumpThat(component)+" has already been used for component "+fluid.dumpThat(that.pathToComponent[path])+" - this is a circular instantiation or other oversight."+" Please clear the component using instantiator.clearComponent() before reusing the path.")}that.pathToComponent[path]=component}that.recordRoot=function(component){recordComponent(null,component,"","",true)};that.recordKnownComponent=function(parent,component,name,created){parent[name]=component;if(fluid.isComponent(component)||component.type==="instantiator"){var parentShadow=that.idToShadow[parent.id];parentShadow.childComponents[name]=component;var path=that.composePath(parentShadow.path,name);recordComponent(parent,component,path,name,created);that.events.onComponentAttach.fire(component,path,that,created)}else{fluid.fail("Cannot record non-component with value ",component,' at path "'+name+'" of parent ',parent)}};that.clearComponent=function(component,name,child,options,nested,path){var shadow=that.idToShadow[component.id];options=options||{flat:true,destroyRecs:[]};child=child||component[name];path=path||shadow.path;if(path===undefined){fluid.fail("Cannot clear component "+name+" from component ",component," which was not created by this instantiator")}var childPath=that.composePath(path,name);var childShadow=that.idToShadow[child.id];if(!childShadow){return}var created=childShadow.path===childPath;that.events.onComponentClear.fire(child,childPath,component,created);var destroyRec={child:child,childShadow:childShadow,name:name,component:component,shadow:shadow,childPath:childPath};if(created){if(fluid.isDestroyed(child)){fluid.fail('Cannot destroy component which is already in status "'+child.lifecycleStatus+'"')}child.lifecycleStatus="destroying";fluid.visitComponentChildren(child,(function(gchild,gchildname,segs,i){var parentPath=that.composeSegments.apply(null,segs.slice(0,i));that.clearComponent(child,gchildname,null,options,true,parentPath)}),options,that.parseEL(childPath));fluid.fireEvent(child,"onDestroy",[child,name||"",component]);options.destroyRecs.push(destroyRec)}else{fluid.remove_if(childShadow.injectedPaths,(function(troo,path){return path===childPath}));fluid.clearComponentIndexes(that,destroyRec)}if(!nested){delete component[name];options.destroyRecs.forEach((function(destroyRec){fluid.doDestroy(that,destroyRec)}))}};return that};fluid.globalInstantiator=fluid.instantiator();fluid.getInstantiator=function(component){var instantiator=fluid.globalInstantiator;return component&&instantiator.idToShadow[component.id]?instantiator:null};fluid.defaults("fluid.resolveRoot");fluid.defaults("fluid.resolveRootSingle",{gradeNames:"fluid.resolveRoot"});fluid.constructRootComponents=function(instantiator){fluid.rootComponent=instantiator.rootComponent=fluid.typeTag("fluid.rootComponent");instantiator.recordRoot(fluid.rootComponent);fluid.resolveRootComponent=instantiator.resolveRootComponent=fluid.typeTag("fluid.resolveRootComponent");instantiator.recordKnownComponent(fluid.rootComponent,fluid.resolveRootComponent,"resolveRootComponent",true);var rootShadow=instantiator.idToShadow[fluid.rootComponent.id];rootShadow.contextHash={};var resolveRootShadow=instantiator.idToShadow[fluid.resolveRootComponent.id];resolveRootShadow.ownScope=rootShadow.ownScope;resolveRootShadow.childrenScope=rootShadow.childrenScope;instantiator.recordKnownComponent(fluid.resolveRootComponent,instantiator,"instantiator",true);resolveRootShadow.childrenScope.instantiator=instantiator};fluid.constructRootComponents(fluid.globalInstantiator);fluid.expandOptions=function(args,that,mergePolicy,localRecord,outerExpandOptions){if(!args){return args}fluid.pushActivity("expandOptions","expanding options %args for component %that ",{that:that,args:args});var expandOptions=fluid.makeStackResolverOptions(that,localRecord);expandOptions.mergePolicy=mergePolicy;expandOptions.defer=outerExpandOptions&&outerExpandOptions.defer;var expanded=expandOptions.defer?fluid.makeExpandOptions(args,expandOptions):fluid.expand(args,expandOptions);fluid.popActivity();return expanded};fluid.computeMergeListPriority=function(toMerge){toMerge.forEach((function(record){var recordType=record.recordType;if(recordType!=="distribution"){record.priority=fluid.mergeRecordTypes[recordType]+(record.priorityDelta||0);if(!Number.isInteger(record.priority)){fluid.fail("Merge record with unrecognised type "+recordType+": ",record)}}}))};var addPolicyBuiltins=function(policy){fluid.each(["gradeNames","mergePolicy","argumentMap","components","dynamicComponents","events","listeners","modelListeners","modelRelay","distributeOptions","transformOptions"],(function(key){fluid.set(policy,[key,"*","noexpand"],true)}));return policy};fluid.generateExpandBlock=function(record,that,mergePolicy,localRecord){var expanded=fluid.expandOptions(record.options||{},record.contextThat||that,mergePolicy,localRecord,{defer:true});expanded.priority=record.priority;expanded.namespace=record.namespace;expanded.recordType=record.recordType;return expanded};fluid.fabricateDestroyMethod=function(that){return function(){var currentTrans=fluid.currentTreeTransaction();var shadow=fluid.shadowForComponent(that);var transRec=fluid.destroy(shadow.path);if(!currentTrans){transRec.promise.then(null,(function(e){throw e}))}}};fluid.typeNameToMemberName=function(typeName){return typeName.replace(/\./g,"_")};fluid.expandComponentOptions=function(mergePolicy,potentia,lightMerge,that){var toMerge=lightMerge.toMerge;var container=fluid.lightMergeValue(toMerge,"container");if(container){toMerge.push({recordType:"distribution",priority:fluid.mergeRecordTypes.distribution,options:{container:container},contextThat:potentia.parentThat})}that.destroy=fluid.fabricateDestroyMethod(that);addPolicyBuiltins(mergePolicy);var shadow=fluid.shadowForComponent(that);shadow.mergePolicy=mergePolicy;fluid.computeMergeListPriority(toMerge);var togo=fluid.transform(toMerge,(function(value){return fluid.generateExpandBlock(value,that,mergePolicy,potentia.localRecord)}));return togo};fluid.computeDynamicComponentKey=function(recordKey,sourceKey){return recordKey+(sourceKey===0||sourceKey==="0"?"":"-"+sourceKey)};fluid.concludeAnyTreeTransaction=function(){var instantiator=fluid.globalInstantiator;var transactionId=instantiator.currentTreeTransactionId;if(transactionId){var transRec=instantiator.treeTransactions[transactionId];var errorOut;transRec.promise.then(null,(function(e){errorOut=e}));fluid.commitPotentiae(transactionId);if(errorOut){throw errorOut}}};fluid.bindDeferredComponent=function(that,componentName,lightMerge,dynamicComponent){var eventName=lightMerge.createOnEvent;var event=fluid.isIoCReference(eventName)?fluid.expandOptions(eventName,that):that.events[eventName];if(!event||!event.addListener){fluid.fail("Error instantiating createOnEvent component with name "+componentName+" of parent "+fluid.dumpComponentAndPath(that)+" since event specification "+eventName+" could not be expanded to an event - got ",event)}var shadow=fluid.shadowForComponent(that);if(dynamicComponent){fluid.set(shadow,["dynamicComponentCount",componentName],0)}var constructListener=function(){var key=dynamicComponent?fluid.computeDynamicComponentKey(componentName,shadow.dynamicComponentCount[componentName]++):componentName;var localRecord={arguments:fluid.makeArray(arguments)};fluid.pushActivity("initDeferred","instantiating deferred component %componentName of parent %that due to event %eventName",{componentName:componentName,that:that,eventName:eventName});var freshLightMerge=fluid.copy(lightMerge);delete freshLightMerge.createOnEvent;fluid.registerConcreteSubPotentia(freshLightMerge,key,0,that,localRecord);fluid.popActivity()};event.addListener(constructListener);fluid.recordListener(event,constructListener,shadow);event.addListener(fluid.concludeAnyTreeTransaction,"fluid-componentConstruction","last:transaction");fluid.recordListener(event,fluid.concludeAnyTreeTransaction,shadow)};fluid.markSubtree=function(instantiator,that,path,state){that.lifecycleStatus=state;fluid.visitComponentChildren(that,(function(child,name){var childPath=instantiator.composePath(path,name);var childShadow=instantiator.idToShadow[child.id];var created=childShadow&&childShadow.path===childPath;if(created){fluid.markSubtree(instantiator,child,childPath,state)}}),{flat:true})};fluid.assessTreeConstruction=function(that,shadow){var instantiator=fluid.globalInstantiator;var thatStack=instantiator.getThatStack(that);var unstableUp=fluid.find_if(thatStack,(function(that){return that.lifecycleStatus==="constructing"}));if(unstableUp){that.lifecycleStatus="constructed"}else{fluid.markSubtree(instantiator,that,shadow.path,"treeConstructed")}};fluid.concludeComponentObservation=function(shadow){var that=shadow.that;var mergeOptions=shadow.mergeOptions;fluid.pushActivity("concludeComponentObservation","constructing component of type %componentName at path %path",{componentName:that.typeName,path:shadow.path});mergeOptions.evaluateFully=true;for(var i=0;i<mergeOptions.mergeBlocks.length;++i){mergeOptions.mergeBlocks[i].initter()}mergeOptions.initter();delete that.options.mergePolicy;shadow.memberStrategy.initter();shadow.invokerStrategy.initter();fluid.freezeRecursive(that.options);fluid.each(shadow.lightMergeComponents,(function(lightMerge,key){if(lightMerge.createOnEvent){fluid.bindDeferredComponent(that,key,lightMerge)}}));fluid.each(shadow.lightMergeDynamicComponents,(function(lightMerge,key){if(lightMerge.createOnEvent){fluid.bindDeferredComponent(that,key,lightMerge,true)}}));fluid.popActivity()};fluid.concludeComponentInit=function(shadow){var that=shadow.that;if(fluid.isDestroyed(that)){return}that.lifecycleStatus="constructed";fluid.assessTreeConstruction(that,shadow);that.events.onCreate.fire(that);fluid.popActivity();return that};fluid.pushCreatePotentia=function(potentiaList,path,topush){var existing=potentiaList.pathToPotentia[path];if(existing&&!existing.applied){fluid.lightMergeRecords.pushRecords(existing,topush.records||topush.lightMerge.toMerge)}else{potentiaList.pathToPotentia[path]=topush;if(topush.records){topush.lightMerge=fluid.lightMergeRecords(topush.records);delete topush.records}return topush}};fluid.blankPotentiaList=function(){return{destroys:[],creates:[],activeCount:0,pathToPotentia:{}}};fluid.isInjectedComponentRecord=function(record){return typeof record==="string"||fluid.isPlainObject(record,true)&&record.expander};fluid.lightMergeValue=function(records,member){var value;records.forEach((function(record){var recValue=record[member];value=recValue===undefined?value:recValue}));return value};fluid.lightMergeRecords=function(records){var togo={toMerge:[],isInjected:false};fluid.lightMergeRecords.pushRecords(togo,records);return togo};fluid.lightMergeRecords.pushRecord=function(lightMerge,record){if(fluid.isInjectedComponentRecord(record)){lightMerge.toMerge=[{injected:record}];lightMerge.isInjected=true}else{lightMerge.type=record.type||lightMerge.type;lightMerge.createOnEvent=record.createOnEvent||lightMerge.createOnEvent;lightMerge.source=record.source||lightMerge.source;lightMerge.sources=record.sources||lightMerge.sources;if(lightMerge.isInjected){lightMerge.toMerge=[record]}else{lightMerge.toMerge.push(record)}lightMerge.isInjected=false}};fluid.lightMergeRecords.pushRecords=function(lightMerge,records){records.forEach((function(record){fluid.lightMergeRecords.pushRecord(lightMerge,record)}))};fluid.instantiateEvents=function(shadow){var that=shadow.that;shadow.eventStrategyBlock.initter();var listeners=fluid.getForComponent(that,["options","listeners"]);fluid.mergeListeners(that,that.events,listeners);var errors=fluid.validateListenersImplemented(that);if(errors.length>0){fluid.fail(fluid.transform(errors,(function(error){return["Error constructing component "+fluid.dumpComponentAndPath(that)+" - the listener for event "+error.name+" with namespace "+error.namespace+((error.componentSource?" which was defined in grade "+error.componentSource:"")+" needs to be overridden with a concrete implementation")]}))).join("\n")}};fluid.initComponentShell=function(potentia,lightMerge){var instantiator=fluid.globalInstantiator,upDefaults=fluid.defaults(lightMerge.type),parentThat=potentia.parentThat,memberName=potentia.memberName,fakeThat={};var distributions=fluid.receiveDistributions(parentThat,upDefaults&&upDefaults.gradeNames,memberName,fakeThat);fluid.each(distributions,(function(distribution){fluid.computeDistributionPriority(parentThat,distribution);if(fluid.isPrimitive(distribution.priority)){distribution.priority=fluid.parsePriority(distribution.priority,0,false,"options distribution")}}));fluid.sortByPriority(distributions);fluid.lightMergeRecords.pushRecords(lightMerge,distributions);upDefaults=fluid.defaults(lightMerge.type);var defaultCopy=fluid.copy(upDefaults);lightMerge.toMerge.unshift({options:defaultCopy,recordType:"defaults"});var that=lightMerge.type==="fluid.emptySubcomponent"?null:fluid.typeTag(lightMerge.type,potentia.componentId);if(that){that.lifecycleStatus="constructing";instantiator.recordKnownComponent(parentThat,that,memberName,true);var mergeOptions=fluid.mergeComponentOptions(that,potentia,lightMerge);mergeOptions.exceptions={members:{model:true,modelRelay:true}};that.events={}}return that};fluid.registerConcreteSubPotentia=function(lightMerge,key,componentDepth,parentShell,localRecord,transactionId){componentDepth=componentDepth||0;var newSegs=fluid.pathForComponent(parentShell).concat([key]);var existing=parentShell[key];if(existing){fluid.registerPotentia({segs:newSegs,type:"destroy"},transactionId)}lightMerge.toMerge=fluid.transform(lightMerge.toMerge,(function(toMerge){var record=$.extend({componentDepth:componentDepth+1,sourceComponentId:parentShell.id,recordType:"subcomponentRecord"},toMerge);return record}));lightMerge.type=fluid.expandImmediate(lightMerge.type,parentShell,localRecord);var subPotentia={type:"create",segs:newSegs,lightMerge:lightMerge,localRecord:localRecord};fluid.registerPotentia(subPotentia,transactionId)};fluid.lightMergeComponentRecord=function(shadow,shadowKey,key,mergingArray){var lightMerge=fluid.lightMergeRecords(mergingArray);fluid.set(shadow,[shadowKey,key],lightMerge);return lightMerge};fluid.componentRecordExpected=fluid.arrayToHash(["type","options","container","createOnEvent"]);fluid.dynamicComponentRecordExpected=$.extend({},fluid.componentRecordExpected,fluid.arrayToHash(["source","sources"]));fluid.checkComponentRecord=function(localRecord,expected){if(!fluid.isInjectedComponentRecord(localRecord)){if(fluid.isPlainObject(localRecord,true)){fluid.each(localRecord,(function(value,key){if(!expected[key]){fluid.fail("Error in subcomponent record "+JSON.stringify(localRecord)+' - key "'+key+'" found, where the only legal options are '+fluid.keys(expected).join(", "))}}))}else{fluid.fail("Error in subcomponent record "+JSON.stringify(localRecord)+' - this should either be an object with member "type" or else a reference to another component')}}};fluid.checkSubcomponentRecords=function(subcomponentRecords,expected){subcomponentRecords.forEach((function(oneRecord){fluid.checkComponentRecord(oneRecord,expected)}))};fluid.registerSourcedDynamicComponent=function(potentia,shell,source,sourceKey,lightMerge,key,localRecordContributor){var localRecord=$.extend({},potentia.localRecord,{source:source,sourcePath:sourceKey});(localRecordContributor||fluid.identity)(localRecord,source,sourceKey);var dynamicKey=fluid.computeDynamicComponentKey(key,sourceKey);var freshLightMerge=fluid.copy(lightMerge);fluid.registerConcreteSubPotentia(freshLightMerge,dynamicKey,potentia.componentDepth,shell,localRecord)};fluid.registerSourcedDynamicComponents=function(potentia,shell,sources,lightMerge,key,localRecordContributor){fluid.each(sources,(function(source,sourceKey){fluid.registerSourcedDynamicComponent(potentia,shell,source,sourceKey,lightMerge,key,localRecordContributor)}))};fluid.lensedComponentModelListener=function(that,key,segs,value,isBoolean){var isEmptyValue=function(value){return isBoolean?!value:value===undefined};var shadow=fluid.shadowForComponent(that);var sourceKey=isBoolean?0:fluid.peek(segs);var expectedMemberName=fluid.computeDynamicComponentKey(key,sourceKey);var currentComponent=that[expectedMemberName];if(!isEmptyValue(value)&&!currentComponent){var lightMerge=shadow.lightMergeDynamicComponents[key];var parentRecord=shadow.modelSourcedDynamicComponents[key];fluid.registerSourcedDynamicComponent(shadow.potentia,that,value,sourceKey,lightMerge,key,parentRecord.localRecordContributor)}else if(isEmptyValue(value)&&currentComponent){currentComponent.destroy()}};fluid.lensedComponentDefToBlock=function(key,sourcesParsed,isBoolean){var fromModelPath=sourcesParsed.segs.slice(1);var modelListener={path:{context:sourcesParsed.context,segs:fromModelPath.concat(isBoolean?[]:["*"])},excludeSource:"init",transactional:true,funcName:"fluid.lensedComponentModelListener",args:["{that}",key,"{change}.path","{change}.value",isBoolean]};var modelListeners={};modelListeners["lensedComponents-"+key]=modelListener;return{modelListeners:modelListeners}};fluid.addLensedComponentBlocks=function(lensedComponentBlocks,potentia,shadow){var merged=fluid.extend.apply(null,[true,{}].concat(lensedComponentBlocks));shadow.mergeOptions.mergeBlocks.push(fluid.generateExpandBlock({options:merged,recordType:"lensedComponents",priority:fluid.mergeRecordTypes.lensedComponents},shadow.that,shadow.mergePolicy,potentia.localRecord));shadow.mergeOptions.updateBlocks()};fluid.pushMarkupSourcedDynamicComponentListener=function(shell,key,sourcesParsed,registerDynamicComponents){var namespace=shell.id+"-markupDynamicComponents-"+key;var context=fluid.resolveContext(sourcesParsed.context,shell);if(context.events.onDomBind){context.events.onDomBind.addListener(registerDynamicComponents,namespace)}else{var targetShadow=fluid.shadowForComponent(context);fluid.addLensedComponentBlocks([{listeners:{onDomBind:{namespace:namespace,listener:registerDynamicComponents}}}],{},targetShadow)}};fluid.expectExactlyOne=function(failStart,target,members){var found=0;members.forEach((function(member){if(target[member]!==undefined){++found}}));if(found!==1){fluid.fail.apply(null,failStart.concat([" must contain exactly one member out of "+members.join(", ")]))}};fluid.registerSourcedDynamicComponentsTriage=function(potentia,shell,sourceOrSources,lightMerge,key,isBoolean,localRecordContributor){if(isBoolean&&sourceOrSources){fluid.registerSourcedDynamicComponent(potentia,shell,sourceOrSources,0,lightMerge,key,localRecordContributor)}else{fluid.registerSourcedDynamicComponents(potentia,shell,sourceOrSources,lightMerge,key,localRecordContributor)}};fluid.processComponentShell=function(potentia,shell,transRec){var instantiator=fluid.globalInstantiator;var shadow=instantiator.idToShadow[shell.id];shadow.potentia=potentia;shadow.createdTransactionId=transRec.transactionId;var mergeOptions=shadow.mergeOptions;var components=fluid.driveStrategy(shell.options,"components",mergeOptions.strategy);fluid.each(components,(function(subcomponentRecords,key){fluid.checkSubcomponentRecords(subcomponentRecords,fluid.componentRecordExpected);var lightMerge=fluid.lightMergeComponentRecord(shadow,"lightMergeComponents",key,subcomponentRecords);if(!lightMerge.createOnEvent){fluid.registerConcreteSubPotentia(lightMerge,key,potentia.componentDepth,shell,potentia.localRecord)}}));var dynamicComponents=fluid.driveStrategy(shell.options,"dynamicComponents",mergeOptions.strategy);var lensedComponentBlocks=[];fluid.each(dynamicComponents,(function(subcomponentRecords,key){fluid.checkSubcomponentRecords(subcomponentRecords,fluid.dynamicComponentRecordExpected);var lightMerge=fluid.lightMergeComponentRecord(shadow,"lightMergeDynamicComponents",key,subcomponentRecords);fluid.expectExactlyOne(["dynamicComponents records ",subcomponentRecords],lightMerge,["source","sources","createOnEvent"]);if(lightMerge.sources!==undefined||lightMerge.source!==undefined){var recordSources=lightMerge.sources,isBoolean=false;if(lightMerge.source!==undefined){recordSources=lightMerge.source;isBoolean=true}if(fluid.isIoCReference(recordSources)){var sourcesParsed=fluid.parseValidModelReference(shell,"dynamicComponents source",recordSources,true);var registerDynamicComponents=function(){var sources=fluid.getForComponent(sourcesParsed.that,sourcesParsed.segs);fluid.registerSourcedDynamicComponentsTriage(potentia,shell,sources,lightMerge,key,null,isBoolean)};if(sourcesParsed.nonModel){if(sourcesParsed.segs[0]==="dom"){fluid.pushMarkupSourcedDynamicComponentListener(shell,key,sourcesParsed,registerDynamicComponents)}else{registerDynamicComponents()}}else{fluid.set(shadow,["modelSourcedDynamicComponents",key],{sourcesParsed:sourcesParsed,isBoolean:isBoolean});lensedComponentBlocks.push(fluid.lensedComponentDefToBlock(key,sourcesParsed,isBoolean))}}else{var sources=fluid.expandImmediate(recordSources,shell,potentia.localRecord);fluid.registerSourcedDynamicComponentsTriage(potentia,shell,sources,lightMerge,key,null,isBoolean)}}}));if(lensedComponentBlocks.length){fluid.addLensedComponentBlocks(lensedComponentBlocks,potentia,shadow)}if(transRec.deferredDistributions.length){transRec.pendingPotentiae.creates.push({type:"distributeOptions",distributions:transRec.deferredDistributions});++transRec.pendingPotentiae.activeCount;transRec.deferredDistributions=[]}};fluid.preparePathedPotentia=function(potentia,instantiator){var segs=potentia.segs||instantiator.parseToSegments(potentia.path);potentia.segs=segs;potentia.memberName=fluid.peek(segs);potentia.parentThat=fluid.getImmediate(fluid.rootComponent,segs.slice(0,-1));if(potentia.type==="create"&&!potentia.parentThat){fluid.fail("Cannot construct component at path ",segs," whose parent does not exist")}};fluid.fetchNestedInjectedComponentReference=function(transRec,potentiaList,injected,head,parentPath,segs){var instantiator=fluid.globalInstantiator;var path=parentPath,current=head;for(var i=0;i<segs.length;++i){path=fluid.composePath(path,segs[i]);current=instantiator.pathToComponent[path];if(!current){var upcoming=potentiaList.pathToPotentia[path];if(upcoming){if(upcoming.applied){fluid.fail("Circular reference found when resolving injected component reference ",injected," - the target of the reference is still in construction")}else{current=fluid.operateCreatePotentia(transRec,upcoming);if(current){path=instantiator.idToShadow[current.id].path}}}}if(!current&&i!==segs.length-1){fluid.fail("Failed to resolved injected component reference ",injected," - component at segment "+segs[i]+" was not found")}}return current};fluid.fetchInjectedComponentReference=function(transRec,potentiaList,injected,parentThat){var instantiator=fluid.globalInstantiator;if(injected.expander){return fluid.expandImmediate(injected,parentThat,null,true)}else{var parsed=fluid.parseContextReference(injected);var head=fluid.resolveContext(parsed.context,parentThat);if(!head){if(parsed.path!==""){fluid.fail("Error in injected component reference ",injected," - could not resolve context {"+parsed.context+"} to a head component")}else{return head}}else{var parentPath=instantiator.idToShadow[head.id].path;var segs=fluid.model.parseEL(parsed.path);return fluid.fetchNestedInjectedComponentReference(transRec,potentiaList,injected,head,parentPath,segs)}}};fluid.operateCreatePotentia=function(transRec,potentia){var instantiator=fluid.globalInstantiator;var potentiaList=transRec.pendingPotentiae;fluid.preparePathedPotentia(potentia,instantiator);var memberName=potentia.memberName,parentThat=potentia.parentThat,shell;fluid.pushActivity("operateCreatePotentia",'operating create potentia for path "%path" with records %records',{path:potentia.path,records:potentia.records});potentia.applied=true;--potentiaList.activeCount;var lightMerge=potentia.lightMerge;if(lightMerge.isInjected){parentThat[memberName]=fluid.inEvaluationMarker;shell=fluid.fetchInjectedComponentReference(transRec,potentiaList,lightMerge.toMerge[0].injected,parentThat);if(shell){instantiator.recordKnownComponent(parentThat,shell,memberName,false)}else{delete parentThat[memberName]}}else if(lightMerge.type){shell=fluid.initComponentShell(potentia,lightMerge);if(shell){fluid.processComponentShell(potentia,shell,transRec);var shadow=instantiator.idToShadow[shell.id];transRec.outputShadows.push(shadow)}}else{fluid.fail("Unrecognised material in place of subcomponent "+memberName+" - could not recognise the records ",potentia.records," as designating either an injected or concrete component")}fluid.pushPotentia(transRec.restoreRecords,instantiator,{type:"destroy",segs:potentia.segs});fluid.popActivity();return shell};fluid.operateDestroyPotentia=function(transRec,potentia,instantiator){instantiator=instantiator||fluid.globalInstantiator;fluid.preparePathedPotentia(potentia,instantiator);var that=fluid.getImmediate(fluid.rootComponent,potentia.segs);if(that){instantiator.clearComponent(potentia.parentThat,potentia.memberName,that)}};fluid.lookupWorkflowStage=function(workflowName){if(!workflowName){return fluid.workflowCacheSorted.length}else if(workflowName==="shells"){return 0}else{var found=fluid.find_if(fluid.workflowCacheSorted,(function(workflowEntry){return workflowEntry.workflowName===workflowName}));if(found){return found.index+1}else{fluid.fail("Unknown workflow name "+workflowName+' supplied as "breakAt" for tree transaction: '+": valid names are "+fluid.getMembers(fluid.workflowCacheSorted,"workflowName").join(", "))}}};fluid.evaluateWorkflows=function(shadows,workflowType){var togo=[];fluid.workflowCacheSorted[workflowType].forEach((function(workflowRecord){var workflowShadows=shadows.filter((function(oneShadow){return fluid.componentHasGrade(oneShadow.that,workflowRecord.gradeName)}));if(workflowShadows.length>0){togo.push({shadows:shadows,workflowIndex:workflowRecord.index,workflowOptions:workflowRecord.workflowOptions})}}));return togo};fluid.findWorkflowShadows=function(shadows,blockStart,blockEnd,workflowRecord){var workflowShadows=[];for(var i=blockStart;i<blockEnd;++i){if(fluid.componentHasGrade(shadows[i].that,workflowRecord.gradeName)){if(workflowRecord.workflowType==="global"){workflowShadows.push(shadows[i])}else{workflowShadows.unshift(shadows[i])}}}return workflowShadows};fluid.waitPendingIOTask=function(transRec){var sequence;var waitIOTask=function(){return transRec.pendingIO.length?sequence=fluid.promise.sequence(transRec.pendingIO):null};waitIOTask.taskName="waitIO";waitIOTask.sequence=sequence;return waitIOTask};fluid.enqueueWorkflowBlock=function(transRec,shadows,workflowStart,workflowEnd,blockStart,blockEnd,sequencer){var workQueued=false;var instantiator=fluid.globalInstantiator;var resumeCurrentTransaction=function(){instantiator.currentTreeTransactionId=transRec.transactionId};transRec.lastWorkflowShadow=Math.max(transRec.lastWorkflowShadow,blockEnd);fluid.forEachInRange(fluid.workflowCacheSorted,workflowStart,workflowEnd,(function(workflowRecord,workflowIndex){if(workflowIndex===0){for(var i=blockStart;i<blockEnd;++i){fluid.instantiateEvents(shadows[i])}}var workflowShadows=fluid.findWorkflowShadows(shadows,blockStart,blockEnd,workflowRecord);transRec.maximumWorkflowStage=Math.max(transRec.maximumWorkflowStage,workflowIndex+1);if(workflowShadows.length>0){var workflow=workflowRecord.workflowOptions;var workflowFunc=fluid.getGlobalValue(workflow.funcName);var sequence=sequencer.sources;if(workflow.waitIO){sequence.push(fluid.waitPendingIOTask(transRec))}if(workflowRecord.workflowType==="global"){var globalWorkflowTask=function(){resumeCurrentTransaction();workflowFunc(workflowShadows,transRec)};globalWorkflowTask.taskName=workflowRecord.namespace;sequence.push(globalWorkflowTask)}else{var localWorkflowTask=function(){resumeCurrentTransaction();if(workflowRecord.namespace==="concludeComponentInit"){sequencer.hasStartedConcludeInit=true}workflowShadows.forEach((function(shadow){workflowFunc(shadow,transRec)}))};localWorkflowTask.taskName=workflowRecord.namespace;sequence.push(localWorkflowTask)}workQueued=true}}));if(transRec.maximumWorkflowStage===transRec.workflowStageBreak){transRec.maximumWorkflowStage=0;transRec.restartLastWorkflowShadow=transRec.lastWorkflowShadow}return workQueued};fluid.applyWorkflowPhase=function(transRec,sequencer){var shadows=transRec.outputShadows;if(shadows.length>transRec.lastWorkflowShadow&&transRec.maximumWorkflowStage>0){fluid.enqueueWorkflowBlock(transRec,shadows,0,transRec.maximumWorkflowStage,transRec.lastWorkflowShadow,shadows.length,sequencer);return true}else if(transRec.maximumWorkflowStage<transRec.workflowStageBreak){for(var workflowStage=transRec.maximumWorkflowStage;workflowStage<transRec.workflowStageBreak;++workflowStage){var workQueued=fluid.enqueueWorkflowBlock(transRec,shadows,workflowStage,workflowStage+1,transRec.restartLastWorkflowShadow,shadows.length,sequencer);if(workQueued){return workQueued}}}return false};fluid.commitPotentiaePhase=function(transRec){var pendingPotentiae=transRec.pendingPotentiae;pendingPotentiae.destroys.forEach((function(potentia){if(!potentia.applied){potentia.applied=true;--pendingPotentiae.activeCount;fluid.operateDestroyPotentia(transRec,potentia)}}));for(var i=0;i<pendingPotentiae.creates.length;++i){var potentia=pendingPotentiae.creates[i];if(!potentia.applied){if(potentia.type==="create"){fluid.operateCreatePotentia(transRec,potentia)}else if(potentia.type==="distributeOptions"){potentia.distributions.forEach((function(distro){fluid.distributeOptionsOne(distro.that,distro.record,distro.targetRef,distro.selector,distro.context)}));potentia.applied=true;--pendingPotentiae.activeCount}else{fluid.fail("Unrecognised potentia type "+potentia.type)}}}};fluid.isPopulatedPotentiaList=function(potentiaList){return potentiaList.activeCount>0};fluid.commitPotentiae=function(transactionId,resumeSequencer){var instantiator=fluid.globalInstantiator;var transRec=instantiator.treeTransactions[transactionId];++transRec.commitDepth;var lastWorkflowShadow=transRec.lastWorkflowShadow;var rootSequencer=transRec.rootSequencer;var sequencer=resumeSequencer;if(!sequencer){var topSequencer=fluid.getImmediate(fluid.peek(rootSequencer.sources),["sequencer"]);if(!topSequencer||topSequencer.hasStartedConcludeInit||topSequencer.promise.disposition){sequencer=fluid.promise.makeSequencer([],{},fluid.promise.makeSequenceStrategy());sequencer.promise.sequencer=sequencer;rootSequencer.sources.push(sequencer.promise)}else{sequencer=topSequencer}}fluid.tryCatch((function commitPotentiae(){if(fluid.isPopulatedPotentiaList(transRec.pendingPotentiae)){fluid.commitPotentiaePhase(transRec)}var workflowEnqueued=fluid.applyWorkflowPhase(transRec,sequencer);if(workflowEnqueued){sequencer.sources.push((function(){if(!sequencer.hasStartedConcludeInit){fluid.commitPotentiae(transactionId,sequencer)}else if(sequencer===fluid.peek(rootSequencer.sources).sequencer){fluid.commitPotentiae(transactionId,null)}}))}if(!sequencer.sequenceStarted){fluid.promise.resumeSequence(sequencer)}if(!rootSequencer.sequenceStarted){fluid.promise.resumeSequence(rootSequencer)}}),(function(e){if(!transRec.promise.disposition){transRec.promise.reject(e)}}));--transRec.commitDepth;if(transRec.commitDepth===0&&!resumeSequencer){instantiator.currentTreeTransactionId=null}return transRec.outputShadows[lastWorkflowShadow]};fluid.pushPotentia=function(potentiaList,instantiator,potentia){var segs=potentia.segs=potentia.segs||instantiator.parseToSegments(potentia.path);var path=potentia.path=instantiator.composeSegments.apply(null,segs);if(potentia.type==="destroy"){potentiaList.destroys.push(potentia);potentiaList.activeCount++;fluid.remove_if(potentiaList.creates,(function(create){if(!create.applied&&create.path.startsWith(potentia.path)){potentiaList.activeCount--;return true}}))}else{var newPotentia=potentia;if(potentia.type==="create"){newPotentia=fluid.pushCreatePotentia(potentiaList,path,potentia)}if(newPotentia){potentiaList.creates.push(potentia);potentiaList.activeCount++}}};fluid.pathForComponent=function(component,instantiator){instantiator=instantiator||fluid.getInstantiator(component)||fluid.globalInstantiator;var shadow=instantiator.idToShadow[component.id];if(!shadow){return null}return instantiator.parseEL(shadow.path)};fluid.currentTreeTransaction=function(){var instantiator=fluid.globalInstantiator;return instantiator.treeTransactions[instantiator.currentTreeTransactionId]};fluid.clearTreeTransaction=function(transRec){transRec.rootSequencer=fluid.promise.makeSequencer([],{},fluid.promise.makeSequenceStrategy());transRec.restoreRecords=fluid.blankPotentiaList();transRec.initModelTransaction={};transRec.outputShadows=[];transRec.lastWorkflowShadow=0;transRec.maximumWorkflowStage=0;transRec.restartLastWorkflowShadow=0;transRec.deferredDistributions=[]};fluid.beginTreeTransaction=function(transactionOptions){var instantiator=fluid.globalInstantiator;if(instantiator.currentTreeTransactionId){fluid.fail("Attempt to start new tree transaction when transaction "+instantiator.currentTreeTransactionId+" is already active")}var transactionId=instantiator.currentTreeTransactionId=fluid.allocateGuid();var transRec=$.extend({transactionId:transactionId,workflowStageBreak:undefined,pendingPotentiae:fluid.blankPotentiaList(),commitDepth:0,cancelled:false,cancellationError:null,pendingIO:[]},transactionOptions);fluid.clearTreeTransaction(transRec);transRec.promise=transRec.rootSequencer.promise;var onConclude=function(){instantiator.events.onEndTreeTransaction.fire(transRec);if(transRec.rootSequencer.promise.disposition){instantiator.currentTreeTransactionId=null;delete instantiator.treeTransactions[transactionId]}};var onException=function(err){if(!transRec.cancelled){delete transRec.rootSequencer;instantiator.inEvaluationPaths.length=0;fluid.cancelTreeTransaction(transactionId,instantiator,err);onConclude()}};transRec.promise.then(onConclude,onException);instantiator.treeTransactions[transactionId]=transRec;try{transRec.workflowStageBreak=fluid.lookupWorkflowStage(transRec.breakAt)}catch(e){transRec.promise.reject(e)}instantiator.events.onBeginTreeTransaction.fire(transRec);return transRec};fluid.registerPotentia=function(potentia,transactionId){var instantiator=fluid.globalInstantiator;transactionId=transactionId||instantiator.currentTreeTransactionId;if(!transactionId){transactionId=fluid.beginTreeTransaction().transactionId}var transRec=instantiator.treeTransactions[transactionId];fluid.pushPotentia(transRec.pendingPotentiae,instantiator,potentia);return transRec};fluid.cancelTreeTransaction=function(transactionId,instantiator){var transRec=instantiator.treeTransactions[transactionId];if(transRec){try{transRec.pendingPotentiae=transRec.restoreRecords;transRec.cancelled=true;fluid.clearTreeTransaction(transRec);fluid.commitPotentiae(transactionId)}catch(e){fluid.log(fluid.logLevel.FAIL,"Fatal error cancelling transaction "+transactionId+": destroying all affected paths");transRec.restoreRecords.creates.forEach((function(potentia){instantiator.clearComponent(potentia.parentThat,potentia.memberName,potentia.parentThat[potentia.memberName])}));throw e}}};fluid.constructChild=function(parent,memberName,options){var parentPath=fluid.pathForComponent(parent);var path=parentPath.concat([memberName]);return fluid.construct(path,options)};fluid.construct=function(path,componentOptions,constructOptions){constructOptions=constructOptions||{};var transRec=fluid.registerPotentia({path:path,type:"destroy"},constructOptions.transactionId);var record={recordType:"user"};fluid.each(fluid.componentRecordExpected,(function(troo,key){if(componentOptions[key]!==undefined){record[key]=componentOptions[key]}}));record.options=componentOptions;var potentia={path:path,type:"create",localRecord:constructOptions.localRecord,records:[record]};fluid.registerPotentia(potentia,transRec.transactionId);if(!constructOptions.transactionId){fluid.commitPotentiae(transRec.transactionId)}fluid.adaptTransactionFailure(transRec);return constructOptions.returnTransaction?transRec:fluid.getImmediate(fluid.rootComponent,potentia.segs)};fluid.destroy=function(path,instantiator){instantiator=instantiator||fluid.globalInstantiator;var segs=instantiator.parseToSegments(path);if(segs.length===0){fluid.fail("Cannot destroy the root component")}var transRec=fluid.registerPotentia({path:path,type:"destroy"});fluid.commitPotentiae(transRec.transactionId);return transRec};fluid.constructSingle=function(parentPath,options,instantiator){instantiator=instantiator||fluid.globalInstantiator;parentPath=parentPath||"";var segs=fluid.model.parseToSegments(parentPath,instantiator.parseEL,true);if(typeof options==="string"){options={type:options}}var type=options.type;if(!type){fluid.fail("Cannot construct singleton object without a type entry")}options=$.extend({},options);var gradeNames=options.gradeNames=fluid.makeArray(options.gradeNames);gradeNames.unshift(type);options.type="fluid.component";var root=segs.length===0;if(root){gradeNames.push("fluid.resolveRoot")}var memberName=fluid.typeNameToMemberName(options.singleRootType||type);segs.push(memberName);return fluid.construct(segs,options)};fluid.destroySingle=function(parentPath,typeName,instantiator){instantiator=instantiator||fluid.globalInstantiator;var segs=fluid.model.parseToSegments(parentPath,instantiator.parseEL,true);var memberName=fluid.typeNameToMemberName(typeName);segs.push(memberName);fluid.destroy(segs,instantiator)};fluid.makeGradeLinkage=function(linkageName,inputNames,outputNames){fluid.defaults(linkageName,{gradeNames:"fluid.component",distributeOptions:{record:outputNames,target:"{/ "+inputNames.join("&")+"}.options.gradeNames"}});fluid.constructSingle([],linkageName)};fluid.componentForPath=function(path){return fluid.globalInstantiator.pathToComponent[fluid.isArrayable(path)?path.join("."):path]};fluid.thisistToApplicable=function(record,recthis,that){return{apply:function(noThis,args){var resolvedThis=fluid.expandImmediate(recthis,that);if(typeof resolvedThis==="string"){resolvedThis=fluid.getGlobalValue(resolvedThis)}if(!resolvedThis){fluid.fail("Could not resolve reference "+recthis+" to a value")}var resolvedFunc=resolvedThis[record.method];if(typeof resolvedFunc!=="function"){fluid.fail("Object ",resolvedThis," at reference "+recthis+" has no member named "+record.method+" which is a function ")}if(fluid.passLogLevel(fluid.logLevel.TRACE)){fluid.log(fluid.logLevel.TRACE,"Applying arguments ",args," to method "+record.method+" of instance ",resolvedThis)}return resolvedFunc.apply(resolvedThis,args)}}};fluid.changeToApplicable=function(record,that){fluid.getForComponent(that,"applier");var parsed=fluid.parseValidModelReference(that,"changePath listener record",record.changePath);fluid.materialiseModelPath(parsed.that,parsed.modelSegs);return{apply:function(noThis,args,localRecord,mergeRecord){var value;if(record.func||record.funcName){var invoker=fluid.makeInvoker(that,fluid.filterKeys(record,["func","funcName","args"]),"changePath listener record",localRecord);value=invoker()}else{value=fluid.expandImmediate(record.value,that,fluid.extend(localRecord,{arguments:args}))}var sources=mergeRecord&&mergeRecord.source&&mergeRecord.source.length?fluid.makeArray(record.source).concat(mergeRecord.source):record.source;parsed.applier.change(parsed.modelSegs,value,record.type,sources)}}};fluid.recordToApplicable=function(record,that,standard){if(record.changePath!==undefined){return fluid.changeToApplicable(record,that,standard)}var recthis=record["this"];if(record.method^recthis){fluid.fail("Record ",that,' must contain both entries "method" and "this" if it contains either')}return record.method?fluid.thisistToApplicable(record,recthis,that):null};fluid.getGlobalValueNonComponent=function(funcName,context){var defaults=fluid.defaults(funcName);if(defaults&&fluid.hasGrade(defaults,"fluid.component")){fluid.fail("Error in function specification - cannot invoke function "+funcName+" in the context of "+context+": component creator functions can only be used as subcomponents")}return fluid.getGlobalValue(funcName)};fluid.makeInvoker=function(that,invokerec,name,localRecord){invokerec=fluid.upgradePrimitiveFunc(invokerec);if(invokerec.args!==undefined&&invokerec.args!==fluid.NO_ARGUMENTS&&!fluid.isArrayable(invokerec.args)){invokerec.args=fluid.makeArray(invokerec.args)}var func=fluid.recordToApplicable(invokerec,that);var invokePre=fluid.preExpand(invokerec.args);localRecord=localRecord||{};var expandOptions=fluid.makeStackResolverOptions(that,localRecord,true);func=func||(invokerec.funcName?fluid.getGlobalValueNonComponent(invokerec.funcName,"an invoker"):fluid.expandImmediate(invokerec.func,that));if(!func||!func.apply){fluid.fail("Error in invoker record: could not resolve members func, funcName or method to a function implementation - got "+func+" from ",invokerec)}else if(func===fluid.notImplemented){fluid.fail("Error constructing component "+fluid.dumpComponentAndPath(that)+" - the invoker named "+name+" which was defined in grade "+invokerec.componentSource+" needs to be overridden with a concrete implementation")}return function invokeInvoker(){if(fluid.defeatLogging===false){fluid.pushActivity("invokeInvoker","invoking invoker with name %name and record %record holding component %that",{name:name,record:invokerec,that:that})}var togo,finalArgs;if(that.lifecycleStatus==="destroyed"){fluid.log(fluid.logLevel.WARN,"Ignoring call to invoker "+name+" of component "+fluid.dumpComponentAndPath(that)+" which has been destroyed")}else{localRecord.arguments=arguments;if(invokerec.args===undefined||invokerec.args===fluid.NO_ARGUMENTS){finalArgs=arguments}else{fluid.expandImmediateImpl(invokePre,expandOptions);finalArgs=invokePre.source}togo=func.apply(null,finalArgs)}if(fluid.defeatLogging===false){fluid.popActivity()}return togo}};fluid.event.makeTrackedListenerAdder=function(source){var shadow=fluid.shadowForComponent(source);return function(event){return{addListener:function(listener,namespace,priority,softNamespace,listenerId){fluid.recordListener(event,listener,shadow,listenerId);event.addListener.apply(null,arguments)}}}};fluid.event.listenerEngine=function(eventSpec,callback,adder){var argstruc={};function checkFire(){var notall=fluid.find(eventSpec,(function(value,key){if(argstruc[key]===undefined){return true}}));if(!notall){var oldstruc=argstruc;argstruc={};callback(oldstruc)}}fluid.each(eventSpec,(function(event,eventName){adder(event).addListener((function(){argstruc[eventName]=fluid.makeArray(arguments);checkFire()}))}))};fluid.event.dispatchListener=function(that,listener,eventName,eventSpec,wrappedArgs){if(eventSpec.args!==undefined&&eventSpec.args!==fluid.NO_ARGUMENTS&&!fluid.isArrayable(eventSpec.args)){eventSpec.args=fluid.makeArray(eventSpec.args)}listener=fluid.event.resolveListener(listener);var dispatchPre=fluid.preExpand(eventSpec.args);var localRecord={};var expandOptions=fluid.makeStackResolverOptions(that,localRecord,true);var togo=function(){if(fluid.defeatLogging===false){fluid.pushActivity("dispatchListener","firing to listener to event named %eventName of component %that",{eventName:eventName,that:that})}var args=wrappedArgs?arguments[0]:arguments,finalArgs;localRecord.arguments=args;if(eventSpec.args!==undefined&&eventSpec.args!==fluid.NO_ARGUMENTS){fluid.expandImmediateImpl(dispatchPre,expandOptions);finalArgs=dispatchPre.source}else{finalArgs=args}var togo=listener.apply(null,finalArgs);if(fluid.defeatLogging===false){fluid.popActivity()}return togo};fluid.event.impersonateListener(listener,togo);return togo};fluid.event.resolveSoftNamespace=function(key){if(typeof key!=="string"){return null}else{var lastpos=Math.max(key.lastIndexOf("."),key.lastIndexOf("}"));return key.substring(lastpos+1)}};fluid.event.resolveListenerRecord=function(lisrec,that,eventName,namespace,standard){var badRec=function(record,extra){fluid.fail("Error in listener record - could not resolve reference ",record," to a listener or firer. "+'Did you miss out "events." when referring to an event firer?'+extra)};fluid.pushActivity("resolveListenerRecord","resolving listener record for event named %eventName for component %that",{eventName:eventName,that:that});var records=fluid.makeArray(lisrec);var transRecs=fluid.transform(records,(function(record){var expanded=fluid.isPrimitive(record)||record.expander?{listener:record}:fluid.copy(record);var methodist=fluid.recordToApplicable(record,that,standard);if(methodist){expanded.listener=methodist}else{expanded.listener=expanded.listener||expanded.func||expanded.funcName}if(!expanded.listener){badRec(record,' Listener record must contain a member named "listener", "func", "funcName" or "method"')}var softNamespace=record.method?fluid.event.resolveSoftNamespace(record["this"])+"."+record.method:fluid.event.resolveSoftNamespace(expanded.listener);if(!expanded.namespace&&!namespace&&softNamespace){expanded.softNamespace=true;expanded.namespace=(record.componentSource?record.componentSource:that.typeName)+"."+softNamespace}var listener=expanded.listener=fluid.expandOptions(expanded.listener,that);if(!listener){badRec(record,"")}var firer=false;if(listener.typeName==="fluid.event.firer"){listener=listener.fire;firer=true}expanded.listener=standard&&(expanded.args&&listener!=="fluid.notImplemented"||firer)?fluid.event.dispatchListener(that,listener,eventName,expanded):listener;expanded.listenerId=fluid.allocateGuid();return expanded}));var togo={records:transRecs,adderWrapper:standard?fluid.event.makeTrackedListenerAdder(that):null};fluid.popActivity();return togo};fluid.event.expandOneEvent=function(that,event){var origin;if(typeof event==="string"&&event.charAt(0)!=="{"){origin=fluid.getForComponent(that,["events",event])}else{origin=fluid.expandOptions(event,that)}if(!origin||origin.typeName!=="fluid.event.firer"){fluid.fail("Error in event specification - could not resolve base event reference ",event," to an event firer: got ",origin)}return origin};fluid.event.expandEvents=function(that,event){return typeof event==="string"?fluid.event.expandOneEvent(that,event):fluid.transform(event,(function(oneEvent){return fluid.event.expandOneEvent(that,oneEvent)}))};fluid.event.resolveEvent=function(that,eventName,eventSpec){fluid.pushActivity("resolveEvent","resolving event with name %eventName attached to component %that",{eventName:eventName,that:that});var adder=fluid.event.makeTrackedListenerAdder(that);if(typeof eventSpec==="string"){eventSpec={event:eventSpec}}var event=eventSpec.typeName==="fluid.event.firer"?eventSpec:eventSpec.event||eventSpec.events;if(!event){fluid.fail("Event specification for event with name "+eventName+" does not include a base event specification: ",eventSpec)}var origin=event.typeName==="fluid.event.firer"?event:fluid.event.expandEvents(that,event);var isMultiple=origin.typeName!=="fluid.event.firer";var isComposite=eventSpec.args||isMultiple;var firer;if(isComposite){firer=fluid.makeEventFirer({name:" [composite] "+fluid.event.nameEvent(that,eventName)});var dispatcher=fluid.event.dispatchListener(that,firer.fire,eventName,eventSpec,isMultiple);if(isMultiple){fluid.event.listenerEngine(origin,dispatcher,adder)}else{adder(origin).addListener(dispatcher)}}else{firer={typeName:"fluid.event.firer"};firer.fire=function(){var outerArgs=fluid.makeArray(arguments);fluid.pushActivity("fireSynthetic","firing synthetic event %eventName ",{eventName:eventName});var togo=origin.fire.apply(null,outerArgs);fluid.popActivity();return togo};firer.addListener=function(listener,namespace,priority,softNamespace,listenerId){var dispatcher=fluid.event.dispatchListener(that,listener,eventName,eventSpec);adder(origin).addListener(dispatcher,namespace,priority,softNamespace,listenerId)};firer.removeListener=function(listener){origin.removeListener(listener)};firer.originEvent=origin}fluid.popActivity();return firer};fluid.coerceToPrimitive=function(string){return string==="false"?false:string==="true"?true:isFinite(string)?Number(string):string};fluid.compactStringToRec=function(string,type){var openPos=string.indexOf("(");var closePos=string.indexOf(")");if(openPos===-1^closePos===-1||openPos>closePos){fluid.fail("Badly-formed compact "+type+" record without matching parentheses: "+string)}if(openPos!==-1&&closePos!==-1){var trail=string.substring(closePos+1);if(trail.trim()!==""){fluid.fail("Badly-formed compact "+type+" record "+string+" - unexpected material following close parenthesis: "+trail)}var prefix=string.substring(0,openPos);var body=string.substring(openPos+1,closePos).trim();var args=body===""?[]:fluid.transform(body.split(","),(function(str){return str.trim()}),fluid.coerceToPrimitive);var togo=fluid.upgradePrimitiveFunc(prefix,null);togo.args=args;return togo}else if(type==="expander"){fluid.fail("Badly-formed compact expander record without parentheses: "+string)}return string};fluid.expandPrefix="@expand:";fluid.expandCompactString=function(string,active){var rec=string;if(string.indexOf(fluid.expandPrefix)===0){var rem=string.substring(fluid.expandPrefix.length);rec={expander:fluid.compactStringToRec(rem,"expander")}}else if(active){rec=fluid.compactStringToRec(string,active)}return rec};var singularPenRecord={listeners:"listener",modelListeners:"modelListener"};var singularRecord=$.extend({invokers:"invoker"},singularPenRecord);fluid.expandCompactRec=function(segs,target,source){fluid.guardCircularExpansion(segs,segs.length);var pen=fluid.peek(segs);var active=singularRecord[pen];if(!active&&segs.length>1){active=singularPenRecord[segs[segs.length-2]]}fluid.each(source,(function(value,key){if(fluid.isPlainObject(value)){target[key]=fluid.freshContainer(value);segs.push(key);fluid.expandCompactRec(segs,target[key],value);segs.pop();return}else if(typeof value==="string"){value=fluid.expandCompactString(value,active)}target[key]=value}))};fluid.expandCompact=function(options){var togo={};fluid.expandCompactRec([],togo,options);return togo};fluid.extractEL=function(string,options){if(options.ELstyle==="ALL"||options.ELstyle==="{}"){return string}else if(options.ELstyle.length===1){if(string.charAt(0)===options.ELstyle){return string.substring(1)}}else if(options.ELstyle==="${}"){var i1=string.indexOf("${");var i2=string.lastIndexOf("}");if(i1===0&&i2!==-1){return string.substring(2,i2)}}};fluid.extractELWithContext=function(string,options){var EL=fluid.extractEL(string,options);if(fluid.isIoCReference(EL)){return fluid.parseContextReference(EL)}else if(options.ELstyle==="{}"){return null}return EL?{path:EL}:EL};fluid.parseContextReference=function(reference,index,delimiter){index=index||0;var isNested=reference.charAt(index+1)==="{",endcpos,context,nested;if(isNested){nested=fluid.parseContextReference(reference,index+1,"}");endcpos=nested.endpos}else{endcpos=reference.indexOf("}",index+1)}if(endcpos===-1){fluid.fail('Cannot parse context reference "'+reference+'": Malformed context reference without }')}if(isNested){context=nested}else{context=reference.substring(index+1,endcpos)}var endpos=delimiter?reference.indexOf(delimiter,endcpos+1):reference.length;var path=reference.substring(endcpos+1,endpos);if(path.charAt(0)==="."){path=path.substring(1)}return{context:context,path:path,endpos:endpos}};fluid.renderContextReference=function(parsed){var context=parsed.context;return"{"+(fluid.isPrimitive(context)?context:fluid.renderContextReference(context))+"}"+(parsed.path?"."+parsed.path:"")};fluid.resolveContextValue=function(string,options){function fetch(parsed){fluid.pushActivity("resolveContextValue","resolving context value %parsed",{parsed:parsed});var togo=options.fetcher(parsed);fluid.pushActivity("resolvedContextValue","resolved value %parsed to value %value",{parsed:parsed,value:togo});fluid.popActivity(2);return togo}var parsed;if(options.bareContextRefs&&fluid.isIoCReference(string)){parsed=fluid.parseContextReference(string);return fetch(parsed)}else if(options.ELstyle&&options.ELstyle!=="${}"){parsed=fluid.extractELWithContext(string,options);if(parsed){return fetch(parsed)}}if(options.ELstyle==="${}"){while(typeof string==="string"){var i1=string.indexOf("${");var i2=string.indexOf("}",i1+2);if(i1!==-1&&i2!==-1){if(string.charAt(i1+2)==="{"){parsed=fluid.parseContextReference(string,i1+2,"}");i2=parsed.endpos}else{parsed={path:string.substring(i1+2,i2)}}var subs=fetch(parsed);var all=i1===0&&i2===string.length-1;if(subs===undefined||subs===null){return subs}string=all?subs:string.substring(0,i1)+subs+string.substring(i2+1)}else{break}}}return string};fluid.fetchExpandChildren=function(target,i,segs,source,mergePolicy,options){if(source.expander){var expanded=fluid.expandExpander(target,source,options);if(fluid.isPrimitive(expanded)||!fluid.isPlainObject(expanded)||fluid.isArrayable(expanded)^fluid.isArrayable(target)){return expanded}else{$.extend(true,target,expanded)}}fluid.each(source,(function(newSource,key){if(newSource===undefined){target[key]=undefined}else if(key!=="expander"){segs[i]=key;if(fluid.getImmediate(options.exceptions,segs,i)!==true){options.strategy(target,key,i+1,segs,source,mergePolicy)}}}));return target};fluid.isUnexpandable=function(source){return fluid.isPrimitive(source)||!fluid.isPlainObject(source)};fluid.expandSource=function(options,target,i,segs,deliverer,source,policy,recurse){var expanded,isTrunk;var thisPolicy=fluid.derefMergePolicy(policy);if(typeof source==="string"&&!thisPolicy.noexpand){if(!options.defaultEL||source.charAt(0)==="{"){fluid.pushActivity("expandContextValue","expanding context value %source held at path %path",{source:source,path:fluid.path.apply(null,segs.slice(0,i))});expanded=fluid.copy(fluid.resolveContextValue(source,options));fluid.popActivity(1)}else{expanded=source}}else if(thisPolicy.noexpand||fluid.isUnexpandable(source)){expanded=fluid.copy(source)}else if(source.expander){expanded=fluid.expandExpander(deliverer,source,options)}else{expanded=fluid.freshContainer(source);isTrunk=true}if(expanded!==fluid.NO_VALUE){deliverer(expanded)}if(isTrunk){recurse(expanded,source,i,segs,policy)}return expanded};fluid.guardCircularExpansion=function(segs,i){if(i>fluid.strategyRecursionBailout){fluid.fail("Overflow/circularity in options expansion, current path is ",segs," at depth ",i,' - please ensure options are not circularly connected, or protect from expansion using the "noexpand" policy or expander')}};fluid.makeExpandStrategy=function(options){var recurse=function(target,source,i,segs,policy){return fluid.fetchExpandChildren(target,i||0,segs||[],source,policy,options)};var strategy=function(target,name,i,segs,source,policy){fluid.guardCircularExpansion(segs,i);if(!target){return}if(target.hasOwnProperty(name)){return target[name]}if(source===undefined){source=fluid.regenerateCursor(options.source,segs,i-1,options.sourceStrategy);policy=fluid.regenerateCursor(options.mergePolicy,segs,i-1,fluid.concreteTrundler)}var thisSource=options.sourceStrategy(source,name,i,segs);var thisPolicy=fluid.concreteTrundler(policy,name);function deliverer(value){target[name]=value}return fluid.expandSource(options,target,i,segs,deliverer,thisSource,thisPolicy,recurse)};options.recurse=recurse;options.strategy=strategy;return strategy};fluid.defaults("fluid.makeExpandOptions",{ELstyle:"${}",bareContextRefs:true,target:fluid.inCreationMarker});fluid.makeExpandOptions=function(source,options){options=$.extend({},fluid.rawDefaults("fluid.makeExpandOptions"),options);options.defaultEL=options.ELStyle==="${}"&&options.bareContextRefs;options.expandSource=function(source){return fluid.expandSource(options,null,0,[],fluid.identity,source,options.mergePolicy,false)};if(!fluid.isUnexpandable(source)){options.source=source;options.target=fluid.freshContainer(source);options.sourceStrategy=options.sourceStrategy||fluid.concreteTrundler;fluid.makeExpandStrategy(options);options.initter=function(){options.target=fluid.fetchExpandChildren(options.target,0,[],options.source,options.mergePolicy,options)}}else{options.strategy=fluid.concreteTrundler;options.initter=fluid.identity;if(typeof source==="string"){options.target=(options.defer?fluid.copy:fluid.identity)(options.expandSource(source))}else{options.target=source}options.immutableTarget=true}return options};fluid.expand=function(source,options){var expandOptions=fluid.makeExpandOptions(source,options);expandOptions.initter();return expandOptions.target};fluid.preExpandRecurse=function(root,source,holder,member,rootSegs){fluid.guardCircularExpansion(rootSegs,rootSegs.length);function pushExpander(expander){root.expanders.push({expander:expander,holder:holder,member:member});delete holder[member]}if(fluid.isIoCReference(source)){var parsed=fluid.parseContextReference(source);var segs=fluid.model.parseEL(parsed.path);pushExpander({typeFunc:fluid.expander.fetch,context:parsed.context,segs:segs})}else if(fluid.isPlainObject(source)){if(source.expander){source.expander.typeFunc=fluid.getGlobalValue(source.expander.type||"fluid.expander.invokeFunc");pushExpander(source.expander)}else{fluid.each(source,(function(value,key){rootSegs.push(key);fluid.preExpandRecurse(root,value,source,key,rootSegs);rootSegs.pop()}))}}};fluid.preExpand=function(source){var root={expanders:[],source:fluid.isUnexpandable(source)?source:fluid.copy(source)};fluid.preExpandRecurse(root,root.source,root,"source",[]);return root};fluid.expandImmediate=function(source,that,localRecord,noproxy){var options=fluid.makeStackResolverOptions(that,localRecord,true);options.noproxy=!!noproxy;var root=fluid.preExpand(source);fluid.expandImmediateImpl(root,options);return root.source};fluid.expandImmediateImpl=function(root,options){var expanders=root.expanders;for(var i=0;i<expanders.length;++i){var expander=expanders[i];expander.holder[expander.member]=expander.expander.typeFunc(null,expander,options)}};fluid.expandExpander=function(deliverer,source,options){var expander=fluid.getGlobalValue(source.expander.type||"fluid.expander.invokeFunc");if(!expander){fluid.fail("Unknown expander with type "+source.expander.type)}return expander(deliverer,source,options)};fluid.proxyComponentHandler=function(target,prop){return prop===Symbol.toStringTag?Object.prototype.toString.call(target):prop in target?target[prop]:fluid.getForComponent(target,prop)};fluid.proxyComponent=function(component){var shadow=fluid.shadowForComponent(component);if(!shadow.proxy){shadow.proxy=new Proxy(component,{get:fluid.proxyComponentHandler})}return shadow.proxy};fluid.possiblyProxyComponent=function(value){return fluid.isComponent(value)&&value.lifecycleStatus!=="treeConstructed"?fluid.proxyComponent(value):value};fluid.proxyComponentArgs=function(args){args.forEach((function(arg,i){args[i]=fluid.possiblyProxyComponent(arg)}))};fluid.registerNamespace("fluid.expander");fluid.expander.fetch=function(deliverer,source,options){var localRecord=options.localRecord,context=source.expander.context,segs=source.expander.segs;var inLocal=localRecord[context]!==undefined;var contextStatus=options.contextThat.lifecycleStatus;var fast=contextStatus==="treeConstructed"||contextStatus==="destroyed";var component=inLocal?localRecord[context]:fluid.resolveContext(context,options.contextThat,fast);if(component!==undefined){var root=component;if(inLocal||component.lifecycleStatus!=="constructing"){for(var i=0;i<segs.length;++i){root=root?root[segs[i]]:undefined}}else{root=fluid.getForComponent(component,segs)}if(root===undefined&&!inLocal){root=fluid.getForComponent(component,segs)}if(!fast&&!options.noproxy&&fluid.isComponent(root)){return fluid.proxyComponent(root)}return root}else if(segs.length>0){fluid.triggerMismatchedPathError(source.expander,options.contextThat)}};fluid.expander.invokeFunc=function(deliverer,source,options){var expander=source.expander;var args=fluid.makeArray(expander.args);var whichFuncEntry=expander.func?"func":expander.funcName?"funcName":null;expander.args=args;if(options.recurse){args=options.recurse([],args)}else{expander=fluid.expandImmediate(expander,options.contextThat,options.localRecord,expander.noproxy);args=expander.args}if(!expander.noproxy){fluid.proxyComponentArgs(args)}var funcEntry=expander[whichFuncEntry];var func=(options.expandSource?options.expandSource(funcEntry):funcEntry)||fluid.recordToApplicable(expander,options.contextThat);if(typeof func==="string"){func=fluid.getGlobalValue(func)}if(!func){fluid.fail("Error in expander record ",source.expander,": "+source.expander[whichFuncEntry]+" could not be resolved to a function for component ",options.contextThat)}return func.apply(null,args)};fluid.expander.noexpand=function(deliverer,source){return source.expander.value?source.expander.value:source.expander.tree};fluid.noexpand=fluid.expander.noexpand;"use strict";fluid.model.makeEnvironmentStrategy=function(environment){return function(root,segment,index){return index===0&&environment[segment]?environment[segment]:undefined}};fluid.model.defaultCreatorStrategy=function(root,segment){if(root[segment]===undefined){root[segment]={};return root[segment]}};fluid.model.defaultFetchStrategy=function(root,segment){return root[segment]};fluid.model.funcResolverStrategy=function(root,segment){if(root.resolvePathSegment){return root.resolvePathSegment(segment)}};fluid.model.traverseWithStrategy=function(root,segs,initPos,config,uncess){var strategies=config.strategies;var limit=segs.length-uncess;for(var i=initPos;i<limit;++i){if(!root){return root}var accepted;for(var j=0;j<strategies.length;++j){accepted=strategies[j](root,segs[i],i+1,segs);if(accepted!==undefined){break}}if(accepted===fluid.NO_VALUE){accepted=undefined}root=accepted}return root};fluid.model.getValueAndSegments=function(root,EL,config,initSegs){return fluid.model.accessWithStrategy(root,EL,fluid.NO_VALUE,config,initSegs,true)};fluid.model.makeTrundler=function(config){return function(valueSeg,EL){return fluid.model.getValueAndSegments(valueSeg.root,EL,config,valueSeg.segs)}};fluid.model.getWithStrategy=function(root,EL,config,initSegs){return fluid.model.accessWithStrategy(root,EL,fluid.NO_VALUE,config,initSegs)};fluid.model.setWithStrategy=function(root,EL,newValue,config,initSegs){fluid.model.accessWithStrategy(root,EL,newValue,config,initSegs)};fluid.model.accessWithStrategy=function(root,EL,newValue,config,initSegs,returnSegs){if(!fluid.isPrimitive(EL)&&!fluid.isArrayable(EL)){var key=EL.type||"default";var resolver=config.resolvers[key];if(!resolver){fluid.fail("Unable to find resolver of type "+key)}var trundler=fluid.model.makeTrundler(config);var valueSeg={root:root,segs:initSegs};valueSeg=resolver(valueSeg,EL,trundler);if(EL.path&&valueSeg){valueSeg=trundler(valueSeg,EL.path)}return returnSegs?valueSeg:valueSeg?valueSeg.root:undefined}else{return fluid.model.accessImpl(root,EL,newValue,config,initSegs,returnSegs,fluid.model.traverseWithStrategy)}};fluid.registerNamespace("fluid.pathUtil");fluid.pathUtil.getPathSegmentImpl=function(accept,path,i){var segment=null;if(accept){segment=""}var escaped=false;var limit=path.length;for(;i<limit;++i){var c=path.charAt(i);if(!escaped){if(c==="."){break}else if(c==="\\"){escaped=true}else if(segment!==null){segment+=c}}else{escaped=false;if(segment!==null){segment+=c}}}if(segment!==null){accept[0]=segment}return i};var globalAccept=[];fluid.pathUtil.parseEL=function(path){var togo=[];var index=0;var limit=path.length;while(index<limit){var firstdot=fluid.pathUtil.getPathSegmentImpl(globalAccept,path,index);togo.push(globalAccept[0]);index=firstdot+1}return togo};fluid.pathUtil.composeSegment=function(prefix,toappend){toappend=toappend.toString();for(var i=0;i<toappend.length;++i){var c=toappend.charAt(i);if(c==="."||c==="\\"||c==="}"){prefix+="\\"}prefix+=c}return prefix};fluid.pathUtil.escapeSegment=function(segment){return fluid.pathUtil.composeSegment("",segment)};fluid.pathUtil.composePath=function(prefix,suffix){if(prefix.length!==0){prefix+="."}return fluid.pathUtil.composeSegment(prefix,suffix)};fluid.pathUtil.composeSegments=function(){var path="";for(var i=0;i<arguments.length;++i){path=fluid.pathUtil.composePath(path,arguments[i])}return path};fluid.pathUtil.matchSegments=function(toMatch,segs,start,end){if(end-start!==toMatch.length){return false}for(var i=start;i<end;++i){if(segs[i]!==toMatch[i-start]){return false}}return true};fluid.model.unescapedParser={parse:fluid.model.parseEL,compose:fluid.model.composeSegments};fluid.model.defaultGetConfig={parser:fluid.model.unescapedParser,strategies:[fluid.model.funcResolverStrategy,fluid.model.defaultFetchStrategy]};fluid.model.defaultSetConfig={parser:fluid.model.unescapedParser,strategies:[fluid.model.funcResolverStrategy,fluid.model.defaultFetchStrategy,fluid.model.defaultCreatorStrategy]};fluid.model.escapedParser={parse:fluid.pathUtil.parseEL,compose:fluid.pathUtil.composeSegments};fluid.model.escapedGetConfig={parser:fluid.model.escapedParser,strategies:[fluid.model.defaultFetchStrategy]};fluid.model.escapedSetConfig={parser:fluid.model.escapedParser,strategies:[fluid.model.defaultFetchStrategy,fluid.model.defaultCreatorStrategy]};fluid.stronglyConnected=function(vertices,accessor){var that={stack:[],accessor:accessor,components:[],index:0};vertices.forEach((function(vertex){delete vertex.lowIndex;delete vertex.tarjanIndex;delete vertex.onStack}));vertices.forEach((function(vertex){if(vertex.tarjanIndex===undefined){fluid.stronglyConnectedOne(vertex,that)}}));return that.components};fluid.stronglyConnectedOne=function(vertex,that){vertex.tarjanIndex=that.index;vertex.lowIndex=that.index;++that.index;that.stack.push(vertex);vertex.onStack=true;var outEdges=that.accessor(vertex);outEdges.forEach((function(outVertex){if(outVertex.tarjanIndex===undefined){fluid.stronglyConnectedOne(outVertex,that);vertex.lowIndex=Math.min(vertex.lowIndex,outVertex.lowIndex)}else if(outVertex.onStack){vertex.lowIndex=Math.min(vertex.lowIndex,outVertex.tarjanIndex)}}));if(vertex.lowIndex===vertex.tarjanIndex){var component=[],outVertex;do{outVertex=that.stack.pop();outVertex.onStack=false;component.push(outVertex)}while(outVertex!==vertex);that.components.push(component)}};fluid.initRelayModel=function(that){return that.model};fluid.findInitModelTransaction=function(that){var transRec=fluid.currentTreeTransaction();if(transRec&&fluid.isComponent(that)){return transRec.initModelTransaction[that.id]}};fluid.enlistModelComponent=function(that){var treeTransaction=fluid.currentTreeTransaction();var transId=treeTransaction.initModelTransactionId;var initModelTransaction=treeTransaction.initModelTransaction;var enlist=initModelTransaction[that.id];if(!enlist){var shadow=fluid.shadowForComponent(that);enlist={that:that,applier:fluid.getForComponent(that,"applier"),initModels:[],completeOnInit:!!shadow.initTransactionId,transaction:that.applier.initiate(null,"init",transId)};initModelTransaction[that.id]=enlist;var transRec=fluid.getModelTransactionRec(fluid.rootComponent,transId);transRec[that.applier.applierId]={transaction:enlist.transaction};fluid.registerMaterialisationListener(that,that.applier)}return enlist};fluid.clearTransactions=function(){var instantiator=fluid.globalInstantiator;fluid.clear(instantiator.modelTransactions)};fluid.failureEvent.addListener(fluid.clearTransactions,"clearTransactions","before:fail");fluid.clearLinkCounts=function(transRec,relaysAlso){fluid.each(transRec,(function(value,key){if(typeof value==="number"){transRec[key]=0}else if(relaysAlso&&value.options&&typeof value.relayCount==="number"){value.relayCount=0}}))};fluid.computeInitialOutArcs=function(transacs,initModelTransaction){return fluid.transform(initModelTransaction,(function(recel,id){var oneOutArcs={};var listeners=recel.that.applier.listeners.sortedListeners;fluid.each(listeners,(function(listener){if(listener.isRelay&&!fluid.isExcludedChangeSource(transacs[id],listener.cond)){var targetId=listener.targetId;if(targetId!==id){oneOutArcs[targetId]=true}}}));var oneOutArcList=Object.keys(oneOutArcs);var togo=oneOutArcList.map((function(id){return initModelTransaction[id]}));fluid.remove_if(togo,(function(rec){return rec===undefined}));return togo}))};fluid.sortCompleteLast=function(reca,recb){return(reca.completeOnInit?1:0)-(recb.completeOnInit?1:0)};fluid.subscribeResourceModelUpdates=function(that,resourceMapEntry){var treeTransaction=fluid.currentTreeTransaction();var resourceSpec=resourceMapEntry.resourceSpec;var resourceUpdateListener=function(){var initTransaction=fluid.getImmediate(treeTransaction,["initModelTransaction",that.id]);var trans=initTransaction?initTransaction.transaction:that.applier.initiate();resourceMapEntry.listeners.forEach((function(oneListener){var innerValue=fluid.getImmediate(resourceSpec,oneListener.resourceSegs);var segs=oneListener.segs;trans.change(segs,null,"DELETE");trans.change(segs,innerValue)}));if(!initTransaction){trans.commit()}else{var transRec=fluid.getModelTransactionRec(fluid.rootComponent,trans.id);fluid.clearLinkCounts(transRec,true);that.applier.preCommit.fire(trans,that)}};resourceSpec.onFetched.addListener(resourceUpdateListener);fluid.recordListener(resourceSpec.onFetched,resourceUpdateListener,fluid.shadowForComponent(that))};fluid.resolveResourceModelWorkflow=function(shadows,treeTransaction){var initModelTransaction=treeTransaction.initModelTransaction;shadows.forEach((function(shadow){var that=shadow.that;fluid.registerMergedModelListeners(that,that.options.modelListeners);fluid.each(shadow.modelSourcedDynamicComponents,(function(componentRecord,key){fluid.constructLensedComponents(shadow,initModelTransaction[that.id],componentRecord.sourcesParsed,key)}))}))};fluid.condenseResourceMap=function(resourceMap){var byId={};resourceMap.forEach((function(resourceMapEntry){var resourceSpec=resourceMapEntry.fetchOne.resourceSpec;var id=resourceSpec.transformEvent.eventId;var existing=byId[id];if(!existing){existing=byId[id]={resourceSpec:resourceSpec,listeners:[]}}existing.listeners.push({resourceSegs:resourceMapEntry.fetchOne.segs,segs:resourceMapEntry.segs})}));return byId};fluid.operateInitialTransaction=function(initModelTransaction,transId){var transacs=fluid.transform(initModelTransaction,(function(recel){return recel.transaction}));var outArcs=fluid.computeInitialOutArcs(transacs,initModelTransaction);var arcAccessor=function(initTransactionRecord){return outArcs[initTransactionRecord.that.id]};var recs=fluid.values(initModelTransaction);var components=fluid.stronglyConnected(recs,arcAccessor);var priorityIndex=0;components.forEach((function(component){component.forEach((function(recel){recel.initPriority=recel.completeOnInit?Infinity:priorityIndex++}))}));recs.sort((function(reca,recb){return reca.initPriority-recb.initPriority}));var transRec=fluid.getModelTransactionRec(fluid.rootComponent,transId);recs.forEach((function applyInitialModelTransactionValues(recel){var that=recel.that,applier=recel.that.applier,transac=transacs[that.id];if(recel.completeOnInit){fluid.notifyModelChanges(applier.listeners.sortedListeners,"ADD",transac.oldHolder,fluid.emptyHolder,null,transac,applier,that)}else{fluid.each(recel.initModels,(function(oneInitModel){if(oneInitModel!==undefined){transac.fireChangeRequest({type:"ADD",segs:[],value:oneInitModel})}fluid.clearLinkCounts(transRec,true)}))}}));recs.forEach((function updateInitialModelTransactionRelays(recel){var that=recel.that,applier=recel.that.applier,transac=transacs[that.id];applier.preCommit.fire(transac,that);if(!recel.completeOnInit){var resourceMapById=fluid.condenseResourceMap(applier.resourceMap);fluid.each(resourceMapById,(function(resourceMapEntry){fluid.subscribeResourceModelUpdates(that,resourceMapEntry)}));applier.earlyModelResolved.fire(that.model);applier.preCommit.fire(transac,that);recel.completeOnInit=true;var shadow=fluid.shadowForComponent(that);if(shadow&&!shadow.initTransactionId){shadow.initTransactionId=transId}}}))};fluid.parseModelReference=function(that,ref){var parsed=fluid.parseContextReference(ref);parsed.segs=fluid.pathUtil.parseEL(parsed.path);return parsed};fluid.parseValidModelReference=function(that,name,ref,permitNonModel){var localRecord=fluid.shadowForComponent(that).localRecord;var reject=function(){var failArgs=["Error in "+name+": ",ref].concat(fluid.makeArray(arguments));fluid.fail.apply(null,failArgs)};var rejectNonModel=function(value){reject(" must be a reference to a component with a ChangeApplier (descended from fluid.modelComponent), instead got ",value)};var parsed;if(typeof ref==="string"){if(fluid.isIoCReference(ref)){parsed=fluid.parseModelReference(that,ref);var modelPoint=parsed.segs.indexOf("model");if(modelPoint===-1){if(permitNonModel){parsed.nonModel=true}else{reject(' must be a reference into a component model via a path including the segment "model"')}}else{parsed.modelSegs=parsed.segs.slice(modelPoint+1);parsed.contextSegs=parsed.segs.slice(0,modelPoint);delete parsed.path}}else{parsed={path:ref,modelSegs:that.applier.parseEL(ref)}}}else{if(!fluid.isArrayable(ref.segs)){reject(' must contain an entry "segs" holding path segments referring a model path within a component')}parsed={context:ref.context,modelSegs:fluid.expandImmediate(ref.segs,that,localRecord)};fluid.each(parsed.modelSegs,(function(seg,index){if(!fluid.isValue(seg)){reject(" did not resolve path segment reference "+ref.segs[index]+" at index "+index)}}))}var contextTarget,target;if(parsed.context){if(localRecord&&parsed.context in localRecord){if(parsed.context==="source"&&localRecord.sourceModelReference){target=localRecord.sourceModelReference.that;parsed.modelSegs=localRecord.sourceModelReference.modelSegs.concat(parsed.segs);parsed.nonModel=false}else{target=localRecord[parsed.context]}}else{contextTarget=fluid.resolveContext(parsed.context,that);if(!contextTarget){reject(" context must be a reference to an existing component")}target=parsed.contextSegs?fluid.getForComponent(contextTarget,parsed.contextSegs):contextTarget}}else{target=that}if(!parsed.nonModel){if(!fluid.isComponent(target)){rejectNonModel(target)}if(!target.applier){fluid.getForComponent(target,["applier"])}if(!target.applier){rejectNonModel(target)}}parsed.that=target;parsed.applier=target&&target.applier;if(!parsed.path&&parsed.applier){parsed.path=target&&parsed.applier.composeSegments.apply(null,parsed.modelSegs)}return parsed};fluid.registerNamespace("fluid.materialiserRegistry");fluid.matchMaterialiserSpec=function(record,segs){var trundle=record;var routedPath=null;for(var i=0;i<segs.length;++i){var seg=segs[i];var wildcard=trundle["*"];if(wildcard){routedPath=wildcard}trundle=trundle[seg]||wildcard;if(!trundle){break}else if(trundle.materialiser){return trundle}}if(routedPath){fluid.fail("Materialised DOM path ",segs," did not match any registered materialiser - available paths are "+Object.keys(routedPath).join(", "))}return null};fluid.materialiseModelPath=function(that,segs){var shadow=fluid.shadowForComponent(that);var materialisedPath=["materialisedPaths"].concat(segs);if(!fluid.getImmediate(shadow,materialisedPath)){fluid.each(fluid.materialiserRegistry,(function(gradeRecord,grade){if(fluid.componentHasGrade(that,grade)){var record=fluid.matchMaterialiserSpec(gradeRecord,segs);if(record&&record.materialiser){fluid.model.setSimple(shadow,materialisedPath,{});var args=fluid.makeArray(record.args);fluid.invokeGlobalFunction(record.materialiser,[that,fluid.makeArray(segs)].concat(args))}}}))}};fluid.materialiseAgainstValue=function(that,newValue,segs){if(fluid.isPlainObject(newValue)){fluid.each(newValue,(function(inner,seg){segs.push(seg);fluid.materialiseAgainstValue(that,inner,segs);segs.pop()}))}else{fluid.materialiseModelPath(that,segs)}};fluid.registerMaterialisationListener=function(that,applier){fluid.each(fluid.materialiserRegistry,(function(gradeRecord,grade){if(fluid.componentHasGrade(that,grade)){fluid.each(gradeRecord,(function(rest,root){applier.modelChanged.addListener({transactional:false,path:root},(function(newValue){var segs=[root];fluid.materialiseAgainstValue(that,newValue,segs)}))}))}}))};fluid.getModelTransactionRec=function(that,transId){if(!transId){fluid.fail("Cannot get transaction record without transaction id")}var instantiator=fluid.isComponent(that)&&!fluid.isDestroyed(that,true)?fluid.globalInstantiator:null;if(!instantiator){return null}var transRec=instantiator.modelTransactions[transId];if(!transRec){transRec=instantiator.modelTransactions[transId]={relays:[],sources:{},externalChanges:{}}}return transRec};fluid.recordChangeListener=function(component,applier,sourceListener,listenerId){var shadow=fluid.shadowForComponent(component);fluid.recordListener(applier.modelChanged,sourceListener,shadow,listenerId)};fluid.registerRelayTransaction=function(transRec,targetApplier,transId,options,npOptions){var newTrans=targetApplier.initiate("relay",null,transId);var transEl=transRec[targetApplier.applierId]={transaction:newTrans,relayCount:0,namespace:npOptions.namespace,priority:npOptions.priority,options:options};transEl.priority=fluid.parsePriority(transEl.priority,transRec.relays.length,false,"model relay");transRec.relays.push(transEl);return transEl};fluid.relayRecursionBailout=100;fluid.registerDirectChangeRelay=function(target,targetSegs,source,sourceSegs,linkId,transducer,options,npOptions){var targetApplier=options.targetApplier||target.applier;var sourceApplier=options.sourceApplier||source.applier;if(!options.targetApplier){fluid.materialiseModelPath(target,targetSegs)}if(!options.sourceApplier){fluid.materialiseModelPath(source,sourceSegs)}var applierId=targetApplier.applierId;targetSegs=fluid.makeArray(targetSegs);sourceSegs=fluid.makeArray(sourceSegs);var sourceListener=function(newValue,oldValue,path,changeRequest,trans,applier){var transId=trans.id;var transRec=fluid.getModelTransactionRec(target,transId);if(applier&&trans&&!transRec[applier.applierId]){transRec[applier.applierId]={transaction:trans}}var transEl=transRec[applierId];transRec[linkId]=transRec[linkId]||0;var relay=true;if(relay){++transRec[linkId];if(transRec[linkId]>fluid.relayRecursionBailout){fluid.fail("Error in model relay specification at component ",target," - operated more than "+fluid.relayRecursionBailout+" relays without model value settling - current model contents are ",trans.newHolder.model)}if(!transEl){transEl=fluid.registerRelayTransaction(transRec,targetApplier,transId,options,npOptions)}if(transducer&&!options.targetApplier){fluid.pushActivity("relayTransducer",'computing modelRelay output for rule with target path "%targetSegs" and namespace "%namespace"',{targetSegs:targetSegs,namespace:npOptions.namespace});transducer(transEl.transaction,options.sourceApplier?undefined:newValue,source,sourceSegs,targetSegs,changeRequest);fluid.popActivity()}else{if(changeRequest&&changeRequest.type==="DELETE"){var deleteSegs=targetSegs.concat(changeRequest.segs.slice(sourceSegs.length));transEl.transaction.fireChangeRequest({type:"DELETE",segs:deleteSegs})}else if(newValue!==undefined){transEl.transaction.fireChangeRequest({type:"ADD",segs:targetSegs,value:newValue})}}}};var spec=sourceApplier.modelChanged.addListener({isRelay:true,cond:transducer&&transducer.cond,targetId:target.id,targetApplierId:targetApplier.id,segs:sourceSegs,transactional:options.transactional},sourceListener);if(fluid.passLogLevel(fluid.logLevel.TRACE)){fluid.log(fluid.logLevel.TRACE,"Adding relay listener with listenerId "+spec.listenerId+" to source applier with id "+sourceApplier.applierId+" from target applier with id "+applierId+" for target component with id "+target.id)}if(source){fluid.recordChangeListener(source,sourceApplier,sourceListener,spec.listenerId);if(target!==source){fluid.recordChangeListener(target,sourceApplier,sourceListener,spec.listenerId)}}};fluid.connectModelRelay=function(source,sourceSegs,target,targetSegs,options){var linkId=fluid.allocateGuid();fluid.enlistModelComponent(target);fluid.enlistModelComponent(source);var npOptions=fluid.filterKeys(options,["namespace","priority"]);if(options.update){if(options.targetApplier){fluid.registerDirectChangeRelay(source,sourceSegs,target,targetSegs,linkId,null,{transactional:false,targetApplier:options.targetApplier,refCount:options.refCount,update:options.update},npOptions)}else{fluid.registerDirectChangeRelay(target,targetSegs,source,[],linkId+"-transform",options.forwardAdapter,{transactional:true,sourceApplier:options.forwardApplier},npOptions)}}else{fluid.registerDirectChangeRelay(target,targetSegs,source,sourceSegs,linkId,options.forwardAdapter,{transactional:false},npOptions);fluid.registerDirectChangeRelay(source,sourceSegs,target,targetSegs,linkId,options.backwardAdapter,{transactional:false},npOptions)}};fluid.parseSourceExclusionSpec=function(targetSpec,sourceSpec){targetSpec.excludeSource=fluid.arrayToHash(fluid.makeArray(sourceSpec.excludeSource||(sourceSpec.includeSource?"*":undefined)));targetSpec.includeSource=fluid.arrayToHash(fluid.makeArray(sourceSpec.includeSource));return targetSpec};fluid.isExcludedChangeSource=function(transaction,spec){if(!spec||!spec.excludeSource){return false}var excluded=spec.excludeSource["*"];for(var source in transaction.fullSources){if(spec.excludeSource[source]){excluded=true}if(spec.includeSource[source]){excluded=false}}return excluded};fluid.model.guardedAdapter=function(transaction,cond,func,args){if(!fluid.isExcludedChangeSource(transaction,cond)&&func!==fluid.model.transform.uninvertibleTransform){func.apply(null,args)}};fluid.transformToAdapter=function(transform,targetPath){var basedTransform={};basedTransform[targetPath]=transform;return function(trans,newValue,source,sourceSegs,targetSegs,changeRequest){if(changeRequest&&changeRequest.type==="DELETE"){trans.fireChangeRequest({type:"DELETE",path:targetPath})}var oldTarget=fluid.getImmediate(trans.oldHolder.model,targetSegs);var oldSource=fluid.getImmediate(source.model,sourceSegs);fluid.model.transformWithRules(newValue,basedTransform,{finalApplier:trans,oldTarget:oldTarget,oldSource:oldSource})}};fluid.makeTransformPackage=function(componentThat,transform,sourcePath,targetPath,forwardCond,backwardCond,namespace,priority){var that={forwardHolder:{model:transform},backwardHolder:{model:null}};that.generateAdapters=function(trans){that.forwardAdapterImpl=fluid.transformToAdapter(trans?trans.newHolder.model:that.forwardHolder.model,targetPath);if(sourcePath!==null){var inverted=fluid.model.transform.invertConfiguration(transform);if(inverted!==fluid.model.transform.uninvertibleTransform){that.backwardHolder.model=inverted;that.backwardAdapterImpl=fluid.transformToAdapter(that.backwardHolder.model,sourcePath)}else{that.backwardAdapterImpl=inverted}}};that.forwardAdapter=function(transaction,newValue){if(newValue===undefined){that.generateAdapters()}fluid.model.guardedAdapter(transaction,forwardCond,that.forwardAdapterImpl,arguments)};that.forwardAdapter.cond=forwardCond;that.runTransform=function(trans){trans.commit();trans.reset()};that.forwardApplier=fluid.makeHolderChangeApplier(that.forwardHolder);that.forwardApplier.isRelayApplier=true;that.invalidator=fluid.makeEventFirer({name:"Invalidator for model relay with applier "+that.forwardApplier.applierId});if(sourcePath!==null){that.backwardApplier=fluid.makeHolderChangeApplier(that.backwardHolder);that.backwardAdapter=function(transaction){fluid.model.guardedAdapter(transaction,backwardCond,that.backwardAdapterImpl,arguments)};that.backwardAdapter.cond=backwardCond}that.update=that.invalidator.fire;var implicitOptions={targetApplier:that.forwardApplier,update:that.update,namespace:namespace,priority:priority,refCount:0};that.forwardHolder.model=fluid.parseImplicitRelay(componentThat,transform,[],implicitOptions);that.refCount=implicitOptions.refCount;that.namespace=namespace;that.priority=priority;that.generateAdapters();that.invalidator.addListener(that.generateAdapters);that.invalidator.addListener(that.runTransform);return that};fluid.singleTransformToFull=function(singleTransform){var expanded=typeof singleTransform==="string"?{type:singleTransform}:singleTransform;var withPath=$.extend(true,{inputPath:""},expanded);return{"":{transform:withPath}}};fluid.funcToSingleTransform=function(that,mrrec){if(mrrec.func){if((mrrec.args!==undefined)+(mrrec.source!==undefined)+(mrrec.value!==undefined)!==1){fluid.fail("Error in model relay definition: short-form relay must specify just one out of (args, source, value)")}return{type:"fluid.transforms.free",func:mrrec.func,args:mrrec.args?mrrec.args:[fluid.isIoCReference(mrrec.source)?mrrec.source:"{that}.model."+mrrec.source]}}else{return null}};fluid.model.relayConditions={initOnly:{includeSource:"init"},liveOnly:{excludeSource:"init"},never:{includeSource:[]},always:{}};fluid.model.expandRelayCondition=function(condition){var exclusionRec;if(condition==="initOnly"){fluid.log(fluid.logLevel.WARN,'The relay condition "initOnly" is deprecated: Please use the form \'includeSource: "init"\' instead')}else if(condition==="liveOnly"){fluid.log(fluid.logLevel.WARN,'The relay condition "liveOnly" is deprecated: Please use the form \'excludeSource: "init"\' instead')}if(!condition){exclusionRec={}}else if(typeof condition==="string"){exclusionRec=fluid.model.relayConditions[condition];if(!exclusionRec){fluid.fail('Unrecognised model relay condition string "'+condition+'": the supported values are "never" or a record with members "includeSource" and/or "excludeSource"')}}else{exclusionRec=condition}return exclusionRec};fluid.model.parseRelayConditions=function(conditions){var expanded=conditions.map(fluid.model.expandRelayCondition);var mergeArgs=[true,{}].concat(expanded);var merged=fluid.extend.apply(null,mergeArgs);return fluid.parseSourceExclusionSpec({},merged)};fluid.parseModelRelay=function(that,mrrec,key){fluid.pushActivity("parseModelRelay",'parsing modelRelay definition with key "%key" and body "%body" attached to component "%that"',{key:key,body:mrrec,that:that});if(typeof mrrec.target!=="string"&&!(fluid.isPlainObject(mrrec.target,true)&&mrrec.target.segs)){fluid.fail('Error parsing model relay definition: model reference must be specified for "target"')}var parsedSource=mrrec.source!==undefined?fluid.parseValidModelReference(that,'modelRelay record member "source"',mrrec.source,true):mrrec.value!==undefined?{nonModel:true}:{path:null,modelSegs:null};var parsedTarget=fluid.parseValidModelReference(that,'modelRelay record member "target"',mrrec.target);var namespace=mrrec.namespace||key;var singleTransform=typeof mrrec.singleTransform==="string"?{type:mrrec.singleTransform}:mrrec.singleTransform;var shortSingleTransform=fluid.funcToSingleTransform(that,mrrec);var transform=mrrec.transform||fluid.singleTransformToFull(singleTransform||shortSingleTransform||{type:"fluid.transforms.identity"});var upDefaults=singleTransform?fluid.defaults(singleTransform.type):null;var relayOptions=upDefaults&&upDefaults.relayOptions||{};var forwardCond=fluid.model.parseRelayConditions([relayOptions.forward,mrrec.forward]),backwardCond=fluid.model.parseRelayConditions([relayOptions.backward,mrrec.backward]);var transformPackage=fluid.makeTransformPackage(that,transform,parsedSource.path,parsedTarget.path,forwardCond,backwardCond,namespace,mrrec.priority);if(parsedSource.nonModel){var initValue=fluid.parseImplicitRelay(that,fluid.firstDefined(mrrec.source,mrrec.value),parsedTarget.modelSegs),transformed;if(transform[""].transform.type!=="fluid.transforms.identity"){var localTransform=fluid.copy(transform);localTransform[""].transform.args=[initValue];transformed=fluid.model.transformWithRules(initValue,localTransform)}else{transformed=initValue}var enlist=fluid.enlistModelComponent(parsedTarget.that);var initModel={};fluid.model.setSimple(initModel,parsedTarget.modelSegs,transformed);enlist.initModels.push(initModel)}else{if(transformPackage.refCount===0){fluid.connectModelRelay(parsedSource.that||that,parsedSource.modelSegs,parsedTarget.that,parsedTarget.modelSegs,fluid.filterKeys(transformPackage,["forwardAdapter","backwardAdapter","namespace","priority"]))}else{if(parsedSource.modelSegs&&!shortSingleTransform){fluid.fail('Error in model relay definition: If a relay transform has a model dependency, you can not specify a "source" entry - please instead enter this as "input" in the transform specification. Definition was ',mrrec," for component ",that)}fluid.connectModelRelay(that,null,parsedTarget.that,parsedTarget.modelSegs,transformPackage)}}fluid.popActivity()};fluid.parseImplicitRelay=function(that,modelRec,segs,options){var value;if(fluid.isIoCReference(modelRec)){var parsed=fluid.parseValidModelReference(that,"model reference from model (implicit relay)",modelRec,true);if(parsed.nonModel){value=fluid.isComponent(parsed.that)?fluid.possiblyProxyComponent(fluid.getForComponent(parsed.that,parsed.segs)):fluid.getImmediate(parsed.that,parsed.segs);if(value instanceof fluid.fetchResources.FetchOne){that.applier.resourceMap.push({segs:fluid.makeArray(segs),fetchOne:value});return undefined}}else{++options.refCount;fluid.connectModelRelay(that,segs,parsed.that,parsed.modelSegs,options)}}else if(fluid.isPrimitive(modelRec)||!fluid.isPlainObject(modelRec)){value=modelRec}else if(modelRec.expander&&fluid.isPlainObject(modelRec.expander)){value=fluid.expandOptions(modelRec,that)}else{value=fluid.freshContainer(modelRec);fluid.each(modelRec,(function(innerValue,key){segs.push(key);var innerTrans=fluid.parseImplicitRelay(that,innerValue,segs,options);if(innerTrans!==undefined){value[key]=innerTrans}segs.pop()}))}return value};fluid.model.notifyExternal=function(transRec){var allChanges=transRec?fluid.values(transRec.externalChanges):[];fluid.sortByPriority(allChanges);for(var i=0;i<allChanges.length;++i){var change=allChanges[i];var targetApplier=change.args[5];if(!targetApplier.destroyed){change.listener.apply(null,change.args)}}fluid.clearLinkCounts(transRec,true)};fluid.model.commitRelays=function(instantiator,transactionId){var transRec=instantiator.modelTransactions[transactionId];fluid.each(transRec,(function(transEl){if(transEl.transaction){transEl.transaction.commit("relay");transEl.transaction.reset()}}))};fluid.model.updateRelays=function(instantiator,transactionId){var transRec=instantiator.modelTransactions[transactionId];var updates=0;fluid.sortByPriority(transRec.relays);fluid.each(transRec.relays,(function(transEl){var maxRelay=transEl.options.refCount?transEl.options.refCount*4:4;if(transEl.transaction.changeRecord.changes>0&&transEl.relayCount<maxRelay&&transEl.options.update){transEl.relayCount++;fluid.clearLinkCounts(transRec);transEl.options.update(transEl.transaction,transRec);++updates}}));return updates};fluid.concludeModelTransaction=function(transaction){var instantiator=fluid.globalInstantiator;fluid.model.notifyExternal(instantiator.modelTransactions[transaction.id]);delete instantiator.modelTransactions[transaction.id]};fluid.establishModelRelay=function(that,optionsModel,optionsML,optionsMR,applier){var shadow=fluid.shadowForComponent(that);if(!shadow.modelRelayEstablished){shadow.modelRelayEstablished=true}else{fluid.fail("FLUID-5887 failure: Model relay initialised twice on component",that)}var enlist=fluid.enlistModelComponent(that);var initModels=(optionsModel||[]).map((function(modelRec){return fluid.parseImplicitRelay(that,modelRec,[],{refCount:0,priority:"first"})}));Array.prototype.push.apply(enlist.initModels,initModels);fluid.each(optionsMR,(function(mrrec,key){if(key===""){for(var i=0;i<mrrec.length;++i){fluid.parseModelRelay(that,mrrec[i],key)}}else{var lightMerge=fluid.extend.apply(null,[true,{}].concat(mrrec));fluid.parseModelRelay(that,lightMerge,key)}}));var instantiator=fluid.getInstantiator(that);function updateRelays(transaction){while(fluid.model.updateRelays(instantiator,transaction.id)>0){}}function commitRelays(transaction){fluid.model.commitRelays(instantiator,transaction.id)}applier.preCommit.addListener(updateRelays);applier.preCommit.addListener(commitRelays);applier.postCommit.addListener(fluid.concludeModelTransaction);applier.postCommit.addListener(fluid.concludeAnyTreeTransaction);return null};fluid.destroyLensedComponentSource=function(that,isBoolean){var shadow=fluid.shadowForComponent(that);var sourceModelReference=shadow.localRecord.sourceModelReference;if(sourceModelReference&&!fluid.isDestroyed(sourceModelReference.that,true)){sourceModelReference.that.applier.change(sourceModelReference.modelSegs,false,isBoolean?"ADD":"DELETE")}};fluid.constructLensedComponents=function(shadow,initTransRec,sourcesParsed,dynamicComponentKey){var lightMerge=shadow.lightMergeDynamicComponents[dynamicComponentKey];var sources=fluid.getImmediate(shadow.that.model,sourcesParsed.modelSegs);var shadowRecord=shadow.modelSourcedDynamicComponents[dynamicComponentKey];var localRecordContributor=shadowRecord.localRecordContributor=function(localRecord,source,sourceKey){localRecord.sourceModelReference={that:sourcesParsed.that,modelSegs:sourcesParsed.modelSegs.concat(shadowRecord.isBoolean?[]:[sourceKey])}};fluid.lightMergeRecords.pushRecord(lightMerge,{options:{listeners:{afterDestroy:{funcName:"fluid.destroyLensedComponentSource",args:["{that}",shadowRecord.isBoolean]}}}});fluid.registerSourcedDynamicComponentsTriage(shadow.potentia,shadow.that,sources,lightMerge,dynamicComponentKey,shadowRecord.isBoolean,localRecordContributor)};fluid.operateInitialTransactionWorkflow=function(shadows,treeTransaction){fluid.tryCatch((function(){var initModelTransaction=treeTransaction.initModelTransaction;var transId=treeTransaction.initModelTransactionId;fluid.operateInitialTransaction(initModelTransaction,transId)}),(function(e){treeTransaction.initModelTransaction={};treeTransaction.initModelTransactionId=null;fluid.clearTransactions();throw e}),fluid.identity)};fluid.enlistModelWorkflow=function(shadows,treeTransaction){var transId=treeTransaction.initModelTransactionId;if(!transId){transId=fluid.allocateGuid();treeTransaction.initModelTransactionId=transId}shadows.forEach((function(shadow){fluid.getForComponent(shadow.that,"modelRelay")}));fluid.operateInitialTransactionWorkflow(shadows,treeTransaction)};fluid.notifyInitModelWorkflow=function(shadow,treeTransaction){if(!shadow.modelComplete){var initModelTransaction=treeTransaction.initModelTransaction;var transRec=fluid.getModelTransactionRec(fluid.rootComponent,shadow.initTransactionId);var trans=fluid.values(initModelTransaction)[0].transaction;treeTransaction.initModelTransaction={};treeTransaction.initModelTransactionId=null;trans.commit();fluid.each(initModelTransaction,(function(oneRec){var that=oneRec.that,applier=that.applier;trans=transRec[applier.applierId].transaction;var listeners=applier.transListeners.sortedListeners;var initShadow=fluid.shadowForComponent(that);initShadow.modelComplete=true;var shadowTrans=initShadow.initTransactionId;if(shadowTrans===shadow.initTransactionId){fluid.notifyModelChanges(listeners,"ADD",trans.oldHolder,fluid.emptyHolder,null,trans,applier,that)}else{}}));fluid.concludeModelTransaction(trans)}};fluid.defaults("fluid.modelComponent",{gradeNames:["fluid.component"],workflows:{global:{enlistModel:{funcName:"fluid.enlistModelWorkflow"},resolveResourceModel:{funcName:"fluid.resolveResourceModelWorkflow",priority:"after:enlistModel",waitIO:true}},local:{notifyInitModelWorkflow:{funcName:"fluid.notifyInitModelWorkflow",priority:"before:concludeComponentInit"}}},members:{model:{expander:{funcName:"fluid.initRelayModel",args:["{that}","{that}.modelRelay"],noproxy:true}},applier:{expander:{funcName:"fluid.makeHolderChangeApplier",args:["{that}","{that}.options.changeApplierOptions"],noproxy:true}},modelRelay:{expander:{funcName:"fluid.establishModelRelay",args:["{that}","{that}.options.model","{that}.options.modelListeners","{that}.options.modelRelay","{that}.applier"],noproxy:true}}},mergePolicy:{model:{noexpand:true,func:fluid.arrayConcatPolicy},modelListeners:fluid.makeMergeListenersPolicy(fluid.arrayConcatPolicy),modelRelay:fluid.makeMergeListenersPolicy(fluid.arrayConcatPolicy,true)}});fluid.modelChangedToChange=function(args){return{value:args[0],oldValue:args[1],path:args[2],transaction:args[4]}};fluid.event.invokeListener=function(listener,args,localRecord,mergeRecord){if(typeof listener==="string"){listener=fluid.event.resolveListener(listener)}return listener.apply(null,args,localRecord,mergeRecord)};fluid.resolveModelListener=function(that,record){var togo=function(){if(fluid.isDestroyed(that,true)){return}var change=fluid.modelChangedToChange(arguments);var args=arguments;var localRecord={change:change,arguments:args};var mergeRecord={source:Object.keys(change.transaction.sources)};if(record.args){args=fluid.expandImmediate(record.args,that,localRecord)}fluid.event.invokeListener(record.listener,fluid.makeArray(args),localRecord,mergeRecord)};fluid.event.impersonateListener(record.listener,togo);return togo};fluid.registerModelListeners=function(that,record,paths,namespace){var func=fluid.resolveModelListener(that,record);fluid.each(record.byTarget,(function(parsedArray){var parsed=parsedArray[0];var spec={listener:func,listenerId:fluid.allocateGuid(),segsArray:fluid.getMembers(parsedArray,"modelSegs"),includeSource:record.includeSource,excludeSource:record.excludeSource,priority:fluid.expandOptions(record.priority,that),transactional:true};spec=parsed.applier.modelChanged.addListener(spec,func,namespace,record.softNamespace);spec.segsArray.forEach((function(segs){fluid.materialiseModelPath(that,segs)}));fluid.recordChangeListener(that,parsed.applier,func,spec.listenerId)}))};fluid.registerMergedModelListeners=function(that,listeners){fluid.each(listeners,(function(value,key){if(typeof value==="string"){value={funcName:value}}var records=fluid.event.resolveListenerRecord(value,that,"modelListeners",null,false).records;fluid.each(records,(function(record){record.byTarget={};var paths=fluid.makeArray(record.path===undefined?key:record.path);fluid.each(paths,(function(path){var parsed=fluid.parseValidModelReference(that,"modelListeners entry",path);fluid.pushArray(record.byTarget,parsed.that.id,parsed)}));var namespace=(record.namespace&&!record.softNamespace?record.namespace:null)||(record.path!==undefined?key:null);fluid.registerModelListeners(that,record,paths,namespace)}))}))};fluid.replaceModelValue=function(applier,path,newValue){var transaction=applier.initiate();transaction.fireChangeRequest({path:path,type:"DELETE"});transaction.fireChangeRequest({path:path,value:newValue});transaction.commit();return applier.holder.model};fluid.fireChanges=function(applier,changes){for(var i=0;i<changes.length;++i){applier.fireChangeRequest(changes[i])}};fluid.model.isChangedPath=function(changeMap,segs){for(var i=0;i<=segs.length;++i){if(typeof changeMap==="string"){return changeMap}if(i<segs.length&&changeMap){changeMap=changeMap[segs[i]]}}return null};fluid.model.setChangedPath=function(options,segs,value){var notePath=function(record){var root=options;segs.unshift(record);for(var i=0;i<segs.length-1;++i){var seg=segs[i];if(root[seg]===undefined){root[seg]={}}root=root[seg]}if(fluid.isPlainObject(root)){root[fluid.peek(segs)]=value}segs.shift()};if(fluid.model.isChangedPath(options.changeMap,segs)!==value){++options.changes;notePath("changeMap")}if(fluid.model.isChangedPath(options.deltaMap,segs)!==value){++options.deltas;notePath("deltaMap")}};fluid.model.fetchChangeChildren=function(target,i,segs,source,options){fluid.each(source,(function(value,key){segs[i]=key;fluid.model.applyChangeStrategy(target,key,i,segs,value,options);segs.length=i}))};fluid.model.isSameValue=function(a,b){if(typeof a!=="number"||typeof b!=="number"){return a===b}else{if(a===b||a!==a&&b!==b){return true}else{var relError=Math.abs((a-b)/b);return relError<1e-12}}};fluid.model.applyChangeStrategy=function(target,name,i,segs,source,options){var targetSlot=target[name];var sourceCode=fluid.typeCode(source);var targetCode=fluid.typeCode(targetSlot);var changedValue=fluid.NO_VALUE;if(sourceCode==="primitive"){if(!fluid.model.isSameValue(targetSlot,source)){changedValue=source;++options.unchanged}}else if(targetCode!==sourceCode||sourceCode==="array"&&source.length!==targetSlot.length){changedValue=fluid.freshContainer(source)}if(changedValue!==fluid.NO_VALUE){target[name]=changedValue;if(options.changeMap){fluid.model.setChangedPath(options,segs,options.inverse?"DELETE":"ADD")}}if(sourceCode!=="primitive"){fluid.model.fetchChangeChildren(target[name],i+1,segs,source,options)}};fluid.model.stepTargetAccess=function(target,type,segs,startpos,endpos,options){for(var i=startpos;i<endpos;++i){if(!target){continue}var oldTrunk=target[segs[i]];target=fluid.model.traverseWithStrategy(target,segs,i,options[type==="ADD"?"resolverSetConfig":"resolverGetConfig"],segs.length-i-1);if(oldTrunk!==target&&options.changeMap){fluid.model.setChangedPath(options,segs.slice(0,i+1),"ADD")}}return{root:target,last:segs[endpos]}};fluid.model.defaultAccessorConfig=function(options){options=options||{};options.resolverSetConfig=options.resolverSetConfig||fluid.model.escapedSetConfig;options.resolverGetConfig=options.resolverGetConfig||fluid.model.escapedGetConfig;return options};fluid.model.applyHolderChangeRequest=function(holder,request,options){options=fluid.model.defaultAccessorConfig(options);options.deltaMap=options.changeMap?{}:null;options.deltas=0;var length=request.segs.length;var pen,atRoot=length===0;if(atRoot){pen={root:holder,last:"model"}}else{if(!holder.model&&request.type!=="DELETE"){holder.model={};fluid.model.setChangedPath(options,[],options.inverse?"DELETE":"ADD")}pen=fluid.model.stepTargetAccess(holder.model,request.type,request.segs,0,length-1,options)}if(request.type==="ADD"){var value=request.value;var segs=fluid.makeArray(request.segs);fluid.model.applyChangeStrategy(pen.root,pen.last,length-1,segs,value,options,atRoot)}else if(request.type==="DELETE"){if(pen.root&&pen.root[pen.last]!==undefined){delete pen.root[pen.last];if(options.changeMap){fluid.model.setChangedPath(options,request.segs,"DELETE")}}}else{fluid.fail("Unrecognised change type of "+request.type)}return options.deltas?options.deltaMap:null};fluid.model.diff=function(modela,modelb,options){options=options||{changes:0,unchanged:0,changeMap:{}};var typea=fluid.typeCode(modela);var typeb=fluid.typeCode(modelb);var togo;if(typea==="primitive"&&typeb==="primitive"){togo=fluid.model.isSameValue(modela,modelb)}else if(typea==="primitive"^typeb==="primitive"){togo=false}else{var holderb={model:fluid.copy(modelb)};options.inverse=true;fluid.model.applyHolderChangeRequest(holderb,{value:modela,segs:[],type:"ADD"},options);var holdera={model:fluid.copy(modela)};options.inverse=false;fluid.model.applyHolderChangeRequest(holdera,{value:modelb,segs:[],type:"ADD"},options);togo=options.changes===0}if(togo===false&&options.changes===0){options.changes=1;options.changeMap=modelb===undefined?"DELETE":"ADD"}else if(togo===true&&options.unchanged===0){options.unchanged=1}return togo};fluid.outputWildcardMatches=function(matches,outSegs,root){fluid.each(root,(function(value,key){matches.push(outSegs.concat(key))}))};fluid.matchChanges=function(changeMap,specSegs,newHolder,oldHolder){var newRoot=newHolder.model;var oldRoot=oldHolder.model;var map=changeMap;var outSegs=["model"];var wildcard=false;var togo=[];for(var i=0;i<specSegs.length;++i){var seg=specSegs[i];if(seg==="*"){if(i===specSegs.length-1){wildcard=true}else{fluid.fail("Wildcard specification in modelChanged listener is only supported for the final path segment: "+specSegs.join("."))}}else{outSegs.push(seg);map=fluid.isPrimitive(map)?map:map[seg];newRoot=newRoot?newRoot[seg]:undefined;oldRoot=oldRoot?oldRoot[seg]:undefined}}if(map){if(wildcard){if(typeof map==="string"){var allKeys=fluid.extend({},oldRoot,newRoot);fluid.outputWildcardMatches(togo,outSegs,allKeys)}else{fluid.outputWildcardMatches(togo,outSegs,map)}}else{togo.push(outSegs)}}return togo};fluid.storeExternalChange=function(transRec,applier,invalidPath,spec,args){var pathString=applier.composeSegments.apply(null,invalidPath);var keySegs=[applier.holder.id,spec.listenerId,spec.wildcard?pathString:""];var keyString=keySegs.join("|");transRec.externalChanges[keyString]={listener:spec.listener,namespace:spec.namespace,priority:spec.priority,args:args}};fluid.notifyModelChanges=function(listeners,changeMap,newHolder,oldHolder,changeRequest,transaction,applier,that){if(!listeners){return}var transRec=fluid.getModelTransactionRec(that,transaction.id);for(var i=0;i<listeners.length;++i){var spec=listeners[i];var multiplePaths=spec.segsArray.length>1;for(var j=0;j<spec.segsArray.length;++j){var invalidPaths=fluid.matchChanges(changeMap,spec.segsArray[j],newHolder,oldHolder);for(var k=0;k<invalidPaths.length;++k){if(applier.destroyed){return}var invalidPath=invalidPaths[k];spec.listener=fluid.event.resolveListener(spec.listener);var args=[multiplePaths?newHolder.model:fluid.model.getSimple(newHolder,invalidPath),multiplePaths?oldHolder.model:fluid.model.getSimple(oldHolder,invalidPath),multiplePaths?[]:invalidPath.slice(1),changeRequest,transaction,applier];if(!spec.isRelay){var isNull=fluid.model.diff(args[0],args[1]);if(isNull){continue}var sourceExcluded=fluid.isExcludedChangeSource(transaction,spec);if(sourceExcluded){continue}}if(transRec&&!spec.isRelay&&spec.transactional){fluid.storeExternalChange(transRec,applier,invalidPath,spec,args)}else{spec.listener.apply(null,args)}}}}};fluid.bindELMethods=function(applier){applier.parseEL=function(EL){return fluid.model.pathToSegments(EL,applier.options.resolverSetConfig)};applier.composeSegments=function(){return applier.options.resolverSetConfig.parser.compose.apply(null,arguments)}};fluid.emptyHolder=fluid.freezeRecursive({model:undefined});fluid.preFireChangeRequest=function(applier,changeRequest){if(!changeRequest.type){changeRequest.type="ADD"}changeRequest.segs=changeRequest.segs||applier.parseEL(changeRequest.path)};fluid.bindRequestChange=function(that){that.change=function(path,value,type,source){var changeRequest={path:path,value:value,type:type,source:source};that.fireChangeRequest(changeRequest)}};fluid.mergeChangeSources=function(target,globalSources){if(fluid.isPlainObject(globalSources,true)){fluid.extend(target,globalSources)}else{fluid.each(fluid.makeArray(globalSources),(function(globalSource){target[globalSource]=true}))}};fluid.ChangeApplier=function(){};fluid.makeHolderChangeApplier=function(holder,options){options=fluid.model.defaultAccessorConfig(options);var applierId=fluid.allocateGuid();var that=new fluid.ChangeApplier;var name=fluid.isComponent(holder)?"ChangeApplier for component "+fluid.dumpThat(holder):"ChangeApplier with id "+applierId;$.extend(that,{applierId:applierId,holder:holder,listeners:fluid.makeEventFirer({name:"Internal change listeners for "+name}),transListeners:fluid.makeEventFirer({name:"External change listeners for "+name}),options:options,modelChanged:{},resourceMap:[],earlyModelResolved:fluid.makeEventFirer({name:"earlyModelResolved event for "+name}),preCommit:fluid.makeEventFirer({name:"preCommit event for "+name}),postCommit:fluid.makeEventFirer({name:"postCommit event for "+name})});that.destroy=function(){that.preCommit.destroy();that.postCommit.destroy();that.destroyed=true};that.modelChanged.addListener=function(spec,listener,namespace,softNamespace){if(typeof spec==="string"){spec={path:spec}}else{spec=fluid.copy(spec)}spec.listenerId=spec.listenerId||fluid.allocateGuid();spec.namespace=namespace;spec.softNamespace=softNamespace;if(typeof listener==="string"){listener={globalName:listener}}spec.listener=listener;if(spec.transactional!==false){spec.transactional=true}if(!spec.segsArray){if(spec.path!==undefined){spec.segs=spec.segs||that.parseEL(spec.path)}spec.segsArray=[spec.segs]}if(!spec.isRelay){fluid.parseSourceExclusionSpec(spec,spec);spec.wildcard=spec.segsArray.some((function(segs){return segs.includes("*")}));if(spec.wildcard&&spec.segsArray.length>1){fluid.fail("Error in model listener specification ",spec," - you may not supply a wildcard pattern as one of a set of multiple paths to be matched")}}var firer=that[spec.transactional?"transListeners":"listeners"];firer.addListener(spec);return spec};that.modelChanged.removeListener=function(listener){that.listeners.removeListener(listener);that.transListeners.removeListener(listener)};that.fireChangeRequest=function(changeRequest){var initTransaction=fluid.findInitModelTransaction(holder);if(initTransaction){initTransaction.transaction.fireChangeRequest(changeRequest)}else{var ation=that.initiate("local",changeRequest.source);ation.fireChangeRequest(changeRequest);ation.commit()}};that.initiate=function(localSource,globalSources,transactionId){localSource=globalSources==="init"?null:localSource||"local";var defeatPost=localSource==="relay"||globalSources==="init";var trans={instanceId:fluid.allocateGuid(),id:transactionId||fluid.allocateGuid(),changeRecord:{resolverSetConfig:options.resolverSetConfig,resolverGetConfig:options.resolverGetConfig},reset:function(){trans.oldHolder=holder;trans.newHolder={model:fluid.copy(holder.model)};trans.changeRecord.changes=0;trans.changeRecord.unchanged=0;trans.changeRecord.changeMap={}},commit:function(code){if(code!=="relay"){that.preCommit.fire(trans,that,code)}if(trans.changeRecord.changes>0){var oldHolder={model:holder.model};holder.model=trans.newHolder.model;fluid.notifyModelChanges(that.transListeners.sortedListeners,trans.changeRecord.changeMap,holder,oldHolder,null,trans,that,holder)}if(!defeatPost&&code!=="relay"){that.postCommit.fire(trans,that,code)}},fireChangeRequest:function(changeRequest){fluid.preFireChangeRequest(that,changeRequest);changeRequest.transactionId=trans.id;var deltaMap=fluid.model.applyHolderChangeRequest(trans.newHolder,changeRequest,trans.changeRecord);fluid.notifyModelChanges(that.listeners.sortedListeners,deltaMap,trans.newHolder,holder,changeRequest,trans,that,holder)},hasChangeSource:function(source){return trans.fullSources[source]}};var transRec=fluid.getModelTransactionRec(holder,trans.id);if(transRec){fluid.mergeChangeSources(transRec.sources,globalSources);trans.sources=transRec.sources;trans.fullSources=Object.create(transRec.sources);if(localSource){trans.fullSources[localSource]=true}}trans.reset();fluid.bindRequestChange(trans);return trans};fluid.bindRequestChange(that);fluid.bindELMethods(that);return that};fluid.modelPairToChanges=function(value,oldValue,changePathPrefix){changePathPrefix=changePathPrefix||"";var diffOptions={changes:0,unchanged:0,changeMap:{}};fluid.model.diff(oldValue,value,diffOptions);var changes=[];fluid.modelPairToChangesImpl(value,fluid.pathUtil.parseEL(changePathPrefix),diffOptions.changeMap,[],changes);return changes};fluid.modelPairToChangesImpl=function(value,changePathPrefixSegs,changeMap,changeSegs,changes){if(changeMap==="ADD"){changes.push({path:changePathPrefixSegs,value:value,type:"ADD"})}else if(changeMap==="DELETE"){changes.push({path:changePathPrefixSegs,value:null,type:"DELETE"})}else if(fluid.isPlainObject(changeMap,true)){fluid.each(changeMap,(function(change,seg){var currentChangeSegs=changeSegs.concat([seg]);if(change==="ADD"){changes.push({path:changePathPrefixSegs.concat(currentChangeSegs),value:fluid.get(value,currentChangeSegs),type:"ADD"})}else if(change==="DELETE"){changes.push({path:changePathPrefixSegs.concat(currentChangeSegs),value:null,type:"DELETE"})}else if(fluid.isPlainObject(change,true)){fluid.modelPairToChangesImpl(value,changePathPrefixSegs,change,currentChangeSegs,changes)}}))}};"use strict";fluid.defaults("fluid.remoteModelComponent",{gradeNames:["fluid.modelComponent"],events:{afterFetch:null,onFetch:null,onFetchError:null,afterWrite:null,onWrite:null,onWriteError:null},members:{pendingRequests:{write:null,fetch:null}},model:{local:{},remote:{},requestInFlight:false},modelListeners:{requestInFlight:{listener:"fluid.remoteModelComponent.launchPendingRequest",args:["{that}"]}},listeners:{"afterFetch.updateModel":{listener:"fluid.remoteModelComponent.updateModelFromFetch",args:["{that}","{arguments}.0"],priority:"before:unblock"},"afterFetch.unblock":{listener:"fluid.remoteModelComponent.unblockFetchReq",args:["{that}"]},"onFetchError.unblock":{listener:"fluid.remoteModelComponent.unblockFetchReq",args:["{that}"]},"afterWrite.updateRemoteModel":{listener:"fluid.remoteModelComponent.updateRemoteFromLocal",args:["{that}"]},"afterWrite.unblock":{changePath:"requestInFlight",value:false,priority:"after:updateRemoteModel"},"onWriteError.unblock":{changePath:"requestInFlight",value:false}},invokers:{fetch:{funcName:"fluid.remoteModelComponent.fetch",args:["{that}"]},fetchImpl:"fluid.notImplemented",write:{funcName:"fluid.remoteModelComponent.write",args:["{that}"]},writeImpl:"fluid.notImplemented"}});fluid.remoteModelComponent.launchPendingRequest=function(that){if(!that.model.requestInFlight){if(that.pendingRequests.fetch){that.fetch()}else if(that.pendingRequests.write){that.write()}}};fluid.remoteModelComponent.updateModelFromFetch=function(that,fetchedModel){var remoteChanges=fluid.modelPairToChanges(fetchedModel,that.model.remote,"local");var localChanges=fluid.modelPairToChanges(that.model.local,that.model.remote,"local");var changes=remoteChanges.concat(localChanges);var transaction=that.applier.initiate();transaction.fireChangeRequest({path:"local",type:"DELETE"});transaction.change("local",that.model.remote);transaction.fireChangeRequest({path:"remote",type:"DELETE"});transaction.change("remote",fetchedModel);fluid.fireChanges(transaction,changes);transaction.commit()};fluid.remoteModelComponent.updateRemoteFromLocal=function(that){fluid.replaceModelValue(that.applier,"remote",that.model.local)};fluid.remoteModelComponent.makeSequenceStrategy=function(payload){return{invokeNext:function(that){var lisrec=that.sources[that.index];lisrec.listener=fluid.event.resolveListener(lisrec.listener);var value=lisrec.listener.apply(null,[payload,that.options]);return value},resolveResult:function(){return payload}}};fluid.remoteModelComponent.makeSequence=function(listeners,payload,options){var sequencer=fluid.promise.makeSequencer(listeners,options,fluid.remoteModelComponent.makeSequenceStrategy(payload));fluid.promise.resumeSequence(sequencer);return sequencer};fluid.remoteModelComponent.fireEventSequence=function(event,payload,options){var listeners=fluid.makeArray(event.sortedListeners);var sequence=fluid.remoteModelComponent.makeSequence(listeners,payload,options);return sequence.promise};fluid.remoteModelComponent.fetch=function(that){var promise=fluid.promise();var activePromise;if(that.pendingRequests.fetch){activePromise=that.pendingRequests.fetch;fluid.promise.follow(activePromise,promise)}else{activePromise=promise;that.pendingRequests.fetch=promise}if(!that.model.requestInFlight){var onFetchSeqPromise=fluid.remoteModelComponent.fireEventSequence(that.events.onFetch);onFetchSeqPromise.then((function(){that.applier.change("requestInFlight",true);var reqPromise=that.fetchImpl();reqPromise.then((function(data){var afterFetchSeqPromise=fluid.remoteModelComponent.fireEventSequence(that.events.afterFetch,data);fluid.promise.follow(afterFetchSeqPromise,activePromise)}),that.events.onFetchError.fire)}),that.events.onFetchError.fire)}return promise};fluid.remoteModelComponent.unblockFetchReq=function(that){that.pendingRequests.fetch=null;that.applier.change("requestInFlight",false)};fluid.remoteModelComponent.write=function(that){var promise=fluid.promise();var activePromise;if(that.pendingRequests.write){activePromise=that.pendingRequests.write;fluid.promise.follow(that.pendingRequests.write,promise)}else{activePromise=promise}if(that.model.requestInFlight){that.pendingRequests.write=activePromise}else{var onWriteSeqPromise=fluid.remoteModelComponent.fireEventSequence(that.events.onWrite);onWriteSeqPromise.then((function(){that.applier.change("requestInFlight",true);that.pendingRequests.write=null;if(fluid.model.diff(that.model.local,that.model.remote)){var afterWriteSeqPromise=fluid.remoteModelComponent.fireEventSequence(that.events.afterWrite,that.model.local);fluid.promise.follow(afterWriteSeqPromise,activePromise)}else{var reqPromise=that.writeImpl(that.model.local);reqPromise.then((function(data){var afterWriteSeqPromise=fluid.remoteModelComponent.fireEventSequence(that.events.afterWrite,data);fluid.promise.follow(afterWriteSeqPromise,activePromise)}),that.events.onWriteError.fire)}}),that.events.onWriteError.fire)}return promise};"use strict";fluid.registerNamespace("fluid.model.transform");fluid.defaults("fluid.transformFunction",{gradeNames:"fluid.function"});fluid.defaults("fluid.standardInputTransformFunction",{gradeNames:"fluid.transformFunction"});fluid.defaults("fluid.standardOutputTransformFunction",{gradeNames:"fluid.transformFunction"});fluid.defaults("fluid.multiInputTransformFunction",{gradeNames:"fluid.transformFunction"});fluid.defaults("fluid.standardTransformFunction",{gradeNames:["fluid.standardInputTransformFunction","fluid.standardOutputTransformFunction"]});fluid.defaults("fluid.lens",{gradeNames:"fluid.transformFunction",invertConfiguration:null});fluid.model.transform.pathToRule=function(inputPath){return{transform:{type:"fluid.transforms.value",inputPath:inputPath}}};fluid.model.transform.literalValueToRule=function(input){return{transform:{type:"fluid.transforms.literalValue",input:input}}};fluid.model.composePaths=function(prefix,suffix){prefix=prefix===0?"0":prefix||"";suffix=suffix===0?"0":suffix||"";return!prefix?suffix:!suffix?prefix:prefix+"."+suffix};fluid.model.transform.accumulateInputPath=function(inputPath,transformer,paths){if(inputPath!==undefined){paths.push(fluid.model.composePaths(transformer.inputPrefix,inputPath))}};fluid.model.transform.accumulateStandardInputPath=function(input,transformSpec,transformer,paths){fluid.model.transform.getValue(undefined,transformSpec[input],transformer);fluid.model.transform.accumulateInputPath(transformSpec[input+"Path"],transformer,paths)};fluid.model.transform.accumulateMultiInputPaths=function(inputVariables,transformSpec,transformer,paths){fluid.each(inputVariables,(function(v,k){fluid.model.transform.accumulateStandardInputPath(k,transformSpec,transformer,paths)}))};fluid.model.transform.getValue=function(inputPath,value,transformer){var togo;if(inputPath!==undefined){togo=fluid.get(transformer.source,fluid.model.composePaths(transformer.inputPrefix,inputPath),transformer.resolverGetConfig)}if(togo===undefined){togo=fluid.isPrimitive(value)?value:"literalValue"in value?value.literalValue:value.transform===undefined?value:transformer.expand(value)}return togo};fluid.model.transform.NONDEFAULT_OUTPUT_PATH_RETURN={};fluid.model.transform.setValue=function(userOutputPath,value,transformer){var toset=fluid.copy(value);var outputPath=fluid.model.composePaths(transformer.outputPrefix,userOutputPath);if(toset!==undefined){transformer.applier.change(outputPath,toset)}return userOutputPath?fluid.model.transform.NONDEFAULT_OUTPUT_PATH_RETURN:toset};fluid.model.transform.resolveParam=function(transformSpec,transformer,key,def){var val=fluid.model.transform.getValue(transformSpec[key+"Path"],transformSpec[key],transformer);return val!==undefined?val:def};fluid.model.transform.matchValue=function(expected,actual,partialMatches){var stats={changes:0,unchanged:0,changeMap:{}};fluid.model.diff(expected,actual,stats);return stats.unchanged===0?0:partialMatches?0xffffff000000-16777216*stats.changes+stats.unchanged:stats.changes?0:0xffffff000000+stats.unchanged};fluid.model.transform.invertPaths=function(transformSpec,transformer){var oldOutput=fluid.model.composePaths(transformer.outputPrefix,transformSpec.outputPath);transformSpec.outputPath=fluid.model.composePaths(transformer.inputPrefix,transformSpec.inputPath);transformSpec.inputPath=oldOutput;return transformSpec};fluid.model.transform.prefixApplier=function(transformSpec,transformer){if(transformSpec.inputPrefix){transformer.inputPrefixOp.push(transformSpec.inputPrefix)}if(transformSpec.outputPrefix){transformer.outputPrefixOp.push(transformSpec.outputPrefix)}transformer.expand(transformSpec.input);if(transformSpec.inputPrefix){transformer.inputPrefixOp.pop()}if(transformSpec.outputPrefix){transformer.outputPrefixOp.pop()}};fluid.defaults("fluid.model.transform.prefixApplier",{gradeNames:["fluid.transformFunction"]});fluid.model.makePathStack=function(transform,prefixName){var stack=transform[prefixName+"Stack"]=[];transform[prefixName]="";return{push:function(prefix){var newPath=fluid.model.composePaths(transform[prefixName],prefix);stack.push(transform[prefixName]);transform[prefixName]=newPath},pop:function(){transform[prefixName]=stack.pop()}}};fluid.model.transform.doTransform=function(transformSpec,transformer,transformOpts){var expdef=transformOpts.defaults;var transformFn=fluid.getGlobalValue(transformOpts.typeName);if(typeof transformFn!=="function"){fluid.fail("Transformation record specifies transformation function with name "+transformSpec.type+" which is not a function - ",transformFn)}if(!fluid.hasGrade(expdef,"fluid.transformFunction")){expdef=fluid.defaults("fluid.standardTransformFunction")}var transformArgs=[transformSpec,transformer];if(fluid.hasGrade(expdef,"fluid.multiInputTransformFunction")){var inputs={};fluid.each(expdef.inputVariables,(function(v,k){inputs[k]=function(){var input=fluid.model.transform.getValue(transformSpec[k+"Path"],transformSpec[k],transformer);input=input===undefined&&v!==null?v:input;return input}}));transformArgs.unshift(inputs)}if(fluid.hasGrade(expdef,"fluid.standardInputTransformFunction")){if(!("input"in transformSpec)&&!("inputPath"in transformSpec)){fluid.fail('Error in transform specification. Either "input" or "inputPath" must be specified for a standardInputTransformFunction: received ',transformSpec)}var expanded=fluid.model.transform.getValue(transformSpec.inputPath,transformSpec.input,transformer);transformArgs.unshift(expanded);if(expanded===undefined){return undefined}}var transformed=transformFn.apply(null,transformArgs);if(fluid.hasGrade(expdef,"fluid.standardOutputTransformFunction")){var outputPath=transformSpec.outputPath!==undefined?transformSpec.outputPath:transformOpts.doOutput?"":undefined;if(outputPath!==undefined&&transformed!==undefined){fluid.model.transform.setValue(transformSpec.outputPath,transformed,transformer);transformed=undefined}}return transformed};var globalAccept=[];fluid.registerNamespace("fluid.pathUtil");fluid.pathUtil.getPathSegment=function(path,i){fluid.pathUtil.getPathSegmentImpl(globalAccept,path,i);return globalAccept[0]};fluid.pathUtil.getHeadPath=function(path){return fluid.pathUtil.getPathSegment(path,0)};fluid.pathUtil.getFromHeadPath=function(path){var firstdot=fluid.pathUtil.getPathSegmentImpl(null,path,0);return firstdot===path.length?"":path.substring(firstdot+1)};fluid.pathUtil.matchPath=function(spec,path,exact){var togo=[];while(true){if(path===""^spec===""&&exact){return null}if(!spec||!path){break}var spechead=fluid.pathUtil.getHeadPath(spec);var pathhead=fluid.pathUtil.getHeadPath(path);if(spechead!=="*"&&spechead!==pathhead){return null}togo.push(pathhead);spec=fluid.pathUtil.getFromHeadPath(spec);path=fluid.pathUtil.getFromHeadPath(path)}return togo};fluid.model.transform.expandWildcards=function(transformer,source){fluid.each(source,(function(value,key){var q=transformer.queuedTransforms;transformer.pathOp.push(fluid.pathUtil.escapeSegment(key.toString()));for(var i=0;i<q.length;++i){if(fluid.pathUtil.matchPath(q[i].matchPath,transformer.path,true)){var esCopy=fluid.copy(q[i].transformSpec);if(esCopy.inputPath===undefined||fluid.model.transform.hasWildcard(esCopy.inputPath)){esCopy.inputPath=""}transformer.inputPrefixOp.push(transformer.path);transformer.outputPrefixOp.push(transformer.path);var transformOpts=fluid.model.transform.lookupType(esCopy.type);var result=fluid.model.transform.doTransform(esCopy,transformer,transformOpts);if(result!==undefined){fluid.model.transform.setValue(null,result,transformer)}transformer.outputPrefixOp.pop();transformer.inputPrefixOp.pop()}}if(!fluid.isPrimitive(value)){fluid.model.transform.expandWildcards(transformer,value)}transformer.pathOp.pop()}))};fluid.model.transform.hasWildcard=function(path){return typeof path==="string"&&path.indexOf("*")!==-1};fluid.model.transform.maybePushWildcard=function(transformSpec,transformer){var hw=fluid.model.transform.hasWildcard;var matchPath;if(hw(transformSpec.inputPath)){matchPath=fluid.model.composePaths(transformer.inputPrefix,transformSpec.inputPath)}else if(hw(transformer.outputPrefix)||hw(transformSpec.outputPath)){matchPath=fluid.model.composePaths(transformer.outputPrefix,transformSpec.outputPath)}if(matchPath){transformer.queuedTransforms.push({transformSpec:transformSpec,outputPrefix:transformer.outputPrefix,inputPrefix:transformer.inputPrefix,matchPath:matchPath});return true}return false};fluid.model.sortByKeyLength=function(inObject){var keys=fluid.keys(inObject);return keys.sort(fluid.compareStringLength(true))};fluid.model.transform.handleTransformStrategy=function(transformSpec,transformer,transformOpts){if(fluid.model.transform.maybePushWildcard(transformSpec,transformer)){return}else{return fluid.model.transform.doTransform(transformSpec,transformer,transformOpts)}};fluid.model.transform.handleInvertStrategy=function(transformSpec,transformer,transformOpts){transformSpec=fluid.copy(transformSpec);if(fluid.hasGrade(transformOpts.defaults,"fluid.standardTransformFunction")){transformSpec=fluid.model.transform.invertPaths(transformSpec,transformer)}var invertor=transformOpts.defaults&&transformOpts.defaults.invertConfiguration;if(invertor){var inverted=fluid.invokeGlobalFunction(invertor,[transformSpec,transformer]);transformer.inverted.push(inverted)}else{transformer.inverted.push(fluid.model.transform.uninvertibleTransform)}};fluid.model.transform.handleCollectStrategy=function(transformSpec,transformer,transformOpts){var defaults=transformOpts.defaults;var standardInput=fluid.hasGrade(defaults,"fluid.standardInputTransformFunction");var multiInput=fluid.hasGrade(defaults,"fluid.multiInputTransformFunction");if(standardInput){fluid.model.transform.accumulateStandardInputPath("input",transformSpec,transformer,transformer.inputPaths)}if(multiInput){fluid.model.transform.accumulateMultiInputPaths(defaults.inputVariables,transformSpec,transformer,transformer.inputPaths)}var collector=defaults.collectInputPaths;if(collector){var collected=fluid.makeArray(fluid.invokeGlobalFunction(collector,[transformSpec,transformer]));Array.prototype.push.apply(transformer.inputPaths,collected)}};fluid.model.transform.lookupType=function(typeName,transformSpec){if(!typeName){fluid.fail("Transformation record is missing a type name: ",transformSpec)}if(typeName.indexOf(".")===-1){typeName="fluid.transforms."+typeName}var defaults=fluid.defaults(typeName);return{defaults:defaults,typeName:typeName}};fluid.model.transform.processRule=function(rule,transformer){if(typeof rule==="string"){rule=fluid.model.transform.pathToRule(rule)}else if(rule.literalValue!==undefined){rule=fluid.model.transform.literalValueToRule(rule.literalValue)}var togo;if(rule.transform){var transformSpec,transformOpts;if(fluid.isArrayable(rule.transform)){var transforms=rule.transform;togo=undefined;for(var i=0;i<transforms.length;++i){transformSpec=transforms[i];transformOpts=fluid.model.transform.lookupType(transformSpec.type);transformer.transformHandler(transformSpec,transformer,transformOpts)}}else{transformSpec=rule.transform;transformOpts=fluid.model.transform.lookupType(transformSpec.type);togo=transformer.transformHandler(transformSpec,transformer,transformOpts)}}if(fluid.isArrayable(rule)){transformer.collectedFlatSchemaOpts=transformer.collectedFlatSchemaOpts||{};transformer.collectedFlatSchemaOpts[transformer.outputPrefix]="array"}fluid.each(rule,(function(value,key){if(key!=="transform"){transformer.outputPrefixOp.push(key);var togo=transformer.expand(value,transformer);if(togo!==undefined){fluid.model.transform.setValue(null,togo,transformer);togo=undefined}transformer.outputPrefixOp.pop()}}));return togo};fluid.model.transform.makeStrategy=function(transformer,handleFn,transformFn){transformFn=transformFn||fluid.model.transform.processRule;transformer.expand=function(rules){return transformFn(rules,transformer)};transformer.outputPrefixOp=fluid.model.makePathStack(transformer,"outputPrefix");transformer.inputPrefixOp=fluid.model.makePathStack(transformer,"inputPrefix");transformer.transformHandler=handleFn};fluid.model.transform.uninvertibleTransform=Object.freeze({});fluid.model.transform.invertConfiguration=function(rules){var transformer={inverted:[]};fluid.model.transform.makeStrategy(transformer,fluid.model.transform.handleInvertStrategy);transformer.expand(rules);var invertible=transformer.inverted.indexOf(fluid.model.transform.uninvertibleTransform)===-1;return invertible?{transform:transformer.inverted}:fluid.model.transform.uninvertibleTransform};fluid.model.transform.collectInputPaths=function(rules){var transformer={inputPaths:[]};fluid.model.transform.makeStrategy(transformer,fluid.model.transform.handleCollectStrategy);transformer.expand(rules);var inputPathHash=fluid.arrayToHash(transformer.inputPaths);return Object.keys(inputPathHash)};fluid.model.transform.flatSchemaStrategy=function(flatSchema,getConfig){var keys=fluid.model.sortByKeyLength(flatSchema);return function(root,segment,index,segs){var path=getConfig.parser.compose.apply(null,segs.slice(0,index));for(var i=0;i<keys.length;++i){var key=keys[i];if(fluid.pathUtil.matchPath(key,path,true)!==null){return flatSchema[key]}}}};fluid.model.transform.defaultSchemaValue=function(schemaValue){var type=fluid.isPrimitive(schemaValue)?schemaValue:schemaValue.type;return type==="array"?[]:{}};fluid.model.transform.isomorphicSchemaStrategy=function(source,getConfig){return function(root,segment,index,segs){var existing=fluid.get(source,segs.slice(0,index),getConfig);return fluid.isArrayable(existing)?"array":"object"}};fluid.model.transform.decodeStrategy=function(source,options,getConfig){if(options.isomorphic){return fluid.model.transform.isomorphicSchemaStrategy(source,getConfig)}else if(options.flatSchema){return fluid.model.transform.flatSchemaStrategy(options.flatSchema,getConfig)}};fluid.model.transform.schemaToCreatorStrategy=function(strategy){return function(root,segment,index,segs){if(root[segment]===undefined){var schemaValue=strategy(root,segment,index,segs);root[segment]=fluid.model.transform.defaultSchemaValue(schemaValue);return root[segment]}}};fluid.model.transform.sequence=function(source,rules,options){for(var i=0;i<rules.length;++i){source=fluid.model.transform(source,rules[i],options)}return source};fluid.model.compareByPathLength=function(changea,changeb){var pdiff=changea.path.length-changeb.path.length;return pdiff===0?changea.sequence-changeb.sequence:pdiff};fluid.model.fireSortedChanges=function(changes,applier){changes.sort(fluid.model.compareByPathLength);fluid.fireChanges(applier,changes)};fluid.model.transformWithRules=function(source,rules,options){options=options||{};var getConfig=fluid.model.escapedGetConfig;var setConfig=fluid.model.escapedSetConfig;var schemaStrategy=fluid.model.transform.decodeStrategy(source,options,getConfig);var transformer={source:source,target:{model:schemaStrategy?fluid.model.transform.defaultSchemaValue(schemaStrategy(null,"",0,[""])):{}},oldSource:options.oldSource,oldTarget:options.oldTarget,resolverGetConfig:getConfig,resolverSetConfig:setConfig,collectedFlatSchemaOpts:undefined,queuedChanges:[],queuedTransforms:[]};fluid.model.transform.makeStrategy(transformer,fluid.model.transform.handleTransformStrategy);transformer.applier={fireChangeRequest:function(changeRequest){changeRequest.sequence=transformer.queuedChanges.length;transformer.queuedChanges.push(changeRequest)}};fluid.bindRequestChange(transformer.applier);transformer.expand(rules);var rootSetConfig=fluid.copy(setConfig);if(transformer.collectedFlatSchemaOpts!==undefined){$.extend(transformer.collectedFlatSchemaOpts,options.flatSchema);schemaStrategy=fluid.model.transform.flatSchemaStrategy(transformer.collectedFlatSchemaOpts,getConfig)}rootSetConfig.strategies=[fluid.model.defaultFetchStrategy,schemaStrategy?fluid.model.transform.schemaToCreatorStrategy(schemaStrategy):fluid.model.defaultCreatorStrategy];transformer.finalApplier=options.finalApplier||fluid.makeHolderChangeApplier(transformer.target,{resolverSetConfig:rootSetConfig});if(transformer.queuedTransforms.length>0){transformer.typeStack=[];transformer.pathOp=fluid.model.makePathStack(transformer,"path");fluid.model.transform.expandWildcards(transformer,source)}fluid.model.fireSortedChanges(transformer.queuedChanges,transformer.finalApplier);return transformer.target.model};$.extend(fluid.model.transformWithRules,fluid.model.transform);fluid.model.transform=fluid.model.transformWithRules;fluid.transformOne=function(rules){return{transformOptions:{transformer:"fluid.model.transformWithRules",config:rules}}};fluid.transformMany=function(rules){return{transformOptions:{transformer:"fluid.model.transform.sequence",config:rules}}};"use strict";fluid.registerNamespace("fluid.model.transform");fluid.registerNamespace("fluid.transforms");fluid.defaults("fluid.transforms.value",{gradeNames:"fluid.standardTransformFunction",invertConfiguration:"fluid.identity"});fluid.transforms.value=fluid.identity;fluid.transforms.identity=fluid.transforms.value;fluid.defaults("fluid.transforms.identity",{gradeNames:"fluid.transforms.value"});fluid.transforms.invertToIdentity=function(transformSpec){transformSpec.type="fluid.transforms.identity";return transformSpec};fluid.defaults("fluid.transforms.literalValue",{gradeNames:"fluid.standardOutputTransformFunction"});fluid.transforms.literalValue=function(transformSpec){return transformSpec.input};fluid.defaults("fluid.transforms.stringToNumber",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.stringToNumber.invert"});fluid.transforms.stringToNumber=function(value){var newValue=Number(value);return isNaN(newValue)?undefined:newValue};fluid.transforms.stringToNumber.invert=function(transformSpec){transformSpec.type="fluid.transforms.numberToString";return transformSpec};fluid.defaults("fluid.transforms.numberToString",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.numberToString.invert"});fluid.transforms.numberToString=function(value,transformSpec){if(typeof value==="number"){if(typeof transformSpec.scale==="number"&&!isNaN(transformSpec.scale)){var rounded=fluid.roundToDecimal(value,transformSpec.scale,transformSpec.method);return rounded.toString()}else{return value.toString()}}};fluid.transforms.numberToString.invert=function(transformSpec){transformSpec.type="fluid.transforms.stringToNumber";return transformSpec};fluid.defaults("fluid.transforms.count",{gradeNames:"fluid.standardTransformFunction"});fluid.transforms.count=function(value){return fluid.makeArray(value).length};fluid.defaults("fluid.transforms.round",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.invertToIdentity"});fluid.transforms.round=function(value,transformSpec){return fluid.roundToDecimal(value,transformSpec.scale,transformSpec.method)};fluid.defaults("fluid.transforms.delete",{gradeNames:"fluid.transformFunction"});fluid.transforms["delete"]=function(transformSpec,transformer){var outputPath=fluid.model.composePaths(transformer.outputPrefix,transformSpec.outputPath);transformer.applier.change(outputPath,null,"DELETE")};fluid.defaults("fluid.transforms.firstValue",{gradeNames:"fluid.standardOutputTransformFunction"});fluid.transforms.firstValue=function(transformSpec,transformer){if(!transformSpec.values||!transformSpec.values.length){fluid.fail('firstValue transformer requires an array of values at path named "values", supplied',transformSpec)}for(var i=0;i<transformSpec.values.length;i++){var value=transformSpec.values[i];var expanded=transformer.expand(value);if(expanded!==undefined){return expanded}}};fluid.defaults("fluid.transforms.linearScale",{gradeNames:["fluid.multiInputTransformFunction","fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.linearScale.invert",inputVariables:{factor:1,offset:0}});fluid.transforms.linearScale=function(input,extraInputs){var factor=extraInputs.factor();var offset=extraInputs.offset();if(typeof input!=="number"||typeof factor!=="number"||typeof offset!=="number"){return undefined}return input*factor+offset};fluid.transforms.linearScale.invert=function(transformSpec){delete transformSpec.factorPath;delete transformSpec.offsetPath;if(transformSpec.factor!==undefined){transformSpec.factor=transformSpec.factor===0?0:1/transformSpec.factor}if(transformSpec.offset!==undefined){transformSpec.offset=-transformSpec.offset*(transformSpec.factor!==undefined?transformSpec.factor:1)}return transformSpec};fluid.defaults("fluid.transforms.binaryOp",{gradeNames:["fluid.multiInputTransformFunction","fluid.standardOutputTransformFunction"],inputVariables:{left:null,right:null}});fluid.transforms.binaryLookup={"===":function(a,b){return fluid.model.isSameValue(a,b)},"!==":function(a,b){return!fluid.model.isSameValue(a,b)},"<=":function(a,b){return a<=b},"<":function(a,b){return a<b},">=":function(a,b){return a>=b},">":function(a,b){return a>b},"+":function(a,b){return a+b},"-":function(a,b){return a-b},"*":function(a,b){return a*b},"/":function(a,b){return a/b},"%":function(a,b){return a%b},"&&":function(a,b){return a&&b},"||":function(a,b){return a||b}};fluid.transforms.binaryOp=function(inputs,transformSpec,transformer){var left=inputs.left();var right=inputs.right();var operator=fluid.model.transform.getValue(undefined,transformSpec.operator,transformer);var fun=fluid.transforms.binaryLookup[operator];return fun===undefined||left===undefined||right===undefined?undefined:fun(left,right)};fluid.defaults("fluid.transforms.condition",{gradeNames:["fluid.multiInputTransformFunction","fluid.standardOutputTransformFunction"],inputVariables:{true:null,false:null,condition:null}});fluid.transforms.condition=function(inputs){var condition=inputs.condition();if(condition===null){return undefined}return inputs[condition?"true":"false"]()};fluid.defaults("fluid.transforms.valueMapper",{gradeNames:["fluid.lens"],invertConfiguration:"fluid.transforms.valueMapper.invert",collectInputPaths:"fluid.transforms.valueMapper.collect"});fluid.model.transform.compareMatches=function(speca,specb){var matchDiff=specb.matchValue-speca.matchValue;return matchDiff===0?speca.index-specb.index:matchDiff};fluid.transforms.valueMapper=function(transformSpec,transformer){if(!transformSpec.match){fluid.fail('valueMapper requires an array or hash of matches at path named "match", supplied ',transformSpec)}var value=fluid.model.transform.getValue(transformSpec.defaultInputPath,transformSpec.defaultInput,transformer);var matchedEntry=fluid.isArrayable(transformSpec.match)?fluid.transforms.valueMapper.longFormMatch(value,transformSpec,transformer):transformSpec.match[value];if(matchedEntry===undefined){matchedEntry=transformSpec.noMatch}if(matchedEntry===undefined){return}var outputPath=matchedEntry.outputPath===undefined?transformSpec.defaultOutputPath:matchedEntry.outputPath;transformer.outputPrefixOp.push(outputPath);var outputValue;if(fluid.isPrimitive(matchedEntry)){outputValue=matchedEntry}else if(matchedEntry.outputUndefinedValue){outputValue=undefined}else{outputValue=fluid.model.transform.resolveParam(matchedEntry,transformer,"outputValue",undefined);outputValue=outputValue===undefined?transformSpec.defaultOutputValue:outputValue}if(typeof outputPath==="string"&&outputValue!==undefined){fluid.model.transform.setValue(undefined,outputValue,transformer,transformSpec.merge);outputValue=undefined}transformer.outputPrefixOp.pop();return outputValue};fluid.transforms.valueMapper.longFormMatch=function(valueFromDefaultPath,transformSpec,transformer){var o=transformSpec.match;if(o.length===0){fluid.fail("valueMapper supplied empty list of matches: ",transformSpec)}var matchPower=[];for(var i=0;i<o.length;++i){var option=o[i];var value=option.inputPath?fluid.model.transform.getValue(option.inputPath,undefined,transformer):valueFromDefaultPath;var matchValue=fluid.model.transform.matchValue(option.inputValue,value,option.partialMatches);matchPower[i]={index:i,matchValue:matchValue}}matchPower.sort(fluid.model.transform.compareMatches);return matchPower[0].matchValue<=0?undefined:o[matchPower[0].index]};fluid.transforms.valueMapper.invert=function(transformSpec,transformer){var match=[];var togo={type:"fluid.transforms.valueMapper",match:match};var isArray=fluid.isArrayable(transformSpec.match);togo.defaultInputPath=fluid.model.composePaths(transformer.outputPrefix,transformSpec.defaultOutputPath);togo.defaultOutputPath=fluid.model.composePaths(transformer.inputPrefix,transformSpec.defaultInputPath);var def=fluid.firstDefined;fluid.each(transformSpec.match,(function(option,key){if(option.outputUndefinedValue===true){return}var outOption={};var origInputValue=def(isArray?option.inputValue:key,transformSpec.defaultInputValue);if(origInputValue===undefined){fluid.fail("Failure inverting configuration for valueMapper - inputValue could not be resolved for record "+key+": ",transformSpec)}outOption.outputValue=origInputValue;outOption.inputValue=!isArray&&fluid.isPrimitive(option)?option:def(option.outputValue,transformSpec.defaultOutputValue);if(option.outputPath){outOption.inputPath=fluid.model.composePaths(transformer.outputPrefix,def(option.outputPath,transformSpec.outputPath))}if(option.inputPath){outOption.outputPath=fluid.model.composePaths(transformer.inputPrefix,def(option.inputPath,transformSpec.inputPath))}match.push(outOption)}));return togo};fluid.transforms.valueMapper.collect=function(transformSpec,transformer){var togo=[];fluid.model.transform.accumulateStandardInputPath("defaultInput",transformSpec,transformer,togo);fluid.each(transformSpec.match,(function(option){fluid.model.transform.accumulateInputPath(option.inputPath,transformer,togo)}));return togo};fluid.defaults("fluid.transforms.arrayToSetMembership",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.arrayToSetMembership.invert"});fluid.transforms.arrayToSetMembership=function(value,transformSpec){if(!value||!fluid.isArrayable(value)){fluid.fail("arrayToSetMembership didn't find array at inputPath nor passed as value.")}transformSpec=transformSpec||{};var output=transformSpec.arrayValue?[]:{};var presentValue=transformSpec.presentValue===undefined?true:transformSpec.presentValue,missingValue=transformSpec.missingValue===undefined?false:transformSpec.missingValue,options=transformSpec.options;if(options===undefined){fluid.each(value,(function(outPath){output[outPath]=presentValue}))}else{fluid.each(options,(function(outPath,key){var outVal=value.indexOf(key)!==-1?presentValue:missingValue;output[outPath]=outVal}))}return output};fluid.transforms.arrayToSetMembership.invert=function(transformSpec){return fluid.transforms.arrayToSetMembership.invertWithType(transformSpec,"fluid.transforms.setMembershipToArray")};fluid.transforms.arrayToSetMembership.invertWithType=function(transformSpec,newType){transformSpec.type=newType;var newOptions={};fluid.each(transformSpec.options,(function(path,oldKey){newOptions[path]=oldKey}));if(!$.isEmptyObject(newOptions)){transformSpec.options=newOptions}return transformSpec};fluid.defaults("fluid.transforms.setMembershipToArray",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.setMembershipToArray.invert"});fluid.transforms.setMembershipToArray=function(input,transformSpec){if(!fluid.isPlainObject(input)){fluid.fail("setMembershipToArray didn't find object at inputPath nor passed as value.")}var outputArr=[];transformSpec=transformSpec||{};var presentValue=transformSpec.presentValue===undefined?true:transformSpec.presentValue,options=transformSpec.options;if(options===undefined){fluid.each(input,(function(keyValue,outputVal){if(keyValue===presentValue){outputArr.push(outputVal)}}))}else{fluid.each(options,(function(outputVal,key){if(input[key]===presentValue){outputArr.push(outputVal)}}))}return outputArr};fluid.transforms.setMembershipToArray.invert=function(transformSpec){return fluid.transforms.arrayToSetMembership.invertWithType(transformSpec,"fluid.transforms.arrayToSetMembership")};fluid.model.transform.applyPaths=function(operation,pathOp,paths){for(var i=0;i<paths.length;++i){if(operation==="push"){pathOp.push(paths[i])}else{pathOp.pop()}}};fluid.model.transform.expandInnerValues=function(inputPath,outputPath,transformer,innerValues){var inputPrefixOp=transformer.inputPrefixOp;var outputPrefixOp=transformer.outputPrefixOp;var apply=fluid.model.transform.applyPaths;apply("push",inputPrefixOp,inputPath);apply("push",outputPrefixOp,outputPath);var expanded={};fluid.each(innerValues,(function(innerValue){var expandedInner=transformer.expand(innerValue);if(!fluid.isPrimitive(expandedInner)){$.extend(true,expanded,expandedInner)}else{expanded=expandedInner}}));apply("pop",outputPrefixOp,outputPath);apply("pop",inputPrefixOp,inputPath);return expanded};fluid.defaults("fluid.transforms.indexArrayByKey",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.indexArrayByKey.invert"});fluid.transforms.indexArrayByKey=function(arr,transformSpec,transformer){if(transformSpec.key===undefined){fluid.fail("indexArrayByKey requires a 'key' option.",transformSpec)}if(!fluid.isArrayable(arr)){fluid.fail("indexArrayByKey didn't find array at inputPath.",transformSpec)}var newHash={};var pivot=transformSpec.key;fluid.each(arr,(function(v,k){var newKey=v[pivot];var keyType=typeof newKey;if(keyType!=="string"&&keyType!=="boolean"&&keyType!=="number"){fluid.fail("indexArrayByKey encountered untransformable array due to missing or invalid key",v)}var content=fluid.copy(v);delete content[pivot];if(transformSpec.innerValue){content=fluid.model.transform.expandInnerValues([transformer.inputPrefix,transformSpec.inputPath,k.toString()],[transformSpec.outputPath,newKey],transformer,transformSpec.innerValue)}newHash[newKey]=content}));return newHash};fluid.transforms.indexArrayByKey.invert=function(transformSpec){transformSpec.type="fluid.transforms.deindexIntoArrayByKey";if(transformSpec.innerValue){var innerValue=transformSpec.innerValue;for(var i=0;i<innerValue.length;++i){var inverted=fluid.model.transform.invertConfiguration(innerValue[i]);if(inverted===fluid.model.transform.uninvertibleTransform){return inverted}else{innerValue[i]=inverted}}}return transformSpec};fluid.defaults("fluid.transforms.deindexIntoArrayByKey",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.deindexIntoArrayByKey.invert"});fluid.transforms.deindexIntoArrayByKey=function(hash,transformSpec,transformer){if(transformSpec.key===undefined){fluid.fail('deindexIntoArrayByKey requires a "key" option.',transformSpec)}var newArray=[];var pivot=transformSpec.key;fluid.each(hash,(function(v,k){var content={};content[pivot]=k;if(transformSpec.innerValue){v=fluid.model.transform.expandInnerValues([transformSpec.inputPath,k],[transformSpec.outputPath,newArray.length.toString()],transformer,transformSpec.innerValue)}$.extend(true,content,v);newArray.push(content)}));return newArray};fluid.transforms.deindexIntoArrayByKey.invert=function(transformSpec){transformSpec.type="fluid.transforms.indexArrayByKey";if(transformSpec.innerValue){var innerValue=transformSpec.innerValue;for(var i=0;i<innerValue.length;++i){innerValue[i]=fluid.model.transform.invertConfiguration(innerValue[i])}}return transformSpec};fluid.defaults("fluid.transforms.limitRange",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.invertToIdentity"});fluid.transforms.limitRange=function(value,transformSpec){var min=transformSpec.min;if(min!==undefined){var excludeMin=transformSpec.excludeMin||0;min+=excludeMin;if(value<min){value=min}}var max=transformSpec.max;if(max!==undefined){var excludeMax=transformSpec.excludeMax||0;max-=excludeMax;if(value>max){value=max}}return value};fluid.defaults("fluid.transforms.indexOf",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.indexOf.invert"});fluid.transforms.indexOf=function(value,transformSpec){if(typeof transformSpec.notFound==="number"&&transformSpec.notFound>=0){fluid.fail("A positive number is not allowed as 'notFound' value for indexOf")}var offset=fluid.transforms.parseIndexationOffset(transformSpec.offset,"indexOf");var array=fluid.makeArray(transformSpec.array);var originalIndex=array.indexOf(value);return originalIndex===-1&&transformSpec.notFound?transformSpec.notFound:originalIndex+offset};fluid.transforms.indexOf.invert=function(transformSpec,transformer){var togo=fluid.transforms.invertArrayIndexation(transformSpec,transformer);togo.type="fluid.transforms.dereference";return togo};fluid.defaults("fluid.transforms.dereference",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.dereference.invert"});fluid.transforms.dereference=function(value,transformSpec){if(typeof value!=="number"){return undefined}var offset=fluid.transforms.parseIndexationOffset(transformSpec.offset,"dereference");var array=fluid.makeArray(transformSpec.array);var index=value+offset;return array[index]};fluid.transforms.dereference.invert=function(transformSpec,transformer){var togo=fluid.transforms.invertArrayIndexation(transformSpec,transformer);togo.type="fluid.transforms.indexOf";return togo};fluid.transforms.parseIndexationOffset=function(offset,transformName){var parsedOffset=0;if(offset!==undefined){parsedOffset=fluid.parseInteger(offset);if(isNaN(parsedOffset)){fluid.fail(transformName+' requires the value of "offset" to be an integer or a string that can be converted to an integer. '+offset+" is invalid.")}}return parsedOffset};fluid.transforms.invertArrayIndexation=function(transformSpec){if(!isNaN(Number(transformSpec.offset))){transformSpec.offset=Number(transformSpec.offset)*-1}return transformSpec};fluid.defaults("fluid.transforms.stringTemplate",{gradeNames:"fluid.standardOutputTransformFunction"});fluid.transforms.stringTemplate=function(transformSpec){return fluid.stringTemplate(transformSpec.template,transformSpec.terms)};fluid.defaults("fluid.transforms.free",{gradeNames:"fluid.transformFunction"});fluid.transforms.free=function(transformSpec){var args=fluid.makeArray(transformSpec.args);if(!transformSpec.func){fluid.fail("Error in transform specification ",transformSpec,' required member "func" was not set')}return fluid.event.invokeListener(transformSpec.func,args)};fluid.defaults("fluid.transforms.quantize",{gradeNames:"fluid.standardTransformFunction",collectInputPaths:"fluid.transforms.quantize.collect"});fluid.transforms.quantize=function(value,transformSpec,transformer){if(!transformSpec.ranges||!transformSpec.ranges.length){fluid.fail("fluid.transforms.quantize should have a key called ranges containing an array defining ranges to quantize")}for(var i=0;i<transformSpec.ranges.length;i++){var rangeSpec=transformSpec.ranges[i];if(value<=rangeSpec.upperBound||rangeSpec.upperBound===undefined&&value>=Number.NEGATIVE_INFINITY){return fluid.isPrimitive(rangeSpec.output)?rangeSpec.output:transformer.expand(rangeSpec.output)}}};fluid.transforms.quantize.collect=function(transformSpec,transformer){transformSpec.ranges.forEach((function(rangeSpec){if(!fluid.isPrimitive(rangeSpec.output)){transformer.expand(rangeSpec.output)}}))};fluid.defaults("fluid.transforms.inRange",{gradeNames:"fluid.standardTransformFunction"});fluid.transforms.inRange=function(value,transformSpec){return(transformSpec.min===undefined||transformSpec.min<=value)&&(transformSpec.max===undefined||transformSpec.max>=value)?true:false};fluid.defaults("fluid.transforms.toggle",{gradeNames:["fluid.standardTransformFunction"],invertConfiguration:"fluid.transforms.toggle.invert",relayOptions:{forward:{excludeSource:"init"},backward:{includeSource:"init"}}});fluid.transforms.toggle=function(source,transformSpec,transformer){var oldSource=transformer.oldSource,oldTarget=transformer.oldTarget;var phase=(oldSource||0)-fluid.transforms.inverseToggle.base(oldTarget);return fluid.transforms.toggle.base(source+phase)};fluid.transforms.toggle.base=function(source){return(source||0)%2===1};fluid.transforms.toggle.invert=function(transformSpec){transformSpec.type="fluid.transforms.inverseToggle";return transformSpec};fluid.defaults("fluid.transforms.inverseToggle",{gradeNames:["fluid.standardTransformFunction"]});fluid.transforms.inverseToggle=function(source,transformSpec,transformer){return transformer.originalTarget||undefined};fluid.transforms.inverseToggle.base=function(source){return source?1:0};fluid.transforms.parseClasses=function(classes){var classList=classes.match(fluid.transforms.parseClasses.rnothtmlwhite)||[];return fluid.arrayToHash(classList)};fluid.transforms.parseClasses.rnothtmlwhite=/[^\x20\t\r\n\f]+/g;fluid.transforms.stringToBoolean=function(value){if(value){return!(value==="0"||value==="false")}else{return false}};fluid.transforms.stringToBoolean.invert=function(transformSpec){transformSpec.type="fluid.transforms.booleanToString";return transformSpec};fluid.defaults("fluid.transforms.stringToBoolean",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.stringToBoolean.invert"});fluid.transforms.booleanToString=function(value){return value?"true":"false"};fluid.transforms.booleanToString.invert=function(transformSpec){transformSpec.type="fluid.transforms.stringToBoolean";return transformSpec};fluid.defaults("fluid.transforms.booleanToString",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.booleanToString.invert"});fluid.transforms.JSONstringToObject=function(value){try{return JSON.parse(value)}catch(e){return undefined}};fluid.transforms.JSONstringToObject.invert=function(transformSpec){transformSpec.type="fluid.transforms.objectToJSONString";return transformSpec};fluid.defaults("fluid.transforms.JSONstringToObject",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.JSONstringToObject.invert"});fluid.transforms.objectToJSONString=function(value,transformSpec){var space=transformSpec.space||0;return JSON.stringify(value,null,space)};fluid.transforms.objectToJSONString.invert=function(transformSpec){transformSpec.type="fluid.transforms.JSONstringToObject";return transformSpec};fluid.defaults("fluid.transforms.objectToJSONString",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.objectToJSONString.invert"});fluid.transforms.stringToDate=function(value){var date=new Date(value);return isNaN(date.getTime())?undefined:date};fluid.transforms.stringToDate.invert=function(transformSpec){transformSpec.type="fluid.transforms.dateToString";return transformSpec};fluid.defaults("fluid.transforms.stringToDate",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.stringToDate.invert"});fluid.transforms.dateToString=function(value){if(value instanceof Date){var isoString=value.toISOString();var dateString=isoString.substring(0,isoString.indexOf("T"));return dateString}else{return undefined}};fluid.transforms.dateToString.invert=function(transformSpec){transformSpec.type="fluid.transforms.stringToDate";return transformSpec};fluid.defaults("fluid.transforms.dateToString",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.dateToString.invert"});fluid.transforms.dateTimeToString=function(value){return value instanceof Date?value.toISOString():undefined};fluid.defaults("fluid.transforms.dateTimeToString",{gradeNames:["fluid.standardTransformFunction","fluid.lens"],invertConfiguration:"fluid.transforms.dateToString.invert"});"use strict";var fluid=fluid||{};(function($){fluid.thatistBridge=function(name,peer){var togo=function(funcname){var segs=funcname.split(".");var move=peer;for(var i=0;i<segs.length;++i){move=move[segs[i]]}var args=[this];if(arguments.length===2){args=args.concat($.makeArray(arguments[1]))}var ret=move.apply(null,args);this.that=function(){return ret};return ret&&ret.constructor&&ret.constructor.name==="fluid.componentConstructor"?this:ret};$.fn[name]=togo;return togo};fluid.thatistBridge("fluid",fluid);var canHaveDefaultTabindex=function(elements){if(elements.length<=0){return false}return $(elements[0]).is("a, input, button, select, area, textarea, object")};var getValue=function(elements){if(elements.length<=0){return undefined}if(!fluid.tabindex.hasAttr(elements)){return canHaveDefaultTabindex(elements)?Number(0):undefined}var value=elements.attr("tabindex");return Number(value)};var setValue=function(elements,toIndex){return elements.each((function(i,item){$(item).attr("tabindex",toIndex)}))};fluid.tabindex=function(target,toIndex){target=$(target);if(toIndex!==null&&toIndex!==undefined){return setValue(target,toIndex)}else{return getValue(target)}};fluid.tabindex.remove=function(target){target=$(target);return target.each((function(i,item){$(item).removeAttr("tabindex")}))};fluid.tabindex.hasAttr=function(target){target=$(target);if(target.length<=0){return false}var togo=target.map((function(){var attributeNode=this.getAttributeNode("tabindex");return attributeNode?attributeNode.specified:false}));return togo.length===1?togo[0]:togo};fluid.tabindex.has=function(target){target=$(target);return fluid.tabindex.hasAttr(target)||canHaveDefaultTabindex(target)};fluid.a11y=$.a11y||{};fluid.a11y.orientation={HORIZONTAL:0,VERTICAL:1,BOTH:2};var UP_DOWN_KEYMAP={next:$.ui.keyCode.DOWN,previous:$.ui.keyCode.UP};var LEFT_RIGHT_KEYMAP={next:$.ui.keyCode.RIGHT,previous:$.ui.keyCode.LEFT};var unwrap=function(element){return element.jquery?element[0]:element};var makeElementsTabFocussable=function(elements){elements.each((function(idx,item){item=$(item);if(!item.fluid("tabindex.has")||item.fluid("tabindex")<0){item.fluid("tabindex",0)}}))};fluid.tabbable=function(target){target=$(target);makeElementsTabFocussable(target)};var CONTEXT_KEY="selectionContext";var NO_SELECTION=-32768;var cleanUpWhenLeavingContainer=function(selectionContext){if(selectionContext.activeItemIndex!==NO_SELECTION){if(selectionContext.options.onLeaveContainer){selectionContext.options.onLeaveContainer(selectionContext.selectables[selectionContext.activeItemIndex])}else if(selectionContext.options.onUnselect){selectionContext.options.onUnselect(selectionContext.selectables[selectionContext.activeItemIndex])}}if(!selectionContext.options.rememberSelectionState){selectionContext.activeItemIndex=NO_SELECTION}};var drawSelection=function(elementToSelect,handler){if(handler){handler(elementToSelect)}};var eraseSelection=function(selectedElement,handler){if(handler&&selectedElement){handler(selectedElement)}};var unselectElement=function(selectedElement,selectionContext){eraseSelection(selectedElement,selectionContext.options.onUnselect)};var selectElement=function(elementToSelect,selectionContext){unselectElement(selectionContext.selectedElement(),selectionContext);elementToSelect=unwrap(elementToSelect);var newIndex=selectionContext.selectables.index(elementToSelect);if(newIndex===-1){return}selectionContext.activeItemIndex=newIndex;drawSelection(elementToSelect,selectionContext.options.onSelect)};var selectableFocusHandler=function(selectionContext){return function(evt){$(evt.target).fluid("tabindex",0);selectElement(evt.target,selectionContext);return evt.stopPropagation()}};var selectableBlurHandler=function(selectionContext){return function(evt){$(evt.target).fluid("tabindex",selectionContext.options.selectablesTabindex);unselectElement(evt.target,selectionContext);return evt.stopPropagation()}};var reifyIndex=async function(sc_that){var elements=sc_that.selectables;if(sc_that.activeItemIndex>=elements.length){sc_that.activeItemIndex=sc_that.options.noWrap?elements.length-1:0}if(sc_that.activeItemIndex<0&&sc_that.activeItemIndex!==NO_SELECTION){sc_that.activeItemIndex=sc_that.options.noWrap?0:elements.length-1}if(sc_that.activeItemIndex>=0){return fluid.focus(elements[sc_that.activeItemIndex])}};var prepareShift=async function(selectionContext){var selElm=selectionContext.selectedElement();if(selElm){await fluid.blur(selElm)}unselectElement(selectionContext.selectedElement(),selectionContext);if(selectionContext.activeItemIndex===NO_SELECTION){selectionContext.activeItemIndex=-1}};var focusNextElement=async function(selectionContext){await prepareShift(selectionContext);++selectionContext.activeItemIndex;return reifyIndex(selectionContext)};var focusPreviousElement=async function(selectionContext){await prepareShift(selectionContext);--selectionContext.activeItemIndex;return reifyIndex(selectionContext)};var arrowKeyHandler=function(selectionContext,keyMap){return async function(evt){if(evt.which===keyMap.next){await focusNextElement(selectionContext);evt.preventDefault()}else if(evt.which===keyMap.previous){await focusPreviousElement(selectionContext);evt.preventDefault()}}};var getKeyMapForDirection=function(direction){var keyMap;if(direction===fluid.a11y.orientation.HORIZONTAL){keyMap=LEFT_RIGHT_KEYMAP}else if(direction===fluid.a11y.orientation.VERTICAL){keyMap=UP_DOWN_KEYMAP}return keyMap};var tabKeyHandler=function(selectionContext){return function(evt){if(evt.which!==$.ui.keyCode.TAB){return}cleanUpWhenLeavingContainer(selectionContext);if(evt.shiftKey){selectionContext.focusIsLeavingContainer=true}}};var containerFocusHandler=function(selectionContext){return async function(evt){var shouldOrig=selectionContext.options.autoSelectFirstItem;var shouldSelect=typeof shouldOrig==="function"?shouldOrig():shouldOrig;if(selectionContext.focusIsLeavingContainer){shouldSelect=false}if(shouldSelect&&evt.target===selectionContext.container.get(0)){if(selectionContext.activeItemIndex===NO_SELECTION){selectionContext.activeItemIndex=0}await fluid.focus(selectionContext.selectables[selectionContext.activeItemIndex])}return evt.stopPropagation()}};var containerBlurHandler=function(selectionContext){return function(evt){selectionContext.focusIsLeavingContainer=false;return evt.stopPropagation()}};var makeElementsSelectable=function(container,defaults,userOptions){var options=$.extend(true,{},defaults,userOptions);var keyMap=getKeyMapForDirection(options.direction);var selectableElements=options.selectableElements?options.selectableElements:container.find(options.selectableSelector);var that={container:container,activeItemIndex:NO_SELECTION,selectables:selectableElements,focusIsLeavingContainer:false,options:options};that.selectablesUpdated=async function(focusedItem){if(typeof that.options.selectablesTabindex==="number"){that.selectables.fluid("tabindex",that.options.selectablesTabindex)}that.selectables.off("focus."+CONTEXT_KEY);that.selectables.off("blur."+CONTEXT_KEY);that.selectables.on("focus."+CONTEXT_KEY,selectableFocusHandler(that));that.selectables.on("blur."+CONTEXT_KEY,selectableBlurHandler(that));if(keyMap&&that.options.noBubbleListeners){that.selectables.off("keydown."+CONTEXT_KEY);that.selectables.on("keydown."+CONTEXT_KEY,arrowKeyHandler(that,keyMap))}if(focusedItem){selectElement(focusedItem,that)}else{return reifyIndex(that)}};that.refresh=async function(){if(!that.options.selectableSelector){fluid.fail("Cannot refresh selectable context which was not initialised by a selector")}that.selectables=container.find(options.selectableSelector);return that.selectablesUpdated()};that.selectedElement=function(){return that.activeItemIndex<0?null:that.selectables[that.activeItemIndex]};if(keyMap&&!that.options.noBubbleListeners){container.on("keydown",arrowKeyHandler(that,keyMap))}container.on("keydown",tabKeyHandler(that));container.on("focus",containerFocusHandler(that));container.on("blur",containerBlurHandler(that));that.promise=that.selectablesUpdated();return that};fluid.selectable=function(target,options){target=$(target);var that=makeElementsSelectable(target,fluid.selectable.defaults,options);fluid.setScopedData(target,CONTEXT_KEY,that);return that};fluid.selectable.select=async function(target,toSelect){return fluid.focus(toSelect)};fluid.selectable.selectNext=async function(target){target=$(target);return focusNextElement(fluid.getScopedData(target,CONTEXT_KEY))};fluid.selectable.selectPrevious=async function(target){target=$(target);return focusPreviousElement(fluid.getScopedData(target,CONTEXT_KEY))};fluid.selectable.currentSelection=function(target){target=$(target);var that=fluid.getScopedData(target,CONTEXT_KEY);return $(that.selectedElement())};fluid.selectable.defaults={direction:fluid.a11y.orientation.VERTICAL,selectablesTabindex:-1,autoSelectFirstItem:true,rememberSelectionState:true,selectableSelector:".selectable",selectableElements:null,onSelect:null,onUnselect:null,onLeaveContainer:null,noWrap:false};var checkForModifier=function(binding,evt){if(!binding.modifier){return true}var modifierKey=binding.modifier;var isCtrlKeyPresent=modifierKey&&evt.ctrlKey;var isAltKeyPresent=modifierKey&&evt.altKey;var isShiftKeyPresent=modifierKey&&evt.shiftKey;return isCtrlKeyPresent||isAltKeyPresent||isShiftKeyPresent};var makeActivationHandler=function(binding){return function(evt){var target=evt.target;if(!fluid.enabled(target)){return}var code=evt.which?evt.which:evt.keyCode;if(code===binding.key&&binding.activateHandler&&checkForModifier(binding,evt)){var event=$.Event("fluid-activate");$(target).trigger(event,[binding.activateHandler]);if(event.isDefaultPrevented()){evt.preventDefault()}}}};var makeElementsActivatable=function(elements,onActivateHandler,defaultKeys,options){var bindings=[];$(defaultKeys).each((function(index,key){bindings.push({modifier:null,key:key,activateHandler:onActivateHandler})}));if(options&&options.additionalBindings){bindings=bindings.concat(options.additionalBindings)}fluid.initEnablement(elements);for(var i=0;i<bindings.length;++i){var binding=bindings[i];elements.on("keydown",makeActivationHandler(binding))}elements.on("fluid-activate",(function(evt,handler){handler=handler||onActivateHandler;return handler?handler(evt):null}))};fluid.activatable=function(target,fn,options){target=$(target);makeElementsActivatable(target,fn,fluid.activatable.defaults.keys,options)};fluid.activate=function(target){$(target).trigger("fluid-activate")};fluid.activatable.defaults={keys:[$.ui.keyCode.ENTER,$.ui.keyCode.SPACE]}})(jQuery);"use strict";fluid.apply=function(options){return options.func.apply(null,options.args)};fluid.defaults("fluid.baseViewComponent",{gradeNames:"fluid.component",argumentMap:{container:0,options:1},events:{onDomBind:"promise"},listeners:{"onCreate.onDomBind":"{that}.events.onDomBind"},selectors:{},members:{dom:"@expand:fluid.createDomBinder({that}.container, {that}.options.selectors)",locate:"{that}.dom.locate"},mergePolicy:{"members.dom":"replace","members.container":"replace"}});fluid.defaults("fluid.viewComponent",{gradeNames:["fluid.modelComponent","fluid.baseViewComponent"],members:{container:"@expand:fluid.containerForViewComponent({that}, {that}.options.container)"}});fluid.dumpSelector=function(selectable){return typeof selectable==="string"?selectable:selectable.selector?selectable.selector:""};fluid.checkTryCatchParameter=function(){var location=window.location||{search:"",protocol:"file:"};var GETparams=location.search.slice(1).split("&");return fluid.find(GETparams,(function(param){if(param.indexOf("notrycatch")===0){return true}}))===true};fluid.notrycatch=fluid.checkTryCatchParameter();fluid.wrap=function(obj,userJQuery){userJQuery=userJQuery||$;return!obj||obj.jquery?obj:userJQuery(obj)};fluid.unwrap=function(obj){return obj&&obj.jquery?obj[0]:obj};fluid.container=function(containerSpec,fallible,userJQuery){if(!containerSpec){fluid.fail("fluid.container argument is empty")}var selector=containerSpec.selector||containerSpec;if(userJQuery){containerSpec=fluid.unwrap(containerSpec)}var container=fluid.wrap(containerSpec,userJQuery);if(fallible&&(!container||container.length===0)){return null}if(!container||!container.jquery||container.length!==1){if(typeof containerSpec!=="string"){containerSpec=container.selector}var count=container.length!==undefined?container.length:0;var extraMessage=container.selectorName?" with selector name "+container.selectorName+" in context "+fluid.dumpEl(containerSpec.context):"";fluid.fail((count>1?"More than one ("+count+") container elements were":"No container element was")+" found for selector "+containerSpec+extraMessage)}if(!fluid.isDOMNode(container[0])){fluid.fail("fluid.container was supplied a non-jQueryable element")}container.selector=selector;container.context=container.context||containerSpec.ownerDocument||document;return container};fluid.createDomBinder=function(container,selectors){var userJQuery=container.constructor;var that={container:container,id:fluid.allocateGuid(),doQuery:function(selector){return userJQuery(selector,that.container)},cache:{}};that.locate=function(selectorName){var selector=selectorName==="container"?"":selectors[selectorName];if(selector===undefined){fluid.fail("DOM binder request for selector "+selectorName+" which is not registered")}var togo;if(selector===""){togo=that.container}else{togo=that.doQuery(selector,selectorName)}togo.selector=selector;togo.context=that.container;togo.selectorName=selectorName;that.cache[selectorName]=togo;return togo};that.fastLocate=function(selectorName){return that.cache[selectorName]||that.locate(selectorName)};that.resetContainer=function(container){that.container=container;that.clear()};that.clear=function(){that.cache={}};that.resolvePathSegment=that.locate;return that};fluid.createLocalContainerDomBinder=function(container,selectors){var that={container:container,id:fluid.allocateGuid(),cache:{}};var userJQuery=container.constructor;function cacheKey(name,thisContainer){return fluid.allocateSimpleId(thisContainer)+"-"+name}function record(name,thisContainer,result){that.cache[cacheKey(name,thisContainer)]=result}that.locate=function(name,localContainer){var selector,thisContainer,togo;selector=selectors[name];if(selector===undefined){if(name==="container"){selector=""}else{fluid.fail("DOM binder request for selector "+name+" which is not registered")}}thisContainer=localContainer||that.container;if(!thisContainer){fluid.fail("DOM binder invoked for selector "+name+" without container")}if(selector===""){togo=userJQuery(thisContainer)}else{if(typeof selector==="function"){togo=userJQuery(selector.call(null,fluid.unwrap(thisContainer)))}else{togo=userJQuery(selector,thisContainer)}}if(!togo.selector){togo.selector=selector;togo.context=thisContainer}togo.selectorName=name;record(name,thisContainer,togo);return togo};that.fastLocate=function(name,localContainer){var thisContainer=localContainer?localContainer:that.container;var key=cacheKey(name,thisContainer);var togo=that.cache[key];return togo?togo:that.locate(name,localContainer)};that.resetContainer=function(container){that.container=container;that.clear()};that.clear=function(){that.cache={}};that.refresh=function(names,localContainer){var thisContainer=localContainer?localContainer:that.container;if(typeof names==="string"){names=[names]}if(thisContainer.length===undefined){thisContainer=[thisContainer]}for(var i=0;i<names.length;++i){for(var j=0;j<thisContainer.length;++j){that.locate(names[i],thisContainer[j])}}};that.resolvePathSegment=that.locate;return that};fluid.expectFilledSelector=function(result,message){if(result&&result.length===0&&result.jquery){fluid.fail(message+': selector "'+result.selector+'" with name '+result.selectorName+" returned no results in context "+fluid.dumpEl(result.context))}};fluid.containerForViewComponent=function(that,containerSpec){var container=fluid.container(containerSpec);fluid.expectFilledSelector(container,'Error instantiating viewComponent at path "'+fluid.pathForComponent(that));return container};fluid.getId=function(element){return fluid.unwrap(element).id};fluid.allocateSimpleId=function(element){element=fluid.unwrap(element);if(!element||fluid.isPrimitive(element)){return null}if(!element.id){var simpleId="fluid-id-"+fluid.allocateGuid();element.id=simpleId}return element.id};fluid.registerNamespace("fluid.materialisers");fluid.makeDomMaterialiserManager=function(){var that={idToModelListeners:{}};return that};fluid.checkMaterialisedElement=function(element,selectorName,that){if(!element||!element.length){fluid.fail("Could not locate element for selector "+selectorName+" for component "+fluid.dumpComponentAndPath(that))}};fluid.domMaterialiserManager=fluid.makeDomMaterialiserManager();fluid.materialisers.domOutput=function(that,segs,type,options){fluid.freezeRecursive(segs);var selectorName=segs[1];var listener=function(value){if(that.dom){var element=that.dom.locate(selectorName);fluid.checkMaterialisedElement(element,selectorName,that);if(type==="jQuery"){var model={value:value,segs:segs};var args=options.makeArgs?options.makeArgs(model):[model.value];element[options.method].apply(element,args)}else if(type==="booleanAttr"){if(value===undefined){var markupValue=!!element.attr(options.attr);that.applier.change(segs,options.negate?!markupValue:markupValue)}else{var attrValue=options.negate?!value:value;if(attrValue){element.attr(options.attr,options.attr)}else{element.removeAttr(options.attr)}}}}};that.applier.modelChanged.addListener({segs:segs},listener);that.events.onDomBind.addListener((function(){var modelValue=fluid.getImmediate(that.model,segs);listener(modelValue)}))};fluid.incrementModel=function(that,segs){var oldValue=fluid.getImmediate(that.model,segs)||0;that.applier.change(segs,oldValue+1)};fluid.materialisers.domClick=function(that,segs){var listener=function(){fluid.incrementModel(that,segs)};that.events.onDomBind.addListener((function(){that.dom.locate(segs[1]).click(listener)}))};fluid.materialisers.hover=function(that,segs){var makeListener=function(state){return function(){that.applier.change(segs,state)}};that.events.onDomBind.addListener((function(){that.dom.locate(segs[1]).hover(makeListener(true),makeListener(false))}))};fluid.materialisers.focusin=function(that,segs){var makeListener=function(state){return function(){that.applier.change(segs,state)}};that.events.onDomBind.addListener((function(){that.dom.locate(segs[1]).focusin(makeListener(true)).focusout(makeListener(false))}))};fluid.materialisers.id=function(that,segs){that.events.onDomBind.addListener((function(){var element=that.dom.locate(segs[1])[0];var modelValue=fluid.getImmediate(that.model,segs);if(modelValue===undefined){var id=fluid.allocateSimpleId(element);that.applier.change(segs,id,"ADD","DOM")}else{element.id=modelValue}var modelListener=function(value){if(value!==undefined){element.id=value}};that.applier.modelChanged.addListener({segs:segs},modelListener)}))};fluid.materialisers.domValue=function(that,segs){that.events.onDomBind.addListener((function(){var element=that.dom.locate(segs[1]);var domListener=function(){var val=fluid.value(element);that.applier.change(segs,val,"ADD","DOM")};var modelListener=function(value){if(value!==undefined){fluid.value(element,value)}};that.applier.modelChanged.addListener({segs:segs},modelListener);var options=fluid.getImmediate(that,["options","bindingOptions",fluid.model.composeSegments.apply(null,segs)]);var changeEvent=options&&options.changeEvent||"change";element.on(changeEvent,domListener);modelListener(fluid.getImmediate(that.model,segs))}))};fluid.materialisers.style=function(that,segs){var selectorName=segs[1];that.events.onDomBind.addListener((function(){var element=that.dom.locate(selectorName);fluid.checkMaterialisedElement(element,selectorName,that);var modelValue=fluid.getImmediate(that.model,segs);element[0].style[segs[3]]=modelValue}))};fluid.registerNamespace("fluid.materialiserRegistry");fluid.materialiserRegistry["fluid.viewComponent"]={dom:{"*":{text:{materialiser:"fluid.materialisers.domOutput",args:["jQuery",{method:"text"}]},attr:{materialiser:"fluid.materialisers.domOutput",args:["jQuery",{method:"attr",makeArgs:function(model){return[model.segs[3],model.value]}}]},visible:{materialiser:"fluid.materialisers.domOutput",args:["jQuery",{method:"toggle"}]},enabled:{materialiser:"fluid.materialisers.domOutput",args:["booleanAttr",{attr:"disabled",negate:true}]},click:{materialiser:"fluid.materialisers.domClick"},hover:{materialiser:"fluid.materialisers.hover"},focusin:{materialiser:"fluid.materialisers.focusin"},value:{materialiser:"fluid.materialisers.domValue"},class:{materialiser:"fluid.materialisers.domOutput",args:["jQuery",{method:"toggleClass",makeArgs:function(model){return[model.segs[3],!!model.value]}}]},style:{materialiser:"fluid.materialisers.style"},id:{materialiser:"fluid.materialisers.id"}}}};fluid.value=function(nodeIn,newValue){var node=fluid.unwrap(nodeIn);var isMultiple=false;if(node.nodeType===undefined&&node.length>1){node=node[0];isMultiple=true}if("input"!==node.nodeName.toLowerCase()||!/radio|checkbox/.test(node.type)){return newValue===undefined?$(node).val():$(node).val(newValue)}var name=node.name;var elements;if(isMultiple||name===""){elements=nodeIn}else{elements=node.ownerDocument.getElementsByName(name);var scope=fluid.findForm(node);elements=$.grep(elements,(function(element){if(element.name!==name){return false}return!scope||scope.contains(element)}));isMultiple=elements.length>1}if(newValue!==undefined){if(typeof newValue==="boolean"){newValue=newValue?"true":"false"}$.each(elements,(function(){this.checked=newValue instanceof Array?newValue.indexOf(this.value)!==-1:newValue===this.value}))}else{var checked=$.map(elements,(function(element){return element.checked?element.value:null}));return node.type==="radio"?checked[0]:isMultiple?checked:!!checked[0]}};fluid.defaults("fluid.ariaLabeller",{gradeNames:"fluid.viewComponent"});"use strict";fluid.changeElementValue=function(node,value){node=$(node);fluid.value(node,value);node.change()};fluid.findAncestor=function(element,test){element=fluid.unwrap(element);while(element){if(test(element)){return element}element=element.parentNode}};fluid.findForm=function(node){return fluid.findAncestor(node,(function(element){return element.nodeName.toLowerCase()==="form"}))};fluid.each(["text","html"],(function(method){fluid[method]=function(node,newValue){node=$(node);return newValue===undefined?node[method]():node[method](newValue)}}));fluid.BINDING_ROOT_KEY="fluid-binding-root";fluid.findData=function(elem,name){while(elem){var data=$.data(elem,name);if(data){return data}elem=elem.parentNode}};fluid.bindFossils=function(node,data,fossils){$.data(node,fluid.BINDING_ROOT_KEY,{data:data,fossils:fossils})};fluid.boundPathForNode=function(node,fossils){node=fluid.unwrap(node);var key=node.name||node.id;var record=fossils[key];return record?record.EL:null};fluid.applyBoundChange=function(node,newValue,applier){node=fluid.unwrap(node);if(newValue===undefined){newValue=fluid.value(node)}if(node.nodeType===undefined&&node.length>0){node=node[0]}var root=fluid.findData(node,fluid.BINDING_ROOT_KEY);if(!root){fluid.fail("Bound data could not be discovered in any node above "+fluid.dumpEl(node))}var name=node.name;var fossil=root.fossils[name];if(!fossil){fluid.fail("No fossil discovered for name "+name+" in fossil record above "+fluid.dumpEl(node))}var EL=root.fossils[name].EL;if(applier){applier.fireChangeRequest({path:EL,value:newValue,source:"DOM:"+node.id})}else{fluid.set(root.data,EL,newValue)}};fluid.jById=function(id,dokkument){dokkument=dokkument&&dokkument.nodeType===9?dokkument:document;var element=fluid.byId(id,dokkument);var togo=element?$(element):[];togo.selector="#"+id;togo.context=dokkument;return togo};fluid.byId=function(id,dokkument){dokkument=dokkument&&dokkument.nodeType===9?dokkument:document;var el=dokkument.getElementById(id);if(el){if(el.id!==id){fluid.fail("Problem in document structure - picked up element "+fluid.dumpEl(el)+" for id "+id+" without this id - most likely the element has a name which conflicts with this id")}return el}else{return null}};fluid.getDocument=function(element){var node=fluid.unwrap(element);return node.nodeType===9?node:node.ownerDocument};fluid.defaults("fluid.ariaLabeller",{gradeNames:["fluid.viewComponent"],labelAttribute:"aria-label",liveRegionMarkup:'<div class="liveRegion fl-hidden-accessible" aria-live="polite"></div>',liveRegionId:"fluid-ariaLabeller-liveRegion",invokers:{generateLiveElement:{funcName:"fluid.ariaLabeller.generateLiveElement",args:"{that}"},update:{funcName:"fluid.ariaLabeller.update",args:["{that}","{arguments}.0"]}},listeners:{onCreate:{func:"{that}.update",args:[null]}}});fluid.ariaLabeller.update=function(that,newOptions){newOptions=newOptions||that.options;that.container.attr(that.options.labelAttribute,newOptions.text);if(newOptions.dynamicLabel){var live=fluid.jById(that.options.liveRegionId);if(live.length===0){live=that.generateLiveElement()}live.text(newOptions.text)}};fluid.ariaLabeller.generateLiveElement=function(that){var liveEl=$(that.options.liveRegionMarkup);liveEl.prop("id",that.options.liveRegionId);$("body").append(liveEl);return liveEl};var LABEL_KEY="aria-labelling";fluid.getAriaLabeller=function(element){element=$(element);var that=fluid.getScopedData(element,LABEL_KEY);return that};fluid.updateAriaLabel=function(element,text,options){options=$.extend({},options||{},{text:text});var that=fluid.getAriaLabeller(element);if(!that){that=fluid.ariaLabeller(element,options);fluid.setScopedData(element,LABEL_KEY,that)}else{that.update(options)}return that};fluid.dismissList={};$(document).click((function(event){var target=fluid.resolveEventTarget(event);while(target){if(fluid.dismissList[target.id]){return}target=target.parentNode}fluid.each(fluid.dismissList,(function(dismissFunc,key){dismissFunc(event);delete fluid.dismissList[key]}))}));fluid.globalDismissal=function(nodes,dismissFunc){fluid.each(nodes,(function(node){var id=fluid.unwrap(node).ownerDocument===document?fluid.allocateSimpleId(node):fluid.allocateGuid();if(dismissFunc){fluid.dismissList[id]=dismissFunc}else{delete fluid.dismissList[id]}}))};fluid.deadMansBlur=function(control,options){var that={options:$.extend(true,{},fluid.defaults("fluid.deadMansBlur"),options)};that.blurPending=false;that.lastCancel=0;that.canceller=function(event){fluid.log("Cancellation through "+event.type+" on "+fluid.dumpEl(event.target));that.lastCancel=Date.now();that.blurPending=false};that.noteProceeded=function(){fluid.globalDismissal(that.options.exclusions)};that.reArm=function(){fluid.globalDismissal(that.options.exclusions,that.proceed)};that.addExclusion=function(exclusions){fluid.globalDismissal(exclusions,that.proceed)};that.proceed=function(event){fluid.log("Direct proceed through "+event.type+" on "+fluid.dumpEl(event.target));that.blurPending=false;that.options.handler(control)};fluid.each(that.options.exclusions,(function(exclusion){exclusion=$(exclusion);fluid.each(exclusion,(function(excludeEl){$(excludeEl).on("focusin",that.canceller).on("fluid-focus",that.canceller).click(that.canceller).mousedown(that.canceller)}))}));if(!that.options.cancelByDefault){$(control).on("focusout",(function(event){fluid.log("Starting blur timer for element "+fluid.dumpEl(event.target));var now=Date.now();fluid.log("back delay: "+(now-that.lastCancel));if(now-that.lastCancel>that.options.backDelay){that.blurPending=true}setTimeout((function(){if(that.blurPending){that.options.handler(control)}}),that.options.delay)}))}else{that.reArm()}return that};fluid.defaults("fluid.deadMansBlur",{gradeNames:"fluid.function",delay:150,backDelay:100});"use strict";fluid.defaults("fluid.messageResolver",{gradeNames:["fluid.component"],mergePolicy:{messageBase:"nomerge",parents:"nomerge"},resolveFunc:fluid.stringTemplate,parseFunc:fluid.identity,messageBase:{},members:{messageBase:"@expand:{that}.options.parseFunc({that}.options.messageBase)"},invokers:{lookup:"fluid.messageResolver.lookup({that}, {arguments}.0)",resolve:"fluid.messageResolver.resolve({that}, {arguments}.0, {arguments}.1)"},parents:[]});fluid.messageResolver.lookup=function(that,messagecodes){var resolved=fluid.messageResolver.resolveOne(that.messageBase,messagecodes);if(resolved===undefined){return fluid.find(that.options.parents,(function(parent){return parent?parent.lookup(messagecodes):undefined}))}else{return{template:resolved,resolveFunc:that.options.resolveFunc}}};fluid.messageResolver.resolve=function(that,messagecodes,args){if(!messagecodes){return"[No messagecodes provided]"}messagecodes=fluid.makeArray(messagecodes);var looked=that.lookup(messagecodes);return looked?looked.resolveFunc(looked.template,args):"[Message string for key "+messagecodes[0]+" not found]"};fluid.messageResolver.resolveOne=function(messageBase,messagecodes){if(messageBase instanceof fluid.fetchResources.FetchOne){messageBase=fluid.fetchResources.resolveFetchOne(messageBase)}for(var i=0;i<messagecodes.length;++i){var code=messagecodes[i];var message=messageBase[code];if(message instanceof fluid.fetchResources.FetchOne){message=fluid.fetchResources.resolveFetchOne(message)}if(message!==undefined){return message}}};fluid.messageLocator=function(messageBase,resolveFunc){var resolver=fluid.messageResolver({messageBase:messageBase,resolveFunc:resolveFunc});return function(messagecodes,args){return resolver.resolve(messagecodes,args)}};fluid.resolveMessageSource=function(messageSource){if(messageSource.type==="data"){if(messageSource.url===undefined){return fluid.messageLocator(messageSource.messages,messageSource.resolveFunc)}else{}}else if(messageSource.type==="resolver"){return messageSource.resolver.resolve}};"use strict";fluid.explodeLocalisedName=function(fileName,locale,defaultLocale){var lastDot=fileName.lastIndexOf(".");if(lastDot===-1||lastDot===0){lastDot=fileName.length}var baseName=fileName.substring(0,lastDot);var extension=fileName.substring(lastDot);var segs=locale?locale.split("_"):[];var exploded=fluid.transform(segs,(function(seg,index){var shortSegs=segs.slice(0,index+1);return baseName+"_"+shortSegs.join("_")+extension}));if(defaultLocale){exploded.unshift(baseName+"_"+defaultLocale+extension)}exploded.unshift(fileName);return exploded};fluid.fetchResources=function(resourceSpecs,callback,options){var that=fluid.makeResourceFetcher(resourceSpecs,callback,options,fluid.identity);that.optionsReady.resolve();that.fetchAll();return that};fluid.fetchResources.explodeForLocales=function(resourceFetcher){fluid.each(resourceFetcher.resourceSpecs,(function(resourceSpec){resourceSpec.resolvedDefaultLocale=resourceSpec.defaultLocale||resourceFetcher.options.defaultLocale;resourceSpec.resolvedLocale=resourceFetcher.options.locale||resourceSpec.locale||resourceSpec.resolvedDefaultLocale;if(!resourceSpec.loader.loader.noPath){var pathKey=resourceSpec.loader.pathKey;var path=resourceSpec[pathKey];var resolvedPath=resourceSpec[pathKey]=resourceFetcher.transformResourceURL(path);resourceSpec.localeExploded=fluid.explodeLocalisedName(resolvedPath,resourceSpec.resolvedLocale,resourceSpec.resolvedDefaultLocale);resourceSpec.localeExplodedSpecs=fluid.transform(resourceSpec.localeExploded,(function(oneExploded){var togo={loader:resourceSpec.loader,options:resourceSpec.options};togo[pathKey]=oneExploded;return togo}),fluid.fetchResources.prepareRequestOptions)}}))};fluid.fetchResources.launchExplodedLocales=function(localeExplodedSpecs,loader){var promiseArray=fluid.transform(localeExplodedSpecs,loader,(function(promise){var promiseToGo=fluid.promise();promise.then((function(resolve){promiseToGo.resolve({resolved:resolve})}),(function(error){promiseToGo.resolve({rejected:error})}));return promiseToGo}));var settledArrayPromise=fluid.promise.sequence(promiseArray);return settledArrayPromise};fluid.fetchResources.condenseExplodedLocales=function(resourceSpec,settledArray){var togo=fluid.promise();settledArray.reverse();var lastNonError=fluid.find(settledArray,(function(settled){return settled.resolved}));if(lastNonError){togo.resolve(lastNonError)}else{togo.reject({isError:true,message:"No localised variants of the resource could be found at any of the paths "+resourceSpec.localeExploded.join(", ")})}return togo};fluid.fetchResources.resolveLoaderTask=function(resourceSpec,loader){if(resourceSpec.localeExplodedSpecs){return function(){var togo=fluid.promise();var settledArrayPromise=fluid.fetchResources.launchExplodedLocales(resourceSpec.localeExplodedSpecs,loader);settledArrayPromise.then((function(settledArray){var condensed=fluid.fetchResources.condenseExplodedLocales(resourceSpec,settledArray);fluid.promise.follow(condensed,togo)}));return togo}}else{return function(){return loader(resourceSpec)}}};fluid.fetchResources.checkCompletion=function(resourceSpecs,resourceFetcher){var incomplete=fluid.find_if(resourceSpecs,(function(resourceSpec){return!resourceSpec.promise.disposition}));if(!incomplete){var completionPromise=resourceFetcher.completionPromise;fluid.invokeLater((function(){if(!completionPromise.disposition){completionPromise.resolve(resourceSpecs)}}))}};fluid.fetchResources.noteResourceText=function(resourceText,options){options.resourceSpec.resourceText=resourceText;return resourceText};fluid.fetchResources.noteParsed=function(parsed,options){options.resourceSpec.parsed=parsed;return parsed};fluid.fetchResources.fireFetched=function(parsed,options){options.resourceSpec.onFetched.fire(parsed);return parsed};fluid.fetchResources.prepareRequestOptions=function(resourceSpec){var pathKey=resourceSpec.loader.pathKey;var requestOptions={};requestOptions[pathKey]=resourceSpec[pathKey];resourceSpec.options=$.extend(true,{},resourceSpec.options,requestOptions);return resourceSpec};fluid.fetchResources.initOneResource=function(resourceSpec){resourceSpec.promise=fluid.promise();resourceSpec.launched=false};fluid.fetchResources.subscribeOneResource=function(resourceSpec,key,ownerComponentId){if(resourceSpec.transformEvent){fluid.fail("Cannot subscribe resource ",resourceSpec," which has already been subscribed for I/O")}resourceSpec.key=key;resourceSpec.transformEvent=fluid.makeEventFirer({name:'Transform chain for resource "'+key+'"',ownerId:ownerComponentId});resourceSpec.transformEvent.addListener(fluid.fetchResources.noteParsed,"noteParsed","last");var parser=fluid.resourceLoader.resolveResourceParser(resourceSpec);resourceSpec.transformEvent.addListener(parser,"parser","before:noteParsed");resourceSpec.transformEvent.addListener((function(parsed){return fluid.resourceLoader.renderImmutable(parsed,resourceSpec)}),"renderImmutable","after:parser");resourceSpec.transformEvent.addListener(fluid.fetchResources.noteResourceText,"resourceText","before:parser");resourceSpec.transformEvent.addListener(fluid.fetchResources.resolveLoaderTask(resourceSpec,resourceSpec.loader.loader),"loader","before:resourceText");resourceSpec.onFetched=fluid.makeEventFirer({name:'onFetched event for resources "'+key+'"',ownerId:ownerComponentId});resourceSpec.onError=fluid.makeEventFirer({name:'onError event for resources "'+key+'"',ownerId:ownerComponentId});resourceSpec.transformEvent.addListener(fluid.fetchResources.fireFetched,"fireFetched","last");fluid.fetchResources.prepareRequestOptions(resourceSpec);fluid.fetchResources.initOneResource(resourceSpec)};fluid.fetchResources.FetchOne=function(resourceSpec,resourceFetcher,segs){var FetchOne=this;FetchOne.resourceFetcher=resourceFetcher;FetchOne.resourceSpec=resourceSpec;FetchOne.segs=segs||[];var thisPromise=FetchOne.promise=fluid.promise();fluid.fetchResources.fetchOneResource(resourceSpec,resourceFetcher).then((function(){thisPromise.resolve(fluid.fetchResources.resolveFetchOne(FetchOne))}))};fluid.fetchResources.resolveFetchOne=function(FetchOne){return fluid.getImmediate(FetchOne.resourceSpec,FetchOne.segs)};fluid.fetchResources.FetchOne.prototype.resolvePathSegment=function(seg){return new fluid.fetchResources.FetchOne(this.resourceSpec,this.resourceFetcher,this.segs.concat(fluid.makeArray(seg)))};fluid.initResourceFetcher=function(resourceFetcher){resourceFetcher.completionPromise=fluid.promise();fluid.fetchResources.explodeForLocales(resourceFetcher);resourceFetcher.onInit.fire(resourceFetcher.completionPromise)};fluid.resourceFetcher=function(){};fluid.makeResourceFetcher=function(sourceResourceSpecs,callback,options,transformResourceURL){options=options||{};var that=Object.create(fluid.resourceFetcher.prototype);fluid.extend(that,{sourceResourceSpecs:sourceResourceSpecs,options:fluid.copy(options),optionsReady:fluid.promise(),onInit:fluid.makeEventFirer({name:"onInit for resourceFetcher",ownerId:options.ownerComponentId}),transformResourceURL:transformResourceURL});that.fetchAll=function(){return fluid.fetchResources.fetchAll(that)};that.refetchAll=function(){return fluid.fetchResources.refetchAll(that)};that.fetchOneResource=function(key){return fluid.fetchResources.fetchOneResource(that.resourceSpecs[key],that)};that.refetchOneResource=function(key){return fluid.fetchResources.refetchOneResource(that.resourceSpecs[key],that)};that.resourceSpecs=fluid.copy(that.sourceResourceSpecs);that.onInit.addListener((function(completionPromise){completionPromise.then(callback,callback)}));fluid.each(options.onInitListeners,(function(args){that.onInit.addListener.apply(null,args)}));fluid.each(that.resourceSpecs,(function(resourceSpec){resourceSpec.dataType=resourceSpec.dataType||that.options.dataType;resourceSpec.loader=fluid.resourceLoader.resolveResourceLoader(resourceSpec)}));fluid.initResourceFetcher(that);fluid.each(that.resourceSpecs,(function(resourceSpec,key){fluid.fetchResources.subscribeOneResource(resourceSpec,key,that.options.ownerComponentId)}));return that};fluid.fetchResources.fetchAll=function(resourceFetcher){fluid.each(resourceFetcher.resourceSpecs,(function(resourceSpec){fluid.fetchResources.fetchOneResource(resourceSpec,resourceFetcher)}));fluid.fetchResources.checkCompletion(resourceFetcher.resourceSpecs,resourceFetcher);return resourceFetcher.completionPromise};fluid.fetchResources.mutableResourceSpecFields=["promise","resourceText","parsed","locale","defaultLocale"];fluid.fetchResources.refetchOneResource=function(resourceSpec,resourceFetcher,defeatInitiate){resourceSpec.promise.cancel();fluid.fetchResources.mutableResourceSpecFields.forEach((function(field){delete resourceSpec[field]}));fluid.fetchResources.initOneResource(resourceSpec);if(!defeatInitiate){fluid.fetchResources.initiateRefetch(resourceFetcher)}return resourceSpec.promise};fluid.fetchResources.initiateRefetch=function(resourceFetcher){resourceFetcher.completionPromise.cancel();delete resourceFetcher.completionPromise;fluid.initResourceFetcher(resourceFetcher,true);fluid.fetchResources.fetchAll(resourceFetcher);resourceFetcher.fetchAll()};fluid.fetchResources.refetchAll=function(resourceFetcher){var anyLaunched=false;fluid.each(resourceFetcher.resourceSpecs,(function(resourceSpec){if(resourceSpec.resolvedLocale){anyLaunched=true;fluid.fetchResources.refetchOneResource(resourceSpec,resourceFetcher,true)}}));if(anyLaunched){fluid.fetchResources.initiateRefetch(resourceFetcher)}return resourceFetcher.completionPromise};fluid.fetchResources.fireTransformEvent=function(resourceSpec,resourceFetcher){return fluid.promise.fireTransformEvent(resourceSpec.transformEvent,null,{resourceSpec:resourceSpec,resourceFetcher:resourceFetcher})};fluid.fetchResources.fetchOneResource=function(resourceSpec,resourceFetcher){if(!resourceSpec.launched){resourceSpec.launched=true;resourceFetcher.optionsReady.then((function(){var transformPromise=fluid.fetchResources.fireTransformEvent(resourceSpec,resourceFetcher);fluid.promise.follow(transformPromise,resourceSpec.promise);resourceSpec.promise.then((function(){fluid.fetchResources.checkCompletion(resourceFetcher.resourceSpecs,resourceFetcher)}),(function(error){resourceSpec.fetchError=error;resourceSpec.onError.fire(error);resourceFetcher.completionPromise.reject(error)}))}))}return resourceSpec.promise};fluid.registerNamespace("fluid.resourceLoader.loaders");fluid.resourceLoader.modelUpdated=function(resourceFetcher,modelOptions,early){resourceFetcher.options=$.extend(true,{},resourceFetcher.options,modelOptions);if(early){fluid.fetchResources.explodeForLocales(resourceFetcher);resourceFetcher.optionsReady.resolve()}else{resourceFetcher.refetchAll()}};fluid.resourceLoader.sanitizeResourceSpec=function(resourceSpec){return fluid.transform(resourceSpec,(function(value){return fluid.isPrimitive(value)||fluid.isPlainObject(value)&&!fluid.isPromise(value)?value:fluid.NO_VALUE}))};fluid.ImmutableArray=function(){};fluid.ImmutableArray.prototype=[];fluid.ImmutableObject=function(){};fluid.copyImmutableResource=function(tocopy){var newContainer=fluid.isArrayable(tocopy)?new fluid.ImmutableArray:new fluid.ImmutableObject;fluid.each(tocopy,(function(value,key){newContainer[key]=value}));return newContainer};fluid.resourceLoader.renderImmutable=function(parsed,resourceSpec){if(resourceSpec.immutableModelResource){return fluid.copyImmutableResource(parsed)}else{return parsed}};fluid.resourceLoader.resolveResourceLoader=function(resourceSpec){var loaders=[];fluid.each(fluid.resourceLoader.loaders,(function(loader,key){if(fluid.isValue(resourceSpec[key])){loaders.push({loader:loader,pathKey:key})}}));if(loaders.length===0){loaders.push({loader:fluid.resourceLoader.loaders.noLoader})}else if(loaders.length>1){fluid.fail("Resource spec ",fluid.resourceLoader.sanitizeResourceSpec(resourceSpec)," is ambiguous because it has fields for multiple resource loaders filled out: at most one of the fields ",fluid.getMembers(loaders,"pathKey")," can be used")}return loaders[0]};fluid.resourceLoader.loaders.resourceText=function(resourceSpec){return resourceSpec.resourceText};fluid.resourceLoader.loaders.resourceText.noPath=true;fluid.resourceLoader.loaders.promiseFunc=function(resourceSpec){var promiseFunc=fluid.event.resolveListener(resourceSpec.promiseFunc);return promiseFunc.apply(null,fluid.makeArray(resourceSpec.promiseArgs))};fluid.resourceLoader.loaders.promiseFunc.noPath=true;fluid.resourceLoader.loaders.dataSource=function(resourceSpec){fluid.getForComponent(resourceSpec.dataSource,"get");return resourceSpec.dataSource.get(resourceSpec.directModel,resourceSpec.options)};fluid.resourceLoader.loaders.dataSource.noPath=true;fluid.resourceLoader.loaders.dataSource.parsed=true;fluid.resourceLoader.loaders.noLoader=function(resourceSpec){return fluid.promise().resolve({noResource:true,message:["No resource was configured for resource spec ",fluid.resourceLoader.sanitizeResourceSpec(resourceSpec),"; since it had none of the fields fields ",Object.keys(fluid.resourceLoader.loaders)+" filled out"]})};fluid.resourceLoader.loaders.noLoader.noPath=true;fluid.resourceLoader.loaders.noLoader.parsed=true;fluid.registerNamespace("fluid.resourceLoader.parsers");fluid.resourceLoader.resolveResourceParser=function(resourceSpec){return!resourceSpec.loader.loader.parsed&&fluid.resourceLoader.parsers[resourceSpec.dataType]||fluid.identity};fluid.resourceLoader.parsers.json=function(resourceText){return fluid.dataSource.parseJSON(resourceText)};fluid.resourcesMergePolicy=function(target,source){target=target||{};fluid.each(source,(function(oneResource,name){if(!oneResource){target[name]=oneResource;return}else if(fluid.isPrimitive(oneResource)){oneResource={url:oneResource}}var oneR=target[name];if(!oneR){oneR=target[name]={}}for(var key in fluid.resourceLoader.loaders){if(key in oneResource){for(var key2 in fluid.resourceLoader.loaders){delete oneR[key2]}}}$.extend(oneR,oneResource)}));return target};fluid.defaults("fluid.resourceLoader",{gradeNames:["fluid.modelComponent"],listeners:{"onCreate.loadResources":"{that}.resourceFetcher.fetchAll","onDestroy.destroyResourceEvents":"fluid.resourceLoader.destroyResourceEvents({that}.resourceFetcher)","{that}.resourceFetcher.onInit":{namespace:"resourceLoaderCompletion",funcName:"fluid.resourceLoader.subscribeCompletion",args:["{arguments}.0","{that}"]},"{that}.applier.earlyModelResolved":{funcName:"fluid.resourceLoader.modelUpdated",args:["{that}.resourceFetcher","{arguments}.0.resourceLoader",true]}},modelListeners:{resourceLoader:{namespace:"resourceLoader",funcName:"fluid.resourceLoader.modelUpdated",excludeSource:"init",args:["{that}.resourceFetcher","{change}.value"]}},mergePolicy:{resources:fluid.resourcesMergePolicy},members:{resourceFetcher:{expander:{funcName:"fluid.resourceLoader.makeResourceFetcher",args:["{that}","{that}.options.resources","{that}.options.resourceOptions","{that}.transformResourceURL"]}}},resourceOptions:{terms:{}},resources:{},invokers:{transformResourceURL:{funcName:"fluid.stringTemplate",args:["{arguments}.0","{that}.options.resourceOptions.terms"]}},events:{onResourcesLoaded:null,onResourceError:null}});fluid.resourceLoader.makeResourceFetcher=function(that,resourceSpecs,userResourceOptions,transformResourceURL){var resourceOptions=$.extend({ownerComponentId:that.id,ownerComponentPath:fluid.pathForComponent(that),onInitListeners:[[function(completionPromise){fluid.resourceLoader.subscribeCompletion(completionPromise,that)},"resourceLoaderCompletion"]]},userResourceOptions);var fetcher=fluid.makeResourceFetcher(resourceSpecs,null,resourceOptions,transformResourceURL);fluid.each(fetcher.resourceSpecs,(function(resourceSpec,key){resourceSpec.transformEvent.addListener((function(parsed){that.resources[key]=resourceSpec;return parsed}),"noteComponentResource","after:parsed");resourceSpec.onError.addListener(that.events.onResourceError.fire)}));return fetcher};fluid.resourceLoader.subscribeCompletion=function(completionPromise,resourceLoader){var fire=function(){resourceLoader.events.onResourcesLoaded.fire(resourceLoader.resourceFetcher.resourceSpecs)};completionPromise.then((function(){if(resourceLoader.lifecycleStatus==="constructed"||resourceLoader.lifecycleStatus==="treeConstructed"){fire()}else if(resourceLoader.lifecycleStatus!=="destroyed"){resourceLoader.events.onCreate.addListener(fire,"fireOnResourcesLoaded")}}),(function(error){fluid.log("Failure loading resources for component at path "+fluid.dumpComponentPath(resourceLoader)+": ",error)}))};fluid.resourceLoader.destroyResourceEvents=function(resourceFetcher){fluid.each(resourceFetcher.resourceSpecs,(function(resourceSpec){resourceSpec.transformEvent.destroy();resourceSpec.onFetched.destroy()}))};"use strict";fluid.resourceLoader.UrlClass=URL;fluid.resourceLoader.configureXHR=function(xhr,options){fluid.resourceLoader.loaders.XHR.copyProps.forEach((function(prop){if(fluid.isValue(options[prop])){xhr[prop]=options[prop]}}));fluid.each(options.headers,(function(value,key){var values=fluid.makeArray(value);values.forEach((function(oneValue){xhr.setRequestHeader(key,oneValue)}))}))};fluid.resourceLoader.loaders.XHR=function(resourceSpec){var togo=fluid.promise();var xhr=resourceSpec.xhr=new XMLHttpRequest;togo.then(null,null,(function(){xhr.abort()}));var sendSuccess=function(){fluid.invokeLater((function(){var response=!xhr.responseType||xhr.responseType==="text"?xhr.responseText:xhr.response;togo.resolve(response)}))};var sendError=function(){fluid.invokeLater((function(){togo.reject({isError:true,status:xhr.status,textStatus:xhr.statusText})}))};xhr.addEventListener("load",(function(){var isError=fluid.dataSource.URL.isErrorStatus(xhr.status);isError?sendError():sendSuccess()}));xhr.addEventListener("error",sendError);var options=$.extend({async:true},resourceSpec.options);xhr.open(options.method||"GET",resourceSpec.url,options.async,options.username,options.password);fluid.resourceLoader.configureXHR(xhr,options);xhr.send();return togo};fluid.resourceLoader.loaders.XHR.copyProps=["contentType","responseType","timeout"];fluid.resourceLoader.loaders.url=fluid.resourceLoader.loaders.XHR;fluid.dataSource.URL.handleHttp=function(that,baseOptions,data){var promise=fluid.promise();var defaultOptions={method:"GET",async:true};if(baseOptions.operation==="set"){defaultOptions.headers={"Content-Type":that.encoding.options.contentType};defaultOptions.method=baseOptions.writeMethod}var requestOptions=fluid.extend(true,defaultOptions,baseOptions);var whileMsg=" while executing HTTP "+requestOptions.method+" on url "+requestOptions.url;promise.accumulateRejectionReason=function(originError){return fluid.upgradeError(originError,whileMsg)};var xhr=promise.xhr=new XMLHttpRequest;var sendError=function(){var relayed=fluid.dataSource.URL.relayError(xhr.status,xhr.statusText,whileMsg);if(requestOptions.notFoundIsEmpty&&relayed.statusCode===404){promise.resolve(undefined)}else{promise.reject(relayed)}};xhr.addEventListener("load",(function(){if(fluid.dataSource.URL.isErrorStatus(xhr.status)){sendError()}else{var response=!xhr.responseType||xhr.responseType==="text"?xhr.responseText:xhr.response;promise.resolve(response)}}));xhr.addEventListener("error",sendError);var url=fluid.dataSource.URL.condenseUrl(requestOptions);requestOptions.url=url;fluid.log("DataSource Issuing "+requestOptions.protocol.toUpperCase().slice(0,-1)+" request with options ",requestOptions);xhr.open(requestOptions.method||"GET",url.toString(),requestOptions.async);fluid.resourceLoader.configureXHR(xhr,requestOptions);xhr.send(data);return promise};"use strict";fluid.defaults("fluid.newViewComponent",{gradeNames:"fluid.viewComponent",listeners:{"onCreate.onDomBind":null}});fluid.defaults("fluid.containerRenderingView",{gradeNames:["fluid.newViewComponent"],members:{container:"@expand:{that}.renderContainer()"},parentContainer:"{that}.options.container",injectionType:"append",invokers:{renderMarkup:"fluid.identity({that}.options.markup.container)",renderContainer:"fluid.containerRenderingView.renderContainer({that}, {that}.renderMarkup, {that}.addToParent)",addToParent:{funcName:"fluid.containerRenderingView.addToParent",args:["{that}.options.parentContainer","{arguments}.0","{that}.options.injectionType"]}},workflows:{global:{evaluateContainers:{funcName:"fluid.renderer.evaluateContainers",priority:"last",waitIO:true}}},listeners:{"onDestroy.clearInjectedMarkup":{this:"{that}.container",method:"remove",args:[]}}});fluid.registerNamespace("fluid.renderer");fluid.defaults("fluid.templateResourceFetcher",{gradeNames:"fluid.resourceLoader",rendererTemplateResources:{template:true},skipTemplateFetch:false,workflows:{global:{fetchTemplates:{funcName:"fluid.renderer.fetchTemplates",priority:"after:resolveResourceModel"}}}});fluid.renderer.fetchTemplates=function(shadows){shadows.forEach((function(shadow){var that=shadow.that;if(fluid.componentHasGrade(that,"fluid.templateResourceFetcher")){var skipTemplateFetch=fluid.getForComponent(that,["options","skipTemplateFetch"]);if(!skipTemplateFetch){var rendererTemplateResources=fluid.getForComponent(that,["options","rendererTemplateResources"]);fluid.each(rendererTemplateResources,(function(value,key){if(value){fluid.getForComponent(that,["resources",key])}}))}}}))};fluid.containerRenderingView.addToParent=function(parentContainer,elm,method){if(!parentContainer){fluid.fail('fluid.containerRenderingView needs to have "parentContainer" or "container" option supplied')}method=method||"append";$(parentContainer)[method](elm)};fluid.renderer.evaluateContainers=function(shadows){shadows.forEach((function(shadow){fluid.getForComponent(shadow.that,"container")}));shadows.forEach((function(shadow){shadow.that.events.onDomBind.fire(shadow.that)}))};fluid.containerRenderingView.renderContainer=function(that,renderMarkup,addToParent){fluid.log("Rendering container for "+that.id);var containerMarkup=renderMarkup();var container=$(containerMarkup);addToParent(container);return container};fluid.defaults("fluid.templateRenderingView",{gradeNames:["fluid.containerRenderingView","fluid.templateResourceFetcher"],invokers:{renderMarkup:"fluid.identity({that}.resources.template.parsed)"},distributeOptions:{mapTemplateUrl:{source:"{that}.options.templateUrl",target:"{that}.options.resources.template.url"}}});"use strict";fluid.defaults("fluid.mutationObserver",{gradeNames:["fluid.viewComponent"],events:{onNodeAdded:null,onNodeRemoved:null,onAttributeChanged:null},listeners:{"onDestroy.disconnect":"{that}.disconnect"},members:{observer:{expander:{func:"{that}.createObserver"}}},defaultObserveConfig:{attributes:true,childList:true,subtree:true},invokers:{observe:{funcName:"fluid.mutationObserver.observe",args:["{that}","{arguments}.0","{arguments}.1"]},disconnect:{this:"{that}.observer",method:"disconnect"},takeRecords:{this:"{that}.observer",method:"takeRecords"},createObserver:{funcName:"fluid.mutationObserver.createObserver",args:["{that}"]}}});fluid.mutationObserver.createObserver=function(that){var observer=new MutationObserver((function(mutationRecords){fluid.each(mutationRecords,(function(mutationRecord){for(var i=0;i<mutationRecord.addedNodes.length;i++){that.events.onNodeAdded.fire(mutationRecord.addedNodes[i],mutationRecord)}for(var j=0;j<mutationRecord.removedNodes.length;j++){that.events.onNodeRemoved.fire(mutationRecord.removedNodes[j],mutationRecord)}if(mutationRecord.type==="attributes"){that.events.onAttributeChanged.fire(mutationRecord.target,mutationRecord)}}))}));return observer};fluid.mutationObserver.observe=function(that,target,options){target=fluid.unwrap(target||that.container);that.observer.observe(target,options||that.options.defaultObserveConfig)};"use strict";fluid.defaults("fluid.textNodeParser",{gradeNames:["fluid.component"],events:{onParsedTextNode:null,afterParse:null},ignoredSelectors:{ariaHidden:'[aria-hidden="true"]'},parseHidden:false,invokers:{parse:{funcName:"fluid.textNodeParser.parse",args:["{that}","{arguments}.0","{arguments}.1","{that}.events.afterParse.fire"]},hasTextToRead:{funcName:"fluid.textNodeParser.hasTextToRead",args:["{arguments}.0","{that}.options.ignoredSelectors","{that}.options.parseHidden"]},getLang:"fluid.textNodeParser.getLang"}});fluid.textNodeParser.hasGlyph=function(str){return fluid.isValue(str)&&/\S/.test(str)};fluid.textNodeParser.hasTextToRead=function(elm,ignoredSelectors,parseHidden){if(elm&&(elm.tagName.toLowerCase()==="body"||parseHidden||elm.offsetParent)&&fluid.textNodeParser.hasGlyph(elm.innerText)){var selectors=Object.values(ignoredSelectors).filter((sel=>sel));return!selectors.find((selector=>elm.closest(selector)))}else{return false}};fluid.textNodeParser.getLang=function(elm){return $(elm).closest("[lang]").attr("lang")};fluid.textNodeParser.parse=function(that,elm,lang,afterParseEvent){elm=fluid.unwrap(elm);var parsed=[];if(that.hasTextToRead(elm)){var childNodes=elm.childNodes;var elementLang=elm.getAttribute("lang")||lang||that.getLang(elm);Array.prototype.forEach.call(childNodes,(function(childNode,childIndex){if(childNode.nodeType===Node.TEXT_NODE){var textNodeData={node:childNode,lang:elementLang,childIndex:childIndex};parsed.push(textNodeData);that.events.onParsedTextNode.fire(textNodeData)}else if(childNode.nodeType===Node.ELEMENT_NODE){parsed=parsed.concat(fluid.textNodeParser.parse(that,childNode,elementLang))}}))}if(afterParseEvent){afterParseEvent(that,parsed)}return parsed};
//# sourceMappingURL=infusion-framework-no-jquery.js.map