/*!
 * @license RequireJS 2.2.0 Copyright jQuery Foundation and other contributors.
 * Released under MIT license, http://github.com/requirejs/requirejs/LICENSE
 */
var requirejs,require,define;(function(global){var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version='2.2.0',commentRegExp=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,isBrowser=!!(typeof window!=='undefined'&&typeof navigator!=='undefined'&&window.document),isWebWorker=!isBrowser&&typeof importScripts!=='undefined',readyRegExp=isBrowser&&navigator.platform==='PLAYSTATION 3'?/^complete$/:/^(complete|loaded)$/,defContextName='_',isOpera=typeof opera!=='undefined'&&opera.toString()==='[object Opera]',contexts={},cfg={},globalDefQueue=[],useInteractive=false;function commentReplace(match,multi,multiText,singlePrefix){return singlePrefix||'';}
function isFunction(it){return ostring.call(it)==='[object Function]';}
function isArray(it){return ostring.call(it)==='[object Array]';}
function each(ary,func){if(ary){var i;for(i=0;i<ary.length;i+=1){if(ary[i]&&func(ary[i],i,ary)){break;}}}}
function eachReverse(ary,func){if(ary){var i;for(i=ary.length-1;i>-1;i-=1){if(ary[i]&&func(ary[i],i,ary)){break;}}}}
function hasProp(obj,prop){return hasOwn.call(obj,prop);}
function getOwn(obj,prop){return hasProp(obj,prop)&&obj[prop];}
function eachProp(obj,func){var prop;for(prop in obj){if(hasProp(obj,prop)){if(func(obj[prop],prop)){break;}}}}
function mixin(target,source,force,deepStringMixin){if(source){eachProp(source,function(value,prop){if(force||!hasProp(target,prop)){if(deepStringMixin&&typeof value==='object'&&value&&!isArray(value)&&!isFunction(value)&&!(value instanceof RegExp)){if(!target[prop]){target[prop]={};}
mixin(target[prop],value,force,deepStringMixin);}else{target[prop]=value;}}});}
return target;}
function bind(obj,fn){return function(){return fn.apply(obj,arguments);};}
function scripts(){return document.getElementsByTagName('script');}
function defaultOnError(err){throw err;}
function getGlobal(value){if(!value){return value;}
var g=global;each(value.split('.'),function(part){g=g[part];});return g;}
function makeError(id,msg,err,requireModules){var e=new Error(msg+'\nhttp://requirejs.org/docs/errors.html#'+id);e.requireType=id;e.requireModules=requireModules;if(err){e.originalError=err;}
return e;}
if(typeof define!=='undefined'){return;}
if(typeof requirejs!=='undefined'){if(isFunction(requirejs)){return;}
cfg=requirejs;requirejs=undefined;}
if(typeof require!=='undefined'&&!isFunction(require)){cfg=require;require=undefined;}
function newContext(contextName){var inCheckLoaded,Module,context,handlers,checkLoadedTimeoutId,config={waitSeconds:7,baseUrl:'./',paths:{},bundles:{},pkgs:{},shim:{},config:{}},registry={},enabledRegistry={},undefEvents={},defQueue=[],defined={},urlFetched={},bundlesMap={},requireCounter=1,unnormalizedCounter=1;function trimDots(ary){var i,part;for(i=0;i<ary.length;i++){part=ary[i];if(part==='.'){ary.splice(i,1);i-=1;}else if(part==='..'){if(i===0||(i===1&&ary[2]==='..')||ary[i-1]==='..'){continue;}else if(i>0){ary.splice(i-1,2);i-=2;}}}}
function normalize(name,baseName,applyMap){var pkgMain,mapValue,nameParts,i,j,nameSegment,lastIndex,foundMap,foundI,foundStarMap,starI,normalizedBaseParts,baseParts=(baseName&&baseName.split('/')),map=config.map,starMap=map&&map['*'];if(name){name=name.split('/');lastIndex=name.length-1;if(config.nodeIdCompat&&jsSuffixRegExp.test(name[lastIndex])){name[lastIndex]=name[lastIndex].replace(jsSuffixRegExp,'');}
if(name[0].charAt(0)==='.'&&baseParts){normalizedBaseParts=baseParts.slice(0,baseParts.length-1);name=normalizedBaseParts.concat(name);}
trimDots(name);name=name.join('/');}
if(applyMap&&map&&(baseParts||starMap)){nameParts=name.split('/');outerLoop:for(i=nameParts.length;i>0;i-=1){nameSegment=nameParts.slice(0,i).join('/');if(baseParts){for(j=baseParts.length;j>0;j-=1){mapValue=getOwn(map,baseParts.slice(0,j).join('/'));if(mapValue){mapValue=getOwn(mapValue,nameSegment);if(mapValue){foundMap=mapValue;foundI=i;break outerLoop;}}}}
if(!foundStarMap&&starMap&&getOwn(starMap,nameSegment)){foundStarMap=getOwn(starMap,nameSegment);starI=i;}}
if(!foundMap&&foundStarMap){foundMap=foundStarMap;foundI=starI;}
if(foundMap){nameParts.splice(0,foundI,foundMap);name=nameParts.join('/');}}
pkgMain=getOwn(config.pkgs,name);return pkgMain?pkgMain:name;}
function removeScript(name){if(isBrowser){each(scripts(),function(scriptNode){if(scriptNode.getAttribute('data-requiremodule')===name&&scriptNode.getAttribute('data-requirecontext')===context.contextName){scriptNode.parentNode.removeChild(scriptNode);return true;}});}}
function hasPathFallback(id){var pathConfig=getOwn(config.paths,id);if(pathConfig&&isArray(pathConfig)&&pathConfig.length>1){pathConfig.shift();context.require.undef(id);context.makeRequire(null,{skipMap:true})([id]);return true;}}
function splitPrefix(name){var prefix,index=name?name.indexOf('!'):-1;if(index>-1){prefix=name.substring(0,index);name=name.substring(index+1,name.length);}
return[prefix,name];}
function makeModuleMap(name,parentModuleMap,isNormalized,applyMap){var url,pluginModule,suffix,nameParts,prefix=null,parentName=parentModuleMap?parentModuleMap.name:null,originalName=name,isDefine=true,normalizedName='';if(!name){isDefine=false;name='_@r'+(requireCounter+=1);}
nameParts=splitPrefix(name);prefix=nameParts[0];name=nameParts[1];if(prefix){prefix=normalize(prefix,parentName,applyMap);pluginModule=getOwn(defined,prefix);}
if(name){if(prefix){if(pluginModule&&pluginModule.normalize){normalizedName=pluginModule.normalize(name,function(name){return normalize(name,parentName,applyMap);});}else{normalizedName=name.indexOf('!')===-1?normalize(name,parentName,applyMap):name;}}else{normalizedName=normalize(name,parentName,applyMap);nameParts=splitPrefix(normalizedName);prefix=nameParts[0];normalizedName=nameParts[1];isNormalized=true;url=context.nameToUrl(normalizedName);}}
suffix=prefix&&!pluginModule&&!isNormalized?'_unnormalized'+(unnormalizedCounter+=1):'';return{prefix:prefix,name:normalizedName,parentMap:parentModuleMap,unnormalized:!!suffix,url:url,originalName:originalName,isDefine:isDefine,id:(prefix?prefix+'!'+normalizedName:normalizedName)+suffix};}
function getModule(depMap){var id=depMap.id,mod=getOwn(registry,id);if(!mod){mod=registry[id]=new context.Module(depMap);}
return mod;}
function on(depMap,name,fn){var id=depMap.id,mod=getOwn(registry,id);if(hasProp(defined,id)&&(!mod||mod.defineEmitComplete)){if(name==='defined'){fn(defined[id]);}}else{mod=getModule(depMap);if(mod.error&&name==='error'){fn(mod.error);}else{mod.on(name,fn);}}}
function onError(err,errback){var ids=err.requireModules,notified=false;if(errback){errback(err);}else{each(ids,function(id){var mod=getOwn(registry,id);if(mod){mod.error=err;if(mod.events.error){notified=true;mod.emit('error',err);}}});if(!notified){req.onError(err);}}}
function takeGlobalQueue(){if(globalDefQueue.length){each(globalDefQueue,function(queueItem){var id=queueItem[0];if(typeof id==='string'){context.defQueueMap[id]=true;}
defQueue.push(queueItem);});globalDefQueue=[];}}
handlers={'require':function(mod){if(mod.require){return mod.require;}else{return(mod.require=context.makeRequire(mod.map));}},'exports':function(mod){mod.usingExports=true;if(mod.map.isDefine){if(mod.exports){return(defined[mod.map.id]=mod.exports);}else{return(mod.exports=defined[mod.map.id]={});}}},'module':function(mod){if(mod.module){return mod.module;}else{return(mod.module={id:mod.map.id,uri:mod.map.url,config:function(){return getOwn(config.config,mod.map.id)||{};},exports:mod.exports||(mod.exports={})});}}};function cleanRegistry(id){delete registry[id];delete enabledRegistry[id];}
function breakCycle(mod,traced,processed){var id=mod.map.id;if(mod.error){mod.emit('error',mod.error);}else{traced[id]=true;each(mod.depMaps,function(depMap,i){var depId=depMap.id,dep=getOwn(registry,depId);if(dep&&!mod.depMatched[i]&&!processed[depId]){if(getOwn(traced,depId)){mod.defineDep(i,defined[depId]);mod.check();}else{breakCycle(dep,traced,processed);}}});processed[id]=true;}}
function checkLoaded(){var err,usingPathFallback,waitInterval=config.waitSeconds*1000,expired=waitInterval&&(context.startTime+waitInterval)<new Date().getTime(),noLoads=[],reqCalls=[],stillLoading=false,needCycleCheck=true;if(inCheckLoaded){return;}
inCheckLoaded=true;eachProp(enabledRegistry,function(mod){var map=mod.map,modId=map.id;if(!mod.enabled){return;}
if(!map.isDefine){reqCalls.push(mod);}
if(!mod.error){if(!mod.inited&&expired){if(hasPathFallback(modId)){usingPathFallback=true;stillLoading=true;}else{noLoads.push(modId);removeScript(modId);}}else if(!mod.inited&&mod.fetched&&map.isDefine){stillLoading=true;if(!map.prefix){return(needCycleCheck=false);}}}});if(expired&&noLoads.length){err=makeError('timeout','Load timeout for modules: '+noLoads,null,noLoads);err.contextName=context.contextName;return onError(err);}
if(needCycleCheck){each(reqCalls,function(mod){breakCycle(mod,{},{});});}
if((!expired||usingPathFallback)&&stillLoading){if((isBrowser||isWebWorker)&&!checkLoadedTimeoutId){checkLoadedTimeoutId=setTimeout(function(){checkLoadedTimeoutId=0;checkLoaded();},50);}}
inCheckLoaded=false;}
Module=function(map){this.events=getOwn(undefEvents,map.id)||{};this.map=map;this.shim=getOwn(config.shim,map.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0;};Module.prototype={init:function(depMaps,factory,errback,options){options=options||{};if(this.inited){return;}
this.factory=factory;if(errback){this.on('error',errback);}else if(this.events.error){errback=bind(this,function(err){this.emit('error',err);});}
this.depMaps=depMaps&&depMaps.slice(0);this.errback=errback;this.inited=true;this.ignore=options.ignore;if(options.enabled||this.enabled){this.enable();}else{this.check();}},defineDep:function(i,depExports){if(!this.depMatched[i]){this.depMatched[i]=true;this.depCount-=1;this.depExports[i]=depExports;}},fetch:function(){if(this.fetched){return;}
this.fetched=true;context.startTime=(new Date()).getTime();var map=this.map;if(this.shim){context.makeRequire(this.map,{enableBuildCallback:true})(this.shim.deps||[],bind(this,function(){return map.prefix?this.callPlugin():this.load();}));}else{return map.prefix?this.callPlugin():this.load();}},load:function(){var url=this.map.url;if(!urlFetched[url]){urlFetched[url]=true;context.load(this.map.id,url);}},check:function(){if(!this.enabled||this.enabling){return;}
var err,cjsModule,id=this.map.id,depExports=this.depExports,exports=this.exports,factory=this.factory;if(!this.inited){if(!hasProp(context.defQueueMap,id)){this.fetch();}}else if(this.error){this.emit('error',this.error);}else if(!this.defining){this.defining=true;if(this.depCount<1&&!this.defined){if(isFunction(factory)){if((this.events.error&&this.map.isDefine)||req.onError!==defaultOnError){try{exports=context.execCb(id,factory,depExports,exports);}catch(e){err=e;}}else{exports=context.execCb(id,factory,depExports,exports);}
if(this.map.isDefine&&exports===undefined){cjsModule=this.module;if(cjsModule){exports=cjsModule.exports;}else if(this.usingExports){exports=this.exports;}}
if(err){err.requireMap=this.map;err.requireModules=this.map.isDefine?[this.map.id]:null;err.requireType=this.map.isDefine?'define':'require';return onError((this.error=err));}}else{exports=factory;}
this.exports=exports;if(this.map.isDefine&&!this.ignore){defined[id]=exports;if(req.onResourceLoad){var resLoadMaps=[];each(this.depMaps,function(depMap){resLoadMaps.push(depMap.normalizedMap||depMap);});req.onResourceLoad(context,this.map,resLoadMaps);}}
cleanRegistry(id);this.defined=true;}
this.defining=false;if(this.defined&&!this.defineEmitted){this.defineEmitted=true;this.emit('defined',this.exports);this.defineEmitComplete=true;}}},callPlugin:function(){var map=this.map,id=map.id,pluginMap=makeModuleMap(map.prefix);this.depMaps.push(pluginMap);on(pluginMap,'defined',bind(this,function(plugin){var load,normalizedMap,normalizedMod,bundleId=getOwn(bundlesMap,this.map.id),name=this.map.name,parentName=this.map.parentMap?this.map.parentMap.name:null,localRequire=context.makeRequire(map.parentMap,{enableBuildCallback:true});if(this.map.unnormalized){if(plugin.normalize){name=plugin.normalize(name,function(name){return normalize(name,parentName,true);})||'';}
normalizedMap=makeModuleMap(map.prefix+'!'+name,this.map.parentMap);on(normalizedMap,'defined',bind(this,function(value){this.map.normalizedMap=normalizedMap;this.init([],function(){return value;},null,{enabled:true,ignore:true});}));normalizedMod=getOwn(registry,normalizedMap.id);if(normalizedMod){this.depMaps.push(normalizedMap);if(this.events.error){normalizedMod.on('error',bind(this,function(err){this.emit('error',err);}));}
normalizedMod.enable();}
return;}
if(bundleId){this.map.url=context.nameToUrl(bundleId);this.load();return;}
load=bind(this,function(value){this.init([],function(){return value;},null,{enabled:true});});load.error=bind(this,function(err){this.inited=true;this.error=err;err.requireModules=[id];eachProp(registry,function(mod){if(mod.map.id.indexOf(id+'_unnormalized')===0){cleanRegistry(mod.map.id);}});onError(err);});load.fromText=bind(this,function(text,textAlt){var moduleName=map.name,moduleMap=makeModuleMap(moduleName),hasInteractive=useInteractive;if(textAlt){text=textAlt;}
if(hasInteractive){useInteractive=false;}
getModule(moduleMap);if(hasProp(config.config,id)){config.config[moduleName]=config.config[id];}
try{req.exec(text);}catch(e){return onError(makeError('fromtexteval','fromText eval for '+id+' failed: '+e,e,[id]));}
if(hasInteractive){useInteractive=true;}
this.depMaps.push(moduleMap);context.completeLoad(moduleName);localRequire([moduleName],load);});plugin.load(map.name,localRequire,load,config);}));context.enable(pluginMap,this);this.pluginMaps[pluginMap.id]=pluginMap;},enable:function(){enabledRegistry[this.map.id]=this;this.enabled=true;this.enabling=true;each(this.depMaps,bind(this,function(depMap,i){var id,mod,handler;if(typeof depMap==='string'){depMap=makeModuleMap(depMap,(this.map.isDefine?this.map:this.map.parentMap),false,!this.skipMap);this.depMaps[i]=depMap;handler=getOwn(handlers,depMap.id);if(handler){this.depExports[i]=handler(this);return;}
this.depCount+=1;on(depMap,'defined',bind(this,function(depExports){if(this.undefed){return;}
this.defineDep(i,depExports);this.check();}));if(this.errback){on(depMap,'error',bind(this,this.errback));}else if(this.events.error){on(depMap,'error',bind(this,function(err){this.emit('error',err);}));}}
id=depMap.id;mod=registry[id];if(!hasProp(handlers,id)&&mod&&!mod.enabled){context.enable(depMap,this);}}));eachProp(this.pluginMaps,bind(this,function(pluginMap){var mod=getOwn(registry,pluginMap.id);if(mod&&!mod.enabled){context.enable(pluginMap,this);}}));this.enabling=false;this.check();},on:function(name,cb){var cbs=this.events[name];if(!cbs){cbs=this.events[name]=[];}
cbs.push(cb);},emit:function(name,evt){each(this.events[name],function(cb){cb(evt);});if(name==='error'){delete this.events[name];}}};function callGetModule(args){if(!hasProp(defined,args[0])){getModule(makeModuleMap(args[0],null,true)).init(args[1],args[2]);}}
function removeListener(node,func,name,ieName){if(node.detachEvent&&!isOpera){if(ieName){node.detachEvent(ieName,func);}}else{node.removeEventListener(name,func,false);}}
function getScriptData(evt){var node=evt.currentTarget||evt.srcElement;removeListener(node,context.onScriptLoad,'load','onreadystatechange');removeListener(node,context.onScriptError,'error');return{node:node,id:node&&node.getAttribute('data-requiremodule')};}
function intakeDefines(){var args;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null){return onError(makeError('mismatch','Mismatched anonymous define() module: '+
args[args.length-1]));}else{callGetModule(args);}}
context.defQueueMap={};}
context={config:config,contextName:contextName,registry:registry,defined:defined,urlFetched:urlFetched,defQueue:defQueue,defQueueMap:{},Module:Module,makeModuleMap:makeModuleMap,nextTick:req.nextTick,onError:onError,configure:function(cfg){if(cfg.baseUrl){if(cfg.baseUrl.charAt(cfg.baseUrl.length-1)!=='/'){cfg.baseUrl+='/';}}
if(typeof cfg.urlArgs==='string'){var urlArgs=cfg.urlArgs;cfg.urlArgs=function(id,url){return(url.indexOf('?')===-1?'?':'&')+urlArgs;};}
var shim=config.shim,objs={paths:true,bundles:true,config:true,map:true};eachProp(cfg,function(value,prop){if(objs[prop]){if(!config[prop]){config[prop]={};}
mixin(config[prop],value,true,true);}else{config[prop]=value;}});if(cfg.bundles){eachProp(cfg.bundles,function(value,prop){each(value,function(v){if(v!==prop){bundlesMap[v]=prop;}});});}
if(cfg.shim){eachProp(cfg.shim,function(value,id){if(isArray(value)){value={deps:value};}
if((value.exports||value.init)&&!value.exportsFn){value.exportsFn=context.makeShimExports(value);}
shim[id]=value;});config.shim=shim;}
if(cfg.packages){each(cfg.packages,function(pkgObj){var location,name;pkgObj=typeof pkgObj==='string'?{name:pkgObj}:pkgObj;name=pkgObj.name;location=pkgObj.location;if(location){config.paths[name]=pkgObj.location;}
config.pkgs[name]=pkgObj.name+'/'+(pkgObj.main||'main').replace(currDirRegExp,'').replace(jsSuffixRegExp,'');});}
eachProp(registry,function(mod,id){if(!mod.inited&&!mod.map.unnormalized){mod.map=makeModuleMap(id,null,true);}});if(cfg.deps||cfg.callback){context.require(cfg.deps||[],cfg.callback);}},makeShimExports:function(value){function fn(){var ret;if(value.init){ret=value.init.apply(global,arguments);}
return ret||(value.exports&&getGlobal(value.exports));}
return fn;},makeRequire:function(relMap,options){options=options||{};function localRequire(deps,callback,errback){var id,map,requireMod;if(options.enableBuildCallback&&callback&&isFunction(callback)){callback.__requireJsBuild=true;}
if(typeof deps==='string'){if(isFunction(callback)){return onError(makeError('requireargs','Invalid require call'),errback);}
if(relMap&&hasProp(handlers,deps)){return handlers[deps](registry[relMap.id]);}
if(req.get){return req.get(context,deps,relMap,localRequire);}
map=makeModuleMap(deps,relMap,false,true);id=map.id;if(!hasProp(defined,id)){return onError(makeError('notloaded','Module name "'+
id+'" has not been loaded yet for context: '+
contextName+
(relMap?'':'. Use require([])')));}
return defined[id];}
intakeDefines();context.nextTick(function(){intakeDefines();requireMod=getModule(makeModuleMap(null,relMap));requireMod.skipMap=options.skipMap;requireMod.init(deps,callback,errback,{enabled:true});checkLoaded();});return localRequire;}
mixin(localRequire,{isBrowser:isBrowser,toUrl:function(moduleNamePlusExt){var ext,index=moduleNamePlusExt.lastIndexOf('.'),segment=moduleNamePlusExt.split('/')[0],isRelative=segment==='.'||segment==='..';if(index!==-1&&(!isRelative||index>1)){ext=moduleNamePlusExt.substring(index,moduleNamePlusExt.length);moduleNamePlusExt=moduleNamePlusExt.substring(0,index);}
return context.nameToUrl(normalize(moduleNamePlusExt,relMap&&relMap.id,true),ext,true);},defined:function(id){return hasProp(defined,makeModuleMap(id,relMap,false,true).id);},specified:function(id){id=makeModuleMap(id,relMap,false,true).id;return hasProp(defined,id)||hasProp(registry,id);}});if(!relMap){localRequire.undef=function(id){takeGlobalQueue();var map=makeModuleMap(id,relMap,true),mod=getOwn(registry,id);mod.undefed=true;removeScript(id);delete defined[id];delete urlFetched[map.url];delete undefEvents[id];eachReverse(defQueue,function(args,i){if(args[0]===id){defQueue.splice(i,1);}});delete context.defQueueMap[id];if(mod){if(mod.events.defined){undefEvents[id]=mod.events;}
cleanRegistry(id);}};}
return localRequire;},enable:function(depMap){var mod=getOwn(registry,depMap.id);if(mod){getModule(depMap).enable();}},completeLoad:function(moduleName){var found,args,mod,shim=getOwn(config.shim,moduleName)||{},shExports=shim.exports;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null){args[0]=moduleName;if(found){break;}
found=true;}else if(args[0]===moduleName){found=true;}
callGetModule(args);}
context.defQueueMap={};mod=getOwn(registry,moduleName);if(!found&&!hasProp(defined,moduleName)&&mod&&!mod.inited){if(config.enforceDefine&&(!shExports||!getGlobal(shExports))){if(hasPathFallback(moduleName)){return;}else{return onError(makeError('nodefine','No define call for '+moduleName,null,[moduleName]));}}else{callGetModule([moduleName,(shim.deps||[]),shim.exportsFn]);}}
checkLoaded();},nameToUrl:function(moduleName,ext,skipExt){var paths,syms,i,parentModule,url,parentPath,bundleId,pkgMain=getOwn(config.pkgs,moduleName);if(pkgMain){moduleName=pkgMain;}
bundleId=getOwn(bundlesMap,moduleName);if(bundleId){return context.nameToUrl(bundleId,ext,skipExt);}
if(req.jsExtRegExp.test(moduleName)){url=moduleName+(ext||'');}else{paths=config.paths;syms=moduleName.split('/');for(i=syms.length;i>0;i-=1){parentModule=syms.slice(0,i).join('/');parentPath=getOwn(paths,parentModule);if(parentPath){if(isArray(parentPath)){parentPath=parentPath[0];}
syms.splice(0,i,parentPath);break;}}
url=syms.join('/');url+=(ext||(/^data\:|^blob\:|\?/.test(url)||skipExt?'':'.js'));url=(url.charAt(0)==='/'||url.match(/^[\w\+\.\-]+:/)?'':config.baseUrl)+url;}
return config.urlArgs&&!/^blob\:/.test(url)?url+config.urlArgs(moduleName,url):url;},load:function(id,url){req.load(context,id,url);},execCb:function(name,callback,args,exports){return callback.apply(exports,args);},onScriptLoad:function(evt){if(evt.type==='load'||(readyRegExp.test((evt.currentTarget||evt.srcElement).readyState))){interactiveScript=null;var data=getScriptData(evt);context.completeLoad(data.id);}},onScriptError:function(evt){var data=getScriptData(evt);if(!hasPathFallback(data.id)){var parents=[];eachProp(registry,function(value,key){if(key.indexOf('_@r')!==0){each(value.depMaps,function(depMap){if(depMap.id===data.id){parents.push(key);return true;}});}});return onError(makeError('scripterror','Script error for "'+data.id+
(parents.length?'", needed by: '+parents.join(', '):'"'),evt,[data.id]));}}};context.require=context.makeRequire();return context;}
req=requirejs=function(deps,callback,errback,optional){var context,config,contextName=defContextName;if(!isArray(deps)&&typeof deps!=='string'){config=deps;if(isArray(callback)){deps=callback;callback=errback;errback=optional;}else{deps=[];}}
if(config&&config.context){contextName=config.context;}
context=getOwn(contexts,contextName);if(!context){context=contexts[contextName]=req.s.newContext(contextName);}
if(config){context.configure(config);}
return context.require(deps,callback,errback);};req.config=function(config){return req(config);};req.nextTick=typeof setTimeout!=='undefined'?function(fn){setTimeout(fn,4);}:function(fn){fn();};if(!require){require=req;}
req.version=version;req.jsExtRegExp=/^\/|:|\?|\.js$/;req.isBrowser=isBrowser;s=req.s={contexts:contexts,newContext:newContext};req({});each(['toUrl','undef','defined','specified'],function(prop){req[prop]=function(){var ctx=contexts[defContextName];return ctx.require[prop].apply(ctx,arguments);};});if(isBrowser){head=s.head=document.getElementsByTagName('head')[0];baseElement=document.getElementsByTagName('base')[0];if(baseElement){head=s.head=baseElement.parentNode;}}
req.onError=defaultOnError;req.createNode=function(config,moduleName,url){var node=config.xhtml?document.createElementNS('http://www.w3.org/1999/xhtml','html:script'):document.createElement('script');node.type=config.scriptType||'text/javascript';node.charset='utf-8';node.async=true;return node;};req.load=function(context,moduleName,url){var config=(context&&context.config)||{},node;if(isBrowser){node=req.createNode(config,moduleName,url);node.setAttribute('data-requirecontext',context.contextName);node.setAttribute('data-requiremodule',moduleName);if(node.attachEvent&&!(node.attachEvent.toString&&node.attachEvent.toString().indexOf('[native code')<0)&&!isOpera){useInteractive=true;node.attachEvent('onreadystatechange',context.onScriptLoad);}else{node.addEventListener('load',context.onScriptLoad,false);node.addEventListener('error',context.onScriptError,false);}
node.src=url;if(config.onNodeCreated){config.onNodeCreated(node,config,moduleName,url);}
currentlyAddingScript=node;if(baseElement){head.insertBefore(node,baseElement);}else{head.appendChild(node);}
currentlyAddingScript=null;return node;}else if(isWebWorker){try{setTimeout(function(){},0);importScripts(url);context.completeLoad(moduleName);}catch(e){context.onError(makeError('importscripts','importScripts failed for '+
moduleName+' at '+url,e,[moduleName]));}}};function getInteractiveScript(){if(interactiveScript&&interactiveScript.readyState==='interactive'){return interactiveScript;}
eachReverse(scripts(),function(script){if(script.readyState==='interactive'){return(interactiveScript=script);}});return interactiveScript;}
if(isBrowser&&!cfg.skipDataMain){eachReverse(scripts(),function(script){if(!head){head=script.parentNode;}
dataMain=script.getAttribute('data-main');if(dataMain){mainScript=dataMain;if(!cfg.baseUrl&&mainScript.indexOf('!')===-1){src=mainScript.split('/');mainScript=src.pop();subPath=src.length?src.join('/')+'/':'./';cfg.baseUrl=subPath;}
mainScript=mainScript.replace(jsSuffixRegExp,'');if(req.jsExtRegExp.test(mainScript)){mainScript=dataMain;}
cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript];return true;}});}
define=function(name,deps,callback){var node,context;if(typeof name!=='string'){callback=deps;deps=name;name=null;}
if(!isArray(deps)){callback=deps;deps=null;}
if(!deps&&isFunction(callback)){deps=[];if(callback.length){callback.toString().replace(commentRegExp,commentReplace).replace(cjsRequireRegExp,function(match,dep){deps.push(dep);});deps=(callback.length===1?['require']:['require','exports','module']).concat(deps);}}
if(useInteractive){node=currentlyAddingScript||getInteractiveScript();if(node){if(!name){name=node.getAttribute('data-requiremodule');}
context=contexts[node.getAttribute('data-requirecontext')];}}
if(context){context.defQueue.push([name,deps,callback]);context.defQueueMap[name]=true;}else{globalDefQueue.push([name,deps,callback]);}};define.amd={jQuery:true};req.exec=function(text){return eval(text);};req(cfg);}(this));
/*!
 * The MIT License (MIT)
 * 
 * Copyright (c) 2013-2015 Petka Antonov
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 */!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('bluebird',[],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var SomePromiseArray=Promise._SomePromiseArray;function any(promises){var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(1);ret.setUnwrap();ret.init();return promise;}
Promise.any=function(promises){return any(promises);};Promise.prototype.any=function(){return any(this);};};},{}],2:[function(_dereq_,module,exports){"use strict";var firstLineError;try{throw new Error();}catch(e){firstLineError=e;}
var schedule=_dereq_("./schedule");var Queue=_dereq_("./queue");var util=_dereq_("./util");function Async(){this._customScheduler=false;this._isTickUsed=false;this._lateQueue=new Queue(16);this._normalQueue=new Queue(16);this._haveDrainedQueues=false;this._trampolineEnabled=true;var self=this;this.drainQueues=function(){self._drainQueues();};this._schedule=schedule;}
Async.prototype.setScheduler=function(fn){var prev=this._schedule;this._schedule=fn;this._customScheduler=true;return prev;};Async.prototype.hasCustomScheduler=function(){return this._customScheduler;};Async.prototype.enableTrampoline=function(){this._trampolineEnabled=true;};Async.prototype.disableTrampolineIfNecessary=function(){if(util.hasDevTools){this._trampolineEnabled=false;}};Async.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues;};Async.prototype.fatalError=function(e,isNode){if(isNode){process.stderr.write("Fatal "+(e instanceof Error?e.stack:e)+"\n");process.exit(2);}else{this.throwLater(e);}};Async.prototype.throwLater=function(fn,arg){if(arguments.length===1){arg=fn;fn=function(){throw arg;};}
if(typeof setTimeout!=="undefined"){setTimeout(function(){fn(arg);},0);}else try{this._schedule(function(){fn(arg);});}catch(e){throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}};function AsyncInvokeLater(fn,receiver,arg){this._lateQueue.push(fn,receiver,arg);this._queueTick();}
function AsyncInvoke(fn,receiver,arg){this._normalQueue.push(fn,receiver,arg);this._queueTick();}
function AsyncSettlePromises(promise){this._normalQueue._pushOne(promise);this._queueTick();}
if(!util.hasDevTools){Async.prototype.invokeLater=AsyncInvokeLater;Async.prototype.invoke=AsyncInvoke;Async.prototype.settlePromises=AsyncSettlePromises;}else{Async.prototype.invokeLater=function(fn,receiver,arg){if(this._trampolineEnabled){AsyncInvokeLater.call(this,fn,receiver,arg);}else{this._schedule(function(){setTimeout(function(){fn.call(receiver,arg);},100);});}};Async.prototype.invoke=function(fn,receiver,arg){if(this._trampolineEnabled){AsyncInvoke.call(this,fn,receiver,arg);}else{this._schedule(function(){fn.call(receiver,arg);});}};Async.prototype.settlePromises=function(promise){if(this._trampolineEnabled){AsyncSettlePromises.call(this,promise);}else{this._schedule(function(){promise._settlePromises();});}};}
Async.prototype.invokeFirst=function(fn,receiver,arg){this._normalQueue.unshift(fn,receiver,arg);this._queueTick();};Async.prototype._drainQueue=function(queue){while(queue.length()>0){var fn=queue.shift();if(typeof fn!=="function"){fn._settlePromises();continue;}
var receiver=queue.shift();var arg=queue.shift();fn.call(receiver,arg);}};Async.prototype._drainQueues=function(){this._drainQueue(this._normalQueue);this._reset();this._haveDrainedQueues=true;this._drainQueue(this._lateQueue);};Async.prototype._queueTick=function(){if(!this._isTickUsed){this._isTickUsed=true;this._schedule(this.drainQueues);}};Async.prototype._reset=function(){this._isTickUsed=false;};module.exports=Async;module.exports.firstLineError=firstLineError;},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,debug){var calledBind=false;var rejectThis=function(_,e){this._reject(e);};var targetRejected=function(e,context){context.promiseRejectionQueued=true;context.bindingPromise._then(rejectThis,rejectThis,null,this,e);};var bindingResolved=function(thisArg,context){if(((this._bitField&50397184)===0)){this._resolveCallback(context.target);}};var bindingRejected=function(e,context){if(!context.promiseRejectionQueued)this._reject(e);};Promise.prototype.bind=function(thisArg){if(!calledBind){calledBind=true;Promise.prototype._propagateFrom=debug.propagateFromFunction();Promise.prototype._boundValue=debug.boundValueFunction();}
var maybePromise=tryConvertToPromise(thisArg);var ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();ret._setBoundTo(maybePromise);if(maybePromise instanceof Promise){var context={promiseRejectionQueued:false,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,undefined,ret,context);maybePromise._then(bindingResolved,bindingRejected,undefined,ret,context);ret._setOnCancel(maybePromise);}else{ret._resolveCallback(target);}
return ret;};Promise.prototype._setBoundTo=function(obj){if(obj!==undefined){this._bitField=this._bitField|2097152;this._boundTo=obj;}else{this._bitField=this._bitField&(~2097152);}};Promise.prototype._isBound=function(){return(this._bitField&2097152)===2097152;};Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg);};};},{}],4:[function(_dereq_,module,exports){"use strict";var old;if(typeof Promise!=="undefined")old=Promise;function noConflict(){try{if(Promise===bluebird)Promise=old;}
catch(e){}
return bluebird;}
var bluebird=_dereq_("./promise")();bluebird.noConflict=noConflict;module.exports=bluebird;},{"./promise":22}],5:[function(_dereq_,module,exports){"use strict";var cr=Object.create;if(cr){var callerCache=cr(null);var getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0;}
module.exports=function(Promise){var util=_dereq_("./util");var canEvaluate=util.canEvaluate;var isIdentifier=util.isIdentifier;var getMethodCaller;var getGetter;if(!true){var makeMethodCaller=function(methodName){return new Function("ensureMethod","                                    \n        return function(obj) {                                               \n            'use strict'                                                     \n            var len = this.length;                                           \n            ensureMethod(obj, 'methodName');                                 \n            switch(len) {                                                    \n                case 1: return obj.methodName(this[0]);                      \n                case 2: return obj.methodName(this[0], this[1]);             \n                case 3: return obj.methodName(this[0], this[1], this[2]);    \n                case 0: return obj.methodName();                             \n                default:                                                     \n                    return obj.methodName.apply(obj, this);                  \n            }                                                                \n        };                                                                   \n        ".replace(/methodName/g,methodName))(ensureMethod);};var makeGetter=function(propertyName){return new Function("obj","                                             \n        'use strict';                                                        \n        return obj.propertyName;                                             \n        ".replace("propertyName",propertyName));};var getCompiled=function(name,compiler,cache){var ret=cache[name];if(typeof ret!=="function"){if(!isIdentifier(name)){return null;}
ret=compiler(name);cache[name]=ret;cache[" size"]++;if(cache[" size"]>512){var keys=Object.keys(cache);for(var i=0;i<256;++i)delete cache[keys[i]];cache[" size"]=keys.length-256;}}
return ret;};getMethodCaller=function(name){return getCompiled(name,makeMethodCaller,callerCache);};getGetter=function(name){return getCompiled(name,makeGetter,getterCache);};}
function ensureMethod(obj,methodName){var fn;if(obj!=null)fn=obj[methodName];if(typeof fn!=="function"){var message="Object "+util.classString(obj)+" has no method '"+
util.toString(methodName)+"'";throw new Promise.TypeError(message);}
return fn;}
function caller(obj){var methodName=this.pop();var fn=ensureMethod(obj,methodName);return fn.apply(obj,this);}
Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);;if(!true){if(canEvaluate){var maybeCaller=getMethodCaller(methodName);if(maybeCaller!==null){return this._then(maybeCaller,undefined,undefined,args,undefined);}}}
args.push(methodName);return this._then(caller,undefined,undefined,args,undefined);};function namedGetter(obj){return obj[this];}
function indexedGetter(obj){var index=+this;if(index<0)index=Math.max(0,index+obj.length);return obj[index];}
Promise.prototype.get=function(propertyName){var isIndex=(typeof propertyName==="number");var getter;if(!isIndex){if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=maybeGetter!==null?maybeGetter:namedGetter;}else{getter=namedGetter;}}else{getter=indexedGetter;}
return this._then(getter,undefined,undefined,propertyName,undefined);};};},{"./util":36}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var async=Promise._async;Promise.prototype["break"]=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");var promise=this;var child=promise;while(promise.isCancellable()){if(!promise._cancelBy(child)){if(child._isFollowing()){child._followee().cancel();}else{child._cancelBranched();}
break;}
var parent=promise._cancellationParent;if(parent==null||!parent.isCancellable()){if(promise._isFollowing()){promise._followee().cancel();}else{promise._cancelBranched();}
break;}else{if(promise._isFollowing())promise._followee().cancel();child=promise;promise=parent;}}};Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--;};Promise.prototype._enoughBranchesHaveCancelled=function(){return this._branchesRemainingToCancel===undefined||this._branchesRemainingToCancel<=0;};Promise.prototype._cancelBy=function(canceller){if(canceller===this){this._branchesRemainingToCancel=0;this._invokeOnCancel();return true;}else{this._branchHasCancelled();if(this._enoughBranchesHaveCancelled()){this._invokeOnCancel();return true;}}
return false;};Promise.prototype._cancelBranched=function(){if(this._enoughBranchesHaveCancelled()){this._cancel();}};Promise.prototype._cancel=function(){if(!this.isCancellable())return;this._setCancelled();async.invoke(this._cancelPromises,this,undefined);};Promise.prototype._cancelPromises=function(){if(this._length()>0)this._settlePromises();};Promise.prototype._unsetOnCancel=function(){this._onCancelField=undefined;};Promise.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled();};Promise.prototype._doInvokeOnCancel=function(onCancelCallback,internalOnly){if(util.isArray(onCancelCallback)){for(var i=0;i<onCancelCallback.length;++i){this._doInvokeOnCancel(onCancelCallback[i],internalOnly);}}else if(onCancelCallback!==undefined){if(typeof onCancelCallback==="function"){if(!internalOnly){var e=tryCatch(onCancelCallback).call(this._boundValue());if(e===errorObj){this._attachExtraTrace(e.e);async.throwLater(e.e);}}}else{onCancelCallback._resultCancelled(this);}}};Promise.prototype._invokeOnCancel=function(){var onCancelCallback=this._onCancel();this._unsetOnCancel();async.invoke(this._doInvokeOnCancel,this,onCancelCallback);};Promise.prototype._invokeInternalOnCancel=function(){if(this.isCancellable()){this._doInvokeOnCancel(this._onCancel(),true);this._unsetOnCancel();}};Promise.prototype._resultCancelled=function(){this.cancel();};};},{"./util":36}],7:[function(_dereq_,module,exports){"use strict";module.exports=function(NEXT_FILTER){var util=_dereq_("./util");var getKeys=_dereq_("./es5").keys;var tryCatch=util.tryCatch;var errorObj=util.errorObj;function catchFilter(instances,cb,promise){return function(e){var boundTo=promise._boundValue();predicateLoop:for(var i=0;i<instances.length;++i){var item=instances[i];if(item===Error||(item!=null&&item.prototype instanceof Error)){if(e instanceof item){return tryCatch(cb).call(boundTo,e);}}else if(typeof item==="function"){var matchesPredicate=tryCatch(item).call(boundTo,e);if(matchesPredicate===errorObj){return matchesPredicate;}else if(matchesPredicate){return tryCatch(cb).call(boundTo,e);}}else if(util.isObject(e)){var keys=getKeys(item);for(var j=0;j<keys.length;++j){var key=keys[j];if(item[key]!=e[key]){continue predicateLoop;}}
return tryCatch(cb).call(boundTo,e);}}
return NEXT_FILTER;};}
return catchFilter;};},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var longStackTraces=false;var contextStack=[];Promise.prototype._promiseCreated=function(){};Promise.prototype._pushContext=function(){};Promise.prototype._popContext=function(){return null;};Promise._peekContext=Promise.prototype._peekContext=function(){};function Context(){this._trace=new Context.CapturedTrace(peekContext());}
Context.prototype._pushContext=function(){if(this._trace!==undefined){this._trace._promiseCreated=null;contextStack.push(this._trace);}};Context.prototype._popContext=function(){if(this._trace!==undefined){var trace=contextStack.pop();var ret=trace._promiseCreated;trace._promiseCreated=null;return ret;}
return null;};function createContext(){if(longStackTraces)return new Context();}
function peekContext(){var lastIndex=contextStack.length-1;if(lastIndex>=0){return contextStack[lastIndex];}
return undefined;}
Context.CapturedTrace=null;Context.create=createContext;Context.deactivateLongStackTraces=function(){};Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext;var Promise_popContext=Promise.prototype._popContext;var Promise_PeekContext=Promise._peekContext;var Promise_peekContext=Promise.prototype._peekContext;var Promise_promiseCreated=Promise.prototype._promiseCreated;Context.deactivateLongStackTraces=function(){Promise.prototype._pushContext=Promise_pushContext;Promise.prototype._popContext=Promise_popContext;Promise._peekContext=Promise_PeekContext;Promise.prototype._peekContext=Promise_peekContext;Promise.prototype._promiseCreated=Promise_promiseCreated;longStackTraces=false;};longStackTraces=true;Promise.prototype._pushContext=Context.prototype._pushContext;Promise.prototype._popContext=Context.prototype._popContext;Promise._peekContext=Promise.prototype._peekContext=peekContext;Promise.prototype._promiseCreated=function(){var ctx=this._peekContext();if(ctx&&ctx._promiseCreated==null)ctx._promiseCreated=this;};};return Context;};},{}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,Context){var getDomain=Promise._getDomain;var async=Promise._async;var Warning=_dereq_("./errors").Warning;var util=_dereq_("./util");var canAttachTrace=util.canAttachTrace;var unhandledRejectionHandled;var possiblyUnhandledRejection;var bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;var stackFramePattern=null;var formatStack=null;var indentStackFrames=false;var printWarning;var debugging=!!(util.env("BLUEBIRD_DEBUG")!=0&&(true||util.env("BLUEBIRD_DEBUG")||util.env("NODE_ENV")==="development"));var warnings=!!(util.env("BLUEBIRD_WARNINGS")!=0&&(debugging||util.env("BLUEBIRD_WARNINGS")));var longStackTraces=!!(util.env("BLUEBIRD_LONG_STACK_TRACES")!=0&&(debugging||util.env("BLUEBIRD_LONG_STACK_TRACES")));var wForgottenReturn=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")!=0&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=((target._bitField&(~1048576))|524288);};Promise.prototype._ensurePossibleRejectionHandled=function(){if((this._bitField&524288)!==0)return;this._setRejectionIsUnhandled();async.invokeLater(this._notifyUnhandledRejection,this,undefined);};Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,undefined,this);};Promise.prototype._setReturnedNonUndefined=function(){this._bitField=this._bitField|268435456;};Promise.prototype._returnedNonUndefined=function(){return(this._bitField&268435456)!==0;};Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._settledValue();this._setUnhandledRejectionIsNotified();fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this);}};Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=this._bitField|262144;};Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&(~262144);};Promise.prototype._isUnhandledRejectionNotified=function(){return(this._bitField&262144)>0;};Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=this._bitField|1048576;};Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&(~1048576);if(this._isUnhandledRejectionNotified()){this._unsetUnhandledRejectionIsNotified();this._notifyUnhandledRejectionIsHandled();}};Promise.prototype._isRejectionUnhandled=function(){return(this._bitField&1048576)>0;};Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this);};Promise.onPossiblyUnhandledRejection=function(fn){var domain=getDomain();possiblyUnhandledRejection=typeof fn==="function"?(domain===null?fn:domain.bind(fn)):undefined;};Promise.onUnhandledRejectionHandled=function(fn){var domain=getDomain();unhandledRejectionHandled=typeof fn==="function"?(domain===null?fn:domain.bind(fn)):undefined;};var disableLongStackTraces=function(){};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces){throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
if(!config.longStackTraces&&longStackTracesIsSupported()){var Promise_captureStackTrace=Promise.prototype._captureStackTrace;var Promise_attachExtraTrace=Promise.prototype._attachExtraTrace;config.longStackTraces=true;disableLongStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces){throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
Promise.prototype._captureStackTrace=Promise_captureStackTrace;Promise.prototype._attachExtraTrace=Promise_attachExtraTrace;Context.deactivateLongStackTraces();async.enableTrampoline();config.longStackTraces=false;};Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace;Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace;Context.activateLongStackTraces();async.disableTrampolineIfNecessary();}};Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported();};var fireDomEvent=(function(){try{var event=document.createEvent("CustomEvent");event.initCustomEvent("testingtheevent",false,true,{});util.global.dispatchEvent(event);return function(name,event){var domEvent=document.createEvent("CustomEvent");domEvent.initCustomEvent(name.toLowerCase(),false,true,event);return!util.global.dispatchEvent(domEvent);};}catch(e){}
return function(){return false;};})();var fireGlobalEvent=(function(){if(util.isNode){return function(){return process.emit.apply(process,arguments);};}else{if(!util.global){return function(){return false;};}
return function(name){var methodName="on"+name.toLowerCase();var method=util.global[methodName];if(!method)return false;method.apply(util.global,[].slice.call(arguments,1));return true;};}})();function generatePromiseLifecycleEventObject(name,promise){return{promise:promise};}
var eventToObjectGenerator={promiseCreated:generatePromiseLifecycleEventObject,promiseFulfilled:generatePromiseLifecycleEventObject,promiseRejected:generatePromiseLifecycleEventObject,promiseResolved:generatePromiseLifecycleEventObject,promiseCancelled:generatePromiseLifecycleEventObject,promiseChained:function(name,promise,child){return{promise:promise,child:child};},warning:function(name,warning){return{warning:warning};},unhandledRejection:function(name,reason,promise){return{reason:reason,promise:promise};},rejectionHandled:generatePromiseLifecycleEventObject};var activeFireEvent=function(name){var globalEventFired=false;try{globalEventFired=fireGlobalEvent.apply(null,arguments);}catch(e){async.throwLater(e);globalEventFired=true;}
var domEventFired=false;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments));}catch(e){async.throwLater(e);domEventFired=true;}
return domEventFired||globalEventFired;};Promise.config=function(opts){opts=Object(opts);if("longStackTraces"in opts){if(opts.longStackTraces){Promise.longStackTraces();}else if(!opts.longStackTraces&&Promise.hasLongStackTraces()){disableLongStackTraces();}}
if("warnings"in opts){var warningsOption=opts.warnings;config.warnings=!!warningsOption;wForgottenReturn=config.warnings;if(util.isObject(warningsOption)){if("wForgottenReturn"in warningsOption){wForgottenReturn=!!warningsOption.wForgottenReturn;}}}
if("cancellation"in opts&&opts.cancellation&&!config.cancellation){if(async.haveItemsQueued()){throw new Error("cannot enable cancellation after promises are in use");}
Promise.prototype._clearCancellationData=cancellationClearCancellationData;Promise.prototype._propagateFrom=cancellationPropagateFrom;Promise.prototype._onCancel=cancellationOnCancel;Promise.prototype._setOnCancel=cancellationSetOnCancel;Promise.prototype._attachCancellationCallback=cancellationAttachCancellationCallback;Promise.prototype._execute=cancellationExecute;propagateFromFunction=cancellationPropagateFrom;config.cancellation=true;}
if("monitoring"in opts){if(opts.monitoring&&!config.monitoring){config.monitoring=true;Promise.prototype._fireEvent=activeFireEvent;}else if(!opts.monitoring&&config.monitoring){config.monitoring=false;Promise.prototype._fireEvent=defaultFireEvent;}}};function defaultFireEvent(){return false;}
Promise.prototype._fireEvent=defaultFireEvent;Promise.prototype._execute=function(executor,resolve,reject){try{executor(resolve,reject);}catch(e){return e;}};Promise.prototype._onCancel=function(){};Promise.prototype._setOnCancel=function(handler){;};Promise.prototype._attachCancellationCallback=function(onCancel){;};Promise.prototype._captureStackTrace=function(){};Promise.prototype._attachExtraTrace=function(){};Promise.prototype._clearCancellationData=function(){};Promise.prototype._propagateFrom=function(parent,flags){;;};function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,function(onCancel){if(typeof onCancel!=="function"){throw new TypeError("onCancel must be a function, got: "+
util.toString(onCancel));}
promise._attachCancellationCallback(onCancel);});}catch(e){return e;}}
function cancellationAttachCancellationCallback(onCancel){if(!this.isCancellable())return this;var previousOnCancel=this._onCancel();if(previousOnCancel!==undefined){if(util.isArray(previousOnCancel)){previousOnCancel.push(onCancel);}else{this._setOnCancel([previousOnCancel,onCancel]);}}else{this._setOnCancel(onCancel);}}
function cancellationOnCancel(){return this._onCancelField;}
function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel;}
function cancellationClearCancellationData(){this._cancellationParent=undefined;this._onCancelField=undefined;}
function cancellationPropagateFrom(parent,flags){if((flags&1)!==0){this._cancellationParent=parent;var branchesRemainingToCancel=parent._branchesRemainingToCancel;if(branchesRemainingToCancel===undefined){branchesRemainingToCancel=0;}
parent._branchesRemainingToCancel=branchesRemainingToCancel+1;}
if((flags&2)!==0&&parent._isBound()){this._setBoundTo(parent._boundTo);}}
function bindingPropagateFrom(parent,flags){if((flags&2)!==0&&parent._isBound()){this._setBoundTo(parent._boundTo);}}
var propagateFromFunction=bindingPropagateFrom;function boundValueFunction(){var ret=this._boundTo;if(ret!==undefined){if(ret instanceof Promise){if(ret.isFulfilled()){return ret.value();}else{return undefined;}}}
return ret;}
function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext());}
function longStackTracesAttachExtraTrace(error,ignoreSelf){if(canAttachTrace(error)){var trace=this._trace;if(trace!==undefined){if(ignoreSelf)trace=trace._parent;}
if(trace!==undefined){trace.attachExtraTrace(error);}else if(!error.__stackCleaned__){var parsed=parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n"));util.notEnumerableProp(error,"__stackCleaned__",true);}}}
function checkForgottenReturns(returnValue,promiseCreated,name,promise,parent){if(returnValue===undefined&&promiseCreated!==null&&wForgottenReturn){if(parent!==undefined&&parent._returnedNonUndefined())return;if((promise._bitField&65535)===0)return;if(name)name=name+" ";var msg="a promise was created in a "+name+"handler but was not returned from it";promise._warn(msg,true,promiseCreated);}}
function deprecated(name,replacement){var message=name+" is deprecated and will be removed in a future version.";if(replacement)message+=" Use "+replacement+" instead.";return warn(message);}
function warn(message,shouldUseOwnTrace,promise){if(!config.warnings)return;var warning=new Warning(message);var ctx;if(shouldUseOwnTrace){promise._attachExtraTrace(warning);}else if(config.longStackTraces&&(ctx=Promise._peekContext())){ctx.attachExtraTrace(warning);}else{var parsed=parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n");}
if(!activeFireEvent("warning",warning)){formatAndLogError(warning,"",true);}}
function reconstructStack(message,stacks){for(var i=0;i<stacks.length-1;++i){stacks[i].push("From previous event:");stacks[i]=stacks[i].join("\n");}
if(i<stacks.length){stacks[i]=stacks[i].join("\n");}
return message+"\n"+stacks.join("\n");}
function removeDuplicateOrEmptyJumps(stacks){for(var i=0;i<stacks.length;++i){if(stacks[i].length===0||((i+1<stacks.length)&&stacks[i][0]===stacks[i+1][0])){stacks.splice(i,1);i--;}}}
function removeCommonRoots(stacks){var current=stacks[0];for(var i=1;i<stacks.length;++i){var prev=stacks[i];var currentLastIndex=current.length-1;var currentLastLine=current[currentLastIndex];var commonRootMeetPoint=-1;for(var j=prev.length-1;j>=0;--j){if(prev[j]===currentLastLine){commonRootMeetPoint=j;break;}}
for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]===line){current.pop();currentLastIndex--;}else{break;}}
current=prev;}}
function cleanStack(stack){var ret=[];for(var i=0;i<stack.length;++i){var line=stack[i];var isTraceLine="    (No stack trace)"===line||stackFramePattern.test(line);var isInternalFrame=isTraceLine&&shouldIgnore(line);if(isTraceLine&&!isInternalFrame){if(indentStackFrames&&line.charAt(0)!==" "){line="    "+line;}
ret.push(line);}}
return ret;}
function stackFramesAsArray(error){var stack=error.stack.replace(/\s+$/g,"").split("\n");for(var i=0;i<stack.length;++i){var line=stack[i];if("    (No stack trace)"===line||stackFramePattern.test(line)){break;}}
if(i>0){stack=stack.slice(i);}
return stack;}
function parseStackAndMessage(error){var stack=error.stack;var message=error.toString();stack=typeof stack==="string"&&stack.length>0?stackFramesAsArray(error):["    (No stack trace)"];return{message:message,stack:cleanStack(stack)};}
function formatAndLogError(error,title,isSoft){if(typeof console!=="undefined"){var message;if(util.isObject(error)){var stack=error.stack;message=title+formatStack(stack,error);}else{message=title+String(error);}
if(typeof printWarning==="function"){printWarning(message,isSoft);}else if(typeof console.log==="function"||typeof console.log==="object"){console.log(message);}}}
function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=false;try{if(typeof localHandler==="function"){localEventFired=true;if(name==="rejectionHandled"){localHandler(promise);}else{localHandler(reason,promise);}}}catch(e){async.throwLater(e);}
if(name==="unhandledRejection"){if(!activeFireEvent(name,reason,promise)&&!localEventFired){formatAndLogError(reason,"Unhandled rejection ");}}else{activeFireEvent(name,promise);}}
function formatNonError(obj){var str;if(typeof obj==="function"){str="[function "+
(obj.name||"anonymous")+"]";}else{str=obj&&typeof obj.toString==="function"?obj.toString():util.toString(obj);var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str)){try{var newStr=JSON.stringify(obj);str=newStr;}
catch(e){}}
if(str.length===0){str="(empty array)";}}
return("(<"+snip(str)+">, no stack trace)");}
function snip(str){var maxChars=41;if(str.length<maxChars){return str;}
return str.substr(0,maxChars-3)+"...";}
function longStackTracesIsSupported(){return typeof captureStackTrace==="function";}
var shouldIgnore=function(){return false;};var parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function parseLineInfo(line){var matches=line.match(parseLineInfoRegex);if(matches){return{fileName:matches[1],line:parseInt(matches[2],10)};}}
function setBounds(firstLineError,lastLineError){if(!longStackTracesIsSupported())return;var firstStackLines=firstLineError.stack.split("\n");var lastStackLines=lastLineError.stack.split("\n");var firstIndex=-1;var lastIndex=-1;var firstFileName;var lastFileName;for(var i=0;i<firstStackLines.length;++i){var result=parseLineInfo(firstStackLines[i]);if(result){firstFileName=result.fileName;firstIndex=result.line;break;}}
for(var i=0;i<lastStackLines.length;++i){var result=parseLineInfo(lastStackLines[i]);if(result){lastFileName=result.fileName;lastIndex=result.line;break;}}
if(firstIndex<0||lastIndex<0||!firstFileName||!lastFileName||firstFileName!==lastFileName||firstIndex>=lastIndex){return;}
shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return true;var info=parseLineInfo(line);if(info){if(info.fileName===firstFileName&&(firstIndex<=info.line&&info.line<=lastIndex)){return true;}}
return false;};}
function CapturedTrace(parent){this._parent=parent;this._promisesCreated=0;var length=this._length=1+(parent===undefined?0:parent._length);captureStackTrace(this,CapturedTrace);if(length>32)this.uncycle();}
util.inherits(CapturedTrace,Error);Context.CapturedTrace=CapturedTrace;CapturedTrace.prototype.uncycle=function(){var length=this._length;if(length<2)return;var nodes=[];var stackToIndex={};for(var i=0,node=this;node!==undefined;++i){nodes.push(node);node=node._parent;}
length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;if(stackToIndex[stack]===undefined){stackToIndex[stack]=i;}}
for(var i=0;i<length;++i){var currentStack=nodes[i].stack;var index=stackToIndex[currentStack];if(index!==undefined&&index!==i){if(index>0){nodes[index-1]._parent=undefined;nodes[index-1]._length=1;}
nodes[i]._parent=undefined;nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;if(index<length-1){cycleEdgeNode._parent=nodes[index+1];cycleEdgeNode._parent.uncycle();cycleEdgeNode._length=cycleEdgeNode._parent._length+1;}else{cycleEdgeNode._parent=undefined;cycleEdgeNode._length=1;}
var currentChildLength=cycleEdgeNode._length+1;for(var j=i-2;j>=0;--j){nodes[j]._length=currentChildLength;currentChildLength++;}
return;}}};CapturedTrace.prototype.attachExtraTrace=function(error){if(error.__stackCleaned__)return;this.uncycle();var parsed=parseStackAndMessage(error);var message=parsed.message;var stacks=[parsed.stack];var trace=this;while(trace!==undefined){stacks.push(cleanStack(trace.stack.split("\n")));trace=trace._parent;}
removeCommonRoots(stacks);removeDuplicateOrEmptyJumps(stacks);util.notEnumerableProp(error,"stack",reconstructStack(message,stacks));util.notEnumerableProp(error,"__stackCleaned__",true);};var captureStackTrace=(function stackDetection(){var v8stackFramePattern=/^\s*at\s*/;var v8stackFormatter=function(stack,error){if(typeof stack==="string")return stack;if(error.name!==undefined&&error.message!==undefined){return error.toString();}
return formatNonError(error);};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6;stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;shouldIgnore=function(line){return bluebirdFramePattern.test(line);};return function(receiver,ignoreUntil){Error.stackTraceLimit+=6;captureStackTrace(receiver,ignoreUntil);Error.stackTraceLimit-=6;};}
var err=new Error();if(typeof err.stack==="string"&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0){stackFramePattern=/@/;formatStack=v8stackFormatter;indentStackFrames=true;return function captureStackTrace(o){o.stack=new Error().stack;};}
var hasStackAfterThrow;try{throw new Error();}
catch(e){hasStackAfterThrow=("stack"in e);}
if(!("stack"in err)&&hasStackAfterThrow&&typeof Error.stackTraceLimit==="number"){stackFramePattern=v8stackFramePattern;formatStack=v8stackFormatter;return function captureStackTrace(o){Error.stackTraceLimit+=6;try{throw new Error();}
catch(e){o.stack=e.stack;}
Error.stackTraceLimit-=6;};}
formatStack=function(stack,error){if(typeof stack==="string")return stack;if((typeof error==="object"||typeof error==="function")&&error.name!==undefined&&error.message!==undefined){return error.toString();}
return formatNonError(error);};return null;})([]);if(typeof console!=="undefined"&&typeof console.warn!=="undefined"){printWarning=function(message){console.warn(message);};if(util.isNode&&process.stderr.isTTY){printWarning=function(message,isSoft){var color=isSoft?"\u001b[33m":"\u001b[31m";console.warn(color+message+"\u001b[0m\n");};}else if(!util.isNode&&typeof(new Error().stack)==="string"){printWarning=function(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red");};}}
var config={warnings:warnings,longStackTraces:false,cancellation:false,monitoring:false};if(longStackTraces)Promise.longStackTraces();return{longStackTraces:function(){return config.longStackTraces;},warnings:function(){return config.warnings;},cancellation:function(){return config.cancellation;},monitoring:function(){return config.monitoring;},propagateFromFunction:function(){return propagateFromFunction;},boundValueFunction:function(){return boundValueFunction;},checkForgottenReturns:checkForgottenReturns,setBounds:setBounds,warn:warn,deprecated:deprecated,CapturedTrace:CapturedTrace,fireDomEvent:fireDomEvent,fireGlobalEvent:fireGlobalEvent};};},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function returner(){return this.value;}
function thrower(){throw this.reason;}
Promise.prototype["return"]=Promise.prototype.thenReturn=function(value){if(value instanceof Promise)value.suppressUnhandledRejections();return this._then(returner,undefined,undefined,{value:value},undefined);};Promise.prototype["throw"]=Promise.prototype.thenThrow=function(reason){return this._then(thrower,undefined,undefined,{reason:reason},undefined);};Promise.prototype.catchThrow=function(reason){if(arguments.length<=1){return this._then(undefined,thrower,undefined,{reason:reason},undefined);}else{var _reason=arguments[1];var handler=function(){throw _reason;};return this.caught(reason,handler);}};Promise.prototype.catchReturn=function(value){if(arguments.length<=1){if(value instanceof Promise)value.suppressUnhandledRejections();return this._then(undefined,returner,undefined,{value:value},undefined);}else{var _value=arguments[1];if(_value instanceof Promise)_value.suppressUnhandledRejections();var handler=function(){return _value;};return this.caught(value,handler);}};};},{}],11:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseReduce=Promise.reduce;var PromiseAll=Promise.all;function promiseAllThis(){return PromiseAll(this);}
function PromiseMapSeries(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL);}
Promise.prototype.each=function(fn){return this.mapSeries(fn)._then(promiseAllThis,undefined,undefined,this,undefined);};Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL);};Promise.each=function(promises,fn){return PromiseMapSeries(promises,fn)._then(promiseAllThis,undefined,undefined,promises,undefined);};Promise.mapSeries=PromiseMapSeries;};},{}],12:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5");var Objectfreeze=es5.freeze;var util=_dereq_("./util");var inherits=util.inherits;var notEnumerableProp=util.notEnumerableProp;function subError(nameProperty,defaultMessage){function SubError(message){if(!(this instanceof SubError))return new SubError(message);notEnumerableProp(this,"message",typeof message==="string"?message:defaultMessage);notEnumerableProp(this,"name",nameProperty);if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor);}else{Error.call(this);}}
inherits(SubError,Error);return SubError;}
var _TypeError,_RangeError;var Warning=subError("Warning","warning");var CancellationError=subError("CancellationError","cancellation error");var TimeoutError=subError("TimeoutError","timeout error");var AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError;_RangeError=RangeError;}catch(e){_TypeError=subError("TypeError","type error");_RangeError=subError("RangeError","range error");}
var methods=("join pop push shift unshift slice filter forEach some "+"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");for(var i=0;i<methods.length;++i){if(typeof Array.prototype[methods[i]]==="function"){AggregateError.prototype[methods[i]]=Array.prototype[methods[i]];}}
es5.defineProperty(AggregateError.prototype,"length",{value:0,configurable:false,writable:true,enumerable:true});AggregateError.prototype["isOperational"]=true;var level=0;AggregateError.prototype.toString=function(){var indent=Array(level*4+1).join(" ");var ret="\n"+indent+"AggregateError of:"+"\n";level++;indent=Array(level*4+1).join(" ");for(var i=0;i<this.length;++i){var str=this[i]===this?"[Circular AggregateError]":this[i]+"";var lines=str.split("\n");for(var j=0;j<lines.length;++j){lines[j]=indent+lines[j];}
str=lines.join("\n");ret+=str+"\n";}
level--;return ret;};function OperationalError(message){if(!(this instanceof OperationalError))
return new OperationalError(message);notEnumerableProp(this,"name","OperationalError");notEnumerableProp(this,"message",message);this.cause=message;this["isOperational"]=true;if(message instanceof Error){notEnumerableProp(this,"message",message.message);notEnumerableProp(this,"stack",message.stack);}else if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor);}}
inherits(OperationalError,Error);var errorTypes=Error["__BluebirdErrorTypes__"];if(!errorTypes){errorTypes=Objectfreeze({CancellationError:CancellationError,TimeoutError:TimeoutError,OperationalError:OperationalError,RejectionError:OperationalError,AggregateError:AggregateError});es5.defineProperty(Error,"__BluebirdErrorTypes__",{value:errorTypes,writable:false,enumerable:false,configurable:false});}
module.exports={Error:Error,TypeError:_TypeError,RangeError:_RangeError,CancellationError:errorTypes.CancellationError,OperationalError:errorTypes.OperationalError,TimeoutError:errorTypes.TimeoutError,AggregateError:errorTypes.AggregateError,Warning:Warning};},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){var isES5=(function(){"use strict";return this===undefined;})();if(isES5){module.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:isES5,propertyIsWritable:function(obj,prop){var descriptor=Object.getOwnPropertyDescriptor(obj,prop);return!!(!descriptor||descriptor.writable||descriptor.set);}};}else{var has={}.hasOwnProperty;var str={}.toString;var proto={}.constructor.prototype;var ObjectKeys=function(o){var ret=[];for(var key in o){if(has.call(o,key)){ret.push(key);}}
return ret;};var ObjectGetDescriptor=function(o,key){return{value:o[key]};};var ObjectDefineProperty=function(o,key,desc){o[key]=desc.value;return o;};var ObjectFreeze=function(obj){return obj;};var ObjectGetPrototypeOf=function(obj){try{return Object(obj).constructor.prototype;}
catch(e){return proto;}};var ArrayIsArray=function(obj){try{return str.call(obj)==="[object Array]";}
catch(e){return false;}};module.exports={isArray:ArrayIsArray,keys:ObjectKeys,names:ObjectKeys,defineProperty:ObjectDefineProperty,getDescriptor:ObjectGetDescriptor,freeze:ObjectFreeze,getPrototypeOf:ObjectGetPrototypeOf,isES5:isES5,propertyIsWritable:function(){return true;}};}},{}],14:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var PromiseMap=Promise.map;Promise.prototype.filter=function(fn,options){return PromiseMap(this,fn,options,INTERNAL);};Promise.filter=function(promises,fn,options){return PromiseMap(promises,fn,options,INTERNAL);};};},{}],15:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,tryConvertToPromise){var util=_dereq_("./util");var CancellationError=Promise.CancellationError;var errorObj=util.errorObj;function PassThroughHandlerContext(promise,type,handler){this.promise=promise;this.type=type;this.handler=handler;this.called=false;this.cancelPromise=null;}
PassThroughHandlerContext.prototype.isFinallyHandler=function(){return this.type===0;};function FinallyHandlerCancelReaction(finallyHandler){this.finallyHandler=finallyHandler;}
FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler);};function checkCancel(ctx,reason){if(ctx.cancelPromise!=null){if(arguments.length>1){ctx.cancelPromise._reject(reason);}else{ctx.cancelPromise._cancel();}
ctx.cancelPromise=null;return true;}
return false;}
function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue());}
function fail(reason){if(checkCancel(this,reason))return;errorObj.e=reason;return errorObj;}
function finallyHandler(reasonOrValue){var promise=this.promise;var handler=this.handler;if(!this.called){this.called=true;var ret=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(ret!==undefined){promise._setReturnedNonUndefined();var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){if(this.cancelPromise!=null){if(maybePromise.isCancelled()){var reason=new CancellationError("late cancellation observer");promise._attachExtraTrace(reason);errorObj.e=reason;return errorObj;}else if(maybePromise.isPending()){maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this));}}
return maybePromise._then(succeed,fail,undefined,this,undefined);}}}
if(promise.isRejected()){checkCancel(this);errorObj.e=reasonOrValue;return errorObj;}else{checkCancel(this);return reasonOrValue;}}
Promise.prototype._passThrough=function(handler,type,success,fail){if(typeof handler!=="function")return this.then();return this._then(success,fail,undefined,new PassThroughHandlerContext(this,type,handler),undefined);};Promise.prototype.lastly=Promise.prototype["finally"]=function(handler){return this._passThrough(handler,0,finallyHandler,finallyHandler);};Promise.prototype.tap=function(handler){return this._passThrough(handler,1,finallyHandler);};return PassThroughHandlerContext;};},{"./util":36}],16:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){var errors=_dereq_("./errors");var TypeError=errors.TypeError;var util=_dereq_("./util");var errorObj=util.errorObj;var tryCatch=util.tryCatch;var yieldHandlers=[];function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i<yieldHandlers.length;++i){traceParent._pushContext();var result=tryCatch(yieldHandlers[i])(value);traceParent._popContext();if(result===errorObj){traceParent._pushContext();var ret=Promise.reject(errorObj.e);traceParent._popContext();return ret;}
var maybePromise=tryConvertToPromise(result,traceParent);if(maybePromise instanceof Promise)return maybePromise;}
return null;}
function PromiseSpawn(generatorFunction,receiver,yieldHandler,stack){if(debug.cancellation()){var internal=new Promise(INTERNAL);var _finallyPromise=this._finallyPromise=new Promise(INTERNAL);this._promise=internal.lastly(function(){return _finallyPromise;});internal._captureStackTrace();internal._setOnCancel(this);}else{var promise=this._promise=new Promise(INTERNAL);promise._captureStackTrace();}
this._stack=stack;this._generatorFunction=generatorFunction;this._receiver=receiver;this._generator=undefined;this._yieldHandlers=typeof yieldHandler==="function"?[yieldHandler].concat(yieldHandlers):yieldHandlers;this._yieldedPromise=null;this._cancellationPhase=false;}
util.inherits(PromiseSpawn,Proxyable);PromiseSpawn.prototype._isResolved=function(){return this._promise===null;};PromiseSpawn.prototype._cleanup=function(){this._promise=this._generator=null;if(debug.cancellation()&&this._finallyPromise!==null){this._finallyPromise._fulfill();this._finallyPromise=null;}};PromiseSpawn.prototype._promiseCancelled=function(){if(this._isResolved())return;var implementsReturn=typeof this._generator["return"]!=="undefined";var result;if(!implementsReturn){var reason=new Promise.CancellationError("generator .return() sentinel");Promise.coroutine.returnSentinel=reason;this._promise._attachExtraTrace(reason);this._promise._pushContext();result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext();}else{this._promise._pushContext();result=tryCatch(this._generator["return"]).call(this._generator,undefined);this._promise._popContext();}
this._cancellationPhase=true;this._yieldedPromise=null;this._continue(result);};PromiseSpawn.prototype._promiseFulfilled=function(value){this._yieldedPromise=null;this._promise._pushContext();var result=tryCatch(this._generator.next).call(this._generator,value);this._promise._popContext();this._continue(result);};PromiseSpawn.prototype._promiseRejected=function(reason){this._yieldedPromise=null;this._promise._attachExtraTrace(reason);this._promise._pushContext();var result=tryCatch(this._generator["throw"]).call(this._generator,reason);this._promise._popContext();this._continue(result);};PromiseSpawn.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof Promise){var promise=this._yieldedPromise;this._yieldedPromise=null;promise.cancel();}};PromiseSpawn.prototype.promise=function(){return this._promise;};PromiseSpawn.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver);this._receiver=this._generatorFunction=undefined;this._promiseFulfilled(undefined);};PromiseSpawn.prototype._continue=function(result){var promise=this._promise;if(result===errorObj){this._cleanup();if(this._cancellationPhase){return promise.cancel();}else{return promise._rejectCallback(result.e,false);}}
var value=result.value;if(result.done===true){this._cleanup();if(this._cancellationPhase){return promise.cancel();}else{return promise._resolveCallback(value);}}else{var maybePromise=tryConvertToPromise(value,this._promise);if(!(maybePromise instanceof Promise)){maybePromise=promiseFromYieldHandler(maybePromise,this._yieldHandlers,this._promise);if(maybePromise===null){this._promiseRejected(new TypeError("A value %s was yielded that could not be treated as a promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a\u000a".replace("%s",value)+"From coroutine:\u000a"+
this._stack.split("\n").slice(1,-7).join("\n")));return;}}
maybePromise=maybePromise._target();var bitField=maybePromise._bitField;;if(((bitField&50397184)===0)){this._yieldedPromise=maybePromise;maybePromise._proxy(this,null);}else if(((bitField&33554432)!==0)){this._promiseFulfilled(maybePromise._value());}else if(((bitField&16777216)!==0)){this._promiseRejected(maybePromise._reason());}else{this._promiseCancelled();}}};Promise.coroutine=function(generatorFunction,options){if(typeof generatorFunction!=="function"){throw new TypeError("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
var yieldHandler=Object(options).yieldHandler;var PromiseSpawn$=PromiseSpawn;var stack=new Error().stack;return function(){var generator=generatorFunction.apply(this,arguments);var spawn=new PromiseSpawn$(undefined,undefined,yieldHandler,stack);var ret=spawn.promise();spawn._generator=generator;spawn._promiseFulfilled(undefined);return ret;};};Promise.coroutine.addYieldHandler=function(fn){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn));}
yieldHandlers.push(fn);};Promise.spawn=function(generatorFunction){debug.deprecated("Promise.spawn()","Promise.coroutine()");if(typeof generatorFunction!=="function"){return apiRejection("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
var spawn=new PromiseSpawn(generatorFunction,this);var ret=spawn.promise();spawn._run(Promise.spawn);return ret;};};},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,INTERNAL){var util=_dereq_("./util");var canEvaluate=util.canEvaluate;var tryCatch=util.tryCatch;var errorObj=util.errorObj;var reject;if(!true){if(canEvaluate){var thenCallback=function(i){return new Function("value","holder","                             \n            'use strict';                                                    \n            holder.pIndex = value;                                           \n            holder.checkFulfillment(this);                                   \n            ".replace(/Index/g,i));};var promiseSetter=function(i){return new Function("promise","holder","                           \n            'use strict';                                                    \n            holder.pIndex = promise;                                         \n            ".replace(/Index/g,i));};var generateHolderClass=function(total){var props=new Array(total);for(var i=0;i<props.length;++i){props[i]="this.p"+(i+1);}
var assignment=props.join(" = ")+" = null;";var cancellationCode="var promise;\n"+props.map(function(prop){return"                                                         \n                promise = "+prop+";                                      \n                if (promise instanceof Promise) {                            \n                    promise.cancel();                                        \n                }                                                            \n            ";}).join("\n");var passedArguments=props.join(", ");var name="Holder$"+total;var code="return function(tryCatch, errorObj, Promise) {           \n            'use strict';                                                    \n            function [TheName](fn) {                                         \n                [TheProperties]                                              \n                this.fn = fn;                                                \n                this.now = 0;                                                \n            }                                                                \n            [TheName].prototype.checkFulfillment = function(promise) {       \n                var now = ++this.now;                                        \n                if (now === [TheTotal]) {                                    \n                    promise._pushContext();                                  \n                    var callback = this.fn;                                  \n                    var ret = tryCatch(callback)([ThePassedArguments]);      \n                    promise._popContext();                                   \n                    if (ret === errorObj) {                                  \n                        promise._rejectCallback(ret.e, false);               \n                    } else {                                                 \n                        promise._resolveCallback(ret);                       \n                    }                                                        \n                }                                                            \n            };                                                               \n                                                                             \n            [TheName].prototype._resultCancelled = function() {              \n                [CancellationCode]                                           \n            };                                                               \n                                                                             \n            return [TheName];                                                \n        }(tryCatch, errorObj, Promise);                                      \n        ";code=code.replace(/\[TheName\]/g,name).replace(/\[TheTotal\]/g,total).replace(/\[ThePassedArguments\]/g,passedArguments).replace(/\[TheProperties\]/g,assignment).replace(/\[CancellationCode\]/g,cancellationCode);return new Function("tryCatch","errorObj","Promise",code)
(tryCatch,errorObj,Promise);};var holderClasses=[];var thenCallbacks=[];var promiseSetters=[];for(var i=0;i<8;++i){holderClasses.push(generateHolderClass(i+1));thenCallbacks.push(thenCallback(i+1));promiseSetters.push(promiseSetter(i+1));}
reject=function(reason){this._reject(reason);};}}
Promise.join=function(){var last=arguments.length-1;var fn;if(last>0&&typeof arguments[last]==="function"){fn=arguments[last];if(!true){if(last<=8&&canEvaluate){var ret=new Promise(INTERNAL);ret._captureStackTrace();var HolderClass=holderClasses[last-1];var holder=new HolderClass(fn);var callbacks=thenCallbacks;for(var i=0;i<last;++i){var maybePromise=tryConvertToPromise(arguments[i],ret);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;;if(((bitField&50397184)===0)){maybePromise._then(callbacks[i],reject,undefined,ret,holder);promiseSetters[i](maybePromise,holder);}else if(((bitField&33554432)!==0)){callbacks[i].call(ret,maybePromise._value(),holder);}else if(((bitField&16777216)!==0)){ret._reject(maybePromise._reason());}else{ret._cancel();}}else{callbacks[i].call(ret,maybePromise,holder);}}
if(!ret._isFateSealed()){ret._setAsyncGuaranteed();ret._setOnCancel(holder);}
return ret;}}}
var args=[].slice.call(arguments);;if(fn)args.pop();var ret=new PromiseArray(args).promise();return fn!==undefined?ret.spread(fn):ret;};};},{"./util":36}],18:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var getDomain=Promise._getDomain;var util=_dereq_("./util");var tryCatch=util.tryCatch;var errorObj=util.errorObj;var EMPTY_ARRAY=[];function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises);this._promise._captureStackTrace();var domain=getDomain();this._callback=domain===null?fn:domain.bind(fn);this._preservedValues=_filter===INTERNAL?new Array(this.length()):null;this._limit=limit;this._inFlight=0;this._queue=limit>=1?[]:EMPTY_ARRAY;this._init$(undefined,-2);}
util.inherits(MappingPromiseArray,PromiseArray);MappingPromiseArray.prototype._init=function(){};MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values;var length=this.length();var preservedValues=this._preservedValues;var limit=this._limit;if(index<0){index=(index*-1)-1;values[index]=value;if(limit>=1){this._inFlight--;this._drainQueue();if(this._isResolved())return true;}}else{if(limit>=1&&this._inFlight>=limit){values[index]=value;this._queue.push(index);return false;}
if(preservedValues!==null)preservedValues[index]=value;var promise=this._promise;var callback=this._callback;var receiver=promise._boundValue();promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length);var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,preservedValues!==null?"Promise.filter":"Promise.map",promise);if(ret===errorObj){this._reject(ret.e);return true;}
var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;;if(((bitField&50397184)===0)){if(limit>=1)this._inFlight++;values[index]=maybePromise;maybePromise._proxy(this,(index+1)*-1);return false;}else if(((bitField&33554432)!==0)){ret=maybePromise._value();}else if(((bitField&16777216)!==0)){this._reject(maybePromise._reason());return true;}else{this._cancel();return true;}}
values[index]=ret;}
var totalResolved=++this._totalResolved;if(totalResolved>=length){if(preservedValues!==null){this._filter(values,preservedValues);}else{this._resolve(values);}
return true;}
return false;};MappingPromiseArray.prototype._drainQueue=function(){var queue=this._queue;var limit=this._limit;var values=this._values;while(queue.length>0&&this._inFlight<limit){if(this._isResolved())return;var index=queue.pop();this._promiseFulfilled(values[index],index);}};MappingPromiseArray.prototype._filter=function(booleans,values){var len=values.length;var ret=new Array(len);var j=0;for(var i=0;i<len;++i){if(booleans[i])ret[j++]=values[i];}
ret.length=j;this._resolve(ret);};MappingPromiseArray.prototype.preservedValues=function(){return this._preservedValues;};function map(promises,fn,options,_filter){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn));}
var limit=0;if(options!==undefined){if(typeof options==="object"&&options!==null){if(typeof options.concurrency!=="number"){return Promise.reject(new TypeError("'concurrency' must be a number but it is "+
util.classString(options.concurrency)));}
limit=options.concurrency;}else{return Promise.reject(new TypeError("options argument must be an object but it is "+
util.classString(options)));}}
limit=typeof limit==="number"&&isFinite(limit)&&limit>=1?limit:0;return new MappingPromiseArray(promises,fn,limit,_filter).promise();}
Promise.prototype.map=function(fn,options){return map(this,fn,options,null);};Promise.map=function(promises,fn,options,_filter){return map(promises,fn,options,_filter);};};},{"./util":36}],19:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug){var util=_dereq_("./util");var tryCatch=util.tryCatch;Promise.method=function(fn){if(typeof fn!=="function"){throw new Promise.TypeError("expecting a function but got "+util.classString(fn));}
return function(){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value=tryCatch(fn).apply(this,arguments);var promiseCreated=ret._popContext();debug.checkForgottenReturns(value,promiseCreated,"Promise.method",ret);ret._resolveFromSyncValue(value);return ret;};};Promise.attempt=Promise["try"]=function(fn){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn));}
var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._pushContext();var value;if(arguments.length>1){debug.deprecated("calling Promise.try with more than 1 argument");var arg=arguments[1];var ctx=arguments[2];value=util.isArray(arg)?tryCatch(fn).apply(ctx,arg):tryCatch(fn).call(ctx,arg);}else{value=tryCatch(fn)();}
var promiseCreated=ret._popContext();debug.checkForgottenReturns(value,promiseCreated,"Promise.try",ret);ret._resolveFromSyncValue(value);return ret;};Promise.prototype._resolveFromSyncValue=function(value){if(value===util.errorObj){this._rejectCallback(value.e,false);}else{this._resolveCallback(value,true);}};};},{"./util":36}],20:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util");var maybeWrapAsError=util.maybeWrapAsError;var errors=_dereq_("./errors");var OperationalError=errors.OperationalError;var es5=_dereq_("./es5");function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype;}
var rErrorKey=/^(?:name|message|stack|cause)$/;function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj);ret.name=obj.name;ret.message=obj.message;ret.stack=obj.stack;var keys=es5.keys(obj);for(var i=0;i<keys.length;++i){var key=keys[i];if(!rErrorKey.test(key)){ret[key]=obj[key];}}
return ret;}
util.markAsOriginatingFromRejection(obj);return obj;}
function nodebackForPromise(promise,multiArgs){return function(err,value){if(promise===null)return;if(err){var wrapped=wrapAsOperationalError(maybeWrapAsError(err));promise._attachExtraTrace(wrapped);promise._reject(wrapped);}else if(!multiArgs){promise._fulfill(value);}else{var args=[].slice.call(arguments,1);;promise._fulfill(args);}
promise=null;};}
module.exports=nodebackForPromise;},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){var util=_dereq_("./util");var async=Promise._async;var tryCatch=util.tryCatch;var errorObj=util.errorObj;function spreadAdapter(val,nodeback){var promise=this;if(!util.isArray(val))return successAdapter.call(promise,val,nodeback);var ret=tryCatch(nodeback).apply(promise._boundValue(),[null].concat(val));if(ret===errorObj){async.throwLater(ret.e);}}
function successAdapter(val,nodeback){var promise=this;var receiver=promise._boundValue();var ret=val===undefined?tryCatch(nodeback).call(receiver,null):tryCatch(nodeback).call(receiver,null,val);if(ret===errorObj){async.throwLater(ret.e);}}
function errorAdapter(reason,nodeback){var promise=this;if(!reason){var newReason=new Error(reason+"");newReason.cause=reason;reason=newReason;}
var ret=tryCatch(nodeback).call(promise._boundValue(),reason);if(ret===errorObj){async.throwLater(ret.e);}}
Promise.prototype.asCallback=Promise.prototype.nodeify=function(nodeback,options){if(typeof nodeback=="function"){var adapter=successAdapter;if(options!==undefined&&Object(options).spread){adapter=spreadAdapter;}
this._then(adapter,errorAdapter,undefined,this,nodeback);}
return this;};};},{"./util":36}],22:[function(_dereq_,module,exports){"use strict";module.exports=function(){var makeSelfResolutionError=function(){return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/MqrFmX\u000a");};var reflectHandler=function(){return new Promise.PromiseInspection(this._target());};var apiRejection=function(msg){return Promise.reject(new TypeError(msg));};function Proxyable(){}
var UNDEFINED_BINDING={};var util=_dereq_("./util");var getDomain;if(util.isNode){getDomain=function(){var ret=process.domain;if(ret===undefined)ret=null;return ret;};}else{getDomain=function(){return null;};}
util.notEnumerableProp(Promise,"_getDomain",getDomain);var es5=_dereq_("./es5");var Async=_dereq_("./async");var async=new Async();es5.defineProperty(Promise,"_async",{value:async});var errors=_dereq_("./errors");var TypeError=Promise.TypeError=errors.TypeError;Promise.RangeError=errors.RangeError;var CancellationError=Promise.CancellationError=errors.CancellationError;Promise.TimeoutError=errors.TimeoutError;Promise.OperationalError=errors.OperationalError;Promise.RejectionError=errors.OperationalError;Promise.AggregateError=errors.AggregateError;var INTERNAL=function(){};var APPLY={};var NEXT_FILTER={};var tryConvertToPromise=_dereq_("./thenables")(Promise,INTERNAL);var PromiseArray=_dereq_("./promise_array")(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable);var Context=_dereq_("./context")(Promise);var createContext=Context.create;var debug=_dereq_("./debuggability")(Promise,Context);var CapturedTrace=debug.CapturedTrace;var PassThroughHandlerContext=_dereq_("./finally")(Promise,tryConvertToPromise);var catchFilter=_dereq_("./catch_filter")(NEXT_FILTER);var nodebackForPromise=_dereq_("./nodeback");var errorObj=util.errorObj;var tryCatch=util.tryCatch;function check(self,executor){if(typeof executor!=="function"){throw new TypeError("expecting a function but got "+util.classString(executor));}
if(self.constructor!==Promise){throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}}
function Promise(executor){this._bitField=0;this._fulfillmentHandler0=undefined;this._rejectionHandler0=undefined;this._promise0=undefined;this._receiver0=undefined;if(executor!==INTERNAL){check(this,executor);this._resolveFromExecutor(executor);}
this._promiseCreated();this._fireEvent("promiseCreated",this);}
Promise.prototype.toString=function(){return"[object Promise]";};Promise.prototype.caught=Promise.prototype["catch"]=function(fn){var len=arguments.length;if(len>1){var catchInstances=new Array(len-1),j=0,i;for(i=0;i<len-1;++i){var item=arguments[i];if(util.isObject(item)){catchInstances[j++]=item;}else{return apiRejection("expecting an object but got "+util.classString(item));}}
catchInstances.length=j;fn=arguments[i];return this.then(undefined,catchFilter(catchInstances,fn,this));}
return this.then(undefined,fn);};Promise.prototype.reflect=function(){return this._then(reflectHandler,reflectHandler,undefined,this,undefined);};Promise.prototype.then=function(didFulfill,didReject){if(debug.warnings()&&arguments.length>0&&typeof didFulfill!=="function"&&typeof didReject!=="function"){var msg=".then() only accepts functions but was passed: "+
util.classString(didFulfill);if(arguments.length>1){msg+=", "+util.classString(didReject);}
this._warn(msg);}
return this._then(didFulfill,didReject,undefined,undefined,undefined);};Promise.prototype.done=function(didFulfill,didReject){var promise=this._then(didFulfill,didReject,undefined,undefined,undefined);promise._setIsFinal();};Promise.prototype.spread=function(fn){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn));}
return this.all()._then(fn,undefined,undefined,APPLY,undefined);};Promise.prototype.toJSON=function(){var ret={isFulfilled:false,isRejected:false,fulfillmentValue:undefined,rejectionReason:undefined};if(this.isFulfilled()){ret.fulfillmentValue=this.value();ret.isFulfilled=true;}else if(this.isRejected()){ret.rejectionReason=this.reason();ret.isRejected=true;}
return ret;};Promise.prototype.all=function(){if(arguments.length>0){this._warn(".all() was passed arguments but it does not take any");}
return new PromiseArray(this).promise();};Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn);};Promise.is=function(val){return val instanceof Promise;};Promise.fromNode=Promise.fromCallback=function(fn){var ret=new Promise(INTERNAL);ret._captureStackTrace();var multiArgs=arguments.length>1?!!Object(arguments[1]).multiArgs:false;var result=tryCatch(fn)(nodebackForPromise(ret,multiArgs));if(result===errorObj){ret._rejectCallback(result.e,true);}
if(!ret._isFateSealed())ret._setAsyncGuaranteed();return ret;};Promise.all=function(promises){return new PromiseArray(promises).promise();};Promise.cast=function(obj){var ret=tryConvertToPromise(obj);if(!(ret instanceof Promise)){ret=new Promise(INTERNAL);ret._captureStackTrace();ret._setFulfilled();ret._rejectionHandler0=obj;}
return ret;};Promise.resolve=Promise.fulfilled=Promise.cast;Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);ret._captureStackTrace();ret._rejectCallback(reason,true);return ret;};Promise.setScheduler=function(fn){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn));}
return async.setScheduler(fn);};Promise.prototype._then=function(didFulfill,didReject,_,receiver,internalData){var haveInternalData=internalData!==undefined;var promise=haveInternalData?internalData:new Promise(INTERNAL);var target=this._target();var bitField=target._bitField;if(!haveInternalData){promise._propagateFrom(this,3);promise._captureStackTrace();if(receiver===undefined&&((this._bitField&2097152)!==0)){if(!((bitField&50397184)===0)){receiver=this._boundValue();}else{receiver=target===this?undefined:this._boundTo;}}
this._fireEvent("promiseChained",this,promise);}
var domain=getDomain();if(!((bitField&50397184)===0)){var handler,value,settler=target._settlePromiseCtx;if(((bitField&33554432)!==0)){value=target._rejectionHandler0;handler=didFulfill;}else if(((bitField&16777216)!==0)){value=target._fulfillmentHandler0;handler=didReject;target._unsetRejectionIsUnhandled();}else{settler=target._settlePromiseLateCancellationObserver;value=new CancellationError("late cancellation observer");target._attachExtraTrace(value);handler=didReject;}
async.invoke(settler,target,{handler:domain===null?handler:(typeof handler==="function"&&domain.bind(handler)),promise:promise,receiver:receiver,value:value});}else{target._addCallbacks(didFulfill,didReject,promise,receiver,domain);}
return promise;};Promise.prototype._length=function(){return this._bitField&65535;};Promise.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0;};Promise.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864;};Promise.prototype._setLength=function(len){this._bitField=(this._bitField&-65536)|(len&65535);};Promise.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432;this._fireEvent("promiseFulfilled",this);};Promise.prototype._setRejected=function(){this._bitField=this._bitField|16777216;this._fireEvent("promiseRejected",this);};Promise.prototype._setFollowing=function(){this._bitField=this._bitField|67108864;this._fireEvent("promiseResolved",this);};Promise.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304;};Promise.prototype._isFinal=function(){return(this._bitField&4194304)>0;};Promise.prototype._unsetCancelled=function(){this._bitField=this._bitField&(~65536);};Promise.prototype._setCancelled=function(){this._bitField=this._bitField|65536;this._fireEvent("promiseCancelled",this);};Promise.prototype._setAsyncGuaranteed=function(){if(async.hasCustomScheduler())return;this._bitField=this._bitField|134217728;};Promise.prototype._receiverAt=function(index){var ret=index===0?this._receiver0:this[index*4-4+3];if(ret===UNDEFINED_BINDING){return undefined;}else if(ret===undefined&&this._isBound()){return this._boundValue();}
return ret;};Promise.prototype._promiseAt=function(index){return this[index*4-4+2];};Promise.prototype._fulfillmentHandlerAt=function(index){return this[index*4-4+0];};Promise.prototype._rejectionHandlerAt=function(index){return this[index*4-4+1];};Promise.prototype._boundValue=function(){};Promise.prototype._migrateCallback0=function(follower){var bitField=follower._bitField;var fulfill=follower._fulfillmentHandler0;var reject=follower._rejectionHandler0;var promise=follower._promise0;var receiver=follower._receiverAt(0);if(receiver===undefined)receiver=UNDEFINED_BINDING;this._addCallbacks(fulfill,reject,promise,receiver,null);};Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index);var reject=follower._rejectionHandlerAt(index);var promise=follower._promiseAt(index);var receiver=follower._receiverAt(index);if(receiver===undefined)receiver=UNDEFINED_BINDING;this._addCallbacks(fulfill,reject,promise,receiver,null);};Promise.prototype._addCallbacks=function(fulfill,reject,promise,receiver,domain){var index=this._length();if(index>=65535-4){index=0;this._setLength(0);}
if(index===0){this._promise0=promise;this._receiver0=receiver;if(typeof fulfill==="function"){this._fulfillmentHandler0=domain===null?fulfill:domain.bind(fulfill);}
if(typeof reject==="function"){this._rejectionHandler0=domain===null?reject:domain.bind(reject);}}else{var base=index*4-4;this[base+2]=promise;this[base+3]=receiver;if(typeof fulfill==="function"){this[base+0]=domain===null?fulfill:domain.bind(fulfill);}
if(typeof reject==="function"){this[base+1]=domain===null?reject:domain.bind(reject);}}
this._setLength(index+1);return index;};Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(undefined,undefined,arg,proxyable,null);};Promise.prototype._resolveCallback=function(value,shouldBind){if(((this._bitField&117506048)!==0))return;if(value===this)
return this._rejectCallback(makeSelfResolutionError(),false);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);if(shouldBind)this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this){this._reject(makeSelfResolutionError());return;}
var bitField=promise._bitField;if(((bitField&50397184)===0)){var len=this._length();if(len>0)promise._migrateCallback0(this);for(var i=1;i<len;++i){promise._migrateCallbackAt(this,i);}
this._setFollowing();this._setLength(0);this._setFollowee(promise);}else if(((bitField&33554432)!==0)){this._fulfill(promise._value());}else if(((bitField&16777216)!==0)){this._reject(promise._reason());}else{var reason=new CancellationError("late cancellation observer");promise._attachExtraTrace(reason);this._reject(reason);}};Promise.prototype._rejectCallback=function(reason,synchronous,ignoreNonErrorWarnings){var trace=util.ensureErrorObject(reason);var hasStack=trace===reason;if(!hasStack&&!ignoreNonErrorWarnings&&debug.warnings()){var message="a promise was rejected with a non-error: "+
util.classString(reason);this._warn(message,true);}
this._attachExtraTrace(trace,synchronous?hasStack:false);this._reject(reason);};Promise.prototype._resolveFromExecutor=function(executor){var promise=this;this._captureStackTrace();this._pushContext();var synchronous=true;var r=this._execute(executor,function(value){promise._resolveCallback(value);},function(reason){promise._rejectCallback(reason,synchronous);});synchronous=false;this._popContext();if(r!==undefined){promise._rejectCallback(r,true);}};Promise.prototype._settlePromiseFromHandler=function(handler,receiver,value,promise){var bitField=promise._bitField;if(((bitField&65536)!==0))return;promise._pushContext();var x;if(receiver===APPLY){if(!value||typeof value.length!=="number"){x=errorObj;x.e=new TypeError("cannot .spread() a non-array: "+
util.classString(value));}else{x=tryCatch(handler).apply(this._boundValue(),value);}}else{x=tryCatch(handler).call(receiver,value);}
var promiseCreated=promise._popContext();bitField=promise._bitField;if(((bitField&65536)!==0))return;if(x===NEXT_FILTER){promise._reject(value);}else if(x===errorObj){promise._rejectCallback(x.e,false);}else{debug.checkForgottenReturns(x,promiseCreated,"",promise,this);promise._resolveCallback(x);}};Promise.prototype._target=function(){var ret=this;while(ret._isFollowing())ret=ret._followee();return ret;};Promise.prototype._followee=function(){return this._rejectionHandler0;};Promise.prototype._setFollowee=function(promise){this._rejectionHandler0=promise;};Promise.prototype._settlePromise=function(promise,handler,receiver,value){var isPromise=promise instanceof Promise;var bitField=this._bitField;var asyncGuaranteed=((bitField&134217728)!==0);if(((bitField&65536)!==0)){if(isPromise)promise._invokeInternalOnCancel();if(receiver instanceof PassThroughHandlerContext&&receiver.isFinallyHandler()){receiver.cancelPromise=promise;if(tryCatch(handler).call(receiver,value)===errorObj){promise._reject(errorObj.e);}}else if(handler===reflectHandler){promise._fulfill(reflectHandler.call(receiver));}else if(receiver instanceof Proxyable){receiver._promiseCancelled(promise);}else if(isPromise||promise instanceof PromiseArray){promise._cancel();}else{receiver.cancel();}}else if(typeof handler==="function"){if(!isPromise){handler.call(receiver,value,promise);}else{if(asyncGuaranteed)promise._setAsyncGuaranteed();this._settlePromiseFromHandler(handler,receiver,value,promise);}}else if(receiver instanceof Proxyable){if(!receiver._isResolved()){if(((bitField&33554432)!==0)){receiver._promiseFulfilled(value,promise);}else{receiver._promiseRejected(value,promise);}}}else if(isPromise){if(asyncGuaranteed)promise._setAsyncGuaranteed();if(((bitField&33554432)!==0)){promise._fulfill(value);}else{promise._reject(value);}}};Promise.prototype._settlePromiseLateCancellationObserver=function(ctx){var handler=ctx.handler;var promise=ctx.promise;var receiver=ctx.receiver;var value=ctx.value;if(typeof handler==="function"){if(!(promise instanceof Promise)){handler.call(receiver,value,promise);}else{this._settlePromiseFromHandler(handler,receiver,value,promise);}}else if(promise instanceof Promise){promise._reject(value);}};Promise.prototype._settlePromiseCtx=function(ctx){this._settlePromise(ctx.promise,ctx.handler,ctx.receiver,ctx.value);};Promise.prototype._settlePromise0=function(handler,value,bitField){var promise=this._promise0;var receiver=this._receiverAt(0);this._promise0=undefined;this._receiver0=undefined;this._settlePromise(promise,handler,receiver,value);};Promise.prototype._clearCallbackDataAtIndex=function(index){var base=index*4-4;this[base+2]=this[base+3]=this[base+0]=this[base+1]=undefined;};Promise.prototype._fulfill=function(value){var bitField=this._bitField;if(((bitField&117506048)>>>16))return;if(value===this){var err=makeSelfResolutionError();this._attachExtraTrace(err);return this._reject(err);}
this._setFulfilled();this._rejectionHandler0=value;if((bitField&65535)>0){if(((bitField&134217728)!==0)){this._settlePromises();}else{async.settlePromises(this);}}};Promise.prototype._reject=function(reason){var bitField=this._bitField;if(((bitField&117506048)>>>16))return;this._setRejected();this._fulfillmentHandler0=reason;if(this._isFinal()){return async.fatalError(reason,util.isNode);}
if((bitField&65535)>0){async.settlePromises(this);}else{this._ensurePossibleRejectionHandled();}};Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i<len;i++){var handler=this._fulfillmentHandlerAt(i);var promise=this._promiseAt(i);var receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i);this._settlePromise(promise,handler,receiver,value);}};Promise.prototype._rejectPromises=function(len,reason){for(var i=1;i<len;i++){var handler=this._rejectionHandlerAt(i);var promise=this._promiseAt(i);var receiver=this._receiverAt(i);this._clearCallbackDataAtIndex(i);this._settlePromise(promise,handler,receiver,reason);}};Promise.prototype._settlePromises=function(){var bitField=this._bitField;var len=(bitField&65535);if(len>0){if(((bitField&16842752)!==0)){var reason=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,reason,bitField);this._rejectPromises(len,reason);}else{var value=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,value,bitField);this._fulfillPromises(len,value);}
this._setLength(0);}
this._clearCancellationData();};Promise.prototype._settledValue=function(){var bitField=this._bitField;if(((bitField&33554432)!==0)){return this._rejectionHandler0;}else if(((bitField&16777216)!==0)){return this._fulfillmentHandler0;}};function deferResolve(v){this.promise._resolveCallback(v);}
function deferReject(v){this.promise._rejectCallback(v,false);}
Promise.defer=Promise.pending=function(){debug.deprecated("Promise.defer","new Promise");var promise=new Promise(INTERNAL);return{promise:promise,resolve:deferResolve,reject:deferReject};};util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError);_dereq_("./method")(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug);_dereq_("./bind")(Promise,INTERNAL,tryConvertToPromise,debug);_dereq_("./cancel")(Promise,PromiseArray,apiRejection,debug);_dereq_("./direct_resolve")(Promise);_dereq_("./synchronous_inspection")(Promise);_dereq_("./join")(Promise,PromiseArray,tryConvertToPromise,INTERNAL,debug);Promise.Promise=Promise;Promise.version="3.4.0";_dereq_('./map.js')(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug);_dereq_('./call_get.js')(Promise);_dereq_('./using.js')(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug);_dereq_('./timers.js')(Promise,INTERNAL,debug);_dereq_('./generators.js')(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug);_dereq_('./nodeify.js')(Promise);_dereq_('./promisify.js')(Promise,INTERNAL);_dereq_('./props.js')(Promise,PromiseArray,tryConvertToPromise,apiRejection);_dereq_('./race.js')(Promise,INTERNAL,tryConvertToPromise,apiRejection);_dereq_('./reduce.js')(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug);_dereq_('./settle.js')(Promise,PromiseArray,debug);_dereq_('./some.js')(Promise,PromiseArray,apiRejection);_dereq_('./filter.js')(Promise,INTERNAL);_dereq_('./each.js')(Promise,INTERNAL);_dereq_('./any.js')(Promise);util.toFastProperties(Promise);util.toFastProperties(Promise.prototype);function fillTypes(value){var p=new Promise(INTERNAL);p._fulfillmentHandler0=value;p._rejectionHandler0=value;p._promise0=value;p._receiver0=value;}
fillTypes({a:1});fillTypes({b:2});fillTypes({c:3});fillTypes(1);fillTypes(function(){});fillTypes(undefined);fillTypes(false);fillTypes(new Promise(INTERNAL));debug.setBounds(Async.firstLineError,util.lastLineError);return Promise;};},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable){var util=_dereq_("./util");var isArray=util.isArray;function toResolutionValue(val){switch(val){case-2:return[];case-3:return{};}}
function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);if(values instanceof Promise){promise._propagateFrom(values,3);}
promise._setOnCancel(this);this._values=values;this._length=0;this._totalResolved=0;this._init(undefined,-2);}
util.inherits(PromiseArray,Proxyable);PromiseArray.prototype.length=function(){return this._length;};PromiseArray.prototype.promise=function(){return this._promise;};PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){values=values._target();var bitField=values._bitField;;this._values=values;if(((bitField&50397184)===0)){this._promise._setAsyncGuaranteed();return values._then(init,this._reject,undefined,this,resolveValueIfEmpty);}else if(((bitField&33554432)!==0)){values=values._value();}else if(((bitField&16777216)!==0)){return this._reject(values._reason());}else{return this._cancel();}}
values=util.asArray(values);if(values===null){var err=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason();this._promise._rejectCallback(err,false);return;}
if(values.length===0){if(resolveValueIfEmpty===-5){this._resolveEmptyArray();}
else{this._resolve(toResolutionValue(resolveValueIfEmpty));}
return;}
this._iterate(values);};PromiseArray.prototype._iterate=function(values){var len=this.getActualLength(values.length);this._length=len;this._values=this.shouldCopyValues()?new Array(len):this._values;var result=this._promise;var isResolved=false;var bitField=null;for(var i=0;i<len;++i){var maybePromise=tryConvertToPromise(values[i],result);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();bitField=maybePromise._bitField;}else{bitField=null;}
if(isResolved){if(bitField!==null){maybePromise.suppressUnhandledRejections();}}else if(bitField!==null){if(((bitField&50397184)===0)){maybePromise._proxy(this,i);this._values[i]=maybePromise;}else if(((bitField&33554432)!==0)){isResolved=this._promiseFulfilled(maybePromise._value(),i);}else if(((bitField&16777216)!==0)){isResolved=this._promiseRejected(maybePromise._reason(),i);}else{isResolved=this._promiseCancelled(i);}}else{isResolved=this._promiseFulfilled(maybePromise,i);}}
if(!isResolved)result._setAsyncGuaranteed();};PromiseArray.prototype._isResolved=function(){return this._values===null;};PromiseArray.prototype._resolve=function(value){this._values=null;this._promise._fulfill(value);};PromiseArray.prototype._cancel=function(){if(this._isResolved()||!this._promise.isCancellable())return;this._values=null;this._promise._cancel();};PromiseArray.prototype._reject=function(reason){this._values=null;this._promise._rejectCallback(reason,false);};PromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values);return true;}
return false;};PromiseArray.prototype._promiseCancelled=function(){this._cancel();return true;};PromiseArray.prototype._promiseRejected=function(reason){this._totalResolved++;this._reject(reason);return true;};PromiseArray.prototype._resultCancelled=function(){if(this._isResolved())return;var values=this._values;this._cancel();if(values instanceof Promise){values.cancel();}else{for(var i=0;i<values.length;++i){if(values[i]instanceof Promise){values[i].cancel();}}}};PromiseArray.prototype.shouldCopyValues=function(){return true;};PromiseArray.prototype.getActualLength=function(len){return len;};return PromiseArray;};},{"./util":36}],24:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var THIS={};var util=_dereq_("./util");var nodebackForPromise=_dereq_("./nodeback");var withAppended=util.withAppended;var maybeWrapAsError=util.maybeWrapAsError;var canEvaluate=util.canEvaluate;var TypeError=_dereq_("./errors").TypeError;var defaultSuffix="Async";var defaultPromisified={__isPromisified__:true};var noCopyProps=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"];var noCopyPropsPattern=new RegExp("^(?:"+noCopyProps.join("|")+")$");var defaultFilter=function(name){return util.isIdentifier(name)&&name.charAt(0)!=="_"&&name!=="constructor";};function propsFilter(key){return!noCopyPropsPattern.test(key);}
function isPromisified(fn){try{return fn.__isPromisified__===true;}
catch(e){return false;}}
function hasPromisified(obj,key,suffix){var val=util.getDataPropertyOrDefault(obj,key+suffix,defaultPromisified);return val?isPromisified(val):false;}
function checkValid(ret,suffix,suffixRegexp){for(var i=0;i<ret.length;i+=2){var key=ret[i];if(suffixRegexp.test(key)){var keyWithoutAsyncSuffix=key.replace(suffixRegexp,"");for(var j=0;j<ret.length;j+=2){if(ret[j]===keyWithoutAsyncSuffix){throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a    See http://goo.gl/MqrFmX\u000a".replace("%s",suffix));}}}}}
function promisifiableMethods(obj,suffix,suffixRegexp,filter){var keys=util.inheritedDataKeys(obj);var ret=[];for(var i=0;i<keys.length;++i){var key=keys[i];var value=obj[key];var passesDefaultFilter=filter===defaultFilter?true:defaultFilter(key,value,obj);if(typeof value==="function"&&!isPromisified(value)&&!hasPromisified(obj,key,suffix)&&filter(key,value,obj,passesDefaultFilter)){ret.push(key,value);}}
checkValid(ret,suffix,suffixRegexp);return ret;}
var escapeIdentRegex=function(str){return str.replace(/([$])/,"\\$");};var makeNodePromisifiedEval;if(!true){var switchCaseArgumentOrder=function(likelyArgumentCount){var ret=[likelyArgumentCount];var min=Math.max(0,likelyArgumentCount-1-3);for(var i=likelyArgumentCount-1;i>=min;--i){ret.push(i);}
for(var i=likelyArgumentCount+1;i<=3;++i){ret.push(i);}
return ret;};var argumentSequence=function(argumentCount){return util.filledRange(argumentCount,"_arg","");};var parameterDeclaration=function(parameterCount){return util.filledRange(Math.max(parameterCount,3),"_arg","");};var parameterCount=function(fn){if(typeof fn.length==="number"){return Math.max(Math.min(fn.length,1023+1),0);}
return 0;};makeNodePromisifiedEval=function(callback,receiver,originalName,fn,_,multiArgs){var newParameterCount=Math.max(0,parameterCount(fn)-1);var argumentOrder=switchCaseArgumentOrder(newParameterCount);var shouldProxyThis=typeof callback==="string"||receiver===THIS;function generateCallForArgumentCount(count){var args=argumentSequence(count).join(", ");var comma=count>0?", ":"";var ret;if(shouldProxyThis){ret="ret = callback.call(this, {{args}}, nodeback); break;\n";}else{ret=receiver===undefined?"ret = callback({{args}}, nodeback); break;\n":"ret = callback.call(receiver, {{args}}, nodeback); break;\n";}
return ret.replace("{{args}}",args).replace(", ",comma);}
function generateArgumentSwitchCase(){var ret="";for(var i=0;i<argumentOrder.length;++i){ret+="case "+argumentOrder[i]+":"+
generateCallForArgumentCount(argumentOrder[i]);}
ret+="                                                             \n        default:                                                             \n            var args = new Array(len + 1);                                   \n            var i = 0;                                                       \n            for (var i = 0; i < len; ++i) {                                  \n               args[i] = arguments[i];                                       \n            }                                                                \n            args[i] = nodeback;                                              \n            [CodeForCall]                                                    \n            break;                                                           \n        ".replace("[CodeForCall]",(shouldProxyThis?"ret = callback.apply(this, args);\n":"ret = callback.apply(receiver, args);\n"));return ret;}
var getFunctionCode=typeof callback==="string"?("this != null ? this['"+callback+"'] : fn"):"fn";var body="'use strict';                                                \n        var ret = function (Parameters) {                                    \n            'use strict';                                                    \n            var len = arguments.length;                                      \n            var promise = new Promise(INTERNAL);                             \n            promise._captureStackTrace();                                    \n            var nodeback = nodebackForPromise(promise, "+multiArgs+");   \n            var ret;                                                         \n            var callback = tryCatch([GetFunctionCode]);                      \n            switch(len) {                                                    \n                [CodeForSwitchCase]                                          \n            }                                                                \n            if (ret === errorObj) {                                          \n                promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n            }                                                                \n            if (!promise._isFateSealed()) promise._setAsyncGuaranteed();     \n            return promise;                                                  \n        };                                                                   \n        notEnumerableProp(ret, '__isPromisified__', true);                   \n        return ret;                                                          \n    ".replace("[CodeForSwitchCase]",generateArgumentSwitchCase()).replace("[GetFunctionCode]",getFunctionCode);body=body.replace("Parameters",parameterDeclaration(newParameterCount));return new Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",body)(Promise,fn,receiver,withAppended,maybeWrapAsError,nodebackForPromise,util.tryCatch,util.errorObj,util.notEnumerableProp,INTERNAL);};}
function makeNodePromisifiedClosure(callback,receiver,_,fn,__,multiArgs){var defaultThis=(function(){return this;})();var method=callback;if(typeof method==="string"){callback=fn;}
function promisified(){var _receiver=receiver;if(receiver===THIS)_receiver=this;var promise=new Promise(INTERNAL);promise._captureStackTrace();var cb=typeof method==="string"&&this!==defaultThis?this[method]:callback;var fn=nodebackForPromise(promise,multiArgs);try{cb.apply(_receiver,withAppended(arguments,fn));}catch(e){promise._rejectCallback(maybeWrapAsError(e),true,true);}
if(!promise._isFateSealed())promise._setAsyncGuaranteed();return promise;}
util.notEnumerableProp(promisified,"__isPromisified__",true);return promisified;}
var makeNodePromisified=canEvaluate?makeNodePromisifiedEval:makeNodePromisifiedClosure;function promisifyAll(obj,suffix,filter,promisifier,multiArgs){var suffixRegexp=new RegExp(escapeIdentRegex(suffix)+"$");var methods=promisifiableMethods(obj,suffix,suffixRegexp,filter);for(var i=0,len=methods.length;i<len;i+=2){var key=methods[i];var fn=methods[i+1];var promisifiedKey=key+suffix;if(promisifier===makeNodePromisified){obj[promisifiedKey]=makeNodePromisified(key,THIS,key,fn,suffix,multiArgs);}else{var promisified=promisifier(fn,function(){return makeNodePromisified(key,THIS,key,fn,suffix,multiArgs);});util.notEnumerableProp(promisified,"__isPromisified__",true);obj[promisifiedKey]=promisified;}}
util.toFastProperties(obj);return obj;}
function promisify(callback,receiver,multiArgs){return makeNodePromisified(callback,receiver,undefined,callback,null,multiArgs);}
Promise.promisify=function(fn,options){if(typeof fn!=="function"){throw new TypeError("expecting a function but got "+util.classString(fn));}
if(isPromisified(fn)){return fn;}
options=Object(options);var receiver=options.context===undefined?THIS:options.context;var multiArgs=!!options.multiArgs;var ret=promisify(fn,receiver,multiArgs);util.copyDescriptors(fn,ret,propsFilter);return ret;};Promise.promisifyAll=function(target,options){if(typeof target!=="function"&&typeof target!=="object"){throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
options=Object(options);var multiArgs=!!options.multiArgs;var suffix=options.suffix;if(typeof suffix!=="string")suffix=defaultSuffix;var filter=options.filter;if(typeof filter!=="function")filter=defaultFilter;var promisifier=options.promisifier;if(typeof promisifier!=="function")promisifier=makeNodePromisified;if(!util.isIdentifier(suffix)){throw new RangeError("suffix must be a valid identifier\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
var keys=util.inheritedDataKeys(target);for(var i=0;i<keys.length;++i){var value=target[keys[i]];if(keys[i]!=="constructor"&&util.isClass(value)){promisifyAll(value.prototype,suffix,filter,promisifier,multiArgs);promisifyAll(value,suffix,filter,promisifier,multiArgs);}}
return promisifyAll(target,suffix,filter,promisifier,multiArgs);};};},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,tryConvertToPromise,apiRejection){var util=_dereq_("./util");var isObject=util.isObject;var es5=_dereq_("./es5");var Es6Map;if(typeof Map==="function")Es6Map=Map;var mapToEntries=(function(){var index=0;var size=0;function extractEntry(value,key){this[index]=value;this[index+size]=key;index++;}
return function mapToEntries(map){size=map.size;index=0;var ret=new Array(map.size*2);map.forEach(extractEntry,ret);return ret;};})();var entriesToMap=function(entries){var ret=new Es6Map();var length=entries.length / 2|0;for(var i=0;i<length;++i){var key=entries[length+i];var value=entries[i];ret.set(key,value);}
return ret;};function PropertiesPromiseArray(obj){var isMap=false;var entries;if(Es6Map!==undefined&&obj instanceof Es6Map){entries=mapToEntries(obj);isMap=true;}else{var keys=es5.keys(obj);var len=keys.length;entries=new Array(len*2);for(var i=0;i<len;++i){var key=keys[i];entries[i]=obj[key];entries[i+len]=key;}}
this.constructor$(entries);this._isMap=isMap;this._init$(undefined,-3);}
util.inherits(PropertiesPromiseArray,PromiseArray);PropertiesPromiseArray.prototype._init=function(){};PropertiesPromiseArray.prototype._promiseFulfilled=function(value,index){this._values[index]=value;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){var val;if(this._isMap){val=entriesToMap(this._values);}else{val={};var keyOffset=this.length();for(var i=0,len=this.length();i<len;++i){val[this._values[i+keyOffset]]=this._values[i];}}
this._resolve(val);return true;}
return false;};PropertiesPromiseArray.prototype.shouldCopyValues=function(){return false;};PropertiesPromiseArray.prototype.getActualLength=function(len){return len>>1;};function props(promises){var ret;var castValue=tryConvertToPromise(promises);if(!isObject(castValue)){return apiRejection("cannot await properties of a non-object\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}else if(castValue instanceof Promise){ret=castValue._then(Promise.props,undefined,undefined,undefined,undefined);}else{ret=new PropertiesPromiseArray(castValue).promise();}
if(castValue instanceof Promise){ret._propagateFrom(castValue,2);}
return ret;}
Promise.prototype.props=function(){return props(this);};Promise.props=function(promises){return props(promises);};};},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){"use strict";function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j<len;++j){dst[j+dstIndex]=src[j+srcIndex];src[j+srcIndex]=void 0;}}
function Queue(capacity){this._capacity=capacity;this._length=0;this._front=0;}
Queue.prototype._willBeOverCapacity=function(size){return this._capacity<size;};Queue.prototype._pushOne=function(arg){var length=this.length();this._checkCapacity(length+1);var i=(this._front+length)&(this._capacity-1);this[i]=arg;this._length=length+1;};Queue.prototype._unshiftOne=function(value){var capacity=this._capacity;this._checkCapacity(this.length()+1);var front=this._front;var i=((((front-1)&(capacity-1))^capacity)-capacity);this[i]=value;this._front=i;this._length=this.length()+1;};Queue.prototype.unshift=function(fn,receiver,arg){this._unshiftOne(arg);this._unshiftOne(receiver);this._unshiftOne(fn);};Queue.prototype.push=function(fn,receiver,arg){var length=this.length()+3;if(this._willBeOverCapacity(length)){this._pushOne(fn);this._pushOne(receiver);this._pushOne(arg);return;}
var j=this._front+length-3;this._checkCapacity(length);var wrapMask=this._capacity-1;this[(j+0)&wrapMask]=fn;this[(j+1)&wrapMask]=receiver;this[(j+2)&wrapMask]=arg;this._length=length;};Queue.prototype.shift=function(){var front=this._front,ret=this[front];this[front]=undefined;this._front=(front+1)&(this._capacity-1);this._length--;return ret;};Queue.prototype.length=function(){return this._length;};Queue.prototype._checkCapacity=function(size){if(this._capacity<size){this._resizeTo(this._capacity<<1);}};Queue.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;var front=this._front;var length=this._length;var moveItemsCount=(front+length)&(oldCapacity-1);arrayMove(this,0,this,oldCapacity,moveItemsCount);};module.exports=Queue;},{}],27:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection){var util=_dereq_("./util");var raceLater=function(promise){return promise.then(function(array){return race(array,promise);});};function race(promises,parent){var maybePromise=tryConvertToPromise(promises);if(maybePromise instanceof Promise){return raceLater(maybePromise);}else{promises=util.asArray(promises);if(promises===null)
return apiRejection("expecting an array or an iterable object but got "+util.classString(promises));}
var ret=new Promise(INTERNAL);if(parent!==undefined){ret._propagateFrom(parent,3);}
var fulfill=ret._fulfill;var reject=ret._reject;for(var i=0,len=promises.length;i<len;++i){var val=promises[i];if(val===undefined&&!(i in promises)){continue;}
Promise.cast(val)._then(fulfill,reject,undefined,ret,null);}
return ret;}
Promise.race=function(promises){return race(promises,undefined);};Promise.prototype.race=function(){return race(this,undefined);};};},{"./util":36}],28:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){var getDomain=Promise._getDomain;var util=_dereq_("./util");var tryCatch=util.tryCatch;function ReductionPromiseArray(promises,fn,initialValue,_each){this.constructor$(promises);var domain=getDomain();this._fn=domain===null?fn:domain.bind(fn);if(initialValue!==undefined){initialValue=Promise.resolve(initialValue);initialValue._attachCancellationCallback(this);}
this._initialValue=initialValue;this._currentCancellable=null;this._eachValues=_each===INTERNAL?[]:undefined;this._promise._captureStackTrace();this._init$(undefined,-5);}
util.inherits(ReductionPromiseArray,PromiseArray);ReductionPromiseArray.prototype._gotAccum=function(accum){if(this._eachValues!==undefined&&accum!==INTERNAL){this._eachValues.push(accum);}};ReductionPromiseArray.prototype._eachComplete=function(value){this._eachValues.push(value);return this._eachValues;};ReductionPromiseArray.prototype._init=function(){};ReductionPromiseArray.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==undefined?this._eachValues:this._initialValue);};ReductionPromiseArray.prototype.shouldCopyValues=function(){return false;};ReductionPromiseArray.prototype._resolve=function(value){this._promise._resolveCallback(value);this._values=null;};ReductionPromiseArray.prototype._resultCancelled=function(sender){if(sender===this._initialValue)return this._cancel();if(this._isResolved())return;this._resultCancelled$();if(this._currentCancellable instanceof Promise){this._currentCancellable.cancel();}
if(this._initialValue instanceof Promise){this._initialValue.cancel();}};ReductionPromiseArray.prototype._iterate=function(values){this._values=values;var value;var i;var length=values.length;if(this._initialValue!==undefined){value=this._initialValue;i=0;}else{value=Promise.resolve(values[0]);i=1;}
this._currentCancellable=value;if(!value.isRejected()){for(;i<length;++i){var ctx={accum:null,value:values[i],index:i,length:length,array:this};value=value._then(gotAccum,undefined,undefined,ctx,undefined);}}
if(this._eachValues!==undefined){value=value._then(this._eachComplete,undefined,undefined,this,undefined);}
value._then(completed,completed,undefined,value,this);};Promise.prototype.reduce=function(fn,initialValue){return reduce(this,fn,initialValue,null);};Promise.reduce=function(promises,fn,initialValue,_each){return reduce(promises,fn,initialValue,_each);};function completed(valueOrReason,array){if(this.isFulfilled()){array._resolve(valueOrReason);}else{array._reject(valueOrReason);}}
function reduce(promises,fn,initialValue,_each){if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn));}
var array=new ReductionPromiseArray(promises,fn,initialValue,_each);return array.promise();}
function gotAccum(accum){this.accum=accum;this.array._gotAccum(accum);var value=tryConvertToPromise(this.value,this.array._promise);if(value instanceof Promise){this.array._currentCancellable=value;return value._then(gotValue,undefined,undefined,this,undefined);}else{return gotValue.call(this,value);}}
function gotValue(value){var array=this.array;var promise=array._promise;var fn=tryCatch(array._fn);promise._pushContext();var ret;if(array._eachValues!==undefined){ret=fn.call(promise._boundValue(),value,this.index,this.length);}else{ret=fn.call(promise._boundValue(),this.accum,value,this.index,this.length);}
if(ret instanceof Promise){array._currentCancellable=ret;}
var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,array._eachValues!==undefined?"Promise.each":"Promise.reduce",promise);return ret;}};},{"./util":36}],29:[function(_dereq_,module,exports){"use strict";var util=_dereq_("./util");var schedule;var noAsyncScheduler=function(){throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");};var NativePromise=util.getNativePromise();if(util.isNode&&typeof MutationObserver==="undefined"){var GlobalSetImmediate=global.setImmediate;var ProcessNextTick=process.nextTick;schedule=util.isRecentNode?function(fn){GlobalSetImmediate.call(global,fn);}:function(fn){ProcessNextTick.call(process,fn);};}else if(typeof NativePromise==="function"){var nativePromise=NativePromise.resolve();schedule=function(fn){nativePromise.then(fn);};}else if((typeof MutationObserver!=="undefined")&&!(typeof window!=="undefined"&&window.navigator&&window.navigator.standalone)){schedule=(function(){var div=document.createElement("div");var opts={attributes:true};var toggleScheduled=false;var div2=document.createElement("div");var o2=new MutationObserver(function(){div.classList.toggle("foo");toggleScheduled=false;});o2.observe(div2,opts);var scheduleToggle=function(){if(toggleScheduled)return;toggleScheduled=true;div2.classList.toggle("foo");};return function schedule(fn){var o=new MutationObserver(function(){o.disconnect();fn();});o.observe(div,opts);scheduleToggle();};})();}else if(typeof setImmediate!=="undefined"){schedule=function(fn){setImmediate(fn);};}else if(typeof setTimeout!=="undefined"){schedule=function(fn){setTimeout(fn,0);};}else{schedule=noAsyncScheduler;}
module.exports=schedule;},{"./util":36}],30:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,debug){var PromiseInspection=Promise.PromiseInspection;var util=_dereq_("./util");function SettledPromiseArray(values){this.constructor$(values);}
util.inherits(SettledPromiseArray,PromiseArray);SettledPromiseArray.prototype._promiseResolved=function(index,inspection){this._values[index]=inspection;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values);return true;}
return false;};SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection();ret._bitField=33554432;ret._settledValueField=value;return this._promiseResolved(index,ret);};SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection();ret._bitField=16777216;ret._settledValueField=reason;return this._promiseResolved(index,ret);};Promise.settle=function(promises){debug.deprecated(".settle()",".reflect()");return new SettledPromiseArray(promises).promise();};Promise.prototype.settle=function(){return Promise.settle(this);};};},{"./util":36}],31:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection){var util=_dereq_("./util");var RangeError=_dereq_("./errors").RangeError;var AggregateError=_dereq_("./errors").AggregateError;var isArray=util.isArray;var CANCELLATION={};function SomePromiseArray(values){this.constructor$(values);this._howMany=0;this._unwrap=false;this._initialized=false;}
util.inherits(SomePromiseArray,PromiseArray);SomePromiseArray.prototype._init=function(){if(!this._initialized){return;}
if(this._howMany===0){this._resolve([]);return;}
this._init$(undefined,-5);var isArrayResolved=isArray(this._values);if(!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()){this._reject(this._getRangeError(this.length()));}};SomePromiseArray.prototype.init=function(){this._initialized=true;this._init();};SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=true;};SomePromiseArray.prototype.howMany=function(){return this._howMany;};SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count;};SomePromiseArray.prototype._promiseFulfilled=function(value){this._addFulfilled(value);if(this._fulfilled()===this.howMany()){this._values.length=this.howMany();if(this.howMany()===1&&this._unwrap){this._resolve(this._values[0]);}else{this._resolve(this._values);}
return true;}
return false;};SomePromiseArray.prototype._promiseRejected=function(reason){this._addRejected(reason);return this._checkOutcome();};SomePromiseArray.prototype._promiseCancelled=function(){if(this._values instanceof Promise||this._values==null){return this._cancel();}
this._addRejected(CANCELLATION);return this._checkOutcome();};SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){var e=new AggregateError();for(var i=this.length();i<this._values.length;++i){if(this._values[i]!==CANCELLATION){e.push(this._values[i]);}}
if(e.length>0){this._reject(e);}else{this._cancel();}
return true;}
return false;};SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved;};SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length();};SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason);};SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value;};SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected();};SomePromiseArray.prototype._getRangeError=function(count){var message="Input array must contain at least "+
this._howMany+" items but contains only "+count+" items";return new RangeError(message);};SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0));};function some(promises,howMany){if((howMany|0)!==howMany||howMany<0){return apiRejection("expecting a positive integer\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
var ret=new SomePromiseArray(promises);var promise=ret.promise();ret.setHowMany(howMany);ret.init();return promise;}
Promise.some=function(promises,howMany){return some(promises,howMany);};Promise.prototype.some=function(howMany){return some(this,howMany);};Promise._SomePromiseArray=SomePromiseArray;};},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise){function PromiseInspection(promise){if(promise!==undefined){promise=promise._target();this._bitField=promise._bitField;this._settledValueField=promise._isFateSealed()?promise._settledValue():undefined;}
else{this._bitField=0;this._settledValueField=undefined;}}
PromiseInspection.prototype._settledValue=function(){return this._settledValueField;};var value=PromiseInspection.prototype.value=function(){if(!this.isFulfilled()){throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
return this._settledValue();};var reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected()){throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a");}
return this._settledValue();};var isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0;};var isRejected=PromiseInspection.prototype.isRejected=function(){return(this._bitField&16777216)!==0;};var isPending=PromiseInspection.prototype.isPending=function(){return(this._bitField&50397184)===0;};var isResolved=PromiseInspection.prototype.isResolved=function(){return(this._bitField&50331648)!==0;};PromiseInspection.prototype.isCancelled=Promise.prototype._isCancelled=function(){return(this._bitField&65536)===65536;};Promise.prototype.isCancelled=function(){return this._target()._isCancelled();};Promise.prototype.isPending=function(){return isPending.call(this._target());};Promise.prototype.isRejected=function(){return isRejected.call(this._target());};Promise.prototype.isFulfilled=function(){return isFulfilled.call(this._target());};Promise.prototype.isResolved=function(){return isResolved.call(this._target());};Promise.prototype.value=function(){return value.call(this._target());};Promise.prototype.reason=function(){var target=this._target();target._unsetRejectionIsUnhandled();return reason.call(target);};Promise.prototype._value=function(){return this._settledValue();};Promise.prototype._reason=function(){this._unsetRejectionIsUnhandled();return this._settledValue();};Promise.PromiseInspection=PromiseInspection;};},{}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=_dereq_("./util");var errorObj=util.errorObj;var isObject=util.isObject;function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var then=getThen(obj);if(then===errorObj){if(context)context._pushContext();var ret=Promise.reject(then.e);if(context)context._popContext();return ret;}else if(typeof then==="function"){if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);obj._then(ret._fulfill,ret._reject,undefined,ret,null);return ret;}
return doThenable(obj,then,context);}}
return obj;}
function doGetThen(obj){return obj.then;}
function getThen(obj){try{return doGetThen(obj);}catch(e){errorObj.e=e;return errorObj;}}
var hasProp={}.hasOwnProperty;function isAnyBluebirdPromise(obj){try{return hasProp.call(obj,"_promise0");}catch(e){return false;}}
function doThenable(x,then,context){var promise=new Promise(INTERNAL);var ret=promise;if(context)context._pushContext();promise._captureStackTrace();if(context)context._popContext();var synchronous=true;var result=util.tryCatch(then).call(x,resolve,reject);synchronous=false;if(promise&&result===errorObj){promise._rejectCallback(result.e,true,true);promise=null;}
function resolve(value){if(!promise)return;promise._resolveCallback(value);promise=null;}
function reject(reason){if(!promise)return;promise._rejectCallback(reason,synchronous,true);promise=null;}
return ret;}
return tryConvertToPromise;};},{"./util":36}],34:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,debug){var util=_dereq_("./util");var TimeoutError=Promise.TimeoutError;function HandleWrapper(handle){this.handle=handle;}
HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle);};var afterValue=function(value){return delay(+this).thenReturn(value);};var delay=Promise.delay=function(ms,value){var ret;var handle;if(value!==undefined){ret=Promise.resolve(value)._then(afterValue,null,null,ms,undefined);if(debug.cancellation()&&value instanceof Promise){ret._setOnCancel(value);}}else{ret=new Promise(INTERNAL);handle=setTimeout(function(){ret._fulfill();},+ms);if(debug.cancellation()){ret._setOnCancel(new HandleWrapper(handle));}}
ret._setAsyncGuaranteed();return ret;};Promise.prototype.delay=function(ms){return delay(ms,this);};var afterTimeout=function(promise,message,parent){var err;if(typeof message!=="string"){if(message instanceof Error){err=message;}else{err=new TimeoutError("operation timed out");}}else{err=new TimeoutError(message);}
util.markAsOriginatingFromRejection(err);promise._attachExtraTrace(err);promise._reject(err);if(parent!=null){parent.cancel();}};function successClear(value){clearTimeout(this.handle);return value;}
function failureClear(reason){clearTimeout(this.handle);throw reason;}
Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent;var handleWrapper=new HandleWrapper(setTimeout(function timeoutTimeout(){if(ret.isPending()){afterTimeout(ret,message,parent);}},ms));if(debug.cancellation()){parent=this.then();ret=parent._then(successClear,failureClear,undefined,handleWrapper,undefined);ret._setOnCancel(handleWrapper);}else{ret=this._then(successClear,failureClear,undefined,handleWrapper,undefined);}
return ret;};};},{"./util":36}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){var util=_dereq_("./util");var TypeError=_dereq_("./errors").TypeError;var inherits=_dereq_("./util").inherits;var errorObj=util.errorObj;var tryCatch=util.tryCatch;var NULL={};function thrower(e){setTimeout(function(){throw e;},0);}
function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);if(maybePromise!==thenable&&typeof thenable._isDisposable==="function"&&typeof thenable._getDisposer==="function"&&thenable._isDisposable()){maybePromise._setDisposable(thenable._getDisposer());}
return maybePromise;}
function dispose(resources,inspection){var i=0;var len=resources.length;var ret=new Promise(INTERNAL);function iterator(){if(i>=len)return ret._fulfill();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise);}catch(e){return thrower(e);}
if(maybePromise instanceof Promise){return maybePromise._then(iterator,thrower,null,null,null);}}
iterator();}
iterator();return ret;}
function Disposer(data,promise,context){this._data=data;this._promise=promise;this._context=context;}
Disposer.prototype.data=function(){return this._data;};Disposer.prototype.promise=function(){return this._promise;};Disposer.prototype.resource=function(){if(this.promise().isFulfilled()){return this.promise().value();}
return NULL;};Disposer.prototype.tryDispose=function(inspection){var resource=this.resource();var context=this._context;if(context!==undefined)context._pushContext();var ret=resource!==NULL?this.doDispose(resource,inspection):null;if(context!==undefined)context._popContext();this._promise._unsetDisposable();this._data=null;return ret;};Disposer.isDisposer=function(d){return(d!=null&&typeof d.resource==="function"&&typeof d.tryDispose==="function");};function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context);}
inherits(FunctionDisposer,Disposer);FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection);};function maybeUnwrapDisposer(value){if(Disposer.isDisposer(value)){this.resources[this.index]._setDisposable(value);return value.promise();}
return value;}
function ResourceList(length){this.length=length;this.promise=null;this[length-1]=null;}
ResourceList.prototype._resultCancelled=function(){var len=this.length;for(var i=0;i<len;++i){var item=this[i];if(item instanceof Promise){item.cancel();}}};Promise.using=function(){var len=arguments.length;if(len<2)return apiRejection("you must pass at least 2 arguments to Promise.using");var fn=arguments[len-1];if(typeof fn!=="function"){return apiRejection("expecting a function but got "+util.classString(fn));}
var input;var spreadArgs=true;if(len===2&&Array.isArray(arguments[0])){input=arguments[0];len=input.length;spreadArgs=false;}else{input=arguments;len--;}
var resources=new ResourceList(len);for(var i=0;i<len;++i){var resource=input[i];if(Disposer.isDisposer(resource)){var disposer=resource;resource=resource.promise();resource._setDisposable(disposer);}else{var maybePromise=tryConvertToPromise(resource);if(maybePromise instanceof Promise){resource=maybePromise._then(maybeUnwrapDisposer,null,null,{resources:resources,index:i},undefined);}}
resources[i]=resource;}
var reflectedResources=new Array(resources.length);for(var i=0;i<reflectedResources.length;++i){reflectedResources[i]=Promise.resolve(resources[i]).reflect();}
var resultPromise=Promise.all(reflectedResources).then(function(inspections){for(var i=0;i<inspections.length;++i){var inspection=inspections[i];if(inspection.isRejected()){errorObj.e=inspection.error();return errorObj;}else if(!inspection.isFulfilled()){resultPromise.cancel();return;}
inspections[i]=inspection.value();}
promise._pushContext();fn=tryCatch(fn);var ret=spreadArgs?fn.apply(undefined,inspections):fn(inspections);var promiseCreated=promise._popContext();debug.checkForgottenReturns(ret,promiseCreated,"Promise.using",promise);return ret;});var promise=resultPromise.lastly(function(){var inspection=new Promise.PromiseInspection(resultPromise);return dispose(resources,inspection);});resources.promise=promise;promise._setOnCancel(resources);return promise;};Promise.prototype._setDisposable=function(disposer){this._bitField=this._bitField|131072;this._disposer=disposer;};Promise.prototype._isDisposable=function(){return(this._bitField&131072)>0;};Promise.prototype._getDisposer=function(){return this._disposer;};Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&(~131072);this._disposer=undefined;};Promise.prototype.disposer=function(fn){if(typeof fn==="function"){return new FunctionDisposer(fn,this,createContext());}
throw new TypeError();};};},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){"use strict";var es5=_dereq_("./es5");var canEvaluate=typeof navigator=="undefined";var errorObj={e:{}};var tryCatchTarget;var globalObject=typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this!==undefined?this:null;function tryCatcher(){try{var target=tryCatchTarget;tryCatchTarget=null;return target.apply(this,arguments);}catch(e){errorObj.e=e;return errorObj;}}
function tryCatch(fn){tryCatchTarget=fn;return tryCatcher;}
var inherits=function(Child,Parent){var hasProp={}.hasOwnProperty;function T(){this.constructor=Child;this.constructor$=Parent;for(var propertyName in Parent.prototype){if(hasProp.call(Parent.prototype,propertyName)&&propertyName.charAt(propertyName.length-1)!=="$"){this[propertyName+"$"]=Parent.prototype[propertyName];}}}
T.prototype=Parent.prototype;Child.prototype=new T();return Child.prototype;};function isPrimitive(val){return val==null||val===true||val===false||typeof val==="string"||typeof val==="number";}
function isObject(value){return typeof value==="function"||typeof value==="object"&&value!==null;}
function maybeWrapAsError(maybeError){if(!isPrimitive(maybeError))return maybeError;return new Error(safeToString(maybeError));}
function withAppended(target,appendee){var len=target.length;var ret=new Array(len+1);var i;for(i=0;i<len;++i){ret[i]=target[i];}
ret[i]=appendee;return ret;}
function getDataPropertyOrDefault(obj,key,defaultValue){if(es5.isES5){var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null){return desc.get==null&&desc.set==null?desc.value:defaultValue;}}else{return{}.hasOwnProperty.call(obj,key)?obj[key]:undefined;}}
function notEnumerableProp(obj,name,value){if(isPrimitive(obj))return obj;var descriptor={value:value,configurable:true,enumerable:false,writable:true};es5.defineProperty(obj,name,descriptor);return obj;}
function thrower(r){throw r;}
var inheritedDataKeys=(function(){var excludedPrototypes=[Array.prototype,Object.prototype,Function.prototype];var isExcludedProto=function(val){for(var i=0;i<excludedPrototypes.length;++i){if(excludedPrototypes[i]===val){return true;}}
return false;};if(es5.isES5){var getKeys=Object.getOwnPropertyNames;return function(obj){var ret=[];var visitedKeys=Object.create(null);while(obj!=null&&!isExcludedProto(obj)){var keys;try{keys=getKeys(obj);}catch(e){return ret;}
for(var i=0;i<keys.length;++i){var key=keys[i];if(visitedKeys[key])continue;visitedKeys[key]=true;var desc=Object.getOwnPropertyDescriptor(obj,key);if(desc!=null&&desc.get==null&&desc.set==null){ret.push(key);}}
obj=es5.getPrototypeOf(obj);}
return ret;};}else{var hasProp={}.hasOwnProperty;return function(obj){if(isExcludedProto(obj))return[];var ret=[];enumeration:for(var key in obj){if(hasProp.call(obj,key)){ret.push(key);}else{for(var i=0;i<excludedPrototypes.length;++i){if(hasProp.call(excludedPrototypes[i],key)){continue enumeration;}}
ret.push(key);}}
return ret;};}})();var thisAssignmentPattern=/this\s*\.\s*\S+\s*=/;function isClass(fn){try{if(typeof fn==="function"){var keys=es5.names(fn.prototype);var hasMethods=es5.isES5&&keys.length>1;var hasMethodsOtherThanConstructor=keys.length>0&&!(keys.length===1&&keys[0]==="constructor");var hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods){return true;}}
return false;}catch(e){return false;}}
function toFastProperties(obj){function FakeConstructor(){}
FakeConstructor.prototype=obj;var l=8;while(l--)new FakeConstructor();return obj;eval(obj);}
var rident=/^[a-z$_][a-z$_0-9]*$/i;function isIdentifier(str){return rident.test(str);}
function filledRange(count,prefix,suffix){var ret=new Array(count);for(var i=0;i<count;++i){ret[i]=prefix+i+suffix;}
return ret;}
function safeToString(obj){try{return obj+"";}catch(e){return"[no string representation]";}}
function isError(obj){return obj!==null&&typeof obj==="object"&&typeof obj.message==="string"&&typeof obj.name==="string";}
function markAsOriginatingFromRejection(e){try{notEnumerableProp(e,"isOperational",true);}
catch(ignore){}}
function originatesFromRejection(e){if(e==null)return false;return((e instanceof Error["__BluebirdErrorTypes__"].OperationalError)||e["isOperational"]===true);}
function canAttachTrace(obj){return isError(obj)&&es5.propertyIsWritable(obj,"stack");}
var ensureErrorObject=(function(){if(!("stack"in new Error())){return function(value){if(canAttachTrace(value))return value;try{throw new Error(safeToString(value));}
catch(err){return err;}};}else{return function(value){if(canAttachTrace(value))return value;return new Error(safeToString(value));};}})();function classString(obj){return{}.toString.call(obj);}
function copyDescriptors(from,to,filter){var keys=es5.names(from);for(var i=0;i<keys.length;++i){var key=keys[i];if(filter(key)){try{es5.defineProperty(to,key,es5.getDescriptor(from,key));}catch(ignore){}}}}
var asArray=function(v){if(es5.isArray(v)){return v;}
return null;};if(typeof Symbol!=="undefined"&&Symbol.iterator){var ArrayFrom=typeof Array.from==="function"?function(v){return Array.from(v);}:function(v){var ret=[];var it=v[Symbol.iterator]();var itResult;while(!((itResult=it.next()).done)){ret.push(itResult.value);}
return ret;};asArray=function(v){if(es5.isArray(v)){return v;}else if(v!=null&&typeof v[Symbol.iterator]==="function"){return ArrayFrom(v);}
return null;};}
var isNode=typeof process!=="undefined"&&classString(process).toLowerCase()==="[object process]";function env(key,def){return isNode?process.env[key]:def;}
function getNativePromise(){if(typeof Promise==="function"){try{var promise=new Promise(function(){});if({}.toString.call(promise)==="[object Promise]"){return Promise;}}catch(e){}}}
var ret={isClass:isClass,isIdentifier:isIdentifier,inheritedDataKeys:inheritedDataKeys,getDataPropertyOrDefault:getDataPropertyOrDefault,thrower:thrower,isArray:es5.isArray,asArray:asArray,notEnumerableProp:notEnumerableProp,isPrimitive:isPrimitive,isObject:isObject,isError:isError,canEvaluate:canEvaluate,errorObj:errorObj,tryCatch:tryCatch,inherits:inherits,withAppended:withAppended,maybeWrapAsError:maybeWrapAsError,toFastProperties:toFastProperties,filledRange:filledRange,toString:safeToString,canAttachTrace:canAttachTrace,ensureErrorObject:ensureErrorObject,originatesFromRejection:originatesFromRejection,markAsOriginatingFromRejection:markAsOriginatingFromRejection,classString:classString,copyDescriptors:copyDescriptors,hasDevTools:typeof chrome!=="undefined"&&chrome&&typeof chrome.loadTimes==="function",isNode:isNode,env:env,global:globalObject,getNativePromise:getNativePromise};ret.isRecentNode=ret.isNode&&(function(){var version=process.versions.node.split(".").map(Number);return(version[0]===0&&version[1]>10)||(version[0]>0);})();if(ret.isNode)ret.toFastProperties(process);try{throw new Error();}catch(e){ret.lastLineError=e;}
module.exports=ret;},{"./es5":13}]},{},[4])(4)});;if(typeof window!=='undefined'&&window!==null){window.P=window.Promise;}else if(typeof self!=='undefined'&&self!==null){self.P=self.Promise;}
(function(root,factory){if(typeof define==='function'&&define.amd){define('score.init',factory);}else if(typeof module==='object'&&module.exports){module.exports=factory();}else{var old=root.score,score=factory();score.noConflict=function(){root.score=old;old=score;score.noConflict=function(){return score;};return score;};root.score=score;}})(this,function(){var __queue=[],score={__version__:'0.0.2',extend:function(fullName,dependencies,callback){var i,j,tmp,nextName,parts,currentPart,nextPart,missing=[];for(i=0;i<dependencies.length;i++){parts=dependencies[i].split('.');currentPart=score;for(j=0;j<parts.length;j++){try{nextPart=currentPart[parts[j]];}catch(e){missing.push(parts.slice(0,j+1).join('.'));break;}
if(!nextPart){missing.push(parts.slice(0,j+1).join('.'));break;}
currentPart=nextPart;}}
currentPart=score;parts=fullName.split('.');for(j=0;j<parts.length-1;j++){try{nextPart=currentPart[parts[j]];}catch(e){missing.push(parts.slice(0,j+1).join('.'));break;}
if(!nextPart){missing.push(parts.slice(0,j+1).join('.'));break;}
currentPart=nextPart;}
nextName=parts[j];if(missing.length){__queue.push([fullName,dependencies,callback]);tmp={};tmp[nextName]={configurable:true,get:function(){throw new Error('Missing '+fullName+' dependencies: ['+missing.join(', ')+']');},set:function(value){tmp[nextName]={value:value,enumerable:true};Object.defineProperties(currentPart,tmp);}};Object.defineProperties(currentPart,tmp);}else{currentPart[nextName]=callback.call(score,score);tmp=__queue;__queue=[];for(i=0;i<tmp.length;i++){score.extend.apply(this,tmp[i]);}}}};return score;});(function(root,factory){if(typeof define==='function'&&define.amd){define('score.oop',['score.init'],factory);}else if(typeof module==='object'&&module.exports){module.exports=factory(require('score.init'));}else{factory(root.score);}}(this,function(score){score.extend('oop',[],function(){var oop={__version__:"0.4.0"};var superRe=/\b__super__\b/;var argumentsRe=/\barguments\b/;var extractParameterNames=function(function_){var i=0;var funcStr=extractParameterNames.toString.call(function_);var skipTo=function(chr){while(funcStr[i]!==chr){i++;if(funcStr[i]!=='/'){continue;}
i++;if(funcStr[i]==='/'){i++;while(funcStr[i]!=='\n'){i++;}}else if(funcStr[i]==='*'){i++;while(funcStr[i]!=='*'&&funcStr[i+1]!=='/'){i++;}}}
return i;};var startIdx=skipTo('(')+1;var stopIdx=skipTo(')');return funcStr.substring(startIdx,stopIdx).replace(/\/\*.*?\*\//,'').replace(/\/\/.*?\n/,'').trim().split(/\s*,\s*/);};var createSubFunc=function(__super__,function_,name){if(!argumentsRe.test(function_)&&function_.length===0&&(!__super__||!superRe.test(function_))){return function_;}
var args=extractParameterNames(function_).slice(1);var declaration='function '+name+'('+args.join(', ')+') {\n';var body;if(argumentsRe.test(function_)){body='    var __args__ = new Array(arguments.length + 1);\n'+'    __args__[0] = this;\n'+'    for (var i = 0; i < arguments.length; i++) {\n'+'        __args__[i + 1] = arguments[i];\n'+'    }\n'+'    var __result__ = function_.apply(this, __args__);\n';}else if(function_.length>1){body='    var __result__ = function_.call(this, this, '+args.join(', ')+');\n';}else if(function_.length==1){body='    var __result__ = function_.call(this, this);\n';}else{body='    var __result__ = function_.call(this);\n';}
if(__super__&&superRe.test(function_)){body='    var __previous_super__ = this.__super__;\n'+'    this.__super__ = __super__.bind(this);\n'+
body+'    this.__super__ = __previous_super__;\n';}else{body='    var __previous_super__ = this.__super__;\n'+'    delete this.__super__;\n'+
body+'    this.__super__ = __previous_super__;\n';}
body+='    return __result__;\n}';return eval('['+declaration+body+']')[0];};var createConstructor=function(name,conf,parents,members,methods){var __init__,__parent_init__;if(conf.__init__){__init__=conf.__init__;}
for(var i=parents.length-1;i>=0;i--){if(parents[i].__conf__.__init__){if(!__init__){__init__=parents[i].__conf__.__init__;}else{__parent_init__=parents[i].__conf__.__wrapped_init__;break;}}}
var args;if(!__init__){args=[];}else{args=extractParameterNames(__init__).slice(1);}
var declaration='function '+name+'('+args.join(', ')+') {\n';var call,body;if(__init__&&argumentsRe.test(__init__)){call='        var args = [];\n'+'        for (var i = 0; i < arguments.length; i++) {\n'+'            args.push("arguments[" + i + "]");\n'+'        }\n'+'        return eval("new '+name+'(" + args.join(", ") + ")")\n';}else{call='        return new '+name+'('+args.join(', ')+');\n';}
body='    if (!(this instanceof '+name+')) {\n'+
call+'    }\n';if(parents[parents.length-1].prototype.__events__){body+='        this.__events__ = {\n'+'            validNames: '+name+'.prototype.__events__.validNames,\n'+'            listeners: {}\n'+'        };\n';}
for(var attr in members){if(members[attr]instanceof Array){body+='    this.'+attr+' = [\n';var lines=[];for(var i=0;i<members[attr].length;i++){lines.push('        members.'+attr+'['+i+']');}
body+=lines.join(',\n')+'\n';body+='    ];\n';}else if(members[attr]instanceof Object){body+='    this.'+attr+' = {\n';var lines=[];for(var key in members[attr]){lines.push('        "'+key+'": members.'+attr+'["'+key+'"]');}
body+=lines.join(',\n')+'\n';body+='    };\n';}else{body+='    this.'+attr+' = members.'+attr+';\n';}}
for(attr in methods){body+='    this.'+attr+' = methods.'+attr+'.bind(this);\n';}
if(__init__){conf.__wrapped_init__=createSubFunc(__parent_init__,__init__,name+'__init__');var initCall;if(argumentsRe.test(__init__)){initCall='    var args = new Array(arguments.length + 1);\n'+'    args[0] = this;\n'+'    for (var i = 0; i < arguments.length; i++) {\n'+'        args[i + 1] = arguments[i];\n'+'    }\n'+'    __init__.apply(this, args);\n';}else if(__init__.length>1){initCall='    __init__.call(this, this, '+args.join(', ')+');\n';}else if(__init__.length==1){initCall='    __init__.call(this, this);\n';}else{initCall='    __init__.call(this);\n';}
if(__parent_init__){initCall='    var __previous_super__ = this.__super__;\n'+'    this.__super__ = __parent_init__.bind(this);\n'+
initCall+'    this.__super__ = __previous_super__;\n';}
body+=initCall;}
body+='}';return eval('['+declaration+body+']')[0];};var checkConf=function(conf){if(typeof conf!=='object'){throw new Error('Class configuration not an object');}
if(!conf.__name__){throw new Error('No class __name__ defined');}
if(!/^_*[A-Z]/.test(conf.__name__)){console.warn('Class names should start with a capital letter',conf.__name__);}
if(!/^_*[a-zA-Z][a-zA-Z0-9_]*$/.test(conf.__name__)){throw new Error('Invalid class name "'+conf.__name__+'"');}
if(typeof conf.__init__!=='undefined'){if(typeof conf.__init__!=='function'){throw new Error(conf.__name__+'.__init__ must be a function');}}
if(conf.__parent__&&!(conf.__parent__.__conf__&&conf.__parent__.__conf__.__name__)){throw new Error(conf.__name__+'.__parent__ is not an oop.Class type');}};var gatherParents=function(conf){if(!conf.__parent__){return[oop.Class];}
var parents=[];for(var parent=conf.__parent__;parent;parent=parent.__conf__.__parent__){parents.push(parent);}
if(parents[parents.length-1]!==oop.Exception){parents.push(oop.Class);}
parents=parents.reverse();return parents;};oop.Class=function(conf){checkConf(conf);var clsName=conf.__name__;var parents=gatherParents(conf);var staticMembers={};var staticMethods={};var members={};var methods={};var static2cls={};parents.forEach(function(cls){if(cls.__conf__.__static__){for(var attr in cls.__conf__.__static__){if(attr[0]==='_'&&attr[1]==='_'){continue;}
var thing=cls.__conf__.__static__[attr];if(typeof thing==='function'){staticMethods[attr]=cls.__conf__.__static__.__unbound__[attr];}else{staticMembers[attr]=thing;}
static2cls[attr]=cls;}}
for(var attr in cls.__conf__){if(attr[0]==='_'&&attr[1]==='_'){continue;}
var thing=cls.__conf__[attr];if(typeof thing==='function'){methods[attr]=cls.prototype[attr];}else{members[attr]=thing;}}});var prototype=Object.create(conf.__parent__?conf.__parent__.prototype:oop.Class.prototype);if(conf.__static__){conf.__static__.__unbound__={};for(var attr in conf.__static__){var thing=conf.__static__[attr];if(typeof thing==='function'){if(typeof staticMembers[attr]!=='undefined'){throw new Error('Static member '+clsName+'.'+attr+' was not a function in a parent class');}
conf.__static__.__unbound__[attr]=prototype[attr]=staticMethods[attr]=createSubFunc(staticMethods[attr],thing,clsName+'__'+attr);}else{if(typeof staticMethods[attr]==='function'){throw new Error('Static member '+clsName+'.'+attr+' was a function in a parent class');}
prototype[attr]=staticMembers[attr]=thing;}}}
for(var attr in conf){if(attr[0]==='_'&&attr[1]==='_'){continue;}
var thing=conf[attr];if(typeof thing==='function'){if(attr!=='toString'&&typeof members[attr]!=='undefined'){throw new Error('Member '+clsName+'.'+attr+' was not a function in a parent class');}
prototype[attr]=methods[attr]=createSubFunc(methods[attr],thing,clsName+'__'+attr);}else{if(typeof methods[attr]!=='undefined'){throw new Error('Member '+clsName+'.'+attr+' was a function in a parent class');}
prototype[attr]=members[attr]=thing;}}
var cls=createConstructor(clsName,conf,parents,members,methods);for(var attr in staticMembers){cls[attr]=staticMembers[attr];}
for(var attr in staticMethods){cls[attr]=staticMethods[attr].bind(cls);}
cls.__conf__=conf;cls.__name__=conf.__name__;cls.prototype=prototype;cls.prototype.__class__=cls;cls.prototype.constructor=cls;cls.toString=function(){return'<'+cls.__name__+' class>';};setEventNames(cls,conf,true);if(conf.__events__){setEventNames(cls,conf,false);}
return cls;};var setEventNames=function(cls,conf,static_){var names={},inheritedNames;if(!static_&&conf.__parent__){inheritedNames=conf.__parent__.prototype.__events__.validNames;if(inheritedNames==='__all__'){names='__all__';}else{for(var name in inheritedNames){names[name]=inheritedNames[name];}}}
var events=conf.__events__;if(static_){events=[];if(conf.__static__&&conf.__static__.__events__){events=conf.__static__.__events__;}}
if(events instanceof Array){for(var i=0;i<events.length;i++){names[events[i]]=cls;}}else if(events){names='__all__';}
if(static_){cls.__events__={validNames:names,listeners:{}};}else{cls.prototype.__events__={validNames:names,listeners:{}};}};var eventFunctions={on:function(self,eventList,callback){var events=eventList.trim().split(/\s+/);for(var i=0;i<events.length;i++){var event=events[i];if(self.__events__.validNames!=='__all__'&&!self.__events__.validNames[event]){throw new Error('Invalid event "'+event+'"');}
if(typeof self.__events__.listeners[event]==='undefined'){self.__events__.listeners[event]=[];}
self.__events__.listeners[event].push(callback);}
return self;},off:function(self,eventList,callback){var events=eventList.trim().split(/\s+/);for(var i=0;i<events.length;i++){var event=events[i];if(self.__events__.validNames!=='__all__'&&!self.__events__.validNames[event]){throw new Error('Invalid event "'+event+'"');}
if(typeof self.__events__.listeners[event]==='undefined'){continue;}
if(typeof callback==='undefined'){delete self.__events__.listeners[event];}else{var idx=self.__events__.listeners[event].indexOf(callback);if(idx<0){continue;}
if(self.__events__.listeners[event].length==1){delete self.__events__.listeners[event];}else{self.__events__.listeners[event].splice(idx,1);}}}
return self;},trigger:function(self,event){if(self.__events__.validNames!=='__all__'&&!self.__events__.validNames[event]){throw new Error('Invalid event "'+event+'"');}
if(typeof self.__events__.listeners[event]==='undefined'){return true;}
var args=[];for(var i=2;i<arguments.length;i++){args.push(arguments[i]);}
var listeners=self.__events__.listeners[event].slice(0);var result=true;for(var i=0;i<listeners.length;i++){var funcResult=listeners[i].apply(self,args);if(typeof funcResult!=='undefined'&&!funcResult){result=false;}}
return result;}};oop.Class.__conf__={__name__:'Class',__static__:{__events__:[],on:eventFunctions.on,off:eventFunctions.off,trigger:eventFunctions.trigger,__unbound__:{on:function(eventList,callback){return oop.Class.on.call(this,this,eventList,callback);},off:function(eventList,callback){return oop.Class.off.call(this,this,eventList,callback);},trigger:function(event){var args=new Array(arguments.length+1);args[0]=this;for(var i=0;i<arguments.length;i++){args[i+1]=arguments[i];}
return oop.Class.trigger.apply(this,args);},}},__events__:[],on:eventFunctions.on,off:eventFunctions.off,trigger:eventFunctions.trigger,toString:function(self){return'<'+self.__class__.__name__+' object>';}};oop.Class.__name__='Class';oop.Class.__events__={validNames:{},listeners:{}};oop.Class.on=oop.Class.__conf__.__static__.on.bind(oop.Class);oop.Class.off=oop.Class.__conf__.__static__.off.bind(oop.Class);oop.Class.trigger=oop.Class.__conf__.__static__.trigger.bind(oop.Class);oop.Class.prototype.__events__={validNames:{},listeners:{}};oop.Class.prototype.on=function Class__on(eventList,callback){return eventFunctions.on.call(this,this,eventList,callback);};oop.Class.prototype.off=function Class__off(eventList,callback){return eventFunctions.off.call(this,this,eventList,callback);};oop.Class.prototype.trigger=function Class__trigger(event){var args=new Array(arguments.length+1);args[0]=this;for(var i=0;i<arguments.length;i++){args[i+1]=arguments[i];}
return eventFunctions.trigger.apply(this,args);};oop.Class.prototype.toString=function(){return oop.Class.__conf__.toString.call(this,this);};oop.Class.prototype.__str__=oop.Class.prototype.toString;oop.Exception=function(message){return oop.Exception.__conf__.__init__.call(this,this,message);};oop.Exception.__name__='Exception';oop.Exception.__init__='Exception';oop.Exception.prototype=Object.create(Error.prototype);oop.Exception.__conf__={__name__:"Exception",__init__:function(self,message){Error.call(this);this.name=this.__class__.name;this.message=message;this.stack=(new Error()).stack;}};oop.Exception.prototype.toString=function(){return oop.Class.__conf__.toString.call(this,this);};oop.Exception.prototype.__str__=oop.Exception.prototype.toString;return oop;});}));(function(root,factory){if(typeof define==='function'&&define.amd){define('score.ajax',['bluebird','score.init'],factory);}else if(typeof module==='object'&&module.exports){factory(require('bluebird'),require('score.init'));}else{factory(Promise,root.score);}})(this,function(Promise,score){score.extend('ajax',[],function(){var ajax=function(url,options){return new Promise(function(resolve,reject){return ajax.callback(url,options,resolve,reject);});};ajax.Error=function(request,message){if((!request.responseType||typeof request.response=='undefined')&&request.getResponseHeader('Content-Type').trim().substr(0,16)=='application/json'){request.responseJSON=JSON.parse(request.responseText);}
this.message=message;this.request=request;Error.call(this,message);};ajax.Error.prototype=Object.create(Error.prototype);ajax.callback=function(url,options,successCallback,errorCallback){if(typeof options=='function'){errorCallback=successCallback;successCallback=options;options={};}else if(!options){options={};}
var request=new XMLHttpRequest();request.onreadystatechange=function(){if(request.readyState===XMLHttpRequest.DONE){if(request.status==200){var response;if(request.responseType&&typeof request.response!='undefined'){response=request.response;}else{response=request.responseText;if(request.getResponseHeader('Content-Type').trim().substr(0,16)=='application/json'){response=JSON.parse(response);}}
successCallback(response);}else if(errorCallback){errorCallback(new ajax.Error(request,'Unexpected status code '+request.status));}}};request.open(options.method||'GET',url,true);if(!options.crossDomain){request.setRequestHeader('X-Requested-With','XMLHttpRequest');}else{request.withCredentials=true;}
if(options.headers){for(var key in options.headers){request.setRequestHeader(key,options.headers[key]);}}
request.send(options.data||'');};return ajax;});});(function(root,factory){if(typeof define==='function'&&define.amd){define('score.router',['bluebird','score.init','score.oop'],factory);}else if(typeof module==='object'&&module.exports){module.exports=factory(require('bluebird'),require('score.init'),require('score.oop'));}else{factory(Promise,root.score);}}(this,function(Promise,score){score.extend('router',['oop'],function(){var Route=score.oop.Class({__name__:'Route',__init__:function(self,path,loader,params2urlparts,urlparts2params){self.path=path;self._setParamHandlers();self.loader=loader;if(typeof params2urlparts!=='undefined'){self.params2urlparts=params2urlparts;}
if(typeof urlparts2params!=='undefined'){self.urlparts2params=urlparts2params;}},invoke:function(self,parameters){return Promise.resolve().then(function(){return self.loader.call(self,parameters);});},url:function(self,parameters){if(typeof parameters==='undefined'){parameters={};}
if(self.params2urlparts){parameters=self.params2urlparts(parameters);}
return self.parts2url(parameters);},handle:function(self,url){var params=self.extractParams(url);if(params===null){return null;}
if(self.urlparts2params){params=self.urlparts2params(params);if(params===null){return null;}}
return self.invoke(params);},extractParams:function(self,url){var match=self.regex.exec(url);if(!match){return null;}
return self.match2parts(match);},_setParamHandlers:function(self){var parts=[];var path=self.path;while(path.length){var start=path.indexOf('{');var end=path.indexOf('}');if(start<0||end<0){parts.push(path);path='';break;}
if(start!==0){parts.push(path.substring(0,start));}
var name=path.substring(start+1,end);var regex='.*?';var colon=name.indexOf(':');if(colon>0){regex=name.substring(colon+1);name=name.substring(0,colon);}
parts.push({'name':name,'regex':regex});path=path.substring(end+1);}
var regex='';var idx2name={};var idx=1;for(var i=0;i<parts.length;i++){if(typeof parts[i]==='object'){regex+='('+parts[i].regex.replace(/\((?!\?:)/,'(?:')+')';idx2name[idx++]=parts[i].name;}else{regex+=parts[i];}}
regex='^'+regex+'$';self.regex=new RegExp(regex);self.match2parts=function(match){var obj={};for(var idx in idx2name){obj[idx2name[idx]]=match[idx];}
return obj;};self.parts2url=function(params){var url='';for(var i=0;i<parts.length;i++){if(typeof parts[i]==='object'){url+=params[parts[i].name];}else{url+=parts[i];}}
return url;};}});var Router=score.oop.Class({__name__:'Router',__static__:{__version__:'0.3.0'},routes:{},addRoute:function(self,name,path,loader,params2urlparts,urlparts2params){if(name in self.routes){throw new Error('Route "'+name+'" already configured');}
self.routes[name]=new Route(path,loader,params2urlparts,urlparts2params);},load:function(self,url){for(var name in self.routes){var result=self.routes[name].handle(url);if(result){return result;}}
throw new Error('No route could handle the url: '+url);},invoke:function(self,name,parameters){if(!(name in self.routes)){throw new Error('No route called "'+name+'" configured');}
return self.routes[name].invoke(parameters);},url:function(self,name,parameters){if(!(name in self.routes)){throw new Error('No route called "'+name+'" configured');}
return self.routes[name].url(parameters);}});return Router;});}));(function(root,factory){if(typeof define==='function'&&define.amd){define('score.dom',['score.init'],factory);}else if(typeof module==='object'&&module.exports){factory(require('score.init'));}else{factory(root.score);}})(this,function(score){score.extend('dom',[],function(){var i,j,result,tmp,wrapped,re,existing,matches=['matches','webkitMatchesSelector','msMatchesSelector'].filter(function(func){return func in document.documentElement;})[0],dom=function(arg){result=Object.create(dom.proto);if(arg){if(typeof arg=='object'&&Object.getPrototypeOf(arg)==dom.proto){result=arg;}else if(Array.isArray(arg)){result.concat(arg);}else if(/\[object (HTMLCollection|NodeList)\]/.test(Object.prototype.toString.call(arg))){for(i=0;i<arg.length;i++){result.push(arg[i]);}}else if(typeof arg=='object'){result.push(arg);}else{tmp=dom.queryGlobal(arg);for(i=tmp.length-1;i>=0;i--){result.push(tmp[i]);}}}
return result;};dom.proto=Object.create(Array.prototype,{first:{get:function(){if(!this.length){throw new Error('Empty list');}
return score.dom(this[0]);}},eq:{value:function(index){return score.dom(this[index]);}},uniq:{value:function(index){result=Object.create(dom.proto);for(i=0;i<this.length;i++){if(result.indexOf(this[i])<0){result.push(this[i]);}}
return result;}},clone:{value:function(deep){if(typeof deep=='undefined'){deep=true;}
result=Object.create(dom.proto);for(i=0;i<this.length;i++){result.push(this[i].cloneNode(deep));}
return result;}},matches:{value:function(selector){if(!this.length){throw new Error('Empty list');}
for(i=0;i<this.length;i++){if(!dom.testMatch(this[i],selector)){return false;}}
return true;}},empty:{value:function(){return!this.length;}},forEach:{value:function(callback,thisArg){for(var i=0;i<this.length;i++){callback.call(thisArg,score.dom(this[i]),i,this);}
return this;}},children:{value:function(selector){result=Object.create(dom.proto);for(i=0;i<this.length;i++){tmp=this[i].children;for(j=0;j<tmp.length;j++){if(!selector||dom.testMatch(tmp[j],selector)){result.push(tmp[j]);}}}
return result;}},parent:{value:function(selector){result=Object.create(dom.proto);for(i=0;i<this.length;i++){tmp=this[i].parentNode;if(!selector||dom.testMatch(tmp,selector)){result.push(tmp);}}
return result;}},find:{value:function(selector){result=Object.create(dom.proto);for(i=0;i<this.length;i++){tmp=dom.queryLocal(this[i],selector);for(j=0;j<tmp.length;j++){result.push(tmp[j]);}}
return result;}},closest:{value:function(selector){result=Object.create(dom.proto);for(i=0;i<this.length;i++){tmp=this[i].parentNode;while(tmp){if(dom.testMatch(tmp,selector)){result.push(tmp);break;}
tmp=tmp.parentNode;}}
return result;}},text:{value:function(value){if(typeof value=='undefined'){if(!this.length){throw new Error('Empty list');}else if(this.length>1){throw new Error('Attempting Single-Node-Operation on multiple nodes');}
return this[0].textContent;}
for(i=0;i<this.length;i++){this[i].textContent=value;}
return this;}},attr:{value:function(attribute,value){if(typeof value=='undefined'){if(!this.length){throw new Error('Empty list');}else if(this.length>1){throw new Error('Attempting Single-Node-Operation on multiple nodes');}
return this[0].getAttribute(attribute);}
if(value===null){for(i=0;i<this.length;i++){this[i].removeAttribute(attribute);}}else{for(i=0;i<this.length;i++){this[i].setAttribute(attribute,value);}}
return this;}},detach:{value:function(){for(i=0;i<this.length;i++){this[i].parentNode.removeChild(this[i]);}
return this;}},append:{value:function(value){if(!this.length){throw new Error('Empty list');}else if(this.length>1){throw new Error('Attempting Single-Node-Operation on multiple nodes');}
wrapped=score.dom(value);for(i=0;i<wrapped.length;i++){this[0].appendChild(wrapped[i]);}
return this;}},prepend:{value:function(value){if(!this.length){throw new Error('Empty list');}else if(this.length>1){throw new Error('Attempting Single-Node-Operation on multiple nodes');}
if(!this[0].children.length){return this.append(value);}
tmp=this[0].children[0];wrapped=score.dom(value);for(i=0;i<wrapped.length;i++){this[0].insertBefore(wrapped[i],tmp);}
return this;}},hasClass:{value:function(cls){if(!this.length){return false;}
re=new RegExp('(^|\\s+)('+cls+')(\\s+|$)');for(i=0;i<this.length;i++){if(!this[i].className.match(re)){return false;}}
return true;}},addClass:{value:function(cls){re=new RegExp('(^|\\s+)('+cls+')(\\s+|$)');for(i=0;i<this.length;i++){existing=this[i].className;if(!existing){this[i].className=cls;}else if(!existing.match(re)){this[i].className=existing+' '+cls;}}
return this;}},toggleClass:{value:function(cls){re=new RegExp('(^|\\s+)('+cls+')(\\s+|$)');for(i=0;i<this.length;i++){existing=this[i].className;if(!existing){this[i].className=cls;}else if(existing.match(re)){this[i].className=existing.replace(re,'$3');}else{this[i].className=existing+' '+cls;}}
return this;}},removeClass:{value:function(cls){re=new RegExp('(^|\\s+)('+cls+')(\\s+|$)');for(i=0;i<this.length;i++){existing=this[i].className;if(existing){this[i].className=existing.replace(re,'$3');}}
return this;}},on:{value:function(event,callback){for(i=0;i<this.length;i++){this[i].addEventListener(event,callback);}
return this;}},off:{value:function(event,callback){for(i=0;i<this.length;i++){this[i].removeEventListener(event,callback);}
return this;}}});dom.fromString=function(html){var div=document.createElement('div');div.insertAdjacentHTML('afterbegin',html);return score.dom(div.children).detach();};dom.queryGlobal=document.querySelectorAll.bind(document);dom.queryLocal=function(root,selector){return root.querySelectorAll(selector);};dom.testMatch=function(node,selector){return node[matches](selector);};dom.__version__='0.0.8';return dom;});});(function(root,factory){if(typeof define==='function'&&define.amd){define('score.dom.theater',['bluebird','score.init','score.dom','score.oop'],factory);}else if(typeof module==='object'&&module.exports){module.exports=factory(require('bluebird'),require('score.init'),require('score.dom'),require('score.oop'));}else{factory(Promise,root.score);}})(this,function(Promise,score){score.extend('dom.theater',['dom','oop'],function(){var hash=function(value,visited){if(typeof visited==='undefined'){visited=[];}
var index=visited.indexOf(value);if(index>=0){return'__visited__['+index+']';}
visited.push(value);if(value instanceof Array){value=value.slice(0);value.unshift('__list_hash__');}else if(typeof value==='object'){var keys=[];var values=[];for(var k in value){if(value.hasOwnProperty(k)){keys.push(k);}}
keys.sort();for(var i=0;i<keys.length;i++){values.push(hash(value[keys[i]],visited));}
value=['__dict_hash__',keys,values];}
if(arguments[1]){return value;}
return JSON.stringify(value);};var Cancel=function(){};Cancel.prototype=Object.create(Error.prototype);Cancel.prototype.constructor=Cancel;var theater={__version__:"0.0.3",Cancel:new Cancel(),Stage:score.oop.Class({__name__:'TheaterStage',__init__:function(self,node){self.node=score.dom(node);self.node.addClass('score-theater-stage');self.activeScene=null;self.scenes={};},_activate:function(self,scene){if(scene===self.activeScene){return;}
var promise=Promise.resolve();if(typeof promise.cancellable==='function'){promise=promise.cancellable();}
if(self.activeScene!==null){promise=promise.then(function(){if(!self.activeScene.trigger('deactivate')){throw new Promise.CancellationError();}
return Promise.resolve().then(function(){return self.activeScene._deactivate();}).catch(Cancel,function(){throw new Promise.CancellationError();}).then(function(){if(!self.activeScene){return;}
if(self.activeScene.node){self.activeScene.node.removeClass('score-theater-scene--active');}
if(self.node){self.node.removeClass('score-theater-stage--'+self.activeScene.name);}
self.activeScene=null;});});}
return promise.then(function(){self.activeScene=scene;if(self.node){self.node.addClass('score-theater-stage--'+self.activeScene.name);}
if(self.activeScene.node){self.activeScene.node.addClass('score-theater-scene--active');}
return Promise.resolve(self.activeScene._activate()).then(function(){self.activeScene.trigger('activate');});});},_register:function(self,scene){if(scene.name in self.scenes){throw new Error('Scene with the name '+scene.name+' already registered!');}
self.scenes[scene.name]=scene;},show:function(self,scene){if(typeof scene==='string'){if(typeof self.scenes[scene]==='undefined'){throw new Error('Scene '+scene+' does not exist!');}
scene=self.scenes[scene];}else if(!(scene instanceof theater.Scene)){throw new Error('Argument must be a scene, or the name of a scene!');}
var args=[];for(var i=2;i<arguments.length;i++){args.push(arguments[i]);}
return scene.show.apply(scene,args);}}),Scene:score.oop.Class({__name__:'Scene',__events__:['init','load','activate','deactivate'],__init__:function(self,stage,name,node){if(!(stage instanceof theater.Stage)){throw new Error('First argument must be a theater.Stage object!');}
if(typeof name!=='string'){throw new Error('Name not a string!');}
if(node){self.node=score.dom(node);self.node.addClass('score-theater-scene');}
self.stage=stage;self.name=name;self.initialized=false;self.stage._register(self);},show:function(self){var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
var promise=Promise.resolve();if(!self.initialized){promise=promise.then(function(){return Promise.resolve(self._init()).then(function(){self.initialized=true;self.trigger('init');});});}
if(hash(args)!==hash(self.args)){promise=promise.then(function(){return Promise.resolve(self._load.apply(self,args)).then(function(){self.trigger('load',args);});});}
return promise.then(function(){self.args=args;return self.stage._activate(self);});},_init:function(){},_load:function(){},_deactivate:function(){},_activate:function(){}})};return theater;});});
/*!
 * @license
 * lodash <https://lodash.com/>
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */;(function(){var undefined;var VERSION='4.12.0';var LARGE_ARRAY_SIZE=200;var FUNC_ERROR_TEXT='Expected a function';var HASH_UNDEFINED='__lodash_hash_undefined__';var PLACEHOLDER='__lodash_placeholder__';var BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512;var UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2;var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION='...';var HOT_COUNT=150,HOT_SPAN=16;var LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3;var INFINITY=1 / 0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e+308,NAN=0 / 0;var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;var argsTag='[object Arguments]',arrayTag='[object Array]',boolTag='[object Boolean]',dateTag='[object Date]',errorTag='[object Error]',funcTag='[object Function]',genTag='[object GeneratorFunction]',mapTag='[object Map]',numberTag='[object Number]',objectTag='[object Object]',promiseTag='[object Promise]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',symbolTag='[object Symbol]',weakMapTag='[object WeakMap]',weakSetTag='[object WeakSet]';var arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]';var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);var reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/;var reBasicWord=/[a-zA-Z0-9]+/g;var reEscapeChar=/\\(\\)?/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reHasHexPrefix=/^0x/i;var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;var reIsBinary=/^0b[01]+$/i;var reIsHostCtor=/^\[object .+?Constructor\]$/;var reIsOctal=/^0o[0-7]+$/i;var reIsUint=/^(?:0|[1-9]\d*)$/;var reLatin1=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;var reNoMatch=/($^)/;var reUnescapedString=/['\n\r\u2028\u2029\\]/g;var rsAstralRange='\\ud800-\\udfff',rsComboMarksRange='\\u0300-\\u036f\\ufe20-\\ufe23',rsComboSymbolsRange='\\u20d0-\\u20f0',rsDingbatRange='\\u2700-\\u27bf',rsLowerRange='a-z\\xdf-\\xf6\\xf8-\\xff',rsMathOpRange='\\xac\\xb1\\xd7\\xf7',rsNonCharRange='\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',rsPunctuationRange='\\u2000-\\u206f',rsSpaceRange=' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',rsUpperRange='A-Z\\xc0-\\xd6\\xd8-\\xde',rsVarRange='\\ufe0e\\ufe0f',rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange;var rsApos="['\u2019]",rsAstral='['+rsAstralRange+']',rsBreak='['+rsBreakRange+']',rsCombo='['+rsComboMarksRange+rsComboSymbolsRange+']',rsDigits='\\d+',rsDingbat='['+rsDingbatRange+']',rsLower='['+rsLowerRange+']',rsMisc='[^'+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+']',rsFitz='\\ud83c[\\udffb-\\udfff]',rsModifier='(?:'+rsCombo+'|'+rsFitz+')',rsNonAstral='[^'+rsAstralRange+']',rsRegional='(?:\\ud83c[\\udde6-\\uddff]){2}',rsSurrPair='[\\ud800-\\udbff][\\udc00-\\udfff]',rsUpper='['+rsUpperRange+']',rsZWJ='\\u200d';var rsLowerMisc='(?:'+rsLower+'|'+rsMisc+')',rsUpperMisc='(?:'+rsUpper+'|'+rsMisc+')',rsOptLowerContr='(?:'+rsApos+'(?:d|ll|m|re|s|t|ve))?',rsOptUpperContr='(?:'+rsApos+'(?:D|LL|M|RE|S|T|VE))?',reOptMod=rsModifier+'?',rsOptVar='['+rsVarRange+']?',rsOptJoin='(?:'+rsZWJ+'(?:'+[rsNonAstral,rsRegional,rsSurrPair].join('|')+')'+rsOptVar+reOptMod+')*',rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji='(?:'+[rsDingbat,rsRegional,rsSurrPair].join('|')+')'+rsSeq,rsSymbol='(?:'+[rsNonAstral+rsCombo+'?',rsCombo,rsRegional,rsSurrPair,rsAstral].join('|')+')';var reApos=RegExp(rsApos,'g');var reComboMark=RegExp(rsCombo,'g');var reComplexSymbol=RegExp(rsFitz+'(?='+rsFitz+')|'+rsSymbol+rsSeq,'g');var reComplexWord=RegExp([rsUpper+'?'+rsLower+'+'+rsOptLowerContr+'(?='+[rsBreak,rsUpper,'$'].join('|')+')',rsUpperMisc+'+'+rsOptUpperContr+'(?='+[rsBreak,rsUpper+rsLowerMisc,'$'].join('|')+')',rsUpper+'?'+rsLowerMisc+'+'+rsOptLowerContr,rsUpper+'+'+rsOptUpperContr,rsDigits,rsEmoji].join('|'),'g');var reHasComplexSymbol=RegExp('['+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+']');var reHasComplexWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;var contextProps=['Array','Buffer','DataView','Date','Error','Float32Array','Float64Array','Function','Int8Array','Int16Array','Int32Array','Map','Math','Object','Promise','Reflect','RegExp','Set','String','Symbol','TypeError','Uint8Array','Uint8ClampedArray','Uint16Array','Uint32Array','WeakMap','_','clearTimeout','isFinite','parseInt','setTimeout'];var templateCounter=-1;var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=false;var deburredLetters={'\xc0':'A','\xc1':'A','\xc2':'A','\xc3':'A','\xc4':'A','\xc5':'A','\xe0':'a','\xe1':'a','\xe2':'a','\xe3':'a','\xe4':'a','\xe5':'a','\xc7':'C','\xe7':'c','\xd0':'D','\xf0':'d','\xc8':'E','\xc9':'E','\xca':'E','\xcb':'E','\xe8':'e','\xe9':'e','\xea':'e','\xeb':'e','\xcC':'I','\xcd':'I','\xce':'I','\xcf':'I','\xeC':'i','\xed':'i','\xee':'i','\xef':'i','\xd1':'N','\xf1':'n','\xd2':'O','\xd3':'O','\xd4':'O','\xd5':'O','\xd6':'O','\xd8':'O','\xf2':'o','\xf3':'o','\xf4':'o','\xf5':'o','\xf6':'o','\xf8':'o','\xd9':'U','\xda':'U','\xdb':'U','\xdc':'U','\xf9':'u','\xfa':'u','\xfb':'u','\xfc':'u','\xdd':'Y','\xfd':'y','\xff':'y','\xc6':'Ae','\xe6':'ae','\xde':'Th','\xfe':'th','\xdf':'ss'};var htmlEscapes={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','`':'&#96;'};var htmlUnescapes={'&amp;':'&','&lt;':'<','&gt;':'>','&quot;':'"','&#39;':"'",'&#96;':'`'};var objectTypes={'function':true,'object':true};var stringEscapes={'\\':'\\',"'":"'",'\n':'n','\r':'r','\u2028':'u2028','\u2029':'u2029'};var freeParseFloat=parseFloat,freeParseInt=parseInt;var freeExports=(objectTypes[typeof exports]&&exports&&!exports.nodeType)?exports:undefined;var freeModule=(objectTypes[typeof module]&&module&&!module.nodeType)?module:undefined;var moduleExports=(freeModule&&freeModule.exports===freeExports)?freeExports:undefined;var freeGlobal=checkGlobal(freeExports&&freeModule&&typeof global=='object'&&global);var freeSelf=checkGlobal(objectTypes[typeof self]&&self);var freeWindow=checkGlobal(objectTypes[typeof window]&&window);var thisGlobal=checkGlobal(objectTypes[typeof this]&&this);var root=freeGlobal||((freeWindow!==(thisGlobal&&thisGlobal.window))&&freeWindow)||freeSelf||thisGlobal||Function('return this')();function addMapEntry(map,pair){map.set(pair[0],pair[1]);return map;}
function addSetEntry(set,value){set.add(value);return set;}
function apply(func,thisArg,args){var length=args.length;switch(length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2]);}
return func.apply(thisArg,args);}
function arrayAggregator(array,setter,iteratee,accumulator){var index=-1,length=array.length;while(++index<length){var value=array[index];setter(accumulator,value,iteratee(value),array);}
return accumulator;}
function arrayEach(array,iteratee){var index=-1,length=array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break;}}
return array;}
function arrayEachRight(array,iteratee){var length=array.length;while(length--){if(iteratee(array[length],length,array)===false){break;}}
return array;}
function arrayEvery(array,predicate){var index=-1,length=array.length;while(++index<length){if(!predicate(array[index],index,array)){return false;}}
return true;}
function arrayFilter(array,predicate){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[resIndex++]=value;}}
return result;}
function arrayIncludes(array,value){return!!array.length&&baseIndexOf(array,value,0)>-1;}
function arrayIncludesWith(array,value,comparator){var index=-1,length=array.length;while(++index<length){if(comparator(value,array[index])){return true;}}
return false;}
function arrayMap(array,iteratee){var index=-1,length=array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array);}
return result;}
function arrayPush(array,values){var index=-1,length=values.length,offset=array.length;while(++index<length){array[offset+index]=values[index];}
return array;}
function arrayReduce(array,iteratee,accumulator,initAccum){var index=-1,length=array.length;if(initAccum&&length){accumulator=array[++index];}
while(++index<length){accumulator=iteratee(accumulator,array[index],index,array);}
return accumulator;}
function arrayReduceRight(array,iteratee,accumulator,initAccum){var length=array.length;if(initAccum&&length){accumulator=array[--length];}
while(length--){accumulator=iteratee(accumulator,array[length],length,array);}
return accumulator;}
function arraySome(array,predicate){var index=-1,length=array.length;while(++index<length){if(predicate(array[index],index,array)){return true;}}
return false;}
function baseFind(collection,predicate,eachFunc,retKey){var result;eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection)){result=retKey?key:value;return false;}});return result;}
function baseFindIndex(array,predicate,fromRight){var length=array.length,index=fromRight?length:-1;while((fromRight?index--:++index<length)){if(predicate(array[index],index,array)){return index;}}
return-1;}
function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex);}
var index=fromIndex-1,length=array.length;while(++index<length){if(array[index]===value){return index;}}
return-1;}
function baseIndexOfWith(array,value,fromIndex,comparator){var index=fromIndex-1,length=array.length;while(++index<length){if(comparator(array[index],value)){return index;}}
return-1;}
function baseMean(array,iteratee){var length=array?array.length:0;return length?(baseSum(array,iteratee)/ length):NAN;}
function baseReduce(collection,iteratee,accumulator,initAccum,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initAccum?(initAccum=false,value):iteratee(accumulator,value,index,collection);});return accumulator;}
function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value;}
return array;}
function baseSum(array,iteratee){var result,index=-1,length=array.length;while(++index<length){var current=iteratee(array[index]);if(current!==undefined){result=result===undefined?current:(result+current);}}
return result;}
function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index);}
return result;}
function baseToPairs(object,props){return arrayMap(props,function(key){return[key,object[key]];});}
function baseUnary(func){return function(value){return func(value);};}
function baseValues(object,props){return arrayMap(props,function(key){return object[key];});}
function cacheHas(cache,key){return cache.has(key);}
function charsStartIndex(strSymbols,chrSymbols){var index=-1,length=strSymbols.length;while(++index<length&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}
return index;}
function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}
return index;}
function checkGlobal(value){return(value&&value.Object===Object)?value:null;}
function countHolders(array,placeholder){var length=array.length,result=0;while(length--){if(array[length]===placeholder){result++;}}
return result;}
function deburrLetter(letter){return deburredLetters[letter];}
function escapeHtmlChar(chr){return htmlEscapes[chr];}
function escapeStringChar(chr){return'\\'+stringEscapes[chr];}
function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromIndex+(fromRight?0:-1);while((fromRight?index--:++index<length)){var other=array[index];if(other!==other){return index;}}
return-1;}
function isHostObject(value){var result=false;if(value!=null&&typeof value.toString!='function'){try{result=!!(value+'');}catch(e){}}
return result;}
function iteratorToArray(iterator){var data,result=[];while(!(data=iterator.next()).done){result.push(data.value);}
return result;}
function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value];});return result;}
function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(value===placeholder||value===PLACEHOLDER){array[index]=PLACEHOLDER;result[resIndex++]=index;}}
return result;}
function setToArray(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=value;});return result;}
function setToPairs(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=[value,value];});return result;}
function stringSize(string){if(!(string&&reHasComplexSymbol.test(string))){return string.length;}
var result=reComplexSymbol.lastIndex=0;while(reComplexSymbol.test(string)){result++;}
return result;}
function stringToArray(string){return string.match(reComplexSymbol);}
function unescapeHtmlChar(chr){return htmlUnescapes[chr];}
function runInContext(context){context=context?_.defaults({},context,_.pick(root,contextProps)):root;var Date=context.Date,Error=context.Error,Math=context.Math,RegExp=context.RegExp,TypeError=context.TypeError;var arrayProto=context.Array.prototype,objectProto=context.Object.prototype,stringProto=context.String.prototype;var funcToString=context.Function.prototype.toString;var hasOwnProperty=objectProto.hasOwnProperty;var idCounter=0;var objectCtorString=funcToString.call(Object);var objectToString=objectProto.toString;var oldDash=root._;var reIsNative=RegExp('^'+
funcToString.call(hasOwnProperty).replace(reRegExpChar,'\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$');var Buffer=moduleExports?context.Buffer:undefined,Reflect=context.Reflect,Symbol=context.Symbol,Uint8Array=context.Uint8Array,clearTimeout=context.clearTimeout,enumerate=Reflect?Reflect.enumerate:undefined,getOwnPropertySymbols=Object.getOwnPropertySymbols,iteratorSymbol=typeof(iteratorSymbol=Symbol&&Symbol.iterator)=='symbol'?iteratorSymbol:undefined,objectCreate=Object.create,propertyIsEnumerable=objectProto.propertyIsEnumerable,setTimeout=context.setTimeout,splice=arrayProto.splice;var nativeCeil=Math.ceil,nativeFloor=Math.floor,nativeGetPrototype=Object.getPrototypeOf,nativeIsFinite=context.isFinite,nativeJoin=arrayProto.join,nativeKeys=Object.keys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random,nativeReplace=stringProto.replace,nativeReverse=arrayProto.reverse,nativeSplit=stringProto.split;var DataView=getNative(context,'DataView'),Map=getNative(context,'Map'),Promise=getNative(context,'Promise'),Set=getNative(context,'Set'),WeakMap=getNative(context,'WeakMap'),nativeCreate=getNative(Object,'create');var metaMap=WeakMap&&new WeakMap;var nonEnumShadows=!propertyIsEnumerable.call({'valueOf':1},'valueOf');var realNames={};var dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap);var symbolProto=Symbol?Symbol.prototype:undefined,symbolValueOf=symbolProto?symbolProto.valueOf:undefined,symbolToString=symbolProto?symbolProto.toString:undefined;function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper){return value;}
if(hasOwnProperty.call(value,'__wrapped__')){return wrapperClone(value);}}
return new LodashWrapper(value);}
function baseLodash(){}
function LodashWrapper(value,chainAll){this.__wrapped__=value;this.__actions__=[];this.__chain__=!!chainAll;this.__index__=0;this.__values__=undefined;}
lodash.templateSettings={'escape':reEscape,'evaluate':reEvaluate,'interpolate':reInterpolate,'variable':'','imports':{'_':lodash}};lodash.prototype=baseLodash.prototype;lodash.prototype.constructor=lodash;LodashWrapper.prototype=baseCreate(baseLodash.prototype);LodashWrapper.prototype.constructor=LodashWrapper;function LazyWrapper(value){this.__wrapped__=value;this.__actions__=[];this.__dir__=1;this.__filtered__=false;this.__iteratees__=[];this.__takeCount__=MAX_ARRAY_LENGTH;this.__views__=[];}
function lazyClone(){var result=new LazyWrapper(this.__wrapped__);result.__actions__=copyArray(this.__actions__);result.__dir__=this.__dir__;result.__filtered__=this.__filtered__;result.__iteratees__=copyArray(this.__iteratees__);result.__takeCount__=this.__takeCount__;result.__views__=copyArray(this.__views__);return result;}
function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1;result.__filtered__=true;}else{result=this.clone();result.__dir__*=-1;}
return result;}
function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:(start-1),iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||arrLength<LARGE_ARRAY_SIZE||(arrLength==length&&takeCount==length)){return baseWrapperValue(array,this.__actions__);}
var result=[];outer:while(length--&&resIndex<takeCount){index+=dir;var iterIndex=-1,value=array[index];while(++iterIndex<iterLength){var data=iteratees[iterIndex],iteratee=data.iteratee,type=data.type,computed=iteratee(value);if(type==LAZY_MAP_FLAG){value=computed;}else if(!computed){if(type==LAZY_FILTER_FLAG){continue outer;}else{break outer;}}}
result[resIndex++]=value;}
return result;}
LazyWrapper.prototype=baseCreate(baseLodash.prototype);LazyWrapper.prototype.constructor=LazyWrapper;function Hash(entries){var index=-1,length=entries?entries.length:0;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}
function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{};}
function hashDelete(key){return this.has(key)&&delete this.__data__[key];}
function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?undefined:result;}
return hasOwnProperty.call(data,key)?data[key]:undefined;}
function hashHas(key){var data=this.__data__;return nativeCreate?data[key]!==undefined:hasOwnProperty.call(data,key);}
function hashSet(key,value){var data=this.__data__;data[key]=(nativeCreate&&value===undefined)?HASH_UNDEFINED:value;return this;}
Hash.prototype.clear=hashClear;Hash.prototype['delete']=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;function ListCache(entries){var index=-1,length=entries?entries.length:0;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}
function listCacheClear(){this.__data__=[];}
function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){return false;}
var lastIndex=data.length-1;if(index==lastIndex){data.pop();}else{splice.call(data,index,1);}
return true;}
function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?undefined:data[index][1];}
function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1;}
function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){data.push([key,value]);}else{data[index][1]=value;}
return this;}
ListCache.prototype.clear=listCacheClear;ListCache.prototype['delete']=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;function MapCache(entries){var index=-1,length=entries?entries.length:0;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}
function mapCacheClear(){this.__data__={'hash':new Hash,'map':new(Map||ListCache),'string':new Hash};}
function mapCacheDelete(key){return getMapData(this,key)['delete'](key);}
function mapCacheGet(key){return getMapData(this,key).get(key);}
function mapCacheHas(key){return getMapData(this,key).has(key);}
function mapCacheSet(key,value){getMapData(this,key).set(key,value);return this;}
MapCache.prototype.clear=mapCacheClear;MapCache.prototype['delete']=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;function SetCache(values){var index=-1,length=values?values.length:0;this.__data__=new MapCache;while(++index<length){this.add(values[index]);}}
function setCacheAdd(value){this.__data__.set(value,HASH_UNDEFINED);return this;}
function setCacheHas(value){return this.__data__.has(value);}
SetCache.prototype.add=SetCache.prototype.push=setCacheAdd;SetCache.prototype.has=setCacheHas;function Stack(entries){this.__data__=new ListCache(entries);}
function stackClear(){this.__data__=new ListCache;}
function stackDelete(key){return this.__data__['delete'](key);}
function stackGet(key){return this.__data__.get(key);}
function stackHas(key){return this.__data__.has(key);}
function stackSet(key,value){var cache=this.__data__;if(cache instanceof ListCache&&cache.__data__.length==LARGE_ARRAY_SIZE){cache=this.__data__=new MapCache(cache.__data__);}
cache.set(key,value);return this;}
Stack.prototype.clear=stackClear;Stack.prototype['delete']=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;function assignInDefaults(objValue,srcValue,key,object){if(objValue===undefined||(eq(objValue,objectProto[key])&&!hasOwnProperty.call(object,key))){return srcValue;}
return objValue;}
function assignMergeValue(object,key,value){if((value!==undefined&&!eq(object[key],value))||(typeof key=='number'&&value===undefined&&!(key in object))){object[key]=value;}}
function assignValue(object,key,value){var objValue=object[key];if(!(hasOwnProperty.call(object,key)&&eq(objValue,value))||(value===undefined&&!(key in object))){object[key]=value;}}
function assocIndexOf(array,key){var length=array.length;while(length--){if(eq(array[length][0],key)){return length;}}
return-1;}
function baseAggregator(collection,setter,iteratee,accumulator){baseEach(collection,function(value,key,collection){setter(accumulator,value,iteratee(value),collection);});return accumulator;}
function baseAssign(object,source){return object&&copyObject(source,keys(source),object);}
function baseAt(object,paths){var index=-1,isNil=object==null,length=paths.length,result=Array(length);while(++index<length){result[index]=isNil?undefined:get(object,paths[index]);}
return result;}
function baseClamp(number,lower,upper){if(number===number){if(upper!==undefined){number=number<=upper?number:upper;}
if(lower!==undefined){number=number>=lower?number:lower;}}
return number;}
function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer){result=object?customizer(value,key,object,stack):customizer(value);}
if(result!==undefined){return result;}
if(!isObject(value)){return value;}
var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result);}}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value)){return cloneBuffer(value,isDeep);}
if(tag==objectTag||tag==argsTag||(isFunc&&!object)){if(isHostObject(value)){return object?value:{};}
result=initCloneObject(isFunc?{}:value);if(!isDeep){return copySymbols(value,baseAssign(result,value));}}else{if(!cloneableTags[tag]){return object?value:{};}
result=initCloneByTag(value,tag,baseClone,isDeep);}}
stack||(stack=new Stack);var stacked=stack.get(value);if(stacked){return stacked;}
stack.set(value,result);if(!isArr){var props=isFull?getAllKeys(value):keys(value);}
arrayEach(props||value,function(subValue,key){if(props){key=subValue;subValue=value[key];}
assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack));});return result;}
function baseConforms(source){var props=keys(source),length=props.length;return function(object){if(object==null){return!length;}
var index=length;while(index--){var key=props[index],predicate=source[key],value=object[key];if((value===undefined&&!(key in Object(object)))||!predicate(value)){return false;}}
return true;};}
function baseCreate(proto){return isObject(proto)?objectCreate(proto):{};}
function baseDelay(func,wait,args){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
return setTimeout(function(){func.apply(undefined,args);},wait);}
function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=true,length=array.length,result=[],valuesLength=values.length;if(!length){return result;}
if(iteratee){values=arrayMap(values,baseUnary(iteratee));}
if(comparator){includes=arrayIncludesWith;isCommon=false;}
else if(values.length>=LARGE_ARRAY_SIZE){includes=cacheHas;isCommon=false;values=new SetCache(values);}
outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;value=(comparator||value!==0)?value:0;if(isCommon&&computed===computed){var valuesIndex=valuesLength;while(valuesIndex--){if(values[valuesIndex]===computed){continue outer;}}
result.push(value);}
else if(!includes(values,computed,comparator)){result.push(value);}}
return result;}
var baseEach=createBaseEach(baseForOwn);var baseEachRight=createBaseEach(baseForOwnRight,true);function baseEvery(collection,predicate){var result=true;baseEach(collection,function(value,index,collection){result=!!predicate(value,index,collection);return result;});return result;}
function baseExtremum(array,iteratee,comparator){var index=-1,length=array.length;while(++index<length){var value=array[index],current=iteratee(value);if(current!=null&&(computed===undefined?(current===current&&!isSymbol(current)):comparator(current,computed))){var computed=current,result=value;}}
return result;}
function baseFill(array,value,start,end){var length=array.length;start=toInteger(start);if(start<0){start=-start>length?0:(length+start);}
end=(end===undefined||end>length)?length:toInteger(end);if(end<0){end+=length;}
end=start>end?0:toLength(end);while(start<end){array[start++]=value;}
return array;}
function baseFilter(collection,predicate){var result=[];baseEach(collection,function(value,index,collection){if(predicate(value,index,collection)){result.push(value);}});return result;}
function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;predicate||(predicate=isFlattenable);result||(result=[]);while(++index<length){var value=array[index];if(depth>0&&predicate(value)){if(depth>1){baseFlatten(value,depth-1,predicate,isStrict,result);}else{arrayPush(result,value);}}else if(!isStrict){result[result.length]=value;}}
return result;}
var baseFor=createBaseFor();var baseForRight=createBaseFor(true);function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}
function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys);}
function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key]);});}
function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);var index=0,length=path.length;while(object!=null&&index<length){object=object[toKey(path[index++])];}
return(index&&index==length)?object:undefined;}
function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object));}
function baseGt(value,other){return value>other;}
function baseHas(object,key){return hasOwnProperty.call(object,key)||(typeof object=='object'&&key in object&&getPrototype(object)===null);}
function baseHasIn(object,key){return key in Object(object);}
function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number<nativeMax(start,end);}
function baseIntersection(arrays,iteratee,comparator){var includes=comparator?arrayIncludesWith:arrayIncludes,length=arrays[0].length,othLength=arrays.length,othIndex=othLength,caches=Array(othLength),maxLength=Infinity,result=[];while(othIndex--){var array=arrays[othIndex];if(othIndex&&iteratee){array=arrayMap(array,baseUnary(iteratee));}
maxLength=nativeMin(array.length,maxLength);caches[othIndex]=!comparator&&(iteratee||(length>=120&&array.length>=120))?new SetCache(othIndex&&array):undefined;}
array=arrays[0];var index=-1,seen=caches[0];outer:while(++index<length&&result.length<maxLength){var value=array[index],computed=iteratee?iteratee(value):value;value=(comparator||value!==0)?value:0;if(!(seen?cacheHas(seen,computed):includes(result,computed,comparator))){othIndex=othLength;while(--othIndex){var cache=caches[othIndex];if(!(cache?cacheHas(cache,computed):includes(arrays[othIndex],computed,comparator))){continue outer;}}
if(seen){seen.push(computed);}
result.push(value);}}
return result;}
function baseInverter(object,setter,iteratee,accumulator){baseForOwn(object,function(value,key,object){setter(accumulator,iteratee(value),key,object);});return accumulator;}
function baseInvoke(object,path,args){if(!isKey(path,object)){path=castPath(path);object=parent(object,path);path=last(path);}
var func=object==null?object:object[toKey(path)];return func==null?undefined:apply(func,object,args);}
function baseIsEqual(value,other,customizer,bitmask,stack){if(value===other){return true;}
if(value==null||other==null||(!isObject(value)&&!isObjectLike(other))){return value!==value&&other!==other;}
return baseIsEqualDeep(value,other,baseIsEqual,customizer,bitmask,stack);}
function baseIsEqualDeep(object,other,equalFunc,customizer,bitmask,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;if(!objIsArr){objTag=getTag(object);objTag=objTag==argsTag?objectTag:objTag;}
if(!othIsArr){othTag=getTag(other);othTag=othTag==argsTag?objectTag:othTag;}
var objIsObj=objTag==objectTag&&!isHostObject(object),othIsObj=othTag==objectTag&&!isHostObject(other),isSameTag=objTag==othTag;if(isSameTag&&!objIsObj){stack||(stack=new Stack);return(objIsArr||isTypedArray(object))?equalArrays(object,other,equalFunc,customizer,bitmask,stack):equalByTag(object,other,objTag,equalFunc,customizer,bitmask,stack);}
if(!(bitmask&PARTIAL_COMPARE_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,'__wrapped__'),othIsWrapped=othIsObj&&hasOwnProperty.call(other,'__wrapped__');if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;stack||(stack=new Stack);return equalFunc(objUnwrapped,othUnwrapped,customizer,bitmask,stack);}}
if(!isSameTag){return false;}
stack||(stack=new Stack);return equalObjects(object,other,equalFunc,customizer,bitmask,stack);}
function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(object==null){return!length;}
object=Object(object);while(index--){var data=matchData[index];if((noCustomizer&&data[2])?data[1]!==object[data[0]]:!(data[0]in object)){return false;}}
while(++index<length){data=matchData[index];var key=data[0],objValue=object[key],srcValue=data[1];if(noCustomizer&&data[2]){if(objValue===undefined&&!(key in object)){return false;}}else{var stack=new Stack;if(customizer){var result=customizer(objValue,srcValue,key,object,source,stack);}
if(!(result===undefined?baseIsEqual(srcValue,objValue,customizer,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG,stack):result)){return false;}}}
return true;}
function baseIteratee(value){if(typeof value=='function'){return value;}
if(value==null){return identity;}
if(typeof value=='object'){return isArray(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value);}
return property(value);}
function baseKeys(object){return nativeKeys(Object(object));}
function baseKeysIn(object){object=object==null?object:Object(object);var result=[];for(var key in object){result.push(key);}
return result;}
if(enumerate&&!propertyIsEnumerable.call({'valueOf':1},'valueOf')){baseKeysIn=function(object){return iteratorToArray(enumerate(object));};}
function baseLt(value,other){return value<other;}
function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection);});return result;}
function baseMatches(source){var matchData=getMatchData(source);if(matchData.length==1&&matchData[0][2]){return matchesStrictComparable(matchData[0][0],matchData[0][1]);}
return function(object){return object===source||baseIsMatch(object,source,matchData);};}
function baseMatchesProperty(path,srcValue){if(isKey(path)&&isStrictComparable(srcValue)){return matchesStrictComparable(toKey(path),srcValue);}
return function(object){var objValue=get(object,path);return(objValue===undefined&&objValue===srcValue)?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG);};}
function baseMerge(object,source,srcIndex,customizer,stack){if(object===source){return;}
if(!(isArray(source)||isTypedArray(source))){var props=keysIn(source);}
arrayEach(props||source,function(srcValue,key){if(props){key=srcValue;srcValue=source[key];}
if(isObject(srcValue)){stack||(stack=new Stack);baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);}
else{var newValue=customizer?customizer(object[key],srcValue,(key+''),object,source,stack):undefined;if(newValue===undefined){newValue=srcValue;}
assignMergeValue(object,key,newValue);}});}
function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked){assignMergeValue(object,key,stacked);return;}
var newValue=customizer?customizer(objValue,srcValue,(key+''),object,source,stack):undefined;var isCommon=newValue===undefined;if(isCommon){newValue=srcValue;if(isArray(srcValue)||isTypedArray(srcValue)){if(isArray(objValue)){newValue=objValue;}
else if(isArrayLikeObject(objValue)){newValue=copyArray(objValue);}
else{isCommon=false;newValue=baseClone(srcValue,true);}}
else if(isPlainObject(srcValue)||isArguments(srcValue)){if(isArguments(objValue)){newValue=toPlainObject(objValue);}
else if(!isObject(objValue)||(srcIndex&&isFunction(objValue))){isCommon=false;newValue=baseClone(srcValue,true);}
else{newValue=objValue;}}
else{isCommon=false;}}
stack.set(srcValue,newValue);if(isCommon){mergeFunc(newValue,srcValue,srcIndex,customizer,stack);}
stack['delete'](srcValue);assignMergeValue(object,key,newValue);}
function baseNth(array,n){var length=array.length;if(!length){return;}
n+=n<0?length:0;return isIndex(n,length)?array[n]:undefined;}
function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value);});return{'criteria':criteria,'index':++index,'value':value};});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders);});}
function basePick(object,props){object=Object(object);return arrayReduce(props,function(result,key){if(key in object){result[key]=object[key];}
return result;},{});}
function basePickBy(object,predicate){var index=-1,props=getAllKeysIn(object),length=props.length,result={};while(++index<length){var key=props[index],value=object[key];if(predicate(value,key)){result[key]=value;}}
return result;}
function baseProperty(key){return function(object){return object==null?undefined:object[key];};}
function basePropertyDeep(path){return function(object){return baseGet(object,path);};}
function basePullAll(array,values,iteratee,comparator){var indexOf=comparator?baseIndexOfWith:baseIndexOf,index=-1,length=values.length,seen=array;if(iteratee){seen=arrayMap(array,baseUnary(iteratee));}
while(++index<length){var fromIndex=0,value=values[index],computed=iteratee?iteratee(value):value;while((fromIndex=indexOf(seen,computed,fromIndex,comparator))>-1){if(seen!==array){splice.call(seen,fromIndex,1);}
splice.call(array,fromIndex,1);}}
return array;}
function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index)){splice.call(array,index,1);}
else if(!isKey(index,array)){var path=castPath(index),object=parent(array,path);if(object!=null){delete object[toKey(last(path))];}}
else{delete array[toKey(index)];}}}
return array;}
function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1));}
function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step;}
return result;}
function baseRepeat(string,n){var result='';if(!string||n<1||n>MAX_SAFE_INTEGER){return result;}
do{if(n%2){result+=string;}
n=nativeFloor(n / 2);if(n){string+=string;}}while(n);return result;}
function baseSet(object,path,value,customizer){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++index<length){var key=toKey(path[index]);if(isObject(nested)){var newValue=value;if(index!=lastIndex){var objValue=nested[key];newValue=customizer?customizer(objValue,key,nested):undefined;if(newValue===undefined){newValue=objValue==null?(isIndex(path[index+1])?[]:{}):objValue;}}
assignValue(nested,key,newValue);}
nested=nested[key];}
return object;}
var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func;};function baseSlice(array,start,end){var index=-1,length=array.length;if(start<0){start=-start>length?0:(length+start);}
end=end>length?length:end;if(end<0){end+=length;}
length=start>end?0:((end-start)>>>0);start>>>=0;var result=Array(length);while(++index<length){result[index]=array[index+start];}
return result;}
function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result;});return!!result;}
function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(typeof value=='number'&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){while(low<high){var mid=(low+high)>>>1,computed=array[mid];if(computed!==null&&!isSymbol(computed)&&(retHighest?(computed<=value):(computed<value))){low=mid+1;}else{high=mid;}}
return high;}
return baseSortedIndexBy(array,value,identity,retHighest);}
function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=value===null,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;while(low<high){var mid=nativeFloor((low+high)/ 2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=computed===null,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN){var setLow=retHighest||othIsReflexive;}else if(valIsUndefined){setLow=othIsReflexive&&(retHighest||othIsDefined);}else if(valIsNull){setLow=othIsReflexive&&othIsDefined&&(retHighest||!othIsNull);}else if(valIsSymbol){setLow=othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol);}else if(othIsNull||othIsSymbol){setLow=false;}else{setLow=retHighest?(computed<=value):(computed<value);}
if(setLow){low=mid+1;}else{high=mid;}}
return nativeMin(high,MAX_ARRAY_INDEX);}
function baseSortedUniq(array,iteratee){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;if(!index||!eq(computed,seen)){var seen=computed;result[resIndex++]=value===0?0:value;}}
return result;}
function baseToNumber(value){if(typeof value=='number'){return value;}
if(isSymbol(value)){return NAN;}
return+value;}
function baseToString(value){if(typeof value=='string'){return value;}
if(isSymbol(value)){return symbolToString?symbolToString.call(value):'';}
var result=(value+'');return(result=='0'&&(1 / value)==-INFINITY)?'-0':result;}
function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=true,result=[],seen=result;if(comparator){isCommon=false;includes=arrayIncludesWith;}
else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set);}
isCommon=false;includes=cacheHas;seen=new SetCache;}
else{seen=iteratee?[]:result;}
outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;value=(comparator||value!==0)?value:0;if(isCommon&&computed===computed){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer;}}
if(iteratee){seen.push(computed);}
result.push(value);}
else if(!includes(seen,computed,comparator)){if(seen!==result){seen.push(computed);}
result.push(value);}}
return result;}
function baseUnset(object,path){path=isKey(path,object)?[path]:castPath(path);object=parent(object,path);var key=toKey(last(path));return!(object!=null&&baseHas(object,key))||delete object[key];}
function baseUpdate(object,path,updater,customizer){return baseSet(object,path,updater(baseGet(object,path)),customizer);}
function baseWhile(array,predicate,isDrop,fromRight){var length=array.length,index=fromRight?length:-1;while((fromRight?index--:++index<length)&&predicate(array[index],index,array)){}
return isDrop?baseSlice(array,(fromRight?0:index),(fromRight?index+1:length)):baseSlice(array,(fromRight?index+1:0),(fromRight?length:index));}
function baseWrapperValue(value,actions){var result=value;if(result instanceof LazyWrapper){result=result.value();}
return arrayReduce(actions,function(result,action){return action.func.apply(action.thisArg,arrayPush([result],action.args));},result);}
function baseXor(arrays,iteratee,comparator){var index=-1,length=arrays.length;while(++index<length){var result=result?arrayPush(baseDifference(result,arrays[index],iteratee,comparator),baseDifference(arrays[index],result,iteratee,comparator)):arrays[index];}
return(result&&result.length)?baseUniq(result,iteratee,comparator):[];}
function baseZipObject(props,values,assignFunc){var index=-1,length=props.length,valsLength=values.length,result={};while(++index<length){var value=index<valsLength?values[index]:undefined;assignFunc(result,props[index],value);}
return result;}
function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[];}
function castFunction(value){return typeof value=='function'?value:identity;}
function castPath(value){return isArray(value)?value:stringToPath(value);}
function castSlice(array,start,end){var length=array.length;end=end===undefined?length:end;return(!start&&end>=length)?array:baseSlice(array,start,end);}
function cloneBuffer(buffer,isDeep){if(isDeep){return buffer.slice();}
var result=new buffer.constructor(buffer.length);buffer.copy(result);return result;}
function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);new Uint8Array(result).set(new Uint8Array(arrayBuffer));return result;}
function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength);}
function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),true):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor);}
function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result;}
function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),true):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor);}
function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{};}
function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length);}
function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=value===null,valIsReflexive=value===value,valIsSymbol=isSymbol(value);var othIsDefined=other!==undefined,othIsNull=other===null,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if((!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other)||(valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol)||(valIsNull&&othIsDefined&&othIsReflexive)||(!valIsDefined&&othIsReflexive)||!valIsReflexive){return 1;}
if((!valIsNull&&!valIsSymbol&&!othIsSymbol&&value<other)||(othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol)||(othIsNull&&valIsDefined&&valIsReflexive)||(!othIsDefined&&valIsReflexive)||!othIsReflexive){return-1;}}
return 0;}
function compareMultiple(object,other,orders){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;while(++index<length){var result=compareAscending(objCriteria[index],othCriteria[index]);if(result){if(index>=ordersLength){return result;}
var order=orders[index];return result*(order=='desc'?-1:1);}}
return object.index-other.index;}
function composeArgs(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;while(++leftIndex<leftLength){result[leftIndex]=partials[leftIndex];}
while(++argsIndex<holdersLength){if(isUncurried||argsIndex<argsLength){result[holders[argsIndex]]=args[argsIndex];}}
while(rangeLength--){result[leftIndex++]=args[argsIndex++];}
return result;}
function composeArgsRight(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;while(++argsIndex<rangeLength){result[argsIndex]=args[argsIndex];}
var offset=argsIndex;while(++rightIndex<rightLength){result[offset+rightIndex]=partials[rightIndex];}
while(++holdersIndex<holdersLength){if(isUncurried||argsIndex<argsLength){result[offset+holders[holdersIndex]]=args[argsIndex++];}}
return result;}
function copyArray(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index];}
return array;}
function copyObject(source,props,object,customizer){object||(object={});var index=-1,length=props.length;while(++index<length){var key=props[index];var newValue=customizer?customizer(object[key],source[key],key,object,source):source[key];assignValue(object,key,newValue);}
return object;}
function copySymbols(source,object){return copyObject(source,getSymbols(source),object);}
function createAggregator(setter,initializer){return function(collection,iteratee){var func=isArray(collection)?arrayAggregator:baseAggregator,accumulator=initializer?initializer():{};return func(collection,setter,getIteratee(iteratee),accumulator);};}
function createAssigner(assigner){return rest(function(object,sources){var index=-1,length=sources.length,customizer=length>1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;customizer=(assigner.length>3&&typeof customizer=='function')?(length--,customizer):undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1;}
object=Object(object);while(++index<length){var source=sources[index];if(source){assigner(object,source,index,customizer);}}
return object;});}
function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){if(collection==null){return collection;}
if(!isArrayLike(collection)){return eachFunc(collection,iteratee);}
var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);while((fromRight?index--:++index<length)){if(iteratee(iterable[index],index,iterable)===false){break;}}
return collection;};}
function createBaseFor(fromRight){return function(object,iteratee,keysFunc){var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;while(length--){var key=props[fromRight?length:++index];if(iteratee(iterable[key],key,iterable)===false){break;}}
return object;};}
function createBaseWrapper(func,bitmask,thisArg){var isBind=bitmask&BIND_FLAG,Ctor=createCtorWrapper(func);function wrapper(){var fn=(this&&this!==root&&this instanceof wrapper)?Ctor:func;return fn.apply(isBind?thisArg:this,arguments);}
return wrapper;}
function createCaseFirst(methodName){return function(string){string=toString(string);var strSymbols=reHasComplexSymbol.test(string)?stringToArray(string):undefined;var chr=strSymbols?strSymbols[0]:string.charAt(0);var trailing=strSymbols?castSlice(strSymbols,1).join(''):string.slice(1);return chr[methodName]()+trailing;};}
function createCompounder(callback){return function(string){return arrayReduce(words(deburr(string).replace(reApos,'')),callback,'');};}
function createCtorWrapper(Ctor){return function(){var args=arguments;switch(args.length){case 0:return new Ctor;case 1:return new Ctor(args[0]);case 2:return new Ctor(args[0],args[1]);case 3:return new Ctor(args[0],args[1],args[2]);case 4:return new Ctor(args[0],args[1],args[2],args[3]);case 5:return new Ctor(args[0],args[1],args[2],args[3],args[4]);case 6:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5]);case 7:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);}
var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,args);return isObject(result)?result:thisBinding;};}
function createCurryWrapper(func,bitmask,arity){var Ctor=createCtorWrapper(func);function wrapper(){var length=arguments.length,args=Array(length),index=length,placeholder=getHolder(wrapper);while(index--){args[index]=arguments[index];}
var holders=(length<3&&args[0]!==placeholder&&args[length-1]!==placeholder)?[]:replaceHolders(args,placeholder);length-=holders.length;if(length<arity){return createRecurryWrapper(func,bitmask,createHybridWrapper,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);}
var fn=(this&&this!==root&&this instanceof wrapper)?Ctor:func;return apply(fn,this,args);}
return wrapper;}
function createFlow(fromRight){return rest(function(funcs){funcs=baseFlatten(funcs,1);var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;if(fromRight){funcs.reverse();}
while(index--){var func=funcs[index];if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
if(prereq&&!wrapper&&getFuncName(func)=='wrapper'){var wrapper=new LodashWrapper([],true);}}
index=wrapper?index:length;while(++index<length){func=funcs[index];var funcName=getFuncName(func),data=funcName=='wrapper'?getData(func):undefined;if(data&&isLaziable(data[0])&&data[1]==(ARY_FLAG|CURRY_FLAG|PARTIAL_FLAG|REARG_FLAG)&&!data[4].length&&data[9]==1){wrapper=wrapper[getFuncName(data[0])].apply(wrapper,data[3]);}else{wrapper=(func.length==1&&isLaziable(func))?wrapper[funcName]():wrapper.thru(func);}}
return function(){var args=arguments,value=args[0];if(wrapper&&args.length==1&&isArray(value)&&value.length>=LARGE_ARRAY_SIZE){return wrapper.plant(value).value();}
var index=0,result=length?funcs[index].apply(this,args):value;while(++index<length){result=funcs[index].call(this,result);}
return result;};});}
function createHybridWrapper(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtorWrapper(func);function wrapper(){var length=arguments.length,args=Array(length),index=length;while(index--){args[index]=arguments[index];}
if(isCurried){var placeholder=getHolder(wrapper),holdersCount=countHolders(args,placeholder);}
if(partials){args=composeArgs(args,partials,holders,isCurried);}
if(partialsRight){args=composeArgsRight(args,partialsRight,holdersRight,isCurried);}
length-=holdersCount;if(isCurried&&length<arity){var newHolders=replaceHolders(args,placeholder);return createRecurryWrapper(func,bitmask,createHybridWrapper,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length);}
var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;length=args.length;if(argPos){args=reorder(args,argPos);}else if(isFlip&&length>1){args.reverse();}
if(isAry&&ary<length){args.length=ary;}
if(this&&this!==root&&this instanceof wrapper){fn=Ctor||createCtorWrapper(fn);}
return fn.apply(thisBinding,args);}
return wrapper;}
function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{});};}
function createMathOperation(operator){return function(value,other){var result;if(value===undefined&&other===undefined){return 0;}
if(value!==undefined){result=value;}
if(other!==undefined){if(result===undefined){return other;}
if(typeof value=='string'||typeof other=='string'){value=baseToString(value);other=baseToString(other);}else{value=baseToNumber(value);other=baseToNumber(other);}
result=operator(value,other);}
return result;};}
function createOver(arrayFunc){return rest(function(iteratees){iteratees=(iteratees.length==1&&isArray(iteratees[0]))?arrayMap(iteratees[0],baseUnary(getIteratee())):arrayMap(baseFlatten(iteratees,1,isFlattenableIteratee),baseUnary(getIteratee()));return rest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args);});});});}
function createPadding(length,chars){chars=chars===undefined?' ':baseToString(chars);var charsLength=chars.length;if(charsLength<2){return charsLength?baseRepeat(chars,length):chars;}
var result=baseRepeat(chars,nativeCeil(length / stringSize(chars)));return reHasComplexSymbol.test(chars)?castSlice(stringToArray(result),0,length).join(''):result.slice(0,length);}
function createPartialWrapper(func,bitmask,thisArg,partials){var isBind=bitmask&BIND_FLAG,Ctor=createCtorWrapper(func);function wrapper(){var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=(this&&this!==root&&this instanceof wrapper)?Ctor:func;while(++leftIndex<leftLength){args[leftIndex]=partials[leftIndex];}
while(argsLength--){args[leftIndex++]=arguments[++argsIndex];}
return apply(fn,isBind?thisArg:this,args);}
return wrapper;}
function createRange(fromRight){return function(start,end,step){if(step&&typeof step!='number'&&isIterateeCall(start,end,step)){end=step=undefined;}
start=toNumber(start);start=start===start?start:0;if(end===undefined){end=start;start=0;}else{end=toNumber(end)||0;}
step=step===undefined?(start<end?1:-1):(toNumber(step)||0);return baseRange(start,end,step,fromRight);};}
function createRelationalOperation(operator){return function(value,other){if(!(typeof value=='string'&&typeof other=='string')){value=toNumber(value);other=toNumber(other);}
return operator(value,other);};}
function createRecurryWrapper(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=(isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG);bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG);if(!(bitmask&CURRY_BOUND_FLAG)){bitmask&=~(BIND_FLAG|BIND_KEY_FLAG);}
var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity];var result=wrapFunc.apply(undefined,newData);if(isLaziable(func)){setData(result,newData);}
result.placeholder=placeholder;return result;}
function createRound(methodName){var func=Math[methodName];return function(number,precision){number=toNumber(number);precision=toInteger(precision);if(precision){var pair=(toString(number)+'e').split('e'),value=func(pair[0]+'e'+(+pair[1]+precision));pair=(toString(value)+'e').split('e');return+(pair[0]+'e'+(+pair[1]-precision));}
return func(number);};}
var createSet=!(Set&&(1 / setToArray(new Set([,-0]))[1])==INFINITY)?noop:function(values){return new Set(values);};function createToPairs(keysFunc){return function(object){var tag=getTag(object);if(tag==mapTag){return mapToArray(object);}
if(tag==setTag){return setToPairs(object);}
return baseToPairs(object,keysFunc(object));};}
function createWrapper(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
var length=partials?partials.length:0;if(!length){bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG);partials=holders=undefined;}
ary=ary===undefined?ary:nativeMax(toInteger(ary),0);arity=arity===undefined?arity:toInteger(arity);length-=holders?holders.length:0;if(bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined;}
var data=isBindKey?undefined:getData(func);var newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data){mergeData(newData,data);}
func=newData[0];bitmask=newData[1];thisArg=newData[2];partials=newData[3];holders=newData[4];arity=newData[9]=newData[9]==null?(isBindKey?0:func.length):nativeMax(newData[9]-length,0);if(!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)){bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG);}
if(!bitmask||bitmask==BIND_FLAG){var result=createBaseWrapper(func,bitmask,thisArg);}else if(bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG){result=createCurryWrapper(func,bitmask,arity);}else if((bitmask==PARTIAL_FLAG||bitmask==(BIND_FLAG|PARTIAL_FLAG))&&!holders.length){result=createPartialWrapper(func,bitmask,thisArg,partials);}else{result=createHybridWrapper.apply(undefined,newData);}
var setter=data?baseSetData:setData;return setter(result,newData);}
function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength)){return false;}
var stacked=stack.get(array);if(stacked){return stacked==other;}
var index=-1,result=true,seen=(bitmask&UNORDERED_COMPARE_FLAG)?new SetCache:undefined;stack.set(array,other);while(++index<arrLength){var arrValue=array[index],othValue=other[index];if(customizer){var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack);}
if(compared!==undefined){if(compared){continue;}
result=false;break;}
if(seen){if(!arraySome(other,function(othValue,othIndex){if(!seen.has(othIndex)&&(arrValue===othValue||equalFunc(arrValue,othValue,customizer,bitmask,stack))){return seen.add(othIndex);}})){result=false;break;}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,customizer,bitmask,stack))){result=false;break;}}
stack['delete'](array);return result;}
function equalByTag(object,other,tag,equalFunc,customizer,bitmask,stack){switch(tag){case dataViewTag:if((object.byteLength!=other.byteLength)||(object.byteOffset!=other.byteOffset)){return false;}
object=object.buffer;other=other.buffer;case arrayBufferTag:if((object.byteLength!=other.byteLength)||!equalFunc(new Uint8Array(object),new Uint8Array(other))){return false;}
return true;case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return(object!=+object)?other!=+other:object==+other;case regexpTag:case stringTag:return object==(other+'');case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&PARTIAL_COMPARE_FLAG;convert||(convert=setToArray);if(object.size!=other.size&&!isPartial){return false;}
var stacked=stack.get(object);if(stacked){return stacked==other;}
bitmask|=UNORDERED_COMPARE_FLAG;stack.set(object,other);return equalArrays(convert(object),convert(other),equalFunc,customizer,bitmask,stack);case symbolTag:if(symbolValueOf){return symbolValueOf.call(object)==symbolValueOf.call(other);}}
return false;}
function equalObjects(object,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial){return false;}
var index=objLength;while(index--){var key=objProps[index];if(!(isPartial?key in other:baseHas(other,key))){return false;}}
var stacked=stack.get(object);if(stacked){return stacked==other;}
var result=true;stack.set(object,other);var skipCtor=isPartial;while(++index<objLength){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer){var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack);}
if(!(compared===undefined?(objValue===othValue||equalFunc(objValue,othValue,customizer,bitmask,stack)):compared)){result=false;break;}
skipCtor||(skipCtor=key=='constructor');}
if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&('constructor'in object&&'constructor'in other)&&!(typeof objCtor=='function'&&objCtor instanceof objCtor&&typeof othCtor=='function'&&othCtor instanceof othCtor)){result=false;}}
stack['delete'](object);return result;}
function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols);}
function getAllKeysIn(object){return baseGetAllKeys(object,keysIn,getSymbolsIn);}
var getData=!metaMap?noop:function(func){return metaMap.get(func);};function getFuncName(func){var result=(func.name+''),array=realNames[result],length=hasOwnProperty.call(realNames,result)?array.length:0;while(length--){var data=array[length],otherFunc=data.func;if(otherFunc==null||otherFunc==func){return data.name;}}
return result;}
function getHolder(func){var object=hasOwnProperty.call(lodash,'placeholder')?lodash:func;return object.placeholder;}
function getIteratee(){var result=lodash.iteratee||iteratee;result=result===iteratee?baseIteratee:result;return arguments.length?result(arguments[0],arguments[1]):result;}
var getLength=baseProperty('length');function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data[typeof key=='string'?'string':'hash']:data.map;}
function getMatchData(object){var result=toPairs(object),length=result.length;while(length--){result[length][2]=isStrictComparable(result[length][1]);}
return result;}
function getNative(object,key){var value=object[key];return isNative(value)?value:undefined;}
function getPrototype(value){return nativeGetPrototype(Object(value));}
function getSymbols(object){return getOwnPropertySymbols(Object(object));}
if(!getOwnPropertySymbols){getSymbols=function(){return[];};}
var getSymbolsIn=!getOwnPropertySymbols?getSymbols:function(object){var result=[];while(object){arrayPush(result,getSymbols(object));object=getPrototype(object);}
return result;};function getTag(value){return objectToString.call(value);}
if((DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag)||(Map&&getTag(new Map)!=mapTag)||(Promise&&getTag(Promise.resolve())!=promiseTag)||(Set&&getTag(new Set)!=setTag)||(WeakMap&&getTag(new WeakMap)!=weakMapTag)){getTag=function(value){var result=objectToString.call(value),Ctor=result==objectTag?value.constructor:undefined,ctorString=Ctor?toSource(Ctor):undefined;if(ctorString){switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag;}}
return result;};}
function getView(start,end,transforms){var index=-1,length=transforms.length;while(++index<length){var data=transforms[index],size=data.size;switch(data.type){case'drop':start+=size;break;case'dropRight':end-=size;break;case'take':end=nativeMin(end,start+size);break;case'takeRight':start=nativeMax(start,end-size);break;}}
return{'start':start,'end':end};}
function hasPath(object,path,hasFunc){path=isKey(path,object)?[path]:castPath(path);var result,index=-1,length=path.length;while(++index<length){var key=toKey(path[index]);if(!(result=object!=null&&hasFunc(object,key))){break;}
object=object[key];}
if(result){return result;}
var length=object?object.length:0;return!!length&&isLength(length)&&isIndex(key,length)&&(isArray(object)||isString(object)||isArguments(object));}
function initCloneArray(array){var length=array.length,result=array.constructor(length);if(length&&typeof array[0]=='string'&&hasOwnProperty.call(array,'index')){result.index=array.index;result.input=array.input;}
return result;}
function initCloneObject(object){return(typeof object.constructor=='function'&&!isPrototype(object))?baseCreate(getPrototype(object)):{};}
function initCloneByTag(object,tag,cloneFunc,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return cloneArrayBuffer(object);case boolTag:case dateTag:return new Ctor(+object);case dataViewTag:return cloneDataView(object,isDeep);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:return cloneTypedArray(object,isDeep);case mapTag:return cloneMap(object,isDeep,cloneFunc);case numberTag:case stringTag:return new Ctor(object);case regexpTag:return cloneRegExp(object);case setTag:return cloneSet(object,isDeep,cloneFunc);case symbolTag:return cloneSymbol(object);}}
function indexKeys(object){var length=object?object.length:undefined;if(isLength(length)&&(isArray(object)||isString(object)||isArguments(object))){return baseTimes(length,String);}
return null;}
function isFlattenable(value){return isArray(value)||isArguments(value);}
function isFlattenableIteratee(value){return isArray(value)&&!(value.length==2&&!isFunction(value[0]));}
function isIndex(value,length){length=length==null?MAX_SAFE_INTEGER:length;return!!length&&(typeof value=='number'||reIsUint.test(value))&&(value>-1&&value%1==0&&value<length);}
function isIterateeCall(value,index,object){if(!isObject(object)){return false;}
var type=typeof index;if(type=='number'?(isArrayLike(object)&&isIndex(index,object.length)):(type=='string'&&index in object)){return eq(object[index],value);}
return false;}
function isKey(value,object){if(isArray(value)){return false;}
var type=typeof value;if(type=='number'||type=='symbol'||type=='boolean'||value==null||isSymbol(value)){return true;}
return reIsPlainProp.test(value)||!reIsDeepProp.test(value)||(object!=null&&value in Object(object));}
function isKeyable(value){var type=typeof value;return(type=='string'||type=='number'||type=='symbol'||type=='boolean')?(value!=='__proto__'):(value===null);}
function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if(typeof other!='function'||!(funcName in LazyWrapper.prototype)){return false;}
if(func===other){return true;}
var data=getData(other);return!!data&&func===data[0];}
function isPrototype(value){var Ctor=value&&value.constructor,proto=(typeof Ctor=='function'&&Ctor.prototype)||objectProto;return value===proto;}
function isStrictComparable(value){return value===value&&!isObject(value);}
function matchesStrictComparable(key,srcValue){return function(object){if(object==null){return false;}
return object[key]===srcValue&&(srcValue!==undefined||(key in Object(object)));};}
function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=newBitmask<(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG);var isCombo=((srcBitmask==ARY_FLAG)&&(bitmask==CURRY_FLAG))||((srcBitmask==ARY_FLAG)&&(bitmask==REARG_FLAG)&&(data[7].length<=source[8]))||((srcBitmask==(ARY_FLAG|REARG_FLAG))&&(source[7].length<=source[8])&&(bitmask==CURRY_FLAG));if(!(isCommon||isCombo)){return data;}
if(srcBitmask&BIND_FLAG){data[2]=source[2];newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG;}
var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value;data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4];}
value=source[5];if(value){partials=data[5];data[5]=partials?composeArgsRight(partials,value,source[6]):value;data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6];}
value=source[7];if(value){data[7]=value;}
if(srcBitmask&ARY_FLAG){data[8]=data[8]==null?source[8]:nativeMin(data[8],source[8]);}
if(data[9]==null){data[9]=source[9];}
data[0]=source[0];data[1]=newBitmask;return data;}
function mergeDefaults(objValue,srcValue,key,object,source,stack){if(isObject(objValue)&&isObject(srcValue)){baseMerge(objValue,srcValue,undefined,mergeDefaults,stack.set(srcValue,objValue));}
return objValue;}
function parent(object,path){return path.length==1?object:baseGet(object,baseSlice(path,0,-1));}
function reorder(array,indexes){var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=copyArray(array);while(length--){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:undefined;}
return array;}
var setData=(function(){var count=0,lastCalled=0;return function(key,value){var stamp=now(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return key;}}else{count=0;}
return baseSetData(key,value);};}());var stringToPath=memoize(function(string){var result=[];toString(string).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,'$1'):(number||match));});return result;});function toKey(value){if(typeof value=='string'||isSymbol(value)){return value;}
var result=(value+'');return(result=='0'&&(1 / value)==-INFINITY)?'-0':result;}
function toSource(func){if(func!=null){try{return funcToString.call(func);}catch(e){}
try{return(func+'');}catch(e){}}
return'';}
function wrapperClone(wrapper){if(wrapper instanceof LazyWrapper){return wrapper.clone();}
var result=new LodashWrapper(wrapper.__wrapped__,wrapper.__chain__);result.__actions__=copyArray(wrapper.__actions__);result.__index__=wrapper.__index__;result.__values__=wrapper.__values__;return result;}
function chunk(array,size,guard){if((guard?isIterateeCall(array,size,guard):size===undefined)){size=1;}else{size=nativeMax(toInteger(size),0);}
var length=array?array.length:0;if(!length||size<1){return[];}
var index=0,resIndex=0,result=Array(nativeCeil(length / size));while(index<length){result[resIndex++]=baseSlice(array,index,(index+=size));}
return result;}
function compact(array){var index=-1,length=array?array.length:0,resIndex=0,result=[];while(++index<length){var value=array[index];if(value){result[resIndex++]=value;}}
return result;}
function concat(){var length=arguments.length,args=Array(length?length-1:0),array=arguments[0],index=length;while(index--){args[index-1]=arguments[index];}
return length?arrayPush(isArray(array)?copyArray(array):[array],baseFlatten(args,1)):[];}
var difference=rest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true)):[];});var differenceBy=rest(function(array,values){var iteratee=last(values);if(isArrayLikeObject(iteratee)){iteratee=undefined;}
return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),getIteratee(iteratee)):[];});var differenceWith=rest(function(array,values){var comparator=last(values);if(isArrayLikeObject(comparator)){comparator=undefined;}
return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),undefined,comparator):[];});function drop(array,n,guard){var length=array?array.length:0;if(!length){return[];}
n=(guard||n===undefined)?1:toInteger(n);return baseSlice(array,n<0?0:n,length);}
function dropRight(array,n,guard){var length=array?array.length:0;if(!length){return[];}
n=(guard||n===undefined)?1:toInteger(n);n=length-n;return baseSlice(array,0,n<0?0:n);}
function dropRightWhile(array,predicate){return(array&&array.length)?baseWhile(array,getIteratee(predicate,3),true,true):[];}
function dropWhile(array,predicate){return(array&&array.length)?baseWhile(array,getIteratee(predicate,3),true):[];}
function fill(array,value,start,end){var length=array?array.length:0;if(!length){return[];}
if(start&&typeof start!='number'&&isIterateeCall(array,value,start)){start=0;end=length;}
return baseFill(array,value,start,end);}
function findIndex(array,predicate){return(array&&array.length)?baseFindIndex(array,getIteratee(predicate,3)):-1;}
function findLastIndex(array,predicate){return(array&&array.length)?baseFindIndex(array,getIteratee(predicate,3),true):-1;}
function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[];}
function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[];}
function flattenDepth(array,depth){var length=array?array.length:0;if(!length){return[];}
depth=depth===undefined?1:toInteger(depth);return baseFlatten(array,depth);}
function fromPairs(pairs){var index=-1,length=pairs?pairs.length:0,result={};while(++index<length){var pair=pairs[index];result[pair[0]]=pair[1];}
return result;}
function head(array){return(array&&array.length)?array[0]:undefined;}
function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1;}
fromIndex=toInteger(fromIndex);if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0);}
return baseIndexOf(array,value,fromIndex);}
function initial(array){return dropRight(array,1);}
var intersection=rest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return(mapped.length&&mapped[0]===arrays[0])?baseIntersection(mapped):[];});var intersectionBy=rest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);if(iteratee===last(mapped)){iteratee=undefined;}else{mapped.pop();}
return(mapped.length&&mapped[0]===arrays[0])?baseIntersection(mapped,getIteratee(iteratee)):[];});var intersectionWith=rest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);if(comparator===last(mapped)){comparator=undefined;}else{mapped.pop();}
return(mapped.length&&mapped[0]===arrays[0])?baseIntersection(mapped,undefined,comparator):[];});function join(array,separator){return array?nativeJoin.call(array,separator):'';}
function last(array){var length=array?array.length:0;return length?array[length-1]:undefined;}
function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1;}
var index=length;if(fromIndex!==undefined){index=toInteger(fromIndex);index=(index<0?nativeMax(length+index,0):nativeMin(index,length-1))+1;}
if(value!==value){return indexOfNaN(array,index,true);}
while(index--){if(array[index]===value){return index;}}
return-1;}
function nth(array,n){return(array&&array.length)?baseNth(array,toInteger(n)):undefined;}
var pull=rest(pullAll);function pullAll(array,values){return(array&&array.length&&values&&values.length)?basePullAll(array,values):array;}
function pullAllBy(array,values,iteratee){return(array&&array.length&&values&&values.length)?basePullAll(array,values,getIteratee(iteratee)):array;}
function pullAllWith(array,values,comparator){return(array&&array.length&&values&&values.length)?basePullAll(array,values,undefined,comparator):array;}
var pullAt=rest(function(array,indexes){indexes=baseFlatten(indexes,1);var length=array?array.length:0,result=baseAt(array,indexes);basePullAt(array,arrayMap(indexes,function(index){return isIndex(index,length)?+index:index;}).sort(compareAscending));return result;});function remove(array,predicate){var result=[];if(!(array&&array.length)){return result;}
var index=-1,indexes=[],length=array.length;predicate=getIteratee(predicate,3);while(++index<length){var value=array[index];if(predicate(value,index,array)){result.push(value);indexes.push(index);}}
basePullAt(array,indexes);return result;}
function reverse(array){return array?nativeReverse.call(array):array;}
function slice(array,start,end){var length=array?array.length:0;if(!length){return[];}
if(end&&typeof end!='number'&&isIterateeCall(array,start,end)){start=0;end=length;}
else{start=start==null?0:toInteger(start);end=end===undefined?length:toInteger(end);}
return baseSlice(array,start,end);}
function sortedIndex(array,value){return baseSortedIndex(array,value);}
function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee));}
function sortedIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value);if(index<length&&eq(array[index],value)){return index;}}
return-1;}
function sortedLastIndex(array,value){return baseSortedIndex(array,value,true);}
function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee),true);}
function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,true)-1;if(eq(array[index],value)){return index;}}
return-1;}
function sortedUniq(array){return(array&&array.length)?baseSortedUniq(array):[];}
function sortedUniqBy(array,iteratee){return(array&&array.length)?baseSortedUniq(array,getIteratee(iteratee)):[];}
function tail(array){return drop(array,1);}
function take(array,n,guard){if(!(array&&array.length)){return[];}
n=(guard||n===undefined)?1:toInteger(n);return baseSlice(array,0,n<0?0:n);}
function takeRight(array,n,guard){var length=array?array.length:0;if(!length){return[];}
n=(guard||n===undefined)?1:toInteger(n);n=length-n;return baseSlice(array,n<0?0:n,length);}
function takeRightWhile(array,predicate){return(array&&array.length)?baseWhile(array,getIteratee(predicate,3),false,true):[];}
function takeWhile(array,predicate){return(array&&array.length)?baseWhile(array,getIteratee(predicate,3)):[];}
var union=rest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true));});var unionBy=rest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}
return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),getIteratee(iteratee));});var unionWith=rest(function(arrays){var comparator=last(arrays);if(isArrayLikeObject(comparator)){comparator=undefined;}
return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),undefined,comparator);});function uniq(array){return(array&&array.length)?baseUniq(array):[];}
function uniqBy(array,iteratee){return(array&&array.length)?baseUniq(array,getIteratee(iteratee)):[];}
function uniqWith(array,comparator){return(array&&array.length)?baseUniq(array,undefined,comparator):[];}
function unzip(array){if(!(array&&array.length)){return[];}
var length=0;array=arrayFilter(array,function(group){if(isArrayLikeObject(group)){length=nativeMax(group.length,length);return true;}});return baseTimes(length,function(index){return arrayMap(array,baseProperty(index));});}
function unzipWith(array,iteratee){if(!(array&&array.length)){return[];}
var result=unzip(array);if(iteratee==null){return result;}
return arrayMap(result,function(group){return apply(iteratee,undefined,group);});}
var without=rest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[];});var xor=rest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject));});var xorBy=rest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}
return baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee));});var xorWith=rest(function(arrays){var comparator=last(arrays);if(isArrayLikeObject(comparator)){comparator=undefined;}
return baseXor(arrayFilter(arrays,isArrayLikeObject),undefined,comparator);});var zip=rest(unzip);function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue);}
function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet);}
var zipWith=rest(function(arrays){var length=arrays.length,iteratee=length>1?arrays[length-1]:undefined;iteratee=typeof iteratee=='function'?(arrays.pop(),iteratee):undefined;return unzipWith(arrays,iteratee);});function chain(value){var result=lodash(value);result.__chain__=true;return result;}
function tap(value,interceptor){interceptor(value);return value;}
function thru(value,interceptor){return interceptor(value);}
var wrapperAt=rest(function(paths){paths=baseFlatten(paths,1);var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths);};if(length>1||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)){return this.thru(interceptor);}
value=value.slice(start,+start+(length?1:0));value.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined});return new LodashWrapper(value,this.__chain__).thru(function(array){if(length&&!array.length){array.push(undefined);}
return array;});});function wrapperChain(){return chain(this);}
function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__);}
function wrapperNext(){if(this.__values__===undefined){this.__values__=toArray(this.value());}
var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{'done':done,'value':value};}
function wrapperToIterator(){return this;}
function wrapperPlant(value){var result,parent=this;while(parent instanceof baseLodash){var clone=wrapperClone(parent);clone.__index__=0;clone.__values__=undefined;if(result){previous.__wrapped__=clone;}else{result=clone;}
var previous=clone;parent=parent.__wrapped__;}
previous.__wrapped__=value;return result;}
function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;if(this.__actions__.length){wrapped=new LazyWrapper(this);}
wrapped=wrapped.reverse();wrapped.__actions__.push({'func':thru,'args':[reverse],'thisArg':undefined});return new LodashWrapper(wrapped,this.__chain__);}
return this.thru(reverse);}
function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__);}
var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:(result[key]=1);});function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}
return func(collection,getIteratee(predicate,3));}
function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3));}
function find(collection,predicate){predicate=getIteratee(predicate,3);if(isArray(collection)){var index=baseFindIndex(collection,predicate);return index>-1?collection[index]:undefined;}
return baseFind(collection,predicate,baseEach);}
function findLast(collection,predicate){predicate=getIteratee(predicate,3);if(isArray(collection)){var index=baseFindIndex(collection,predicate,true);return index>-1?collection[index]:undefined;}
return baseFind(collection,predicate,baseEachRight);}
function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1);}
function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY);}
function flatMapDepth(collection,iteratee,depth){depth=depth===undefined?1:toInteger(depth);return baseFlatten(map(collection,iteratee),depth);}
function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3));}
function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3));}
var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value);}else{result[key]=[value];}});function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection);fromIndex=(fromIndex&&!guard)?toInteger(fromIndex):0;var length=collection.length;if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0);}
return isString(collection)?(fromIndex<=length&&collection.indexOf(value,fromIndex)>-1):(!!length&&baseIndexOf(collection,value,fromIndex)>-1);}
var invokeMap=rest(function(collection,path,args){var index=-1,isFunc=typeof path=='function',isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value){var func=isFunc?path:((isProp&&value!=null)?value[path]:undefined);result[++index]=func?apply(func,value,args):baseInvoke(value,path,args);});return result;});var keyBy=createAggregator(function(result,value,key){result[key]=value;});function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3));}
function orderBy(collection,iteratees,orders,guard){if(collection==null){return[];}
if(!isArray(iteratees)){iteratees=iteratees==null?[]:[iteratees];}
orders=guard?undefined:orders;if(!isArray(orders)){orders=orders==null?[]:[orders];}
return baseOrderBy(collection,iteratees,orders);}
var partition=createAggregator(function(result,value,key){result[key?0:1].push(value);},function(){return[[],[]];});function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach);}
function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight);}
function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;predicate=getIteratee(predicate,3);return func(collection,function(value,index,collection){return!predicate(value,index,collection);});}
function sample(collection){var array=isArrayLike(collection)?collection:values(collection),length=array.length;return length>0?array[baseRandom(0,length-1)]:undefined;}
function sampleSize(collection,n,guard){var index=-1,result=toArray(collection),length=result.length,lastIndex=length-1;if((guard?isIterateeCall(collection,n,guard):n===undefined)){n=1;}else{n=baseClamp(toInteger(n),0,length);}
while(++index<n){var rand=baseRandom(index,lastIndex),value=result[rand];result[rand]=result[index];result[index]=value;}
result.length=n;return result;}
function shuffle(collection){return sampleSize(collection,MAX_ARRAY_LENGTH);}
function size(collection){if(collection==null){return 0;}
if(isArrayLike(collection)){var result=collection.length;return(result&&isString(collection))?stringSize(collection):result;}
if(isObjectLike(collection)){var tag=getTag(collection);if(tag==mapTag||tag==setTag){return collection.size;}}
return keys(collection).length;}
function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}
return func(collection,getIteratee(predicate,3));}
var sortBy=rest(function(collection,iteratees){if(collection==null){return[];}
var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[];}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees=[iteratees[0]];}
iteratees=(iteratees.length==1&&isArray(iteratees[0]))?iteratees[0]:baseFlatten(iteratees,1,isFlattenableIteratee);return baseOrderBy(collection,iteratees,[]);});var now=Date.now;function after(n,func){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
n=toInteger(n);return function(){if(--n<1){return func.apply(this,arguments);}};}
function ary(func,n,guard){n=guard?undefined:n;n=(func&&n==null)?func.length:n;return createWrapper(func,ARY_FLAG,undefined,undefined,undefined,undefined,n);}
function before(n,func){var result;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
n=toInteger(n);return function(){if(--n>0){result=func.apply(this,arguments);}
if(n<=1){func=undefined;}
return result;};}
var bind=rest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG;}
return createWrapper(func,bitmask,thisArg,partials,holders);});var bindKey=rest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG;}
return createWrapper(key,bitmask,object,partials,holders);});function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrapper(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curry.placeholder;return result;}
function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrapper(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curryRight.placeholder;return result;}
function debounce(func,wait,options){var lastArgs,lastThis,maxWait,result,timerId,lastCallTime=0,lastInvokeTime=0,leading=false,maxing=false,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
wait=toNumber(wait)||0;if(isObject(options)){leading=!!options.leading;maxing='maxWait'in options;maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait;trailing='trailing'in options?!!options.trailing:trailing;}
function invokeFunc(time){var args=lastArgs,thisArg=lastThis;lastArgs=lastThis=undefined;lastInvokeTime=time;result=func.apply(thisArg,args);return result;}
function leadingEdge(time){lastInvokeTime=time;timerId=setTimeout(timerExpired,wait);return leading?invokeFunc(time):result;}
function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result;}
function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return(!lastCallTime||(timeSinceLastCall>=wait)||(timeSinceLastCall<0)||(maxing&&timeSinceLastInvoke>=maxWait));}
function timerExpired(){var time=now();if(shouldInvoke(time)){return trailingEdge(time);}
timerId=setTimeout(timerExpired,remainingWait(time));}
function trailingEdge(time){clearTimeout(timerId);timerId=undefined;if(trailing&&lastArgs){return invokeFunc(time);}
lastArgs=lastThis=undefined;return result;}
function cancel(){if(timerId!==undefined){clearTimeout(timerId);}
lastCallTime=lastInvokeTime=0;lastArgs=lastThis=timerId=undefined;}
function flush(){return timerId===undefined?result:trailingEdge(now());}
function debounced(){var time=now(),isInvoking=shouldInvoke(time);lastArgs=arguments;lastThis=this;lastCallTime=time;if(isInvoking){if(timerId===undefined){return leadingEdge(lastCallTime);}
if(maxing){clearTimeout(timerId);timerId=setTimeout(timerExpired,wait);return invokeFunc(lastCallTime);}}
if(timerId===undefined){timerId=setTimeout(timerExpired,wait);}
return result;}
debounced.cancel=cancel;debounced.flush=flush;return debounced;}
var defer=rest(function(func,args){return baseDelay(func,1,args);});var delay=rest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args);});function flip(func){return createWrapper(func,FLIP_FLAG);}
function memoize(func,resolver){if(typeof func!='function'||(resolver&&typeof resolver!='function')){throw new TypeError(FUNC_ERROR_TEXT);}
var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}
var result=func.apply(this,args);memoized.cache=cache.set(key,result);return result;};memoized.cache=new(memoize.Cache||MapCache);return memoized;}
memoize.Cache=MapCache;function negate(predicate){if(typeof predicate!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
return function(){return!predicate.apply(this,arguments);};}
function once(func){return before(2,func);}
var overArgs=rest(function(func,transforms){transforms=(transforms.length==1&&isArray(transforms[0]))?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1,isFlattenableIteratee),baseUnary(getIteratee()));var funcsLength=transforms.length;return rest(function(args){var index=-1,length=nativeMin(args.length,funcsLength);while(++index<length){args[index]=transforms[index].call(this,args[index]);}
return apply(func,this,args);});});var partial=rest(function(func,partials){var holders=replaceHolders(partials,getHolder(partial));return createWrapper(func,PARTIAL_FLAG,undefined,partials,holders);});var partialRight=rest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrapper(func,PARTIAL_RIGHT_FLAG,undefined,partials,holders);});var rearg=rest(function(func,indexes){return createWrapper(func,REARG_FLAG,undefined,undefined,undefined,baseFlatten(indexes,1));});function rest(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
start=nativeMax(start===undefined?(func.length-1):toInteger(start),0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index<length){array[index]=args[start+index];}
switch(start){case 0:return func.call(this,array);case 1:return func.call(this,args[0],array);case 2:return func.call(this,args[0],args[1],array);}
var otherArgs=Array(start+1);index=-1;while(++index<start){otherArgs[index]=args[index];}
otherArgs[start]=array;return apply(func,this,otherArgs);};}
function spread(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
start=start===undefined?0:nativeMax(toInteger(start),0);return rest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);if(array){arrayPush(otherArgs,array);}
return apply(func,this,otherArgs);});}
function throttle(func,wait,options){var leading=true,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
if(isObject(options)){leading='leading'in options?!!options.leading:leading;trailing='trailing'in options?!!options.trailing:trailing;}
return debounce(func,wait,{'leading':leading,'maxWait':wait,'trailing':trailing});}
function unary(func){return ary(func,1);}
function wrap(value,wrapper){wrapper=wrapper==null?identity:wrapper;return partial(wrapper,value);}
function castArray(){if(!arguments.length){return[];}
var value=arguments[0];return isArray(value)?value:[value];}
function clone(value){return baseClone(value,false,true);}
function cloneWith(value,customizer){return baseClone(value,false,true,customizer);}
function cloneDeep(value){return baseClone(value,true,true);}
function cloneDeepWith(value,customizer){return baseClone(value,true,true,customizer);}
function eq(value,other){return value===other||(value!==value&&other!==other);}
var gt=createRelationalOperation(baseGt);var gte=createRelationalOperation(function(value,other){return value>=other;});function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,'callee')&&(!propertyIsEnumerable.call(value,'callee')||objectToString.call(value)==argsTag);}
var isArray=Array.isArray;function isArrayBuffer(value){return isObjectLike(value)&&objectToString.call(value)==arrayBufferTag;}
function isArrayLike(value){return value!=null&&isLength(getLength(value))&&!isFunction(value);}
function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value);}
function isBoolean(value){return value===true||value===false||(isObjectLike(value)&&objectToString.call(value)==boolTag);}
var isBuffer=!Buffer?constant(false):function(value){return value instanceof Buffer;};function isDate(value){return isObjectLike(value)&&objectToString.call(value)==dateTag;}
function isElement(value){return!!value&&value.nodeType===1&&isObjectLike(value)&&!isPlainObject(value);}
function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||isString(value)||isFunction(value.splice)||isArguments(value)||isBuffer(value))){return!value.length;}
if(isObjectLike(value)){var tag=getTag(value);if(tag==mapTag||tag==setTag){return!value.size;}}
for(var key in value){if(hasOwnProperty.call(value,key)){return false;}}
return!(nonEnumShadows&&keys(value).length);}
function isEqual(value,other){return baseIsEqual(value,other);}
function isEqualWith(value,other,customizer){customizer=typeof customizer=='function'?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result;}
function isError(value){if(!isObjectLike(value)){return false;}
return(objectToString.call(value)==errorTag)||(typeof value.message=='string'&&typeof value.name=='string');}
function isFinite(value){return typeof value=='number'&&nativeIsFinite(value);}
function isFunction(value){var tag=isObject(value)?objectToString.call(value):'';return tag==funcTag||tag==genTag;}
function isInteger(value){return typeof value=='number'&&value==toInteger(value);}
function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}
function isObject(value){var type=typeof value;return!!value&&(type=='object'||type=='function');}
function isObjectLike(value){return!!value&&typeof value=='object';}
function isMap(value){return isObjectLike(value)&&getTag(value)==mapTag;}
function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source));}
function isMatchWith(object,source,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseIsMatch(object,source,getMatchData(source),customizer);}
function isNaN(value){return isNumber(value)&&value!=+value;}
function isNative(value){if(!isObject(value)){return false;}
var pattern=(isFunction(value)||isHostObject(value))?reIsNative:reIsHostCtor;return pattern.test(toSource(value));}
function isNull(value){return value===null;}
function isNil(value){return value==null;}
function isNumber(value){return typeof value=='number'||(isObjectLike(value)&&objectToString.call(value)==numberTag);}
function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag||isHostObject(value)){return false;}
var proto=getPrototype(value);if(proto===null){return true;}
var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return(typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString);}
function isRegExp(value){return isObject(value)&&objectToString.call(value)==regexpTag;}
function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER;}
function isSet(value){return isObjectLike(value)&&getTag(value)==setTag;}
function isString(value){return typeof value=='string'||(!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag);}
function isSymbol(value){return typeof value=='symbol'||(isObjectLike(value)&&objectToString.call(value)==symbolTag);}
function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objectToString.call(value)];}
function isUndefined(value){return value===undefined;}
function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag;}
function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag;}
var lt=createRelationalOperation(baseLt);var lte=createRelationalOperation(function(value,other){return value<=other;});function toArray(value){if(!value){return[];}
if(isArrayLike(value)){return isString(value)?stringToArray(value):copyArray(value);}
if(iteratorSymbol&&value[iteratorSymbol]){return iteratorToArray(value[iteratorSymbol]());}
var tag=getTag(value),func=tag==mapTag?mapToArray:(tag==setTag?setToArray:values);return func(value);}
function toFinite(value){if(!value){return value===0?value:0;}
value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=(value<0?-1:1);return sign*MAX_INTEGER;}
return value===value?value:0;}
function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?(remainder?result-remainder:result):0;}
function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0;}
function toNumber(value){if(typeof value=='number'){return value;}
if(isSymbol(value)){return NAN;}
if(isObject(value)){var other=isFunction(value.valueOf)?value.valueOf():value;value=isObject(other)?(other+''):other;}
if(typeof value!='string'){return value===0?value:+value;}
value=value.replace(reTrim,'');var isBinary=reIsBinary.test(value);return(isBinary||reIsOctal.test(value))?freeParseInt(value.slice(2),isBinary?2:8):(reIsBadHex.test(value)?NAN:+value);}
function toPlainObject(value){return copyObject(value,keysIn(value));}
function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER);}
function toString(value){return value==null?'':baseToString(value);}
var assign=createAssigner(function(object,source){if(nonEnumShadows||isPrototype(source)||isArrayLike(source)){copyObject(source,keys(source),object);return;}
for(var key in source){if(hasOwnProperty.call(source,key)){assignValue(object,key,source[key]);}}});var assignIn=createAssigner(function(object,source){if(nonEnumShadows||isPrototype(source)||isArrayLike(source)){copyObject(source,keysIn(source),object);return;}
for(var key in source){assignValue(object,key,source[key]);}});var assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer);});var assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer);});var at=rest(function(object,paths){return baseAt(object,baseFlatten(paths,1));});function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result;}
var defaults=rest(function(args){args.push(undefined,assignInDefaults);return apply(assignInWith,undefined,args);});var defaultsDeep=rest(function(args){args.push(undefined,mergeDefaults);return apply(mergeWith,undefined,args);});function findKey(object,predicate){return baseFind(object,getIteratee(predicate,3),baseForOwn,true);}
function findLastKey(object,predicate){return baseFind(object,getIteratee(predicate,3),baseForOwnRight,true);}
function forIn(object,iteratee){return object==null?object:baseFor(object,getIteratee(iteratee,3),keysIn);}
function forInRight(object,iteratee){return object==null?object:baseForRight(object,getIteratee(iteratee,3),keysIn);}
function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3));}
function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3));}
function functions(object){return object==null?[]:baseFunctions(object,keys(object));}
function functionsIn(object){return object==null?[]:baseFunctions(object,keysIn(object));}
function get(object,path,defaultValue){var result=object==null?undefined:baseGet(object,path);return result===undefined?defaultValue:result;}
function has(object,path){return object!=null&&hasPath(object,path,baseHas);}
function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn);}
var invert=createInverter(function(result,value,key){result[value]=key;},constant(identity));var invertBy=createInverter(function(result,value,key){if(hasOwnProperty.call(result,value)){result[value].push(key);}else{result[value]=[key];}},getIteratee);var invoke=rest(baseInvoke);function keys(object){var isProto=isPrototype(object);if(!(isProto||isArrayLike(object))){return baseKeys(object);}
var indexes=indexKeys(object),skipIndexes=!!indexes,result=indexes||[],length=result.length;for(var key in object){if(baseHas(object,key)&&!(skipIndexes&&(key=='length'||isIndex(key,length)))&&!(isProto&&key=='constructor')){result.push(key);}}
return result;}
function keysIn(object){var index=-1,isProto=isPrototype(object),props=baseKeysIn(object),propsLength=props.length,indexes=indexKeys(object),skipIndexes=!!indexes,result=indexes||[],length=result.length;while(++index<propsLength){var key=props[index];if(!(skipIndexes&&(key=='length'||isIndex(key,length)))&&!(key=='constructor'&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key);}}
return result;}
function mapKeys(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){result[iteratee(value,key,object)]=value;});return result;}
function mapValues(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){result[key]=iteratee(value,key,object);});return result;}
var merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex);});var mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer);});var omit=rest(function(object,props){if(object==null){return{};}
props=arrayMap(baseFlatten(props,1),toKey);return basePick(object,baseDifference(getAllKeysIn(object),props));});function omitBy(object,predicate){predicate=getIteratee(predicate);return basePickBy(object,function(value,key){return!predicate(value,key);});}
var pick=rest(function(object,props){return object==null?{}:basePick(object,arrayMap(baseFlatten(props,1),toKey));});function pickBy(object,predicate){return object==null?{}:basePickBy(object,getIteratee(predicate));}
function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;if(!length){object=undefined;length=1;}
while(++index<length){var value=object==null?undefined:object[toKey(path[index])];if(value===undefined){index=length;value=defaultValue;}
object=isFunction(value)?value.call(object):value;}
return object;}
function set(object,path,value){return object==null?object:baseSet(object,path,value);}
function setWith(object,path,value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseSet(object,path,value,customizer);}
var toPairs=createToPairs(keys);var toPairsIn=createToPairs(keysIn);function transform(object,iteratee,accumulator){var isArr=isArray(object)||isTypedArray(object);iteratee=getIteratee(iteratee,4);if(accumulator==null){if(isArr||isObject(object)){var Ctor=object.constructor;if(isArr){accumulator=isArray(object)?new Ctor:[];}else{accumulator=isFunction(Ctor)?baseCreate(getPrototype(object)):{};}}else{accumulator={};}}
(isArr?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object);});return accumulator;}
function unset(object,path){return object==null?true:baseUnset(object,path);}
function update(object,path,updater){return object==null?object:baseUpdate(object,path,castFunction(updater));}
function updateWith(object,path,updater,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseUpdate(object,path,castFunction(updater),customizer);}
function values(object){return object?baseValues(object,keys(object)):[];}
function valuesIn(object){return object==null?[]:baseValues(object,keysIn(object));}
function clamp(number,lower,upper){if(upper===undefined){upper=lower;lower=undefined;}
if(upper!==undefined){upper=toNumber(upper);upper=upper===upper?upper:0;}
if(lower!==undefined){lower=toNumber(lower);lower=lower===lower?lower:0;}
return baseClamp(toNumber(number),lower,upper);}
function inRange(number,start,end){start=toNumber(start)||0;if(end===undefined){end=start;start=0;}else{end=toNumber(end)||0;}
number=toNumber(number);return baseInRange(number,start,end);}
function random(lower,upper,floating){if(floating&&typeof floating!='boolean'&&isIterateeCall(lower,upper,floating)){upper=floating=undefined;}
if(floating===undefined){if(typeof upper=='boolean'){floating=upper;upper=undefined;}
else if(typeof lower=='boolean'){floating=lower;lower=undefined;}}
if(lower===undefined&&upper===undefined){lower=0;upper=1;}
else{lower=toNumber(lower)||0;if(upper===undefined){upper=lower;lower=0;}else{upper=toNumber(upper)||0;}}
if(lower>upper){var temp=lower;lower=upper;upper=temp;}
if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+(rand*(upper-lower+freeParseFloat('1e-'+((rand+'').length-1)))),upper);}
return baseRandom(lower,upper);}
var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return result+(index?capitalize(word):word);});function capitalize(string){return upperFirst(toString(string).toLowerCase());}
function deburr(string){string=toString(string);return string&&string.replace(reLatin1,deburrLetter).replace(reComboMark,'');}
function endsWith(string,target,position){string=toString(string);target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);position-=target.length;return position>=0&&string.indexOf(target,position)==position;}
function escape(string){string=toString(string);return(string&&reHasUnescapedHtml.test(string))?string.replace(reUnescapedHtml,escapeHtmlChar):string;}
function escapeRegExp(string){string=toString(string);return(string&&reHasRegExpChar.test(string))?string.replace(reRegExpChar,'\\$&'):string;}
var kebabCase=createCompounder(function(result,word,index){return result+(index?'-':'')+word.toLowerCase();});var lowerCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toLowerCase();});var lowerFirst=createCaseFirst('toLowerCase');function pad(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length){return string;}
var mid=(length-strLength)/ 2;return(createPadding(nativeFloor(mid),chars)+
string+
createPadding(nativeCeil(mid),chars));}
function padEnd(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return(length&&strLength<length)?(string+createPadding(length-strLength,chars)):string;}
function padStart(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return(length&&strLength<length)?(createPadding(length-strLength,chars)+string):string;}
function parseInt(string,radix,guard){if(guard||radix==null){radix=0;}else if(radix){radix=+radix;}
string=toString(string).replace(reTrim,'');return nativeParseInt(string,radix||(reHasHexPrefix.test(string)?16:10));}
function repeat(string,n,guard){if((guard?isIterateeCall(string,n,guard):n===undefined)){n=1;}else{n=toInteger(n);}
return baseRepeat(toString(string),n);}
function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:nativeReplace.call(string,args[1],args[2]);}
var snakeCase=createCompounder(function(result,word,index){return result+(index?'_':'')+word.toLowerCase();});function split(string,separator,limit){if(limit&&typeof limit!='number'&&isIterateeCall(string,separator,limit)){separator=limit=undefined;}
limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0;if(!limit){return[];}
string=toString(string);if(string&&(typeof separator=='string'||(separator!=null&&!isRegExp(separator)))){separator=baseToString(separator);if(separator==''&&reHasComplexSymbol.test(string)){return castSlice(stringToArray(string),0,limit);}}
return nativeSplit.call(string,separator,limit);}
var startCase=createCompounder(function(result,word,index){return result+(index?' ':'')+upperFirst(word);});function startsWith(string,target,position){string=toString(string);position=baseClamp(toInteger(position),0,string.length);return string.lastIndexOf(baseToString(target),position)==position;}
function template(string,options,guard){var settings=lodash.templateSettings;if(guard&&isIterateeCall(string,options,guard)){options=undefined;}
string=toString(string);options=assignInWith({},options,settings,assignInDefaults);var imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys);var isEscaping,isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+'|'+
interpolate.source+'|'+
(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+'|'+
(options.evaluate||reNoMatch).source+'|$','g');var sourceURL='//# sourceURL='+
('sourceURL'in options?options.sourceURL:('lodash.templateSources['+(++templateCounter)+']'))+'\n';string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){isEscaping=true;source+="' +\n__e("+escapeValue+") +\n'";}
if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '";}
if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'";}
index=offset+match.length;return match;});source+="';\n";var variable=options.variable;if(!variable){source='with (obj) {\n'+source+'\n}\n';}
source=(isEvaluating?source.replace(reEmptyStringLeading,''):source).replace(reEmptyStringMiddle,'$1').replace(reEmptyStringTrailing,'$1;');source='function('+(variable||'obj')+') {\n'+
(variable?'':'obj || (obj = {});\n')+"var __t, __p = ''"+
(isEscaping?', __e = _.escape':'')+
(isEvaluating?', __j = Array.prototype.join;\n'+"function print() { __p += __j.call(arguments, '') }\n":';\n')+
source+'return __p\n}';var result=attempt(function(){return Function(importsKeys,sourceURL+'return '+source).apply(undefined,importsValues);});result.source=source;if(isError(result)){throw result;}
return result;}
function toLower(value){return toString(value).toLowerCase();}
function toUpper(value){return toString(value).toUpperCase();}
function trim(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return string.replace(reTrim,'');}
if(!string||!(chars=baseToString(chars))){return string;}
var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join('');}
function trimEnd(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return string.replace(reTrimEnd,'');}
if(!string||!(chars=baseToString(chars))){return string;}
var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join('');}
function trimStart(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return string.replace(reTrimStart,'');}
if(!string||!(chars=baseToString(chars))){return string;}
var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join('');}
function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator='separator'in options?options.separator:separator;length='length'in options?toInteger(options.length):length;omission='omission'in options?baseToString(options.omission):omission;}
string=toString(string);var strLength=string.length;if(reHasComplexSymbol.test(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length;}
if(length>=strLength){return string;}
var end=length-stringSize(omission);if(end<1){return omission;}
var result=strSymbols?castSlice(strSymbols,0,end).join(''):string.slice(0,end);if(separator===undefined){return result+omission;}
if(strSymbols){end+=(result.length-end);}
if(isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;if(!separator.global){separator=RegExp(separator.source,toString(reFlags.exec(separator))+'g');}
separator.lastIndex=0;while((match=separator.exec(substring))){var newEnd=match.index;}
result=result.slice(0,newEnd===undefined?end:newEnd);}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);if(index>-1){result=result.slice(0,index);}}
return result+omission;}
function unescape(string){string=toString(string);return(string&&reHasEscapedHtml.test(string))?string.replace(reEscapedHtml,unescapeHtmlChar):string;}
var upperCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toUpperCase();});var upperFirst=createCaseFirst('toUpperCase');function words(string,pattern,guard){string=toString(string);pattern=guard?undefined:pattern;if(pattern===undefined){pattern=reHasComplexWord.test(string)?reComplexWord:reBasicWord;}
return string.match(pattern)||[];}
var attempt=rest(function(func,args){try{return apply(func,undefined,args);}catch(e){return isError(e)?e:new Error(e);}});var bindAll=rest(function(object,methodNames){arrayEach(baseFlatten(methodNames,1),function(key){key=toKey(key);object[key]=bind(object[key],object);});return object;});function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();pairs=!length?[]:arrayMap(pairs,function(pair){if(typeof pair[1]!='function'){throw new TypeError(FUNC_ERROR_TEXT);}
return[toIteratee(pair[0]),pair[1]];});return rest(function(args){var index=-1;while(++index<length){var pair=pairs[index];if(apply(pair[0],this,args)){return apply(pair[1],this,args);}}});}
function conforms(source){return baseConforms(baseClone(source,true));}
function constant(value){return function(){return value;};}
var flow=createFlow();var flowRight=createFlow(true);function identity(value){return value;}
function iteratee(func){return baseIteratee(typeof func=='function'?func:baseClone(func,true));}
function matches(source){return baseMatches(baseClone(source,true));}
function matchesProperty(path,srcValue){return baseMatchesProperty(path,baseClone(srcValue,true));}
var method=rest(function(path,args){return function(object){return baseInvoke(object,path,args);};});var methodOf=rest(function(object,args){return function(path){return baseInvoke(object,path,args);};});function mixin(object,source,options){var props=keys(source),methodNames=baseFunctions(source,props);if(options==null&&!(isObject(source)&&(methodNames.length||!props.length))){options=source;source=object;object=this;methodNames=baseFunctions(source,keys(source));}
var chain=!(isObject(options)&&'chain'in options)||!!options.chain,isFunc=isFunction(object);arrayEach(methodNames,function(methodName){var func=source[methodName];object[methodName]=func;if(isFunc){object.prototype[methodName]=function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__),actions=result.__actions__=copyArray(this.__actions__);actions.push({'func':func,'args':arguments,'thisArg':object});result.__chain__=chainAll;return result;}
return func.apply(object,arrayPush([this.value()],arguments));};}});return object;}
function noConflict(){if(root._===this){root._=oldDash;}
return this;}
function noop(){}
function nthArg(n){n=toInteger(n);return rest(function(args){return baseNth(args,n);});}
var over=createOver(arrayMap);var overEvery=createOver(arrayEvery);var overSome=createOver(arraySome);function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path);}
function propertyOf(object){return function(path){return object==null?undefined:baseGet(object,path);};}
var range=createRange();var rangeRight=createRange(true);function times(n,iteratee){n=toInteger(n);if(n<1||n>MAX_SAFE_INTEGER){return[];}
var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee);n-=MAX_ARRAY_LENGTH;var result=baseTimes(length,iteratee);while(++index<n){iteratee(index);}
return result;}
function toPath(value){if(isArray(value)){return arrayMap(value,toKey);}
return isSymbol(value)?[value]:copyArray(stringToPath(value));}
function uniqueId(prefix){var id=++idCounter;return toString(prefix)+id;}
var add=createMathOperation(function(augend,addend){return augend+addend;});var ceil=createRound('ceil');var divide=createMathOperation(function(dividend,divisor){return dividend / divisor;});var floor=createRound('floor');function max(array){return(array&&array.length)?baseExtremum(array,identity,baseGt):undefined;}
function maxBy(array,iteratee){return(array&&array.length)?baseExtremum(array,getIteratee(iteratee),baseGt):undefined;}
function mean(array){return baseMean(array,identity);}
function meanBy(array,iteratee){return baseMean(array,getIteratee(iteratee));}
function min(array){return(array&&array.length)?baseExtremum(array,identity,baseLt):undefined;}
function minBy(array,iteratee){return(array&&array.length)?baseExtremum(array,getIteratee(iteratee),baseLt):undefined;}
var multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand;});var round=createRound('round');var subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend;});function sum(array){return(array&&array.length)?baseSum(array,identity):0;}
function sumBy(array,iteratee){return(array&&array.length)?baseSum(array,getIteratee(iteratee)):0;}
lodash.after=after;lodash.ary=ary;lodash.assign=assign;lodash.assignIn=assignIn;lodash.assignInWith=assignInWith;lodash.assignWith=assignWith;lodash.at=at;lodash.before=before;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.castArray=castArray;lodash.chain=chain;lodash.chunk=chunk;lodash.compact=compact;lodash.concat=concat;lodash.cond=cond;lodash.conforms=conforms;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.curry=curry;lodash.curryRight=curryRight;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defaultsDeep=defaultsDeep;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.differenceBy=differenceBy;lodash.differenceWith=differenceWith;lodash.drop=drop;lodash.dropRight=dropRight;lodash.dropRightWhile=dropRightWhile;lodash.dropWhile=dropWhile;lodash.fill=fill;lodash.filter=filter;lodash.flatMap=flatMap;lodash.flatMapDeep=flatMapDeep;lodash.flatMapDepth=flatMapDepth;lodash.flatten=flatten;lodash.flattenDeep=flattenDeep;lodash.flattenDepth=flattenDepth;lodash.flip=flip;lodash.flow=flow;lodash.flowRight=flowRight;lodash.fromPairs=fromPairs;lodash.functions=functions;lodash.functionsIn=functionsIn;lodash.groupBy=groupBy;lodash.initial=initial;lodash.intersection=intersection;lodash.intersectionBy=intersectionBy;lodash.intersectionWith=intersectionWith;lodash.invert=invert;lodash.invertBy=invertBy;lodash.invokeMap=invokeMap;lodash.iteratee=iteratee;lodash.keyBy=keyBy;lodash.keys=keys;lodash.keysIn=keysIn;lodash.map=map;lodash.mapKeys=mapKeys;lodash.mapValues=mapValues;lodash.matches=matches;lodash.matchesProperty=matchesProperty;lodash.memoize=memoize;lodash.merge=merge;lodash.mergeWith=mergeWith;lodash.method=method;lodash.methodOf=methodOf;lodash.mixin=mixin;lodash.negate=negate;lodash.nthArg=nthArg;lodash.omit=omit;lodash.omitBy=omitBy;lodash.once=once;lodash.orderBy=orderBy;lodash.over=over;lodash.overArgs=overArgs;lodash.overEvery=overEvery;lodash.overSome=overSome;lodash.partial=partial;lodash.partialRight=partialRight;lodash.partition=partition;lodash.pick=pick;lodash.pickBy=pickBy;lodash.property=property;lodash.propertyOf=propertyOf;lodash.pull=pull;lodash.pullAll=pullAll;lodash.pullAllBy=pullAllBy;lodash.pullAllWith=pullAllWith;lodash.pullAt=pullAt;lodash.range=range;lodash.rangeRight=rangeRight;lodash.rearg=rearg;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.reverse=reverse;lodash.sampleSize=sampleSize;lodash.set=set;lodash.setWith=setWith;lodash.shuffle=shuffle;lodash.slice=slice;lodash.sortBy=sortBy;lodash.sortedUniq=sortedUniq;lodash.sortedUniqBy=sortedUniqBy;lodash.split=split;lodash.spread=spread;lodash.tail=tail;lodash.take=take;lodash.takeRight=takeRight;lodash.takeRightWhile=takeRightWhile;lodash.takeWhile=takeWhile;lodash.tap=tap;lodash.throttle=throttle;lodash.thru=thru;lodash.toArray=toArray;lodash.toPairs=toPairs;lodash.toPairsIn=toPairsIn;lodash.toPath=toPath;lodash.toPlainObject=toPlainObject;lodash.transform=transform;lodash.unary=unary;lodash.union=union;lodash.unionBy=unionBy;lodash.unionWith=unionWith;lodash.uniq=uniq;lodash.uniqBy=uniqBy;lodash.uniqWith=uniqWith;lodash.unset=unset;lodash.unzip=unzip;lodash.unzipWith=unzipWith;lodash.update=update;lodash.updateWith=updateWith;lodash.values=values;lodash.valuesIn=valuesIn;lodash.without=without;lodash.words=words;lodash.wrap=wrap;lodash.xor=xor;lodash.xorBy=xorBy;lodash.xorWith=xorWith;lodash.zip=zip;lodash.zipObject=zipObject;lodash.zipObjectDeep=zipObjectDeep;lodash.zipWith=zipWith;lodash.entries=toPairs;lodash.entriesIn=toPairsIn;lodash.extend=assignIn;lodash.extendWith=assignInWith;mixin(lodash,lodash);lodash.add=add;lodash.attempt=attempt;lodash.camelCase=camelCase;lodash.capitalize=capitalize;lodash.ceil=ceil;lodash.clamp=clamp;lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.cloneDeepWith=cloneDeepWith;lodash.cloneWith=cloneWith;lodash.deburr=deburr;lodash.divide=divide;lodash.endsWith=endsWith;lodash.eq=eq;lodash.escape=escape;lodash.escapeRegExp=escapeRegExp;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.floor=floor;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.get=get;lodash.gt=gt;lodash.gte=gte;lodash.has=has;lodash.hasIn=hasIn;lodash.head=head;lodash.identity=identity;lodash.includes=includes;lodash.indexOf=indexOf;lodash.inRange=inRange;lodash.invoke=invoke;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isArrayBuffer=isArrayBuffer;lodash.isArrayLike=isArrayLike;lodash.isArrayLikeObject=isArrayLikeObject;lodash.isBoolean=isBoolean;lodash.isBuffer=isBuffer;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isEqualWith=isEqualWith;lodash.isError=isError;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isInteger=isInteger;lodash.isLength=isLength;lodash.isMap=isMap;lodash.isMatch=isMatch;lodash.isMatchWith=isMatchWith;lodash.isNaN=isNaN;lodash.isNative=isNative;lodash.isNil=isNil;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isObjectLike=isObjectLike;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isSafeInteger=isSafeInteger;lodash.isSet=isSet;lodash.isString=isString;lodash.isSymbol=isSymbol;lodash.isTypedArray=isTypedArray;lodash.isUndefined=isUndefined;lodash.isWeakMap=isWeakMap;lodash.isWeakSet=isWeakSet;lodash.join=join;lodash.kebabCase=kebabCase;lodash.last=last;lodash.lastIndexOf=lastIndexOf;lodash.lowerCase=lowerCase;lodash.lowerFirst=lowerFirst;lodash.lt=lt;lodash.lte=lte;lodash.max=max;lodash.maxBy=maxBy;lodash.mean=mean;lodash.meanBy=meanBy;lodash.min=min;lodash.minBy=minBy;lodash.multiply=multiply;lodash.nth=nth;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.pad=pad;lodash.padEnd=padEnd;lodash.padStart=padStart;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.repeat=repeat;lodash.replace=replace;lodash.result=result;lodash.round=round;lodash.runInContext=runInContext;lodash.sample=sample;lodash.size=size;lodash.snakeCase=snakeCase;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.sortedIndexBy=sortedIndexBy;lodash.sortedIndexOf=sortedIndexOf;lodash.sortedLastIndex=sortedLastIndex;lodash.sortedLastIndexBy=sortedLastIndexBy;lodash.sortedLastIndexOf=sortedLastIndexOf;lodash.startCase=startCase;lodash.startsWith=startsWith;lodash.subtract=subtract;lodash.sum=sum;lodash.sumBy=sumBy;lodash.template=template;lodash.times=times;lodash.toFinite=toFinite;lodash.toInteger=toInteger;lodash.toLength=toLength;lodash.toLower=toLower;lodash.toNumber=toNumber;lodash.toSafeInteger=toSafeInteger;lodash.toString=toString;lodash.toUpper=toUpper;lodash.trim=trim;lodash.trimEnd=trimEnd;lodash.trimStart=trimStart;lodash.truncate=truncate;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.upperCase=upperCase;lodash.upperFirst=upperFirst;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.first=head;mixin(lodash,(function(){var source={};baseForOwn(lodash,function(func,methodName){if(!hasOwnProperty.call(lodash.prototype,methodName)){source[methodName]=func;}});return source;}()),{'chain':false});lodash.VERSION=VERSION;arrayEach(['bind','bindKey','curry','curryRight','partial','partialRight'],function(methodName){lodash[methodName].placeholder=lodash;});arrayEach(['drop','take'],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index){return new LazyWrapper(this);}
n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();if(filtered){result.__takeCount__=nativeMin(n,result.__takeCount__);}else{result.__views__.push({'size':nativeMin(n,MAX_ARRAY_LENGTH),'type':methodName+(result.__dir__<0?'Right':'')});}
return result;};LazyWrapper.prototype[methodName+'Right']=function(n){return this.reverse()[methodName](n).reverse();};});arrayEach(['filter','map','takeWhile'],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();result.__iteratees__.push({'iteratee':getIteratee(iteratee,3),'type':type});result.__filtered__=result.__filtered__||isFilter;return result;};});arrayEach(['head','last'],function(methodName,index){var takeName='take'+(index?'Right':'');LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0];};});arrayEach(['initial','tail'],function(methodName,index){var dropName='drop'+(index?'':'Right');LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1);};});LazyWrapper.prototype.compact=function(){return this.filter(identity);};LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head();};LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate);};LazyWrapper.prototype.invokeMap=rest(function(path,args){if(typeof path=='function'){return new LazyWrapper(this);}
return this.map(function(value){return baseInvoke(value,path,args);});});LazyWrapper.prototype.reject=function(predicate){predicate=getIteratee(predicate,3);return this.filter(function(value){return!predicate(value);});};LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;if(result.__filtered__&&(start>0||end<0)){return new LazyWrapper(result);}
if(start<0){result=result.takeRight(-start);}else if(start){result=result.drop(start);}
if(end!==undefined){end=toInteger(end);result=end<0?result.dropRight(-end):result.take(end-start);}
return result;};LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse();};LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH);};baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?('take'+(methodName=='last'?'Right':'')):methodName],retUnwrapped=isTaker||/^find/.test(methodName);if(!lodashFunc){return;}
lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value);var interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return(isTaker&&chainAll)?result[0]:result;};if(useLazy&&checkIteratee&&typeof iteratee=='function'&&iteratee.length!=1){isLazy=useLazy=false;}
var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);result.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined});return new LodashWrapper(result,chainAll);}
if(isUnwrapped&&onlyLazy){return func.apply(this,args);}
result=this.thru(interceptor);return isUnwrapped?(isTaker?result.value()[0]:result.value()):result;};});arrayEach(['pop','push','shift','sort','splice','unshift'],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?'tap':'thru',retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args);}
return this[chainName](function(value){return func.apply(isArray(value)?value:[],args);});};});baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=(lodashFunc.name+''),names=realNames[key]||(realNames[key]=[]);names.push({'name':methodName,'func':lodashFunc});}});realNames[createHybridWrapper(undefined,BIND_KEY_FLAG).name]=[{'name':'wrapper','func':undefined}];LazyWrapper.prototype.clone=lazyClone;LazyWrapper.prototype.reverse=lazyReverse;LazyWrapper.prototype.value=lazyValue;lodash.prototype.at=wrapperAt;lodash.prototype.chain=wrapperChain;lodash.prototype.commit=wrapperCommit;lodash.prototype.next=wrapperNext;lodash.prototype.plant=wrapperPlant;lodash.prototype.reverse=wrapperReverse;lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue;if(iteratorSymbol){lodash.prototype[iteratorSymbol]=wrapperToIterator;}
return lodash;}
var _=runInContext();(freeWindow||freeSelf||{})._=_;if(typeof define=='function'&&typeof define.amd=='object'&&define.amd){define('lodash',function(){return _;});}
else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_;}
freeExports._=_;}
else{root._=_;}}.call(this));
/*!
 * JavaScript Cookie v2.1.0
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
(function(factory){if(typeof define==='function'&&define.amd){define('lib/cookie',factory);}else if(typeof exports==='object'){module.exports=factory();}else{var _OldCookies=window.Cookies;var api=window.Cookies=factory();api.noConflict=function(){window.Cookies=_OldCookies;return api;};}}(function(){function extend(){var i=0;var result={};for(;i<arguments.length;i++){var attributes=arguments[i];for(var key in attributes){result[key]=attributes[key];}}
return result;}
function init(converter){function api(key,value,attributes){var result;if(typeof document==='undefined'){return;}
if(arguments.length>1){attributes=extend({path:'/'},api.defaults,attributes);if(typeof attributes.expires==='number'){var expires=new Date();expires.setMilliseconds(expires.getMilliseconds()+attributes.expires*864e+5);attributes.expires=expires;}
try{result=JSON.stringify(value);if(/^[\{\[]/.test(result)){value=result;}}catch(e){}
if(!converter.write){value=encodeURIComponent(String(value)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent);}else{value=converter.write(value,key);}
key=encodeURIComponent(String(key));key=key.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent);key=key.replace(/[\(\)]/g,escape);return(document.cookie=[key,'=',value,attributes.expires&&'; expires='+attributes.expires.toUTCString(),attributes.path&&'; path='+attributes.path,attributes.domain&&'; domain='+attributes.domain,attributes.secure?'; secure':''].join(''));}
if(!key){result={};}
var cookies=document.cookie?document.cookie.split('; '):[];var rdecode=/(%[0-9A-Z]{2})+/g;var i=0;for(;i<cookies.length;i++){var parts=cookies[i].split('=');var name=parts[0].replace(rdecode,decodeURIComponent);var cookie=parts.slice(1).join('=');if(cookie.charAt(0)==='"'){cookie=cookie.slice(1,-1);}
try{cookie=converter.read?converter.read(cookie,name):converter(cookie,name)||cookie.replace(rdecode,decodeURIComponent);if(this.json){try{cookie=JSON.parse(cookie);}catch(e){}}
if(key===name){result=cookie;break;}
if(!key){result[name]=cookie;}}catch(e){}}
return result;}
api.set=api;api.get=function(key){return api(key);};api.getJSON=function(){return api.apply({json:true},[].slice.call(arguments));};api.defaults={};api.remove=function(key,attributes){api(key,'',extend(attributes,{expires:-1}));};api.withConverter=init;return api;}
return init(function(){});}));define('coachingzone',['coach','score.init','score.oop','score.dom'],function(Coach,score){'use strict';return score.oop.Class({__name__:'Header',__init__:function(self){self.node=score.dom('#header');self.loginButton=self.node.find('.login');self.registerButton=self.node.find('.register');self.userMenu=self.node.find('.usermenu');self.profileButton=self.node.find('.profile');self.logoutButton=self.node.find('.logout');Coach.on('login',self._showUserMenu);Coach.on('logout',self._hideUserMenu);Coach.get();self.mobileNavigationButton=self.node.find('.header__button-mobile-navigation');self.mobileNavigationButton[0].addEventListener('click',self._toggleMobileNavigation);self.menuContainer=self.node.find('.header__menu-container');document.addEventListener('click',self._globalClickHandler);},_showUserMenu:function(self,coach){self.loginButton.removeClass('active');self.registerButton.removeClass('active');self.logoutButton.addClass('active');self.profileButton.addClass('active');},_hideUserMenu:function(self){self.logoutButton.removeClass('active');self.profileButton.removeClass('active');self.loginButton.addClass('active');self.registerButton.addClass('active');},_toggleUserMenu:function(self,event){event.preventDefault();self.userMenu.toggleClass('active');},_toggleMobileNavigation:function(self,event){event.preventDefault();self.mobileNavigationButton.toggleClass('active');self.menuContainer.toggleClass('active');},_globalClickHandler:function(self,event){if(event.target!==self.mobileNavigationButton[0]&&!self.mobileNavigationButton[0].contains(event.target)&&self.menuContainer.hasClass('active')&&!self.menuContainer[0].contains(event.target)){self.menuContainer.removeClass('active');self.mobileNavigationButton.removeClass('active');}}})();});define('header',['components/myfavorites','user','score.init','score.oop','score.dom'],function(myFavorites,User,score){'use strict';return score.oop.Class({__name__:'Header',__init__:function(self){self.node=score.dom('#header');self.loginButton=self.node.find('.login');self.loginButton[0].addEventListener('click',function(event){event.preventDefault();require(['components/overlay'],function(Overlay){Overlay.scenes['login'].node.find("p.not-yet-registered")[0].style.display="";Overlay.show('login');});});self.favButton=self.node.find('.favorites');self.registerButton=self.node.find('.register');self.registerButton[0].addEventListener('click',function(event){event.preventDefault();require(['components/overlay'],function(Overlay){Overlay.show('register-choose-portal');});});self.userMenu=self.node.find('.usermenu');self.profileButtonStudent=self.node.find('.profile');self.profileButtonTeacher=self.node.find('.teacher');self.profileButtonClient=self.node.find('.client');self.jobSearchStudent=self.node.find('.jobsearch');self.logoutButton=self.node.find('.logout');myFavorites.on('add',function(){self.favButton[0].setAttribute('data-count',myFavorites.count());});myFavorites.on('remove',function(){self.favButton[0].setAttribute('data-count',myFavorites.count());});User.on('login',self._showUserMenu);User.on('logout',self._hideUserMenu);User.get();self.mobileNavigationButton=self.node.find('.header__button-mobile-navigation');self.mobileNavigationButton[0].addEventListener('click',self._toggleMobileNavigation);self.menuContainer=self.node.find('.header__menu-container');document.addEventListener('click',self._globalClickHandler);},_showUserMenu:function(self,user){self.loginButton.removeClass('active');self.registerButton.removeClass('active');self.logoutButton.addClass('active');if(user){if(user.teacher){self.profileButtonTeacher.addClass('active');}else if(user.client){self.profileButtonClient.addClass('active');}else{self.profileButtonStudent.addClass('active');self.jobSearchStudent.addClass('active');}}},_hideUserMenu:function(self){self.logoutButton.removeClass('active');self.profileButtonStudent.removeClass('active');self.profileButtonTeacher.removeClass('active');self.profileButtonClient.removeClass('active');self.loginButton.addClass('active');self.registerButton.addClass('active');self.jobSearchStudent.removeClass('active');},_toggleUserMenu:function(self,event){event.preventDefault();self.userMenu.toggleClass('active');},_toggleMobileNavigation:function(self,event){event.preventDefault();self.mobileNavigationButton.toggleClass('active');self.menuContainer.toggleClass('active');},_globalClickHandler:function(self,event){if(event.target!==self.mobileNavigationButton[0]&&!self.mobileNavigationButton[0].contains(event.target)&&self.menuContainer.hasClass('active')&&!self.menuContainer[0].contains(event.target)){self.menuContainer.removeClass('active');self.mobileNavigationButton.removeClass('active');}}})();});define('selfcare',['client','score.init','score.oop','score.dom'],function(Client,score){'use strict';return score.oop.Class({__name__:'Header',__init__:function(self){self.node=score.dom('#header');self.loginButton=self.node.find('.login');self.registerButton=self.node.find('.register');self.userMenu=self.node.find('.usermenu');self.profileButton=self.node.find('.profile');self.logoutButton=self.node.find('.logout');Client.on('login',self._showUserMenu);Client.on('logout',self._hideUserMenu);Client.get();self.mobileNavigationButton=self.node.find('.header__button-mobile-navigation');self.mobileNavigationButton[0].addEventListener('click',self._toggleMobileNavigation);self.menuContainer=self.node.find('.header__menu-container');document.addEventListener('click',self._globalClickHandler);},_showUserMenu:function(self,client){self.loginButton.removeClass('active');self.registerButton.removeClass('active');self.logoutButton.addClass('active');self.profileButton.addClass('active');},_hideUserMenu:function(self){self.logoutButton.removeClass('active');self.profileButton.removeClass('active');self.loginButton.addClass('active');self.registerButton.addClass('active');},_toggleUserMenu:function(self,event){event.preventDefault();self.userMenu.toggleClass('active');},_toggleMobileNavigation:function(self,event){event.preventDefault();self.mobileNavigationButton.toggleClass('active');self.menuContainer.toggleClass('active');},_globalClickHandler:function(self,event){if(event.target!==self.mobileNavigationButton[0]&&!self.mobileNavigationButton[0].contains(event.target)&&self.menuContainer.hasClass('active')&&!self.menuContainer[0].contains(event.target)){self.menuContainer.removeClass('active');self.mobileNavigationButton.removeClass('active');}}})();});define('teachersroom',['teacher','score.init','score.oop','score.dom'],function(Teacher,score){'use strict';return score.oop.Class({__name__:'Header',__init__:function(self){self.node=score.dom('#header');self.loginButton=self.node.find('.login');self.registerButton=self.node.find('.register');self.userMenu=self.node.find('.usermenu');self.profileButton=self.node.find('.profile');self.logoutButton=self.node.find('.logout');Teacher.on('login',self._showUserMenu);Teacher.on('logout',self._hideUserMenu);Teacher.get();self.mobileNavigationButton=self.node.find('.header__button-mobile-navigation');self.mobileNavigationButton[0].addEventListener('click',self._toggleMobileNavigation);self.menuContainer=self.node.find('.header__menu-container');document.addEventListener('click',self._globalClickHandler);},_showUserMenu:function(self,teacher){self.loginButton.removeClass('active');self.registerButton.removeClass('active');self.logoutButton.addClass('active');self.profileButton.addClass('active');},_hideUserMenu:function(self){self.logoutButton.removeClass('active');self.profileButton.removeClass('active');self.loginButton.addClass('active');self.registerButton.addClass('active');},_toggleUserMenu:function(self,event){event.preventDefault();self.userMenu.toggleClass('active');},_toggleMobileNavigation:function(self,event){event.preventDefault();self.mobileNavigationButton.toggleClass('active');self.menuContainer.toggleClass('active');},_globalClickHandler:function(self,event){if(event.target!==self.mobileNavigationButton[0]&&!self.mobileNavigationButton[0].contains(event.target)&&self.menuContainer.hasClass('active')&&!self.menuContainer[0].contains(event.target)){self.menuContainer.removeClass('active');self.mobileNavigationButton.removeClass('active');}}})();});var spunQ=spunQ||{};spunQ.Adition=spunQ.Adition||{}
spunQ.Adition.clicked=spunQ.Adition.clicked||1;var adition=adition||{};adition.srq=adition.srq||[];(function(){var script=document.createElement('script');script.type='text/javascript';script.src=(document.location.protocol==='https:'?'https:':'http:')+'//imagesrv.adition.com/js/srp.js';script.charset='utf-8';script.async=true;var firstScript=document.getElementsByTagName('script')[0];firstScript.parentNode.insertBefore(script,firstScript);})();spunQ.Adition.init=function(func){if(typeof func!=='function'){return;}
adition.srq.push(func);};spunQ.Adition.renderSlot=function(slot){if(typeof adition==='undefined'){return;}
adition.srq.push(function(api){api.events.onNoBanner(function(renderSlotElement){var adContainer=document.getElementById(renderSlotElement.id);adContainer.parentNode.className+=" hideAd";});api.renderSlot(slot);});};define('client',['alertify','bluebird','lib/cookie','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Cookie,score){return score.oop.Class({__name__:'Client',__static__:{COOKIEWATCHER_INTERVAL:1000,KEEPALIVE_INTERVAL:600000},__events__:['login','logout'],__init__:function(self){self.on('login',self._login);self.on('logout',self._logout);self._startCookieWatcher();self._keepAlive();window.onbeforeunload=function(e){var message="Your confirmation message goes here.",e=e||window.event;if(e){e.returnValue=message;}
return message;};},get:function(self){if(!Cookie.get('MJESSID')){self.trigger('logout');return BPromise.resolve(null);}
if(self.client){return BPromise.resolve(self.client);}
if(self.getPromise){return self.getPromise;}
self.getPromise=score.ajax.rest.getJSON('/rest/selfcare/client').then(function(data){self.getPromise=null;if(data.client&&data.client.id){self.trigger('login',data.client,false);return data.client;}
self.trigger('logout');return null;}).catch(function(){self.getPromise=null;self.trigger('logout');});return self.getPromise;},login:function(self,data){return score.ajax.rest.postJSON('/rest/client/_login',data).then(function(data){if(!data.client){alertify.error('Benutzername oder Passwort falsch.');return;}
self.trigger('login',data.client,true);alertify.success('Sie haben sich erfolgreich angemeldet.');return data.client;});},_login:function(self,client){self.client=client;},_logout:function(self){self.client=null;Cookie.remove('MJESSID',{path:'/',domain:'meinjob.at',secure:false});Cookie.remove('MJESSID',{path:'/',secure:false});},_startCookieWatcher:function(self){setInterval(function(){if(!Cookie.get('MJESSID')&&self.client){self.trigger('logout');}else if(Cookie.get('MJESSID')&&!self.client){self.get();}},self.COOKIEWATCHER_INTERVAL);},_keepAlive:function(self){setInterval(function(){score.ajax('/keepalive');},self.KEEPALIVE_INTERVAL);}})();});define('coach',['alertify','bluebird','lib/cookie','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Cookie,score){return score.oop.Class({__name__:'Coach',__static__:{COOKIEWATCHER_INTERVAL:1000,KEEPALIVE_INTERVAL:600000},__events__:['login','logout'],__init__:function(self){self.on('login',self._login);self.on('logout',self._logout);self._startCookieWatcher();self._keepAlive();window.onbeforeunload=function(e){var message="Your confirmation message goes here.",e=e||window.event;if(e){e.returnValue=message;}
return message;};},get:function(self){if(!Cookie.get('MJESSID')){self.trigger('logout');return BPromise.resolve(null);}
if(self.coach){return BPromise.resolve(self.coach);}
if(self.getPromise){return self.getPromise;}
self.getPromise=score.ajax.rest.getJSON('/rest/coachingzone/coach').then(function(data){self.getPromise=null;if(data.coach&&data.coach.id){self.trigger('login',data.coach,false);return data.coach;}
self.trigger('logout');return null;}).catch(function(){self.getPromise=null;self.trigger('logout');});return self.getPromise;},login:function(self,data){return score.ajax.rest.postJSON('/rest/coach/_login',data).then(function(data){if(!data.coach){alertify.error('Benutzername oder Passwort falsch.');return;}
self.trigger('login',data.coach,true);alertify.success('Sie haben sich erfolgreich angemeldet.');return data.coach;});},_login:function(self,coach){self.coach=coach;},_logout:function(self){self.coach=null;Cookie.remove('MJESSID',{path:'/',domain:'meinjob.at',secure:false});Cookie.remove('MJESSID',{path:'/',secure:false});},_startCookieWatcher:function(self){setInterval(function(){if(!Cookie.get('MJESSID')&&self.coach){self.trigger('logout');}else if(Cookie.get('MJESSID')&&!self.coach){self.get();}},self.COOKIEWATCHER_INTERVAL);},_keepAlive:function(self){setInterval(function(){score.ajax('/keepalive');},self.KEEPALIVE_INTERVAL);}})();});define('coachingzone/mainmenu',['statictext','ractive','rv!rvtpl/coachingzone/mainmenu','lodash','coach','score.init','score.oop'],function(StaticText,Ractive,template,_,Coach,score){return score.oop.Class({__name__:'MainMenu',__static__:{instance:null,LOAD_STATIC_TEXTS:['coach_menu_text'],},__events__:['message-click','student-click'],__init__:function(self){self.ractive=new Ractive({el:'[data-component=mainmenu]',template:template});StaticText.loadTexts(self.ractive,self.LOAD_STATIC_TEXTS);self.ractive.on('menuclick',function(a){if(a.context.href==='#/schueler'){return self.trigger('student-click');}
if(a.context.href==='#/nachrichten'){return self.trigger('message-click');}});self._loadPromise=self._loadData().then(function(data){self.ractive.set('menu.entries',data.menu.entries);Coach.get().then(self._hasNewMessages);if(self._hash){return self._handleHash();}});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();window.setInterval(function(){Coach.get().then(self._hasNewMessages);},5000);},_hashChanged:function(self){self._hash=document.location.hash;self._handleHash();},_handleHash:function(self){var entries=self.ractive.get('menu.entries');if(!self._hash||!entries||self._hash.indexOf('#/')!==0){return;}
_.forEach(entries,function(entry,key){if(self._hash!=='#/'&&entry.href==='#/'){return;}
entry.isActive=self._hash.indexOf(entry.href)===0;});self.ractive.set('menu.entries',entries);},_loadData:function(self){return score.ajax.rest.getJSON('rest/coachingzone/mainmenu');},_hasNewMessages:function(self){var entries=self.ractive.get('menu.entries');if(!entries){return;}
score.ajax.rest.getJSON('/rest/coachingzone/message').then(function(data){if(!data.messages){return;}
var hasNewMessages=false;for(var i=0;i<data.messages.length;i++){if(data.messages[i].isNew){hasNewMessages=true;break;}}
for(var i=0;i<entries.length;i++){if(entries[i].href==='#/nachrichten'){entries[i].hasNewMessages=hasNewMessages;break;}}
self.ractive.set('menu.entries',entries);});}});});define('coachingzone/register',['bluebird','components/form','score.init','score.oop','score.ajax.rest'],function(BPromise,Form,score){'use strict';return score.oop.Class({__name__:'Register',__init__:function(self,form){new BPromise(function(resolve,reject){window.onbeforeunload=null;return resolve();});self._timeouts={'_nameInputHandler':null,'_emailInputHandler':null,'_passwordInputHandler':null};self.form=form;self.form.addEventListener('submit',function(e){e.preventDefault();var data=Form.serialize(self.form);if(self._validate(data)){score.ajax.rest.postJSON('/rest/coach/_register',data).then(function(result){window.location.href='/coach/registrieren/done';});}});self.firstNameInput=self.form.querySelector('input[name=firstName]');self.firstNameInput.addEventListener('keyup',self._nameInputHandler);self.firstNameInput.addEventListener('blur',self._nameInputHandler);self.firstNameInput.addEventListener('change',self._nameInputHandler);self.nameError=self.form.querySelector('.error-message__name');self.lastNameInput=self.form.querySelector('input[name=lastName]');self.lastNameInput.addEventListener('keyup',self._nameInputHandler);self.lastNameInput.addEventListener('blur',self._nameInputHandler);self.lastNameInput.addEventListener('change',self._nameInputHandler);self.emailInput=self.form.querySelector('input[name=email]');self.emailInput.addEventListener('keyup',self._emailInputHandler);self.emailInput.addEventListener('blur',self._emailInputHandler);self.emailInput.addEventListener('change',self._emailInputHandler);self.emailError=self.form.querySelector('.error-message__email');self.passwordInput=self.form.querySelector('input[name=password]');self.password2Input=self.form.querySelector('input[name=password2]');self.passwordInput.addEventListener('keyup',self._passwordInputHandler);self.passwordInput.addEventListener('blur',self._passwordInputHandler);self.passwordInput.addEventListener('change',self._passwordInputHandler);self.password2Input.addEventListener('keyup',self._passwordInputHandler);self.password2Input.addEventListener('blur',self._passwordInputHandler);self.password2Input.addEventListener('change',self._passwordInputHandler);self.passwordError=self.form.querySelector('.error-message__password');self.consentInput=self.form.querySelector('input[name=consent]');self.consentInput.addEventListener('keyup',self._validateConsent);self.consentInput.addEventListener('blur',self._validateConsent);self.consentInput.addEventListener('change',self._validateConsent);self.consentError=self.form.querySelector('.error-message__consent');self.gtcInput=self.form.querySelector('input[name=gtc]');self.gtcInput.addEventListener('keyup',self._validateGtc);self.gtcInput.addEventListener('blur',self._validateGtc);self.gtcInput.addEventListener('change',self._validateGtc);self.gtcError=self.form.querySelector('.error-message__gtc');self.form.addEventListener('change',function(){self._validateForm();});self._validateTimeout=setTimeout(function(){self._validateForm();},1000);_.forEach(self.form.querySelectorAll('input[required=required]'),function(field){if(field.name==='password'){return;}
field.classList.add('invalid');});},_nameInputHandler:function(self,event){if(self.firstNameInput.value!=''&&self.lastNameInput.value!=''){self.firstNameInput.classList.remove('invalid');self.firstNameInput.classList.add('valid');self.lastNameInput.classList.remove('invalid');self.lastNameInput.classList.add('valid');self.nameError.classList.remove('visible');}else{self.firstNameInput.classList.remove('valid');self.firstNameInput.classList.add('invalid');self.lastNameInput.classList.remove('valid');self.lastNameInput.classList.add('invalid');self.nameError.classList.add('visible');self.nameError.innerHTML='Bitte geben Sie Vor- und Nachname an.';}},_passwordInputHandler:function(self,event){clearTimeout(self._timeouts['_passwordInputHandler']);self._timeouts['_passwordInputHandler']=setTimeout(function(){if(!self.passwordInput.value&&self.passwordInput.value===self.password2Input.value){self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='';}else if(self.passwordInput.value&&self.passwordInput.value===self.password2Input.value){score.ajax.rest.postJSON('/rest/user/_passwordpolicy',{'value':self.passwordInput.value}).then(function(){self.password2Input.classList.remove('invalid');self.password2Input.classList.add('valid');self.passwordError.classList.remove('visible');}).catch(function(){self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='Das Passwort muss aus mindestens 6 Zeichen bestehen.';});}else{self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='Die Passwörter stimmen nicht überein.';}
self._validateForm();},500);},_emailInputHandler:function(self,event){clearTimeout(self._timeouts['_emailInputHandler']);self._timeouts['_emailInputHandler']=setTimeout(function(){self._validateEmail(self.emailInput.value).then(function(email){self.emailInput.classList.remove('invalid');self.emailInput.classList.add('valid');self.emailError.classList.remove('visible');}).caught(function(email){self.emailInput.classList.add('invalid');self.emailInput.classList.remove('valid');}).finally(function(){self._validateForm();});},500);},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!email){self.emailError.classList.add('visible');self.emailError.innerText='';return reject(Error(email));}
if(!isEmail){self.emailError.classList.add('visible');self.emailError.innerText='Die Mail-Adresse ist ungültig.';return reject(Error(email));}
score.ajax.rest.getJSON('/rest/user/username-unique/'+encodeURIComponent(email)).then(function(data){resolve(email);}).catch(function(error){self.emailError.classList.add('visible');self.emailError.innerText='Die Mail-Adresse ist bereits vorhanden.';return reject(Error(email));});});},_validateConsent:function(self){if(self.consentInput.checked){self.consentInput.classList.remove('invalid');self.consentInput.classList.add('valid');self.consentError.classList.remove('visible');}else{self.consentInput.classList.remove('valid');self.consentInput.classList.add('invalid');self.consentError.classList.add('visible');self.consentError.innerHTML='Zustimmung notwendig!';};},_validateGtc:function(self){if(self.gtcInput.checked){self.gtcInput.classList.remove('invalid');self.gtcInput.classList.add('valid');self.gtcError.classList.remove('visible');}else{self.gtcInput.classList.remove('valid');self.gtcInput.classList.add('invalid');self.gtcError.classList.add('visible');self.gtcError.innerHTML='Zustimmung notwendig!';};},_validateForm:function(self){var data=Form.serialize(self.form);return self.form.querySelector('button[type=submit]').disabled=!self._validate(data);},_validate:function(self,data){var noErrors=self.form.querySelectorAll('input.invalid').length===0;return noErrors&&data.email&&data.email.length>=7&&data.password&&data.password===data.password2&&data.firstName&&data.firstName.length>1&&data.lastName&&data.lastName.length>1&&data.gtc&&data.consent;},})});define('coachingzone/router',['coachingzone/stage','score.init','score.oop','score.router'],function(stage,score){var Router=score.oop.Class({__name__:'Router',__parent__:score.router,__init__:function(self){self.addRoute('coach-data','/daten',function(){stage.show('coach-data');});self.addRoute('students','/schueler',function(){stage.show('student');});self.addRoute('messages','/nachrichten',function(){stage.show('message');});self.addRoute('student-profile','/schueler/{id}/profile',function(vars){stage.show('student',{id:vars.id,profile:true});});self.addRoute('student','/schueler/{id}',function(vars){stage.show('student',{id:vars.id});});self.addRoute('message','/nachrichten/{id}',function(vars){stage.show('message',vars.id);});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();},_hashChanged:function(self,event){var hash=document.location.hash;if(!hash||hash==='#'){document.location.hash='#/daten';}
var url=document.location.hash.substr(1);self.load(url);}});return new Router();});define('coachingzone/scene',['bluebird','coach','score.init','score.oop','score.dom.theater','../transitions/fade'],function(BPromise,Coach,score){'use strict';return score.oop.Class({__name__:'BaseCoachingzoneScene',__parent__:score.dom.theater.Scene,__events__:['createRactive'],__init__:function(self,stage,name){self.name=name;self.__super__(stage,name,score.dom('[data-component="'+name+'"]'));self.on('createRactive',self.onCreateRactive);},onCreateRactive:function(self){self.ractive.set('login',{email:'',password:''});self.ractive.set('_coach',Coach.get());Coach.on('logout',function(){self.ractive.set('_coach',BPromise.resolve());});Coach.on('login',function(coach){self.ractive.set('_coach',BPromise.resolve(coach));});self.ractive.on('set',function(event,keyPath){self.ractive.set(self.MODEL.name+'.result'+keyPath,event.context);self.ractive.set('search'+keyPath,null);});self.ractive.on('unset',function(event,keyPath){self.ractive.set(self.MODEL.name+'.result'+keyPath,null);});self.ractive.on('add',function(event,keyPath){self.ractive.set('search'+keyPath+'.value',null);if(self.ractive.get(self.MODEL.name+'.result'+keyPath)==null){self.ractive.set(self.MODEL.name+'.result'+keyPath,[]);}
self.ractive.push(self.MODEL.name+'.result'+keyPath,event.context);self.ractive.update(self.MODEL.name+'.result'+keyPath);});self.ractive.on('remove',function(event,keyPath){event.original.preventDefault();if(self.ractive.get(self.MODEL.name+'.result').isDeleted){return;}
self.ractive.splice(self.MODEL.name+'.result'+keyPath,event.index.key,1);self.ractive.update(self.MODEL.name+'.result'+keyPath);});self.ractive.on('navlist',function(event,direction,itemPath){var items=self.ractive.get(itemPath+'.result.result');var active=self.ractive.get(itemPath+'.active');if(direction==='down'){if(active===undefined){active=0;}else{active++;if(active===items.length){active=0;}}}else{if(active===undefined){active=items.length-1;}else{active--;if(active<0){active=items.length-1;}}}
self.ractive.set(itemPath+'.active',active);});self.ractive.on('markActive',function(event,index,path){self.ractive.set(path,index);});self.ractive.on('select',function(event,member,path,append){var active=self.ractive.get(path+'.active');if(active===undefined){return;}
var item=self.ractive.get(path+'.result.result.'+active);if(append){self.ractive.push(self.MODEL.name+'.result'+member,item);self.ractive.set(path+'.value',null);self.ractive.set(path+'.active',null);self.ractive.set(path+'.show',false);self.ractive.update(self.MODEL.name+'.result'+member);}else{self.ractive.set(self.MODEL.name+'.result'+member,item);self.ractive.set(path,null);}});self.ractive.on('hideSearch',function(event,keyPath){window.setTimeout(function(){self.ractive.set(keyPath,false);},150);})},_getRactive:function(self){if(self.ractive){return BPromise.resolve(self.ractive);}
return new BPromise(function(resolve,reject){require(['ractive','rv!rvtpl/coachingzone/'+self.name,'ractive-events-keys','ractive-promise-alt'],function(Ractive,template,keys){var CKEditor=Ractive.extend({template:'<textarea placeholder="{{placeholder}}" disabled="{{disabled}}">{{{text}}}</textarea>',onrender:function(){var _ractive=this;CKEDITOR.timestamp='1578918270';var placeholder='placeholder'in this.find('textarea').attributes?this.find('textarea').attributes['placeholder'].textContent:null;var object={placeholder:placeholder};var editor=this.editor=CKEDITOR.replace(this.find('textarea'),object);editor.on('change',function(evt){_ractive.set('text',evt.editor.getData());});},onteardown:function(){this.editor.destroy();}});var DatetimePicker=Ractive.extend({template:'<input class="flatpickr" data-default-date="{{text}}"/>',onrender:function(){var _ractive=this;new Flatpickr(this.find('input.flatpickr'),{enableTime:true,enableSeconds:false,allowInput:true,weekNumbers:true,onChange:function(dateObj,dateStr,instance){_ractive.set('text',parseInt(dateObj.getTime()/ 1000));}});}});self.ractive=new Ractive({el:self.node,template:template,adapt:['promise-alt'],events:{enter:keys.enter,downarrow:keys.downarrow,uparrow:keys.uparrow},components:{'ck-editor':CKEditor,'datetime-picker':DatetimePicker}});self.trigger('createRactive');resolve(self.ractive);});});},_loadData:function(self){return BPromise.resolve('create a _loadData() function in your Scene');},_loadSearchData:function(self,resource){return score.ajax.rest.getJSON('rest/'+resource+'?q=1');},_search:function(self,type,search,singleType,forceFetch){if(self.searchTimeout){clearTimeout(self.searchTimeout);}
var searchData=self.ractive.get('search.'+type+'.data')||[];var promise;if(!searchData.length||forceFetch){promise=new BPromise(function(resolve){self.searchTimeout=setTimeout(function(){self._loadSearchData(singleType?singleType.toLowerCase():type.toLowerCase()).then(function(data){self.ractive.set('search.'+type+'.data',data.results);return resolve(data.results);});},600);});}else{promise=BPromise.resolve(searchData);}
var p=promise.then(function(data){var ids=_.map(self.ractive.get(self.MODEL.name+'.result.'+type),'id');return _.filter(data,function(object){return ids.indexOf(object.id)===-1;});}).then(function(data){if(search==='*'){return data;}
search=search.toLowerCase();return _.filter(data,function(object){for(var key in object){var value=object[key];if(typeof value==='number'){value+='';}
if(typeof value==='string'&&value.toLowerCase().indexOf(search)>=0){return true;}}});});self.ractive.set('search.'+type+'.result',p);},_registerSearch:function(self,type,singleType,forceFetch){self.ractive.observe('search.'+type+'.show',function(newValue,oldValue){if(newValue){self._search(type,'*',singleType,forceFetch);}});self.ractive.observe('search.'+type+'.value',function(newValue,oldValue){if(newValue){self._search(type,newValue,singleType,forceFetch);}else{self.ractive.set('search.'+type+'.result',newValue);}});},_beforeSave:function(){return true;}});});define('coachingzone/scenes/coach-data',['coachingzone/scene','alertify','coach','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,Coach,score){'use strict';return score.oop.Class({__name__:'CoachDataScene',__parent__:Scene,__static__:{MODEL:{name:'coach'}},onCreateRactive:function(self){self.__super__();self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
_event.node.disabled=true;score.ajax.rest.putJSON('rest/coachingzone/'+self.MODEL.name.toLowerCase(),object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);}).catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},_load:function(self){return self._getRactive();},_activate:function(self){Coach.get().then(function(coach){if(!coach){return;}
self.ractive.set(self.MODEL.name,self._loadData());});},_loadData:function(self){return score.ajax.rest.getJSON('rest/coachingzone/'+self.MODEL.name).then(function(data){return data[self.MODEL.name];});},_validate:function(self,data){if(data.password!==data.password2){alertify.error('Die beiden Passwörter stimmen nicht überein.');return false;}
if(!data||!data.id){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.email||!data.firstName||!data.lastName||!data.gender){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},_beforeSave:function(self,coach){if(coach.password===''){delete coach.password;delete coach.password2;}
return true;},_beforeCreate:function(self,coach){return delete coach.password2;},_beforeSetData:function(self,key,value){if(key===self.MODEL.name&&value){value.password=null;value.password2=null;}},});});define('coachingzone/scenes/message',['coachingzone/scene','alertify','user','bluebird','lodash','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,User,BPromise,_,score){'use strict';return score.oop.Class({__name__:'MessageScene',__parent__:Scene,__static__:{MODEL:{name:'message'}},onCreateRactive:function(self){self.__super__();self.ractive.on('edit',function(event){if(event.context.isNew){self.setRead(event.context.id).then(function(data){window.location.href='#/nachrichten/'+event.context.id;});}else{window.location.href='#/nachrichten/'+event.context.id;}});self.ractive.on('new',function(event){window.location.href='#/nachrichten/new';});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});self.ractive.on('delete',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.delete(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('restore',function(event){event.original.stopPropagation();if(!event.context.isDeleted){return;}
self.restore(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('mark-as-new',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setNew(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('mark-as-read',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setRead(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('back',function(event){window.location.href='#/nachrichten';});require('coachingzone/mainmenu').instance.on('message-click',function(){window.location.href='#/nachrichten';});self.ractive.on('toggleIsBlacklisted',self._toggleIsBlacklisted);User.get().then(function(user){if(user){self.ractive.set('isBlacklisted',user.isBlacklisted);}});},_toggleIsBlacklisted:function(self,event){if(event!==undefined){event.original.preventDefault();if(event.context.isBlacklisted){var message='Wirklich keine Emails mehr erhalten?';}else{var message='Wirklich Emails aktivieren?';}
alertify.confirm(message,function(){self.ractive.toggle('isBlacklisted').then(function(result){event.node.checked=!self.ractive.get('isBlacklisted');score.ajax.rest.putJSON('rest/user',{'isBlacklisted':!event.node.checked}).then(function(result){alertify.success('Daten erfolgreich gespeichert.');});});},function(){});}},get:function(self,id){return self._loadData(id);},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
var create=!_event.context.id;_event.node.disabled=true;var promise;if(create){promise=score.ajax.rest.postJSON('rest/coachingzone/'+self.MODEL.name.toLowerCase(),object).then(function(data){window.location.href='#/nachrichten/'+data[self.MODEL.name].id;});}else{promise=score.ajax.rest.putJSON('rest/coachingzone/'+self.MODEL.name.toLowerCase()+'/'+object.id,object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);});}
promise.catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},delete:function(self,id){return self.setStatus(id,2);},restore:function(self,id){return self.setStatus(id,-1);},setRead:function(self,id){return self.setStatus(id,1);},setNew:function(self,id){return self.setStatus(id,0);},setStatus:function(self,id,status){return score.ajax.rest.putJSON('rest/coachingzone/'+self.MODEL.name.toLowerCase()+'/'+id,{'status':status});},_updateMesssage:function(self,message){var messages=self.ractive.get('_data.result.messages');if(messages){var idx=_.findIndex(messages,{'id':message.id});self.ractive.set('_data.result.messages.'+idx,message);}
if(self.ractive.get(self.MODEL.name)){self.ractive.set(self.MODEL.name+'.result',message);}},_load:function(self,id){var ractive=self._getRactive();ractive.then(function(){if(id){if(id==='new'){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));}else{self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data[self.MODEL.name];}));}
self.ractive.update(self.MODEL.name+'.result');}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/coachingzone/'+self.MODEL.name.toLowerCase()+(id?'/'+id:'');return score.ajax.rest.getJSON(url);},_validate:function(self,data){if(!data){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.subject||!data.recipient){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},});});define('coachingzone/scenes/student',['coachingzone/scene','alertify','bluebird','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,BPromise,score){'use strict';return score.oop.Class({__name__:'StudentScene',__parent__:Scene,__static__:{MODEL:{name:'student'}},onCreateRactive:function(self){self.__super__();self.ractive.on('edit',function(event){window.location.href='#/schueler/'+event.context.id;});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});self.ractive.on('delete',function(event){event.original.preventDefault();self.delete(event);return false;});self.ractive.on('back',function(event){if(event.context.student){window.location.href='#/schueler/'+event.context.student.id;}else{window.location.href='#/schueler';}});self.ractive.on('profile',function(event){window.location.href='#/schueler/'+event.context.id+'/profile';});require('coachingzone/mainmenu').instance.on('student-click',function(){window.location.href='#/schueler';});},delete:function(self,_event){alertify.confirm('Willst du das Coaching von '+_event.context.title+' wirklich beenden?',function(){var studentId=_event.context.id;score.ajax.rest.deleteJSON('/rest/coachingzone/student/'+studentId).then(function(result){if(result){self.ractive.splice('_data.result.students',_event.index.key,1);alertify.success('Coaching beendet.');}});},function(){});},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(object&&object.student){object=object.student;_event.context=_event.context.student;}
if(!self._beforeSave(object)){return;}
var create=!_event.context.id;_event.node.disabled=true;var promise;if(create){promise=score.ajax.rest.postJSON('rest/coachingzone/'+self.MODEL.name.toLowerCase(),object).then(function(data){window.location.href='#/schueler/'+data[self.MODEL.name].id;});}else{promise=score.ajax.rest.putJSON('rest/coachingzone/'+self.MODEL.name.toLowerCase()+'/'+object.id,object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);});}
promise.catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},_load:function(self,vars){var ractive=self._getRactive();ractive.then(function(){if(vars){var id=vars.id;var profile=vars.profile;if(profile){self.ractive.set(self.MODEL.name,self._loadProfileData(id).then(function(data){return data;}));self.ractive.set('profile','profile');}else{self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data[self.MODEL.name];}));self.ractive.set('profile',undefined);}}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/coachingzone/'+self.MODEL.name.toLowerCase()+(id?'/'+id:'');return score.ajax.rest.getJSON(url).then(function(data){if(data.students){data.students.forEach(function(part,index,array){array[index].studentRequestsApprovedCount=_.sumBy(part.studentRequests,function(o){return o.studentApproved?1:0});});}
return data;});},_loadProfileData:function(self,id){return score.ajax.rest.getJSON('/rest/coachingzone/student-profile/'+id);},_validate:function(self,data){if(data&&data.student){data=data.student;}
if(!data||!data.user){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.user.name||!data.user.email){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},});});define('coachingzone/stage',['coachingzone/scenes/coach-data','coachingzone/scenes/student','coachingzone/scenes/message','score.init','score.dom.theater'],function(CoachDataScene,StudentScene,MessageScene,score){'use strict';var stage=new score.dom.theater.Stage(score.dom('#stage'));new CoachDataScene(stage,'coach-data');new StudentScene(stage,'student');new MessageScene(stage,'message');return stage;});define('components/form',function(){'use strict';var serialize=function(form){if(!form||form.nodeName!=="FORM"){return;}
var i,j,o={},r;for(i=form.elements.length-1;i>=0;i=i-1){if(form.elements[i].name===""){continue;}
switch(form.elements[i].nodeName){case'INPUT':switch(form.elements[i].type){case'text':case'hidden':case'password':case'button':case'reset':case'submit':case'email':o[form.elements[i].name]=form.elements[i].value;break;case'checkbox':if(form.elements[i].checked){if(o[form.elements[i].name]&&Object.prototype.toString.call(o[form.elements[i].name])!=='[object Array]'){o[form.elements[i].name]=[o[form.elements[i].name]];}
if(o[form.elements[i].name]&&Object.prototype.toString.call(o[form.elements[i].name])==='[object Array]'){o[form.elements[i].name].push(form.elements[i].value)}else{o[form.elements[i].name]=form.elements[i].value;}}
break;case'radio':if(form.elements[i].checked){o[form.elements[i].name]=form.elements[i].value;}
break;case'file':break;}
break;case'TEXTAREA':o[form.elements[i].name]=form.elements[i].value;break;case'SELECT':switch(form.elements[i].type){case'select-one':o[form.elements[i].name]=form.elements[i].value;break;case'select-multiple':r=[];for(j=form.elements[i].options.length-1;j>=0;j=j-1){if(form.elements[i].options[j].selected){r.push(form.elements[i].options[j].value);}}
o[form.elements[i].name]=r;break;}
break;case'BUTTON':switch(form.elements[i].type){case'reset':case'submit':case'button':o[form.elements[i].name]=form.elements[i].value;break;}
break;}}
return o;};var toJSON=function(form){return JSON.stringify(serialize(form));};return{serialize:serialize,toJSON:toJSON};});define('components/myfavorites',['alertify','bluebird','lodash','lib/cookie','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,_,Cookies,score){'use strict';var MyFavorites=score.oop.Class({__name__:'MyFavorites',__static__:{LOCAL_STORAGE:function(){var test='test';try{localStorage.setItem(test,test);localStorage.removeItem(test);return true;}catch(e){return false;}}(),MAX_STORAGE_TIME:1000*60*60*24,COOKIE_NAME:'favorites'},__events__:['add','remove'],__init__:function(self){self._ids=[];self._parseIds().then(function(ids){_.forEach(ids,function(id){self.add(id);});});alertify;},_parseIds:function(self){return BPromise.resolve(JSON.parse(Cookies.get(self.COOKIE_NAME)||'[]'));},add:function(self,id){if(self._ids.indexOf(parseInt(id))>=0){return;}
self._ids.push(id);Cookies.set(self.COOKIE_NAME,JSON.stringify(self._ids));self.trigger('add',id);},remove:function(self,id){var index=self._ids.indexOf(parseInt(id));if(index<0){return;}
var _id=self._ids.splice(index,1)[0];Cookies.set(self.COOKIE_NAME,JSON.stringify(self._ids));self.trigger('remove',_id);},toggle:function(self,id){if(self._ids.indexOf(parseInt(id))>=0){alertify.error('Der Job wurde von deiner Merkliste gelöscht.');return self.remove(id);}
alertify.success('Der Job wurde zu deiner Merkliste hinzugefügt.');self.add(id);},clear:function(self){},get:function(self){if(self.getPromise&&self.getPromise.isPending()){return self.getPromise;}
self.getPromise=new BPromise(function(resolve,reject){var fetch=!self.LOCAL_STORAGE;if(!fetch){fetch=self._storageExpired();}
if(!fetch){var storage=JSON.parse(localStorage.getItem('favorites')||'[]');var ids=_.map(storage,'id');_.forEach(self._ids,function(id){fetch=ids.indexOf(id)===-1;return!fetch;});if(!fetch){var data=_.filter(storage,function(o){return self._ids.indexOf(o.id)>-1;});localStorage.setItem('favorites',JSON.stringify(data));return resolve(data);}}
score.ajax.rest.getJSON('/rest/favorite').then(function(response){var data=_.filter(response.favorites,{'isDeleted':false});_.forEach(_.filter(response.favorites,'isDeleted'),function(item){self.remove(item.id);});if(self.LOCAL_STORAGE){localStorage.setItem('favorites',JSON.stringify(data));localStorage.setItem('favorites_time',new Date().getTime());}
resolve(data);});});return self.getPromise;},count:function(self){return self._ids.length;},_storageExpired:function(self){return new Date().getTime()-localStorage.getItem('favorites_time')>=self.MAX_STORAGE_TIME;}});return new MyFavorites();});define('components/myjobalarm',['bluebird','lodash','lib/cookie','score.init','score.oop','score.ajax.rest'],function(BPromise,_,Cookies,score){'use strict';var MyJobAlarm=score.oop.Class({__name__:'MyJobAlarm',__static__:{LOCAL_STORAGE:function(){var test='test';try{localStorage.setItem(test,test);localStorage.removeItem(test);return true;}catch(e){return false;}}(),data:{"location":"","keywords":"","employmentTypes":[],"positions":[],"categories":[]}},__events__:['update','storageError'],__init__:function(self){if(!self.LOCAL_STORAGE){return self.trigger('storageError');}
self._retrieve().then(function(data){self.data=data;self.trigger('update',data);});},_retrieve:function(self){var json=localStorage.getItem('jobalarm');if(json){return BPromise.resolve(JSON.parse(json));}
localStorage.setItem('jobalarm',JSON.stringify(self.data));return BPromise.resolve(self._retrieve());},set:function(self,data){self.data=data;localStorage.setItem('jobalarm',JSON.stringify(self.data));self.trigger('update',data);return BPromise.resolve();},isEmpty:function(self){return!(self.data.keywords||self.data.location||self.data.employmentTypes.length||self.data.positions.length||self.data.categories.length);},getResults:function(self){return score.ajax.rest.postJSON('/rest/jobposting/_search',self.data).then(function(data){return data.results;});}});return new MyJobAlarm();});define('components/overlay',['components/overlay/student-request-approval','components/overlay/login','components/overlay/jobalarm','components/overlay/litebox','components/overlay/register-choose-portal','components/overlay/register','components/overlay/registerStudent','components/overlay/register-complete','components/overlay/register-complete-student','components/overlay/forgot-password','components/overlay/newsletter','components/overlay/newsletter-activate-link','components/overlay/newsletter-email-exist','score.init','score.oop','score.dom.theater'],function(StudentRequestApprovalScene,LoginScene,JobalarmScene,LiteboxScene,RegisterChoosePortalScene,RegisterScene,RegisterStudentScene,RegisterCompleteScene,RegisterCompleteStudentScene,ForgotPasswordScene,NewsletterScene,NewsletterActivateLinkScene,NewsletterEmailExistScene,score){'use strict';var overlayNode=score.dom('#overlay');var Overlay=score.oop.Class({__name__:'Overlay',__parent__:score.dom.theater.Stage,__init__:function(self,node){self.__super__(node);self.node[0].addEventListener('click',function(event){if(event.target!==event.currentTarget){return;}
self.hide();});},show:function(self){self.__super__.apply(self,Array.prototype.slice.call(arguments,1));self.node.addClass('active');score.dom('body').addClass('no-scroll');},hide:function(self){self.node.removeClass('active');score.dom('body').removeClass('no-scroll');self.activeScene.trigger('deactivate');}});var overlay=new Overlay(overlayNode);overlayNode.find('.close')[0].addEventListener('click',overlay.hide);new StudentRequestApprovalScene(overlay,'student-request-approval',overlayNode.find('.student-request-approval')[0]);new LoginScene(overlay,'login',overlayNode.find('.login')[0]);new JobalarmScene(overlay,'jobalarm',overlayNode.find('.jobalarm')[0]);new LiteboxScene(overlay,'litebox',overlayNode.find('.litebox')[0]);new RegisterChoosePortalScene(overlay,'register-choose-portal',overlayNode.find('.register-choose-portal')[0]);new RegisterScene(overlay,'register',overlayNode.find('.register')[0]);new RegisterStudentScene(overlay,'registerStudent',overlayNode.find('.registerStudent')[0]);new RegisterCompleteScene(overlay,'register-complete',overlayNode.find('.register-complete')[0]);new RegisterCompleteStudentScene(overlay,'register-complete-student',overlayNode.find('.register-complete-student')[0]);new ForgotPasswordScene(overlay,'forgot-password',overlayNode.find('.forgot-password')[0]);new NewsletterScene(overlay,'newsletter',overlayNode.find('.newsletter')[0]);new NewsletterActivateLinkScene(overlay,'newsletter-activate-link',overlayNode.find('.newsletter-activate-link')[0]);new NewsletterEmailExistScene(overlay,'newsletter-email-exist',overlayNode.find('.newsletter-email-exist')[0]);return overlay;});define('components/overlay/forgot-password',['bluebird','score.init','score.oop','score.dom.theater','score.ajax.rest'],function(BPromise,score){'use strict';return score.oop.Class({__name__:'ForgotPasswordScene',__parent__:score.dom.theater.Scene,_init:function(self){self.node.on('submit',self._submitHandler);self.emailInput=self.node.find('input[name=email]');self.emailInput.on('invalid',self._submitHandler);self.errorMessage=self.node.find('.error-message');self.node.find('.close').on('click',self._close);self.on('deactivate',self._reset);},_activate:function(self,id){self.emailInput.removeClass('invalid');self.emailInput.addClass('valid');self.errorMessage.removeClass('visible');},_submitHandler:function(self,event){event.preventDefault();self._validateEmail(self.emailInput[0].value).then(function(email){self.emailInput.removeClass('invalid');self.emailInput.addClass('valid');self.errorMessage.removeClass('visible');var data={email:self.emailInput[0].value,forgot_password:true};score.ajax.rest.putJSON('/rest/user',data).then(function(){self.stage.hide();});}).caught(function(email){self.emailInput.addClass('invalid');self.emailInput.removeClass('valid');}).finally(function(){});},_reset:function(self){self.emailInput[0].value='';},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!email){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Bitte geben Sie Ihre E-Mail Adresse ein';return reject(Error(email));}
if(!isEmail){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Die E-Mail Adresse ist ungültig.';return reject(Error(email));}
score.ajax.rest.getJSON('/rest/user/_search?q='+encodeURIComponent('email='+email)).then(function(data){if(!data.user){self.errorMessage.addClass('visible');self.errorMessage[0].innerHTML='Es existiert kein Benutzer mit dieser E-Mail Adresse';return reject(Error(email));}
resolve(email);});});},_close:function(self,event){self.stage.hide();}});});define('components/overlay/jobalarm',['alertify','user','score.init','score.oop','score.dom.theater','score.ajax.rest'],function(alertify,User,score){'use strict';return score.oop.Class({__name__:'JobalarmScene',__parent__:score.dom.theater.Scene,_init:function(self){self.emailInput=self.node.find('input[name=email]');self.newsletter=self.node.find('input[name=newsletter-too]');self.errorMessage=self.node.find('.error-message');var closeButton=self.node.find('.close')[0];closeButton.addEventListener('click',self._close);var submitButton=self.node.find('button')[0];submitButton.addEventListener('click',self._submitHandler);self.on('deactivate',self._reset);},_reset:function(self){self.emailInput[0].value='';},_submitHandler:function(self,event){event.preventDefault();var email=self.emailInput[0].value;var newsletter=self.newsletter[0].checked;if(!self._validateEmail(email)){return;}
var data={email:email,keywords:self._getKeywords().join(' '),location:self._getLocations().join(' '),categories:self._getUrlParam('categories[]'),positions:self._getUrlParam('positions[]'),employmentTypes:self._getUrlParam('employmentTypes[]'),newsletter:newsletter};score.ajax.rest.postJSON('/rest/jobalarm',data).then(function(jobalarm){if(jobalarm){alertify.success('Ihr Job-Alarm wurde gespeichert');}else{alertify.error('Ihr Job-Alarm wurde nicht gespeichert');}});return self._close();},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);if(!isEmail){self.errorMessage.addClass('visible');return false;}
self.errorMessage.removeClass('visible');return true;},_close:function(self,event){self.stage.hide();},_getUrlParams:function(self){var _get=decodeURI(document.location.search.slice(1));_get=_get.replace(new RegExp(/\+/g),' ');_get=_get.replace(new RegExp('%2B','g'),'+');var parts=_get.split('&');var params={};for(var i=0;i<parts.length;i++){var subparts=parts[i].split('=');if(subparts[0].indexOf('[]')===subparts[0].length-2){if(!params[subparts[0]]){params[subparts[0]]=[];}
params[subparts[0]].push(subparts[1]);continue;}
params[subparts[0]]=subparts[1];}
return params;},_getUrlParam:function(self,name){var params=self._getUrlParams();console.log(params);if(!params[name]){return;}
return params[name];},_getLocations:function(self){var params=self._getUrlParams();if(!params.location){return[];}
var locations=params.location.split('+');for(var i=0;i<locations.length;i++){locations[i]=locations[i].trim();}
return locations;},_getKeywords:function(self){var params=self._getUrlParams();if(!params.keywords){return[];}
var keywords=params.keywords.split('+');for(var i=0;i<keywords.length;i++){keywords[i]=keywords[i].trim();}
return keywords;},});});define('components/overlay/litebox',['score.init','score.oop','score.dom.theater'],function(score){'use strict';return score.oop.Class({__name__:'Litebox',__parent__:score.dom.theater.Scene,_init:function(self){var closeButton=self.node.find('.close');closeButton.on('click',self._close);},_close:function(self,event){self.stage.hide();},_load:function(self,url){if(url){var iframe=self.node.find('iframe');iframe.attr('src',url);return false;}
console.log('litebox_load: no url passed');}});});define('components/overlay/login',['bluebird','user','score.init','score.oop','score.dom.theater'],function(BPromise,User,score){'use strict';return score.oop.Class({__name__:'LoginScene',__parent__:score.dom.theater.Scene,_init:function(self){self.usernameInput=self.node.find('input[name=username]');self.passwordInput=self.node.find('input[name=password]');self.errorMessage=self.node.find('.error-message');var closeButton=self.node.find('.close')[0];var registerButton=self.node.find('.open-register')[0];var forgotButton=self.node.find('.open-forgot_password')[0];closeButton.addEventListener('click',self._close);registerButton.addEventListener('click',self._openRegister);forgotButton.addEventListener('click',self._openForgotPassword);var submitButton=self.node.find('button')[0];submitButton.addEventListener('click',self._submitHandler);self.on('deactivate',self._reset);},_activate:function(self,id){self.errorMessage.removeClass('visible');},_reset:function(self){self.usernameInput[0].value='';self.passwordInput[0].value='';},_submitHandler:function(self,event){event.preventDefault();var data={username:self.usernameInput[0].value,password:self.passwordInput[0].value};User.login(data).then(function(user){if(!user||!user.id){self.errorMessage.addClass('visible');return;}
self.stage.hide();});},setIsStudent:function(self,isStudent){self.isStudent=isStudent;},_openRegister:function(self,event){event.preventDefault();self._close;require(['components/overlay'],function(Overlay){if(self.isStudent){Overlay.show('registerStudent');}else{Overlay.show('register');}});},_openForgotPassword:function(self,event){event.preventDefault();self._close;require(['components/overlay'],function(Overlay){Overlay.show('forgot-password');});},_close:function(self,event){self.stage.hide();}});});define('components/overlay/newsletter',['alertify','bluebird','score.init','score.oop','score.dom.theater','score.ajax.rest'],function(alertify,BPromise,score){'use strict';return score.oop.Class({__name__:'NewsletterScene',__parent__:score.dom.theater.Scene,_init:function(self){self.node.on('submit',self._submitHandler);self.emailInput=self.node.find('input[name=email]');self.emailInput.on('invalid',self._submitHandler);self.errorMessage=self.node.find('.error-message');self.node.find('.close').on('click',self._close);self.on('deactivate',self._reset);},_load:function(self){console.log('load');},_activate:function(self,id){self.emailInput.removeClass('invalid');self.emailInput.addClass('valid');self.errorMessage.removeClass('visible');},_submitHandler:function(self,event){event.preventDefault();self._validateEmail(self.emailInput[0].value).then(function(email){self.emailInput.removeClass('invalid');self.emailInput.addClass('valid');self.errorMessage.removeClass('visible');var data={email:self.emailInput[0].value};score.ajax.rest.postJSON('/rest/newsletter',data).then(function(data){if(data.active){return require(['components/overlay'],function(Overlay){Overlay.show('newsletter-email-exist');});}else if(data.redirectUrl){alertify.success('Sie werden weitergeleitet...');window.location.href=data.redirectUrl;}});}).caught(function(email){self.emailInput.addClass('invalid');self.emailInput.removeClass('valid');}).finally(function(){});},_reset:function(self){self.emailInput[0].value='';},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!email){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Bitte geben Sie Ihre E-Mail Adresse ein';return reject(Error(email));}
if(!isEmail){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Die E-Mail Adresse ist ungültig.';return reject(Error(email));}
resolve(email);});},_close:function(self,event){self.stage.hide();}});});define('components/overlay/newsletter-activate-link',['score.init','score.oop','score.dom.theater'],function(score){'use strict';return score.oop.Class({__name__:'NewsletterActivateLinkScene',__parent__:score.dom.theater.Scene,_init:function(self){var closeButton=self.node.find('.close');closeButton.on('click',self._close);},_close:function(self,event){self.stage.hide();}});});define('components/overlay/newsletter-email-exist',['score.init','score.oop','score.dom.theater'],function(score){'use strict';return score.oop.Class({__name__:'NewsletterEmailExistScene',__parent__:score.dom.theater.Scene,_init:function(self){var closeButton=self.node.find('.close');closeButton.on('click',self._close);},_close:function(self,event){self.stage.hide();}});});define('components/overlay/register',['bluebird','score.init','score.oop','score.dom.theater','score.ajax.rest'],function(BPromise,score){'use strict';return score.oop.Class({__name__:'RegisterScene',__parent__:score.dom.theater.Scene,_init:function(self){self.node.on('submit',self._submitHandler);self.emailInput=self.node.find('input[name=username]');self.emailInput.on('keyup',self._emailInputHandler);self.emailInput.on('blur',self._emailInputHandler);self.emailInput.on('change',self._emailInputHandler);self.passwordInput=self.node.find('input[name=password]');self.password2Input=self.node.find('input[name=password2]');self.passwordInput.on('keyup',self._passwordInputHandler);self.passwordInput.on('change',self._passwordInputHandler);self.passwordInput.on('blur',self._passwordInputHandler);self.password2Input.on('keyup',self._passwordInputHandler);self.password2Input.on('change',self._passwordInputHandler);self.password2Input.on('blur',self._passwordInputHandler);self.errorMessage=self.node.find('.error-message');self.gtc=self.node.find('input[name=gtc]');self.gtc.on('change',self._gtcChangeHandler);self.consent=self.node.find('input[name=consent]');self.consent.on('change',self._consentChangeHandler);self.node.find('.close').on('click',self._close);self.on('deactivate',self._reset);},_submitHandler:function(self,event){event.preventDefault();var data={email:self.emailInput[0].value,password:self.passwordInput[0].value,password2:self.password2Input[0].value,newsletter:self.node.find('input[name=newsletter]')[0].checked,gtc:self.gtc[0].checked,consent:self.consent[0].checked,};if(self.emailInput.hasClass('invalid')){console.log('invalid');return;}
if(!data.gtc){console.log('gtc not accepted');return;}
if(!data.consent){console.log('consent not accepted');return;}
if(data.password!==data.password2){console.log('password missmatch');return;}
if(!data.password){console.log('password empty');self.errorMessage.addClass('visible');self.errorMessage.innerHTML='Kein Passwort angegeben.';return;}
self.errorMessage.removeClass('visible');score.ajax.rest.postJSON('/rest/user',data).then(function(data){if(data.user&&data.user.id){return require(['components/overlay'],function(Overlay){Overlay.show('register-complete');});}
console.log(data);});},_reset:function(self){self.emailInput[0].value='';self.passwordInput[0].value='';self.password2Input[0].value='';},_emailInputHandler:function(self,event){if(self._keyUpTimeout){clearTimeout(self._keyUpTimeout);}
self._keyUpTimeout=setTimeout(function(){self._validateEmail(self.emailInput[0].value).then(function(email){self.emailInput.removeClass('invalid');self.emailInput.addClass('valid');self.errorMessage.removeClass('visible');}).caught(function(email){self.emailInput.addClass('invalid');self.emailInput.removeClass('valid');}).finally(function(){self._validateForm();});},600);},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!isEmail){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Die Mail-Adresse ist ungültig.';return reject(Error(email));}
score.ajax.rest.getJSON('/rest/user/username-unique/'+encodeURIComponent(email)).then(function(data){resolve(email);}).catch(function(error){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Die Mail-Adresse ist bereits vorhanden.';return reject(Error(email));});});},_passwordInputHandler:function(self,event){if(self.passwordInput[0].value&&self.passwordInput[0].value===self.password2Input[0].value){self.password2Input.removeClass('invalid');self.password2Input.addClass('valid');self.errorMessage.removeClass('visible');}else{self.password2Input.removeClass('valid');self.password2Input.addClass('invalid');self.errorMessage.addClass('visible');self.errorMessage[0].innerHTML='Die Passwörter stimmen nicht überein.';}
self._validateForm();},_gtcChangeHandler:function(self,event){self._validateForm();},_consentChangeHandler:function(self,event){self._validateForm();},_validateForm:function(self){if((self.emailInput[0].value&&self.emailInput.hasClass('invalid'))||!self.passwordInput[0].value||self.passwordInput[0].value!==self.password2Input[0].value||!self.node.find('input[name=gtc]')[0].checked||!self.node.find('input[name=consent]')[0].checked){return self.node.find('button[type=submit]')[0].disabled=true;}
self.node.find('button[type=submit]')[0].disabled=false;},_close:function(self,event){self.stage.hide();}});});define('components/overlay/register-choose-portal',['bluebird','score.init','score.oop','score.dom.theater','score.ajax.rest'],function(BPromise,score){'use strict';return score.oop.Class({__name__:'RegisterChoosePortalScene',__parent__:score.dom.theater.Scene,_init:function(self){self.adult=self.node.find('div[id=register-choose-adult]');self.adult.on('click',self._switchToAdult);self.student=self.node.find('div[id=register-choose-student]');self.student.on('click',self._switchToStudent);self.node.find('.close').on('click',self._close);self.on('deactivate',self._reset);},_switchToAdult:function(self,event){event.preventDefault();self.stage.show('register');},_switchToStudent:function(self,event){event.preventDefault();self.stage.show('registerStudent');},_reset:function(self){},_close:function(self,event){self.stage.hide();},_activate:function(self){},});});define('components/overlay/register-complete',['score.init','score.oop','score.dom.theater'],function(score){'use strict';return score.oop.Class({__name__:'RegisterCompleteScene',__parent__:score.dom.theater.Scene,_init:function(self){var closeButton=self.node.find('.close');closeButton.on('click',self._close);},_close:function(self,event){self.stage.hide();}});});define('components/overlay/register-complete-student',['score.init','score.oop','score.dom.theater'],function(score){'use strict';return score.oop.Class({__name__:'RegisterCompleteStudentScene',__parent__:score.dom.theater.Scene,_init:function(self){var closeButton=self.node.find('.close');closeButton.on('click',self._close);},_close:function(self,event){self.stage.hide();}});});define('components/overlay/registerStudent',['bluebird','score.init','score.oop','score.dom.theater','score.ajax.rest'],function(BPromise,score){'use strict';return score.oop.Class({__name__:'RegisterStudentScene',__parent__:score.dom.theater.Scene,_init:function(self){self.node.on('submit',self._submitHandler);self.emailInput=self.node.find('input[name=username]');self.emailInput.on('keyup',self._emailInputHandler);self.emailInput.on('blur',self._emailInputHandler);self.emailInput.on('change',self._emailInputHandler);self.passwordInput=self.node.find('input[name=password]');self.password2Input=self.node.find('input[name=password2]');self.passwordInput.on('keyup',self._passwordInputHandler);self.passwordInput.on('change',self._passwordInputHandler);self.passwordInput.on('blur',self._passwordInputHandler);self.password2Input.on('keyup',self._passwordInputHandler);self.password2Input.on('change',self._passwordInputHandler);self.password2Input.on('blur',self._passwordInputHandler);self.errorMessage=self.node.find('.error-message');self.gtc=self.node.find('input[name=gtc]');self.gtc.on('change',self._gtcChangeHandler);self.consent=self.node.find('input[name=consent]');self.consent.on('change',self._consentChangeHandler);self.node.find('.close').on('click',self._close);self.on('deactivate',self._reset);},_submitHandler:function(self,event){event.preventDefault();var data={email:self.emailInput[0].value,password:self.passwordInput[0].value,password2:self.password2Input[0].value,gtc:self.gtc[0].checked,consent:self.consent[0].checked,};if(self.emailInput.hasClass('invalid')){console.log('invalid');return;}
if(!data.gtc){console.log('gtc not accepted');return;}
if(!data.consent){console.log('consent not accepted');return;}
if(data.password!==data.password2){console.log('password missmatch');return;}
if(!data.password){console.log('password empty');self.errorMessage.addClass('visible');self.errorMessage.innerHTML='Kein Passwort angegeben.';return;}
self.errorMessage.removeClass('visible');score.ajax.rest.postJSON('/rest/student',data).then(function(data){if(data.student&&data.student.id){return require(['components/overlay'],function(Overlay){Overlay.show('register-complete-student');});}
console.log(data);});},_reset:function(self){self.emailInput[0].value='';self.passwordInput[0].value='';self.password2Input[0].value='';},_emailInputHandler:function(self,event){if(self._keyUpTimeout){clearTimeout(self._keyUpTimeout);}
self._keyUpTimeout=setTimeout(function(){self._validateEmail(self.emailInput[0].value).then(function(email){self.emailInput.removeClass('invalid');self.emailInput.addClass('valid');self.errorMessage.removeClass('visible');}).caught(function(email){self.emailInput.addClass('invalid');self.emailInput.removeClass('valid');}).finally(function(){self._validateForm();});},600);},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!isEmail){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Die Mail-Adresse ist ungültig.';return reject(Error(email));}
score.ajax.rest.getJSON('/rest/user/username-unique/'+encodeURIComponent(email)).then(function(data){resolve(email);}).catch(function(error){self.errorMessage.addClass('visible');self.errorMessage[0].innerText='Die Mail-Adresse ist bereits vorhanden.';return reject(Error(email));});});},_passwordInputHandler:function(self,event){if(self.passwordInput[0].value&&self.passwordInput[0].value===self.password2Input[0].value){score.ajax.rest.postJSON('/rest/user/_passwordpolicy',{'value':self.passwordInput[0].value}).then(function(){self.password2Input.removeClass('invalid');self.password2Input.addClass('valid');self.errorMessage.removeClass('visible');}).catch(function(){self.password2Input.removeClass('valid');self.password2Input.addClass('invalid');self.errorMessage.addClass('visible');self.errorMessage[0].innerHTML='Das Passwort muss aus mindestens 6 Zeichen bestehen.';});}else{self.password2Input.removeClass('valid');self.password2Input.addClass('invalid');self.errorMessage.addClass('visible');self.errorMessage[0].innerHTML='Die Passwörter stimmen nicht überein.';}
self._validateForm();},_gtcChangeHandler:function(self,event){self._validateForm();},_consentChangeHandler:function(self,event){self._validateForm();},_validateForm:function(self){if((self.emailInput[0].value&&self.emailInput.hasClass('invalid'))||!self.passwordInput[0].value||self.passwordInput[0].value!==self.password2Input[0].value||!self.node.find('input[name=gtc]')[0].checked||!self.node.find('input[name=consent]')[0].checked){return self.node.find('button[type=submit]')[0].disabled=true;}
self.node.find('button[type=submit]')[0].disabled=false;},_close:function(self,event){self.stage.hide();}});});define('components/overlay/student-request-approval',['bluebird','score.init','score.oop','score.dom.theater'],function(BPromise,score){return score.oop.Class({__name__:'ConfirmClientRequestScene',__parent__:score.dom.theater.Scene,__events__:['studentApproved'],_init:function(self){self.gtcInput=self.node.find('input[name=gtc]')[0];var closeButton=self.node.find('.close')[0];self.gtcInput.addEventListener('click',self._updateSubmitButton);closeButton.addEventListener('click',self._close);self.node.on('submit',self._submitHandler);},_submitHandler:function(self){event.preventDefault();if(self.gtcInput.checked){self.trigger('studentApproved');self._close();}},_updateSubmitButton:function(self){self.node.find('button[type=submit]')[0].disabled=!self.gtcInput.checked;},_close:function(self,event){self.stage.hide();}});});define('components/search/filters',['lodash','score.init','score.oop'],function(_,score){'use strict';return score.oop.Class({__name__:'SearchFilters',__init__:function(self,node){self.node=node;self._updateLocationInputs(node.querySelectorAll('input[name="counties[]"]'));self._updateLocationInputs(node.querySelectorAll('input[name="locations[]"]'));self._updateListInputs('categories[]');self._updateListInputs('positions[]');self._updateListInputs('employmentTypes[]');var inputs=self.node.querySelectorAll('input[type=checkbox]');for(var i=0;i<inputs.length;i++){inputs[i].addEventListener('change',self._checkboxChangeHandler);}
self._getUrlParams();_.forEach(self.node.querySelectorAll('input[name=order]'),function(o){o.addEventListener('change',self._handleResultOrderChange);});},_updateLocationInputs:function(self,inputs){var locations=self._getLocations();for(var i=0;i<inputs.length;i++){for(var j=0;j<locations.length;j++){if(inputs[i].value.toLowerCase()!==locations[j].toLowerCase()){continue;}
inputs[i].checked=true;}}},_updateListInputs:function(self,name){var inputs=self.node.querySelectorAll('input[name="'+name+'"]');var param=self._getUrlParam(name);if(!param){return;}
for(var i=0;i<inputs.length;i++){var id=inputs[i].getAttribute('data-id');if(param.indexOf(id)>-1){inputs[i].checked=true;}}},_getLocations:function(self){var params=self._getUrlParams();if(!params.location){return[];}
var locations=params.location.split('+');for(var i=0;i<locations.length;i++){locations[i]=locations[i].trim();}
return locations;},_setLocations:function(self,locations){var params=self._getUrlParams();params.location=locations.join('+%2B+');return params;},_getUrlParam:function(self,name){var params=self._getUrlParams();if(!params[name]){return;}
return params[name];},_setUrlParam:function(self,name,value){var params=self._setLocations(self._getLocations());params[name]=value;if(!value||!value.length){delete(params[name]);}
self._setUrlParams(params);},_getUrlParams:function(self){var _get=decodeURI(document.location.search.slice(1));_get=_get.replace(new RegExp(/\+/g),' ');_get=_get.replace(new RegExp('%2B','g'),'+');var parts=_get.split('&');var params={};for(var i=0;i<parts.length;i++){var subparts=parts[i].split('=');if(subparts[0].indexOf('[]')===subparts[0].length-2){if(!params[subparts[0]]){params[subparts[0]]=[];}
params[subparts[0]].push(subparts[1]);continue;}
params[subparts[0]]=subparts[1];}
return params;},_setUrlParams:function(self,params){var url=document.location.pathname.replace(/\/(\d+)$/g,'')+'?';for(var key in params){url+=encodeURI(key)+'='+params[key]+'&';}
url=url.slice(0,-1);document.location.href=url;},_checkboxChangeHandler:function(self,event){switch(event.target.name){case'counties[]':case'locations[]':self._handleLocationChange(event.target.value,!event.target.checked);break;default:self._handleCheckboxChange(event);break;}},_handleLocationChange:function(self,locationName,remove){var locations=self._getLocations();if(remove){for(var i=0;i<locations.length;i++){if(locations[i].toLowerCase()===locationName.toLowerCase()){locations.splice(i,1);break;}}}else{locations.push(locationName);}
self._setUrlParams(self._setLocations(locations));},_handleCheckboxChange:function(self,event){var remove=!event.target.checked;var name=event.target.name;var value=event.target.getAttribute('data-id');var param=self._getUrlParam(name);if(remove&&param){var index=param.indexOf(value);param.splice(index,1);}else if(!remove){if(!param){param=[];}
param.push(value);}
self._setUrlParam(name,param);},_handleResultOrderChange:function(self,event){if(event.target.value==='date'){document.location.href=document.location.href+'&order=date';}else{document.location.href=document.location.href.replace('&order=date','');}}});});define('components/searchHeader',['lodash','score.init','score.oop','score.dom'],function(_,score){'use strict';return score.oop.Class({__name__:'SearchHeader',__static__:{ENTER_KEY:13},__init__:function(self,node){self.node=score.dom(node);self.keywordInput=self.node.find('[name=keywords]');self.locationInput=self.node.find('[name=location]');self.submitButton=self.node.find('.search__button');self.submitButton[0].addEventListener('click',self._submitHandler);self.keywordInput[0].addEventListener('keydown',self._inputKeyDownHandler);self.locationInput[0].addEventListener('keydown',self._inputKeyDownHandler);},_submitHandler:function(self,event){event.preventDefault();self.node[0].submit();},_inputKeyDownHandler:function(self,event){var key='which'in event?event.which:event.keyCode;if(key!==self.ENTER_KEY){return;}
self.node[0].submit();},});});define('components/studentUpload',['components/upload','bluebird','score.init','score.oop'],function(Upload,BPromise,score){'use strict';return score.oop.Class({__name__:'StudentUpload',__parent__:Upload,__init__:function(self,input,allowedFileTypes,maxFileSize,denyVideo){self.input=input;self.input.on('change',self._fileChangeHandler);self.allowedFileTypes=allowedFileTypes;self.maxFileSize=maxFileSize;self.denyVideo=denyVideo;},_readFileData:function(self,input){var promises=[];for(var i=0;i<input.files.length;i++){var file=input.files[i];if(self.maxFileSize&&file.size>self.maxFileSize){return new BPromise(function(resolve,reject){resolve({error:{fileSize:{fileSize:(file.size / 1048576).toFixed(2),max:(self.maxFileSize / 1048576).toFixed(2)}}});});}else if(self.allowedFileTypes&&self.allowedFileTypes.indexOf(file.type)===-1){return new BPromise(function(resolve,reject){resolve({error:{fileType:file.type+' not supported'}});});}else if(self.denyVideo&&file.type.indexOf('video')!==-1){return new BPromise(function(resolve,reject){resolve({error:{uploadRestriction:'Only 1 Video is allowed'}});});}else{promises.push(new BPromise(function(resolve,reject){var reader=new FileReader();reader.onabort=reject;reader.onerror=reject;reader.onload=function(){var base64=reader.result;var mimeType=base64.slice(5,base64.indexOf(';'));resolve({name:file.name,data:base64,uuid:self._uuid(),mimeType:mimeType});};reader.readAsDataURL(file);}));}}
return BPromise.all(promises);},setDenyVideo:function(self,denyVideo){self.denyVideo=denyVideo;},});});define('components/upload',['bluebird','score.init','score.oop'],function(BPromise,score){'use strict';return score.oop.Class({__name__:'Upload',__events__:['change'],__static__:{_uuid:function(){return'xxxxxxxx-xyxy'.replace(/[xy]/g,function(c){var r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);return v.toString(16);});}},data:[],__init__:function(self,input,allowedMimeTypes,maxFileSize){self.input=input;self.input.on('change',self._fileChangeHandler);self.allowedMimeTypes=allowedMimeTypes;self.maxFileSize=maxFileSize;},_fileChangeHandler:function(self,event){self._readFileData(event.currentTarget).then(function(result){self.data=result;self.trigger('change',self.data);});},_readFileData:function(self,input){var promises=[];for(var i=0;i<input.files.length;i++){var file=input.files[i];if(self.maxFileSize&&file.size>self.maxFileSize){return new BPromise(function(resolve,reject){resolve({error:{fileSize:{fileSize:(file.size / 1048576).toFixed(2),max:(self.maxFileSize / 1048576).toFixed(2)}}});});}else if(self.allowedMimeTypes&&self.allowedMimeTypes.indexOf(file.type)===-1){return new BPromise(function(resolve,reject){resolve({error:{fileType:file.type+' not supported'}});});}else{promises.push(new BPromise(function(resolve,reject){var reader=new FileReader();reader.onabort=reject;reader.onerror=reject;reader.onload=function(){var base64=reader.result;var mimeType=base64.slice(5,base64.indexOf(';'));resolve({name:file.name,data:base64,uuid:self._uuid(),mimeType:mimeType});};reader.readAsDataURL(file);}));}}
return BPromise.all(promises);},get:function(self,uuid){for(var i=0;i<self.data.length;i++){if(self.data[i].uuid===uuid){return self.data[i];}}},remove:function(self,uuid){for(var i=0;i<self.data.length;i++){if(self.data[i].uuid===uuid){self.data.splice(i,1);return self.trigger('change',self.data);}}}});});define('contact-picture-upload',['components/upload','bluebird','score.init','score.oop','score.dom','score.ajax.rest'],function(Upload,BPromise,score){'use strict';var ContactPictureUpload=score.oop.Class({__name__:'ContactPictureUpload',__events__:['uploaded','cancel'],__init__:function(self,node){self.node=score.dom(node);self.uploader=new Upload(self.node.find('input[type=file]'));self.saveAllBtn=self.node.find('button.save-all');self.closeBtn=self.node.find('button.close');self.uploader.on('change',function(data){if(self.saveAllBtn.length){self.saveAllBtn[0].disabled=!data.length;}
self._populate(data);});self.saveAllBtn.on('click',self._saveAllHandler);self.closeBtn.on('click',self.hide);self.list=self.node.find('ul.contact-picture-upload__file-list')[0];},_saveAllHandler:function(self){for(var i=0;i<self.uploader.data.length;i++){self.upload(self.uploader.data[i].uuid).then(function(data){});}},upload:function(self,uuid){return score.ajax.rest.postJSON('/rest/image',self.uploader.get(uuid)).then(function(data){self.uploader.remove(uuid);self.trigger('uploaded',data.image);return data;});},_populate:function(self,data){self.list.innerHTML='';for(var i=0;i<data.length;i++){var li=document.createElement('li');li.setAttribute('data-uuid',data[i].uuid);var img=document.createElement('img');li.appendChild(img);img.src=data[i].data;var contactname=self.node[0].getAttribute('data-contact-name');self.uploader.get(data[i].uuid).name='contact-picture_'+contactname;var button=document.createElement('button');button.textContent='Speichern';button.addEventListener('click',self.upload.bind(button,data[i].uuid));li.appendChild(button);self.list.appendChild(li);}
if(!data.length){var li=document.createElement('li');li.innerHTML='Keine Dateien ausgewählt';self.list.appendChild(li);}},show:function(self){self.node.addClass('active');self.node.addClass('glass');return new BPromise(function(resolve,reject){self.on('uploaded',function(data){resolve(data);self.hide();});self.on('cancel',reject);});},hide:function(self){self.node.removeClass('active');self.node.removeClass('glass');}});return new ContactPictureUpload(document.querySelector('.contact-picture-upload'));});define('jobposting',['components/form','user','components/upload','alertify','score.init','score.oop','score.dom','score.ajax.rest'],function(Form,User,Upload,alertify,score){'use strict';return score.oop.Class({__name__:'JobPostingBlock',__init__:function(self,node,jobPostingId){self.node=node;self.applyButton=self.node.find('.button-apply');self.applyButton[0].addEventListener('click',function(event){event.preventDefault();if(!score.dom('.letter-of-application-box').hasClass('active')){if(!self.data){score.ajax.rest.getJSON('/rest/letterofapplication/'+jobPostingId).then(function(data){self.data=data.letterofapplication;self._renderData();});}}
User.get().then(function(user){self.user=user;if(user){self.node.find('.file-upload').removeClass('active');self.node.find('input[type=file]')[0].required=false;return;}
self.node.find('.file-upload').addClass('active');self.node.find('input[type=file]')[0].required='required';if(!self.upload){self.upload=new Upload(self.node.find('input[type=file]'));self.upload.on('change',function(files){self.files=files;var listNode=self.node.find('.image-upload__file-list')[0];listNode.innerHTML='';for(var i=0;i<self.files.length;i++){var file=self.files[i];var li=document.createElement('li');li.innerHTML=file.name;listNode.appendChild(li);}});}});score.dom('.letter-of-application-box').toggleClass('active');});self.closeButton=self.node.find('#apply-close');self.closeButton[0].addEventListener('click',function(event){event.preventDefault();score.dom('.letter-of-application-box').toggleClass('active');});self.node.find('#apply-form').on('submit',self._submitHandler);},_renderData:function(self){self.node.find('#first-name')[0].value=self.data.firstName?self.data.firstName:'';self.node.find('#family-name')[0].value=self.data.lastName?self.data.lastName:'';self.node.find('input[type=email]')[0].value=self.data.email?self.data.email:'';self.node.find('#letter-of-application-text')[0].value=self.data.body?self.data.body:'';},_submitHandler:function(self,event){event.preventDefault();if(self.postPromise){return;}
var data=Form.serialize(event.currentTarget);if(!self._validate(data)){return;}
if(self.files&&!self.user){data.files=self.files;}
self.postPromise=score.ajax.rest.postJSON('/rest/jobapplication',data).then(function(){score.dom('.letter-of-application-box')[0].innerHTML='Wir wünschen Ihnen viel Erfolg bei Ihrer Bewerbung.';});},_validate:function(self,data){if(!data.firstName){alertify.alert('Bitte geben Sie ihren Vornamen an.');return false;}
if(!data.lastName){alertify.alert('Bitte geben Sie ihren Nachnamen an.');return false;}
if(!data.email){alertify.alert('Bitte geben Sie ihre E-Mail an.');return false;}
if(!self.user&&(!self.files||!self.files.length)){alertify.alert('Bitte fügen Sie ihrer Bewerbung ein oder mehrere Dokumente hinzu.');return false;}
return(data.firstName&&data.lastName&&data.email)&&(self.user||self.files.length);}});});(function(){"use strict";var TRANSITION_FALLBACK_DURATION=500;var hideElement=function(el){if(!el){return;}
var removeThis=function(){if(el&&el.parentNode){el.parentNode.removeChild(el);}};el.classList.remove("show");el.classList.add("hide");el.addEventListener("transitionend",removeThis);setTimeout(removeThis,TRANSITION_FALLBACK_DURATION);};function Alertify(){var _alertify={parent:document.body,version:"1.0.11",defaultOkLabel:"Ok",okLabel:"Ok",defaultCancelLabel:"Cancel",cancelLabel:"Cancel",defaultMaxLogItems:2,maxLogItems:2,promptValue:"",promptPlaceholder:"",closeLogOnClick:false,closeLogOnClickDefault:false,delay:5000,defaultDelay:5000,logContainerClass:"alertify-logs",logContainerDefaultClass:"alertify-logs",dialogs:{buttons:{holder:"<nav>{{buttons}}</nav>",ok:"<button class='ok' tabindex='1'>{{ok}}</button>",cancel:"<button class='cancel' tabindex='2'>{{cancel}}</button>"},input:"<input type='text'>",message:"<p class='msg'>{{message}}</p>",log:"<div class='{{class}}'>{{message}}</div>"},defaultDialogs:{buttons:{holder:"<nav>{{buttons}}</nav>",ok:"<button class='ok' tabindex='1'>{{ok}}</button>",cancel:"<button class='cancel' tabindex='2'>{{cancel}}</button>"},input:"<input type='text'>",message:"<p class='msg'>{{message}}</p>",log:"<div class='{{class}}'>{{message}}</div>"},build:function(item){var btnTxt=this.dialogs.buttons.ok;var html="<div class='dialog'>"+"<div>"+this.dialogs.message.replace("{{message}}",item.message);if(item.type==="confirm"||item.type==="prompt"){btnTxt=this.dialogs.buttons.cancel+this.dialogs.buttons.ok;}
if(item.type==="prompt"){html+=this.dialogs.input;}
html=(html+this.dialogs.buttons.holder+"</div>"+"</div>").replace("{{buttons}}",btnTxt).replace("{{ok}}",this.okLabel).replace("{{cancel}}",this.cancelLabel);return html;},setCloseLogOnClick:function(bool){this.closeLogOnClick=!!bool;},close:function(elem,wait){if(this.closeLogOnClick){elem.addEventListener("click",function(){hideElement(elem);});}
wait=wait&&!isNaN(+wait)?+wait:this.delay;if(wait<0){hideElement(elem);}else if(wait>0){setTimeout(function(){hideElement(elem);},wait);}},dialog:function(message,type,onOkay,onCancel){return this.setup({type:type,message:message,onOkay:onOkay,onCancel:onCancel});},log:function(message,type,click){var existing=document.querySelectorAll(".alertify-logs > div");if(existing){var diff=existing.length-this.maxLogItems;if(diff>=0){for(var i=0,_i=diff+1;i<_i;i++){this.close(existing[i],-1);}}}
this.notify(message,type,click);},setLogPosition:function(str){this.logContainerClass="alertify-logs "+str;},setupLogContainer:function(){var elLog=document.querySelector(".alertify-logs");var className=this.logContainerClass;if(!elLog){elLog=document.createElement("div");elLog.className=className;this.parent.appendChild(elLog);}
if(elLog.className!==className){elLog.className=className;}
return elLog;},notify:function(message,type,click){var elLog=this.setupLogContainer();var log=document.createElement("div");log.className=(type||"default");if(_alertify.logTemplateMethod){log.innerHTML=_alertify.logTemplateMethod(message);}else{log.innerHTML=message;}
if("function"===typeof click){log.addEventListener("click",click);}
elLog.appendChild(log);setTimeout(function(){log.className+=" show";},10);this.close(log,this.delay);},setup:function(item){var el=document.createElement("div");el.className="alertify hide";el.innerHTML=this.build(item);var btnOK=el.querySelector(".ok");var btnCancel=el.querySelector(".cancel");var input=el.querySelector("input");var label=el.querySelector("label");if(input){if(typeof this.promptPlaceholder==="string"){if(label){label.textContent=this.promptPlaceholder;}else{input.placeholder=this.promptPlaceholder;}}
if(typeof this.promptValue==="string"){input.value=this.promptValue;}}
function setupHandlers(resolve){if("function"!==typeof resolve){resolve=function(){};}
if(btnOK){btnOK.addEventListener("click",function(ev){if(item.onOkay&&"function"===typeof item.onOkay){if(input){item.onOkay(input.value,ev);}else{item.onOkay(ev);}}
if(input){resolve({buttonClicked:"ok",inputValue:input.value,event:ev});}else{resolve({buttonClicked:"ok",event:ev});}
hideElement(el);});}
if(btnCancel){btnCancel.addEventListener("click",function(ev){if(item.onCancel&&"function"===typeof item.onCancel){item.onCancel(ev);}
resolve({buttonClicked:"cancel",event:ev});hideElement(el);});}
if(input){input.addEventListener("keyup",function(ev){if(ev.which===13){btnOK.click();}});}}
var promise;if(typeof Promise==="function"){promise=new Promise(setupHandlers);}else{setupHandlers();}
this.parent.appendChild(el);setTimeout(function(){el.classList.remove("hide");if(input&&item.type&&item.type==="prompt"){input.select();input.focus();}else{if(btnOK){btnOK.focus();}}},100);return promise;},okBtn:function(label){this.okLabel=label;return this;},setDelay:function(time){time=time||0;this.delay=isNaN(time)?this.defaultDelay:parseInt(time,10);return this;},cancelBtn:function(str){this.cancelLabel=str;return this;},setMaxLogItems:function(num){this.maxLogItems=parseInt(num||this.defaultMaxLogItems);},theme:function(themeStr){switch(themeStr.toLowerCase()){case"bootstrap":this.dialogs.buttons.ok="<button class='ok btn btn-primary' tabindex='1'>{{ok}}</button>";this.dialogs.buttons.cancel="<button class='cancel btn btn-default' tabindex='2'>{{cancel}}</button>";this.dialogs.input="<input type='text' class='form-control'>";break;case"purecss":this.dialogs.buttons.ok="<button class='ok pure-button' tabindex='1'>{{ok}}</button>";this.dialogs.buttons.cancel="<button class='cancel pure-button' tabindex='2'>{{cancel}}</button>";break;case"mdl":case"material-design-light":this.dialogs.buttons.ok="<button class='ok mdl-button mdl-js-button mdl-js-ripple-effect'  tabindex='1'>{{ok}}</button>";this.dialogs.buttons.cancel="<button class='cancel mdl-button mdl-js-button mdl-js-ripple-effect' tabindex='2'>{{cancel}}</button>";this.dialogs.input="<div class='mdl-textfield mdl-js-textfield'><input class='mdl-textfield__input'><label class='md-textfield__label'></label></div>";break;case"angular-material":this.dialogs.buttons.ok="<button class='ok md-primary md-button' tabindex='1'>{{ok}}</button>";this.dialogs.buttons.cancel="<button class='cancel md-button' tabindex='2'>{{cancel}}</button>";this.dialogs.input="<div layout='column'><md-input-container md-no-float><input type='text'></md-input-container></div>";break;case"default":default:this.dialogs.buttons.ok=this.defaultDialogs.buttons.ok;this.dialogs.buttons.cancel=this.defaultDialogs.buttons.cancel;this.dialogs.input=this.defaultDialogs.input;break;}},reset:function(){this.parent=document.body;this.theme("default");this.okBtn(this.defaultOkLabel);this.cancelBtn(this.defaultCancelLabel);this.setMaxLogItems();this.promptValue="";this.promptPlaceholder="";this.delay=this.defaultDelay;this.setCloseLogOnClick(this.closeLogOnClickDefault);this.setLogPosition("bottom left");this.logTemplateMethod=null;},injectCSS:function(){if(!document.querySelector("#alertifyCSS")){var head=document.getElementsByTagName("head")[0];var css=document.createElement("style");css.type="text/css";css.id="alertifyCSS";css.innerHTML="/* style.css */";head.insertBefore(css,head.firstChild);}},removeCSS:function(){var css=document.querySelector("#alertifyCSS");if(css&&css.parentNode){css.parentNode.removeChild(css);}}};_alertify.injectCSS();return{_$$alertify:_alertify,parent:function(elem){_alertify.parent=elem;},reset:function(){_alertify.reset();return this;},alert:function(message,onOkay,onCancel){return _alertify.dialog(message,"alert",onOkay,onCancel)||this;},confirm:function(message,onOkay,onCancel){return _alertify.dialog(message,"confirm",onOkay,onCancel)||this;},prompt:function(message,onOkay,onCancel){return _alertify.dialog(message,"prompt",onOkay,onCancel)||this;},log:function(message,click){_alertify.log(message,"default",click);return this;},theme:function(themeStr){_alertify.theme(themeStr);return this;},success:function(message,click){_alertify.log(message,"success",click);return this;},error:function(message,click){_alertify.log(message,"error",click);return this;},cancelBtn:function(label){_alertify.cancelBtn(label);return this;},okBtn:function(label){_alertify.okBtn(label);return this;},delay:function(time){_alertify.setDelay(time);return this;},placeholder:function(str){_alertify.promptPlaceholder=str;return this;},defaultValue:function(str){_alertify.promptValue=str;return this;},maxLogItems:function(num){_alertify.setMaxLogItems(num);return this;},closeLogOnClick:function(bool){_alertify.setCloseLogOnClick(!!bool);return this;},logPosition:function(str){_alertify.setLogPosition(str||"");return this;},setLogTemplate:function(templateMethod){_alertify.logTemplateMethod=templateMethod;return this;},clearLogs:function(){_alertify.setupLogContainer().innerHTML="";return this;},version:_alertify.version};}
if("undefined"!==typeof module&&!!module&&!!module.exports){module.exports=function(){return new Alertify();};var obj=new Alertify();for(var key in obj){module.exports[key]=obj[key];}}else if(typeof define==="function"&&define.amd){define('alertify',[],function(){return new Alertify();});}else{window.alertify=new Alertify();}}());
/*!
	Ractive.js v0.8.0-edge
	Mon May 02 2016 22:23:02 GMT+0000 (UTC) - commit 3c485fe5c9b4724a6ddd33d52aa89e2c828c8d80

	http://ractivejs.org
	http://twitter.com/RactiveJS

	Released under the MIT License.
*/
(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define('ractive',factory):((function(){var current=global.Ractive;var next=factory();next.noConflict=function(){global.Ractive=current;return next;};return global.Ractive=next;})());}(this,function(){'use strict';var defaults={el:void 0,append:false,template:null,delimiters:['{{','}}'],tripleDelimiters:['{{{','}}}'],staticDelimiters:['[[',']]'],staticTripleDelimiters:['[[[',']]]'],csp:true,interpolate:false,preserveWhitespace:false,sanitize:false,stripComments:true,data:{},computed:{},magic:false,modifyArrays:true,adapt:[],isolated:false,twoway:true,lazy:false,noIntro:false,transitionsEnabled:true,complete:void 0,css:null,noCssTransform:false};var easing={linear:function(pos){return pos;},easeIn:function(pos){return Math.pow(pos,3);},easeOut:function(pos){return(Math.pow((pos-1),3)+1);},easeInOut:function(pos){if((pos /=0.5)<1){return(0.5*Math.pow(pos,3));}
return(0.5*(Math.pow((pos-2),3)+2));}};var legacy=null;var win=typeof window!=='undefined'?window:null;var doc=win?document:null;var isClient=!!doc;var isJsdom=(typeof navigator!=='undefined'&&/jsDom/.test(navigator.appName));var hasConsole=(typeof console!=='undefined'&&typeof console.warn==='function'&&typeof console.warn.apply==='function');var magicSupported;try{Object.defineProperty({},'test',{value:0});magicSupported=true;}catch(e){magicSupported=false;}
var svg=doc?doc.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure','1.1'):false;var vendors=['o','ms','moz','webkit'];var html='http://www.w3.org/1999/xhtml';var mathml='http://www.w3.org/1998/Math/MathML';var svg$1='http://www.w3.org/2000/svg';var xlink='http://www.w3.org/1999/xlink';var xml='http://www.w3.org/XML/1998/namespace';var xmlns='http://www.w3.org/2000/xmlns';var namespaces={html:html,mathml:mathml,svg:svg$1,xlink:xlink,xml:xml,xmlns:xmlns};var createElement;var matches;var div;var methodNames;var unprefixed;var prefixed;var i;var j;var makeFunction;if(!svg){createElement=function(type,ns,extend){if(ns&&ns!==html){throw'This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you\'re trying to render SVG in an older browser. See http://docs.ractivejs.org/latest/svg-and-older-browsers for more information';}
return extend?doc.createElement(type,extend):doc.createElement(type);};}else{createElement=function(type,ns,extend){if(!ns||ns===html){return extend?doc.createElement(type,extend):doc.createElement(type);}
return extend?doc.createElementNS(ns,type,extend):doc.createElementNS(ns,type);};}
function createDocumentFragment(){return doc.createDocumentFragment();}
function getElement(input){var output;if(!input||typeof input==='boolean'){return;}
if(!win||!doc||!input){return null;}
if(input.nodeType){return input;}
if(typeof input==='string'){output=doc.getElementById(input);if(!output&&doc.querySelector){output=doc.querySelector(input);}
if(output&&output.nodeType){return output;}}
if(input[0]&&input[0].nodeType){return input[0];}
return null;}
if(!isClient){matches=null;}else{div=createElement('div');methodNames=['matches','matchesSelector'];makeFunction=function(methodName){return function(node,selector){return node[methodName](selector);};};i=methodNames.length;while(i--&&!matches){unprefixed=methodNames[i];if(div[unprefixed]){matches=makeFunction(unprefixed);}else{j=vendors.length;while(j--){prefixed=vendors[i]+unprefixed.substr(0,1).toUpperCase()+unprefixed.substring(1);if(div[prefixed]){matches=makeFunction(prefixed);break;}}}}
if(!matches){matches=function(node,selector){var nodes,parentNode,i;parentNode=node.parentNode;if(!parentNode){div.innerHTML='';parentNode=div;node=node.cloneNode();div.appendChild(node);}
nodes=parentNode.querySelectorAll(selector);i=nodes.length;while(i--){if(nodes[i]===node){return true;}}
return false;};}}
function detachNode(node){if(node&&typeof node.parentNode!=='unknown'&&node.parentNode){node.parentNode.removeChild(node);}
return node;}
function safeToStringValue(value){return(value==null||!value.toString)?'':''+value;}
var create;var defineProperty;var defineProperties;try{Object.defineProperty({},'test',{get:function(){},set:function(){}});if(doc){Object.defineProperty(createElement('div'),'test',{value:0});}
defineProperty=Object.defineProperty;}catch(err){defineProperty=function(obj,prop,desc){obj[prop]=desc.value;};}
try{try{Object.defineProperties({},{test:{value:0}});}catch(err){throw err;}
if(doc){Object.defineProperties(createElement('div'),{test:{value:0}});}
defineProperties=Object.defineProperties;}catch(err){defineProperties=function(obj,props){var prop;for(prop in props){if(props.hasOwnProperty(prop)){defineProperty(obj,prop,props[prop]);}}};}
try{Object.create(null);create=Object.create;}catch(err){create=(function(){var F=function(){};return function(proto,props){var obj;if(proto===null){return{};}
F.prototype=proto;obj=new F();if(props){Object.defineProperties(obj,props);}
return obj;};}());}
function extendObj(target){var sources=[],len=arguments.length-1;while(len-->0)sources[len]=arguments[len+1];var prop;sources.forEach(function(source){for(prop in source){if(hasOwn.call(source,prop)){target[prop]=source[prop];}}});return target;}
function fillGaps(target){var sources=[],len=arguments.length-1;while(len-->0)sources[len]=arguments[len+1];sources.forEach(function(s){for(var key in s){if(hasOwn.call(s,key)&&!(key in target)){target[key]=s[key];}}});return target;}
var hasOwn=Object.prototype.hasOwnProperty;var toString=Object.prototype.toString;function isArray(thing){return toString.call(thing)==='[object Array]';}
function isEqual(a,b){if(a===null&&b===null){return true;}
if(typeof a==='object'||typeof b==='object'){return false;}
return a===b;}
function isNumeric(thing){return!isNaN(parseFloat(thing))&&isFinite(thing);}
function isObject(thing){return(thing&&toString.call(thing)==='[object Object]');}
function noop(){}
var alreadyWarned={};var log;var printWarning;var welcome;if(hasConsole){var welcomeIntro=[("%cRactive.js %c0.8.0-edge %cin debug mode, %cmore..."),'color: rgb(114, 157, 52); font-weight: normal;','color: rgb(85, 85, 85); font-weight: normal;','color: rgb(85, 85, 85); font-weight: normal;','color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;'];var welcomeMessage="You're running Ractive 0.8.0-edge in debug mode - messages will be printed to the console to help you fix problems and optimise your application.\n\nTo disable debug mode, add this line at the start of your app:\n  Ractive.DEBUG = false;\n\nTo disable debug mode when your app is minified, add this snippet:\n  Ractive.DEBUG = /unminified/.test(function(){/*unminified*/});\n\nGet help and support:\n  http://docs.ractivejs.org\n  http://stackoverflow.com/questions/tagged/ractivejs\n  http://groups.google.com/forum/#!forum/ractive-js\n  http://twitter.com/ractivejs\n\nFound a bug? Raise an issue:\n  https://github.com/ractivejs/ractive/issues\n\n";welcome=function(){var hasGroup=!!console.groupCollapsed;console[hasGroup?'groupCollapsed':'log'].apply(console,welcomeIntro);console.log(welcomeMessage);if(hasGroup){console.groupEnd(welcomeIntro);}
welcome=noop;};printWarning=function(message,args){welcome();if(typeof args[args.length-1]==='object'){var options=args.pop();var ractive=options?options.ractive:null;if(ractive){var name;if(ractive.component&&(name=ractive.component.name)){message="<"+name+"> "+message;}
var node;if(node=(options.node||(ractive.fragment&&ractive.fragment.rendered&&ractive.find('*')))){args.push(node);}}}
console.warn.apply(console,['%cRactive.js: %c'+message,'color: rgb(114, 157, 52);','color: rgb(85, 85, 85);'].concat(args));};log=function(){console.log.apply(console,arguments);};}else{printWarning=log=welcome=noop;}
function format(message,args){return message.replace(/%s/g,function(){return args.shift();});}
function fatal(message){var args=[],len=arguments.length-1;while(len-->0)args[len]=arguments[len+1];message=format(message,args);throw new Error(message);}
function logIfDebug(){if(Ractive.DEBUG){log.apply(null,arguments);}}
function warn(message){var args=[],len=arguments.length-1;while(len-->0)args[len]=arguments[len+1];message=format(message,args);printWarning(message,args);}
function warnOnce(message){var args=[],len=arguments.length-1;while(len-->0)args[len]=arguments[len+1];message=format(message,args);if(alreadyWarned[message]){return;}
alreadyWarned[message]=true;printWarning(message,args);}
function warnIfDebug(){if(Ractive.DEBUG){warn.apply(null,arguments);}}
function warnOnceIfDebug(){if(Ractive.DEBUG){warnOnce.apply(null,arguments);}}
var badArguments='Bad arguments';var noRegistryFunctionReturn='A function was specified for "%s" %s, but no %s was returned';var missingPlugin=function(name,type){return("Missing \""+name+"\" "+type+" plugin. You may need to download a plugin via http://docs.ractivejs.org/latest/plugins#"+type+"s");};function findInViewHierarchy(registryName,ractive,name){var instance=findInstance(registryName,ractive,name);return instance?instance[registryName][name]:null;}
function findInstance(registryName,ractive,name){while(ractive){if(name in ractive[registryName]){return ractive;}
if(ractive.isolated){return null;}
ractive=ractive.parent;}}
function interpolate(from,to,ractive,type){if(from===to)return null;if(type){var interpol=findInViewHierarchy('interpolators',ractive,type);if(interpol)return interpol(from,to)||null;fatal(missingPlugin(type,'interpolator'));}
return interpolators.number(from,to)||interpolators.array(from,to)||interpolators.object(from,to)||null;}
function snap(to){return function(){return to;};}
var interpolators={number:function(from,to){var delta;if(!isNumeric(from)||!isNumeric(to)){return null;}
from=+from;to=+to;delta=to-from;if(!delta){return function(){return from;};}
return function(t){return from+(t*delta);};},array:function(from,to){var intermediate,interpolators,len,i;if(!isArray(from)||!isArray(to)){return null;}
intermediate=[];interpolators=[];i=len=Math.min(from.length,to.length);while(i--){interpolators[i]=interpolate(from[i],to[i]);}
for(i=len;i<from.length;i+=1){intermediate[i]=from[i];}
for(i=len;i<to.length;i+=1){intermediate[i]=to[i];}
return function(t){var i=len;while(i--){intermediate[i]=interpolators[i](t);}
return intermediate;};},object:function(from,to){var properties,len,interpolators,intermediate,prop;if(!isObject(from)||!isObject(to)){return null;}
properties=[];intermediate={};interpolators={};for(prop in from){if(hasOwn.call(from,prop)){if(hasOwn.call(to,prop)){properties.push(prop);interpolators[prop]=interpolate(from[prop],to[prop])||snap(to[prop]);}
else{intermediate[prop]=from[prop];}}}
for(prop in to){if(hasOwn.call(to,prop)&&!hasOwn.call(from,prop)){intermediate[prop]=to[prop];}}
len=properties.length;return function(t){var i=len,prop;while(i--){prop=properties[i];intermediate[prop]=interpolators[prop](t);}
return intermediate;};}};var refPattern=/\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g;var splitPattern=/([^\\](?:\\\\)*)\./;var escapeKeyPattern=/\\|\./g;var unescapeKeyPattern=/((?:\\)+)\1|\\(\.)/g;function escapeKey(key){if(typeof key==='string'){return key.replace(escapeKeyPattern,'\\$&');}
return key;}
function normalise(ref){return ref?ref.replace(refPattern,'.$1'):'';}
function splitKeypathI(keypath){var result=[],match;keypath=normalise(keypath);while(match=splitPattern.exec(keypath)){var index=match.index+match[1].length;result.push(keypath.substr(0,index));keypath=keypath.substr(index+1);}
result.push(keypath);return result;}
function unescapeKey(key){if(typeof key==='string'){return key.replace(unescapeKeyPattern,'$1$2');}
return key;}
var errorMessage='Cannot add to a non-numeric value';function add(ractive,keypath,d){if(typeof keypath!=='string'||!isNumeric(d)){throw new Error('Bad arguments');}
var changes;if(/\*/.test(keypath)){changes={};ractive.viewmodel.findMatches(splitKeypathI(keypath)).forEach(function(model){var value=model.get();if(!isNumeric(value))throw new Error(errorMessage);changes[model.getKeypath()]=value+d;});return ractive.set(changes);}
var value=ractive.get(keypath);if(!isNumeric(value)){throw new Error(errorMessage);}
return ractive.set(keypath,+value+d);}
function Ractive$add(keypath,d){return add(this,keypath,(d===undefined?1:+d));}
var deprecations={construct:{deprecated:'beforeInit',replacement:'onconstruct'},render:{deprecated:'init',message:'The "init" method has been deprecated '+'and will likely be removed in a future release. '+'You can either use the "oninit" method which will fire '+'only once prior to, and regardless of, any eventual ractive '+'instance being rendered, or if you need to access the '+'rendered DOM, use "onrender" instead. '+'See http://docs.ractivejs.org/latest/migrating for more information.'},complete:{deprecated:'complete',replacement:'oncomplete'}};var Hook=function Hook(event){this.event=event;this.method='on'+event;this.deprecate=deprecations[event];};Hook.prototype.call=function call(method,ractive,arg){if(ractive[method]){arg?ractive[method](arg):ractive[method]();return true;}};Hook.prototype.fire=function fire(ractive,arg){this.call(this.method,ractive,arg);if(!ractive[this.method]&&this.deprecate&&this.call(this.deprecate.deprecated,ractive,arg)){if(this.deprecate.message){warnIfDebug(this.deprecate.message);}else{warnIfDebug('The method "%s" has been deprecated in favor of "%s" and will likely be removed in a future release. See http://docs.ractivejs.org/latest/migrating for more information.',this.deprecate.deprecated,this.deprecate.replacement);}}
arg?ractive.fire(this.event,arg):ractive.fire(this.event);};function addToArray(array,value){var index=array.indexOf(value);if(index===-1){array.push(value);}}
function arrayContains(array,value){for(var i=0,c=array.length;i<c;i++){if(array[i]==value){return true;}}
return false;}
function arrayContentsMatch(a,b){var i;if(!isArray(a)||!isArray(b)){return false;}
if(a.length!==b.length){return false;}
i=a.length;while(i--){if(a[i]!==b[i]){return false;}}
return true;}
function ensureArray(x){if(typeof x==='string'){return[x];}
if(x===undefined){return[];}
return x;}
function lastItem(array){return array[array.length-1];}
function removeFromArray(array,member){if(!array){return;}
var index=array.indexOf(member);if(index!==-1){array.splice(index,1);}}
function toArray(arrayLike){var array=[],i=arrayLike.length;while(i--){array[i]=arrayLike[i];}
return array;}
var _Promise;var PENDING={};var FULFILLED={};var REJECTED={};if(typeof Promise==='function'){_Promise=Promise;}else{_Promise=function(callback){var fulfilledHandlers=[],rejectedHandlers=[],state=PENDING,result,dispatchHandlers,makeResolver,fulfil,reject,promise;makeResolver=function(newState){return function(value){if(state!==PENDING){return;}
result=value;state=newState;dispatchHandlers=makeDispatcher((state===FULFILLED?fulfilledHandlers:rejectedHandlers),result);wait(dispatchHandlers);};};fulfil=makeResolver(FULFILLED);reject=makeResolver(REJECTED);try{callback(fulfil,reject);}catch(err){reject(err);}
promise={then:function(onFulfilled,onRejected){var promise2=new _Promise(function(fulfil,reject){var processResolutionHandler=function(handler,handlers,forward){if(typeof handler==='function'){handlers.push(function(p1result){var x;try{x=handler(p1result);resolve(promise2,x,fulfil,reject);}catch(err){reject(err);}});}else{handlers.push(forward);}};processResolutionHandler(onFulfilled,fulfilledHandlers,fulfil);processResolutionHandler(onRejected,rejectedHandlers,reject);if(state!==PENDING){wait(dispatchHandlers);}});return promise2;}};promise['catch']=function(onRejected){return this.then(null,onRejected);};return promise;};_Promise.all=function(promises){return new _Promise(function(fulfil,reject){var result=[],pending,i,processPromise;if(!promises.length){fulfil(result);return;}
processPromise=function(promise,i){if(promise&&typeof promise.then==='function'){promise.then(function(value){result[i]=value;--pending||fulfil(result);},reject);}
else{result[i]=promise;--pending||fulfil(result);}};pending=i=promises.length;while(i--){processPromise(promises[i],i);}});};_Promise.resolve=function(value){return new _Promise(function(fulfil){fulfil(value);});};_Promise.reject=function(reason){return new _Promise(function(fulfil,reject){reject(reason);});};}
var Promise$1=_Promise;function wait(callback){setTimeout(callback,0);}
function makeDispatcher(handlers,result){return function(){var handler;while(handler=handlers.shift()){handler(result);}};}
function resolve(promise,x,fulfil,reject){var then;if(x===promise){throw new TypeError('A promise\'s fulfillment handler cannot return the same promise');}
if(x instanceof _Promise){x.then(fulfil,reject);}
else if(x&&(typeof x==='object'||typeof x==='function')){try{then=x.then;}catch(e){reject(e);return;}
if(typeof then==='function'){var called,resolvePromise,rejectPromise;resolvePromise=function(y){if(called){return;}
called=true;resolve(promise,y,fulfil,reject);};rejectPromise=function(r){if(called){return;}
called=true;reject(r);};try{then.call(x,resolvePromise,rejectPromise);}catch(e){if(!called){reject(e);called=true;return;}}}
else{fulfil(x);}}
else{fulfil(x);}}
var TransitionManager=function TransitionManager(callback,parent){this.callback=callback;this.parent=parent;this.intros=[];this.outros=[];this.children=[];this.totalChildren=this.outroChildren=0;this.detachQueue=[];this.outrosComplete=false;if(parent){parent.addChild(this);}};TransitionManager.prototype.add=function add(transition){var list=transition.isIntro?this.intros:this.outros;list.push(transition);};TransitionManager.prototype.addChild=function addChild(child){this.children.push(child);this.totalChildren+=1;this.outroChildren+=1;};TransitionManager.prototype.decrementOutros=function decrementOutros(){this.outroChildren-=1;check(this);};TransitionManager.prototype.decrementTotal=function decrementTotal(){this.totalChildren-=1;check(this);};TransitionManager.prototype.detachNodes=function detachNodes(){this.detachQueue.forEach(detach);this.children.forEach(_detachNodes);};TransitionManager.prototype.remove=function remove(transition){var list=transition.isIntro?this.intros:this.outros;removeFromArray(list,transition);check(this);};TransitionManager.prototype.start=function start(){detachImmediate(this);this.intros.concat(this.outros).forEach(function(t){return t.start();});this.ready=true;check(this);};function detach(element){element.detach();}
function _detachNodes(tm){tm.detachNodes();}
function check(tm){if(!tm.ready||tm.outros.length||tm.outroChildren)return;if(!tm.outrosComplete){if(tm.parent&&!tm.parent.outrosComplete){tm.parent.decrementOutros(tm);}else{tm.detachNodes();}
tm.outrosComplete=true;}
if(!tm.intros.length&&!tm.totalChildren){if(typeof tm.callback==='function'){tm.callback();}
if(tm.parent){tm.parent.decrementTotal();}}}
function detachImmediate(manager){var queue=manager.detachQueue;var outros=collectAllOutros(manager);var i=queue.length,j=0,node,trans;start:while(i--){node=queue[i].node;j=outros.length;while(j--){trans=outros[j].node;if(trans===node||trans.contains(node)||node.contains(trans))continue start;}
queue[i].detach();queue.splice(i,1);}}
function collectAllOutros(manager,list){if(!list){list=[];var parent=manager;while(parent.parent)parent=parent.parent;return collectAllOutros(parent,list);}else{var i=manager.children.length;while(i--){list=collectAllOutros(manager.children[i],list);}
list=list.concat(manager.outros);return list;}}
var changeHook=new Hook('change');var batch;var runloop={start:function(instance,returnPromise){var promise,fulfilPromise;if(returnPromise){promise=new Promise$1(function(f){return(fulfilPromise=f);});}
batch={previousBatch:batch,transitionManager:new TransitionManager(fulfilPromise,batch&&batch.transitionManager),fragments:[],tasks:[],immediateObservers:[],deferredObservers:[],ractives:[],instance:instance};return promise;},end:function(){flushChanges();batch=batch.previousBatch;},addFragment:function(fragment){addToArray(batch.fragments,fragment);},addInstance:function(instance){if(batch)addToArray(batch.ractives,instance);},addObserver:function(observer,defer){addToArray(defer?batch.deferredObservers:batch.immediateObservers,observer);},registerTransition:function(transition){transition._manager=batch.transitionManager;batch.transitionManager.add(transition);},detachWhenReady:function(thing){batch.transitionManager.detachQueue.push(thing);},scheduleTask:function(task,postRender){var _batch;if(!batch){task();}else{_batch=batch;while(postRender&&_batch.previousBatch){_batch=_batch.previousBatch;}
_batch.tasks.push(task);}}};function dispatch(observer){observer.dispatch();}
function flushChanges(){var which=batch.immediateObservers;batch.immediateObservers=[];which.forEach(dispatch);var i=batch.fragments.length;var fragment;which=batch.fragments;batch.fragments=[];var ractives=batch.ractives;batch.ractives=[];while(i--){fragment=which[i];var ractive=fragment.ractive;changeHook.fire(ractive,ractive.viewmodel.changes);ractive.viewmodel.changes={};removeFromArray(ractives,ractive);fragment.update();}
i=ractives.length;while(i--){var ractive$1=ractives[i];changeHook.fire(ractive$1,ractive$1.viewmodel.changes);ractive$1.viewmodel.changes={};}
batch.transitionManager.start();which=batch.deferredObservers;batch.deferredObservers=[];which.forEach(dispatch);var tasks=batch.tasks;batch.tasks=[];for(i=0;i<tasks.length;i+=1){tasks[i]();}
if(batch.fragments.length||batch.immediateObservers.length||batch.deferredObservers.length||batch.ractives.length)return flushChanges();}
var noAnimation=Promise$1.resolve();defineProperty(noAnimation,'stop',{value:noop});var linear=easing.linear;function getOptions(options,instance){options=options||{};var easing;if(options.easing){easing=typeof options.easing==='function'?options.easing:instance.easing[options.easing];}
return{easing:easing||linear,duration:'duration'in options?options.duration:400,complete:options.complete||noop,step:options.step||noop};}
function Ractive$animate(keypath,to,options){if(typeof keypath==='object'){var keys=Object.keys(keypath);throw new Error(("ractive.animate(...) no longer supports objects. Instead of ractive.animate({\n  "+(keys.map(function(key){return("'"+key+"': "+(keypath[key]));}).join('\n  '))+"\n}, {...}), do\n\n"+(keys.map(function(key){return("ractive.animate('"+key+"', "+(keypath[key])+", {...});");}).join('\n'))+"\n"));}
options=getOptions(options,this);var model=this.viewmodel.joinAll(splitKeypathI(keypath));var from=model.get();if(isEqual(from,to)){options.complete(options.to);return noAnimation;}
var interpolator=interpolate(from,to,this,options.interpolator);if(!interpolator){runloop.start();model.set(to);runloop.end();return noAnimation;}
return model.animate(from,to,options,interpolator);}
var detachHook=new Hook('detach');function Ractive$detach(){if(this.isDetached){return this.el;}
if(this.el){removeFromArray(this.el.__ractive_instances__,this);}
this.el=this.fragment.detach();this.isDetached=true;detachHook.fire(this);return this.el;}
function Ractive$find(selector){if(!this.el)throw new Error(("Cannot call ractive.find('"+selector+"') unless instance is rendered to the DOM"));return this.fragment.find(selector);}
function sortByDocumentPosition(node,otherNode){if(node.compareDocumentPosition){var bitmask=node.compareDocumentPosition(otherNode);return(bitmask&2)?1:-1;}
return sortByItemPosition(node,otherNode);}
function sortByItemPosition(a,b){var ancestryA=getAncestry(a.component||a._ractive.proxy);var ancestryB=getAncestry(b.component||b._ractive.proxy);var oldestA=lastItem(ancestryA);var oldestB=lastItem(ancestryB);var mutualAncestor;while(oldestA&&(oldestA===oldestB)){ancestryA.pop();ancestryB.pop();mutualAncestor=oldestA;oldestA=lastItem(ancestryA);oldestB=lastItem(ancestryB);}
oldestA=oldestA.component||oldestA;oldestB=oldestB.component||oldestB;var fragmentA=oldestA.parentFragment;var fragmentB=oldestB.parentFragment;if(fragmentA===fragmentB){var indexA=fragmentA.items.indexOf(oldestA);var indexB=fragmentB.items.indexOf(oldestB);return(indexA-indexB)||ancestryA.length-ancestryB.length;}
var fragments=mutualAncestor.iterations;if(fragments){var indexA$1=fragments.indexOf(fragmentA);var indexB$1=fragments.indexOf(fragmentB);return(indexA$1-indexB$1)||ancestryA.length-ancestryB.length;}
throw new Error('An unexpected condition was met while comparing the position of two components. Please file an issue at https://github.com/ractivejs/ractive/issues - thanks!');}
function getParent(item){var parentFragment=item.parentFragment;if(parentFragment)return parentFragment.owner;if(item.component&&(parentFragment=item.component.parentFragment)){return parentFragment.owner;}}
function getAncestry(item){var ancestry=[item];var ancestor=getParent(item);while(ancestor){ancestry.push(ancestor);ancestor=getParent(ancestor);}
return ancestry;}
var Query=function Query(ractive,selector,live,isComponentQuery){this.ractive=ractive;this.selector=selector;this.live=live;this.isComponentQuery=isComponentQuery;this.result=[];this.dirty=true;};Query.prototype.add=function add(item){this.result.push(item);this.makeDirty();};Query.prototype.cancel=function cancel(){var liveQueries=this._root[this.isComponentQuery?'liveComponentQueries':'liveQueries'];var selector=this.selector;var index=liveQueries.indexOf(selector);if(index!==-1){liveQueries.splice(index,1);liveQueries[selector]=null;}};Query.prototype.init=function init(){this.dirty=false;};Query.prototype.makeDirty=function makeDirty(){var this$1=this;if(!this.dirty){this.dirty=true;runloop.scheduleTask(function(){return this$1.update();});}};Query.prototype.remove=function remove(nodeOrComponent){var index=this.result.indexOf(this.isComponentQuery?nodeOrComponent.instance:nodeOrComponent);if(index!==-1)this.result.splice(index,1);};Query.prototype.update=function update(){this.result.sort(this.isComponentQuery?sortByItemPosition:sortByDocumentPosition);this.dirty=false;};Query.prototype.test=function test(item){return this.isComponentQuery?(!this.selector||item.name===this.selector):(item?matches(item,this.selector):null);};function Ractive$findAll(selector,options){if(!this.el)throw new Error(("Cannot call ractive.findAll('"+selector+"', ...) unless instance is rendered to the DOM"));options=options||{};var liveQueries=this._liveQueries;var query=liveQueries[selector];if(query){return(options&&options.live)?query:query.slice();}
query=new Query(this,selector,!!options.live,false);if(query.live){liveQueries.push(selector);liveQueries['_'+selector]=query;}
this.fragment.findAll(selector,query);query.init();return query.result;}
function Ractive$findAllComponents(selector,options){options=options||{};var liveQueries=this._liveComponentQueries;var query=liveQueries[selector];if(query){return(options&&options.live)?query:query.slice();}
query=new Query(this,selector,!!options.live,true);if(query.live){liveQueries.push(selector);liveQueries['_'+selector]=query;}
this.fragment.findAllComponents(selector,query);query.init();return query.result;}
function Ractive$findComponent(selector){return this.fragment.findComponent(selector);}
function Ractive$findContainer(selector){if(this.container){if(this.container.component&&this.container.component.name===selector){return this.container;}else{return this.container.findContainer(selector);}}
return null;}
function Ractive$findParent(selector){if(this.parent){if(this.parent.component&&this.parent.component.name===selector){return this.parent;}else{return this.parent.findParent(selector);}}
return null;}
function enqueue(ractive,event){if(ractive.event){ractive._eventQueue.push(ractive.event);}
ractive.event=event;}
function dequeue(ractive){if(ractive._eventQueue.length){ractive.event=ractive._eventQueue.pop();}else{ractive.event=null;}}
var starMaps={};function getPotentialWildcardMatches(keypath){var keys,starMap,mapper,i,result,wildcardKeypath;keys=splitKeypathI(keypath);if(!(starMap=starMaps[keys.length])){starMap=getStarMap(keys.length);}
result=[];mapper=function(star,i){return star?'*':keys[i];};i=starMap.length;while(i--){wildcardKeypath=starMap[i].map(mapper).join('.');if(!result.hasOwnProperty(wildcardKeypath)){result.push(wildcardKeypath);result[wildcardKeypath]=true;}}
return result;}
function getStarMap(num){var ones='',max,binary,starMap,mapper,i,j,l,map;if(!starMaps[num]){starMap=[];while(ones.length<num){ones+=1;}
max=parseInt(ones,2);mapper=function(digit){return digit==='1';};for(i=0;i<=max;i+=1){binary=i.toString(2);while(binary.length<num){binary='0'+binary;}
map=[];l=binary.length;for(j=0;j<l;j++){map.push(mapper(binary[j]));}
starMap[i]=map;}
starMaps[num]=starMap;}
return starMaps[num];}
var wildcardCache={};function fireEvent(ractive,eventName,options){if(options===void 0)options={};if(!eventName){return;}
if(!options.event){options.event={name:eventName,_noArg:true};}else{options.event.name=eventName;}
var eventNames=getWildcardNames(eventName);fireEventAs(ractive,eventNames,options.event,options.args,true);}
function getWildcardNames(eventName){if(wildcardCache.hasOwnProperty(eventName)){return wildcardCache[eventName];}else{return wildcardCache[eventName]=getPotentialWildcardMatches(eventName);}}
function fireEventAs(ractive,eventNames,event,args,initialFire){if(initialFire===void 0)initialFire=false;var subscribers,i,bubble=true;enqueue(ractive,event);for(i=eventNames.length;i>=0;i--){subscribers=ractive._subs[eventNames[i]];if(subscribers){bubble=notifySubscribers(ractive,subscribers,event,args)&&bubble;}}
dequeue(ractive);if(ractive.parent&&bubble){if(initialFire&&ractive.component){var fullName=ractive.component.name+'.'+eventNames[eventNames.length-1];eventNames=getWildcardNames(fullName);if(event&&!event.component){event.component=ractive;}}
fireEventAs(ractive.parent,eventNames,event,args);}}
function notifySubscribers(ractive,subscribers,event,args){var originalEvent=null,stopEvent=false;if(event&&!event._noArg){args=[event].concat(args);}
subscribers=subscribers.slice();for(var i=0,len=subscribers.length;i<len;i+=1){if(subscribers[i].apply(ractive,args)===false){stopEvent=true;}}
if(event&&!event._noArg&&stopEvent&&(originalEvent=event.original)){originalEvent.preventDefault&&originalEvent.preventDefault();originalEvent.stopPropagation&&originalEvent.stopPropagation();}
return!stopEvent;}
function Ractive$fire(eventName){var args=[],len=arguments.length-1;while(len-->0)args[len]=arguments[len+1];fireEvent(this,eventName,{args:args});}
function badReference(key){throw new Error(("An index or key reference ("+key+") cannot have child properties"));}
function resolveAmbiguousReference(fragment,ref){var localViewmodel=fragment.findContext().root;var keys=splitKeypathI(ref);var key=keys[0];var hasContextChain;var crossedComponentBoundary;var aliases;while(fragment){if(fragment.isIteration){if(key===fragment.parent.keyRef){if(keys.length>1)badReference(key);return fragment.context.getKeyModel();}
if(key===fragment.parent.indexRef){if(keys.length>1)badReference(key);return fragment.context.getIndexModel(fragment.index);}}
if(((aliases=fragment.owner.aliases)||(aliases=fragment.aliases))&&aliases.hasOwnProperty(key)){var model=aliases[key];if(keys.length===1)return model;else if(typeof model.joinAll==='function'){return model.joinAll(keys.slice(1));}}
if(fragment.context){if(!fragment.isRoot||fragment.ractive.component)hasContextChain=true;if(fragment.context.has(key)){if(crossedComponentBoundary){localViewmodel.map(key,fragment.context.joinKey(key));}
return fragment.context.joinAll(keys);}}
if(fragment.componentParent&&!fragment.ractive.isolated){fragment=fragment.componentParent;crossedComponentBoundary=true;}else{fragment=fragment.parent;}}
if(!hasContextChain){return localViewmodel.joinAll(keys);}}
var stack=[];var captureGroup;function startCapturing(){stack.push(captureGroup=[]);}
function stopCapturing(){var dependencies=stack.pop();captureGroup=stack[stack.length-1];return dependencies;}
function capture(model){if(captureGroup){captureGroup.push(model);}}
function bind(x){x.bind();}
function cancel(x){x.cancel();}
function handleChange(x){x.handleChange();}
function mark(x){x.mark();}
function render(x){x.render();}
function rebind(x){x.rebind();}
function teardown(x){x.teardown();}
function unbind(x){x.unbind();}
function unrender(x){x.unrender();}
function unrenderAndDestroy(x){x.unrender(true);}
function update(x){x.update();}
function toString$1(x){return x.toString();}
function toEscapedString(x){return x.toString(true);}
var requestAnimationFrame;if(!win){requestAnimationFrame=null;}else{(function(vendors,lastTime,win){var x,setTimeout;if(win.requestAnimationFrame){return;}
for(x=0;x<vendors.length&&!win.requestAnimationFrame;++x){win.requestAnimationFrame=win[vendors[x]+'RequestAnimationFrame'];}
if(!win.requestAnimationFrame){setTimeout=win.setTimeout;win.requestAnimationFrame=function(callback){var currTime,timeToCall,id;currTime=Date.now();timeToCall=Math.max(0,16-(currTime-lastTime));id=setTimeout(function(){callback(currTime+timeToCall);},timeToCall);lastTime=currTime+timeToCall;return id;};}}(vendors,0,win));requestAnimationFrame=win.requestAnimationFrame;}
var rAF=requestAnimationFrame;var getTime=(win&&win.performance&&typeof win.performance.now==='function')?function(){return win.performance.now();}:function(){return Date.now();};var tickers=[];var running=false;function tick(){runloop.start();var now=getTime();var i;var ticker;for(i=0;i<tickers.length;i+=1){ticker=tickers[i];if(!ticker.tick(now)){tickers.splice(i--,1);}}
runloop.end();if(tickers.length){rAF(tick);}else{running=false;}}
var Ticker=function Ticker(options){this.duration=options.duration;this.step=options.step;this.complete=options.complete;this.easing=options.easing;this.start=getTime();this.end=this.start+this.duration;this.running=true;tickers.push(this);if(!running)rAF(tick);};Ticker.prototype.tick=function tick$1(now){if(!this.running)return false;if(now>this.end){if(this.step)this.step(1);if(this.complete)this.complete(1);return false;}
var elapsed=now-this.start;var eased=this.easing(elapsed / this.duration);if(this.step)this.step(eased);return true;};Ticker.prototype.stop=function stop(){if(this.abort)this.abort();this.running=false;};var prefixers={};function prefixKeypath(obj,prefix){var prefixed={},key;if(!prefix){return obj;}
prefix+='.';for(key in obj){if(obj.hasOwnProperty(key)){prefixed[prefix+key]=obj[key];}}
return prefixed;}
function getPrefixer(rootKeypath){var rootDot;if(!prefixers[rootKeypath]){rootDot=rootKeypath?rootKeypath+'.':'';prefixers[rootKeypath]=function(relativeKeypath,value){var obj;if(typeof relativeKeypath==='string'){obj={};obj[rootDot+relativeKeypath]=value;return obj;}
if(typeof relativeKeypath==='object'){return rootDot?prefixKeypath(relativeKeypath,rootKeypath):relativeKeypath;}};}
return prefixers[rootKeypath];}
var KeyModel=function KeyModel(key){this.value=key;this.isReadonly=true;this.dependants=[];};KeyModel.prototype.get=function get(){return unescapeKey(this.value);};KeyModel.prototype.getKeypath=function getKeypath(){return unescapeKey(this.value);};KeyModel.prototype.rebind=function rebind(key){this.value=key;this.dependants.forEach(handleChange);};KeyModel.prototype.register=function register(dependant){this.dependants.push(dependant);};KeyModel.prototype.unregister=function unregister(dependant){removeFromArray(this.dependants,dependant);};var KeypathModel=function KeypathModel(parent,ractive){this.parent=parent;this.ractive=ractive;this.value=ractive?parent.getKeypath(ractive):parent.getKeypath();this.dependants=[];this.children=[];};KeypathModel.prototype.addChild=function addChild(model){this.children.push(model);model.owner=this;};KeypathModel.prototype.get=function get(){return this.value;};KeypathModel.prototype.getKeypath=function getKeypath(){return this.value;};KeypathModel.prototype.handleChange=function handleChange$1(){this.value=this.ractive?this.parent.getKeypath(this.ractive):this.parent.getKeypath();if(this.ractive&&this.owner){this.ractive.viewmodel.keypathModels[this.owner.value]=this;}
this.children.forEach(handleChange);this.dependants.forEach(handleChange);};KeypathModel.prototype.register=function register(dependant){this.dependants.push(dependant);};KeypathModel.prototype.removeChild=function removeChild(model){removeFromArray(this.children,model);};KeypathModel.prototype.teardown=function teardown$1(){if(this.owner)this.owner.removeChild(this);this.children.forEach(teardown);};KeypathModel.prototype.unregister=function unregister(dependant){removeFromArray(this.dependants,dependant);};var hasProp=Object.prototype.hasOwnProperty;function updateFromBindings(model){model.updateFromBindings(true);}
function updateKeypathDependants(model){model.updateKeypathDependants();}
var originatingModel=null;var Model=function Model(parent,key){this.deps=[];this.children=[];this.childByKey={};this.indexModels=[];this.unresolved=[];this.unresolvedByKey={};this.bindings=[];this.patternObservers=[];this.value=undefined;this.ticker=null;if(parent){this.parent=parent;this.root=parent.root;this.key=unescapeKey(key);this.isReadonly=parent.isReadonly;if(parent.value){this.value=parent.value[this.key];this.adapt();}}};Model.prototype.adapt=function adapt(){var this$1=this;var adaptors=this.root.adaptors;var len=adaptors.length;this.rewrap=false;if(len===0)return;var value=this.value;var ractive=this.root.ractive;var keypath=this.getKeypath();if(this.wrapper){var shouldTeardown=!this.wrapper.reset||this.wrapper.reset(value)===false;if(shouldTeardown){this.wrapper.teardown();this.wrapper=null;if(this.value!==undefined){var parentValue=this.parent.value||this.parent.createBranch(this.key);if(parentValue[this.key]!==this.value)parentValue[this.key]=value;}}else{this.value=this.wrapper.get();return;}}
var i;for(i=0;i<len;i+=1){var adaptor=adaptors[i];if(adaptor.filter(value,keypath,ractive)){this$1.wrapper=adaptor.wrap(ractive,value,keypath,getPrefixer(keypath));this$1.wrapper.value=this$1.value;this$1.wrapper.__model=this$1;this$1.value=this$1.wrapper.get();break;}}};Model.prototype.addUnresolved=function addUnresolved(key,resolver){if(!this.unresolvedByKey[key]){this.unresolved.push(key);this.unresolvedByKey[key]=[];}
this.unresolvedByKey[key].push(resolver);};Model.prototype.animate=function animate(from,to,options,interpolator){var this$1=this;if(this.ticker)this.ticker.stop();var fulfilPromise;var promise=new Promise$1(function(fulfil){return fulfilPromise=fulfil;});this.ticker=new Ticker({duration:options.duration,easing:options.easing,step:function(t){var value=interpolator(t);this$1.applyValue(value);if(options.step)options.step(t,value);},complete:function(){this$1.applyValue(to);if(options.complete)options.complete(to);this$1.ticker=null;fulfilPromise();}});promise.stop=this.ticker.stop;return promise;};Model.prototype.applyValue=function applyValue(value){if(isEqual(value,this.value))return;this.registerChange(this.getKeypath(),value);if(this.parent.wrapper&&this.parent.wrapper.set){this.parent.wrapper.set(this.key,value);this.parent.value=this.parent.wrapper.get();this.value=this.parent.value[this.key];this.adapt();}else if(this.wrapper){this.value=value;this.adapt();}else{var parentValue=this.parent.value||this.parent.createBranch(this.key);parentValue[this.key]=value;this.value=value;this.adapt();}
this.parent.clearUnresolveds();this.clearUnresolveds();var previousOriginatingModel=originatingModel;originatingModel=this;this.children.forEach(mark);this.deps.forEach(handleChange);this.notifyUpstream();originatingModel=previousOriginatingModel;};Model.prototype.clearUnresolveds=function clearUnresolveds(specificKey){var this$1=this;var i=this.unresolved.length;while(i--){var key=this$1.unresolved[i];if(specificKey&&key!==specificKey)continue;var resolvers=this$1.unresolvedByKey[key];var hasKey=this$1.has(key);var j=resolvers.length;while(j--){if(hasKey)resolvers[j].attemptResolution();if(resolvers[j].resolved)resolvers.splice(j,1);}
if(!resolvers.length){this$1.unresolved.splice(i,1);this$1.unresolvedByKey[key]=null;}}};Model.prototype.createBranch=function createBranch(key){var branch=isNumeric(key)?[]:{};this.set(branch);return branch;};Model.prototype.findMatches=function findMatches(keys){var len=keys.length;var existingMatches=[this];var matches;var i;var loop=function(){var key=keys[i];if(key==='*'){matches=[];existingMatches.forEach(function(model){matches.push.apply(matches,model.getValueChildren(model.get()));});}else{matches=existingMatches.map(function(model){return model.joinKey(key);});}
existingMatches=matches;};for(i=0;i<len;i+=1)loop();return matches;};Model.prototype.get=function get(shouldCapture){if(shouldCapture)capture(this);return this.value;};Model.prototype.getIndexModel=function getIndexModel(fragmentIndex){var indexModels=this.parent.indexModels;if(typeof this.key==='string'&&fragmentIndex!==undefined){return new KeyModel(fragmentIndex);}else if(!indexModels[this.key]){indexModels[this.key]=new KeyModel(this.key);}
return indexModels[this.key];};Model.prototype.getKeyModel=function getKeyModel(){return new KeyModel(escapeKey(this.key));};Model.prototype.getKeypathModel=function getKeypathModel(ractive){var keypath=this.getKeypath(),model=this.keypathModel||(this.keypathModel=new KeypathModel(this));if(ractive&&ractive.component){var mapped=this.getKeypath(ractive);if(mapped!==keypath){var map=ractive.viewmodel.keypathModels||(ractive.viewmodel.keypathModels={});var child=map[keypath]||(map[keypath]=new KeypathModel(this,ractive));model.addChild(child);return child;}}
return model;};Model.prototype.getKeypath=function getKeypath(ractive){var root=this.parent.isRoot?escapeKey(this.key):this.parent.getKeypath()+'.'+escapeKey(this.key);if(ractive&&ractive.component){var map=ractive.viewmodel.mappings;for(var k in map){if(root.indexOf(map[k].getKeypath())>=0){root=root.replace(map[k].getKeypath(),k);break;}}}
return root;};Model.prototype.getValueChildren=function getValueChildren(value){var this$1=this;var children;if(isArray(value)){children=[];if(originatingModel&&originatingModel.parent===this&&originatingModel.key==='length'){children.push(originatingModel);}
value.forEach(function(m,i){children.push(this$1.joinKey(i));});}
else if(isObject(value)||typeof value==='function'){children=Object.keys(value).map(function(key){return this$1.joinKey(key);});}
else if(value!=null){return[];}
return children;};Model.prototype.has=function has(key){var value=this.get();if(!value)return false;key=unescapeKey(key);if(hasProp.call(value,key))return true;var constructor=value.constructor;while(constructor!==Function&&constructor!==Array&&constructor!==Object){if(hasProp.call(constructor.prototype,key))return true;constructor=constructor.constructor;}
return false;};Model.prototype.joinKey=function joinKey(key){if(key===undefined||key==='')return this;if(!this.childByKey.hasOwnProperty(key)){var child=new Model(this,key);this.children.push(child);this.childByKey[key]=child;}
return this.childByKey[key];};Model.prototype.joinAll=function joinAll(keys){var model=this;for(var i=0;i<keys.length;i+=1){model=model.joinKey(keys[i]);}
return model;};Model.prototype.mark=function mark$1(){var value=this.retrieve();if(!isEqual(value,this.value)){var old=this.value;this.value=value;if(old!==value||this.rewrap)this.adapt();this.children.forEach(mark);this.deps.forEach(handleChange);this.clearUnresolveds();}};Model.prototype.merge=function merge(array,comparator){var oldArray=comparator?this.value.map(comparator):this.value;var newArray=comparator?array.map(comparator):array;var oldLength=oldArray.length;var usedIndices={};var firstUnusedIndex=0;var newIndices=oldArray.map(function(item){var index;var start=firstUnusedIndex;do{index=newArray.indexOf(item,start);if(index===-1){return-1;}
start=index+1;}while((usedIndices[index]===true)&&start<oldLength);if(index===firstUnusedIndex){firstUnusedIndex+=1;}
usedIndices[index]=true;return index;});this.parent.value[this.key]=array;this._merged=true;this.shuffle(newIndices);};Model.prototype.notifyUpstream=function notifyUpstream(){var parent=this.parent,prev=this;while(parent){if(parent.patternObservers.length)parent.patternObservers.forEach(function(o){return o.notify(prev.key);});parent.deps.forEach(handleChange);prev=parent;parent=parent.parent;}};Model.prototype.register=function register(dep){this.deps.push(dep);};Model.prototype.registerChange=function registerChange(key,value){if(!this.isRoot){this.root.registerChange(key,value);}else{this.changes[key]=value;runloop.addInstance(this.root.ractive);}};Model.prototype.registerPatternObserver=function registerPatternObserver(observer){this.patternObservers.push(observer);this.register(observer);};Model.prototype.registerTwowayBinding=function registerTwowayBinding(binding){this.bindings.push(binding);};Model.prototype.removeUnresolved=function removeUnresolved(key,resolver){var resolvers=this.unresolvedByKey[key];if(resolvers){removeFromArray(resolvers,resolver);}};Model.prototype.retrieve=function retrieve(){return this.parent.value?this.parent.value[this.key]:undefined;};Model.prototype.set=function set(value){if(this.ticker)this.ticker.stop();this.applyValue(value);};Model.prototype.shuffle=function shuffle(newIndices){var this$1=this;var indexModels=[];newIndices.forEach(function(newIndex,oldIndex){if(newIndex!==oldIndex&&this$1.childByKey[oldIndex])this$1.childByKey[oldIndex].shuffled();if(!~newIndex)return;var model=this$1.indexModels[oldIndex];if(!model)return;indexModels[newIndex]=model;if(newIndex!==oldIndex){model.rebind(newIndex);}});this.indexModels=indexModels;this.deps.forEach(function(dep){if(dep.shuffle)dep.shuffle(newIndices);});this.updateKeypathDependants();this.mark();this.deps.forEach(function(dep){if(!dep.shuffle)dep.handleChange();});};Model.prototype.shuffled=function shuffled(){var this$1=this;var i=this.children.length;while(i--){this$1.children[i].shuffled();}
if(this.wrapper){this.wrapper.teardown();this.wrapper=null;this.rewrap=true;}};Model.prototype.teardown=function teardown$1(){this.children.forEach(teardown);if(this.wrapper)this.wrapper.teardown();if(this.keypathModels){for(var k in this.keypathModels){this.keypathModels[k].teardown();}}};Model.prototype.unregister=function unregister(dependant){removeFromArray(this.deps,dependant);};Model.prototype.unregisterPatternObserver=function unregisterPatternObserver(observer){removeFromArray(this.patternObservers,observer);this.unregister(observer);};Model.prototype.unregisterTwowayBinding=function unregisterTwowayBinding(binding){removeFromArray(this.bindings,binding);};Model.prototype.updateFromBindings=function updateFromBindings$1(cascade){var this$1=this;var i=this.bindings.length;while(i--){var value=this$1.bindings[i].getValue();if(value!==this$1.value)this$1.set(value);}
if(cascade){this.children.forEach(updateFromBindings);}};Model.prototype.updateKeypathDependants=function updateKeypathDependants$1(){this.children.forEach(updateKeypathDependants);if(this.keypathModel)this.keypathModel.handleChange();};var GlobalModel=(function(Model){function GlobalModel(){Model.call(this,null,'@global');this.value=typeof global!=='undefined'?global:window;this.isRoot=true;this.root=this;this.adaptors=[];}
GlobalModel.prototype=Object.create(Model&&Model.prototype);GlobalModel.prototype.constructor=GlobalModel;GlobalModel.prototype.getKeypath=function getKeypath(){return'@global';};GlobalModel.prototype.registerChange=function registerChange(){};return GlobalModel;}(Model));var GlobalModel$1=new GlobalModel();function resolveReference(fragment,ref){var context=fragment.findContext();if(ref==='.'||ref==='this')return context;if(ref==='@keypath')return context.getKeypathModel(fragment.ractive);if(ref==='@rootpath')return context.getKeypathModel();if(ref==='@index'){var repeater=fragment.findRepeatingFragment();if(!repeater.isIteration)return;return repeater.context.getIndexModel(repeater.index);}
if(ref==='@key')return fragment.findRepeatingFragment().context.getKeyModel();if(ref==='@ractive'){return fragment.ractive.viewmodel.getRactiveModel();}
if(ref==='@global'){return GlobalModel$1;}
if(ref[0]==='~')return fragment.ractive.viewmodel.joinAll(splitKeypathI(ref.slice(2)));if(ref[0]==='.'){var parts=ref.split('/');while(parts[0]==='.'||parts[0]==='..'){var part=parts.shift();if(part==='..'){context=context.parent;}}
ref=parts.join('/');if(ref[0]==='.')ref=ref.slice(1);return context.joinAll(splitKeypathI(ref));}
return resolveAmbiguousReference(fragment,ref);}
function Ractive$get(keypath){if(!keypath)return this.viewmodel.get(true);var keys=splitKeypathI(keypath);var key=keys[0];var model;if(!this.viewmodel.has(key)){if(this.component&&!this.isolated){model=resolveReference(this.component.parentFragment,key);if(model){this.viewmodel.map(key,model);}}}
model=this.viewmodel.joinAll(keys);return model.get(true);}
var insertHook=new Hook('insert');function Ractive$insert(target,anchor){if(!this.fragment.rendered){throw new Error('The API has changed - you must call `ractive.render(target[, anchor])` to render your Ractive instance. Once rendered you can use `ractive.insert()`.');}
target=getElement(target);anchor=getElement(anchor)||null;if(!target){throw new Error('You must specify a valid target to insert into');}
target.insertBefore(this.detach(),anchor);this.el=target;(target.__ractive_instances__||(target.__ractive_instances__=[])).push(this);this.isDetached=false;fireInsertHook(this);}
function fireInsertHook(ractive){insertHook.fire(ractive);ractive.findAllComponents('*').forEach(function(child){fireInsertHook(child.instance);});}
function link(there,here){if(here===there||(there+'.').indexOf(here+'.')===0||(here+'.').indexOf(there+'.')===0){throw new Error('A keypath cannot be linked to itself.');}
var promise=runloop.start();var model;var ln=this._links[here];if(ln){if(ln.source.model.str!==there||ln.dest.model.str!==here){ln.unlink();delete this._links[here];this.viewmodel.joinAll(splitKeypathI(here)).set(ln.initialValue);}else{runloop.end();return promise;}}
var sourcePath=splitKeypathI(there);if(!this.viewmodel.has(sourcePath[0])&&this.component){model=resolveReference(this.component.parentFragment,sourcePath[0]);if(model){this.viewmodel.map(sourcePath[0],model);}}
ln=new Link(this.viewmodel.joinAll(sourcePath),this.viewmodel.joinAll(splitKeypathI(here)),this);this._links[here]=ln;ln.source.handleChange();runloop.end();return promise;}
var Link=function Link(source,dest,ractive){this.source=new LinkSide(source,this);this.dest=new LinkSide(dest,this);this.ractive=ractive;this.locked=false;this.initialValue=dest.get();};Link.prototype.sync=function sync(side){if(!this.locked){this.locked=true;if(side===this.dest){this.source.model.set(this.dest.model.get());}else{this.dest.model.set(this.source.model.get());}
this.locked=false;}};Link.prototype.unlink=function unlink(){this.source.model.unregister(this.source);this.dest.model.unregister(this.dest);};var LinkSide=function LinkSide(model,owner){this.model=model;this.owner=owner;model.register(this);};LinkSide.prototype.handleChange=function handleChange(){this.owner.sync(this);};var comparators={};function getComparator(option){if(!option)return null;if(option===true)return JSON.stringify;if(typeof option==='function')return option;if(typeof option==='string'){return comparators[option]||(comparators[option]=function(thing){return thing[option];});}
throw new Error('If supplied, options.compare must be a string, function, or `true`');}
function Ractive$merge(keypath,array,options){var model=this.viewmodel.joinAll(splitKeypathI(keypath));var promise=runloop.start(this,true);var value=model.get();if(array===value){throw new Error('You cannot merge an array with itself');}else if(!isArray(value)||!isArray(array)){throw new Error('You cannot merge an array with a non-array');}
var comparator=getComparator(options&&options.compare);model.merge(array,comparator);runloop.end();return promise;}
function observe(keypath,callback,options){var this$1=this;var observers=[];var map;if(isObject(keypath)){map=keypath;options=callback||{};Object.keys(map).forEach(function(keypath){var callback=map[keypath];keypath.split(' ').forEach(function(keypath){observers.push(createObserver(this$1,keypath,callback,options));});});}
else{var keypaths;if(typeof keypath==='function'){options=callback;callback=keypath;keypaths=[''];}else{keypaths=keypath.split(' ');}
keypaths.forEach(function(keypath){observers.push(createObserver(this$1,keypath,callback,options||{}));});}
this._observers.push.apply(this._observers,observers);return{cancel:function(){observers.forEach(function(observer){removeFromArray(this$1._observers,observer);observer.cancel();});}};}
function createObserver(ractive,keypath,callback,options){var viewmodel=ractive.viewmodel;var keys=splitKeypathI(keypath);var wildcardIndex=keys.indexOf('*');if(!~wildcardIndex){var key=keys[0];if(key!==''&&!viewmodel.has(key)){if(ractive.component){var model=resolveReference(ractive.component.parentFragment,key);if(model)viewmodel.map(key,model);}}
var model$1=viewmodel.joinAll(keys);return new Observer(ractive,model$1,callback,options);}
var baseModel=wildcardIndex===0?viewmodel:viewmodel.joinAll(keys.slice(0,wildcardIndex));return new PatternObserver(ractive,baseModel,keys.splice(wildcardIndex),callback,options);}
var Observer=function Observer(ractive,model,callback,options){this.context=options.context||ractive;this.model=model;this.keypath=model.getKeypath(ractive);this.callback=callback;this.oldValue=undefined;this.newValue=model.get();this.defer=options.defer;this.once=options.once;this.strict=options.strict;this.dirty=false;if(options.init!==false){this.dispatch();}else{this.oldValue=this.newValue;}
model.register(this);};Observer.prototype.cancel=function cancel(){this.model.unregister(this);};Observer.prototype.dispatch=function dispatch(){this.callback.call(this.context,this.newValue,this.oldValue,this.keypath);this.oldValue=this.newValue;this.dirty=false;};Observer.prototype.handleChange=function handleChange(){if(!this.dirty){this.newValue=this.model.get();if(this.strict&&this.newValue===this.oldValue)return;runloop.addObserver(this,this.defer);this.dirty=true;if(this.once)this.cancel();}};var PatternObserver=function PatternObserver(ractive,baseModel,keys,callback,options){var this$1=this;this.context=options.context||ractive;this.ractive=ractive;this.baseModel=baseModel;this.keys=keys;this.callback=callback;var pattern=keys.join('\\.').replace(/\*/g,'(.+)');var baseKeypath=baseModel.getKeypath(ractive);this.pattern=new RegExp(("^"+(baseKeypath?baseKeypath+'\\.':'')+""+pattern+"$"));this.oldValues={};this.newValues={};this.defer=options.defer;this.once=options.once;this.strict=options.strict;this.dirty=false;this.changed=[];this.partial=false;var models=baseModel.findMatches(this.keys);models.forEach(function(model){this$1.newValues[model.getKeypath(this$1.ractive)]=model.get();});if(options.init!==false){this.dispatch();}else{this.oldValues=this.newValues;}
baseModel.registerPatternObserver(this);};PatternObserver.prototype.cancel=function cancel(){this.baseModel.unregisterPatternObserver(this);};PatternObserver.prototype.dispatch=function dispatch(){var this$1=this;Object.keys(this.newValues).forEach(function(keypath){if(this$1.newKeys&&!this$1.newKeys[keypath])return;var newValue=this$1.newValues[keypath];var oldValue=this$1.oldValues[keypath];if(this$1.strict&&newValue===oldValue)return;if(isEqual(newValue,oldValue))return;var args=[newValue,oldValue,keypath];if(keypath){var wildcards=this$1.pattern.exec(keypath).slice(1);args=args.concat(wildcards);}
this$1.callback.apply(this$1.context,args);});if(this.partial){for(var k in this.newValues){this.oldValues[k]=this.newValues[k];}}else{this.oldValues=this.newValues;}
this.newKeys=null;this.dirty=false;};PatternObserver.prototype.notify=function notify(key){this.changed.push(key);};PatternObserver.prototype.shuffle=function shuffle(newIndices){var this$1=this;if(!isArray(this.baseModel.value))return;var base=this.baseModel.getKeypath(this.ractive);var max=this.baseModel.value.length;var suffix=this.keys.length>1?'.'+this.keys.slice(1).join('.'):'';this.newKeys={};for(var i=0;i<newIndices.length;i++){if(newIndices[i]===-1||newIndices[i]===i)continue;this$1.newKeys[(""+base+"."+i+""+suffix)]=true;}
for(var i$1=newIndices.touchedFrom;i$1<max;i$1++){this$1.newKeys[(""+base+"."+i$1+""+suffix)]=true;}};PatternObserver.prototype.handleChange=function handleChange(){var this$1=this;if(!this.dirty){this.newValues={};if(!this.changed.length){this.baseModel.findMatches(this.keys).forEach(function(model){var keypath=model.getKeypath(this$1.ractive);this$1.newValues[keypath]=model.get();});this.partial=false;}else{var ok=this.baseModel.isRoot?this.changed:this.changed.map(function(key){return this$1.baseModel.getKeypath(this$1.ractive)+'.'+escapeKey(key);});this.baseModel.findMatches(this.keys).forEach(function(model){var keypath=model.getKeypath(this$1.ractive);if(ok.filter(function(k){return keypath.indexOf(k)===0&&(keypath.length===k.length||keypath[k.length]==='.');}).length){this$1.newValues[keypath]=model.get();}});this.partial=true;}
runloop.addObserver(this,this.defer);this.dirty=true;this.changed.length=0;if(this.once)this.cancel();}};function observeList(keypath,callback,options){if(typeof keypath!=='string'){throw new Error('ractive.observeList() must be passed a string as its first argument');}
var model=this.viewmodel.joinAll(splitKeypathI(keypath));var observer=new ListObserver(this,model,callback,options||{});this._observers.push(observer);return{cancel:function(){observer.cancel();}};}
function negativeOne(){return-1;}
var ListObserver=function ListObserver(context,model,callback,options){this.context=context;this.model=model;this.keypath=model.getKeypath();this.callback=callback;this.pending=null;model.register(this);if(options.init!==false){this.sliced=[];this.shuffle([]);this.handleChange();}else{this.sliced=this.slice();}};ListObserver.prototype.handleChange=function handleChange(){if(this.pending){this.callback(this.pending);this.pending=null;}
else{this.shuffle(this.sliced.map(negativeOne));this.handleChange();}};ListObserver.prototype.shuffle=function shuffle(newIndices){var this$1=this;var newValue=this.slice();var inserted=[];var deleted=[];var start;var hadIndex={};newIndices.forEach(function(newIndex,oldIndex){hadIndex[newIndex]=true;if(newIndex!==oldIndex&&start===undefined){start=oldIndex;}
if(newIndex===-1){deleted.push(this$1.sliced[oldIndex]);}});if(start===undefined)start=newIndices.length;var len=newValue.length;for(var i=0;i<len;i+=1){if(!hadIndex[i])inserted.push(newValue[i]);}
this.pending={inserted:inserted,deleted:deleted,start:start};this.sliced=newValue;};ListObserver.prototype.slice=function slice(){var value=this.model.get();return isArray(value)?value.slice():[];};var onceOptions={init:false,once:true};function observeOnce(keypath,callback,options){if(isObject(keypath)||typeof keypath==='function'){options=extendObj(callback||{},onceOptions);return this.observe(keypath,options);}
options=extendObj(options||{},onceOptions);return this.observe(keypath,callback,options);}
function trim(str){return str.trim();};function notEmptyString(str){return str!=='';};function Ractive$off(eventName,callback){var this$1=this;if(!eventName){for(eventName in this._subs){delete this._subs[eventName];}}
else{var eventNames=eventName.split(' ').map(trim).filter(notEmptyString);eventNames.forEach(function(eventName){var subscribers=this$1._subs[eventName];if(subscribers){if(callback){var index=subscribers.indexOf(callback);if(index!==-1){subscribers.splice(index,1);}}
else{this$1._subs[eventName]=[];}}});}
return this;}
function Ractive$on(eventName,callback){var this$1=this;if(typeof eventName==='object'){var listeners=[];var n;for(n in eventName){if(eventName.hasOwnProperty(n)){listeners.push(this.on(n,eventName[n]));}}
return{cancel:function(){var listener;while(listener=listeners.pop())listener.cancel();}};}
var eventNames=eventName.split(' ').map(trim).filter(notEmptyString);eventNames.forEach(function(eventName){(this$1._subs[eventName]||(this$1._subs[eventName]=[])).push(callback);});return{cancel:function(){return this$1.off(eventName,callback);}};}
function Ractive$once(eventName,handler){var listener=this.on(eventName,function(){handler.apply(this,arguments);listener.cancel();});return listener;}
function getNewIndices(length,methodName,args){var spliceArguments,newIndices=[],removeStart,removeEnd,balance,i;spliceArguments=getSpliceEquivalent(length,methodName,args);if(!spliceArguments){return null;}
balance=(spliceArguments.length-2)-spliceArguments[1];removeStart=Math.min(length,spliceArguments[0]);removeEnd=removeStart+spliceArguments[1];for(i=0;i<removeStart;i+=1){newIndices.push(i);}
for(;i<removeEnd;i+=1){newIndices.push(-1);}
for(;i<length;i+=1){newIndices.push(i+balance);}
if(balance!==0){newIndices.touchedFrom=spliceArguments[0];}else{newIndices.touchedFrom=length;}
return newIndices;}
function getSpliceEquivalent(length,methodName,args){switch(methodName){case'splice':if(args[0]!==undefined&&args[0]<0){args[0]=length+Math.max(args[0],-length);}
while(args.length<2){args.push(length-args[0]);}
args[1]=Math.min(args[1],length-args[0]);return args;case'sort':case'reverse':return null;case'pop':if(length){return[length-1,1];}
return[0,0];case'push':return[length,0].concat(args);case'shift':return[0,length?1:0];case'unshift':return[0,0].concat(args);}}
var arrayProto=Array.prototype;function makeArrayMethod(methodName){return function(keypath){var args=[],len=arguments.length-1;while(len-->0)args[len]=arguments[len+1];var model=this.viewmodel.joinAll(splitKeypathI(keypath));var array=model.get();if(!isArray(array)){if(array===undefined){array=[];var result$1=arrayProto[methodName].apply(array,args);return this.set(keypath,array).then(function(){return result$1;});}else{throw new Error(("shuffle array method "+methodName+" called on non-array at "+(model.getKeypath())));}}
var newIndices=getNewIndices(array.length,methodName,args);var result=arrayProto[methodName].apply(array,args);var promise=runloop.start(this,true).then(function(){return result;});promise.result=result;if(newIndices){model.shuffle(newIndices);}else{model.set(result);}
runloop.end();return promise;};}
var pop=makeArrayMethod('pop');var push=makeArrayMethod('push');var PREFIX='/* Ractive.js component styles */';var styleDefinitions=[];var isDirty=false;var styleElement=null;var useCssText=null;function addCSS(styleDefinition){styleDefinitions.push(styleDefinition);isDirty=true;}
function applyCSS(){if(!doc||!isDirty)return;if(useCssText){styleElement.styleSheet.cssText=getCSS(null);}else{styleElement.innerHTML=getCSS(null);}
isDirty=false;}
function getCSS(cssIds){var filteredStyleDefinitions=cssIds?styleDefinitions.filter(function(style){return~cssIds.indexOf(style.id);}):styleDefinitions;return filteredStyleDefinitions.reduce(function(styles,style){return(""+styles+"\n\n/* {"+(style.id)+"} */\n"+(style.styles));},PREFIX);}
if(doc&&(!styleElement||!styleElement.parentNode)){styleElement=doc.createElement('style');styleElement.type='text/css';doc.getElementsByTagName('head')[0].appendChild(styleElement);useCssText=!!styleElement.styleSheet;}
var renderHook=new Hook('render');var completeHook=new Hook('complete');function render$1(ractive,target,anchor,occupants){var transitionsEnabled=ractive.transitionsEnabled;if(ractive.noIntro)ractive.transitionsEnabled=false;var promise=runloop.start(ractive,true);runloop.scheduleTask(function(){return renderHook.fire(ractive);},true);if(ractive.fragment.rendered){throw new Error('You cannot call ractive.render() on an already rendered instance! Call ractive.unrender() first');}
anchor=getElement(anchor)||ractive.anchor;ractive.el=target;ractive.anchor=anchor;if(ractive.cssId)applyCSS();if(target){(target.__ractive_instances__||(target.__ractive_instances__=[])).push(ractive);if(anchor){var docFrag=doc.createDocumentFragment();ractive.fragment.render(docFrag);target.insertBefore(docFrag,anchor);}else{ractive.fragment.render(target,occupants);}}
runloop.end();ractive.transitionsEnabled=transitionsEnabled;return promise.then(function(){return completeHook.fire(ractive);});}
function Ractive$render(target,anchor){target=getElement(target)||this.el;if(!this.append&&target){var others=target.__ractive_instances__;if(others)others.forEach(teardown);if(!this.enhance){target.innerHTML='';}}
var occupants=this.enhance?toArray(target.childNodes):null;var promise=render$1(this,target,anchor,occupants);if(occupants){while(occupants.length)target.removeChild(occupants.pop());}
return promise;}
var adaptConfigurator={extend:function(Parent,proto,options){proto.adapt=combine(proto.adapt,ensureArray(options.adapt));},init:function(){}};function combine(a,b){var c=a.slice();var i=b.length;while(i--){if(!~c.indexOf(b[i])){c.push(b[i]);}}
return c;}
var selectorsPattern=/(?:^|\})?\s*([^\{\}]+)\s*\{/g;var commentsPattern=/\/\*.*?\*\//g;var selectorUnitPattern=/((?:(?:\[[^\]+]\])|(?:[^\s\+\>~:]))+)((?:::?[^\s\+\>\~\(:]+(?:\([^\)]+\))?)*\s*[\s\+\>\~]?)\s*/g;var excludePattern=/^(?:@|\d+%)/;var dataRvcGuidPattern=/\[data-ractive-css~="\{[a-z0-9-]+\}"]/g;function trim$1(str){return str.trim();}
function extractString(unit){return unit.str;}
function transformSelector(selector,parent){var selectorUnits=[];var match;while(match=selectorUnitPattern.exec(selector)){selectorUnits.push({str:match[0],base:match[1],modifiers:match[2]});}
var base=selectorUnits.map(extractString);var transformed=[];var i=selectorUnits.length;while(i--){var appended=base.slice();var unit=selectorUnits[i];appended[i]=unit.base+parent+unit.modifiers||'';var prepended=base.slice();prepended[i]=parent+' '+prepended[i];transformed.push(appended.join(' '),prepended.join(' '));}
return transformed.join(', ');}
function transformCss(css,id){var dataAttr="[data-ractive-css~=\"{"+id+"}\"]";var transformed;if(dataRvcGuidPattern.test(css)){transformed=css.replace(dataRvcGuidPattern,dataAttr);}else{transformed=css.replace(commentsPattern,'').replace(selectorsPattern,function(match,$1){if(excludePattern.test($1))return match;var selectors=$1.split(',').map(trim$1);var transformed=selectors.map(function(selector){return transformSelector(selector,dataAttr);}).join(', ')+' ';return match.replace($1,transformed);});}
return transformed;}
function s4(){return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);}
function uuid(){return s4()+s4()+'-'+s4()+'-'+s4()+'-'+s4()+'-'+s4()+s4()+s4();}
var cssConfigurator={name:'css',extend:function(Parent,proto,options){if(!options.css)return;var id=uuid();var styles=options.noCssTransform?options.css:transformCss(options.css,id);proto.cssId=id;addCSS({id:id,styles:styles});},init:function(Parent,target,options){if(!options.css)return;warnIfDebug(("\nThe css option is currently not supported on a per-instance basis and will be discarded. Instead, we recommend instantiating from a component definition with a css option.\n\nconst Component = Ractive.extend({\n\t...\n\tcss: '/* your css */',\n\t...\n});\n\nconst componentInstance = new Component({ ... })\n\t\t"));}};function bind$1(fn,context){if(!/this/.test(fn.toString()))return fn;var bound=fn.bind(context);for(var prop in fn)bound[prop]=fn[prop];return bound;}
function validate(data){if(data&&data.constructor!==Object){if(typeof data==='function'){}else if(typeof data!=='object'){fatal(("data option must be an object or a function, `"+data+"` is not valid"));}else{warnIfDebug('If supplied, options.data should be a plain JavaScript object - using a non-POJO as the root object may work, but is discouraged');}}}
var dataConfigurator={name:'data',extend:function(Parent,proto,options){var key;var value;if(options.data&&isObject(options.data)){for(key in options.data){value=options.data[key];if(value&&typeof value==='object'){if(isObject(value)||isArray(value)){warnIfDebug(("Passing a `data` option with object and array properties to Ractive.extend() is discouraged, as mutating them is likely to cause bugs. Consider using a data function instead:\n\n  // this...\n  data: function () {\n    return {\n      myObject: {}\n    };\n  })\n\n  // instead of this:\n  data: {\n    myObject: {}\n  }"));}}}}
proto.data=combine$1(proto.data,options.data);},init:function(Parent,ractive,options){var result=combine$1(Parent.prototype.data,options.data);if(typeof result==='function')result=result.call(ractive);if(result&&result.constructor===Object){for(var prop in result){if(typeof result[prop]==='function')result[prop]=bind$1(result[prop],ractive);}}
return result||{};},reset:function(ractive){var result=this.init(ractive.constructor,ractive,ractive.viewmodel);ractive.viewmodel.root.set(result);return true;}};function combine$1(parentValue,childValue){validate(childValue);var parentIsFn=typeof parentValue==='function';var childIsFn=typeof childValue==='function';if(!childValue&&!parentIsFn){childValue={};}
if(!parentIsFn&&!childIsFn){return fromProperties(childValue,parentValue);}
return function(){var child=childIsFn?callDataFunction(childValue,this):childValue;var parent=parentIsFn?callDataFunction(parentValue,this):parentValue;return fromProperties(child,parent);};}
function callDataFunction(fn,context){var data=fn.call(context);if(!data)return;if(typeof data!=='object'){fatal('Data function must return an object');}
if(data.constructor!==Object){warnOnceIfDebug('Data function returned something other than a plain JavaScript object. This might work, but is strongly discouraged');}
return data;}
function fromProperties(primary,secondary){if(primary&&secondary){for(var key in secondary){if(!(key in primary)){primary[key]=secondary[key];}}
return primary;}
return primary||secondary;}
var TEMPLATE_VERSION=3;var pattern=/\$\{([^\}]+)\}/g;function fromExpression(body,length){if(length===void 0)length=0;var args=new Array(length);while(length--){args[length]="_"+length;}
return new Function([],("return function ("+(args.join(','))+"){return("+body+");};"))();}
function fromComputationString(str,bindTo){var hasThis;var functionBody='return ('+str.replace(pattern,function(match,keypath){hasThis=true;return("__ractive.get(\""+keypath+"\")");})+');';if(hasThis)functionBody="var __ractive = this; "+functionBody;var fn=new Function(functionBody);return hasThis?fn.bind(bindTo):fn;}
var functions=create(null);function getFunction(str,i){if(functions[str])return functions[str];return functions[str]=createFunction(str,i);}
function addFunctions(template){if(!template)return;var exp=template.e;if(!exp)return;Object.keys(exp).forEach(function(str){if(functions[str])return;functions[str]=exp[str];});}
var Parser;var ParseError;var leadingWhitespace=/^\s+/;ParseError=function(message){this.name='ParseError';this.message=message;try{throw new Error(message);}catch(e){this.stack=e.stack;}};ParseError.prototype=Error.prototype;Parser=function(str,options){var this$1=this;var items,item,lineStart=0;this.str=str;this.options=options||{};this.pos=0;this.lines=this.str.split('\n');this.lineEnds=this.lines.map(function(line){var lineEnd=lineStart+line.length+1;lineStart=lineEnd;return lineEnd;},0);if(this.init)this.init(str,options);items=[];while((this$1.pos<this$1.str.length)&&(item=this$1.read())){items.push(item);}
this.leftover=this.remaining();this.result=this.postProcess?this.postProcess(items,options):items;};Parser.prototype={read:function(converters){var this$1=this;var pos,i,len,item;if(!converters)converters=this.converters;pos=this.pos;len=converters.length;for(i=0;i<len;i+=1){this$1.pos=pos;if(item=converters[i](this$1)){return item;}}
return null;},getLinePos:function(char){var this$1=this;var lineNum=0,lineStart=0,columnNum;while(char>=this$1.lineEnds[lineNum]){lineStart=this$1.lineEnds[lineNum];lineNum+=1;}
columnNum=char-lineStart;return[lineNum+1,columnNum+1,char];},error:function(message){var pos=this.getLinePos(this.pos);var lineNum=pos[0];var columnNum=pos[1];var line=this.lines[pos[0]-1];var numTabs=0;var annotation=line.replace(/\t/g,function(match,char){if(char<pos[1]){numTabs+=1;}
return'  ';})+'\n'+new Array(pos[1]+numTabs).join(' ')+'^----';var error=new ParseError((""+message+" at line "+lineNum+" character "+columnNum+":\n"+annotation));error.line=pos[0];error.character=pos[1];error.shortMessage=message;throw error;},matchString:function(string){if(this.str.substr(this.pos,string.length)===string){this.pos+=string.length;return string;}},matchPattern:function(pattern){var match;if(match=pattern.exec(this.remaining())){this.pos+=match[0].length;return match[1]||match[0];}},allowWhitespace:function(){this.matchPattern(leadingWhitespace);},remaining:function(){return this.str.substring(this.pos);},nextChar:function(){return this.str.charAt(this.pos);}};Parser.extend=function(proto){var Parent=this,Child,key;Child=function(str,options){Parser.call(this,str,options);};Child.prototype=create(Parent.prototype);for(key in proto){if(hasOwn.call(proto,key)){Child.prototype[key]=proto[key];}}
Child.extend=Parser.extend;return Child;};var Parser$1=Parser;var TEXT=1;var INTERPOLATOR=2;var TRIPLE=3;var SECTION=4;var INVERTED=5;var CLOSING=6;var ELEMENT=7;var PARTIAL=8;var COMMENT=9;var DELIMCHANGE=10;var CLOSING_TAG=14;var COMPONENT=15;var YIELDER=16;var INLINE_PARTIAL=17;var DOCTYPE=18;var ALIAS=19;var NUMBER_LITERAL=20;var STRING_LITERAL=21;var ARRAY_LITERAL=22;var OBJECT_LITERAL=23;var BOOLEAN_LITERAL=24;var REGEXP_LITERAL=25;var GLOBAL=26;var KEY_VALUE_PAIR=27;var REFERENCE=30;var REFINEMENT=31;var MEMBER=32;var PREFIX_OPERATOR=33;var BRACKETED=34;var CONDITIONAL=35;var INFIX_OPERATOR=36;var INVOCATION=40;var SECTION_IF=50;var SECTION_UNLESS=51;var SECTION_EACH=52;var SECTION_WITH=53;var SECTION_IF_WITH=54;var ELSE=60;var ELSEIF=61;var delimiterChangePattern=/^[^\s=]+/;var whitespacePattern=/^\s+/;function readDelimiterChange(parser){var start,opening,closing;if(!parser.matchString('=')){return null;}
start=parser.pos;parser.allowWhitespace();opening=parser.matchPattern(delimiterChangePattern);if(!opening){parser.pos=start;return null;}
if(!parser.matchPattern(whitespacePattern)){return null;}
closing=parser.matchPattern(delimiterChangePattern);if(!closing){parser.pos=start;return null;}
parser.allowWhitespace();if(!parser.matchString('=')){parser.pos=start;return null;}
return[opening,closing];}
var regexpPattern=/^(\/(?:[^\n\r\u2028\u2029/\\[]|\\.|\[(?:[^\n\r\u2028\u2029\]\\]|\\.)*])+\/(?:([gimuy])(?![a-z]*\2))*(?![a-zA-Z_$0-9]))/;function readNumberLiteral(parser){var result;if(result=parser.matchPattern(regexpPattern)){return{t:REGEXP_LITERAL,v:result};}
return null;}
var delimiterChangeToken={t:DELIMCHANGE,exclude:true};function readMustache(parser){var mustache,i;if(parser.interpolate[parser.inside]===false){return null;}
for(i=0;i<parser.tags.length;i+=1){if(mustache=readMustacheOfType(parser,parser.tags[i])){return mustache;}}}
function readMustacheOfType(parser,tag){var start,mustache,reader,i;start=parser.pos;if(parser.matchString('\\'+tag.open)){if(start===0||parser.str[start-1]!=='\\'){return tag.open;}}else if(!parser.matchString(tag.open)){return null;}
if(mustache=readDelimiterChange(parser)){if(!parser.matchString(tag.close)){return null;}
tag.open=mustache[0];tag.close=mustache[1];parser.sortMustacheTags();return delimiterChangeToken;}
parser.allowWhitespace();if(parser.matchString('/')){parser.pos-=1;var rewind=parser.pos;if(!readNumberLiteral(parser)){parser.pos=rewind-(tag.close.length);parser.error('Attempted to close a section that wasn\'t open');}else{parser.pos=rewind;}}
for(i=0;i<tag.readers.length;i+=1){reader=tag.readers[i];if(mustache=reader(parser,tag)){if(tag.isStatic){mustache.s=true;}
if(parser.includeLinePositions){mustache.p=parser.getLinePos(start);}
return mustache;}}
parser.pos=start;return null;}
var expectedExpression='Expected a JavaScript expression';var expectedParen='Expected closing paren';var numberPattern=/^(?:[+-]?)0*(?:(?:(?:[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;function readNumberLiteral$1(parser){var result;if(result=parser.matchPattern(numberPattern)){return{t:NUMBER_LITERAL,v:result};}
return null;}
function readBooleanLiteral(parser){var remaining=parser.remaining();if(remaining.substr(0,4)==='true'){parser.pos+=4;return{t:BOOLEAN_LITERAL,v:'true'};}
if(remaining.substr(0,5)==='false'){parser.pos+=5;return{t:BOOLEAN_LITERAL,v:'false'};}
return null;}
var stringMiddlePattern;var escapeSequencePattern;var lineContinuationPattern;stringMiddlePattern=/^(?=.)[^"'\\]+?(?:(?!.)|(?=["'\\]))/;escapeSequencePattern=/^\\(?:['"\\bfnrt]|0(?![0-9])|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|(?=.)[^ux0-9])/;lineContinuationPattern=/^\\(?:\r\n|[\u000A\u000D\u2028\u2029])/;function makeQuotedStringMatcher(okQuote){return function(parser){var literal='"';var done=false;var next;while(!done){next=(parser.matchPattern(stringMiddlePattern)||parser.matchPattern(escapeSequencePattern)||parser.matchString(okQuote));if(next){if(next===("\"")){literal+="\\\"";}else if(next===("\\'")){literal+="'";}else{literal+=next;}}else{next=parser.matchPattern(lineContinuationPattern);if(next){literal+='\\u'+('000'+next.charCodeAt(1).toString(16)).slice(-4);}else{done=true;}}}
literal+='"';return JSON.parse(literal);};}
var getSingleQuotedString=makeQuotedStringMatcher(("\""));var getDoubleQuotedString=makeQuotedStringMatcher(("'"));function readStringLiteral(parser){var start,string;start=parser.pos;if(parser.matchString('"')){string=getDoubleQuotedString(parser);if(!parser.matchString('"')){parser.pos=start;return null;}
return{t:STRING_LITERAL,v:string};}
if(parser.matchString(("'"))){string=getSingleQuotedString(parser);if(!parser.matchString(("'"))){parser.pos=start;return null;}
return{t:STRING_LITERAL,v:string};}
return null;}
var namePattern=/^[a-zA-Z_$][a-zA-Z_$0-9]*/;var identifier=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function readKey(parser){var token;if(token=readStringLiteral(parser)){return identifier.test(token.v)?token.v:'"'+token.v.replace(/"/g,'\\"')+'"';}
if(token=readNumberLiteral$1(parser)){return token.v;}
if(token=parser.matchPattern(namePattern)){return token;}
return null;}
function readKeyValuePair(parser){var start,key,value;start=parser.pos;parser.allowWhitespace();var refKey=parser.nextChar()!=='\''&&parser.nextChar()!=='"';key=readKey(parser);if(key===null){parser.pos=start;return null;}
parser.allowWhitespace();if(refKey&&(parser.nextChar()===','||parser.nextChar()==='}')){if(!namePattern.test(key)){parser.error(("Expected a valid reference, but found '"+key+"' instead."));}
return{t:KEY_VALUE_PAIR,k:key,v:{t:REFERENCE,n:key}};}
if(!parser.matchString(':')){parser.pos=start;return null;}
parser.allowWhitespace();value=readExpression(parser);if(value===null){parser.pos=start;return null;}
return{t:KEY_VALUE_PAIR,k:key,v:value};}
function readKeyValuePairs(parser){var start,pairs,pair,keyValuePairs;start=parser.pos;pair=readKeyValuePair(parser);if(pair===null){return null;}
pairs=[pair];if(parser.matchString(',')){keyValuePairs=readKeyValuePairs(parser);if(!keyValuePairs){parser.pos=start;return null;}
return pairs.concat(keyValuePairs);}
return pairs;}
function readObjectLiteral(parser){var start,keyValuePairs;start=parser.pos;parser.allowWhitespace();if(!parser.matchString('{')){parser.pos=start;return null;}
keyValuePairs=readKeyValuePairs(parser);parser.allowWhitespace();if(!parser.matchString('}')){parser.pos=start;return null;}
return{t:OBJECT_LITERAL,m:keyValuePairs};}
function readExpressionList(parser){parser.allowWhitespace();var expr=readExpression(parser);if(expr===null)return null;var expressions=[expr];parser.allowWhitespace();if(parser.matchString(',')){var next=readExpressionList(parser);if(next===null)parser.error(expectedExpression);expressions.push.apply(expressions,next);}
return expressions;}
function readArrayLiteral(parser){var start,expressionList;start=parser.pos;parser.allowWhitespace();if(!parser.matchString('[')){parser.pos=start;return null;}
expressionList=readExpressionList(parser);if(!parser.matchString(']')){parser.pos=start;return null;}
return{t:ARRAY_LITERAL,m:expressionList};}
function readLiteral(parser){return readNumberLiteral$1(parser)||readBooleanLiteral(parser)||readStringLiteral(parser)||readObjectLiteral(parser)||readArrayLiteral(parser)||readNumberLiteral(parser);}
var prefixPattern=/^(?:~\/|(?:\.\.\/)+|\.\/(?:\.\.\/)*|\.)/;var globals;var keywords;globals=/^(?:Array|console|Date|RegExp|decodeURIComponent|decodeURI|encodeURIComponent|encodeURI|isFinite|isNaN|parseFloat|parseInt|JSON|Math|NaN|undefined|null|Object|Number|String|Boolean)\b/;keywords=/^(?:break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|var|void|while|with)$/;var legalReference=/^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:\.(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/;var relaxedName=/^[a-zA-Z_$][-\/a-zA-Z_$0-9]*/;function readReference(parser){var startPos,prefix,name,global,reference,fullLength,lastDotIndex;startPos=parser.pos;name=parser.matchPattern(/^@(?:keypath|rootpath|index|key|ractive|global)/);if(!name){prefix=parser.matchPattern(prefixPattern)||'';name=(!prefix&&parser.relaxedNames&&parser.matchPattern(relaxedName))||parser.matchPattern(legalReference);if(!name&&prefix==='.'){prefix='';name='.';}}
if(!name){return null;}
if(!prefix&&!parser.relaxedNames&&keywords.test(name)){parser.pos=startPos;return null;}
if(!prefix&&globals.test(name)){global=globals.exec(name)[0];parser.pos=startPos+global.length;return{t:GLOBAL,v:global};}
fullLength=(prefix||'').length+name.length;reference=(prefix||'')+normalise(name);if(parser.matchString('(')){lastDotIndex=reference.lastIndexOf('.');if(lastDotIndex!==-1&&name[name.length-1]!==']'){var refLength=reference.length;reference=reference.substr(0,lastDotIndex);parser.pos=startPos+(fullLength-(refLength-lastDotIndex));}else{parser.pos-=1;}}
return{t:REFERENCE,n:reference.replace(/^this\./,'./').replace(/^this$/,'.')};}
function readBracketedExpression(parser){if(!parser.matchString('('))return null;parser.allowWhitespace();var expr=readExpression(parser);if(!expr)parser.error(expectedExpression);parser.allowWhitespace();if(!parser.matchString(')'))parser.error(expectedParen);return{t:BRACKETED,x:expr};}
function readPrimary(parser){return readLiteral(parser)||readReference(parser)||readBracketedExpression(parser);}
function readRefinement(parser){if(!parser.strictRefinement){parser.allowWhitespace();}
if(parser.matchString('.')){parser.allowWhitespace();var name=parser.matchPattern(namePattern);if(name){return{t:REFINEMENT,n:name};}
parser.error('Expected a property name');}
if(parser.matchString('[')){parser.allowWhitespace();var expr=readExpression(parser);if(!expr)parser.error(expectedExpression);parser.allowWhitespace();if(!parser.matchString(']'))parser.error(("Expected ']'"));return{t:REFINEMENT,x:expr};}
return null;}
function readMemberOrInvocation(parser){var expression=readPrimary(parser);if(!expression)return null;while(expression){var refinement=readRefinement(parser);if(refinement){expression={t:MEMBER,x:expression,r:refinement};}
else if(parser.matchString('(')){parser.allowWhitespace();var expressionList=readExpressionList(parser);parser.allowWhitespace();if(!parser.matchString(')')){parser.error(expectedParen);}
expression={t:INVOCATION,x:expression};if(expressionList)expression.o=expressionList;}
else{break;}}
return expression;}
var readTypeOf;var makePrefixSequenceMatcher;makePrefixSequenceMatcher=function(symbol,fallthrough){return function(parser){var expression;if(expression=fallthrough(parser)){return expression;}
if(!parser.matchString(symbol)){return null;}
parser.allowWhitespace();expression=readExpression(parser);if(!expression){parser.error(expectedExpression);}
return{s:symbol,o:expression,t:PREFIX_OPERATOR};};};(function(){var i,len,matcher,prefixOperators,fallthrough;prefixOperators='! ~ + - typeof'.split(' ');fallthrough=readMemberOrInvocation;for(i=0,len=prefixOperators.length;i<len;i+=1){matcher=makePrefixSequenceMatcher(prefixOperators[i],fallthrough);fallthrough=matcher;}
readTypeOf=fallthrough;}());var readTypeof=readTypeOf;var readLogicalOr;var makeInfixSequenceMatcher;makeInfixSequenceMatcher=function(symbol,fallthrough){return function(parser){var start,left,right;left=fallthrough(parser);if(!left){return null;}
while(true){start=parser.pos;parser.allowWhitespace();if(!parser.matchString(symbol)){parser.pos=start;return left;}
if(symbol==='in'&&/[a-zA-Z_$0-9]/.test(parser.remaining().charAt(0))){parser.pos=start;return left;}
parser.allowWhitespace();right=fallthrough(parser);if(!right){parser.pos=start;return left;}
left={t:INFIX_OPERATOR,s:symbol,o:[left,right]};}};};(function(){var i,len,matcher,infixOperators,fallthrough;infixOperators='* / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | && ||'.split(' ');fallthrough=readTypeof;for(i=0,len=infixOperators.length;i<len;i+=1){matcher=makeInfixSequenceMatcher(infixOperators[i],fallthrough);fallthrough=matcher;}
readLogicalOr=fallthrough;}());var readLogicalOr$1=readLogicalOr;function getConditional(parser){var start,expression,ifTrue,ifFalse;expression=readLogicalOr$1(parser);if(!expression){return null;}
start=parser.pos;parser.allowWhitespace();if(!parser.matchString('?')){parser.pos=start;return expression;}
parser.allowWhitespace();ifTrue=readExpression(parser);if(!ifTrue){parser.error(expectedExpression);}
parser.allowWhitespace();if(!parser.matchString(':')){parser.error('Expected ":"');}
parser.allowWhitespace();ifFalse=readExpression(parser);if(!ifFalse){parser.error(expectedExpression);}
return{t:CONDITIONAL,o:[expression,ifTrue,ifFalse]};}
function readExpression(parser){return getConditional(parser);}
function flattenExpression(expression){var refs;extractRefs(expression,refs=[]);return{r:refs,s:stringify(expression)};function stringify(node){switch(node.t){case BOOLEAN_LITERAL:case GLOBAL:case NUMBER_LITERAL:case REGEXP_LITERAL:return node.v;case STRING_LITERAL:return JSON.stringify(String(node.v));case ARRAY_LITERAL:return'['+(node.m?node.m.map(stringify).join(','):'')+']';case OBJECT_LITERAL:return'{'+(node.m?node.m.map(stringify).join(','):'')+'}';case KEY_VALUE_PAIR:return node.k+':'+stringify(node.v);case PREFIX_OPERATOR:return(node.s==='typeof'?'typeof ':node.s)+stringify(node.o);case INFIX_OPERATOR:return stringify(node.o[0])+(node.s.substr(0,2)==='in'?' '+node.s+' ':node.s)+stringify(node.o[1]);case INVOCATION:return stringify(node.x)+'('+(node.o?node.o.map(stringify).join(','):'')+')';case BRACKETED:return'('+stringify(node.x)+')';case MEMBER:return stringify(node.x)+stringify(node.r);case REFINEMENT:return(node.n?'.'+node.n:'['+stringify(node.x)+']');case CONDITIONAL:return stringify(node.o[0])+'?'+stringify(node.o[1])+':'+stringify(node.o[2]);case REFERENCE:return'_'+refs.indexOf(node.n);default:throw new Error('Expected legal JavaScript');}}}
function extractRefs(node,refs){var i,list;if(node.t===REFERENCE){if(refs.indexOf(node.n)===-1){refs.unshift(node.n);}}
list=node.o||node.m;if(list){if(isObject(list)){extractRefs(list,refs);}else{i=list.length;while(i--){extractRefs(list[i],refs);}}}
if(node.x){extractRefs(node.x,refs);}
if(node.r){extractRefs(node.r,refs);}
if(node.v){extractRefs(node.v,refs);}}
function refineExpression(expression,mustache){var referenceExpression;if(expression){while(expression.t===BRACKETED&&expression.x){expression=expression.x;}
if(expression.t===REFERENCE){mustache.r=expression.n;}else{if(referenceExpression=getReferenceExpression(expression)){mustache.rx=referenceExpression;}else{mustache.x=flattenExpression(expression);}}
return mustache;}}
function getReferenceExpression(expression){var members=[],refinement;while(expression.t===MEMBER&&expression.r.t===REFINEMENT){refinement=expression.r;if(refinement.x){if(refinement.x.t===REFERENCE){members.unshift(refinement.x);}else{members.unshift(flattenExpression(refinement.x));}}else{members.unshift(refinement.n);}
expression=expression.x;}
if(expression.t!==REFERENCE){return null;}
return{r:expression.n,m:members};}
function readTriple(parser,tag){var expression=readExpression(parser),triple;if(!expression){return null;}
if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
triple={t:TRIPLE};refineExpression(expression,triple);return triple;}
function readUnescaped(parser,tag){var expression,triple;if(!parser.matchString('&')){return null;}
parser.allowWhitespace();expression=readExpression(parser);if(!expression){return null;}
if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
triple={t:TRIPLE};refineExpression(expression,triple);return triple;}
var legalAlias=/^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/;var asRE=/^as/i;function readAliases(parser){var aliases=[],alias,start=parser.pos;parser.allowWhitespace();alias=readAlias(parser);if(alias){alias.x=refineExpression(alias.x,{});aliases.push(alias);parser.allowWhitespace();while(parser.matchString(',')){alias=readAlias(parser);if(!alias){parser.error('Expected another alias.');}
alias.x=refineExpression(alias.x,{});aliases.push(alias);parser.allowWhitespace();}
return aliases;}
parser.pos=start;return null;}
function readAlias(parser){var expr,alias,start=parser.pos;parser.allowWhitespace();expr=readExpression(parser,[]);if(!expr){parser.pos=start;return null;}
parser.allowWhitespace();if(!parser.matchPattern(asRE)){parser.pos=start;return null;}
parser.allowWhitespace();alias=parser.matchPattern(legalAlias);if(!alias){parser.error('Expected a legal alias name.');}
return{n:alias,x:expr};}
function readPartial(parser,tag){if(!parser.matchString('>'))return null;parser.allowWhitespace();parser.relaxedNames=parser.strictRefinement=true;var expression=readExpression(parser);parser.relaxedNames=parser.strictRefinement=false;if(!expression)return null;var partial={t:PARTIAL};refineExpression(expression,partial);parser.allowWhitespace();var aliases=readAliases(parser);if(aliases){partial={t:ALIAS,z:aliases,f:[partial]};}
else{var context=readExpression(parser);if(context){partial={t:SECTION,n:SECTION_WITH,f:[partial]};refineExpression(context,partial);}}
parser.allowWhitespace();if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
return partial;}
function readComment(parser,tag){var index;if(!parser.matchString('!')){return null;}
index=parser.remaining().indexOf(tag.close);if(index!==-1){parser.pos+=index+tag.close.length;return{t:COMMENT};}}
function readExpressionOrReference(parser,expectedFollowers){var start,expression,i;start=parser.pos;expression=readExpression(parser);if(!expression){var ref=parser.matchPattern(/^(\w+)/);if(ref){return{t:REFERENCE,n:ref};}
return null;}
for(i=0;i<expectedFollowers.length;i+=1){if(parser.remaining().substr(0,expectedFollowers[i].length)===expectedFollowers[i]){return expression;}}
parser.pos=start;return readReference(parser);}
function readInterpolator(parser,tag){var start,expression,interpolator,err;start=parser.pos;try{expression=readExpressionOrReference(parser,[tag.close]);}catch(e){err=e;}
if(!expression){if(parser.str.charAt(start)==='!'){parser.pos=start;return null;}
if(err){throw err;}}
if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"' after reference"));if(!expression){if(parser.nextChar()==='!'){return null;}
parser.error(("Expected expression or legal reference"));}}
interpolator={t:INTERPOLATOR};refineExpression(expression,interpolator);return interpolator;}
var yieldPattern=/^yield\s*/;function readYielder(parser,tag){if(!parser.matchPattern(yieldPattern))return null;var name=parser.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-]*/);parser.allowWhitespace();if(!parser.matchString(tag.close)){parser.error(("expected legal partial name"));}
var yielder={t:YIELDER};if(name)yielder.n=name;return yielder;}
function readClosing(parser,tag){var start,remaining,index,closing;start=parser.pos;if(!parser.matchString(tag.open)){return null;}
parser.allowWhitespace();if(!parser.matchString('/')){parser.pos=start;return null;}
parser.allowWhitespace();remaining=parser.remaining();index=remaining.indexOf(tag.close);if(index!==-1){closing={t:CLOSING,r:remaining.substr(0,index).split(' ')[0]};parser.pos+=index;if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
return closing;}
parser.pos=start;return null;}
var elsePattern=/^\s*else\s*/;function readElse(parser,tag){var start=parser.pos;if(!parser.matchString(tag.open)){return null;}
if(!parser.matchPattern(elsePattern)){parser.pos=start;return null;}
if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
return{t:ELSE};}
var elsePattern$1=/^\s*elseif\s+/;function readElseIf(parser,tag){var start=parser.pos;if(!parser.matchString(tag.open)){return null;}
if(!parser.matchPattern(elsePattern$1)){parser.pos=start;return null;}
var expression=readExpression(parser);if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
return{t:ELSEIF,x:expression};}
var handlebarsBlockCodes={'each':SECTION_EACH,'if':SECTION_IF,'with':SECTION_IF_WITH,'unless':SECTION_UNLESS};var indexRefPattern=/^\s*:\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/;var keyIndexRefPattern=/^\s*,\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/;var handlebarsBlockPattern=new RegExp('^('+Object.keys(handlebarsBlockCodes).join('|')+')\\b');function readSection(parser,tag){var start,expression,section,child,children,hasElse,block,unlessBlock,conditions,closed,i,expectedClose,aliasOnly=false;start=parser.pos;if(parser.matchString('^')){section={t:SECTION,f:[],n:SECTION_UNLESS};}else if(parser.matchString('#')){section={t:SECTION,f:[]};if(parser.matchString('partial')){parser.pos=start-parser.standardDelimiters[0].length;parser.error('Partial definitions can only be at the top level of the template, or immediately inside components');}
if(block=parser.matchPattern(handlebarsBlockPattern)){expectedClose=block;section.n=handlebarsBlockCodes[block];}}else{return null;}
parser.allowWhitespace();if(block==='with'){var aliases=readAliases(parser);if(aliases){aliasOnly=true;section.z=aliases;section.t=ALIAS;}}else if(block==='each'){var alias=readAlias(parser);if(alias){section.z=[{n:alias.n,x:{r:'.'}}];expression=alias.x;}}
if(!aliasOnly){if(!expression)expression=readExpression(parser);if(!expression){parser.error('Expected expression');}
if(i=parser.matchPattern(indexRefPattern)){var extra;if(extra=parser.matchPattern(keyIndexRefPattern)){section.i=i+','+extra;}else{section.i=i;}}}
parser.allowWhitespace();if(!parser.matchString(tag.close)){parser.error(("Expected closing delimiter '"+(tag.close)+"'"));}
parser.sectionDepth+=1;children=section.f;conditions=[];do{if(child=readClosing(parser,tag)){if(expectedClose&&child.r!==expectedClose){parser.error(("Expected "+(tag.open)+"/"+expectedClose+""+(tag.close)));}
parser.sectionDepth-=1;closed=true;}
else if(!aliasOnly&&(child=readElseIf(parser,tag))){if(section.n===SECTION_UNLESS){parser.error('{{else}} not allowed in {{#unless}}');}
if(hasElse){parser.error('illegal {{elseif...}} after {{else}}');}
if(!unlessBlock){unlessBlock=createUnlessBlock(expression);}
unlessBlock.f.push({t:SECTION,n:SECTION_IF,x:flattenExpression(combine$2(conditions.concat(child.x))),f:children=[]});conditions.push(invert(child.x));}
else if(!aliasOnly&&(child=readElse(parser,tag))){if(section.n===SECTION_UNLESS){parser.error('{{else}} not allowed in {{#unless}}');}
if(hasElse){parser.error('there can only be one {{else}} block, at the end of a section');}
hasElse=true;if(!unlessBlock){unlessBlock=createUnlessBlock(expression);children=unlessBlock.f;}else{unlessBlock.f.push({t:SECTION,n:SECTION_IF,x:flattenExpression(combine$2(conditions)),f:children=[]});}}
else{child=parser.read(READERS);if(!child){break;}
children.push(child);}}while(!closed);if(unlessBlock){section.l=unlessBlock;}
if(!aliasOnly){refineExpression(expression,section);}
if(!section.f.length){delete section.f;}
return section;}
function createUnlessBlock(expression){var unlessBlock={t:SECTION,n:SECTION_UNLESS,f:[]};refineExpression(expression,unlessBlock);return unlessBlock;}
function invert(expression){if(expression.t===PREFIX_OPERATOR&&expression.s==='!'){return expression.o;}
return{t:PREFIX_OPERATOR,s:'!',o:parensIfNecessary(expression)};}
function combine$2(expressions){if(expressions.length===1){return expressions[0];}
return{t:INFIX_OPERATOR,s:'&&',o:[parensIfNecessary(expressions[0]),parensIfNecessary(combine$2(expressions.slice(1)))]};}
function parensIfNecessary(expression){return{t:BRACKETED,x:expression};}
var OPEN_COMMENT='<!--';var CLOSE_COMMENT='-->';function readHtmlComment(parser){var start,content,remaining,endIndex,comment;start=parser.pos;if(!parser.matchString(OPEN_COMMENT)){return null;}
remaining=parser.remaining();endIndex=remaining.indexOf(CLOSE_COMMENT);if(endIndex===-1){parser.error('Illegal HTML - expected closing comment sequence (\'-->\')');}
content=remaining.substr(0,endIndex);parser.pos+=endIndex+3;comment={t:COMMENT,c:content};if(parser.includeLinePositions){comment.p=parser.getLinePos(start);}
return comment;}
var booleanAttributes=/^(allowFullscreen|async|autofocus|autoplay|checked|compact|controls|declare|default|defaultChecked|defaultMuted|defaultSelected|defer|disabled|enabled|formNoValidate|hidden|indeterminate|inert|isMap|itemScope|loop|multiple|muted|noHref|noResize|noShade|noValidate|noWrap|open|pauseOnExit|readOnly|required|reversed|scoped|seamless|selected|sortable|translate|trueSpeed|typeMustMatch|visible)$/i;var voidElementNames=/^(?:area|base|br|col|command|doctype|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;var htmlEntities={quot:34,amp:38,apos:39,lt:60,gt:62,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,copy:169,ordf:170,laquo:171,not:172,shy:173,reg:174,macr:175,deg:176,plusmn:177,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,sup1:185,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,Agrave:192,Aacute:193,Acirc:194,Atilde:195,Auml:196,Aring:197,AElig:198,Ccedil:199,Egrave:200,Eacute:201,Ecirc:202,Euml:203,Igrave:204,Iacute:205,Icirc:206,Iuml:207,ETH:208,Ntilde:209,Ograve:210,Oacute:211,Ocirc:212,Otilde:213,Ouml:214,times:215,Oslash:216,Ugrave:217,Uacute:218,Ucirc:219,Uuml:220,Yacute:221,THORN:222,szlig:223,agrave:224,aacute:225,acirc:226,atilde:227,auml:228,aring:229,aelig:230,ccedil:231,egrave:232,eacute:233,ecirc:234,euml:235,igrave:236,iacute:237,icirc:238,iuml:239,eth:240,ntilde:241,ograve:242,oacute:243,ocirc:244,otilde:245,ouml:246,divide:247,oslash:248,ugrave:249,uacute:250,ucirc:251,uuml:252,yacute:253,thorn:254,yuml:255,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,'int':8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830};var controlCharacters=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];var entityPattern=new RegExp('&(#?(?:x[\\w\\d]+|\\d+|'+Object.keys(htmlEntities).join('|')+'));?','g');var codePointSupport=typeof String.fromCodePoint==='function';var codeToChar=codePointSupport?String.fromCodePoint:String.fromCharCode;function decodeCharacterReferences(html){return html.replace(entityPattern,function(match,entity){var code;if(entity[0]!=='#'){code=htmlEntities[entity];}else if(entity[1]==='x'){code=parseInt(entity.substring(2),16);}else{code=parseInt(entity.substring(1),10);}
if(!code){return match;}
return codeToChar(validateCode(code));});}
var lessThan=/</g;var greaterThan=/>/g;var amp=/&/g;var invalid=65533;function escapeHtml(str){return str.replace(amp,'&amp;').replace(lessThan,'&lt;').replace(greaterThan,'&gt;');}
function validateCode(code){if(!code){return invalid;}
if(code===10){return 32;}
if(code<128){return code;}
if(code<=159){return controlCharacters[code-128];}
if(code<55296){return code;}
if(code<=57343){return invalid;}
if(code<=65535){return code;}else if(!codePointSupport){return invalid;}
if(code>=65536&&code<=131071){return code;}
if(code>=131072&&code<=196607){return code;}
return invalid;}
var leadingLinebreak=/^[ \t\f\r\n]*\r?\n/;var trailingLinebreak=/\r?\n[ \t\f\r\n]*$/;function stripStandalones(items){var i,current,backOne,backTwo,lastSectionItem;for(i=1;i<items.length;i+=1){current=items[i];backOne=items[i-1];backTwo=items[i-2];if(isString(current)&&isComment(backOne)&&isString(backTwo)){if(trailingLinebreak.test(backTwo)&&leadingLinebreak.test(current)){items[i-2]=backTwo.replace(trailingLinebreak,'\n');items[i]=current.replace(leadingLinebreak,'');}}
if(isSection(current)&&isString(backOne)){if(trailingLinebreak.test(backOne)&&isString(current.f[0])&&leadingLinebreak.test(current.f[0])){items[i-1]=backOne.replace(trailingLinebreak,'\n');current.f[0]=current.f[0].replace(leadingLinebreak,'');}}
if(isString(current)&&isSection(backOne)){lastSectionItem=lastItem(backOne.f);if(isString(lastSectionItem)&&trailingLinebreak.test(lastSectionItem)&&leadingLinebreak.test(current)){backOne.f[backOne.f.length-1]=lastSectionItem.replace(trailingLinebreak,'\n');items[i]=current.replace(leadingLinebreak,'');}}}
return items;}
function isString(item){return typeof item==='string';}
function isComment(item){return item.t===COMMENT||item.t===DELIMCHANGE;}
function isSection(item){return(item.t===SECTION||item.t===INVERTED)&&item.f;}
function trimWhitespace(items,leadingPattern,trailingPattern){var item;if(leadingPattern){item=items[0];if(typeof item==='string'){item=item.replace(leadingPattern,'');if(!item){items.shift();}else{items[0]=item;}}}
if(trailingPattern){item=lastItem(items);if(typeof item==='string'){item=item.replace(trailingPattern,'');if(!item){items.pop();}else{items[items.length-1]=item;}}}}
var contiguousWhitespace=/[ \t\f\r\n]+/g;var preserveWhitespaceElements=/^(?:pre|script|style|textarea)$/i;var leadingWhitespace$1=/^[ \t\f\r\n]+/;var trailingWhitespace=/[ \t\f\r\n]+$/;var leadingNewLine=/^(?:\r\n|\r|\n)/;var trailingNewLine=/(?:\r\n|\r|\n)$/;function cleanup(items,stripComments,preserveWhitespace,removeLeadingWhitespace,removeTrailingWhitespace){var i,item,previousItem,nextItem,preserveWhitespaceInsideFragment,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment,key;stripStandalones(items);i=items.length;while(i--){item=items[i];if(item.exclude){items.splice(i,1);}
else if(stripComments&&item.t===COMMENT){items.splice(i,1);}}
trimWhitespace(items,removeLeadingWhitespace?leadingWhitespace$1:null,removeTrailingWhitespace?trailingWhitespace:null);i=items.length;while(i--){item=items[i];if(item.f){var isPreserveWhitespaceElement=item.t===ELEMENT&&preserveWhitespaceElements.test(item.e);preserveWhitespaceInsideFragment=preserveWhitespace||isPreserveWhitespaceElement;if(!preserveWhitespace&&isPreserveWhitespaceElement){trimWhitespace(item.f,leadingNewLine,trailingNewLine);}
if(!preserveWhitespaceInsideFragment){previousItem=items[i-1];nextItem=items[i+1];if(!previousItem||(typeof previousItem==='string'&&trailingWhitespace.test(previousItem))){removeLeadingWhitespaceInsideFragment=true;}
if(!nextItem||(typeof nextItem==='string'&&leadingWhitespace$1.test(nextItem))){removeTrailingWhitespaceInsideFragment=true;}}
cleanup(item.f,stripComments,preserveWhitespaceInsideFragment,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment);}
if(item.l){cleanup(item.l.f,stripComments,preserveWhitespace,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment);items.splice(i+1,0,item.l);delete item.l;}
if(item.a){for(key in item.a){if(item.a.hasOwnProperty(key)&&typeof item.a[key]!=='string'){cleanup(item.a[key],stripComments,preserveWhitespace,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment);}}}
if(item.m){cleanup(item.m,stripComments,preserveWhitespace,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment);}
if(item.v){for(key in item.v){if(item.v.hasOwnProperty(key)){if(isArray(item.v[key].n)){cleanup(item.v[key].n,stripComments,preserveWhitespace,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment);}
if(isArray(item.v[key].d)){cleanup(item.v[key].d,stripComments,preserveWhitespace,removeLeadingWhitespaceInsideFragment,removeTrailingWhitespaceInsideFragment);}}}}}
i=items.length;while(i--){if(typeof items[i]==='string'){if(typeof items[i+1]==='string'){items[i]=items[i]+items[i+1];items.splice(i+1,1);}
if(!preserveWhitespace){items[i]=items[i].replace(contiguousWhitespace,' ');}
if(items[i]===''){items.splice(i,1);}}}}
var closingTagPattern=/^([a-zA-Z]{1,}:?[a-zA-Z0-9\-]*)\s*\>/;function readClosingTag(parser){var start,tag;start=parser.pos;if(!parser.matchString('</')){return null;}
if(tag=parser.matchPattern(closingTagPattern)){if(parser.inside&&tag!==parser.inside){parser.pos=start;return null;}
return{t:CLOSING_TAG,e:tag};}
parser.pos-=2;parser.error('Illegal closing tag');}
var pattern$1=/[-/\\^$*+?.()|[\]{}]/g;function escapeRegExp(str){return str.replace(pattern$1,'\\$&');}
var regExpCache={};function getLowestIndex(haystack,needles){return haystack.search(regExpCache[needles.join()]||(regExpCache[needles.join()]=new RegExp(needles.map(escapeRegExp).join('|'))));}
var attributeNamePattern=/^[^\s"'>\/=]+/;var unquotedAttributeValueTextPattern=/^[^\s"'=<>`]+/;function readAttribute(parser){var attr,name,value;parser.allowWhitespace();name=parser.matchPattern(attributeNamePattern);if(!name){return null;}
attr={name:name};value=readAttributeValue(parser);if(value!=null){attr.value=value;}
return attr;}
function readAttributeValue(parser){var start,valueStart,startDepth,value;start=parser.pos;if(!/[=\/>\s]/.test(parser.nextChar())){parser.error('Expected `=`, `/`, `>` or whitespace');}
parser.allowWhitespace();if(!parser.matchString('=')){parser.pos=start;return null;}
parser.allowWhitespace();valueStart=parser.pos;startDepth=parser.sectionDepth;value=readQuotedAttributeValue(parser,("'"))||readQuotedAttributeValue(parser,("\""))||readUnquotedAttributeValue(parser);if(value===null){parser.error('Expected valid attribute value');}
if(parser.sectionDepth!==startDepth){parser.pos=valueStart;parser.error('An attribute value must contain as many opening section tags as closing section tags');}
if(!value.length){return'';}
if(value.length===1&&typeof value[0]==='string'){return decodeCharacterReferences(value[0]);}
return value;}
function readUnquotedAttributeValueToken(parser){var start,text,haystack,needles,index;start=parser.pos;text=parser.matchPattern(unquotedAttributeValueTextPattern);if(!text){return null;}
haystack=text;needles=parser.tags.map(function(t){return t.open;});if((index=getLowestIndex(haystack,needles))!==-1){text=text.substr(0,index);parser.pos=start+text.length;}
return text;}
function readUnquotedAttributeValue(parser){var tokens,token;parser.inAttribute=true;tokens=[];token=readMustache(parser)||readUnquotedAttributeValueToken(parser);while(token!==null){tokens.push(token);token=readMustache(parser)||readUnquotedAttributeValueToken(parser);}
if(!tokens.length){return null;}
parser.inAttribute=false;return tokens;}
function readQuotedAttributeValue(parser,quoteMark){var start,tokens,token;start=parser.pos;if(!parser.matchString(quoteMark)){return null;}
parser.inAttribute=quoteMark;tokens=[];token=readMustache(parser)||readQuotedStringToken(parser,quoteMark);while(token!==null){tokens.push(token);token=readMustache(parser)||readQuotedStringToken(parser,quoteMark);}
if(!parser.matchString(quoteMark)){parser.pos=start;return null;}
parser.inAttribute=false;return tokens;}
function readQuotedStringToken(parser,quoteMark){var haystack=parser.remaining();var needles=parser.tags.map(function(t){return t.open;});needles.push(quoteMark);var index=getLowestIndex(haystack,needles);if(index===-1){parser.error('Quoted attribute value must have a closing quote');}
if(!index){return null;}
parser.pos+=index;return haystack.substr(0,index);}
var specials={'true':true,'false':false,'null':null,undefined:undefined};var specialsPattern=new RegExp('^(?:'+Object.keys(specials).join('|')+')');var numberPattern$1=/^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;var placeholderPattern=/\$\{([^\}]+)\}/g;var placeholderAtStartPattern=/^\$\{([^\}]+)\}/;var onlyWhitespace=/^\s*$/;var JsonParser=Parser$1.extend({init:function(str,options){this.values=options.values;this.allowWhitespace();},postProcess:function(result){if(result.length!==1||!onlyWhitespace.test(this.leftover)){return null;}
return{value:result[0].v};},converters:[function getPlaceholder(parser){if(!parser.values)return null;var placeholder=parser.matchPattern(placeholderAtStartPattern);if(placeholder&&(parser.values.hasOwnProperty(placeholder))){return{v:parser.values[placeholder]};}},function getSpecial(parser){var special=parser.matchPattern(specialsPattern);if(special)return{v:specials[special]};},function getNumber(parser){var number=parser.matchPattern(numberPattern$1);if(number)return{v:+number};},function getString(parser){var stringLiteral=readStringLiteral(parser);var values=parser.values;if(stringLiteral&&values){return{v:stringLiteral.v.replace(placeholderPattern,function(match,$1){return($1 in values?values[$1]:$1);})};}
return stringLiteral;},function getObject(parser){if(!parser.matchString('{'))return null;var result={};parser.allowWhitespace();if(parser.matchString('}')){return{v:result};}
var pair;while(pair=getKeyValuePair(parser)){result[pair.key]=pair.value;parser.allowWhitespace();if(parser.matchString('}')){return{v:result};}
if(!parser.matchString(',')){return null;}}
return null;},function getArray(parser){if(!parser.matchString('['))return null;var result=[];parser.allowWhitespace();if(parser.matchString(']')){return{v:result};}
var valueToken;while(valueToken=parser.read()){result.push(valueToken.v);parser.allowWhitespace();if(parser.matchString(']')){return{v:result};}
if(!parser.matchString(',')){return null;}
parser.allowWhitespace();}
return null;}]});function getKeyValuePair(parser){parser.allowWhitespace();var key=readKey(parser);if(!key)return null;var pair={key:key};parser.allowWhitespace();if(!parser.matchString(':')){return null;}
parser.allowWhitespace();var valueToken=parser.read();if(!valueToken)return null;pair.value=valueToken.v;return pair;}
function parseJSON(str,values){var parser=new JsonParser(str,{values:values});return parser.result;}
var methodCallPattern=/^([a-zA-Z_$][a-zA-Z_$0-9]*)\(/;var methodCallExcessPattern=/\)\s*$/;var spreadPattern=/(\s*,{0,1}\s*\.{3}arguments\s*)$/;var ExpressionParser;ExpressionParser=Parser$1.extend({converters:[readExpression]});function processDirective(tokens,parentParser){var result,match,token,colonIndex,directiveName,directiveArgs,parsed;if(typeof tokens==='string'){if(match=methodCallPattern.exec(tokens)){var end=tokens.lastIndexOf(')');if(!methodCallExcessPattern.test(tokens)){parentParser.error(("Invalid input after method call expression '"+(tokens.slice(end+1))+"'"));}
result={m:match[1]};var sliced=tokens.slice(result.m.length+1,end);var args=sliced.replace(spreadPattern,'');if(sliced!==args){result.g=true;}
if(args){var parser=new ExpressionParser('['+args+']');result.a=flattenExpression(parser.result[0]);}
return result;}
if(tokens.indexOf(':')===-1){return tokens.trim();}
tokens=[tokens];}
result={};directiveName=[];directiveArgs=[];if(tokens){while(tokens.length){token=tokens.shift();if(typeof token==='string'){colonIndex=token.indexOf(':');if(colonIndex===-1){directiveName.push(token);}else{if(colonIndex){directiveName.push(token.substr(0,colonIndex));}
if(token.length>colonIndex+1){directiveArgs[0]=token.substring(colonIndex+1);}
break;}}
else{directiveName.push(token);}}
directiveArgs=directiveArgs.concat(tokens);}
if(!directiveName.length){result='';}else if(directiveArgs.length||typeof directiveName!=='string'){result={n:(directiveName.length===1&&typeof directiveName[0]==='string'?directiveName[0]:directiveName)};if(directiveArgs.length===1&&typeof directiveArgs[0]==='string'){parsed=parseJSON('['+directiveArgs[0]+']');result.a=parsed?parsed.value:[directiveArgs[0].trim()];}
else{result.d=directiveArgs;}}else{result=directiveName;}
return result;}
var tagNamePattern=/^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;var validTagNameFollower=/^[\s\n\/>]/;var onPattern=/^on/;var proxyEventPattern=/^on-([a-zA-Z\\*\\.$_][a-zA-Z\\*\\.$_0-9\-]+)$/;var reservedEventNames=/^(?:change|reset|teardown|update|construct|config|init|render|unrender|detach|insert)$/;var directives={'intro-outro':'t0',intro:'t1',outro:'t2',decorator:'o'};var exclude={exclude:true};var disallowedContents;disallowedContents={li:['li'],dt:['dt','dd'],dd:['dt','dd'],p:'address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul'.split(' '),rt:['rt','rp'],rp:['rt','rp'],optgroup:['optgroup'],option:['option','optgroup'],thead:['tbody','tfoot'],tbody:['tbody','tfoot'],tfoot:['tbody'],tr:['tr','tbody'],td:['td','th','tr'],th:['td','th','tr']};function readElement(parser){var start,element,directiveName,match,addProxyEvent,attribute,directive,selfClosing,children,partials,hasPartials,child,closed,pos,remaining,closingTag;start=parser.pos;if(parser.inside||parser.inAttribute){return null;}
if(!parser.matchString('<')){return null;}
if(parser.nextChar()==='/'){return null;}
element={};if(parser.includeLinePositions){element.p=parser.getLinePos(start);}
if(parser.matchString('!')){element.t=DOCTYPE;if(!parser.matchPattern(/^doctype/i)){parser.error('Expected DOCTYPE declaration');}
element.a=parser.matchPattern(/^(.+?)>/);return element;}
element.t=ELEMENT;element.e=parser.matchPattern(tagNamePattern);if(!element.e){return null;}
if(!validTagNameFollower.test(parser.nextChar())){parser.error('Illegal tag name');}
addProxyEvent=function(name,directive){var directiveName=directive.n||directive;if(reservedEventNames.test(directiveName)){parser.pos-=directiveName.length;parser.error('Cannot use reserved event names (change, reset, teardown, update, construct, config, init, render, unrender, detach, insert)');}
element.v[name]=directive;};parser.allowWhitespace();while(attribute=readMustache(parser)||readAttribute(parser)){if(attribute.name){if(directiveName=directives[attribute.name]){element[directiveName]=processDirective(attribute.value,parser);}
else if(match=proxyEventPattern.exec(attribute.name)){if(!element.v)element.v={};directive=processDirective(attribute.value,parser);addProxyEvent(match[1],directive);}
else{if(!parser.sanitizeEventAttributes||!onPattern.test(attribute.name)){if(!element.a)element.a={};element.a[attribute.name]=attribute.value||(attribute.value===''?'':0);}}}
else{if(!element.m)element.m=[];element.m.push(attribute);}
parser.allowWhitespace();}
parser.allowWhitespace();if(parser.matchString('/')){selfClosing=true;}
if(!parser.matchString('>')){return null;}
var lowerCaseName=element.e.toLowerCase();var preserveWhitespace=parser.preserveWhitespace;if(!selfClosing&&!voidElementNames.test(element.e)){parser.elementStack.push(lowerCaseName);if(lowerCaseName==='script'||lowerCaseName==='style'||lowerCaseName==='textarea'){parser.inside=lowerCaseName;}
children=[];partials=create(null);do{pos=parser.pos;remaining=parser.remaining();if(!remaining){parser.error(("Missing end "+(parser.elementStack.length>1?'tags':'tag')+" ("+(parser.elementStack.reverse().map(function(x){return("</"+x+">");}).join(''))+")"));}
if(!canContain(lowerCaseName,remaining)){closed=true;}
else if(closingTag=readClosingTag(parser)){closed=true;var closingTagName=closingTag.e.toLowerCase();if(closingTagName!==lowerCaseName){parser.pos=pos;if(!~parser.elementStack.indexOf(closingTagName)){var errorMessage='Unexpected closing tag';if(voidElementNames.test(closingTagName)){errorMessage+=" (<"+closingTagName+"> is a void element - it cannot contain children)";}
parser.error(errorMessage);}}}
else if(child=readClosing(parser,{open:parser.standardDelimiters[0],close:parser.standardDelimiters[1]})){closed=true;parser.pos=pos;}
else{if(child=parser.read(PARTIAL_READERS)){if(partials[child.n]){parser.pos=pos;parser.error('Duplicate partial definition');}
cleanup(child.f,parser.stripComments,preserveWhitespace,!preserveWhitespace,!preserveWhitespace);partials[child.n]=child.f;hasPartials=true;}
else{if(child=parser.read(READERS)){children.push(child);}else{closed=true;}}}}while(!closed);if(children.length){element.f=children;}
if(hasPartials){element.p=partials;}
parser.elementStack.pop();}
parser.inside=null;if(parser.sanitizeElements&&parser.sanitizeElements.indexOf(lowerCaseName)!==-1){return exclude;}
return element;}
function canContain(name,remaining){var match,disallowed;match=/^<([a-zA-Z][a-zA-Z0-9]*)/.exec(remaining);disallowed=disallowedContents[name];if(!match||!disallowed){return true;}
return!~disallowed.indexOf(match[1].toLowerCase());}
function readText(parser){var index,remaining,disallowed,barrier;remaining=parser.remaining();if(parser.textOnlyMode){disallowed=parser.tags.map(function(t){return t.open;});disallowed=disallowed.concat(parser.tags.map(function(t){return'\\'+t.open;}));index=getLowestIndex(remaining,disallowed);}else{barrier=parser.inside?'</'+parser.inside:'<';if(parser.inside&&!parser.interpolate[parser.inside]){index=remaining.indexOf(barrier);}else{disallowed=parser.tags.map(function(t){return t.open;});disallowed=disallowed.concat(parser.tags.map(function(t){return'\\'+t.open;}));if(parser.inAttribute===true){disallowed.push(("\""),("'"),("="),("<"),(">"),'`');}else if(parser.inAttribute){disallowed.push(parser.inAttribute);}else{disallowed.push(barrier);}
index=getLowestIndex(remaining,disallowed);}}
if(!index){return null;}
if(index===-1){index=remaining.length;}
parser.pos+=index;if((parser.inside&&parser.inside!=='textarea')||parser.textOnlyMode){return remaining.substr(0,index);}else{return decodeCharacterReferences(remaining.substr(0,index));}}
var startPattern=/^<!--\s*/;var namePattern$1=/s*>\s*([a-zA-Z_$][-a-zA-Z_$0-9]*)\s*/;var finishPattern=/\s*-->/;function readPartialDefinitionComment(parser){var start=parser.pos;var open=parser.standardDelimiters[0];var close=parser.standardDelimiters[1];if(!parser.matchPattern(startPattern)||!parser.matchString(open)){parser.pos=start;return null;}
var name=parser.matchPattern(namePattern$1);warnOnceIfDebug(("Inline partial comments are deprecated.\nUse this...\n  {{#partial "+name+"}} ... {{/partial}}\n\n...instead of this:\n  <!-- {{>"+name+"}} --> ... <!-- {{/"+name+"}} -->'"));if(!parser.matchString(close)||!parser.matchPattern(finishPattern)){parser.pos=start;return null;}
var content=[];var closed;var endPattern=new RegExp('^<!--\\s*'+escapeRegExp(open)+'\\s*\\/\\s*'+name+'\\s*'+escapeRegExp(close)+'\\s*-->');do{if(parser.matchPattern(endPattern)){closed=true;}
else{var child=parser.read(READERS);if(!child){parser.error(("expected closing comment ('<!-- "+open+"/"+name+""+close+" -->')"));}
content.push(child);}}while(!closed);return{t:INLINE_PARTIAL,f:content,n:name};}
var partialDefinitionSectionPattern=/^#\s*partial\s+/;function readPartialDefinitionSection(parser){var start,name,content,child,closed;start=parser.pos;var delimiters=parser.standardDelimiters;if(!parser.matchString(delimiters[0])){return null;}
if(!parser.matchPattern(partialDefinitionSectionPattern)){parser.pos=start;return null;}
name=parser.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-\/]*/);if(!name){parser.error('expected legal partial name');}
if(!parser.matchString(delimiters[1])){parser.error(("Expected closing delimiter '"+(delimiters[1])+"'"));}
content=[];do{if(child=readClosing(parser,{open:parser.standardDelimiters[0],close:parser.standardDelimiters[1]})){if(!child.r==='partial'){parser.error(("Expected "+(delimiters[0])+"/partial"+(delimiters[1])));}
closed=true;}
else{child=parser.read(READERS);if(!child){parser.error(("Expected "+(delimiters[0])+"/partial"+(delimiters[1])));}
content.push(child);}}while(!closed);return{t:INLINE_PARTIAL,n:name,f:content};}
function readTemplate(parser){var fragment=[];var partials=create(null);var hasPartials=false;var preserveWhitespace=parser.preserveWhitespace;while(parser.pos<parser.str.length){var pos=parser.pos,item,partial;if(partial=parser.read(PARTIAL_READERS)){if(partials[partial.n]){parser.pos=pos;parser.error('Duplicated partial definition');}
cleanup(partial.f,parser.stripComments,preserveWhitespace,!preserveWhitespace,!preserveWhitespace);partials[partial.n]=partial.f;hasPartials=true;}else if(item=parser.read(READERS)){fragment.push(item);}else{parser.error('Unexpected template content');}}
var result={v:TEMPLATE_VERSION,t:fragment};if(hasPartials){result.p=partials;}
return result;}
function insertExpressions(obj,expr){Object.keys(obj).forEach(function(key){if(isExpression(key,obj))return addTo(obj,expr);var ref=obj[key];if(hasChildren(ref))insertExpressions(ref,expr);});}
function isExpression(key,obj){return key==='s'&&isArray(obj.r);}
function addTo(obj,expr){var s=obj.s,r=obj.r;if(!expr[s])expr[s]=fromExpression(s,r.length);}
function hasChildren(ref){return isArray(ref)||isObject(ref);}
var STANDARD_READERS=[readPartial,readUnescaped,readSection,readYielder,readInterpolator,readComment];var TRIPLE_READERS=[readTriple];var STATIC_READERS=[readUnescaped,readSection,readInterpolator];var StandardParser;function parse(template,options){return new StandardParser(template,options||{}).result;}
parse.computedStrings=function(computed){if(!computed)return[];Object.keys(computed).forEach(function(key){var value=computed[key];if(typeof value==='string'){computed[key]=fromComputationString(value);}});};var READERS=[readMustache,readHtmlComment,readElement,readText];var PARTIAL_READERS=[readPartialDefinitionComment,readPartialDefinitionSection];StandardParser=Parser$1.extend({init:function(str,options){var tripleDelimiters=options.tripleDelimiters||['{{{','}}}'],staticDelimiters=options.staticDelimiters||['[[',']]'],staticTripleDelimiters=options.staticTripleDelimiters||['[[[',']]]'];this.standardDelimiters=options.delimiters||['{{','}}'];this.tags=[{isStatic:false,isTriple:false,open:this.standardDelimiters[0],close:this.standardDelimiters[1],readers:STANDARD_READERS},{isStatic:false,isTriple:true,open:tripleDelimiters[0],close:tripleDelimiters[1],readers:TRIPLE_READERS},{isStatic:true,isTriple:false,open:staticDelimiters[0],close:staticDelimiters[1],readers:STATIC_READERS},{isStatic:true,isTriple:true,open:staticTripleDelimiters[0],close:staticTripleDelimiters[1],readers:TRIPLE_READERS}];this.sortMustacheTags();this.sectionDepth=0;this.elementStack=[];this.interpolate={script:!options.interpolate||options.interpolate.script!==false,style:!options.interpolate||options.interpolate.style!==false,textarea:true};if(options.sanitize===true){options.sanitize={elements:'applet base basefont body frame frameset head html isindex link meta noframes noscript object param script style title'.split(' '),eventAttributes:true};}
this.stripComments=options.stripComments!==false;this.preserveWhitespace=options.preserveWhitespace;this.sanitizeElements=options.sanitize&&options.sanitize.elements;this.sanitizeEventAttributes=options.sanitize&&options.sanitize.eventAttributes;this.includeLinePositions=options.includeLinePositions;this.textOnlyMode=options.textOnlyMode;this.csp=options.csp;},postProcess:function(result){if(!result.length){return{t:[],v:TEMPLATE_VERSION};}
if(this.sectionDepth>0){this.error('A section was left open');}
cleanup(result[0].t,this.stripComments,this.preserveWhitespace,!this.preserveWhitespace,!this.preserveWhitespace);if(this.csp!==false){var expr={};insertExpressions(result[0].t,expr);if(Object.keys(expr).length)result[0].e=expr;}
return result[0];},converters:[readTemplate],sortMustacheTags:function(){this.tags.sort(function(a,b){return b.open.length-a.open.length;});}});var parseOptions=['delimiters','tripleDelimiters','staticDelimiters','staticTripleDelimiters','csp','interpolate','preserveWhitespace','sanitize','stripComments'];var TEMPLATE_INSTRUCTIONS="Either preparse or use a ractive runtime source that includes the parser. ";var COMPUTATION_INSTRUCTIONS="Either use:\n\n\tRactive.parse.computedStrings( component.computed )\n\nat build time to pre-convert the strings to functions, or use functions instead of strings in computed properties.";function throwNoParse(method,error,instructions){if(!method){fatal(("Missing Ractive.parse - cannot parse "+error+". "+instructions));}}
function createFunction(body,length){throwNoParse(fromExpression,'new expression function',TEMPLATE_INSTRUCTIONS);return fromExpression(body,length);}
function createFunctionFromString(str,bindTo){throwNoParse(fromComputationString,'compution string "${str}"',COMPUTATION_INSTRUCTIONS);return fromComputationString(str,bindTo);}
var parser={fromId:function(id,options){if(!doc){if(options&&options.noThrow){return;}
throw new Error(("Cannot retrieve template #"+id+" as Ractive is not running in a browser."));}
if(id)id=id.replace(/^#/,'');var template;if(!(template=doc.getElementById(id))){if(options&&options.noThrow){return;}
throw new Error(("Could not find template element with id #"+id));}
if(template.tagName.toUpperCase()!=='SCRIPT'){if(options&&options.noThrow){return;}
throw new Error(("Template element with id #"+id+", must be a <script> element"));}
return('textContent'in template?template.textContent:template.innerHTML);},isParsed:function(template){return!(typeof template==='string');},getParseOptions:function(ractive){if(ractive.defaults){ractive=ractive.defaults;}
return parseOptions.reduce(function(val,key){val[key]=ractive[key];return val;},{});},parse:function(template,options){throwNoParse(parse,'template',TEMPLATE_INSTRUCTIONS);var parsed=parse(template,options);addFunctions(parsed);return parsed;},parseFor:function(template,ractive){return this.parse(template,this.getParseOptions(ractive));}};var templateConfigurator={name:'template',extend:function(Parent,proto,options){if('template'in options){var template=options.template;if(typeof template==='function'){proto.template=template;}else{proto.template=parseTemplate(template,proto);}}},init:function(Parent,ractive,options){var template='template'in options?options.template:Parent.prototype.template;template=template||{v:TEMPLATE_VERSION,t:[]};if(typeof template==='function'){var fn=template;template=getDynamicTemplate(ractive,fn);ractive._config.template={fn:fn,result:template};}
template=parseTemplate(template,ractive);ractive.template=template.t;if(template.p){extendPartials(ractive.partials,template.p);}},reset:function(ractive){var result=resetValue(ractive);if(result){var parsed=parseTemplate(result,ractive);ractive.template=parsed.t;extendPartials(ractive.partials,parsed.p,true);return true;}}};function resetValue(ractive){var initial=ractive._config.template;if(!initial||!initial.fn){return;}
var result=getDynamicTemplate(ractive,initial.fn);if(result!==initial.result){initial.result=result;return result;}}
function getDynamicTemplate(ractive,fn){return fn.call(ractive,{fromId:parser.fromId,isParsed:parser.isParsed,parse:function(template,options){if(options===void 0)options=parser.getParseOptions(ractive);return parser.parse(template,options);}});}
function parseTemplate(template,ractive){if(typeof template==='string'){template=parseAsString(template,ractive);}
else{validate$1(template);addFunctions(template);}
return template;}
function parseAsString(template,ractive){if(template[0]==='#'){template=parser.fromId(template);}
return parser.parseFor(template,ractive);}
function validate$1(template){if(template==undefined){throw new Error(("The template cannot be "+template+"."));}
else if(typeof template.v!=='number'){throw new Error('The template parser was passed a non-string template, but the template doesn\'t have a version.  Make sure you\'re passing in the template you think you are.');}
else if(template.v!==TEMPLATE_VERSION){throw new Error(("Mismatched template version (expected "+TEMPLATE_VERSION+", got "+(template.v)+") Please ensure you are using the latest version of Ractive.js in your build process as well as in your app"));}}
function extendPartials(existingPartials,newPartials,overwrite){if(!newPartials)return;for(var key in newPartials){if(overwrite||!existingPartials.hasOwnProperty(key)){existingPartials[key]=newPartials[key];}}}
var registryNames=['adaptors','components','computed','decorators','easing','events','interpolators','partials','transitions'];var Registry=function Registry(name,useDefaults){this.name=name;this.useDefaults=useDefaults;};Registry.prototype.extend=function extend(Parent,proto,options){this.configure(this.useDefaults?Parent.defaults:Parent,this.useDefaults?proto:proto.constructor,options);};Registry.prototype.init=function init(){};Registry.prototype.configure=function configure(Parent,target,options){var name=this.name;var option=options[name];var registry=create(Parent[name]);for(var key in option){registry[key]=option[key];}
target[name]=registry;};Registry.prototype.reset=function reset(ractive){var registry=ractive[this.name];var changed=false;Object.keys(registry).forEach(function(key){var item=registry[key];if(item._fn){if(item._fn.isOwner){registry[key]=item._fn;}else{delete registry[key];}
changed=true;}});return changed;};var registries=registryNames.map(function(name){return new Registry(name,name==='computed');});function wrap(parent,name,method){if(!/_super/.test(method))return method;function wrapper(){var superMethod=getSuperMethod(wrapper._parent,name);var hasSuper='_super'in this;var oldSuper=this._super;this._super=superMethod;var result=method.apply(this,arguments);if(hasSuper){this._super=oldSuper;}else{delete this._super;}
return result;}
wrapper._parent=parent;wrapper._method=method;return wrapper;}
function getSuperMethod(parent,name){if(name in parent){var value=parent[name];return typeof value==='function'?value:function(){return value;};}
return noop;}
function getMessage(deprecated,correct,isError){return"options."+deprecated+" has been deprecated in favour of options."+correct+"."
+(isError?(" You cannot specify both options, please use options."+correct+"."):'');}
function deprecateOption(options,deprecatedOption,correct){if(deprecatedOption in options){if(!(correct in options)){warnIfDebug(getMessage(deprecatedOption,correct));options[correct]=options[deprecatedOption];}else{throw new Error(getMessage(deprecatedOption,correct,true));}}}
function deprecate(options){deprecateOption(options,'beforeInit','onconstruct');deprecateOption(options,'init','onrender');deprecateOption(options,'complete','oncomplete');deprecateOption(options,'eventDefinitions','events');if(isArray(options.adaptors)){deprecateOption(options,'adaptors','adapt');}}
var custom={adapt:adaptConfigurator,css:cssConfigurator,data:dataConfigurator,template:templateConfigurator};var defaultKeys=Object.keys(defaults);var isStandardKey=makeObj(defaultKeys.filter(function(key){return!custom[key];}));var isBlacklisted=makeObj(defaultKeys.concat(registries.map(function(r){return r.name;})));var order=[].concat(defaultKeys.filter(function(key){return!registries[key]&&!custom[key];}),registries,custom.template,custom.css);var config={extend:function(Parent,proto,options){return configure('extend',Parent,proto,options);},init:function(Parent,ractive,options){return configure('init',Parent,ractive,options);},reset:function(ractive){return order.filter(function(c){return c.reset&&c.reset(ractive);}).map(function(c){return c.name;});},order:order};function configure(method,Parent,target,options){deprecate(options);for(var key in options){if(isStandardKey.hasOwnProperty(key)){var value=options[key];if(key!=='el'&&typeof value==='function'){warnIfDebug((""+key+" is a Ractive option that does not expect a function and will be ignored"),method==='init'?target:null);}
else{target[key]=value;}}}
if(options.append&&options.enhance){throw new Error('Cannot use append and enhance at the same time');}
registries.forEach(function(registry){registry[method](Parent,target,options);});adaptConfigurator[method](Parent,target,options);templateConfigurator[method](Parent,target,options);cssConfigurator[method](Parent,target,options);extendOtherMethods(Parent.prototype,target,options);}
function extendOtherMethods(parent,target,options){for(var key in options){if(!isBlacklisted[key]&&options.hasOwnProperty(key)){var member=options[key];if(typeof member==='function'){member=wrap(parent,key,member);}
target[key]=member;}}}
function makeObj(array){var obj={};array.forEach(function(x){return obj[x]=true;});return obj;}
var shouldRerender=['template','partials','components','decorators','events'];var completeHook$1=new Hook('complete');var resetHook=new Hook('reset');var renderHook$1=new Hook('render');var unrenderHook=new Hook('unrender');function Ractive$reset(data){data=data||{};if(typeof data!=='object'){throw new Error('The reset method takes either no arguments, or an object containing new data');}
data=dataConfigurator.init(this.constructor,this,{data:data});var promise=runloop.start(this,true);var wrapper=this.viewmodel.wrapper;if(wrapper&&wrapper.reset){if(wrapper.reset(data)===false){this.viewmodel.set(data);}}else{this.viewmodel.set(data);}
var changes=config.reset(this);var rerender;var i=changes.length;while(i--){if(shouldRerender.indexOf(changes[i])>-1){rerender=true;break;}}
if(rerender){unrenderHook.fire(this);this.fragment.resetTemplate(this.template);renderHook$1.fire(this);completeHook$1.fire(this);}
runloop.end();resetHook.fire(this,data);return promise;}
function collect(source,name,dest){source.forEach(function(item){if(item.type===PARTIAL&&(item.refName===name||item.name===name)){dest.push(item);return;}
if(item.fragment){collect(item.fragment.iterations||item.fragment.items,name,dest);}
else if(isArray(item.items)){collect(item.items,name,dest);}
else if(item.type===COMPONENT&&item.instance){if(item.instance.partials[name])return;collect(item.instance.fragment.items,name,dest);}
if(item.type===ELEMENT){if(isArray(item.attributes)){collect(item.attributes,name,dest);}
if(isArray(item.conditionalAttributes)){collect(item.conditionalAttributes,name,dest);}}});}
function forceResetTemplate(partial){partial.forceResetTemplate();}
function resetPartial(name,partial){var collection=[];collect(this.fragment.items,name,collection);var promise=runloop.start(this,true);this.partials[name]=partial;collection.forEach(forceResetTemplate);runloop.end();return promise;}
var Item=function Item(options){this.parentFragment=options.parentFragment;this.ractive=options.parentFragment.ractive;this.template=options.template;this.index=options.index;this.type=options.template.t;this.dirty=false;};Item.prototype.bubble=function bubble(){if(!this.dirty){this.dirty=true;this.parentFragment.bubble();}};Item.prototype.find=function find(){return null;};Item.prototype.findAll=function findAll(){};Item.prototype.findComponent=function findComponent(){return null;};Item.prototype.findAllComponents=function findAllComponents(){};Item.prototype.findNextNode=function findNextNode(){return this.parentFragment.findNextNode(this);};Item.prototype.valueOf=function valueOf(){return this.toString();};var ComputationChild=(function(Model){function ComputationChild(){Model.apply(this,arguments);}
ComputationChild.prototype=Object.create(Model&&Model.prototype);ComputationChild.prototype.constructor=ComputationChild;ComputationChild.prototype.get=function get(shouldCapture){if(shouldCapture)capture(this);var parentValue=this.parent.get();return parentValue?parentValue[this.key]:undefined;};ComputationChild.prototype.handleChange=function handleChange$1(){this.dirty=true;this.deps.forEach(handleChange);this.children.forEach(handleChange);this.clearUnresolveds();};ComputationChild.prototype.joinKey=function joinKey(key){if(key===undefined||key==='')return this;if(!this.childByKey.hasOwnProperty(key)){var child=new ComputationChild(this,key);this.children.push(child);this.childByKey[key]=child;}
return this.childByKey[key];};return ComputationChild;}(Model));function getValue(model){return model?model.get(true):undefined;}
var ExpressionProxy=(function(Model){function ExpressionProxy(fragment,template){var this$1=this;Model.call(this,fragment.ractive.viewmodel,null);this.fragment=fragment;this.template=template;this.isReadonly=true;this.fn=getFunction(template.s,template.r.length);this.computation=null;this.resolvers=[];this.models=this.template.r.map(function(ref,index){var model=resolveReference(this$1.fragment,ref);var resolver;if(!model){resolver=this$1.fragment.resolve(ref,function(model){removeFromArray(this$1.resolvers,resolver);this$1.models[index]=model;this$1.bubble();});this$1.resolvers.push(resolver);}
return model;});this.bubble();}
ExpressionProxy.prototype=Object.create(Model&&Model.prototype);ExpressionProxy.prototype.constructor=ExpressionProxy;ExpressionProxy.prototype.bubble=function bubble(){var this$1=this;var ractive=this.fragment.ractive;var key='@'+this.template.s.replace(/_(\d+)/g,function(match,i){if(i>=this$1.models.length)return match;var model=this$1.models[i];return model?model.getKeypath():'@undefined';});var signature={getter:function(){var values=this$1.models.map(getValue);return this$1.fn.apply(ractive,values);},getterString:key};var computation=ractive.viewmodel.compute(key,signature);this.value=computation.get();if(this.computation){this.computation.unregister(this);}
this.computation=computation;computation.register(this);this.handleChange();};ExpressionProxy.prototype.get=function get(shouldCapture){return this.computation.get(shouldCapture);};ExpressionProxy.prototype.getKeypath=function getKeypath(){return this.computation?this.computation.getKeypath():'@undefined';};ExpressionProxy.prototype.handleChange=function handleChange$1(){this.deps.forEach(handleChange);this.children.forEach(handleChange);this.clearUnresolveds();};ExpressionProxy.prototype.joinKey=function joinKey(key){if(key===undefined||key==='')return this;if(!this.childByKey.hasOwnProperty(key)){var child=new ComputationChild(this,key);this.children.push(child);this.childByKey[key]=child;}
return this.childByKey[key];};ExpressionProxy.prototype.mark=function mark(){this.handleChange();};ExpressionProxy.prototype.retrieve=function retrieve(){return this.get();};ExpressionProxy.prototype.teardown=function teardown(){this.unbind();this.fragment=undefined;if(this.computation){this.computation.teardown();}
this.computation=undefined;Model.prototype.teardown.call(this);};ExpressionProxy.prototype.unregister=function unregister(dep){Model.prototype.unregister.call(this,dep);if(!this.deps.length)this.teardown();};ExpressionProxy.prototype.unbind=function unbind$1(){var this$1=this;this.resolvers.forEach(unbind);var i=this.models.length;while(i--){if(this$1.models[i])this$1.models[i].unregister(this$1);}};return ExpressionProxy;}(Model));var ReferenceExpressionChild=(function(Model){function ReferenceExpressionChild(parent,key){Model.call(this,parent,key);}
ReferenceExpressionChild.prototype=Object.create(Model&&Model.prototype);ReferenceExpressionChild.prototype.constructor=ReferenceExpressionChild;ReferenceExpressionChild.prototype.applyValue=function applyValue(value){if(isEqual(value,this.value))return;var parent=this.parent,keys=[this.key];while(parent){if(parent.base){var target=parent.model.joinAll(keys);target.applyValue(value);break;}
keys.unshift(parent.key);parent=parent.parent;}};ReferenceExpressionChild.prototype.joinKey=function joinKey(key){if(key===undefined||key==='')return this;if(!this.childByKey.hasOwnProperty(key)){var child=new ReferenceExpressionChild(this,key);this.children.push(child);this.childByKey[key]=child;}
return this.childByKey[key];};return ReferenceExpressionChild;}(Model));var ReferenceExpressionProxy=(function(Model){function ReferenceExpressionProxy(fragment,template){var this$1=this;Model.call(this,null,null);this.root=fragment.ractive.viewmodel;this.resolvers=[];this.base=resolve$1(fragment,template);var baseResolver;if(!this.base){baseResolver=fragment.resolve(template.r,function(model){this$1.base=model;this$1.bubble();removeFromArray(this$1.resolvers,baseResolver);});this.resolvers.push(baseResolver);}
var intermediary={handleChange:function(){return this$1.bubble();}};this.members=template.m.map(function(template,i){if(typeof template==='string'){return{get:function(){return template;}};}
var model;var resolver;if(template.t===REFERENCE){model=resolveReference(fragment,template.n);if(model){model.register(intermediary);}else{resolver=fragment.resolve(template.n,function(model){this$1.members[i]=model;model.register(intermediary);this$1.bubble();removeFromArray(this$1.resolvers,resolver);});this$1.resolvers.push(resolver);}
return model;}
model=new ExpressionProxy(fragment,template);model.register(intermediary);return model;});this.isUnresolved=true;this.bubble();}
ReferenceExpressionProxy.prototype=Object.create(Model&&Model.prototype);ReferenceExpressionProxy.prototype.constructor=ReferenceExpressionProxy;ReferenceExpressionProxy.prototype.bubble=function bubble(){var this$1=this;if(!this.base)return;var i=this.members.length;while(i--){if(!this$1.members[i])return;}
this.isUnresolved=false;var keys=this.members.map(function(model){return escapeKey(String(model.get()));});var model=this.base.joinAll(keys);if(this.model){this.model.unregister(this);this.model.unregisterTwowayBinding(this);}
this.model=model;this.parent=model.parent;model.register(this);model.registerTwowayBinding(this);if(this.keypathModel)this.keypathModel.handleChange();this.mark();};ReferenceExpressionProxy.prototype.forceResolution=function forceResolution(){this.resolvers.forEach(function(resolver){return resolver.forceResolution();});this.bubble();};ReferenceExpressionProxy.prototype.get=function get(){return this.model?this.model.get():undefined;};ReferenceExpressionProxy.prototype.getValue=function getValue(){var this$1=this;var i=this.bindings.length;while(i--){var value=this$1.bindings[i].getValue();if(value!==this$1.value)return value;}
return this.value;};ReferenceExpressionProxy.prototype.getKeypath=function getKeypath(){return this.model?this.model.getKeypath():'@undefined';};ReferenceExpressionProxy.prototype.handleChange=function handleChange(){this.mark();};ReferenceExpressionProxy.prototype.joinKey=function joinKey(key){if(key===undefined||key==='')return this;if(!this.childByKey.hasOwnProperty(key)){var child=new ReferenceExpressionChild(this,key);this.children.push(child);this.childByKey[key]=child;}
return this.childByKey[key];};ReferenceExpressionProxy.prototype.retrieve=function retrieve(){return this.get();};ReferenceExpressionProxy.prototype.set=function set(value){if(!this.model)throw new Error('Unresolved reference expression. This should not happen!');this.model.set(value);};ReferenceExpressionProxy.prototype.unbind=function unbind$1(){this.resolvers.forEach(unbind);};return ReferenceExpressionProxy;}(Model));function resolve$1(fragment,template){if(template.r){return resolveReference(fragment,template.r);}
else if(template.x){return new ExpressionProxy(fragment,template.x);}
else{return new ReferenceExpressionProxy(fragment,template.rx);}}
function resolveAliases(section){if(section.template.z){section.aliases={};var refs=section.template.z;for(var i=0;i<refs.length;i++){section.aliases[refs[i].n]=resolve$1(section.parentFragment,refs[i].x);}}}
var Alias=(function(Item){function Alias(options){Item.call(this,options);this.fragment=null;}
Alias.prototype=Object.create(Item&&Item.prototype);Alias.prototype.constructor=Alias;Alias.prototype.bind=function bind(){resolveAliases(this);this.fragment=new Fragment({owner:this,template:this.template.f}).bind();};Alias.prototype.detach=function detach(){return this.fragment?this.fragment.detach():createDocumentFragment();};Alias.prototype.find=function find(selector){if(this.fragment){return this.fragment.find(selector);}};Alias.prototype.findAll=function findAll(selector,query){if(this.fragment){this.fragment.findAll(selector,query);}};Alias.prototype.findComponent=function findComponent(name){if(this.fragment){return this.fragment.findComponent(name);}};Alias.prototype.findAllComponents=function findAllComponents(name,query){if(this.fragment){this.fragment.findAllComponents(name,query);}};Alias.prototype.firstNode=function firstNode(skipParent){return this.fragment&&this.fragment.firstNode(skipParent);};Alias.prototype.rebind=function rebind(){resolveAliases(this);if(this.fragment)this.fragment.rebind();};Alias.prototype.render=function render(target){this.rendered=true;if(this.fragment)this.fragment.render(target);};Alias.prototype.toString=function toString(escape){return this.fragment?this.fragment.toString(escape):'';};Alias.prototype.unbind=function unbind(){this.aliases={};if(this.fragment)this.fragment.unbind();};Alias.prototype.unrender=function unrender(shouldDestroy){if(this.rendered&&this.fragment)this.fragment.unrender(shouldDestroy);this.rendered=false;};Alias.prototype.update=function update(){if(this.dirty){this.dirty=false;this.fragment.update();}};return Alias;}(Item));function processWrapper(wrapper,array,methodName,newIndices){var __model=wrapper.__model;if(newIndices){__model.shuffle(newIndices);}else{}}
var mutatorMethods=['pop','push','reverse','shift','sort','splice','unshift'];var patchedArrayProto=[];mutatorMethods.forEach(function(methodName){var method=function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var newIndices=getNewIndices(this.length,methodName,args);var result=Array.prototype[methodName].apply(this,arguments);runloop.start();this._ractive.setting=true;var i=this._ractive.wrappers.length;while(i--){processWrapper(this$1._ractive.wrappers[i],this$1,methodName,newIndices);}
runloop.end();this._ractive.setting=false;return result;};defineProperty(patchedArrayProto,methodName,{value:method});});var patchArrayMethods;var unpatchArrayMethods;if(({}).__proto__){patchArrayMethods=function(array){return array.__proto__=patchedArrayProto;};unpatchArrayMethods=function(array){return array.__proto__=Array.prototype;};}
else{patchArrayMethods=function(array){var i=mutatorMethods.length;while(i--){var methodName=mutatorMethods[i];defineProperty(array,methodName,{value:patchedArrayProto[methodName],configurable:true});}};unpatchArrayMethods=function(array){var i=mutatorMethods.length;while(i--){delete array[mutatorMethods[i]];}};}
patchArrayMethods.unpatch=unpatchArrayMethods;var patch=patchArrayMethods;var errorMessage$1='Something went wrong in a rather interesting way';var arrayAdaptor={filter:function(object){return isArray(object)&&(!object._ractive||!object._ractive.setting);},wrap:function(ractive,array,keypath){return new ArrayWrapper(ractive,array,keypath);}};var ArrayWrapper=function ArrayWrapper(ractive,array){this.root=ractive;this.value=array;this.__model=null;if(!array._ractive){defineProperty(array,'_ractive',{value:{wrappers:[],instances:[],setting:false},configurable:true});patch(array);}
if(!array._ractive.instances[ractive._guid]){array._ractive.instances[ractive._guid]=0;array._ractive.instances.push(ractive);}
array._ractive.instances[ractive._guid]+=1;array._ractive.wrappers.push(this);};ArrayWrapper.prototype.get=function get(){return this.value;};ArrayWrapper.prototype.reset=function reset(value){return this.value===value;};ArrayWrapper.prototype.teardown=function teardown(){var array,storage,wrappers,instances,index;array=this.value;storage=array._ractive;wrappers=storage.wrappers;instances=storage.instances;if(storage.setting){return false;}
index=wrappers.indexOf(this);if(index===-1){throw new Error(errorMessage$1);}
wrappers.splice(index,1);if(!wrappers.length){delete array._ractive;patch.unpatch(this.value);}
else{instances[this.root._guid]-=1;if(!instances[this.root._guid]){index=instances.indexOf(this.root);if(index===-1){throw new Error(errorMessage$1);}
instances.splice(index,1);}}};var magicAdaptor;try{Object.defineProperty({},'test',{get:function(){},set:function(){}});magicAdaptor={filter:function(value){return value&&typeof value==='object';},wrap:function(ractive,value,keypath){return new MagicWrapper(ractive,value,keypath);}};}catch(err){magicAdaptor=false;}
var magicAdaptor$1=magicAdaptor;function createOrWrapDescriptor(originalDescriptor,ractive,keypath){if(originalDescriptor.set&&originalDescriptor.set.__magic){originalDescriptor.set.__magic.dependants.push({ractive:ractive,keypath:keypath});return originalDescriptor;}
var setting;var dependants=[{ractive:ractive,keypath:keypath}];var descriptor={get:function(){return'value'in originalDescriptor?originalDescriptor.value:originalDescriptor.get();},set:function(value){if(setting)return;if('value'in originalDescriptor){originalDescriptor.value=value;}else{originalDescriptor.set(value);}
setting=true;dependants.forEach(function(ref){var ractive=ref.ractive;var keypath=ref.keypath;ractive.set(keypath,value);});setting=false;},enumerable:true};descriptor.set.__magic={dependants:dependants,originalDescriptor:originalDescriptor};return descriptor;}
function revert(descriptor,ractive,keypath){if(!descriptor.set||!descriptor.set.__magic)return true;var dependants=descriptor.set.__magic;var i=dependants.length;while(i--){var dependant=dependants[i];if(dependant.ractive===ractive&&dependant.keypath===keypath){dependants.splice(i,1);return false;}}}
var MagicWrapper=function MagicWrapper(ractive,value,keypath){var this$1=this;this.ractive=ractive;this.value=value;this.keypath=keypath;this.originalDescriptors={};Object.keys(value).forEach(function(key){var originalDescriptor=Object.getOwnPropertyDescriptor(this$1.value,key);this$1.originalDescriptors[key]=originalDescriptor;var childKeypath=keypath?(""+keypath+"."+(escapeKey(key))):escapeKey(key);var descriptor=createOrWrapDescriptor(originalDescriptor,ractive,childKeypath);Object.defineProperty(this$1.value,key,descriptor);});};MagicWrapper.prototype.get=function get(){return this.value;};MagicWrapper.prototype.reset=function reset(value){return this.value===value;};MagicWrapper.prototype.set=function set(key,value){this.value[key]=value;};MagicWrapper.prototype.teardown=function teardown(){var this$1=this;Object.keys(this.value).forEach(function(key){var descriptor=Object.getOwnPropertyDescriptor(this$1.value,key);if(!descriptor.set||!descriptor.set.__magic)return;revert(descriptor);if(descriptor.set.__magic.dependants.length===1){Object.defineProperty(this$1.value,key,descriptor.set.__magic.originalDescriptor);}});};var MagicArrayWrapper=function MagicArrayWrapper(ractive,array,keypath){this.value=array;this.magic=true;this.magicWrapper=magicAdaptor$1.wrap(ractive,array,keypath);this.arrayWrapper=arrayAdaptor.wrap(ractive,array,keypath);Object.defineProperty(this,'__model',{get:function(){return this.arrayWrapper.__model;},set:function(model){this.arrayWrapper.__model=model;}});};MagicArrayWrapper.prototype.get=function get(){return this.value;};MagicArrayWrapper.prototype.teardown=function teardown(){this.arrayWrapper.teardown();this.magicWrapper.teardown();};MagicArrayWrapper.prototype.reset=function reset(value){return this.arrayWrapper.reset(value)&&this.magicWrapper.reset(value);};var magicArrayAdaptor={filter:function(object,keypath,ractive){return magicAdaptor$1.filter(object,keypath,ractive)&&arrayAdaptor.filter(object);},wrap:function(ractive,array,keypath){return new MagicArrayWrapper(ractive,array,keypath);}};function prettify(fnBody){var lines=fnBody.replace(/^\t+/gm,function(tabs){return tabs.split('\t').join('  ');}).split('\n');var minIndent=lines.length<2?0:lines.slice(1).reduce(function(prev,line){return Math.min(prev,/^\s*/.exec(line)[0].length);},Infinity);return lines.map(function(line,i){return'    '+(i?line.substring(minIndent):line);}).join('\n');}
function truncateStack(stack){if(!stack)return'';var lines=stack.split('\n');var name=Computation.name+'.getValue';var truncated=[];var len=lines.length;for(var i=1;i<len;i+=1){var line=lines[i];if(~line.indexOf(name)){return truncated.join('\n');}else{truncated.push(line);}}}
var Computation=(function(Model){function Computation(viewmodel,signature,key){Model.call(this,null,null);this.root=this.parent=viewmodel;this.signature=signature;this.key=key;this.isExpression=key&&key[0]==='@';this.isReadonly=!this.signature.setter;this.context=viewmodel.computationContext;this.dependencies=[];this.children=[];this.childByKey={};this.deps=[];this.boundsSensitive=true;this.dirty=true;this.shuffle=undefined;}
Computation.prototype=Object.create(Model&&Model.prototype);Computation.prototype.constructor=Computation;Computation.prototype.get=function get(shouldCapture){if(shouldCapture)capture(this);if(this.dirty){this.dirty=false;this.value=this.getValue();this.adapt();}
return this.value;};Computation.prototype.getValue=function getValue(){startCapturing();var result;try{result=this.signature.getter.call(this.context);}catch(err){warnIfDebug(("Failed to compute "+(this.getKeypath())+": "+(err.message||err)));if(hasConsole){if(console.groupCollapsed)console.groupCollapsed('%cshow details','color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;');var functionBody=prettify(this.signature.getterString);var stack=this.signature.getterUseStack?'\n\n'+truncateStack(err.stack):'';console.error((""+(err.name)+": "+(err.message)+"\n\n"+functionBody+""+stack));if(console.groupCollapsed)console.groupEnd();}}
var dependencies=stopCapturing();this.setDependencies(dependencies);return result;};Computation.prototype.handleChange=function handleChange$1(){this.dirty=true;this.deps.forEach(handleChange);this.children.forEach(handleChange);this.clearUnresolveds();};Computation.prototype.joinKey=function joinKey(key){if(key===undefined||key==='')return this;if(!this.childByKey.hasOwnProperty(key)){var child=new ComputationChild(this,key);this.children.push(child);this.childByKey[key]=child;}
return this.childByKey[key];};Computation.prototype.mark=function mark(){this.handleChange();};Computation.prototype.set=function set(value){if(!this.signature.setter){throw new Error(("Cannot set read-only computed value '"+(this.key)+"'"));}
this.signature.setter(value);};Computation.prototype.setDependencies=function setDependencies(dependencies){var this$1=this;var i=this.dependencies.length;while(i--){var model=this$1.dependencies[i];if(!~dependencies.indexOf(model))model.unregister(this$1);}
i=dependencies.length;while(i--){var model$1=dependencies[i];if(!~this$1.dependencies.indexOf(model$1))model$1.register(this$1);}
this.dependencies=dependencies;};Computation.prototype.teardown=function teardown(){var this$1=this;var i=this.dependencies.length;while(i--){if(this$1.dependencies[i])this$1.dependencies[i].unregister(this$1);}
if(this.root.computations[this.key]===this)delete this.root.computations[this.key];Model.prototype.teardown.call(this);};return Computation;}(Model));var RactiveModel=(function(Model){function RactiveModel(ractive){Model.call(this,null,'');this.value=ractive;this.isRoot=true;this.root=this;this.adaptors=[];this.ractive=ractive;this.changes={};}
RactiveModel.prototype=Object.create(Model&&Model.prototype);RactiveModel.prototype.constructor=RactiveModel;RactiveModel.prototype.getKeypath=function getKeypath(){return'@ractive';};return RactiveModel;}(Model));var hasProp$1=Object.prototype.hasOwnProperty;var RootModel=(function(Model){function RootModel(options){Model.call(this,null,null);this.changes={};this.isRoot=true;this.root=this;this.ractive=options.ractive;this.value=options.data;this.adaptors=options.adapt;this.adapt();this.mappings={};this.computationContext=options.ractive;this.computations={};}
RootModel.prototype=Object.create(Model&&Model.prototype);RootModel.prototype.constructor=RootModel;RootModel.prototype.applyChanges=function applyChanges(){this._changeHash={};this.flush();return this._changeHash;};RootModel.prototype.compute=function compute(key,signature){var computation=new Computation(this,signature,key);this.computations[key]=computation;return computation;};RootModel.prototype.extendChildren=function extendChildren(fn){var mappings=this.mappings;Object.keys(mappings).forEach(function(key){fn(key,mappings[key]);});var computations=this.computations;Object.keys(computations).forEach(function(key){var computation=computations[key];if(!computation.isExpression){fn(key,computation);}});};RootModel.prototype.get=function get(shouldCapture){if(shouldCapture)capture(this);var result=extendObj({},this.value);this.extendChildren(function(key,model){result[key]=model.value;});return result;};RootModel.prototype.getKeypath=function getKeypath(){return'';};RootModel.prototype.getRactiveModel=function getRactiveModel(){return this.ractiveModel||(this.ractiveModel=new RactiveModel(this.ractive));};RootModel.prototype.getValueChildren=function getValueChildren(){var children=Model.prototype.getValueChildren.call(this,this.value);this.extendChildren(function(key,model){children.push(model);});return children;};RootModel.prototype.handleChange=function handleChange$1(){this.deps.forEach(handleChange);};RootModel.prototype.has=function has(key){if((key in this.mappings)||(key in this.computations))return true;var value=this.value;key=unescapeKey(key);if(hasProp$1.call(value,key))return true;var constructor=value.constructor;while(constructor!==Function&&constructor!==Array&&constructor!==Object){if(hasProp$1.call(constructor.prototype,key))return true;constructor=constructor.constructor;}
return false;};RootModel.prototype.joinKey=function joinKey(key){if(key==='@global')return GlobalModel$1;if(key==='@ractive')return this.getRactiveModel();return this.mappings.hasOwnProperty(key)?this.mappings[key]:this.computations.hasOwnProperty(key)?this.computations[key]:Model.prototype.joinKey.call(this,key);};RootModel.prototype.map=function map(localKey,origin){this.mappings[localKey]=origin;origin.register(this);};RootModel.prototype.set=function set(value){var wrapper=this.wrapper;if(wrapper){var shouldTeardown=!wrapper.reset||wrapper.reset(value)===false;if(shouldTeardown){wrapper.teardown();this.wrapper=null;this.value=value;this.adapt();}}else{this.value=value;this.adapt();}
this.deps.forEach(handleChange);this.children.forEach(mark);this.clearUnresolveds();};RootModel.prototype.retrieve=function retrieve(){return this.value;};RootModel.prototype.teardown=function teardown(){var this$1=this;var keys=Object.keys(this.mappings);var i=keys.length;while(i--){if(this$1.mappings[keys[i]])this$1.mappings[keys[i]].unregister(this$1);}
Model.prototype.teardown.call(this);};RootModel.prototype.update=function update(){};RootModel.prototype.updateFromBindings=function updateFromBindings(cascade){var this$1=this;Model.prototype.updateFromBindings.call(this,cascade);if(cascade){Object.keys(this.mappings).forEach(function(key){var model=this$1.mappings[key];model.updateFromBindings(cascade);});}};return RootModel;}(Model));function getComputationSignature(ractive,key,signature){var getter;var setter;var getterString;var getterUseStack;var setterString;if(typeof signature==='function'){getter=bind$1(signature,ractive);getterString=signature.toString();getterUseStack=true;}
if(typeof signature==='string'){getter=createFunctionFromString(signature,ractive);getterString=signature;}
if(typeof signature==='object'){if(typeof signature.get==='string'){getter=createFunctionFromString(signature.get,ractive);getterString=signature.get;}else if(typeof signature.get==='function'){getter=bind$1(signature.get,ractive);getterString=signature.get.toString();getterUseStack=true;}else{fatal('`%s` computation must have a `get()` method',key);}
if(typeof signature.set==='function'){setter=bind$1(signature.set,ractive);setterString=signature.set.toString();}}
return{getter:getter,setter:setter,getterString:getterString,setterString:setterString,getterUseStack:getterUseStack};}
var constructHook=new Hook('construct');var registryNames$1=['adaptors','components','decorators','easing','events','interpolators','partials','transitions'];var uid=0;function construct(ractive,options){if(Ractive.DEBUG)welcome();initialiseProperties(ractive);defineProperty(ractive,'data',{get:deprecateRactiveData});constructHook.fire(ractive,options);registryNames$1.forEach(function(name){ractive[name]=extendObj(create(ractive.constructor[name]||null),options[name]);});var viewmodel=new RootModel({adapt:getAdaptors(ractive,ractive.adapt,options),data:dataConfigurator.init(ractive.constructor,ractive,options),ractive:ractive});ractive.viewmodel=viewmodel;var computed=extendObj(create(ractive.constructor.prototype.computed),options.computed);for(var key in computed){var signature=getComputationSignature(ractive,key,computed[key]);viewmodel.compute(key,signature);}}
function combine$3(a,b){var c=a.slice();var i=b.length;while(i--){if(!~c.indexOf(b[i])){c.push(b[i]);}}
return c;}
function getAdaptors(ractive,protoAdapt,options){protoAdapt=protoAdapt.map(lookup);var adapt=ensureArray(options.adapt).map(lookup);adapt=combine$3(protoAdapt,adapt);var magic='magic'in options?options.magic:ractive.magic;var modifyArrays='modifyArrays'in options?options.modifyArrays:ractive.modifyArrays;if(magic){if(!magicSupported){throw new Error('Getters and setters (magic mode) are not supported in this browser');}
if(modifyArrays){adapt.push(magicArrayAdaptor);}
adapt.push(magicAdaptor$1);}
if(modifyArrays){adapt.push(arrayAdaptor);}
return adapt;function lookup(adaptor){if(typeof adaptor==='string'){adaptor=findInViewHierarchy('adaptors',ractive,adaptor);if(!adaptor){fatal(missingPlugin(adaptor,'adaptor'));}}
return adaptor;}}
function initialiseProperties(ractive){ractive._guid='r-'+uid++;ractive._subs=create(null);ractive._config={};ractive.nodes={};ractive.event=null;ractive._eventQueue=[];ractive._liveQueries=[];ractive._liveComponentQueries=[];ractive._observers=[];ractive._links={};if(!ractive.component){ractive.root=ractive;ractive.parent=ractive.container=null;}}
function deprecateRactiveData(){throw new Error('Using `ractive.data` is no longer supported - you must use the `ractive.get()` API instead');}
function getChildQueue(queue,ractive){return queue[ractive._guid]||(queue[ractive._guid]=[]);}
function fire(hookQueue,ractive){var childQueue=getChildQueue(hookQueue.queue,ractive);hookQueue.hook.fire(ractive);while(childQueue.length){fire(hookQueue,childQueue.shift());}
delete hookQueue.queue[ractive._guid];}
var HookQueue=function HookQueue(event){this.hook=new Hook(event);this.inProcess={};this.queue={};};HookQueue.prototype.begin=function begin(ractive){this.inProcess[ractive._guid]=true;};HookQueue.prototype.end=function end(ractive){var parent=ractive.parent;if(!parent||!this.inProcess[parent._guid]){fire(this,ractive);}
else{getChildQueue(this.queue,parent).push(ractive);}
delete this.inProcess[ractive._guid];};var configHook=new Hook('config');var initHook=new HookQueue('init');function initialise(ractive,userOptions,options){Object.keys(ractive.viewmodel.computations).forEach(function(key){var computation=ractive.viewmodel.computations[key];if(ractive.viewmodel.value.hasOwnProperty(key)){computation.set(ractive.viewmodel.value[key]);}});config.init(ractive.constructor,ractive,userOptions);configHook.fire(ractive);initHook.begin(ractive);var fragment;if(ractive.template){var cssIds;if(options.cssIds||ractive.cssId){cssIds=options.cssIds?options.cssIds.slice():[];if(ractive.cssId){cssIds.push(ractive.cssId);}}
ractive.fragment=fragment=new Fragment({owner:ractive,template:ractive.template,cssIds:cssIds}).bind(ractive.viewmodel);}
initHook.end(ractive);if(fragment){var el=getElement(ractive.el);if(el){var promise=ractive.render(el,ractive.append);if(Ractive.DEBUG_PROMISES){promise['catch'](function(err){warnOnceIfDebug('Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n  Ractive.DEBUG_PROMISES = false;');warnIfDebug('An error happened during rendering',{ractive:ractive});logIfDebug(err);throw err;});}}}}
function gatherRefs(fragment){var key={},index={};while(fragment){if(fragment.parent&&(fragment.parent.indexRef||fragment.parent.keyRef)){var ref=fragment.parent.indexRef;if(ref&&!(ref in index))index[ref]=fragment.index;ref=fragment.parent.keyRef;if(ref&&!(ref in key))key[ref]=fragment.key;}
if(fragment.componentParent&&!fragment.ractive.isolated){fragment=fragment.componentParent;}else{fragment=fragment.parent;}}
return{key:key,index:index};}
var eventPattern=/^event(?:\.(.+))?$/;var argumentsPattern=/^arguments\.(\d*)$/;var dollarArgsPattern=/^\$(\d*)$/;var EventDirective=function EventDirective(owner,event,template){this.owner=owner;this.event=event;this.template=template;this.ractive=owner.parentFragment.ractive;this.parentFragment=owner.parentFragment;this.context=null;this.passthru=false;this.method=null;this.resolvers=null;this.models=null;this.argsFn=null;this.action=null;this.args=null;};EventDirective.prototype.bind=function bind(){var this$1=this;this.context=this.parentFragment.findContext();var template=this.template;if(template.m){this.method=template.m;this.passthru=!!template.g;if(template.a){this.resolvers=[];this.models=template.a.r.map(function(ref,i){if(eventPattern.test(ref)){return{event:true,keys:ref.length>5?splitKeypathI(ref.slice(6)):[],unbind:noop};}
var argMatch=argumentsPattern.exec(ref);if(argMatch){return{argument:true,index:argMatch[1]};}
var dollarMatch=dollarArgsPattern.exec(ref);if(dollarMatch){return{argument:true,index:dollarMatch[1]-1};}
var resolver;var model=resolveReference(this$1.parentFragment,ref);if(!model){resolver=this$1.parentFragment.resolve(ref,function(model){this$1.models[i]=model;removeFromArray(this$1.resolvers,resolver);});this$1.resolvers.push(resolver);}
return model;});this.argsFn=getFunction(template.a.s,template.a.r.length);}}
else{this.action=typeof template==='string'?template:typeof template.n==='string'?template.n:new Fragment({owner:this,template:template.n});this.args=template.a?(typeof template.a==='string'?[template.a]:template.a):template.d?new Fragment({owner:this,template:template.d}):[];}
if(this.template.n&&typeof this.template.n!=='string')this.action.bind();if(this.template.d)this.args.bind();};EventDirective.prototype.bubble=function bubble(){if(!this.dirty){this.dirty=true;this.owner.bubble();}};EventDirective.prototype.fire=function fire(event,passedArgs){if(passedArgs===void 0)passedArgs=[];if(event){var refs=gatherRefs(this.parentFragment);event.keypath=this.context.getKeypath(this.ractive);event.rootpath=this.context.getKeypath();event.context=this.context.get();event.index=refs.index;event.key=refs.key;}
if(this.method){if(typeof this.ractive[this.method]!=='function'){throw new Error(("Attempted to call a non-existent method (\""+(this.method)+"\")"));}
var args;if(event)passedArgs.unshift(event);if(this.models){var values=this.models.map(function(model){if(!model)return undefined;if(model.event){var obj=event;var keys=model.keys.slice();while(keys.length)obj=obj[keys.shift()];return obj;}
if(model.argument){return passedArgs?passedArgs[model.index]:void 0;}
if(model.wrapper){return model.wrapper.value;}
return model.get();});args=this.argsFn.apply(null,values);}
if(this.passthru){args=args?args.concat(passedArgs):passedArgs;}
var ractive=this.ractive;var oldEvent=ractive.event;ractive.event=event;var result=ractive[this.method].apply(ractive,args);var original;if(result===false&&(original=event.original)){original.preventDefault&&original.preventDefault();original.stopPropagation&&original.stopPropagation();}
ractive.event=oldEvent;}
else{var action=this.action.toString();var args$1=this.template.d?this.args.getArgsList():this.args;if(passedArgs.length)args$1=args$1.concat(passedArgs);if(event)event.name=action;fireEvent(this.ractive,action,{event:event,args:args$1});}};EventDirective.prototype.rebind=function rebind(){this.unbind();this.bind();};EventDirective.prototype.render=function render(){this.event.listen(this);};EventDirective.prototype.unbind=function unbind$1(){var template=this.template;if(template.m){if(this.resolvers)this.resolvers.forEach(unbind);this.resolvers=[];this.models=null;}
else{if(this.action.unbind)this.action.unbind();if(this.args.unbind)this.args.unbind();}};EventDirective.prototype.unrender=function unrender(){this.event.unlisten();};EventDirective.prototype.update=function update(){if(this.method||!this.dirty)return;this.dirty=false;if(this.action.update)this.action.update();if(this.template.d)this.args.update();};var RactiveEvent=function RactiveEvent(ractive,name){this.ractive=ractive;this.name=name;this.handler=null;};RactiveEvent.prototype.listen=function listen(directive){var ractive=this.ractive;this.handler=ractive.on(this.name,function(){var event;if(arguments.length&&arguments[0]&&arguments[0].node){event=Array.prototype.shift.call(arguments);event.component=ractive;}
var args=Array.prototype.slice.call(arguments);directive.fire(event,args);return false;});};RactiveEvent.prototype.unlisten=function unlisten(){this.handler.cancel();};function updateLiveQueries(component){var instance=component.ractive;do{var liveQueries=instance._liveComponentQueries;var i=liveQueries.length;while(i--){var name=liveQueries[i];var query=liveQueries[("_"+name)];if(query.test(component)){query.add(component.instance);component.liveQueries.push(query);}}}while(instance=instance.parent);}
function removeFromLiveComponentQueries(component){var instance=component.ractive;while(instance){var query=instance._liveComponentQueries[("_"+(component.name))];if(query)query.remove(component);instance=instance.parent;}}
function makeDirty(query){query.makeDirty();}
var teardownHook=new Hook('teardown');var Component=(function(Item){function Component(options,ComponentConstructor){Item.call(this,options);this.type=COMPONENT;var instance=create(ComponentConstructor.prototype);this.instance=instance;this.name=options.template.e;this.parentFragment=options.parentFragment;this.complexMappings=[];this.liveQueries=[];if(instance.el){warnIfDebug(("The <"+(this.name)+"> component has a default 'el' property; it has been disregarded"));}
var partials=options.template.p||{};if(!('content'in partials))partials.content=options.template.f||[];this._partials=partials;this.yielders={};var fragment=options.parentFragment;var container;while(fragment){if(fragment.owner.type===YIELDER){container=fragment.owner.container;break;}
fragment=fragment.parent;}
instance.parent=this.parentFragment.ractive;instance.container=container||null;instance.root=instance.parent.root;instance.component=this;construct(this.instance,{partials:partials});instance._inlinePartials=partials;this.eventHandlers=[];if(this.template.v)this.setupEvents();}
Component.prototype=Object.create(Item&&Item.prototype);Component.prototype.constructor=Component;Component.prototype.bind=function bind$1(){var this$1=this;var viewmodel=this.instance.viewmodel;var childData=viewmodel.value;if(this.template.a){Object.keys(this.template.a).forEach(function(localKey){var template=this$1.template.a[localKey];var model;var fragment;if(template===0){viewmodel.joinKey(localKey).set(true);}
else if(typeof template==='string'){var parsed=parseJSON(template);viewmodel.joinKey(localKey).set(parsed?parsed.value:template);}
else if(isArray(template)){if(template.length===1&&template[0].t===INTERPOLATOR){model=resolve$1(this$1.parentFragment,template[0]);if(!model){warnOnceIfDebug(("The "+localKey+"='{{"+(template[0].r)+"}}' mapping is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity"),{ractive:this$1.instance});this$1.parentFragment.ractive.get(localKey);model=this$1.parentFragment.findContext().joinKey(localKey);}
viewmodel.map(localKey,model);if(model.get()===undefined&&localKey in childData){model.set(childData[localKey]);}}
else{fragment=new Fragment({owner:this$1,template:template}).bind();model=viewmodel.joinKey(localKey);model.set(fragment.valueOf());fragment.bubble=function(){Fragment.prototype.bubble.call(fragment);fragment.update();model.set(fragment.valueOf());};this$1.complexMappings.push(fragment);}}});}
initialise(this.instance,{partials:this._partials},{cssIds:this.parentFragment.cssIds});this.eventHandlers.forEach(bind);};Component.prototype.bubble=function bubble(){if(!this.dirty){this.dirty=true;this.parentFragment.bubble();}};Component.prototype.checkYielders=function checkYielders(){var this$1=this;Object.keys(this.yielders).forEach(function(name){if(this$1.yielders[name].length>1){runloop.end();throw new Error(("A component template can only have one {{yield"+(name?' '+name:'')+"}} declaration at a time"));}});};Component.prototype.detach=function detach(){return this.instance.fragment.detach();};Component.prototype.find=function find(selector){return this.instance.fragment.find(selector);};Component.prototype.findAll=function findAll(selector,query){this.instance.fragment.findAll(selector,query);};Component.prototype.findComponent=function findComponent(name){if(!name||this.name===name)return this.instance;if(this.instance.fragment){return this.instance.fragment.findComponent(name);}};Component.prototype.findAllComponents=function findAllComponents(name,query){if(query.test(this)){query.add(this.instance);if(query.live){this.liveQueries.push(query);}}
this.instance.fragment.findAllComponents(name,query);};Component.prototype.firstNode=function firstNode(skipParent){return this.instance.fragment.firstNode(skipParent);};Component.prototype.rebind=function rebind$1(){var this$1=this;this.complexMappings.forEach(rebind);this.liveQueries.forEach(makeDirty);var viewmodel=this.instance.viewmodel;viewmodel.mappings={};if(this.template.a){Object.keys(this.template.a).forEach(function(localKey){var template=this$1.template.a[localKey];var model;if(isArray(template)&&template.length===1&&template[0].t===INTERPOLATOR){model=resolve$1(this$1.parentFragment,template[0]);if(!model){warnOnceIfDebug(("The "+localKey+"='{{"+(template[0].r)+"}}' mapping is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity"),{ractive:this$1.instance});this$1.parentFragment.ractive.get(localKey);model=this$1.parentFragment.findContext().joinKey(localKey);}
viewmodel.map(localKey,model);}});}
this.instance.fragment.rebind(viewmodel);};Component.prototype.render=function render$1$$(target,occupants){render$1(this.instance,target,null,occupants);this.checkYielders();this.eventHandlers.forEach(render);updateLiveQueries(this);this.rendered=true;};Component.prototype.setupEvents=function setupEvents(){var this$1=this;var handlers=this.eventHandlers;Object.keys(this.template.v).forEach(function(key){var eventNames=key.split('-');var template=this$1.template.v[key];eventNames.forEach(function(eventName){var event=new RactiveEvent(this$1.instance,eventName);handlers.push(new EventDirective(this$1,event,template));});});};Component.prototype.toString=function toString(){return this.instance.toHTML();};Component.prototype.unbind=function unbind$1(){this.complexMappings.forEach(unbind);var instance=this.instance;instance.viewmodel.teardown();instance.fragment.unbind();instance._observers.forEach(cancel);removeFromLiveComponentQueries(this);if(instance.fragment.rendered&&instance.el.__ractive_instances__){removeFromArray(instance.el.__ractive_instances__,instance);}
Object.keys(instance._links).forEach(function(k){return instance._links[k].unlink();});teardownHook.fire(instance);};Component.prototype.unrender=function unrender$1(shouldDestroy){var this$1=this;this.shouldDestroy=shouldDestroy;this.instance.unrender();this.eventHandlers.forEach(unrender);this.liveQueries.forEach(function(query){return query.remove(this$1.instance);});};Component.prototype.update=function update$1(){this.dirty=false;this.instance.fragment.update();this.checkYielders();this.eventHandlers.forEach(update);this.complexMappings.forEach(update);};return Component;}(Item));var Doctype=(function(Item){function Doctype(){Item.apply(this,arguments);}
Doctype.prototype=Object.create(Item&&Item.prototype);Doctype.prototype.constructor=Doctype;Doctype.prototype.bind=function bind(){};Doctype.prototype.render=function render(){};Doctype.prototype.teardown=function teardown(){};Doctype.prototype.toString=function toString(){return'<!DOCTYPE'+this.template.a+'>';};Doctype.prototype.unbind=function unbind(){};Doctype.prototype.unrender=function unrender(){};return Doctype;}(Item));function camelCase(hyphenatedStr){return hyphenatedStr.replace(/-([a-zA-Z])/g,function(match,$1){return $1.toUpperCase();});}
var space=/\s+/;var specials$1={'float':'cssFloat'};var remove=/\/\*(?:[\s\S]*?)\*\//g;var escape=/url\(\s*(['"])(?:\\[\s\S]|(?!\1).)*\1\s*\)|url\((?:\\[\s\S]|[^)])*\)|(['"])(?:\\[\s\S]|(?!\1).)*\2/gi;var value=/\0(\d+)/g;function readStyle(css){var values=[];if(typeof css!=='string')return{};return css.replace(escape,function(match){return("\u0000"+(values.push(match)-1));}).replace(remove,'').split(';').filter(function(rule){return!!rule.trim();}).map(function(rule){return rule.replace(value,function(match,n){return values[n];});}).reduce(function(rules,rule){var i=rule.indexOf(':');var name=camelCase(rule.substr(0,i).trim());rules[specials$1[name]||name]=rule.substr(i+1).trim();return rules;},{});}
function readClass(str){var list=str.split(space);var i=list.length;while(i--){if(!list[i])list.splice(i,1);}
return list;}
var textTypes=[undefined,'text','search','url','email','hidden','password','search','reset','submit'];function getUpdateDelegate(attribute){var element=attribute.element,name=attribute.name;if(name==='id')return updateId;if(name==='value'){if(element.name==='select'&&name==='value'){return element.getAttribute('multiple')?updateMultipleSelectValue:updateSelectValue;}
if(element.name==='textarea')return updateStringValue;if(element.getAttribute('contenteditable')!=null)return updateContentEditableValue;if(element.name==='input'){var type=element.getAttribute('type');if(type==='file')return noop;if(type==='radio'&&element.binding&&element.binding.attribute.name==='name')return updateRadioValue;if(~textTypes.indexOf(type))return updateStringValue;}
return updateValue;}
var node=element.node;if(attribute.isTwoway&&name==='name'){if(node.type==='radio')return updateRadioName;if(node.type==='checkbox')return updateCheckboxName;}
if(name==='style')return updateStyleAttribute;if(name.indexOf('style-')===0)return updateInlineStyle;if(name==='class'&&(!node.namespaceURI||node.namespaceURI===html))return updateClassName;if(name.indexOf('class-')===0)return updateInlineClass;if(attribute.isBoolean)return updateBoolean;if(attribute.namespace&&attribute.namespace!==attribute.node.namespaceURI)return updateNamespacedAttribute;return updateAttribute;}
function updateId(){var ref=this,node=ref.node;var value=this.getValue();delete this.ractive.nodes[node.id];this.ractive.nodes[value]=node;node.id=value;}
function updateMultipleSelectValue(){var value=this.getValue();if(!isArray(value))value=[value];var options=this.node.options;var i=options.length;while(i--){var option=options[i];var optionValue=option._ractive?option._ractive.value:option.value;option.selected=arrayContains(value,optionValue);}}
function updateSelectValue(){var value=this.getValue();if(!this.locked){this.node._ractive.value=value;var options=this.node.options;var i=options.length;while(i--){var option=options[i];var optionValue=option._ractive?option._ractive.value:option.value;if(optionValue==value){option.selected=true;return;}}
this.node.selectedIndex=-1;}}
function updateContentEditableValue(){var value=this.getValue();if(!this.locked){this.node.innerHTML=value===undefined?'':value;}}
function updateRadioValue(){var node=this.node;var wasChecked=node.checked;var value=this.getValue();node.value=this.node._ractive.value=value;node.checked=value===this.element.getAttribute('name');if(wasChecked&&!node.checked&&this.element.binding&&this.element.binding.rendered){this.element.binding.group.model.set(this.element.binding.group.getValue());}}
function updateValue(){if(!this.locked){var value=this.getValue();this.node.value=this.node._ractive.value=value;this.node.setAttribute('value',value);}}
function updateStringValue(){if(!this.locked){var value=this.getValue();this.node._ractive.value=value;this.node.value=safeToStringValue(value);this.node.setAttribute('value',safeToStringValue(value));}}
function updateRadioName(){this.node.checked=(this.getValue()==this.node._ractive.value);}
function updateCheckboxName(){var ref=this,element=ref.element,node=ref.node;var binding=element.binding;var value=this.getValue();var valueAttribute=element.getAttribute('value');if(!isArray(value)){binding.isChecked=node.checked=(value==valueAttribute);}else{var i=value.length;while(i--){if(valueAttribute==value[i]){binding.isChecked=node.checked=true;return;}}
binding.isChecked=node.checked=false;}}
function updateStyleAttribute(){var props=readStyle(this.getValue()||'');var style=this.node.style;var keys=Object.keys(props);var prev=this.previous||[];var i=0;while(i<keys.length){if(keys[i]in style)style[keys[i]]=props[keys[i]];i++;}
i=prev.length;while(i--){if(!~keys.indexOf(prev[i])&&prev[i]in style)style[prev[i]]='';}
this.previous=keys;}
var camelize=/(-.)/g;function updateInlineStyle(){if(!this.styleName){this.styleName=this.name.substr(6).replace(camelize,function(s){return s.charAt(1).toUpperCase();});}
this.node.style[this.styleName]=this.getValue();}
function updateClassName(){var value=readClass(safeToStringValue(this.getValue()));var attr=readClass(this.node.className);var prev=this.previous||[];var i=0;while(i<value.length){if(!~attr.indexOf(value[i]))attr.push(value[i]);i++;}
i=prev.length;while(i--){if(!~value.indexOf(prev[i])){var idx=attr.indexOf(prev[i]);if(~idx)attr.splice(idx,1);}}
this.node.className=attr.join(' ');this.previous=value;}
function updateInlineClass(){var name=this.name.substr(6);var attr=readClass(this.node.className);var value=this.getValue();if(value&&!~attr.indexOf(name))attr.push(name);else if(!value&&~attr.indexOf(name))attr.splice(attr.indexOf(name),1);this.node.className=attr.join(' ');}
function updateBoolean(){if(!this.locked){if(this.useProperty){this.node[this.propertyName]=this.getValue();}else{if(this.getValue()){this.node.setAttribute(this.propertyName,'');}else{this.node.removeAttribute(this.propertyName);}}}}
function updateAttribute(){this.node.setAttribute(this.name,safeToStringValue(this.getString()));}
function updateNamespacedAttribute(){this.node.setAttributeNS(this.namespace,this.name.slice(this.name.indexOf(':')+1),safeToStringValue(this.getString()));}
var propertyNames={'accept-charset':'acceptCharset',accesskey:'accessKey',bgcolor:'bgColor','class':'className',codebase:'codeBase',colspan:'colSpan',contenteditable:'contentEditable',datetime:'dateTime',dirname:'dirName','for':'htmlFor','http-equiv':'httpEquiv',ismap:'isMap',maxlength:'maxLength',novalidate:'noValidate',pubdate:'pubDate',readonly:'readOnly',rowspan:'rowSpan',tabindex:'tabIndex',usemap:'useMap'};function lookupNamespace(node,prefix){var qualified="xmlns:"+prefix;while(node){if(node.hasAttribute(qualified))return node.getAttribute(qualified);node=node.parentNode;}
return namespaces[prefix];}
var Attribute=(function(Item){function Attribute(options){Item.call(this,options);this.name=options.name;this.namespace=null;this.element=options.element;this.parentFragment=options.element.parentFragment;this.ractive=this.parentFragment.ractive;this.rendered=false;this.updateDelegate=null;this.fragment=null;this.value=null;if(!isArray(options.template)){this.value=options.template;if(this.value===0){this.value='';}}else{this.fragment=new Fragment({owner:this,template:options.template});}
this.interpolator=this.fragment&&this.fragment.items.length===1&&this.fragment.items[0].type===INTERPOLATOR&&this.fragment.items[0];}
Attribute.prototype=Object.create(Item&&Item.prototype);Attribute.prototype.constructor=Attribute;Attribute.prototype.bind=function bind(){if(this.fragment){this.fragment.bind();}};Attribute.prototype.bubble=function bubble(){if(!this.dirty){this.element.bubble();this.dirty=true;}};Attribute.prototype.getString=function getString(){return this.fragment?this.fragment.toString():this.value!=null?''+this.value:'';};Attribute.prototype.getValue=function getValue(){return this.fragment?this.fragment.valueOf():booleanAttributes.test(this.name)?true:this.value;};Attribute.prototype.rebind=function rebind(){if(this.fragment)this.fragment.rebind();};Attribute.prototype.render=function render(){var node=this.element.node;this.node=node;if(!node.namespaceURI||node.namespaceURI===namespaces.html){this.propertyName=propertyNames[this.name]||this.name;if(node[this.propertyName]!==undefined){this.useProperty=true;}
if(booleanAttributes.test(this.name)||this.isTwoway){this.isBoolean=true;}
if(this.propertyName==='value'){node._ractive.value=this.value;}}
if(node.namespaceURI){var index=this.name.indexOf(':');if(index!==-1){this.namespace=lookupNamespace(node,this.name.slice(0,index));}else{this.namespace=node.namespaceURI;}}
this.rendered=true;this.updateDelegate=getUpdateDelegate(this);this.updateDelegate();};Attribute.prototype.toString=function toString(){var value=this.getValue();if(this.name==='value'&&(this.element.getAttribute('contenteditable')!==undefined||(this.element.name==='select'||this.element.name==='textarea'))){return;}
if(this.name==='name'&&this.element.name==='input'&&this.interpolator&&this.element.getAttribute('type')==='radio'){return("name=\"{{"+(this.interpolator.model.getKeypath())+"}}\"");}
if(booleanAttributes.test(this.name))return value?this.name:'';if(value==null)return'';var str=safeToStringValue(this.getString()).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');return str?(""+(this.name)+"=\""+str+"\""):this.name;};Attribute.prototype.unbind=function unbind(){if(this.fragment)this.fragment.unbind();};Attribute.prototype.update=function update(){if(this.dirty){this.dirty=false;if(this.fragment)this.fragment.update();if(this.rendered)this.updateDelegate();}};return Attribute;}(Item));var div$1=doc?createElement('div'):null;var ConditionalAttribute=(function(Item){function ConditionalAttribute(options){Item.call(this,options);this.attributes=[];this.owner=options.owner;this.fragment=new Fragment({ractive:this.ractive,owner:this,template:[this.template]});this.dirty=false;}
ConditionalAttribute.prototype=Object.create(Item&&Item.prototype);ConditionalAttribute.prototype.constructor=ConditionalAttribute;ConditionalAttribute.prototype.bind=function bind(){this.fragment.bind();};ConditionalAttribute.prototype.bubble=function bubble(){if(!this.dirty){this.dirty=true;this.owner.bubble();}};ConditionalAttribute.prototype.rebind=function rebind(){this.fragment.rebind();};ConditionalAttribute.prototype.render=function render(){this.node=this.owner.node;this.isSvg=this.node.namespaceURI===svg$1;this.rendered=true;this.dirty=true;this.update();};ConditionalAttribute.prototype.toString=function toString(){return this.fragment.toString();};ConditionalAttribute.prototype.unbind=function unbind(){this.fragment.unbind();};ConditionalAttribute.prototype.unrender=function unrender(){this.rendered=false;};ConditionalAttribute.prototype.update=function update(){var this$1=this;var str;var attrs;if(this.dirty){this.dirty=false;this.fragment.update();if(this.rendered){str=this.fragment.toString();attrs=parseAttributes(str,this.isSvg);this.attributes.filter(function(a){return notIn(attrs,a);}).forEach(function(a){this$1.node.removeAttribute(a.name);});attrs.forEach(function(a){this$1.node.setAttribute(a.name,a.value);});this.attributes=attrs;}}};return ConditionalAttribute;}(Item));function parseAttributes(str,isSvg){var tagName=isSvg?'svg':'div';return str?(div$1.innerHTML="<"+tagName+" "+str+"></"+tagName+">")&&toArray(div$1.childNodes[0].attributes):[];}
function notIn(haystack,needle){var i=haystack.length;while(i--){if(haystack[i].name===needle.name){return false;}}
return true;}
var missingDecorator={update:noop,teardown:noop};var Decorator=function Decorator(owner,template){this.owner=owner;this.template=template;this.parentFragment=owner.parentFragment;this.ractive=owner.ractive;this.dynamicName=typeof template.n==='object';this.dynamicArgs=!!template.d;if(this.dynamicName){this.nameFragment=new Fragment({owner:this,template:template.n});}else{this.name=template.n||template;}
if(this.dynamicArgs){this.argsFragment=new Fragment({owner:this,template:template.d});}else{this.args=template.a||[];}
this.node=null;this.intermediary=null;};Decorator.prototype.bind=function bind(){if(this.dynamicName){this.nameFragment.bind();this.name=this.nameFragment.toString();}
if(this.dynamicArgs)this.argsFragment.bind();};Decorator.prototype.bubble=function bubble(){if(!this.dirty){this.dirty=true;this.owner.bubble();}};Decorator.prototype.rebind=function rebind(){if(this.dynamicName)this.nameFragment.rebind();if(this.dynamicArgs)this.argsFragment.rebind();};Decorator.prototype.render=function render(){var fn=findInViewHierarchy('decorators',this.ractive,this.name);if(!fn){warnOnce(missingPlugin(this.name,'decorator'));this.intermediary=missingDecorator;return;}
this.node=this.owner.node;var args=this.dynamicArgs?this.argsFragment.getArgsList():this.args;this.intermediary=fn.apply(this.ractive,[this.node].concat(args));if(!this.intermediary||!this.intermediary.teardown){throw new Error(("The '"+(this.name)+"' decorator must return an object with a teardown method"));}};Decorator.prototype.unbind=function unbind(){if(this.dynamicName)this.nameFragment.unbind();if(this.dynamicArgs)this.argsFragment.unbind();};Decorator.prototype.unrender=function unrender(){if(this.intermediary)this.intermediary.teardown();};Decorator.prototype.update=function update(){if(!this.dirty)return;this.dirty=false;var nameChanged=false;if(this.dynamicName&&this.nameFragment.dirty){var name=this.nameFragment.toString();nameChanged=name!==this.name;this.name=name;}
if(this.intermediary){if(nameChanged||!this.intermediary.update){this.unrender();this.render();}
else{if(this.dynamicArgs){if(this.argsFragment.dirty){var args=this.argsFragment.getArgsList();this.intermediary.update.apply(this.ractive,args);}}
else{this.intermediary.update.apply(this.ractive,this.args);}}}
if(this.dynamicName&&this.nameFragment.dirty){this.nameFragment.update();}
if(this.dynamicArgs&&this.argsFragment.dirty){this.argsFragment.update();}};var DOMEvent=function DOMEvent(name,owner){if(name.indexOf('*')!==-1){fatal(("Only component proxy-events may contain \"*\" wildcards, <"+(owner.name)+" on-"+name+"=\"...\"/> is not valid"));}
this.name=name;this.owner=owner;this.node=null;this.handler=null;};DOMEvent.prototype.listen=function listen(directive){var node=this.node=this.owner.node;var name=this.name;if(!(("on"+name)in node)){warnOnce(missingPlugin(name,'events'));}
node.addEventListener(name,this.handler=function(event){directive.fire({node:node,original:event});},false);};DOMEvent.prototype.unlisten=function unlisten(){this.node.removeEventListener(this.name,this.handler,false);};var CustomEvent=function CustomEvent(eventPlugin,owner){this.eventPlugin=eventPlugin;this.owner=owner;this.handler=null;};CustomEvent.prototype.listen=function listen(directive){var node=this.owner.node;this.handler=this.eventPlugin(node,function(event){if(event===void 0)event={};event.node=event.node||node;directive.fire(event);});};CustomEvent.prototype.unlisten=function unlisten(){this.handler.teardown();};var prefix;if(!isClient){prefix=null;}else{var prefixCache={};var testStyle=createElement('div').style;prefix=function(prop){prop=camelCase(prop);if(!prefixCache[prop]){if(testStyle[prop]!==undefined){prefixCache[prop]=prop;}
else{var capped=prop.charAt(0).toUpperCase()+prop.substring(1);var i=vendors.length;while(i--){var vendor=vendors[i];if(testStyle[vendor+capped]!==undefined){prefixCache[prop]=vendor+capped;break;}}}}
return prefixCache[prop];};}
var prefix$1=prefix;var visible;var hidden='hidden';if(doc){var prefix$2;if(hidden in doc){prefix$2='';}else{var i$1=vendors.length;while(i$1--){var vendor=vendors[i$1];hidden=vendor+'Hidden';if(hidden in doc){prefix$2=vendor;break;}}}
if(prefix$2!==undefined){doc.addEventListener(prefix$2+'visibilitychange',onChange);onChange();}else{if('onfocusout'in doc){doc.addEventListener('focusout',onHide);doc.addEventListener('focusin',onShow);}
else{win.addEventListener('pagehide',onHide);win.addEventListener('blur',onHide);win.addEventListener('pageshow',onShow);win.addEventListener('focus',onShow);}
visible=true;}}
function onChange(){visible=!doc[hidden];}
function onHide(){visible=false;}
function onShow(){visible=true;}
var unprefixPattern=new RegExp('^-(?:'+vendors.join('|')+')-');function unprefix(prop){return prop.replace(unprefixPattern,'');}
var vendorPattern=new RegExp('^(?:'+vendors.join('|')+')([A-Z])');function hyphenate(str){if(!str)return'';if(vendorPattern.test(str))str='-'+str;return str.replace(/[A-Z]/g,function(match){return'-'+match.toLowerCase();});}
var createTransitions;if(!isClient){createTransitions=null;}else{var testStyle$1=createElement('div').style;var linear$1=function(x){return x;};var canUseCssTransitions={};var cannotUseCssTransitions={};var TRANSITION;var TRANSITIONEND;var CSS_TRANSITIONS_ENABLED;var TRANSITION_DURATION;var TRANSITION_PROPERTY;var TRANSITION_TIMING_FUNCTION;if(testStyle$1.transition!==undefined){TRANSITION='transition';TRANSITIONEND='transitionend';CSS_TRANSITIONS_ENABLED=true;}else if(testStyle$1.webkitTransition!==undefined){TRANSITION='webkitTransition';TRANSITIONEND='webkitTransitionEnd';CSS_TRANSITIONS_ENABLED=true;}else{CSS_TRANSITIONS_ENABLED=false;}
if(TRANSITION){TRANSITION_DURATION=TRANSITION+'Duration';TRANSITION_PROPERTY=TRANSITION+'Property';TRANSITION_TIMING_FUNCTION=TRANSITION+'TimingFunction';}
createTransitions=function(t,to,options,changedProperties,resolve){setTimeout(function(){var jsTransitionsComplete;var cssTransitionsComplete;function checkComplete(){if(jsTransitionsComplete&&cssTransitionsComplete){t.ractive.fire(t.name+':end',t.node,t.isIntro);resolve();}}
var hashPrefix=(t.node.namespaceURI||'')+t.node.tagName;var style=t.node.style;var previous={property:style[TRANSITION_PROPERTY],timing:style[TRANSITION_TIMING_FUNCTION],duration:style[TRANSITION_DURATION]};style[TRANSITION_PROPERTY]=changedProperties.map(prefix$1).map(hyphenate).join(',');style[TRANSITION_TIMING_FUNCTION]=hyphenate(options.easing||'linear');style[TRANSITION_DURATION]=(options.duration / 1000)+'s';function transitionEndHandler(event){var index=changedProperties.indexOf(camelCase(unprefix(event.propertyName)));if(index!==-1){changedProperties.splice(index,1);}
if(changedProperties.length){return;}
style[TRANSITION_PROPERTY]=previous.property;style[TRANSITION_TIMING_FUNCTION]=previous.duration;style[TRANSITION_DURATION]=previous.timing;t.node.removeEventListener(TRANSITIONEND,transitionEndHandler,false);cssTransitionsComplete=true;checkComplete();}
t.node.addEventListener(TRANSITIONEND,transitionEndHandler,false);setTimeout(function(){var i=changedProperties.length;var hash;var originalValue;var index;var propertiesToTransitionInJs=[];var prop;var suffix;var interpolator;while(i--){prop=changedProperties[i];hash=hashPrefix+prop;if(CSS_TRANSITIONS_ENABLED&&!cannotUseCssTransitions[hash]){style[prefix$1(prop)]=to[prop];if(!canUseCssTransitions[hash]){originalValue=t.getStyle(prop);canUseCssTransitions[hash]=(t.getStyle(prop)!=to[prop]);cannotUseCssTransitions[hash]=!canUseCssTransitions[hash];if(cannotUseCssTransitions[hash]){style[prefix$1(prop)]=originalValue;}}}
if(!CSS_TRANSITIONS_ENABLED||cannotUseCssTransitions[hash]){if(originalValue===undefined){originalValue=t.getStyle(prop);}
index=changedProperties.indexOf(prop);if(index===-1){warnIfDebug('Something very strange happened with transitions. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!',{node:t.node});}else{changedProperties.splice(index,1);}
suffix=/[^\d]*$/.exec(to[prop])[0];interpolator=interpolate(parseFloat(originalValue),parseFloat(to[prop]))||(function(){return to[prop];});propertiesToTransitionInJs.push({name:prefix$1(prop),interpolator:interpolator,suffix:suffix});}}
if(propertiesToTransitionInJs.length){var easing;if(typeof options.easing==='string'){easing=t.ractive.easing[options.easing];if(!easing){warnOnceIfDebug(missingPlugin(options.easing,'easing'));easing=linear$1;}}else if(typeof options.easing==='function'){easing=options.easing;}else{easing=linear$1;}
new Ticker({duration:options.duration,easing:easing,step:function(pos){var i=propertiesToTransitionInJs.length;while(i--){var prop=propertiesToTransitionInJs[i];t.node.style[prop.name]=prop.interpolator(pos)+prop.suffix;}},complete:function(){jsTransitionsComplete=true;checkComplete();}});}else{jsTransitionsComplete=true;}
if(!changedProperties.length){t.node.removeEventListener(TRANSITIONEND,transitionEndHandler,false);cssTransitionsComplete=true;checkComplete();}},0);},options.delay||0);};}
var createTransitions$1=createTransitions;function resetStyle(node,style){if(style){node.setAttribute('style',style);}else{node.getAttribute('style');node.removeAttribute('style');}}
var getComputedStyle=win&&(win.getComputedStyle||legacy.getComputedStyle);var resolved=Promise$1.resolve();var Transition=function Transition(ractive,node,name,params,eventName){this.ractive=ractive;this.node=node;this.name=name;this.params=params;this.eventName=eventName;this.isIntro=eventName!=='outro';if(typeof name==='function'){this._fn=name;}
else{this._fn=findInViewHierarchy('transitions',ractive,name);if(!this._fn){warnOnceIfDebug(missingPlugin(name,'transition'),{ractive:ractive});}}};Transition.prototype.animateStyle=function animateStyle(style,value,options){var this$1=this;if(arguments.length===4){throw new Error('t.animateStyle() returns a promise - use .then() instead of passing a callback');}
if(!visible){this.setStyle(style,value);return resolved;}
var to;if(typeof style==='string'){to={};to[style]=value;}else{to=style;options=value;}
if(!options){warnOnceIfDebug('The "%s" transition does not supply an options object to `t.animateStyle()`. This will break in a future version of Ractive. For more info see https://github.com/RactiveJS/Ractive/issues/340',this.name);options=this;}
return new Promise$1(function(fulfil){if(!options.duration){this$1.setStyle(to);fulfil();return;}
var propertyNames=Object.keys(to);var changedProperties=[];var computedStyle=getComputedStyle(this$1.node);var i=propertyNames.length;while(i--){var prop=propertyNames[i];var current=computedStyle[prefix$1(prop)];if(current==='0px')current=0;if(current!=to[prop]){changedProperties.push(prop);this$1.node.style[prefix$1(prop)]=current;}}
if(!changedProperties.length){fulfil();return;}
createTransitions$1(this$1,to,options,changedProperties,fulfil);});};Transition.prototype.getStyle=function getStyle(props){var computedStyle=getComputedStyle(this.node);if(typeof props==='string'){var value=computedStyle[prefix$1(props)];return value==='0px'?0:value;}
if(!isArray(props)){throw new Error('Transition$getStyle must be passed a string, or an array of strings representing CSS properties');}
var styles={};var i=props.length;while(i--){var prop=props[i];var value$1=computedStyle[prefix$1(prop)];if(value$1==='0px')value$1=0;styles[prop]=value$1;}
return styles;};Transition.prototype.processParams=function processParams(params,defaults){if(typeof params==='number'){params={duration:params};}
else if(typeof params==='string'){if(params==='slow'){params={duration:600};}else if(params==='fast'){params={duration:200};}else{params={duration:400};}}else if(!params){params={};}
return extendObj({},defaults,params);};Transition.prototype.setStyle=function setStyle(style,value){if(typeof style==='string'){this.node.style[prefix$1(style)]=value;}
else{var prop;for(prop in style){if(style.hasOwnProperty(prop)){this.node.style[prefix$1(prop)]=style[prop];}}}
return this;};Transition.prototype.start=function start(){var this$1=this;var node=this.node;var originalStyle=node.getAttribute('style');var completed;this.complete=function(noReset){if(completed){return;}
if(!noReset&&this$1.eventName==='intro'){resetStyle(node,originalStyle);}
this$1._manager.remove(this$1);completed=true;};if(!this._fn){this.complete();return;}
var promise=this._fn.apply(this.ractive,[this].concat(this.params));if(promise)promise.then(this.complete);};function updateLiveQueries$1(element){var node=element.node;var instance=element.ractive;do{var liveQueries=instance._liveQueries;var i=liveQueries.length;while(i--){var selector=liveQueries[i];var query=liveQueries[("_"+selector)];if(query.test(node)){query.add(node);element.liveQueries.push(query);}}}while(instance=instance.parent);}
function findParentForm(element){while(element=element.parent){if(element.name==='form'){return element;}}}
function warnAboutAmbiguity(description,ractive){warnOnceIfDebug(("The "+description+" being used for two-way binding is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity"),{ractive:ractive});}
var Binding=function Binding(element,name){if(name===void 0)name='value';this.element=element;this.ractive=element.ractive;this.attribute=element.attributeByName[name];var interpolator=this.attribute.interpolator;interpolator.twowayBinding=this;var model=interpolator.model;if(!model){interpolator.resolver.forceResolution();model=interpolator.model;warnAboutAmbiguity(("'"+(interpolator.template.r)+"' reference"),this.ractive);}
else if(model.isUnresolved){model.forceResolution();warnAboutAmbiguity('expression',this.ractive);}
else if(model.isReadonly){var keypath=model.getKeypath().replace(/^@/,'');warnOnceIfDebug(("Cannot use two-way binding on <"+(element.name)+"> element: "+keypath+" is read-only. To suppress this warning use <"+(element.name)+" twoway='false'...>"),{ractive:this.ractive});return false;}
this.attribute.isTwoway=true;this.model=model;var value=model.get();this.wasUndefined=value===undefined;if(value===undefined&&this.getInitialValue){value=this.getInitialValue();model.set(value);}
var parentForm=findParentForm(element);if(parentForm){this.resetValue=value;parentForm.formBindings.push(this);}};Binding.prototype.bind=function bind(){this.model.registerTwowayBinding(this);};Binding.prototype.handleChange=function handleChange(){var this$1=this;runloop.start(this.root);this.attribute.locked=true;this.model.set(this.getValue());runloop.scheduleTask(function(){return this$1.attribute.locked=false;});runloop.end();};Binding.prototype.rebind=function rebind(){this.unbind();this.model=this.attribute.interpolator.model;this.bind();};Binding.prototype.render=function render(){this.node=this.element.node;this.node._ractive.binding=this;this.rendered=true;};Binding.prototype.setFromNode=function setFromNode(node){this.model.set(node.value);};Binding.prototype.unbind=function unbind(){this.model.unregisterTwowayBinding(this);};Binding.prototype.unrender=function unrender(){};function handleDomEvent(){this._ractive.binding.handleChange();}
var CheckboxBinding=(function(Binding){function CheckboxBinding(element){Binding.call(this,element,'checked');}
CheckboxBinding.prototype=Object.create(Binding&&Binding.prototype);CheckboxBinding.prototype.constructor=CheckboxBinding;CheckboxBinding.prototype.render=function render(){Binding.prototype.render.call(this);this.node.addEventListener('change',handleDomEvent,false);if(this.node.attachEvent){this.node.addEventListener('click',handleDomEvent,false);}};CheckboxBinding.prototype.unrender=function unrender(){this.node.removeEventListener('change',handleDomEvent,false);this.node.removeEventListener('click',handleDomEvent,false);};CheckboxBinding.prototype.getInitialValue=function getInitialValue(){return!!this.element.getAttribute('checked');};CheckboxBinding.prototype.getValue=function getValue(){return this.node.checked;};CheckboxBinding.prototype.setFromNode=function setFromNode(node){this.model.set(node.checked);};return CheckboxBinding;}(Binding));function getBindingGroup(group,model,getValue){var hash=""+group+"-bindingGroup";return model[hash]||(model[hash]=new BindingGroup(hash,model,getValue));}
var BindingGroup=function BindingGroup(hash,model,getValue){var this$1=this;this.model=model;this.hash=hash;this.getValue=function(){this$1.value=getValue.call(this$1);return this$1.value;};this.bindings=[];};BindingGroup.prototype.add=function add(binding){this.bindings.push(binding);};BindingGroup.prototype.bind=function bind(){this.value=this.model.get();this.model.registerTwowayBinding(this);this.bound=true;};BindingGroup.prototype.remove=function remove(binding){removeFromArray(this.bindings,binding);if(!this.bindings.length){this.unbind();}};BindingGroup.prototype.unbind=function unbind(){this.model.unregisterTwowayBinding(this);this.bound=false;delete this.model[this.hash];};var push$1=[].push;function getValue$1(){var all=this.bindings.filter(function(b){return b.node&&b.node.checked;}).map(function(b){return b.element.getAttribute('value');});var res=[];all.forEach(function(v){if(!arrayContains(res,v))res.push(v);});return res;}
var CheckboxNameBinding=(function(Binding){function CheckboxNameBinding(element){Binding.call(this,element,'name');this.checkboxName=true;this.group=getBindingGroup('checkboxes',this.model,getValue$1);this.group.add(this);if(this.noInitialValue){this.group.noInitialValue=true;}
if(this.group.noInitialValue&&this.element.getAttribute('checked')){var existingValue=this.model.get();var bindingValue=this.element.getAttribute('value');if(!arrayContains(existingValue,bindingValue)){push$1.call(existingValue,bindingValue);}}}
CheckboxNameBinding.prototype=Object.create(Binding&&Binding.prototype);CheckboxNameBinding.prototype.constructor=CheckboxNameBinding;CheckboxNameBinding.prototype.bind=function bind(){if(!this.group.bound){this.group.bind();}};CheckboxNameBinding.prototype.changed=function changed(){var wasChecked=!!this.isChecked;this.isChecked=this.node.checked;return this.isChecked===wasChecked;};CheckboxNameBinding.prototype.getInitialValue=function getInitialValue(){this.noInitialValue=true;return[];};CheckboxNameBinding.prototype.getValue=function getValue$1(){return this.group.value;};CheckboxNameBinding.prototype.handleChange=function handleChange(){this.isChecked=this.element.node.checked;this.group.value=this.model.get();var value=this.element.getAttribute('value');if(this.isChecked&&!arrayContains(this.group.value,value)){this.group.value.push(value);}else if(!this.isChecked&&arrayContains(this.group.value,value)){removeFromArray(this.group.value,value);}
Binding.prototype.handleChange.call(this);};CheckboxNameBinding.prototype.render=function render(){Binding.prototype.render.call(this);var node=this.node;var existingValue=this.model.get();var bindingValue=this.element.getAttribute('value');if(isArray(existingValue)){this.isChecked=arrayContains(existingValue,bindingValue);}else{this.isChecked=existingValue==bindingValue;}
node.name='{{'+this.model.getKeypath()+'}}';node.checked=this.isChecked;node.addEventListener('change',handleDomEvent,false);if(node.attachEvent){node.addEventListener('click',handleDomEvent,false);}};CheckboxNameBinding.prototype.setFromNode=function setFromNode(node){this.group.bindings.forEach(function(binding){return binding.wasUndefined=true;});if(node.checked){var valueSoFar=this.group.getValue();valueSoFar.push(this.element.getAttribute('value'));this.group.model.set(valueSoFar);}};CheckboxNameBinding.prototype.unbind=function unbind(){this.group.remove(this);};CheckboxNameBinding.prototype.unrender=function unrender(){var node=this.element.node;node.removeEventListener('change',handleDomEvent,false);node.removeEventListener('click',handleDomEvent,false);};return CheckboxNameBinding;}(Binding));var ContentEditableBinding=(function(Binding){function ContentEditableBinding(){Binding.apply(this,arguments);}
ContentEditableBinding.prototype=Object.create(Binding&&Binding.prototype);ContentEditableBinding.prototype.constructor=ContentEditableBinding;ContentEditableBinding.prototype.getInitialValue=function getInitialValue(){return this.element.fragment?this.element.fragment.toString():'';};ContentEditableBinding.prototype.getValue=function getValue(){return this.element.node.innerHTML;};ContentEditableBinding.prototype.render=function render(){Binding.prototype.render.call(this);var node=this.node;node.addEventListener('change',handleDomEvent,false);node.addEventListener('blur',handleDomEvent,false);if(!this.ractive.lazy){node.addEventListener('input',handleDomEvent,false);if(node.attachEvent){node.addEventListener('keyup',handleDomEvent,false);}}};ContentEditableBinding.prototype.setFromNode=function setFromNode(node){this.model.set(node.innerHTML);};ContentEditableBinding.prototype.unrender=function unrender(){var node=this.node;node.removeEventListener('blur',handleDomEvent,false);node.removeEventListener('change',handleDomEvent,false);node.removeEventListener('input',handleDomEvent,false);node.removeEventListener('keyup',handleDomEvent,false);};return ContentEditableBinding;}(Binding));function handleBlur(){handleDomEvent.call(this);var value=this._ractive.binding.model.get();this.value=value==undefined?'':value;}
function handleDelay(delay){var timeout;return function(){var this$1=this;if(timeout)clearTimeout(timeout);timeout=setTimeout(function(){var binding=this$1._ractive.binding;if(binding.rendered)handleDomEvent.call(this$1);timeout=null;},delay);};}
var GenericBinding=(function(Binding){function GenericBinding(){Binding.apply(this,arguments);}
GenericBinding.prototype=Object.create(Binding&&Binding.prototype);GenericBinding.prototype.constructor=GenericBinding;GenericBinding.prototype.getInitialValue=function getInitialValue(){return'';};GenericBinding.prototype.getValue=function getValue(){return this.node.value;};GenericBinding.prototype.render=function render(){Binding.prototype.render.call(this);var lazy=this.ractive.lazy;var timeout=false;if(this.element.template.a&&('lazy'in this.element.template.a)){lazy=this.element.template.a.lazy;if(lazy===0)lazy=true;}
if(lazy==='false')lazy=false;if(isNumeric(lazy)){timeout=+lazy;lazy=false;}
this.handler=timeout?handleDelay(timeout):handleDomEvent;var node=this.node;node.addEventListener('change',handleDomEvent,false);if(!lazy){node.addEventListener('input',this.handler,false);if(node.attachEvent){node.addEventListener('keyup',this.handler,false);}}
node.addEventListener('blur',handleBlur,false);};GenericBinding.prototype.unrender=function unrender(){var node=this.element.node;this.rendered=false;node.removeEventListener('change',handleDomEvent,false);node.removeEventListener('input',this.handler,false);node.removeEventListener('keyup',this.handler,false);node.removeEventListener('blur',handleBlur,false);};return GenericBinding;}(Binding));function getSelectedOptions(select){return select.selectedOptions?toArray(select.selectedOptions):select.options?toArray(select.options).filter(function(option){return option.selected;}):[];}
var MultipleSelectBinding=(function(Binding){function MultipleSelectBinding(){Binding.apply(this,arguments);}
MultipleSelectBinding.prototype=Object.create(Binding&&Binding.prototype);MultipleSelectBinding.prototype.constructor=MultipleSelectBinding;MultipleSelectBinding.prototype.forceUpdate=function forceUpdate(){var this$1=this;var value=this.getValue();if(value!==undefined){this.attribute.locked=true;runloop.scheduleTask(function(){return this$1.attribute.locked=false;});this.model.set(value);}};MultipleSelectBinding.prototype.getInitialValue=function getInitialValue(){return this.element.options.filter(function(option){return option.getAttribute('selected');}).map(function(option){return option.getAttribute('value');});};MultipleSelectBinding.prototype.getValue=function getValue(){var options=this.element.node.options;var len=options.length;var selectedValues=[];for(var i=0;i<len;i+=1){var option=options[i];if(option.selected){var optionValue=option._ractive?option._ractive.value:option.value;selectedValues.push(optionValue);}}
return selectedValues;};MultipleSelectBinding.prototype.handleChange=function handleChange(){var attribute=this.attribute;var previousValue=attribute.getValue();var value=this.getValue();if(previousValue===undefined||!arrayContentsMatch(value,previousValue)){Binding.prototype.handleChange.call(this);}
return this;};MultipleSelectBinding.prototype.render=function render(){Binding.prototype.render.call(this);this.node.addEventListener('change',handleDomEvent,false);if(this.model.get()===undefined){this.handleChange();}};MultipleSelectBinding.prototype.setFromNode=function setFromNode(node){var selectedOptions=getSelectedOptions(node);var i=selectedOptions.length;var result=new Array(i);while(i--){var option=selectedOptions[i];result[i]=option._ractive?option._ractive.value:option.value;}
this.model.set(result);};MultipleSelectBinding.prototype.setValue=function setValue(){throw new Error('TODO not implemented yet');};MultipleSelectBinding.prototype.unrender=function unrender(){this.node.removeEventListener('change',handleDomEvent,false);};MultipleSelectBinding.prototype.updateModel=function updateModel(){if(this.attribute.value===undefined||!this.attribute.value.length){this.keypath.set(this.initialValue);}};return MultipleSelectBinding;}(Binding));var NumericBinding=(function(GenericBinding){function NumericBinding(){GenericBinding.apply(this,arguments);}
NumericBinding.prototype=Object.create(GenericBinding&&GenericBinding.prototype);NumericBinding.prototype.constructor=NumericBinding;NumericBinding.prototype.getInitialValue=function getInitialValue(){return undefined;};NumericBinding.prototype.getValue=function getValue(){var value=parseFloat(this.node.value);return isNaN(value)?undefined:value;};NumericBinding.prototype.setFromNode=function setFromNode(node){var value=parseFloat(node.value);if(!isNaN(value))this.model.set(value);};return NumericBinding;}(GenericBinding));var siblings={};function getSiblings(hash){return siblings[hash]||(siblings[hash]=[]);}
var RadioBinding=(function(Binding){function RadioBinding(element){Binding.call(this,element,'checked');this.siblings=getSiblings(this.ractive._guid+this.element.getAttribute('name'));this.siblings.push(this);}
RadioBinding.prototype=Object.create(Binding&&Binding.prototype);RadioBinding.prototype.constructor=RadioBinding;RadioBinding.prototype.getValue=function getValue(){return this.node.checked;};RadioBinding.prototype.handleChange=function handleChange(){runloop.start(this.root);this.siblings.forEach(function(binding){binding.model.set(binding.getValue());});runloop.end();};RadioBinding.prototype.render=function render(){Binding.prototype.render.call(this);this.node.addEventListener('change',handleDomEvent,false);if(this.node.attachEvent){this.node.addEventListener('click',handleDomEvent,false);}};RadioBinding.prototype.setFromNode=function setFromNode(node){this.model.set(node.checked);};RadioBinding.prototype.unbind=function unbind(){removeFromArray(this.siblings,this);};RadioBinding.prototype.unrender=function unrender(){this.node.removeEventListener('change',handleDomEvent,false);this.node.removeEventListener('click',handleDomEvent,false);};return RadioBinding;}(Binding));function getValue$2(){var checked=this.bindings.filter(function(b){return b.node.checked;});if(checked.length>0){return checked[0].element.getAttribute('value');}}
var RadioNameBinding=(function(Binding){function RadioNameBinding(element){Binding.call(this,element,'name');this.group=getBindingGroup('radioname',this.model,getValue$2);this.group.add(this);if(element.checked){this.group.value=this.getValue();}}
RadioNameBinding.prototype=Object.create(Binding&&Binding.prototype);RadioNameBinding.prototype.constructor=RadioNameBinding;RadioNameBinding.prototype.bind=function bind(){var this$1=this;if(!this.group.bound){this.group.bind();}
this.nameAttributeBinding={handleChange:function(){return this$1.node.name="{{"+(this$1.model.getKeypath())+"}}";}};this.model.getKeypathModel().register(this.nameAttributeBinding);};RadioNameBinding.prototype.getInitialValue=function getInitialValue(){if(this.element.getAttribute('checked')){return this.element.getAttribute('value');}};RadioNameBinding.prototype.getValue=function getValue$1(){return this.element.getAttribute('value');};RadioNameBinding.prototype.handleChange=function handleChange(){if(this.node.checked){this.group.value=this.getValue();Binding.prototype.handleChange.call(this);}};RadioNameBinding.prototype.render=function render(){Binding.prototype.render.call(this);var node=this.node;node.name="{{"+(this.model.getKeypath())+"}}";node.checked=this.model.get()==this.element.getAttribute('value');node.addEventListener('change',handleDomEvent,false);if(node.attachEvent){node.addEventListener('click',handleDomEvent,false);}};RadioNameBinding.prototype.setFromNode=function setFromNode(node){if(node.checked){this.group.model.set(this.element.getAttribute('value'));}};RadioNameBinding.prototype.unbind=function unbind(){this.group.remove(this);this.model.getKeypathModel().unregister(this.nameAttributeBinding);};RadioNameBinding.prototype.unrender=function unrender(){var node=this.node;node.removeEventListener('change',handleDomEvent,false);node.removeEventListener('click',handleDomEvent,false);};return RadioNameBinding;}(Binding));var SingleSelectBinding=(function(Binding){function SingleSelectBinding(){Binding.apply(this,arguments);}
SingleSelectBinding.prototype=Object.create(Binding&&Binding.prototype);SingleSelectBinding.prototype.constructor=SingleSelectBinding;SingleSelectBinding.prototype.forceUpdate=function forceUpdate(){var this$1=this;var value=this.getValue();if(value!==undefined){this.attribute.locked=true;runloop.scheduleTask(function(){return this$1.attribute.locked=false;});this.model.set(value);}};SingleSelectBinding.prototype.getInitialValue=function getInitialValue(){if(this.element.getAttribute('value')!==undefined){return;}
var options=this.element.options;var len=options.length;if(!len)return;var value;var optionWasSelected;var i=len;while(i--){var option=options[i];if(option.getAttribute('selected')){if(!option.getAttribute('disabled')){value=option.getAttribute('value');}
optionWasSelected=true;break;}}
if(!optionWasSelected){while(++i<len){if(!options[i].getAttribute('disabled')){value=options[i].getAttribute('value');break;}}}
if(value!==undefined){this.element.attributeByName.value.value=value;}
return value;};SingleSelectBinding.prototype.getValue=function getValue(){var options=this.node.options;var len=options.length;var i;for(i=0;i<len;i+=1){var option=options[i];if(options[i].selected&&!options[i].disabled){return option._ractive?option._ractive.value:option.value;}}};SingleSelectBinding.prototype.render=function render(){Binding.prototype.render.call(this);this.node.addEventListener('change',handleDomEvent,false);};SingleSelectBinding.prototype.setFromNode=function setFromNode(node){var option=getSelectedOptions(node)[0];this.model.set(option._ractive?option._ractive.value:option.value);};SingleSelectBinding.prototype.setValue=function setValue(value){this.model.set(value);};SingleSelectBinding.prototype.unrender=function unrender(){this.node.removeEventListener('change',handleDomEvent,false);};return SingleSelectBinding;}(Binding));function isBindable(attribute){return attribute&&attribute.template.length===1&&attribute.template[0].t===INTERPOLATOR&&!attribute.template[0].s;}
function selectBinding(element){var attributes=element.attributeByName;if(element.getAttribute('contenteditable')||isBindable(attributes.contenteditable)){return isBindable(attributes.value)?ContentEditableBinding:null;}
if(element.name==='input'){var type=element.getAttribute('type');if(type==='radio'||type==='checkbox'){var bindName=isBindable(attributes.name);var bindChecked=isBindable(attributes.checked);if(bindName&&bindChecked){if(type==='radio'){warnIfDebug('A radio input can have two-way binding on its name attribute, or its checked attribute - not both',{ractive:element.root});}else{return CheckboxBinding;}}
if(bindName){return type==='radio'?RadioNameBinding:CheckboxNameBinding;}
if(bindChecked){return type==='radio'?RadioBinding:CheckboxBinding;}}
if(type==='file'&&isBindable(attributes.value)){return Binding;}
if(isBindable(attributes.value)){return(type==='number'||type==='range')?NumericBinding:GenericBinding;}
return null;}
if(element.name==='select'&&isBindable(attributes.value)){return element.getAttribute('multiple')?MultipleSelectBinding:SingleSelectBinding;}
if(element.name==='textarea'&&isBindable(attributes.value)){return GenericBinding;}}
function makeDirty$1(query){query.makeDirty();}
var Element=(function(Item){function Element(options){var this$1=this;Item.call(this,options);this.liveQueries=[];this.name=options.template.e.toLowerCase();this.isVoid=voidElementNames.test(this.name);var fragment=this.parentFragment;while(fragment){if(fragment.owner.type===ELEMENT){this$1.parent=fragment.owner;break;}
fragment=fragment.parent;}
if(this.parent&&this.parent.name==='option'){throw new Error(("An <option> element cannot contain other elements (encountered <"+(this.name)+">)"));}
this.attributeByName={};this.attributes=[];if(this.template.a){Object.keys(this.template.a).forEach(function(name){if(name==='twoway'||name==='lazy')return;var attribute=new Attribute({name:name,element:this$1,parentFragment:this$1.parentFragment,template:this$1.template.a[name]});this$1.attributeByName[name]=attribute;if(name!=='value'&&name!=='type')this$1.attributes.push(attribute);});if(this.attributeByName.type)this.attributes.unshift(this.attributeByName.type);if(this.attributeByName.value)this.attributes.push(this.attributeByName.value);}
this.conditionalAttributes=(this.template.m||[]).map(function(template){return new ConditionalAttribute({owner:this$1,parentFragment:this$1.parentFragment,template:template});});if(this.template.o){this.decorator=new Decorator(this,this.template.o);}
this.eventHandlers=[];if(this.template.v){Object.keys(this.template.v).forEach(function(key){var eventNames=key.split('-');var template=this$1.template.v[key];eventNames.forEach(function(eventName){var fn=findInViewHierarchy('events',this$1.ractive,eventName);var event=fn?new CustomEvent(fn,this$1):new DOMEvent(eventName,this$1);this$1.eventHandlers.push(new EventDirective(this$1,event,template));});});}
if(options.template.f&&!options.noContent){this.fragment=new Fragment({template:options.template.f,owner:this,cssIds:null});}
this.binding=null;}
Element.prototype=Object.create(Item&&Item.prototype);Element.prototype.constructor=Element;Element.prototype.bind=function bind$1(){this.attributes.forEach(bind);this.conditionalAttributes.forEach(bind);this.eventHandlers.forEach(bind);if(this.decorator)this.decorator.bind();if(this.fragment)this.fragment.bind();if(this.binding=this.createTwowayBinding())this.binding.bind();};Element.prototype.createTwowayBinding=function createTwowayBinding(){var attributes=this.template.a;if(!attributes)return null;var shouldBind='twoway'in attributes?attributes.twoway===0||attributes.twoway==='true':this.ractive.twoway;if(!shouldBind)return null;var Binding=selectBinding(this);if(!Binding)return null;var binding=new Binding(this);return binding&&binding.model?binding:null;};Element.prototype.detach=function detach(){if(this.decorator)this.decorator.unrender();return detachNode(this.node);};Element.prototype.find=function find(selector){if(matches(this.node,selector))return this.node;if(this.fragment){return this.fragment.find(selector);}};Element.prototype.findAll=function findAll(selector,query){var matches=query.test(this.node);if(matches){query.add(this.node);if(query.live)this.liveQueries.push(query);}
if(this.fragment){this.fragment.findAll(selector,query);}};Element.prototype.findComponent=function findComponent(name){if(this.fragment){return this.fragment.findComponent(name);}};Element.prototype.findAllComponents=function findAllComponents(name,query){if(this.fragment){this.fragment.findAllComponents(name,query);}};Element.prototype.findNextNode=function findNextNode(){return null;};Element.prototype.firstNode=function firstNode(){return this.node;};Element.prototype.getAttribute=function getAttribute(name){var attribute=this.attributeByName[name];return attribute?attribute.getValue():undefined;};Element.prototype.rebind=function rebind$1(){this.attributes.forEach(rebind);this.conditionalAttributes.forEach(rebind);this.eventHandlers.forEach(rebind);if(this.decorator)this.decorator.rebind();if(this.fragment)this.fragment.rebind();if(this.binding)this.binding.rebind();this.liveQueries.forEach(makeDirty$1);};Element.prototype.render=function render$1(target,occupants){var this$1=this;this.namespace=getNamespace(this);var node;var existing=false;if(occupants){var n;while((n=occupants.shift())){if(n.nodeName===this$1.template.e.toUpperCase()&&n.namespaceURI===this$1.namespace){this$1.node=node=n;existing=true;break;}else{detachNode(n);}}}
if(!node){node=createElement(this.template.e,this.namespace,this.getAttribute('is'));this.node=node;}
defineProperty(node,'_ractive',{value:{proxy:this,fragment:this.parentFragment}});if(this.parentFragment.cssIds){node.setAttribute('data-ractive-css',this.parentFragment.cssIds.map(function(x){return("{"+x+"}");}).join(' '));}
if(existing&&this.foundNode)this.foundNode(node);if(this.fragment){var children=existing?toArray(node.childNodes):undefined;this.fragment.render(node,children);if(children){children.forEach(detachNode);}}
if(existing){if(this.binding&&this.binding.wasUndefined)this.binding.setFromNode(node);var i=node.attributes.length;while(i--){var name=node.attributes[i].name;if(!this$1.template.a||!(name in this$1.template.a))node.removeAttribute(name);}}
this.attributes.forEach(render);this.conditionalAttributes.forEach(render);if(this.decorator)runloop.scheduleTask(function(){return this$1.decorator.render();},true);if(this.binding)this.binding.render();this.eventHandlers.forEach(render);updateLiveQueries$1(this);this._introTransition=getTransition(this,this.template.t0||this.template.t1,'intro');if(!existing){target.appendChild(node);}
this.rendered=true;};Element.prototype.toString=function toString(){var tagName=this.template.e;var attrs=this.attributes.map(stringifyAttribute).join('')+
this.conditionalAttributes.map(stringifyAttribute).join('');if(this.name==='option'&&this.isSelected()){attrs+=' selected';}
if(this.name==='input'&&inputIsCheckedRadio(this)){attrs+=' checked';}
var str="<"+tagName+""+attrs+">";if(this.isVoid)return str;if(this.name==='textarea'&&this.getAttribute('value')!==undefined){str+=escapeHtml(this.getAttribute('value'));}
else if(this.getAttribute('contenteditable')!==undefined){str+=(this.getAttribute('value')||'');}
if(this.fragment){str+=this.fragment.toString(!/^(?:script|style)$/i.test(this.template.e));}
str+="</"+tagName+">";return str;};Element.prototype.unbind=function unbind$1(){this.attributes.forEach(unbind);this.conditionalAttributes.forEach(unbind);if(this.decorator)this.decorator.unbind();if(this.fragment)this.fragment.unbind();};Element.prototype.unrender=function unrender$1(shouldDestroy){if(!this.rendered)return;this.rendered=false;var transition=this._introTransition;if(transition)transition.complete();if(this.name==='option'){this.detach();}else if(shouldDestroy){runloop.detachWhenReady(this);}
if(this.fragment)this.fragment.unrender();this.eventHandlers.forEach(unrender);if(this.binding)this.binding.unrender();if(!shouldDestroy&&this.decorator)this.decorator.unrender();getTransition(this,this.template.t0||this.template.t2,'outro');var id=this.attributeByName.id;if(id){delete this.ractive.nodes[id.getValue()];}
removeFromLiveQueries(this);};Element.prototype.update=function update$1(){if(this.dirty){this.dirty=false;this.attributes.forEach(update);this.conditionalAttributes.forEach(update);this.eventHandlers.forEach(update);if(this.decorator)this.decorator.update();if(this.fragment)this.fragment.update();}};return Element;}(Item));function getTransition(owner,template,eventName){if(!template||!owner.ractive.transitionsEnabled)return;var name=getTransitionName(owner,template);if(!name)return;var params=getTransitionParams(owner,template);var transition=new Transition(owner.ractive,owner.node,name,params,eventName);runloop.registerTransition(transition);return transition;}
function getTransitionName(owner,template){var name=template.n||template;if(typeof name==='string')return name;var fragment=new Fragment({owner:owner,template:name}).bind();name=fragment.toString();fragment.unbind();return name;}
function getTransitionParams(owner,template){if(template.a)return template.a;if(!template.d)return;var fragment=new Fragment({owner:owner,template:template.d}).bind();var params=fragment.getArgsList();fragment.unbind();return params;}
function inputIsCheckedRadio(element){var attributes=element.attributeByName;var typeAttribute=attributes.type;var valueAttribute=attributes.value;var nameAttribute=attributes.name;if(!typeAttribute||(typeAttribute.value!=='radio')||!valueAttribute||!nameAttribute.interpolator){return;}
if(valueAttribute.getValue()===nameAttribute.interpolator.model.get()){return true;}}
function stringifyAttribute(attribute){var str=attribute.toString();return str?' '+str:'';}
function removeFromLiveQueries(element){var i=element.liveQueries.length;while(i--){var query=element.liveQueries[i];query.remove(element.node);}}
function getNamespace(element){var xmlns=element.getAttribute('xmlns');if(xmlns)return xmlns;if(element.name==='svg')return svg$1;var parent=element.parent;if(parent){if(parent.name==='foreignobject')return html;return parent.node.namespaceURI;}
return element.ractive.el.namespaceURI;}
var Form=(function(Element){function Form(options){Element.call(this,options);this.formBindings=[];}
Form.prototype=Object.create(Element&&Element.prototype);Form.prototype.constructor=Form;Form.prototype.render=function render(target,occupants){Element.prototype.render.call(this,target,occupants);this.node.addEventListener('reset',handleReset,false);};Form.prototype.unrender=function unrender(shouldDestroy){this.node.removeEventListener('reset',handleReset,false);Element.prototype.unrender.call(this,shouldDestroy);};return Form;}(Element));function handleReset(){var element=this._ractive.proxy;runloop.start();element.formBindings.forEach(updateModel);runloop.end();}
function updateModel(binding){binding.model.set(binding.resetValue);}
var Mustache=(function(Item){function Mustache(options){Item.call(this,options);this.parentFragment=options.parentFragment;this.template=options.template;this.index=options.index;this.isStatic=!!options.template.s;this.model=null;this.dirty=false;}
Mustache.prototype=Object.create(Item&&Item.prototype);Mustache.prototype.constructor=Mustache;Mustache.prototype.bind=function bind(){var this$1=this;var model=resolve$1(this.parentFragment,this.template);var value=model?model.get():undefined;if(this.isStatic){this.model={get:function(){return value;}};return;}
if(model){model.register(this);this.model=model;}else{this.resolver=this.parentFragment.resolve(this.template.r,function(model){this$1.model=model;model.register(this$1);this$1.handleChange();this$1.resolver=null;});}};Mustache.prototype.handleChange=function handleChange(){this.bubble();};Mustache.prototype.rebind=function rebind(){if(this.isStatic||!this.model)return;var model=resolve$1(this.parentFragment,this.template);if(model===this.model)return;this.model.unregister(this);this.model=model;if(model){model.register(this);this.handleChange();}};Mustache.prototype.unbind=function unbind(){if(!this.isStatic){this.model&&this.model.unregister(this);this.model=undefined;this.resolver&&this.resolver.unbind();}};return Mustache;}(Item));var Interpolator=(function(Mustache){function Interpolator(){Mustache.apply(this,arguments);}
Interpolator.prototype=Object.create(Mustache&&Mustache.prototype);Interpolator.prototype.constructor=Interpolator;Interpolator.prototype.detach=function detach(){return detachNode(this.node);};Interpolator.prototype.firstNode=function firstNode(){return this.node;};Interpolator.prototype.getString=function getString(){return this.model?safeToStringValue(this.model.get()):'';};Interpolator.prototype.render=function render(target,occupants){var value=this.getString();this.rendered=true;if(occupants){var n=occupants[0];if(n&&n.nodeType===3){occupants.shift();if(n.nodeValue!==value){n.nodeValue=value;}}else{n=this.node=doc.createTextNode(value);if(occupants[0]){target.insertBefore(n,occupants[0]);}else{target.appendChild(n);}}
this.node=n;}else{this.node=doc.createTextNode(value);target.appendChild(this.node);}};Interpolator.prototype.toString=function toString(escape){var string=this.getString();return escape?escapeHtml(string):string;};Interpolator.prototype.unrender=function unrender(shouldDestroy){if(shouldDestroy)this.detach();this.rendered=false;};Interpolator.prototype.update=function update(){if(this.dirty){this.dirty=false;if(this.rendered){this.node.data=this.getString();}}};Interpolator.prototype.valueOf=function valueOf(){return this.model?this.model.get():undefined;};return Interpolator;}(Mustache));var Input=(function(Element){function Input(){Element.apply(this,arguments);}
Input.prototype=Object.create(Element&&Element.prototype);Input.prototype.constructor=Input;Input.prototype.render=function render(target,occupants){Element.prototype.render.call(this,target,occupants);this.node.defaultValue=this.node.value;};return Input;}(Element));function findParentSelect(element){while(element){if(element.name==='select')return element;element=element.parent;}}
var Option=(function(Element){function Option(options){var template=options.template;if(!template.a)template.a={};if(template.a.value===undefined&&!('disabled'in template.a)){template.a.value=template.f||'';}
Element.call(this,options);this.select=findParentSelect(this.parent);}
Option.prototype=Object.create(Element&&Element.prototype);Option.prototype.constructor=Option;Option.prototype.bind=function bind(){if(!this.select){Element.prototype.bind.call(this);return;}
var selectedAttribute=this.attributeByName.selected;if(selectedAttribute&&this.select.getAttribute('value')!==undefined){var index=this.attributes.indexOf(selectedAttribute);this.attributes.splice(index,1);delete this.attributeByName.selected;}
Element.prototype.bind.call(this);this.select.options.push(this);};Option.prototype.isSelected=function isSelected(){var optionValue=this.getAttribute('value');if(optionValue===undefined||!this.select){return false;}
var selectValue=this.select.getAttribute('value');if(selectValue==optionValue){return true;}
if(this.select.getAttribute('multiple')&&isArray(selectValue)){var i=selectValue.length;while(i--){if(selectValue[i]==optionValue){return true;}}}};Option.prototype.unbind=function unbind(){Element.prototype.unbind.call(this);if(this.select){removeFromArray(this.select.options,this);}};return Option;}(Element));function getPartialTemplate(ractive,name,parentFragment){var partial=getPartialFromRegistry(ractive,name,parentFragment||{});if(partial)return partial;partial=parser.fromId(name,{noThrow:true});if(partial){var parsed=parser.parseFor(partial,ractive);if(parsed.p)fillGaps(ractive.partials,parsed.p);return ractive.partials[name]=parsed.t;}}
function getPartialFromRegistry(ractive,name,parentFragment){var partial=findParentPartial(name,parentFragment.owner);if(partial)return partial;var instance=findInstance('partials',ractive,name);if(!instance){return;}
partial=instance.partials[name];var fn;if(typeof partial==='function'){fn=partial.bind(instance);fn.isOwner=instance.partials.hasOwnProperty(name);partial=fn.call(ractive,parser);}
if(!partial&&partial!==''){warnIfDebug(noRegistryFunctionReturn,name,'partial','partial',{ractive:ractive});return;}
if(!parser.isParsed(partial)){var parsed=parser.parseFor(partial,instance);if(parsed.p){warnIfDebug('Partials ({{>%s}}) cannot contain nested inline partials',name,{ractive:ractive});}
var target=fn?instance:findOwner(instance,name);target.partials[name]=partial=parsed.t;}
if(fn)partial._fn=fn;return partial.v?partial.t:partial;}
function findOwner(ractive,key){return ractive.partials.hasOwnProperty(key)?ractive:findConstructor(ractive.constructor,key);}
function findConstructor(constructor,key){if(!constructor){return;}
return constructor.partials.hasOwnProperty(key)?constructor:findConstructor(constructor._Parent,key);}
function findParentPartial(name,parent){if(parent){if(parent.template&&parent.template.p&&parent.template.p[name]){return parent.template.p[name];}else if(parent.parentFragment&&parent.parentFragment.owner){return findParentPartial(name,parent.parentFragment.owner);}}}
var Partial=(function(Mustache){function Partial(){Mustache.apply(this,arguments);}
Partial.prototype=Object.create(Mustache&&Mustache.prototype);Partial.prototype.constructor=Partial;Partial.prototype.bind=function bind(){this.refName=this.template.r;var template=this.refName?getPartialTemplate(this.ractive,this.refName,this.parentFragment)||null:null;var templateObj;if(template){this.named=true;this.setTemplate(this.template.r,template);}
if(!template){Mustache.prototype.bind.call(this);if(this.model&&(templateObj=this.model.get())&&typeof templateObj==='object'&&(typeof templateObj.template==='string'||isArray(templateObj.t))){if(templateObj.template){templateObj=parsePartial(this.template.r,templateObj.template,this.ractive);}
this.setTemplate(this.template.r,templateObj.t);}else if((!this.model||typeof this.model.get()!=='string')&&this.refName){this.setTemplate(this.refName,template);}else{this.setTemplate(this.model.get());}}
this.fragment=new Fragment({owner:this,template:this.partialTemplate}).bind();};Partial.prototype.detach=function detach(){return this.fragment.detach();};Partial.prototype.find=function find(selector){return this.fragment.find(selector);};Partial.prototype.findAll=function findAll(selector,query){this.fragment.findAll(selector,query);};Partial.prototype.findComponent=function findComponent(name){return this.fragment.findComponent(name);};Partial.prototype.findAllComponents=function findAllComponents(name,query){this.fragment.findAllComponents(name,query);};Partial.prototype.firstNode=function firstNode(skipParent){return this.fragment.firstNode(skipParent);};Partial.prototype.forceResetTemplate=function forceResetTemplate(){this.partialTemplate=undefined;if(this.refName){this.partialTemplate=getPartialTemplate(this.ractive,this.refName,this.parentFragment);}
if(!this.partialTemplate){this.partialTemplate=getPartialTemplate(this.ractive,this.name,this.parentFragment);}
if(!this.partialTemplate){warnOnceIfDebug(("Could not find template for partial '"+(this.name)+"'"));this.partialTemplate=[];}
this.fragment.resetTemplate(this.partialTemplate);this.bubble();};Partial.prototype.rebind=function rebind(){Mustache.prototype.unbind.call(this);Mustache.prototype.bind.call(this);this.fragment.rebind();};Partial.prototype.render=function render(target,occupants){this.fragment.render(target,occupants);};Partial.prototype.setTemplate=function setTemplate(name,template){this.name=name;if(!template&&template!==null)template=getPartialTemplate(this.ractive,name,this.parentFragment);if(!template){warnOnceIfDebug(("Could not find template for partial '"+name+"'"));}
this.partialTemplate=template||[];};Partial.prototype.toString=function toString(escape){return this.fragment.toString(escape);};Partial.prototype.unbind=function unbind(){Mustache.prototype.unbind.call(this);this.fragment.unbind();};Partial.prototype.unrender=function unrender(shouldDestroy){this.fragment.unrender(shouldDestroy);};Partial.prototype.update=function update(){var template;if(this.dirty){this.dirty=false;if(!this.named){if(this.model){template=this.model.get();}
if(template&&typeof template==='string'&&template!==this.name){this.setTemplate(template);this.fragment.resetTemplate(this.partialTemplate);}else if(template&&typeof template==='object'&&(typeof template.template==='string'||isArray(template.t))){if(template.template){template=parsePartial(this.name,template.template,this.ractive);}
this.setTemplate(this.name,template.t);this.fragment.resetTemplate(this.partialTemplate);}}
this.fragment.update();}};return Partial;}(Mustache));function parsePartial(name,partial,ractive){var parsed;try{parsed=parser.parse(partial,parser.getParseOptions(ractive));}catch(e){warnIfDebug(("Could not parse partial from expression '"+name+"'\n"+(e.message)));}
return parsed||{t:[]};}
var RepeatedFragment=function RepeatedFragment(options){this.parent=options.owner.parentFragment;this.parentFragment=this;this.owner=options.owner;this.ractive=this.parent.ractive;this.cssIds='cssIds'in options?options.cssIds:(this.parent?this.parent.cssIds:null);this.context=null;this.rendered=false;this.iterations=[];this.template=options.template;this.indexRef=options.indexRef;this.keyRef=options.keyRef;this.pendingNewIndices=null;this.previousIterations=null;this.isArray=false;};RepeatedFragment.prototype.bind=function bind(context){var this$1=this;this.context=context;var value=context.get();if(this.isArray=isArray(value)){this.iterations=[];for(var i=0;i<value.length;i+=1){this$1.iterations[i]=this$1.createIteration(i,i);}}
else if(isObject(value)){this.isArray=false;if(this.indexRef){var refs=this.indexRef.split(',');this.keyRef=refs[0];this.indexRef=refs[1];}
this.iterations=Object.keys(value).map(function(key,index){return this$1.createIteration(key,index);});}
return this;};RepeatedFragment.prototype.bubble=function bubble(){this.owner.bubble();};RepeatedFragment.prototype.createIteration=function createIteration(key,index){var fragment=new Fragment({owner:this,template:this.template});fragment.key=key;fragment.index=index;fragment.isIteration=true;var model=this.context.joinKey(key);if(this.owner.template.z){fragment.aliases={};fragment.aliases[this.owner.template.z[0].n]=model;}
return fragment.bind(model);};RepeatedFragment.prototype.detach=function detach(){var docFrag=createDocumentFragment();this.iterations.forEach(function(fragment){return docFrag.appendChild(fragment.detach());});return docFrag;};RepeatedFragment.prototype.find=function find(selector){var this$1=this;var len=this.iterations.length;var i;for(i=0;i<len;i+=1){var found=this$1.iterations[i].find(selector);if(found)return found;}};RepeatedFragment.prototype.findAll=function findAll(selector,query){var this$1=this;var len=this.iterations.length;var i;for(i=0;i<len;i+=1){this$1.iterations[i].findAll(selector,query);}};RepeatedFragment.prototype.findComponent=function findComponent(name){var this$1=this;var len=this.iterations.length;var i;for(i=0;i<len;i+=1){var found=this$1.iterations[i].findComponent(name);if(found)return found;}};RepeatedFragment.prototype.findAllComponents=function findAllComponents(name,query){var this$1=this;var len=this.iterations.length;var i;for(i=0;i<len;i+=1){this$1.iterations[i].findAllComponents(name,query);}};RepeatedFragment.prototype.findNextNode=function findNextNode(iteration){var this$1=this;if(iteration.index<this.iterations.length-1){for(var i=iteration.index+1;i<this$1.iterations.length;i++){var node=this$1.iterations[i].firstNode(true);if(node)return node;}}
return this.owner.findNextNode();};RepeatedFragment.prototype.firstNode=function firstNode(skipParent){return this.iterations[0]?this.iterations[0].firstNode(skipParent):null;};RepeatedFragment.prototype.rebind=function rebind(context){var this$1=this;this.context=context;this.iterations.forEach(function(fragment){var model=context.joinKey(fragment.key||fragment.index);if(this$1.owner.template.z){fragment.aliases={};fragment.aliases[this$1.owner.template.z[0].n]=model;}
fragment.rebind(model);});};RepeatedFragment.prototype.render=function render(target,occupants){if(this.iterations){this.iterations.forEach(function(fragment){return fragment.render(target,occupants);});}
this.rendered=true;};RepeatedFragment.prototype.shuffle=function shuffle(newIndices){var this$1=this;if(!this.pendingNewIndices)this.previousIterations=this.iterations.slice();if(!this.pendingNewIndices)this.pendingNewIndices=[];this.pendingNewIndices.push(newIndices);var iterations=[];newIndices.forEach(function(newIndex,oldIndex){if(newIndex===-1)return;var fragment=this$1.iterations[oldIndex];iterations[newIndex]=fragment;if(newIndex!==oldIndex&&fragment)fragment.dirty=true;});this.iterations=iterations;this.bubble();};RepeatedFragment.prototype.toString=function toString$1$$(escape){return this.iterations?this.iterations.map(escape?toEscapedString:toString$1).join(''):'';};RepeatedFragment.prototype.unbind=function unbind$1(){this.iterations.forEach(unbind);return this;};RepeatedFragment.prototype.unrender=function unrender$1(shouldDestroy){this.iterations.forEach(shouldDestroy?unrenderAndDestroy:unrender);if(this.pendingNewIndices&&this.previousIterations){this.previousIterations.forEach(function(fragment){if(fragment.rendered)shouldDestroy?unrenderAndDestroy(fragment):unrender(fragment);});}
this.rendered=false;};RepeatedFragment.prototype.update=function update$1(){var this$1=this;if(this.pendingNewIndices){this.updatePostShuffle();return;}
if(this.updating)return;this.updating=true;var value=this.context.get(),wasArray=this.isArray;var toRemove;var oldKeys;var reset=true;var i;if(this.isArray=isArray(value)){if(wasArray){reset=false;if(this.iterations.length>value.length){toRemove=this.iterations.splice(value.length);}}}else if(isObject(value)&&!wasArray){reset=false;toRemove=[];oldKeys={};i=this.iterations.length;while(i--){var fragment$1=this$1.iterations[i];if(fragment$1.key in value){oldKeys[fragment$1.key]=true;}else{this$1.iterations.splice(i,1);toRemove.push(fragment$1);}}}
if(reset){toRemove=this.iterations;this.iterations=[];}
if(toRemove){toRemove.forEach(function(fragment){fragment.unbind();fragment.unrender(true);});}
this.iterations.forEach(update);var newLength=isArray(value)?value.length:isObject(value)?Object.keys(value).length:0;var docFrag;var fragment;if(newLength>this.iterations.length){docFrag=this.rendered?createDocumentFragment():null;i=this.iterations.length;if(isArray(value)){while(i<value.length){fragment=this$1.createIteration(i,i);this$1.iterations.push(fragment);if(this$1.rendered)fragment.render(docFrag);i+=1;}}
else if(isObject(value)){if(this.indexRef&&!this.keyRef){var refs=this.indexRef.split(',');this.keyRef=refs[0];this.indexRef=refs[1];}
Object.keys(value).forEach(function(key){if(!oldKeys||!(key in oldKeys)){fragment=this$1.createIteration(key,i);this$1.iterations.push(fragment);if(this$1.rendered)fragment.render(docFrag);i+=1;}});}
if(this.rendered){var parentNode=this.parent.findParentNode();var anchor=this.parent.findNextNode(this.owner);parentNode.insertBefore(docFrag,anchor);}}
this.updating=false;};RepeatedFragment.prototype.updatePostShuffle=function updatePostShuffle(){var this$1=this;var newIndices=this.pendingNewIndices[0];this.pendingNewIndices.slice(1).forEach(function(indices){newIndices.forEach(function(newIndex,oldIndex){newIndices[oldIndex]=indices[newIndex];});});var len=this.context.get().length;var i,maxIdx=0,merged=false;newIndices.forEach(function(newIndex,oldIndex){var fragment=this$1.previousIterations[oldIndex];if(!merged&&newIndex!==-1){if(newIndex<maxIdx)merged=true;if(newIndex>maxIdx)maxIdx=newIndex;}
if(newIndex===-1){fragment.unbind().unrender(true);}else{fragment.index=newIndex;var model=this$1.context.joinKey(newIndex);if(this$1.owner.template.z){fragment.aliases={};fragment.aliases[this$1.owner.template.z[0].n]=model;}
fragment.rebind(model);}});var docFrag=this.rendered?createDocumentFragment():null;var parentNode=this.rendered?this.parent.findParentNode():null;if(merged){for(i=0;i<len;i+=1){var frag=this$1.iterations[i];if(this$1.rendered){if(frag){docFrag.appendChild(frag.detach());}else{this$1.iterations[i]=this$1.createIteration(i,i);this$1.iterations[i].render(docFrag);}}
if(!this$1.rendered){if(!frag){this$1.iterations[i]=this$1.createIteration(i,i);}}}}else{for(i=0;i<len;i++){var frag$1=this$1.iterations[i];if(this$1.rendered){if(frag$1&&docFrag.childNodes.length){parentNode.insertBefore(docFrag,frag$1.firstNode());}
if(!frag$1){frag$1=this$1.iterations[i]=this$1.createIteration(i,i);frag$1.render(docFrag);}}else if(!frag$1){this$1.iterations[i]=this$1.createIteration(i,i);}}}
if(this.rendered&&docFrag.childNodes.length){parentNode.insertBefore(docFrag,this.owner.findNextNode());}
this.iterations.forEach(update);this.pendingNewIndices=null;};function isEmpty(value){return!value||(isArray(value)&&value.length===0)||(isObject(value)&&Object.keys(value).length===0);}
function getType(value,hasIndexRef){if(hasIndexRef||isArray(value))return SECTION_EACH;if(isObject(value)||typeof value==='function')return SECTION_IF_WITH;if(value===undefined)return null;return SECTION_IF;}
var Section=(function(Mustache){function Section(options){Mustache.call(this,options);this.sectionType=options.template.n||null;this.templateSectionType=this.sectionType;this.fragment=null;}
Section.prototype=Object.create(Mustache&&Mustache.prototype);Section.prototype.constructor=Section;Section.prototype.bind=function bind(){Mustache.prototype.bind.call(this);if(this.model){this.dirty=true;this.update();}else if(this.sectionType&&this.sectionType===SECTION_UNLESS){this.fragment=new Fragment({owner:this,template:this.template.f}).bind();}};Section.prototype.detach=function detach(){return this.fragment?this.fragment.detach():createDocumentFragment();};Section.prototype.find=function find(selector){if(this.fragment){return this.fragment.find(selector);}};Section.prototype.findAll=function findAll(selector,query){if(this.fragment){this.fragment.findAll(selector,query);}};Section.prototype.findComponent=function findComponent(name){if(this.fragment){return this.fragment.findComponent(name);}};Section.prototype.findAllComponents=function findAllComponents(name,query){if(this.fragment){this.fragment.findAllComponents(name,query);}};Section.prototype.firstNode=function firstNode(skipParent){return this.fragment&&this.fragment.firstNode(skipParent);};Section.prototype.rebind=function rebind(){Mustache.prototype.rebind.call(this);if(this.fragment){this.fragment.rebind(this.sectionType===SECTION_IF||this.sectionType===SECTION_UNLESS?null:this.model);}};Section.prototype.render=function render(target,occupants){this.rendered=true;if(this.fragment)this.fragment.render(target,occupants);};Section.prototype.shuffle=function shuffle(newIndices){if(this.fragment&&this.sectionType===SECTION_EACH){this.fragment.shuffle(newIndices);}};Section.prototype.toString=function toString(escape){return this.fragment?this.fragment.toString(escape):'';};Section.prototype.unbind=function unbind(){Mustache.prototype.unbind.call(this);if(this.fragment)this.fragment.unbind();};Section.prototype.unrender=function unrender(shouldDestroy){if(this.rendered&&this.fragment)this.fragment.unrender(shouldDestroy);this.rendered=false;};Section.prototype.update=function update(){if(!this.dirty)return;if(!this.model&&this.sectionType!==SECTION_UNLESS)return;this.dirty=false;var value=!this.model?undefined:this.model.isRoot?this.model.value:this.model.get();var lastType=this.sectionType;if(this.sectionType===null||this.templateSectionType===null)this.sectionType=getType(value,this.template.i);if(lastType&&lastType!==this.sectionType&&this.fragment){if(this.rendered){this.fragment.unbind().unrender(true);}
this.fragment=null;}
var newFragment;if(this.sectionType===SECTION_EACH){if(this.fragment){this.fragment.update();}else{newFragment=new RepeatedFragment({owner:this,template:this.template.f,indexRef:this.template.i}).bind(this.model);}}
else if(this.sectionType===SECTION_WITH){if(this.fragment){this.fragment.update();}else{newFragment=new Fragment({owner:this,template:this.template.f}).bind(this.model);}}
else if(this.sectionType===SECTION_IF_WITH){if(this.fragment){if(isEmpty(value)){if(this.rendered){this.fragment.unbind().unrender(true);}
this.fragment=null;}else{this.fragment.update();}}else if(!isEmpty(value)){newFragment=new Fragment({owner:this,template:this.template.f}).bind(this.model);}}
else{var fragmentShouldExist=this.sectionType===SECTION_UNLESS?isEmpty(value):!!value&&!isEmpty(value);if(this.fragment){if(fragmentShouldExist){this.fragment.update();}else{if(this.rendered){this.fragment.unbind().unrender(true);}
this.fragment=null;}}else if(fragmentShouldExist){newFragment=new Fragment({owner:this,template:this.template.f}).bind(null);}}
if(newFragment){if(this.rendered){var parentNode=this.parentFragment.findParentNode();var anchor=this.parentFragment.findNextNode(this);if(anchor){var docFrag=createDocumentFragment();newFragment.render(docFrag);anchor.parentNode.insertBefore(docFrag,anchor);}else{newFragment.render(parentNode);}}
this.fragment=newFragment;}};return Section;}(Mustache));function valueContains(selectValue,optionValue){var i=selectValue.length;while(i--){if(selectValue[i]==optionValue)return true;}}
var Select=(function(Element){function Select(options){Element.call(this,options);this.options=[];}
Select.prototype=Object.create(Element&&Element.prototype);Select.prototype.constructor=Select;Select.prototype.foundNode=function foundNode(node){if(this.binding){var selectedOptions=getSelectedOptions(node);if(selectedOptions.length>0){this.selectedOptions=selectedOptions;}}};Select.prototype.render=function render(target,occupants){Element.prototype.render.call(this,target,occupants);this.sync();var node=this.node;var i=node.options.length;while(i--){node.options[i].defaultSelected=node.options[i].selected;}
this.rendered=true;};Select.prototype.sync=function sync(){var this$1=this;var selectNode=this.node;if(!selectNode)return;var options=toArray(selectNode.options);if(this.selectedOptions){options.forEach(function(o){if(this$1.selectedOptions.indexOf(o)>=0)o.selected=true;else o.selected=false;});this.binding.setFromNode(selectNode);delete this.selectedOptions;return;}
var selectValue=this.getAttribute('value');var isMultiple=this.getAttribute('multiple');if(selectValue!==undefined){var optionWasSelected;options.forEach(function(o){var optionValue=o._ractive?o._ractive.value:o.value;var shouldSelect=isMultiple?valueContains(selectValue,optionValue):selectValue==optionValue;if(shouldSelect){optionWasSelected=true;}
o.selected=shouldSelect;});if(!optionWasSelected&&!isMultiple){if(this.binding){this.binding.forceUpdate();}}}
else if(this.binding){this.binding.forceUpdate();}};Select.prototype.update=function update(){Element.prototype.update.call(this);this.sync();};return Select;}(Element));var Textarea=(function(Input){function Textarea(options){var template=options.template;if(template.a&&template.a.value&&isBindable({template:template.a.value})){options.noContent=true;}
else if(template.f&&(!template.a||!template.a.value)&&isBindable({template:template.f})){if(!template.a)template.a={};template.a.value=template.f;options.noContent=true;}
Input.call(this,options);}
Textarea.prototype=Object.create(Input&&Input.prototype);Textarea.prototype.constructor=Textarea;Textarea.prototype.bubble=function bubble(){var this$1=this;if(!this.dirty){this.dirty=true;if(this.rendered&&!this.binding&&this.fragment){runloop.scheduleTask(function(){this$1.dirty=false;this$1.node.value=this$1.fragment.toString();});}
this.parentFragment.bubble();}};return Textarea;}(Input));var Text=(function(Item){function Text(options){Item.call(this,options);this.type=TEXT;}
Text.prototype=Object.create(Item&&Item.prototype);Text.prototype.constructor=Text;Text.prototype.bind=function bind(){};Text.prototype.detach=function detach(){return detachNode(this.node);};Text.prototype.firstNode=function firstNode(){return this.node;};Text.prototype.rebind=function rebind(){};Text.prototype.render=function render(target,occupants){this.rendered=true;if(occupants){var n=occupants[0];if(n&&n.nodeType===3){occupants.shift();if(n.nodeValue!==this.template){n.nodeValue=this.template;}}else{n=this.node=doc.createTextNode(this.template);if(occupants[0]){target.insertBefore(n,occupants[0]);}else{target.appendChild(n);}}
this.node=n;}else{this.node=doc.createTextNode(this.template);target.appendChild(this.node);}};Text.prototype.toString=function toString(escape){return escape?escapeHtml(this.template):this.template;};Text.prototype.unbind=function unbind(){};Text.prototype.unrender=function unrender(shouldDestroy){if(this.rendered&&shouldDestroy)this.detach();this.rendered=false;};Text.prototype.update=function update(){};Text.prototype.valueOf=function valueOf(){return this.template;};return Text;}(Item));var elementCache={};var ieBug;var ieBlacklist;try{createElement('table').innerHTML='foo';}catch(err){ieBug=true;ieBlacklist={TABLE:['<table class="x">','</table>'],THEAD:['<table><thead class="x">','</thead></table>'],TBODY:['<table><tbody class="x">','</tbody></table>'],TR:['<table><tr class="x">','</tr></table>'],SELECT:['<select class="x">','</select>']};}
function insertHtml(html,node,docFrag){var nodes=[];if(html==null||html==='')return nodes;var container;var wrapper;var selectedOption;if(ieBug&&(wrapper=ieBlacklist[node.tagName])){container=element('DIV');container.innerHTML=wrapper[0]+html+wrapper[1];container=container.querySelector('.x');if(container.tagName==='SELECT'){selectedOption=container.options[container.selectedIndex];}}
else if(node.namespaceURI===svg$1){container=element('DIV');container.innerHTML='<svg class="x">'+html+'</svg>';container=container.querySelector('.x');}
else if(node.tagName==='TEXTAREA'){container=createElement('div');if(typeof container.textContent!=='undefined'){container.textContent=html;}else{container.innerHTML=html;}}
else{container=element(node.tagName);container.innerHTML=html;if(container.tagName==='SELECT'){selectedOption=container.options[container.selectedIndex];}}
var child;while(child=container.firstChild){nodes.push(child);docFrag.appendChild(child);}
var i;if(node.tagName==='SELECT'){i=nodes.length;while(i--){if(nodes[i]!==selectedOption){nodes[i].selected=false;}}}
return nodes;}
function element(tagName){return elementCache[tagName]||(elementCache[tagName]=createElement(tagName));}
var Triple=(function(Mustache){function Triple(options){Mustache.call(this,options);}
Triple.prototype=Object.create(Mustache&&Mustache.prototype);Triple.prototype.constructor=Triple;Triple.prototype.detach=function detach(){var docFrag=createDocumentFragment();this.nodes.forEach(function(node){return docFrag.appendChild(node);});return docFrag;};Triple.prototype.find=function find(selector){var this$1=this;var len=this.nodes.length;var i;for(i=0;i<len;i+=1){var node=this$1.nodes[i];if(node.nodeType!==1)continue;if(matches(node,selector))return node;var queryResult=node.querySelector(selector);if(queryResult)return queryResult;}
return null;};Triple.prototype.findAll=function findAll(selector,query){var this$1=this;var len=this.nodes.length;var i;for(i=0;i<len;i+=1){var node=this$1.nodes[i];if(node.nodeType!==1)continue;if(query.test(node))query.add(node);var queryAllResult=node.querySelectorAll(selector);if(queryAllResult){var numNodes=queryAllResult.length;var j;for(j=0;j<numNodes;j+=1){query.add(queryAllResult[j]);}}}};Triple.prototype.findComponent=function findComponent(){return null;};Triple.prototype.firstNode=function firstNode(){return this.nodes[0];};Triple.prototype.render=function render(target){var html=this.model?this.model.get():'';this.nodes=insertHtml(html,this.parentFragment.findParentNode(),target);this.rendered=true;};Triple.prototype.toString=function toString(){return this.model&&this.model.get()!=null?decodeCharacterReferences(''+this.model.get()):'';};Triple.prototype.unrender=function unrender(){if(this.nodes)this.nodes.forEach(function(node){return detachNode(node);});this.rendered=false;};Triple.prototype.update=function update(){if(this.rendered&&this.dirty){this.dirty=false;this.unrender();var docFrag=createDocumentFragment();this.render(docFrag);var parentNode=this.parentFragment.findParentNode();var anchor=this.parentFragment.findNextNode(this);parentNode.insertBefore(docFrag,anchor);}};return Triple;}(Mustache));var Yielder=(function(Item){function Yielder(options){Item.call(this,options);this.container=options.parentFragment.ractive;this.component=this.container.component;this.containerFragment=options.parentFragment;this.parentFragment=this.component.parentFragment;this.name=options.template.n||'';}
Yielder.prototype=Object.create(Item&&Item.prototype);Yielder.prototype.constructor=Yielder;Yielder.prototype.bind=function bind(){var name=this.name;(this.component.yielders[name]||(this.component.yielders[name]=[])).push(this);var template=this.container._inlinePartials[name||'content'];if(typeof template==='string'){template=parse(template).t;}
if(!template){warnIfDebug(("Could not find template for partial \""+name+"\""),{ractive:this.ractive});template=[];}
this.fragment=new Fragment({owner:this,ractive:this.container.parent,template:template}).bind();};Yielder.prototype.bubble=function bubble(){if(!this.dirty){this.containerFragment.bubble();this.dirty=true;}};Yielder.prototype.detach=function detach(){return this.fragment.detach();};Yielder.prototype.find=function find(selector){return this.fragment.find(selector);};Yielder.prototype.findAll=function findAll(selector,queryResult){this.fragment.find(selector,queryResult);};Yielder.prototype.findComponent=function findComponent(name){return this.fragment.findComponent(name);};Yielder.prototype.findAllComponents=function findAllComponents(name,queryResult){this.fragment.findAllComponents(name,queryResult);};Yielder.prototype.findNextNode=function findNextNode(){return this.containerFragment.findNextNode(this);};Yielder.prototype.firstNode=function firstNode(skipParent){return this.fragment.firstNode(skipParent);};Yielder.prototype.rebind=function rebind(){this.fragment.rebind();};Yielder.prototype.render=function render(target,occupants){return this.fragment.render(target,occupants);};Yielder.prototype.setTemplate=function setTemplate(name){var template=this.parentFragment.ractive.partials[name];if(typeof template==='string'){template=parse(template).t;}
this.partialTemplate=template||[];};Yielder.prototype.toString=function toString(escape){return this.fragment.toString(escape);};Yielder.prototype.unbind=function unbind(){this.fragment.unbind();removeFromArray(this.component.yielders[this.name],this);};Yielder.prototype.unrender=function unrender(shouldDestroy){this.fragment.unrender(shouldDestroy);};Yielder.prototype.update=function update(){this.dirty=false;this.fragment.update();};return Yielder;}(Item));function getComponentConstructor(ractive,name){var instance=findInstance('components',ractive,name);var Component;if(instance){Component=instance.components[name];if(!Component._Parent){var fn=Component.bind(instance);fn.isOwner=instance.components.hasOwnProperty(name);Component=fn();if(!Component){warnIfDebug(noRegistryFunctionReturn,name,'component','component',{ractive:ractive});return;}
if(typeof Component==='string'){Component=getComponentConstructor(ractive,Component);}
Component._fn=fn;instance.components[name]=Component;}}
return Component;}
var constructors={};constructors[ALIAS]=Alias;constructors[DOCTYPE]=Doctype;constructors[INTERPOLATOR]=Interpolator;constructors[PARTIAL]=Partial;constructors[SECTION]=Section;constructors[TRIPLE]=Triple;constructors[YIELDER]=Yielder;var specialElements={doctype:Doctype,form:Form,input:Input,option:Option,select:Select,textarea:Textarea};function createItem(options){if(typeof options.template==='string'){return new Text(options);}
if(options.template.t===ELEMENT){var ComponentConstructor=getComponentConstructor(options.parentFragment.ractive,options.template.e);if(ComponentConstructor){return new Component(options,ComponentConstructor);}
var tagName=options.template.e.toLowerCase();var ElementConstructor=specialElements[tagName]||Element;return new ElementConstructor(options);}
var Item=constructors[options.template.t];if(!Item)throw new Error(("Unrecognised item type "+(options.template.t)));return new Item(options);}
var ReferenceResolver=function ReferenceResolver(fragment,reference,callback){var this$1=this;this.fragment=fragment;this.reference=normalise(reference);this.callback=callback;this.keys=splitKeypathI(reference);this.resolved=false;while(fragment){if(fragment.context){fragment.context.addUnresolved(this$1.keys[0],this$1);}
fragment=fragment.componentParent||fragment.parent;}};ReferenceResolver.prototype.attemptResolution=function attemptResolution(){if(this.resolved)return;var model=resolveAmbiguousReference(this.fragment,this.reference);if(model){this.resolved=true;this.callback(model);}};ReferenceResolver.prototype.forceResolution=function forceResolution(){if(this.resolved)return;var model=this.fragment.findContext().joinAll(this.keys);this.callback(model);this.resolved=true;};ReferenceResolver.prototype.unbind=function unbind(){var this$1=this;removeFromArray(this.fragment.unresolved,this);if(this.resolved)return;var fragment=this.fragment;while(fragment){if(fragment.context){fragment.context.removeUnresolved(this$1.keys[0],this$1);}
fragment=fragment.componentParent||fragment.parent;}};function processItems(items,values,guid,counter){if(counter===void 0)counter=0;return items.map(function(item){if(item.type===TEXT){return item.template;}
if(item.fragment){if(item.fragment.iterations){return item.fragment.iterations.map(function(fragment){return processItems(fragment.items,values,guid,counter);}).join('');}else{return processItems(item.fragment.items,values,guid,counter);}}
var placeholderId=""+guid+"-"+(counter++);values[placeholderId]=item.model?item.model.wrapper?item.model.wrapper.value:item.model.get():undefined;return'${'+placeholderId+'}';}).join('');}
function unrenderAndDestroy$1(item){item.unrender(true);}
var Fragment=function Fragment(options){this.owner=options.owner;this.isRoot=!options.owner.parentFragment;this.parent=this.isRoot?null:this.owner.parentFragment;this.ractive=options.ractive||(this.isRoot?options.owner:this.parent.ractive);this.componentParent=(this.isRoot&&this.ractive.component)?this.ractive.component.parentFragment:null;this.context=null;this.rendered=false;this.cssIds='cssIds'in options?options.cssIds:(this.parent?this.parent.cssIds:null);this.resolvers=[];this.dirty=false;this.dirtyArgs=this.dirtyValue=true;this.template=options.template||[];this.createItems();};Fragment.prototype.bind=function bind$1(context){this.context=context;this.items.forEach(bind);this.bound=true;if(this.dirty)this.update();return this;};Fragment.prototype.bubble=function bubble(){this.dirtyArgs=this.dirtyValue=true;if(!this.dirty){this.dirty=true;if(this.isRoot){if(this.ractive.component){this.ractive.component.bubble();}else if(this.bound){runloop.addFragment(this);}}else{this.owner.bubble();}}};Fragment.prototype.createItems=function createItems(){var this$1=this;this.items=this.template.map(function(template,index){return createItem({parentFragment:this$1,template:template,index:index});});};Fragment.prototype.detach=function detach(){var docFrag=createDocumentFragment();this.items.forEach(function(item){return docFrag.appendChild(item.detach());});return docFrag;};Fragment.prototype.find=function find(selector){var this$1=this;var len=this.items.length;var i;for(i=0;i<len;i+=1){var found=this$1.items[i].find(selector);if(found)return found;}};Fragment.prototype.findAll=function findAll(selector,query){var this$1=this;if(this.items){var len=this.items.length;var i;for(i=0;i<len;i+=1){var item=this$1.items[i];if(item.findAll){item.findAll(selector,query);}}}
return query;};Fragment.prototype.findComponent=function findComponent(name){var this$1=this;var len=this.items.length;var i;for(i=0;i<len;i+=1){var found=this$1.items[i].findComponent(name);if(found)return found;}};Fragment.prototype.findAllComponents=function findAllComponents(name,query){var this$1=this;if(this.items){var len=this.items.length;var i;for(i=0;i<len;i+=1){var item=this$1.items[i];if(item.findAllComponents){item.findAllComponents(name,query);}}}
return query;};Fragment.prototype.findContext=function findContext(){var fragment=this;while(!fragment.context)fragment=fragment.parent;return fragment.context;};Fragment.prototype.findNextNode=function findNextNode(item){var this$1=this;for(var i=item.index+1;i<this$1.items.length;i++){if(!this$1.items[i])continue;var node=this$1.items[i].firstNode(true);if(node)return node;}
if(this.isRoot){if(this.ractive.component){return this.ractive.component.parentFragment.findNextNode(this.ractive.component);}
return null;}
return this.owner.findNextNode(this);};Fragment.prototype.findParentNode=function findParentNode(){var fragment=this;do{if(fragment.owner.type===ELEMENT){return fragment.owner.node;}
if(fragment.isRoot&&!fragment.ractive.component){return fragment.ractive.el;}
if(fragment.owner.type===YIELDER){fragment=fragment.owner.containerFragment;}else{fragment=fragment.componentParent||fragment.parent;}}while(fragment);throw new Error('Could not find parent node');};Fragment.prototype.findRepeatingFragment=function findRepeatingFragment(){var fragment=this;while(fragment.parent&&!fragment.isIteration){fragment=fragment.parent||fragment.componentParent;}
return fragment;};Fragment.prototype.firstNode=function firstNode(skipParent){var this$1=this;var node;for(var i=0;i<this$1.items.length;i++){node=this$1.items[i].firstNode(true);if(node){return node;}}
if(skipParent)return null;return this.parent.findNextNode(this.owner);};Fragment.prototype.getArgsList=function getArgsList(){if(this.dirtyArgs){var values={};var source=processItems(this.items,values,this.ractive._guid);var parsed=parseJSON('['+source+']',values);this.argsList=parsed?parsed.value:[this.toString()];this.dirtyArgs=false;}
return this.argsList;};Fragment.prototype.rebind=function rebind$1(context){this.context=context;this.items.forEach(rebind);};Fragment.prototype.render=function render(target,occupants){if(this.rendered)throw new Error('Fragment is already rendered!');this.rendered=true;this.items.forEach(function(item){return item.render(target,occupants);});};Fragment.prototype.resetTemplate=function resetTemplate(template){var wasBound=this.bound;var wasRendered=this.rendered;if(wasBound){if(wasRendered)this.unrender(true);this.unbind();}
this.template=template;this.createItems();if(wasBound){this.bind(this.context);if(wasRendered){var parentNode=this.findParentNode();var anchor=this.parent?this.parent.findNextNode(this.owner):null;if(anchor){var docFrag=createDocumentFragment();this.render(docFrag);parentNode.insertBefore(docFrag,anchor);}else{this.render(parentNode);}}}};Fragment.prototype.resolve=function resolve(template,callback){if(!this.context){return this.parent.resolve(template,callback);}
var resolver=new ReferenceResolver(this,template,callback);this.resolvers.push(resolver);return resolver;};Fragment.prototype.toHtml=function toHtml(){return this.toString();};Fragment.prototype.toString=function toString$1$$(escape){return this.items.map(escape?toEscapedString:toString$1).join('');};Fragment.prototype.unbind=function unbind$1(){this.items.forEach(unbind);this.bound=false;return this;};Fragment.prototype.unrender=function unrender$1(shouldDestroy){this.items.forEach(shouldDestroy?unrenderAndDestroy$1:unrender);this.rendered=false;};Fragment.prototype.update=function update$1(){if(this.dirty&&!this.updating){this.dirty=false;this.updating=true;this.items.forEach(update);this.updating=false;}};Fragment.prototype.valueOf=function valueOf(){if(this.items.length===1){return this.items[0].valueOf();}
if(this.dirtyValue){var values={};var source=processItems(this.items,values,this.ractive._guid);var parsed=parseJSON(source,values);this.value=parsed?parsed.value:this.toString();this.dirtyValue=false;}
return this.value;};function Ractive$resetTemplate(template){templateConfigurator.init(null,this,{template:template});var transitionsEnabled=this.transitionsEnabled;this.transitionsEnabled=false;var component=this.component;if(component)component.shouldDestroy=true;this.unrender();if(component)component.shouldDestroy=false;this.fragment.unbind().unrender(true);this.fragment=new Fragment({template:this.template,root:this,owner:this});var docFrag=createDocumentFragment();this.fragment.bind(this.viewmodel).render(docFrag);this.el.insertBefore(docFrag,this.anchor);this.transitionsEnabled=transitionsEnabled;}
var reverse=makeArrayMethod('reverse');function Ractive$set(keypath,value){var promise=runloop.start(this,true);if(isObject(keypath)){var map=keypath;for(var k in map){if(map.hasOwnProperty(k)){set(this,k,map[k]);}}}
else{set(this,keypath,value);}
runloop.end();return promise;}
function set(ractive,keypath,value){if(typeof value==='function')value=bind$1(value,ractive);if(/\*/.test(keypath)){ractive.viewmodel.findMatches(splitKeypathI(keypath)).forEach(function(model){model.set(value);});}else{var model=ractive.viewmodel.joinAll(splitKeypathI(keypath));model.set(value);}}
var shift=makeArrayMethod('shift');var sort=makeArrayMethod('sort');var splice=makeArrayMethod('splice');function Ractive$subtract(keypath,d){return add(this,keypath,(d===undefined?-1:-d));}
var teardownHook$1=new Hook('teardown');function Ractive$teardown(){var this$1=this;this.fragment.unbind();this.viewmodel.teardown();this._observers.forEach(cancel);if(this.fragment.rendered&&this.el.__ractive_instances__){removeFromArray(this.el.__ractive_instances__,this);}
this.shouldDestroy=true;var promise=(this.fragment.rendered?this.unrender():Promise$1.resolve());Object.keys(this._links).forEach(function(k){return this$1._links[k].unlink();});teardownHook$1.fire(this);return promise;}
function Ractive$toggle(keypath){if(typeof keypath!=='string'){throw new TypeError(badArguments);}
var changes;if(/\*/.test(keypath)){changes={};this.viewmodel.findMatches(splitKeypathI(keypath)).forEach(function(model){changes[model.getKeypath()]=!model.get();});return this.set(changes);}
return this.set(keypath,!this.get(keypath));}
function Ractive$toCSS(){var cssIds=[this.cssId].concat(this.findAllComponents().map(function(c){return c.cssId;}));var uniqueCssIds=Object.keys(cssIds.reduce(function(ids,id){return(ids[id]=true,ids);},{}));return getCSS(uniqueCssIds);}
function Ractive$toHTML(){return this.fragment.toString(true);}
function Ractive$transition(name,node,params){if(node instanceof HTMLElement){}
else if(isObject(node)){params=node;}
node=node||this.event.node;if(!node){fatal(("No node was supplied for transition "+name));}
var transition=new Transition(this,node,name,params);var promise=runloop.start(this,true);runloop.registerTransition(transition);runloop.end();return promise;}
function unlink(here){var ln=this._links[here];if(ln){ln.unlink();delete this._links[here];return this.set(here,ln.intialValue);}else{return Promise$1.resolve(true);}}
var unrenderHook$1=new Hook('unrender');function Ractive$unrender(){if(!this.fragment.rendered){warnIfDebug('ractive.unrender() was called on a Ractive instance that was not rendered');return Promise$1.resolve();}
var promise=runloop.start(this,true);var shouldDestroy=!this.component||this.component.shouldDestroy||this.shouldDestroy;this.fragment.unrender(shouldDestroy);removeFromArray(this.el.__ractive_instances__,this);unrenderHook$1.fire(this);runloop.end();return promise;}
var unshift=makeArrayMethod('unshift');var updateHook=new Hook('update');function Ractive$update(keypath){if(keypath)keypath=splitKeypathI(keypath);var model=keypath?this.viewmodel.joinAll(keypath):this.viewmodel;if(model.parent&&model.parent.wrapper)return this.update(model.parent.getKeypath(this));var promise=runloop.start(this,true);model.mark();model.registerChange(model.getKeypath(),model.get());if(keypath){var parent=model.parent;while(keypath.length&&parent){if(parent.clearUnresolveds)parent.clearUnresolveds(keypath.pop());parent=parent.parent;}}
model.notifyUpstream();runloop.end();updateHook.fire(this,model);return promise;}
function Ractive$updateModel(keypath,cascade){var promise=runloop.start(this,true);if(!keypath){this.viewmodel.updateFromBindings(true);}else{this.viewmodel.joinAll(splitKeypathI(keypath)).updateFromBindings(cascade!==false);}
runloop.end();return promise;}
var proto={add:Ractive$add,animate:Ractive$animate,detach:Ractive$detach,find:Ractive$find,findAll:Ractive$findAll,findAllComponents:Ractive$findAllComponents,findComponent:Ractive$findComponent,findContainer:Ractive$findContainer,findParent:Ractive$findParent,fire:Ractive$fire,get:Ractive$get,insert:Ractive$insert,link:link,merge:Ractive$merge,observe:observe,observeList:observeList,observeOnce:observeOnce,off:Ractive$off,on:Ractive$on,once:Ractive$once,pop:pop,push:push,render:Ractive$render,reset:Ractive$reset,resetPartial:resetPartial,resetTemplate:Ractive$resetTemplate,reverse:reverse,set:Ractive$set,shift:shift,sort:sort,splice:splice,subtract:Ractive$subtract,teardown:Ractive$teardown,toggle:Ractive$toggle,toCSS:Ractive$toCSS,toCss:Ractive$toCSS,toHTML:Ractive$toHTML,toHtml:Ractive$toHTML,transition:Ractive$transition,unlink:unlink,unrender:Ractive$unrender,unshift:unshift,update:Ractive$update,updateModel:Ractive$updateModel};function wrap$1(method,superMethod,force){if(force||needsSuper(method,superMethod)){return function(){var hasSuper=('_super'in this),_super=this._super,result;this._super=superMethod;result=method.apply(this,arguments);if(hasSuper){this._super=_super;}
return result;};}
else{return method;}}
function needsSuper(method,superMethod){return typeof superMethod==='function'&&/_super/.test(method);}
function unwrap(Child){var options={};while(Child){addRegistries(Child,options);addOtherOptions(Child,options);if(Child._Parent!==Ractive){Child=Child._Parent;}else{Child=false;}}
return options;}
function addRegistries(Child,options){registries.forEach(function(r){addRegistry(r.useDefaults?Child.prototype:Child,options,r.name);});}
function addRegistry(target,options,name){var registry,keys=Object.keys(target[name]);if(!keys.length){return;}
if(!(registry=options[name])){registry=options[name]={};}
keys.filter(function(key){return!(key in registry);}).forEach(function(key){return registry[key]=target[name][key];});}
function addOtherOptions(Child,options){Object.keys(Child.prototype).forEach(function(key){if(key==='computed'){return;}
var value=Child.prototype[key];if(!(key in options)){options[key]=value._method?value._method:value;}
else if(typeof options[key]==='function'&&typeof value==='function'&&options[key]._method){var result,needsSuper=value._method;if(needsSuper){value=value._method;}
result=wrap$1(options[key]._method,value);if(needsSuper){result._method=result;}
options[key]=result;}});}
function extend(){var options=[],len=arguments.length;while(len--)options[len]=arguments[len];if(!options.length){return extendOne(this);}else{return options.reduce(extendOne,this);}}
function extendOne(Parent,options){if(options===void 0)options={};var Child,proto;if(options.prototype instanceof Ractive){options=unwrap(options);}
Child=function(options){if(!(this instanceof Child))return new Child(options);construct(this,options||{});initialise(this,options||{},{});};proto=create(Parent.prototype);proto.constructor=Child;defineProperties(Child,{defaults:{value:proto},extend:{value:extend,writable:true,configurable:true},_Parent:{value:Parent}});config.extend(Parent,proto,options);dataConfigurator.extend(Parent,proto,options);if(options.computed){proto.computed=extendObj(create(Parent.prototype.computed),options.computed);}
Child.prototype=proto;return Child;}
function getNodeInfo(node){if(!node||!node._ractive)return{};var storage=node._ractive;var ractive=storage.fragment.ractive;var ref=gatherRefs(storage.fragment),key=ref.key,index=ref.index;var context=storage.fragment.findContext();return{ractive:ractive,keypath:context.getKeypath(ractive),rootpath:context.getKeypath(),index:index,key:key};}
function joinKeys(){var keys=[],len=arguments.length;while(len--)keys[len]=arguments[len];return keys.map(escapeKey).join('.');}
function splitKeypath(keypath){return splitKeypathI(keypath).map(unescapeKey);}
var FUNCTION='function';if(typeof Date.now!==FUNCTION||typeof String.prototype.trim!==FUNCTION||typeof Object.keys!==FUNCTION||typeof Array.prototype.indexOf!==FUNCTION||typeof Array.prototype.forEach!==FUNCTION||typeof Array.prototype.map!==FUNCTION||typeof Array.prototype.filter!==FUNCTION||(win&&typeof win.addEventListener!==FUNCTION)){throw new Error('It looks like you\'re attempting to use Ractive.js in an older browser. You\'ll need to use one of the \'legacy builds\' in order to continue - see http://docs.ractivejs.org/latest/legacy-builds for more information.');}
function Ractive(options){if(!(this instanceof Ractive))return new Ractive(options);construct(this,options||{});initialise(this,options||{},{});}
extendObj(Ractive.prototype,proto,defaults);Ractive.prototype.constructor=Ractive;Ractive.defaults=Ractive.prototype;defineProperties(Ractive,{DEBUG:{writable:true,value:true},DEBUG_PROMISES:{writable:true,value:true},extend:{value:extend},escapeKey:{value:escapeKey},getNodeInfo:{value:getNodeInfo},joinKeys:{value:joinKeys},parse:{value:parse},splitKeypath:{value:splitKeypath},unescapeKey:{value:unescapeKey},getCSS:{value:getCSS},Promise:{value:Promise$1},enhance:{writable:true,value:false},svg:{value:svg},magic:{value:magicSupported},VERSION:{value:'0.8.0-edge'},adaptors:{writable:true,value:{}},components:{writable:true,value:{}},decorators:{writable:true,value:{}},easing:{writable:true,value:easing},events:{writable:true,value:{}},interpolators:{writable:true,value:interpolators},partials:{writable:true,value:{}},transitions:{writable:true,value:{}}});return Ractive;}));(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define('ractive-events-keys',['exports'],factory):factory(global.Ractive.events)}(this,function(exports){'use strict';function makeKeyDefinition(code){return function(node,fire){function keydownHandler(event){var which=event.which||event.keyCode;if(which===code){event.preventDefault();fire({node:node,original:event});}}
node.addEventListener('keydown',keydownHandler,false);return{teardown:function teardown(){node.removeEventListener('keydown',keydownHandler,false);}};};}
var enter=makeKeyDefinition(13);var tab=makeKeyDefinition(9);var ractive_events_keys__escape=makeKeyDefinition(27);var space=makeKeyDefinition(32);var leftarrow=makeKeyDefinition(37);var rightarrow=makeKeyDefinition(39);var downarrow=makeKeyDefinition(40);var uparrow=makeKeyDefinition(38);exports.enter=enter;exports.tab=tab;exports.escape=ractive_events_keys__escape;exports.space=space;exports.leftarrow=leftarrow;exports.rightarrow=rightarrow;exports.downarrow=downarrow;exports.uparrow=uparrow;}));;(function(root,factory){if(typeof define==='function'&&define.amd){define('ractive-promise-alt',['ractive'],factory);}else if(typeof exports==='object'){module.exports=factory(require('ractive'));}else{factory(root.Ractive);}}(this,function(Ractive){Ractive.adaptors['promise-alt']={filter:isPromise,wrap:wrap};function isPromise(obj){return obj&&typeof obj.then==='function';}
function wrap(ractive,obj,keypath,prefixer){var data={};function update(values){data=values;ractive.set(prefixer(values));}
ractive.set(keypath,{});update({pending:true});obj.then(function(result){update({pending:void 0,progress:void 0,resolved:true,result:result});},function(err){update({pending:void 0,progress:void 0,error:err});},function(prog){update({pending:true,progress:prog});});return{get:function(){return data;},set:function(){},reset:function(){return false;},teardown:function(){}};}}));
/*!

	rv.js - v0.1.6 - 2014-12-28
	==========================================================

	https://github.com/ractivejs/rv
	MIT licensed.

*/
define('rv',['ractive'],function(Ractive){var amd_loader,tosource,rv;amd_loader=function(){var precompiled;var loader=function(pluginId,ext,allowExts,compile){if(arguments.length==3){compile=allowExts;allowExts=undefined;}else if(arguments.length==2){compile=ext;ext=allowExts=undefined;}
return{buildCache:{},load:function(name,req,load,config){var path=req.toUrl(name);var queryString='';if(path.indexOf('?')!=-1){queryString=path.substr(path.indexOf('?'));path=path.substr(0,path.length-queryString.length);}
if(config.precompiled instanceof Array){for(var i=0;i<config.precompiled.length;i++)
if(path.substr(0,config.precompiled[i].length)==config.precompiled[i])
return require([path+'.'+pluginId+'.js'+queryString],load,load.error);}else if(config.precompiled===true)
return require([path+'.'+pluginId+'.js'+queryString],load,load.error);if(ext&&name.substr(0,1)!='/'&&!name.match(/:\/\//)){var validExt=false;if(allowExts){for(var i=0;i<allowExts.length;i++){if(name.substr(name.length-allowExts[i].length-1)=='.'+allowExts[i])
validExt=true;}}
if(!validExt)
path+='.'+ext+queryString;else
path+=queryString;}else{path+=queryString;}
var self=this;loader.fetch(path,function(source){compile(name,source,req,function(compiled){if(typeof compiled=='string'){if(config.isBuild)
self.buildCache[name]=compiled;load.fromText(compiled);}else
load(compiled);},load.error,config);},load.error);},write:function(pluginName,moduleName,write){var compiled=this.buildCache[moduleName];if(compiled)
write.asModule(pluginName+'!'+moduleName,compiled);},writeFile:function(pluginName,name,req,write){write.asModule(pluginName+'!'+name,req.toUrl(name+'.'+pluginId+'.js'),this.buildCache[name]);}};};if(typeof window!='undefined'){var progIds=['Msxml2.XMLHTTP','Microsoft.XMLHTTP','Msxml2.XMLHTTP.4.0'];var getXhr=function(path){var sameDomain=true,domainCheck=/^(\w+:)?\/\/([^\/]+)/.exec(path);if(typeof window!='undefined'&&domainCheck){sameDomain=domainCheck[2]===window.location.host;if(domainCheck[1])
sameDomain&=domainCheck[1]===window.location.protocol;}
var xhr;if(typeof XMLHttpRequest!=='undefined')
xhr=new XMLHttpRequest();else{var progId;for(var i=0;i<3;i+=1){progId=progIds[i];try{xhr=new ActiveXObject(progId);}catch(e){}
if(xhr){progIds=[progId];break;}}}
if(!sameDomain){if(typeof XDomainRequest!='undefined')
xhr=new XDomainRequest();else if(!('withCredentials'in xhr))
throw new Error('getXhr(): Cross Origin XHR not supported.');}
if(!xhr)
throw new Error('getXhr(): XMLHttpRequest not available');return xhr;};loader.fetch=function(url,callback,errback){var xhr=getXhr(url);xhr.open('GET',url,!requirejs.inlineRequire);xhr.onreadystatechange=function(evt){var status,err;if(xhr.readyState===4){status=xhr.status;if(status>399&&status<600){err=new Error(url+' HTTP status: '+status);err.xhr=xhr;if(errback)
errback(err);}else{if(xhr.responseText=='')
return errback(new Error(url+' empty response'));callback(xhr.responseText);}}};xhr.send(null);};}else if(typeof process!=='undefined'&&process.versions&&!!process.versions.node){var fs=requirejs.nodeRequire('fs');loader.fetch=function(path,callback,errback){try{callback(fs.readFileSync(path,'utf8'));}catch(err){errback(err);}};}else if(typeof Packages!=='undefined'){loader.fetch=function(path,callback,errback){var stringBuffer,line,encoding='utf-8',file=new java.io.File(path),lineSeparator=java.lang.System.getProperty('line.separator'),input=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file),encoding)),content='';try{stringBuffer=new java.lang.StringBuffer();line=input.readLine();if(line&&line.length()&&line.charAt(0)===65279){line=line.substring(1);}
stringBuffer.append(line);while((line=input.readLine())!==null){stringBuffer.append(lineSeparator);stringBuffer.append(line);}
content=String(stringBuffer.toString());}catch(err){if(errback)
errback(err);}finally{input.close();}
callback(content);};}else{loader.fetch=function(){throw new Error('Environment unsupported.');};}
return loader;}();tosource=function(){var KEYWORD_REGEXP=/^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|undefined|var|void|volatile|while|with)$/;return function(object,filter,indent,startingIndent){var seen=[];return walk(object,filter,indent===undefined?'  ':indent||'',startingIndent||'',seen);function walk(object,filter,indent,currentIndent,seen){var nextIndent=currentIndent+indent;object=filter?filter(object):object;switch(typeof object){case'string':return JSON.stringify(object);case'boolean':case'number':case'undefined':return''+object;case'function':return object.toString();}
if(object===null)
return'null';if(object instanceof RegExp)
return object.toString();if(object instanceof Date)
return'new Date('+object.getTime()+')';var seenIndex=seen.indexOf(object)+1;if(seenIndex>0)
return'{$circularReference:'+seenIndex+'}';seen.push(object);function join(elements){return indent.slice(1)+elements.join(','+(indent&&'\n')+nextIndent)+(indent?' ':'');}
if(Array.isArray(object)){return'['+join(object.map(function(element){return walk(element,filter,indent,nextIndent,seen.slice());}))+']';}
var keys=Object.keys(object);return keys.length?'{'+join(keys.map(function(key){return(legalKey(key)?key:JSON.stringify(key))+':'+walk(object[key],filter,indent,nextIndent,seen.slice());}))+'}':'{}';}};function legalKey(string){return /^[a-z_$][0-9a-z_$]*$/gi.test(string)&&!KEYWORD_REGEXP.test(string);}}();rv=function(amdLoader,toSource){return amdLoader('rv','html',function(name,source,req,callback,errback,config){var parsed=Ractive.parse(source);if(!config.isBuild){callback(parsed);}else{callback('define("rv!'+name+'",function(){return '+toSource(parsed)+';})');}});}(amd_loader,tosource);return rv;});(function(root,factory){if(typeof define==='function'&&define.amd){define('score.ajax.rest',['bluebird','score.init','score.ajax'],factory);}else if(typeof module==='object'&&module.exports){factory(require('bluebird'),require('score.init'),require('score.ajax'));}else{factory(Promise,root.score);}})(this,function(Promise,score){score.extend('ajax.rest',['ajax'],function(){var getJSONOptions=function(options){var options=options||{};options.headers=options.headers||{};options.headers['Content-Type']='application/json';return options;};var rest=function(){};rest.get=function(url,options){options=options||{};options.method='GET';return score.ajax(url,options);};rest.getJSON=function(url,options){options=getJSONOptions(options);return rest.get(url,options);};rest.post=function(url,options){options=options||{};options.method='POST';return score.ajax(url,options);};rest.postJSON=function(url,data,options){options=getJSONOptions(options);options.data=JSON.stringify(data);return rest.post(url,options);};rest.put=function(url,options){options=options||{};options.method='PUT';return score.ajax(url,options);};rest.putJSON=function(url,data,options){options=getJSONOptions(options);options.data=JSON.stringify(data);return rest.put(url,options);};rest.delete=function(url,options){options=options||{};options.method='DELETE';return score.ajax(url,options);};rest.deleteJSON=function(url,options){options=getJSONOptions(options);return rest.delete(url,options);};return rest;});});
/*!
 * Swiper 3.4.2
 * Most modern mobile touch slider and framework with hardware accelerated transitions
 *
 * http://www.idangero.us/swiper/
 *
 * Copyright 2017, Vladimir Kharlampidi
 * The iDangero.us
 * http://www.idangero.us/
 *
 * Licensed under MIT
 *
 * Released on: March 10, 2017
 */
(function(){'use strict';var $;var Swiper=function(container,params){if(!(this instanceof Swiper))return new Swiper(container,params);var defaults={direction:'horizontal',touchEventsTarget:'container',initialSlide:0,speed:300,autoplay:false,autoplayDisableOnInteraction:true,autoplayStopOnLast:false,iOSEdgeSwipeDetection:false,iOSEdgeSwipeThreshold:20,freeMode:false,freeModeMomentum:true,freeModeMomentumRatio:1,freeModeMomentumBounce:true,freeModeMomentumBounceRatio:1,freeModeMomentumVelocityRatio:1,freeModeSticky:false,freeModeMinimumVelocity:0.02,autoHeight:false,setWrapperSize:false,virtualTranslate:false,effect:'slide',coverflow:{rotate:50,stretch:0,depth:100,modifier:1,slideShadows:true},flip:{slideShadows:true,limitRotation:true},cube:{slideShadows:true,shadow:true,shadowOffset:20,shadowScale:0.94},fade:{crossFade:false},parallax:false,zoom:false,zoomMax:3,zoomMin:1,zoomToggle:true,scrollbar:null,scrollbarHide:true,scrollbarDraggable:false,scrollbarSnapOnRelease:false,keyboardControl:false,mousewheelControl:false,mousewheelReleaseOnEdges:false,mousewheelInvert:false,mousewheelForceToAxis:false,mousewheelSensitivity:1,mousewheelEventsTarged:'container',hashnav:false,hashnavWatchState:false,history:false,replaceState:false,breakpoints:undefined,spaceBetween:0,slidesPerView:1,slidesPerColumn:1,slidesPerColumnFill:'column',slidesPerGroup:1,centeredSlides:false,slidesOffsetBefore:0,slidesOffsetAfter:0,roundLengths:false,touchRatio:1,touchAngle:45,simulateTouch:true,shortSwipes:true,longSwipes:true,longSwipesRatio:0.5,longSwipesMs:300,followFinger:true,onlyExternal:false,threshold:0,touchMoveStopPropagation:true,touchReleaseOnEdges:false,uniqueNavElements:true,pagination:null,paginationElement:'span',paginationClickable:false,paginationHide:false,paginationBulletRender:null,paginationProgressRender:null,paginationFractionRender:null,paginationCustomRender:null,paginationType:'bullets',resistance:true,resistanceRatio:0.85,nextButton:null,prevButton:null,watchSlidesProgress:false,watchSlidesVisibility:false,grabCursor:false,preventClicks:true,preventClicksPropagation:true,slideToClickedSlide:false,lazyLoading:false,lazyLoadingInPrevNext:false,lazyLoadingInPrevNextAmount:1,lazyLoadingOnTransitionStart:false,preloadImages:true,updateOnImagesReady:true,loop:false,loopAdditionalSlides:0,loopedSlides:null,control:undefined,controlInverse:false,controlBy:'slide',normalizeSlideIndex:true,allowSwipeToPrev:true,allowSwipeToNext:true,swipeHandler:null,noSwiping:true,noSwipingClass:'swiper-no-swiping',passiveListeners:true,containerModifierClass:'swiper-container-',slideClass:'swiper-slide',slideActiveClass:'swiper-slide-active',slideDuplicateActiveClass:'swiper-slide-duplicate-active',slideVisibleClass:'swiper-slide-visible',slideDuplicateClass:'swiper-slide-duplicate',slideNextClass:'swiper-slide-next',slideDuplicateNextClass:'swiper-slide-duplicate-next',slidePrevClass:'swiper-slide-prev',slideDuplicatePrevClass:'swiper-slide-duplicate-prev',wrapperClass:'swiper-wrapper',bulletClass:'swiper-pagination-bullet',bulletActiveClass:'swiper-pagination-bullet-active',buttonDisabledClass:'swiper-button-disabled',paginationCurrentClass:'swiper-pagination-current',paginationTotalClass:'swiper-pagination-total',paginationHiddenClass:'swiper-pagination-hidden',paginationProgressbarClass:'swiper-pagination-progressbar',paginationClickableClass:'swiper-pagination-clickable',paginationModifierClass:'swiper-pagination-',lazyLoadingClass:'swiper-lazy',lazyStatusLoadingClass:'swiper-lazy-loading',lazyStatusLoadedClass:'swiper-lazy-loaded',lazyPreloaderClass:'swiper-lazy-preloader',notificationClass:'swiper-notification',preloaderClass:'preloader',zoomContainerClass:'swiper-zoom-container',observer:false,observeParents:false,a11y:false,prevSlideMessage:'Previous slide',nextSlideMessage:'Next slide',firstSlideMessage:'This is the first slide',lastSlideMessage:'This is the last slide',paginationBulletMessage:'Go to slide {{index}}',runCallbacksOnInit:true};var initialVirtualTranslate=params&&params.virtualTranslate;params=params||{};var originalParams={};for(var param in params){if(typeof params[param]==='object'&&params[param]!==null&&!(params[param].nodeType||params[param]===window||params[param]===document||(typeof Dom7!=='undefined'&&params[param]instanceof Dom7)||(typeof jQuery!=='undefined'&&params[param]instanceof jQuery))){originalParams[param]={};for(var deepParam in params[param]){originalParams[param][deepParam]=params[param][deepParam];}}
else{originalParams[param]=params[param];}}
for(var def in defaults){if(typeof params[def]==='undefined'){params[def]=defaults[def];}
else if(typeof params[def]==='object'){for(var deepDef in defaults[def]){if(typeof params[def][deepDef]==='undefined'){params[def][deepDef]=defaults[def][deepDef];}}}}
var s=this;s.params=params;s.originalParams=originalParams;s.classNames=[];if(typeof $!=='undefined'&&typeof Dom7!=='undefined'){$=Dom7;}
if(typeof $==='undefined'){if(typeof Dom7==='undefined'){$=window.Dom7||window.Zepto||window.jQuery;}
else{$=Dom7;}
if(!$)return;}
s.$=$;s.currentBreakpoint=undefined;s.getActiveBreakpoint=function(){if(!s.params.breakpoints)return false;var breakpoint=false;var points=[],point;for(point in s.params.breakpoints){if(s.params.breakpoints.hasOwnProperty(point)){points.push(point);}}
points.sort(function(a,b){return parseInt(a,10)>parseInt(b,10);});for(var i=0;i<points.length;i++){point=points[i];if(point>=window.innerWidth&&!breakpoint){breakpoint=point;}}
return breakpoint||'max';};s.setBreakpoint=function(){var breakpoint=s.getActiveBreakpoint();if(breakpoint&&s.currentBreakpoint!==breakpoint){var breakPointsParams=breakpoint in s.params.breakpoints?s.params.breakpoints[breakpoint]:s.originalParams;var needsReLoop=s.params.loop&&(breakPointsParams.slidesPerView!==s.params.slidesPerView);for(var param in breakPointsParams){s.params[param]=breakPointsParams[param];}
s.currentBreakpoint=breakpoint;if(needsReLoop&&s.destroyLoop){s.reLoop(true);}}};if(s.params.breakpoints){s.setBreakpoint();}
s.container=$(container);if(s.container.length===0)return;if(s.container.length>1){var swipers=[];s.container.each(function(){var container=this;swipers.push(new Swiper(this,params));});return swipers;}
s.container[0].swiper=s;s.container.data('swiper',s);s.classNames.push(s.params.containerModifierClass+s.params.direction);if(s.params.freeMode){s.classNames.push(s.params.containerModifierClass+'free-mode');}
if(!s.support.flexbox){s.classNames.push(s.params.containerModifierClass+'no-flexbox');s.params.slidesPerColumn=1;}
if(s.params.autoHeight){s.classNames.push(s.params.containerModifierClass+'autoheight');}
if(s.params.parallax||s.params.watchSlidesVisibility){s.params.watchSlidesProgress=true;}
if(s.params.touchReleaseOnEdges){s.params.resistanceRatio=0;}
if(['cube','coverflow','flip'].indexOf(s.params.effect)>=0){if(s.support.transforms3d){s.params.watchSlidesProgress=true;s.classNames.push(s.params.containerModifierClass+'3d');}
else{s.params.effect='slide';}}
if(s.params.effect!=='slide'){s.classNames.push(s.params.containerModifierClass+s.params.effect);}
if(s.params.effect==='cube'){s.params.resistanceRatio=0;s.params.slidesPerView=1;s.params.slidesPerColumn=1;s.params.slidesPerGroup=1;s.params.centeredSlides=false;s.params.spaceBetween=0;s.params.virtualTranslate=true;}
if(s.params.effect==='fade'||s.params.effect==='flip'){s.params.slidesPerView=1;s.params.slidesPerColumn=1;s.params.slidesPerGroup=1;s.params.watchSlidesProgress=true;s.params.spaceBetween=0;if(typeof initialVirtualTranslate==='undefined'){s.params.virtualTranslate=true;}}
if(s.params.grabCursor&&s.support.touch){s.params.grabCursor=false;}
s.wrapper=s.container.children('.'+s.params.wrapperClass);if(s.params.pagination){s.paginationContainer=$(s.params.pagination);if(s.params.uniqueNavElements&&typeof s.params.pagination==='string'&&s.paginationContainer.length>1&&s.container.find(s.params.pagination).length===1){s.paginationContainer=s.container.find(s.params.pagination);}
if(s.params.paginationType==='bullets'&&s.params.paginationClickable){s.paginationContainer.addClass(s.params.paginationModifierClass+'clickable');}
else{s.params.paginationClickable=false;}
s.paginationContainer.addClass(s.params.paginationModifierClass+s.params.paginationType);}
if(s.params.nextButton||s.params.prevButton){if(s.params.nextButton){s.nextButton=$(s.params.nextButton);if(s.params.uniqueNavElements&&typeof s.params.nextButton==='string'&&s.nextButton.length>1&&s.container.find(s.params.nextButton).length===1){s.nextButton=s.container.find(s.params.nextButton);}}
if(s.params.prevButton){s.prevButton=$(s.params.prevButton);if(s.params.uniqueNavElements&&typeof s.params.prevButton==='string'&&s.prevButton.length>1&&s.container.find(s.params.prevButton).length===1){s.prevButton=s.container.find(s.params.prevButton);}}}
s.isHorizontal=function(){return s.params.direction==='horizontal';};s.rtl=s.isHorizontal()&&(s.container[0].dir.toLowerCase()==='rtl'||s.container.css('direction')==='rtl');if(s.rtl){s.classNames.push(s.params.containerModifierClass+'rtl');}
if(s.rtl){s.wrongRTL=s.wrapper.css('display')==='-webkit-box';}
if(s.params.slidesPerColumn>1){s.classNames.push(s.params.containerModifierClass+'multirow');}
if(s.device.android){s.classNames.push(s.params.containerModifierClass+'android');}
s.container.addClass(s.classNames.join(' '));s.translate=0;s.progress=0;s.velocity=0;s.lockSwipeToNext=function(){s.params.allowSwipeToNext=false;if(s.params.allowSwipeToPrev===false&&s.params.grabCursor){s.unsetGrabCursor();}};s.lockSwipeToPrev=function(){s.params.allowSwipeToPrev=false;if(s.params.allowSwipeToNext===false&&s.params.grabCursor){s.unsetGrabCursor();}};s.lockSwipes=function(){s.params.allowSwipeToNext=s.params.allowSwipeToPrev=false;if(s.params.grabCursor)s.unsetGrabCursor();};s.unlockSwipeToNext=function(){s.params.allowSwipeToNext=true;if(s.params.allowSwipeToPrev===true&&s.params.grabCursor){s.setGrabCursor();}};s.unlockSwipeToPrev=function(){s.params.allowSwipeToPrev=true;if(s.params.allowSwipeToNext===true&&s.params.grabCursor){s.setGrabCursor();}};s.unlockSwipes=function(){s.params.allowSwipeToNext=s.params.allowSwipeToPrev=true;if(s.params.grabCursor)s.setGrabCursor();};function round(a){return Math.floor(a);}
s.setGrabCursor=function(moving){s.container[0].style.cursor='move';s.container[0].style.cursor=moving?'-webkit-grabbing':'-webkit-grab';s.container[0].style.cursor=moving?'-moz-grabbin':'-moz-grab';s.container[0].style.cursor=moving?'grabbing':'grab';};s.unsetGrabCursor=function(){s.container[0].style.cursor='';};if(s.params.grabCursor){s.setGrabCursor();}
s.imagesToLoad=[];s.imagesLoaded=0;s.loadImage=function(imgElement,src,srcset,sizes,checkForComplete,callback){var image;function onReady(){if(callback)callback();}
if(!imgElement.complete||!checkForComplete){if(src){image=new window.Image();image.onload=onReady;image.onerror=onReady;if(sizes){image.sizes=sizes;}
if(srcset){image.srcset=srcset;}
if(src){image.src=src;}}else{onReady();}}else{onReady();}};s.preloadImages=function(){s.imagesToLoad=s.container.find('img');function _onReady(){if(typeof s==='undefined'||s===null||!s)return;if(s.imagesLoaded!==undefined)s.imagesLoaded++;if(s.imagesLoaded===s.imagesToLoad.length){if(s.params.updateOnImagesReady)s.update();s.emit('onImagesReady',s);}}
for(var i=0;i<s.imagesToLoad.length;i++){s.loadImage(s.imagesToLoad[i],(s.imagesToLoad[i].currentSrc||s.imagesToLoad[i].getAttribute('src')),(s.imagesToLoad[i].srcset||s.imagesToLoad[i].getAttribute('srcset')),s.imagesToLoad[i].sizes||s.imagesToLoad[i].getAttribute('sizes'),true,_onReady);}};s.autoplayTimeoutId=undefined;s.autoplaying=false;s.autoplayPaused=false;function autoplay(){var autoplayDelay=s.params.autoplay;var activeSlide=s.slides.eq(s.activeIndex);if(activeSlide.attr('data-swiper-autoplay')){autoplayDelay=activeSlide.attr('data-swiper-autoplay')||s.params.autoplay;}
s.autoplayTimeoutId=setTimeout(function(){if(s.params.loop){s.fixLoop();s._slideNext();s.emit('onAutoplay',s);}
else{if(!s.isEnd){s._slideNext();s.emit('onAutoplay',s);}
else{if(!params.autoplayStopOnLast){s._slideTo(0);s.emit('onAutoplay',s);}
else{s.stopAutoplay();}}}},autoplayDelay);}
s.startAutoplay=function(){if(typeof s.autoplayTimeoutId!=='undefined')return false;if(!s.params.autoplay)return false;if(s.autoplaying)return false;s.autoplaying=true;s.emit('onAutoplayStart',s);autoplay();};s.stopAutoplay=function(internal){if(!s.autoplayTimeoutId)return;if(s.autoplayTimeoutId)clearTimeout(s.autoplayTimeoutId);s.autoplaying=false;s.autoplayTimeoutId=undefined;s.emit('onAutoplayStop',s);};s.pauseAutoplay=function(speed){if(s.autoplayPaused)return;if(s.autoplayTimeoutId)clearTimeout(s.autoplayTimeoutId);s.autoplayPaused=true;if(speed===0){s.autoplayPaused=false;autoplay();}
else{s.wrapper.transitionEnd(function(){if(!s)return;s.autoplayPaused=false;if(!s.autoplaying){s.stopAutoplay();}
else{autoplay();}});}};s.minTranslate=function(){return(-s.snapGrid[0]);};s.maxTranslate=function(){return(-s.snapGrid[s.snapGrid.length-1]);};s.updateAutoHeight=function(){var activeSlides=[];var newHeight=0;var i;if(s.params.slidesPerView!=='auto'&&s.params.slidesPerView>1){for(i=0;i<Math.ceil(s.params.slidesPerView);i++){var index=s.activeIndex+i;if(index>s.slides.length)break;activeSlides.push(s.slides.eq(index)[0]);}}else{activeSlides.push(s.slides.eq(s.activeIndex)[0]);}
for(i=0;i<activeSlides.length;i++){if(typeof activeSlides[i]!=='undefined'){var height=activeSlides[i].offsetHeight;newHeight=height>newHeight?height:newHeight;}}
if(newHeight)s.wrapper.css('height',newHeight+'px');};s.updateContainerSize=function(){var width,height;if(typeof s.params.width!=='undefined'){width=s.params.width;}
else{width=s.container[0].clientWidth;}
if(typeof s.params.height!=='undefined'){height=s.params.height;}
else{height=s.container[0].clientHeight;}
if(width===0&&s.isHorizontal()||height===0&&!s.isHorizontal()){return;}
width=width-parseInt(s.container.css('padding-left'),10)-parseInt(s.container.css('padding-right'),10);height=height-parseInt(s.container.css('padding-top'),10)-parseInt(s.container.css('padding-bottom'),10);s.width=width;s.height=height;s.size=s.isHorizontal()?s.width:s.height;};s.updateSlidesSize=function(){s.slides=s.wrapper.children('.'+s.params.slideClass);s.snapGrid=[];s.slidesGrid=[];s.slidesSizesGrid=[];var spaceBetween=s.params.spaceBetween,slidePosition=-s.params.slidesOffsetBefore,i,prevSlideSize=0,index=0;if(typeof s.size==='undefined')return;if(typeof spaceBetween==='string'&&spaceBetween.indexOf('%')>=0){spaceBetween=parseFloat(spaceBetween.replace('%',''))/ 100*s.size;}
s.virtualSize=-spaceBetween;if(s.rtl)s.slides.css({marginLeft:'',marginTop:''});else s.slides.css({marginRight:'',marginBottom:''});var slidesNumberEvenToRows;if(s.params.slidesPerColumn>1){if(Math.floor(s.slides.length / s.params.slidesPerColumn)===s.slides.length / s.params.slidesPerColumn){slidesNumberEvenToRows=s.slides.length;}
else{slidesNumberEvenToRows=Math.ceil(s.slides.length / s.params.slidesPerColumn)*s.params.slidesPerColumn;}
if(s.params.slidesPerView!=='auto'&&s.params.slidesPerColumnFill==='row'){slidesNumberEvenToRows=Math.max(slidesNumberEvenToRows,s.params.slidesPerView*s.params.slidesPerColumn);}}
var slideSize;var slidesPerColumn=s.params.slidesPerColumn;var slidesPerRow=slidesNumberEvenToRows / slidesPerColumn;var numFullColumns=slidesPerRow-(s.params.slidesPerColumn*slidesPerRow-s.slides.length);for(i=0;i<s.slides.length;i++){slideSize=0;var slide=s.slides.eq(i);if(s.params.slidesPerColumn>1){var newSlideOrderIndex;var column,row;if(s.params.slidesPerColumnFill==='column'){column=Math.floor(i / slidesPerColumn);row=i-column*slidesPerColumn;if(column>numFullColumns||(column===numFullColumns&&row===slidesPerColumn-1)){if(++row>=slidesPerColumn){row=0;column++;}}
newSlideOrderIndex=column+row*slidesNumberEvenToRows / slidesPerColumn;slide.css({'-webkit-box-ordinal-group':newSlideOrderIndex,'-moz-box-ordinal-group':newSlideOrderIndex,'-ms-flex-order':newSlideOrderIndex,'-webkit-order':newSlideOrderIndex,'order':newSlideOrderIndex});}
else{row=Math.floor(i / slidesPerRow);column=i-row*slidesPerRow;}
slide.css('margin-'+(s.isHorizontal()?'top':'left'),(row!==0&&s.params.spaceBetween)&&(s.params.spaceBetween+'px')).attr('data-swiper-column',column).attr('data-swiper-row',row);}
if(slide.css('display')==='none')continue;if(s.params.slidesPerView==='auto'){slideSize=s.isHorizontal()?slide.outerWidth(true):slide.outerHeight(true);if(s.params.roundLengths)slideSize=round(slideSize);}
else{slideSize=(s.size-(s.params.slidesPerView-1)*spaceBetween)/ s.params.slidesPerView;if(s.params.roundLengths)slideSize=round(slideSize);if(s.isHorizontal()){s.slides[i].style.width=slideSize+'px';}
else{s.slides[i].style.height=slideSize+'px';}}
s.slides[i].swiperSlideSize=slideSize;s.slidesSizesGrid.push(slideSize);if(s.params.centeredSlides){slidePosition=slidePosition+slideSize / 2+prevSlideSize / 2+spaceBetween;if(prevSlideSize===0&&i!==0)slidePosition=slidePosition-s.size / 2-spaceBetween;if(i===0)slidePosition=slidePosition-s.size / 2-spaceBetween;if(Math.abs(slidePosition)<1 / 1000)slidePosition=0;if((index)%s.params.slidesPerGroup===0)s.snapGrid.push(slidePosition);s.slidesGrid.push(slidePosition);}
else{if((index)%s.params.slidesPerGroup===0)s.snapGrid.push(slidePosition);s.slidesGrid.push(slidePosition);slidePosition=slidePosition+slideSize+spaceBetween;}
s.virtualSize+=slideSize+spaceBetween;prevSlideSize=slideSize;index++;}
s.virtualSize=Math.max(s.virtualSize,s.size)+s.params.slidesOffsetAfter;var newSlidesGrid;if(s.rtl&&s.wrongRTL&&(s.params.effect==='slide'||s.params.effect==='coverflow')){s.wrapper.css({width:s.virtualSize+s.params.spaceBetween+'px'});}
if(!s.support.flexbox||s.params.setWrapperSize){if(s.isHorizontal())s.wrapper.css({width:s.virtualSize+s.params.spaceBetween+'px'});else s.wrapper.css({height:s.virtualSize+s.params.spaceBetween+'px'});}
if(s.params.slidesPerColumn>1){s.virtualSize=(slideSize+s.params.spaceBetween)*slidesNumberEvenToRows;s.virtualSize=Math.ceil(s.virtualSize / s.params.slidesPerColumn)-s.params.spaceBetween;if(s.isHorizontal())s.wrapper.css({width:s.virtualSize+s.params.spaceBetween+'px'});else s.wrapper.css({height:s.virtualSize+s.params.spaceBetween+'px'});if(s.params.centeredSlides){newSlidesGrid=[];for(i=0;i<s.snapGrid.length;i++){if(s.snapGrid[i]<s.virtualSize+s.snapGrid[0])newSlidesGrid.push(s.snapGrid[i]);}
s.snapGrid=newSlidesGrid;}}
if(!s.params.centeredSlides){newSlidesGrid=[];for(i=0;i<s.snapGrid.length;i++){if(s.snapGrid[i]<=s.virtualSize-s.size){newSlidesGrid.push(s.snapGrid[i]);}}
s.snapGrid=newSlidesGrid;if(Math.floor(s.virtualSize-s.size)-Math.floor(s.snapGrid[s.snapGrid.length-1])>1){s.snapGrid.push(s.virtualSize-s.size);}}
if(s.snapGrid.length===0)s.snapGrid=[0];if(s.params.spaceBetween!==0){if(s.isHorizontal()){if(s.rtl)s.slides.css({marginLeft:spaceBetween+'px'});else s.slides.css({marginRight:spaceBetween+'px'});}
else s.slides.css({marginBottom:spaceBetween+'px'});}
if(s.params.watchSlidesProgress){s.updateSlidesOffset();}};s.updateSlidesOffset=function(){for(var i=0;i<s.slides.length;i++){s.slides[i].swiperSlideOffset=s.isHorizontal()?s.slides[i].offsetLeft:s.slides[i].offsetTop;}};s.currentSlidesPerView=function(){var spv=1,i,j;if(s.params.centeredSlides){var size=s.slides[s.activeIndex].swiperSlideSize;var breakLoop;for(i=s.activeIndex+1;i<s.slides.length;i++){if(s.slides[i]&&!breakLoop){size+=s.slides[i].swiperSlideSize;spv++;if(size>s.size)breakLoop=true;}}
for(j=s.activeIndex-1;j>=0;j--){if(s.slides[j]&&!breakLoop){size+=s.slides[j].swiperSlideSize;spv++;if(size>s.size)breakLoop=true;}}}
else{for(i=s.activeIndex+1;i<s.slides.length;i++){if(s.slidesGrid[i]-s.slidesGrid[s.activeIndex]<s.size){spv++;}}}
return spv;};s.updateSlidesProgress=function(translate){if(typeof translate==='undefined'){translate=s.translate||0;}
if(s.slides.length===0)return;if(typeof s.slides[0].swiperSlideOffset==='undefined')s.updateSlidesOffset();var offsetCenter=-translate;if(s.rtl)offsetCenter=translate;s.slides.removeClass(s.params.slideVisibleClass);for(var i=0;i<s.slides.length;i++){var slide=s.slides[i];var slideProgress=(offsetCenter+(s.params.centeredSlides?s.minTranslate():0)-slide.swiperSlideOffset)/(slide.swiperSlideSize+s.params.spaceBetween);if(s.params.watchSlidesVisibility){var slideBefore=-(offsetCenter-slide.swiperSlideOffset);var slideAfter=slideBefore+s.slidesSizesGrid[i];var isVisible=(slideBefore>=0&&slideBefore<s.size)||(slideAfter>0&&slideAfter<=s.size)||(slideBefore<=0&&slideAfter>=s.size);if(isVisible){s.slides.eq(i).addClass(s.params.slideVisibleClass);}}
slide.progress=s.rtl?-slideProgress:slideProgress;}};s.updateProgress=function(translate){if(typeof translate==='undefined'){translate=s.translate||0;}
var translatesDiff=s.maxTranslate()-s.minTranslate();var wasBeginning=s.isBeginning;var wasEnd=s.isEnd;if(translatesDiff===0){s.progress=0;s.isBeginning=s.isEnd=true;}
else{s.progress=(translate-s.minTranslate())/(translatesDiff);s.isBeginning=s.progress<=0;s.isEnd=s.progress>=1;}
if(s.isBeginning&&!wasBeginning)s.emit('onReachBeginning',s);if(s.isEnd&&!wasEnd)s.emit('onReachEnd',s);if(s.params.watchSlidesProgress)s.updateSlidesProgress(translate);s.emit('onProgress',s,s.progress);};s.updateActiveIndex=function(){var translate=s.rtl?s.translate:-s.translate;var newActiveIndex,i,snapIndex;for(i=0;i<s.slidesGrid.length;i++){if(typeof s.slidesGrid[i+1]!=='undefined'){if(translate>=s.slidesGrid[i]&&translate<s.slidesGrid[i+1]-(s.slidesGrid[i+1]-s.slidesGrid[i])/ 2){newActiveIndex=i;}
else if(translate>=s.slidesGrid[i]&&translate<s.slidesGrid[i+1]){newActiveIndex=i+1;}}
else{if(translate>=s.slidesGrid[i]){newActiveIndex=i;}}}
if(s.params.normalizeSlideIndex){if(newActiveIndex<0||typeof newActiveIndex==='undefined')newActiveIndex=0;}
snapIndex=Math.floor(newActiveIndex / s.params.slidesPerGroup);if(snapIndex>=s.snapGrid.length)snapIndex=s.snapGrid.length-1;if(newActiveIndex===s.activeIndex){return;}
s.snapIndex=snapIndex;s.previousIndex=s.activeIndex;s.activeIndex=newActiveIndex;s.updateClasses();s.updateRealIndex();};s.updateRealIndex=function(){s.realIndex=parseInt(s.slides.eq(s.activeIndex).attr('data-swiper-slide-index')||s.activeIndex,10);};s.updateClasses=function(){s.slides.removeClass(s.params.slideActiveClass+' '+s.params.slideNextClass+' '+s.params.slidePrevClass+' '+s.params.slideDuplicateActiveClass+' '+s.params.slideDuplicateNextClass+' '+s.params.slideDuplicatePrevClass);var activeSlide=s.slides.eq(s.activeIndex);activeSlide.addClass(s.params.slideActiveClass);if(params.loop){if(activeSlide.hasClass(s.params.slideDuplicateClass)){s.wrapper.children('.'+s.params.slideClass+':not(.'+s.params.slideDuplicateClass+')[data-swiper-slide-index="'+s.realIndex+'"]').addClass(s.params.slideDuplicateActiveClass);}
else{s.wrapper.children('.'+s.params.slideClass+'.'+s.params.slideDuplicateClass+'[data-swiper-slide-index="'+s.realIndex+'"]').addClass(s.params.slideDuplicateActiveClass);}}
var nextSlide=activeSlide.next('.'+s.params.slideClass).addClass(s.params.slideNextClass);if(s.params.loop&&nextSlide.length===0){nextSlide=s.slides.eq(0);nextSlide.addClass(s.params.slideNextClass);}
var prevSlide=activeSlide.prev('.'+s.params.slideClass).addClass(s.params.slidePrevClass);if(s.params.loop&&prevSlide.length===0){prevSlide=s.slides.eq(-1);prevSlide.addClass(s.params.slidePrevClass);}
if(params.loop){if(nextSlide.hasClass(s.params.slideDuplicateClass)){s.wrapper.children('.'+s.params.slideClass+':not(.'+s.params.slideDuplicateClass+')[data-swiper-slide-index="'+nextSlide.attr('data-swiper-slide-index')+'"]').addClass(s.params.slideDuplicateNextClass);}
else{s.wrapper.children('.'+s.params.slideClass+'.'+s.params.slideDuplicateClass+'[data-swiper-slide-index="'+nextSlide.attr('data-swiper-slide-index')+'"]').addClass(s.params.slideDuplicateNextClass);}
if(prevSlide.hasClass(s.params.slideDuplicateClass)){s.wrapper.children('.'+s.params.slideClass+':not(.'+s.params.slideDuplicateClass+')[data-swiper-slide-index="'+prevSlide.attr('data-swiper-slide-index')+'"]').addClass(s.params.slideDuplicatePrevClass);}
else{s.wrapper.children('.'+s.params.slideClass+'.'+s.params.slideDuplicateClass+'[data-swiper-slide-index="'+prevSlide.attr('data-swiper-slide-index')+'"]').addClass(s.params.slideDuplicatePrevClass);}}
if(s.paginationContainer&&s.paginationContainer.length>0){var current,total=s.params.loop?Math.ceil((s.slides.length-s.loopedSlides*2)/ s.params.slidesPerGroup):s.snapGrid.length;if(s.params.loop){current=Math.ceil((s.activeIndex-s.loopedSlides)/s.params.slidesPerGroup);if(current>s.slides.length-1-s.loopedSlides*2){current=current-(s.slides.length-s.loopedSlides*2);}
if(current>total-1)current=current-total;if(current<0&&s.params.paginationType!=='bullets')current=total+current;}
else{if(typeof s.snapIndex!=='undefined'){current=s.snapIndex;}
else{current=s.activeIndex||0;}}
if(s.params.paginationType==='bullets'&&s.bullets&&s.bullets.length>0){s.bullets.removeClass(s.params.bulletActiveClass);if(s.paginationContainer.length>1){s.bullets.each(function(){if($(this).index()===current)$(this).addClass(s.params.bulletActiveClass);});}
else{s.bullets.eq(current).addClass(s.params.bulletActiveClass);}}
if(s.params.paginationType==='fraction'){s.paginationContainer.find('.'+s.params.paginationCurrentClass).text(current+1);s.paginationContainer.find('.'+s.params.paginationTotalClass).text(total);}
if(s.params.paginationType==='progress'){var scale=(current+1)/ total,scaleX=scale,scaleY=1;if(!s.isHorizontal()){scaleY=scale;scaleX=1;}
s.paginationContainer.find('.'+s.params.paginationProgressbarClass).transform('translate3d(0,0,0) scaleX('+scaleX+') scaleY('+scaleY+')').transition(s.params.speed);}
if(s.params.paginationType==='custom'&&s.params.paginationCustomRender){s.paginationContainer.html(s.params.paginationCustomRender(s,current+1,total));s.emit('onPaginationRendered',s,s.paginationContainer[0]);}}
if(!s.params.loop){if(s.params.prevButton&&s.prevButton&&s.prevButton.length>0){if(s.isBeginning){s.prevButton.addClass(s.params.buttonDisabledClass);if(s.params.a11y&&s.a11y)s.a11y.disable(s.prevButton);}
else{s.prevButton.removeClass(s.params.buttonDisabledClass);if(s.params.a11y&&s.a11y)s.a11y.enable(s.prevButton);}}
if(s.params.nextButton&&s.nextButton&&s.nextButton.length>0){if(s.isEnd){s.nextButton.addClass(s.params.buttonDisabledClass);if(s.params.a11y&&s.a11y)s.a11y.disable(s.nextButton);}
else{s.nextButton.removeClass(s.params.buttonDisabledClass);if(s.params.a11y&&s.a11y)s.a11y.enable(s.nextButton);}}}};s.updatePagination=function(){if(!s.params.pagination)return;if(s.paginationContainer&&s.paginationContainer.length>0){var paginationHTML='';if(s.params.paginationType==='bullets'){var numberOfBullets=s.params.loop?Math.ceil((s.slides.length-s.loopedSlides*2)/ s.params.slidesPerGroup):s.snapGrid.length;for(var i=0;i<numberOfBullets;i++){if(s.params.paginationBulletRender){paginationHTML+=s.params.paginationBulletRender(s,i,s.params.bulletClass);}
else{paginationHTML+='<'+s.params.paginationElement+' class="'+s.params.bulletClass+'"></'+s.params.paginationElement+'>';}}
s.paginationContainer.html(paginationHTML);s.bullets=s.paginationContainer.find('.'+s.params.bulletClass);if(s.params.paginationClickable&&s.params.a11y&&s.a11y){s.a11y.initPagination();}}
if(s.params.paginationType==='fraction'){if(s.params.paginationFractionRender){paginationHTML=s.params.paginationFractionRender(s,s.params.paginationCurrentClass,s.params.paginationTotalClass);}
else{paginationHTML='<span class="'+s.params.paginationCurrentClass+'"></span>'+' / '+'<span class="'+s.params.paginationTotalClass+'"></span>';}
s.paginationContainer.html(paginationHTML);}
if(s.params.paginationType==='progress'){if(s.params.paginationProgressRender){paginationHTML=s.params.paginationProgressRender(s,s.params.paginationProgressbarClass);}
else{paginationHTML='<span class="'+s.params.paginationProgressbarClass+'"></span>';}
s.paginationContainer.html(paginationHTML);}
if(s.params.paginationType!=='custom'){s.emit('onPaginationRendered',s,s.paginationContainer[0]);}}};s.update=function(updateTranslate){if(!s)return;s.updateContainerSize();s.updateSlidesSize();s.updateProgress();s.updatePagination();s.updateClasses();if(s.params.scrollbar&&s.scrollbar){s.scrollbar.set();}
var newTranslate;function forceSetTranslate(){var translate=s.rtl?-s.translate:s.translate;newTranslate=Math.min(Math.max(s.translate,s.maxTranslate()),s.minTranslate());s.setWrapperTranslate(newTranslate);s.updateActiveIndex();s.updateClasses();}
if(updateTranslate){var translated;if(s.controller&&s.controller.spline){s.controller.spline=undefined;}
if(s.params.freeMode){forceSetTranslate();if(s.params.autoHeight){s.updateAutoHeight();}}
else{if((s.params.slidesPerView==='auto'||s.params.slidesPerView>1)&&s.isEnd&&!s.params.centeredSlides){translated=s.slideTo(s.slides.length-1,0,false,true);}
else{translated=s.slideTo(s.activeIndex,0,false,true);}
if(!translated){forceSetTranslate();}}}
else if(s.params.autoHeight){s.updateAutoHeight();}};s.onResize=function(forceUpdatePagination){if(s.params.onBeforeResize)s.params.onBeforeResize(s);if(s.params.breakpoints){s.setBreakpoint();}
var allowSwipeToPrev=s.params.allowSwipeToPrev;var allowSwipeToNext=s.params.allowSwipeToNext;s.params.allowSwipeToPrev=s.params.allowSwipeToNext=true;s.updateContainerSize();s.updateSlidesSize();if(s.params.slidesPerView==='auto'||s.params.freeMode||forceUpdatePagination)s.updatePagination();if(s.params.scrollbar&&s.scrollbar){s.scrollbar.set();}
if(s.controller&&s.controller.spline){s.controller.spline=undefined;}
var slideChangedBySlideTo=false;if(s.params.freeMode){var newTranslate=Math.min(Math.max(s.translate,s.maxTranslate()),s.minTranslate());s.setWrapperTranslate(newTranslate);s.updateActiveIndex();s.updateClasses();if(s.params.autoHeight){s.updateAutoHeight();}}
else{s.updateClasses();if((s.params.slidesPerView==='auto'||s.params.slidesPerView>1)&&s.isEnd&&!s.params.centeredSlides){slideChangedBySlideTo=s.slideTo(s.slides.length-1,0,false,true);}
else{slideChangedBySlideTo=s.slideTo(s.activeIndex,0,false,true);}}
if(s.params.lazyLoading&&!slideChangedBySlideTo&&s.lazy){s.lazy.load();}
s.params.allowSwipeToPrev=allowSwipeToPrev;s.params.allowSwipeToNext=allowSwipeToNext;if(s.params.onAfterResize)s.params.onAfterResize(s);};s.touchEventsDesktop={start:'mousedown',move:'mousemove',end:'mouseup'};if(window.navigator.pointerEnabled)s.touchEventsDesktop={start:'pointerdown',move:'pointermove',end:'pointerup'};else if(window.navigator.msPointerEnabled)s.touchEventsDesktop={start:'MSPointerDown',move:'MSPointerMove',end:'MSPointerUp'};s.touchEvents={start:s.support.touch||!s.params.simulateTouch?'touchstart':s.touchEventsDesktop.start,move:s.support.touch||!s.params.simulateTouch?'touchmove':s.touchEventsDesktop.move,end:s.support.touch||!s.params.simulateTouch?'touchend':s.touchEventsDesktop.end};if(window.navigator.pointerEnabled||window.navigator.msPointerEnabled){(s.params.touchEventsTarget==='container'?s.container:s.wrapper).addClass('swiper-wp8-'+s.params.direction);}
s.initEvents=function(detach){var actionDom=detach?'off':'on';var action=detach?'removeEventListener':'addEventListener';var touchEventsTarget=s.params.touchEventsTarget==='container'?s.container[0]:s.wrapper[0];var target=s.support.touch?touchEventsTarget:document;var moveCapture=s.params.nested?true:false;if(s.browser.ie){touchEventsTarget[action](s.touchEvents.start,s.onTouchStart,false);target[action](s.touchEvents.move,s.onTouchMove,moveCapture);target[action](s.touchEvents.end,s.onTouchEnd,false);}
else{if(s.support.touch){var passiveListener=s.touchEvents.start==='touchstart'&&s.support.passiveListener&&s.params.passiveListeners?{passive:true,capture:false}:false;touchEventsTarget[action](s.touchEvents.start,s.onTouchStart,passiveListener);touchEventsTarget[action](s.touchEvents.move,s.onTouchMove,moveCapture);touchEventsTarget[action](s.touchEvents.end,s.onTouchEnd,passiveListener);}
if((params.simulateTouch&&!s.device.ios&&!s.device.android)||(params.simulateTouch&&!s.support.touch&&s.device.ios)){touchEventsTarget[action]('mousedown',s.onTouchStart,false);document[action]('mousemove',s.onTouchMove,moveCapture);document[action]('mouseup',s.onTouchEnd,false);}}
window[action]('resize',s.onResize);if(s.params.nextButton&&s.nextButton&&s.nextButton.length>0){s.nextButton[actionDom]('click',s.onClickNext);if(s.params.a11y&&s.a11y)s.nextButton[actionDom]('keydown',s.a11y.onEnterKey);}
if(s.params.prevButton&&s.prevButton&&s.prevButton.length>0){s.prevButton[actionDom]('click',s.onClickPrev);if(s.params.a11y&&s.a11y)s.prevButton[actionDom]('keydown',s.a11y.onEnterKey);}
if(s.params.pagination&&s.params.paginationClickable){s.paginationContainer[actionDom]('click','.'+s.params.bulletClass,s.onClickIndex);if(s.params.a11y&&s.a11y)s.paginationContainer[actionDom]('keydown','.'+s.params.bulletClass,s.a11y.onEnterKey);}
if(s.params.preventClicks||s.params.preventClicksPropagation)touchEventsTarget[action]('click',s.preventClicks,true);};s.attachEvents=function(){s.initEvents();};s.detachEvents=function(){s.initEvents(true);};s.allowClick=true;s.preventClicks=function(e){if(!s.allowClick){if(s.params.preventClicks)e.preventDefault();if(s.params.preventClicksPropagation&&s.animating){e.stopPropagation();e.stopImmediatePropagation();}}};s.onClickNext=function(e){e.preventDefault();if(s.isEnd&&!s.params.loop)return;s.slideNext();};s.onClickPrev=function(e){e.preventDefault();if(s.isBeginning&&!s.params.loop)return;s.slidePrev();};s.onClickIndex=function(e){e.preventDefault();var index=$(this).index()*s.params.slidesPerGroup;if(s.params.loop)index=index+s.loopedSlides;s.slideTo(index);};function findElementInEvent(e,selector){var el=$(e.target);if(!el.is(selector)){if(typeof selector==='string'){el=el.parents(selector);}
else if(selector.nodeType){var found;el.parents().each(function(index,_el){if(_el===selector)found=selector;});if(!found)return undefined;else return selector;}}
if(el.length===0){return undefined;}
return el[0];}
s.updateClickedSlide=function(e){var slide=findElementInEvent(e,'.'+s.params.slideClass);var slideFound=false;if(slide){for(var i=0;i<s.slides.length;i++){if(s.slides[i]===slide)slideFound=true;}}
if(slide&&slideFound){s.clickedSlide=slide;s.clickedIndex=$(slide).index();}
else{s.clickedSlide=undefined;s.clickedIndex=undefined;return;}
if(s.params.slideToClickedSlide&&s.clickedIndex!==undefined&&s.clickedIndex!==s.activeIndex){var slideToIndex=s.clickedIndex,realIndex,duplicatedSlides,slidesPerView=s.params.slidesPerView==='auto'?s.currentSlidesPerView():s.params.slidesPerView;if(s.params.loop){if(s.animating)return;realIndex=parseInt($(s.clickedSlide).attr('data-swiper-slide-index'),10);if(s.params.centeredSlides){if((slideToIndex<s.loopedSlides-slidesPerView/2)||(slideToIndex>s.slides.length-s.loopedSlides+slidesPerView/2)){s.fixLoop();slideToIndex=s.wrapper.children('.'+s.params.slideClass+'[data-swiper-slide-index="'+realIndex+'"]:not(.'+s.params.slideDuplicateClass+')').eq(0).index();setTimeout(function(){s.slideTo(slideToIndex);},0);}
else{s.slideTo(slideToIndex);}}
else{if(slideToIndex>s.slides.length-slidesPerView){s.fixLoop();slideToIndex=s.wrapper.children('.'+s.params.slideClass+'[data-swiper-slide-index="'+realIndex+'"]:not(.'+s.params.slideDuplicateClass+')').eq(0).index();setTimeout(function(){s.slideTo(slideToIndex);},0);}
else{s.slideTo(slideToIndex);}}}
else{s.slideTo(slideToIndex);}}};var isTouched,isMoved,allowTouchCallbacks,touchStartTime,isScrolling,currentTranslate,startTranslate,allowThresholdMove,formElements='input, select, textarea, button, video',lastClickTime=Date.now(),clickTimeout,velocities=[],allowMomentumBounce;s.animating=false;s.touches={startX:0,startY:0,currentX:0,currentY:0,diff:0};var isTouchEvent,startMoving;s.onTouchStart=function(e){if(e.originalEvent)e=e.originalEvent;isTouchEvent=e.type==='touchstart';if(!isTouchEvent&&'which'in e&&e.which===3)return;if(s.params.noSwiping&&findElementInEvent(e,'.'+s.params.noSwipingClass)){s.allowClick=true;return;}
if(s.params.swipeHandler){if(!findElementInEvent(e,s.params.swipeHandler))return;}
var startX=s.touches.currentX=e.type==='touchstart'?e.targetTouches[0].pageX:e.pageX;var startY=s.touches.currentY=e.type==='touchstart'?e.targetTouches[0].pageY:e.pageY;if(s.device.ios&&s.params.iOSEdgeSwipeDetection&&startX<=s.params.iOSEdgeSwipeThreshold){return;}
isTouched=true;isMoved=false;allowTouchCallbacks=true;isScrolling=undefined;startMoving=undefined;s.touches.startX=startX;s.touches.startY=startY;touchStartTime=Date.now();s.allowClick=true;s.updateContainerSize();s.swipeDirection=undefined;if(s.params.threshold>0)allowThresholdMove=false;if(e.type!=='touchstart'){var preventDefault=true;if($(e.target).is(formElements))preventDefault=false;if(document.activeElement&&$(document.activeElement).is(formElements)){document.activeElement.blur();}
if(preventDefault){e.preventDefault();}}
s.emit('onTouchStart',s,e);};s.onTouchMove=function(e){if(e.originalEvent)e=e.originalEvent;if(isTouchEvent&&e.type==='mousemove')return;if(e.preventedByNestedSwiper){s.touches.startX=e.type==='touchmove'?e.targetTouches[0].pageX:e.pageX;s.touches.startY=e.type==='touchmove'?e.targetTouches[0].pageY:e.pageY;return;}
if(s.params.onlyExternal){s.allowClick=false;if(isTouched){s.touches.startX=s.touches.currentX=e.type==='touchmove'?e.targetTouches[0].pageX:e.pageX;s.touches.startY=s.touches.currentY=e.type==='touchmove'?e.targetTouches[0].pageY:e.pageY;touchStartTime=Date.now();}
return;}
if(isTouchEvent&&s.params.touchReleaseOnEdges&&!s.params.loop){if(!s.isHorizontal()){if((s.touches.currentY<s.touches.startY&&s.translate<=s.maxTranslate())||(s.touches.currentY>s.touches.startY&&s.translate>=s.minTranslate())){return;}}
else{if((s.touches.currentX<s.touches.startX&&s.translate<=s.maxTranslate())||(s.touches.currentX>s.touches.startX&&s.translate>=s.minTranslate())){return;}}}
if(isTouchEvent&&document.activeElement){if(e.target===document.activeElement&&$(e.target).is(formElements)){isMoved=true;s.allowClick=false;return;}}
if(allowTouchCallbacks){s.emit('onTouchMove',s,e);}
if(e.targetTouches&&e.targetTouches.length>1)return;s.touches.currentX=e.type==='touchmove'?e.targetTouches[0].pageX:e.pageX;s.touches.currentY=e.type==='touchmove'?e.targetTouches[0].pageY:e.pageY;if(typeof isScrolling==='undefined'){var touchAngle;if(s.isHorizontal()&&s.touches.currentY===s.touches.startY||!s.isHorizontal()&&s.touches.currentX===s.touches.startX){isScrolling=false;}
else{touchAngle=Math.atan2(Math.abs(s.touches.currentY-s.touches.startY),Math.abs(s.touches.currentX-s.touches.startX))*180 / Math.PI;isScrolling=s.isHorizontal()?touchAngle>s.params.touchAngle:(90-touchAngle>s.params.touchAngle);}}
if(isScrolling){s.emit('onTouchMoveOpposite',s,e);}
if(typeof startMoving==='undefined'){if(s.touches.currentX!==s.touches.startX||s.touches.currentY!==s.touches.startY){startMoving=true;}}
if(!isTouched)return;if(isScrolling){isTouched=false;return;}
if(!startMoving){return;}
s.allowClick=false;s.emit('onSliderMove',s,e);e.preventDefault();if(s.params.touchMoveStopPropagation&&!s.params.nested){e.stopPropagation();}
if(!isMoved){if(params.loop){s.fixLoop();}
startTranslate=s.getWrapperTranslate();s.setWrapperTransition(0);if(s.animating){s.wrapper.trigger('webkitTransitionEnd transitionend oTransitionEnd MSTransitionEnd msTransitionEnd');}
if(s.params.autoplay&&s.autoplaying){if(s.params.autoplayDisableOnInteraction){s.stopAutoplay();}
else{s.pauseAutoplay();}}
allowMomentumBounce=false;if(s.params.grabCursor&&(s.params.allowSwipeToNext===true||s.params.allowSwipeToPrev===true)){s.setGrabCursor(true);}}
isMoved=true;var diff=s.touches.diff=s.isHorizontal()?s.touches.currentX-s.touches.startX:s.touches.currentY-s.touches.startY;diff=diff*s.params.touchRatio;if(s.rtl)diff=-diff;s.swipeDirection=diff>0?'prev':'next';currentTranslate=diff+startTranslate;var disableParentSwiper=true;if((diff>0&&currentTranslate>s.minTranslate())){disableParentSwiper=false;if(s.params.resistance)currentTranslate=s.minTranslate()-1+Math.pow(-s.minTranslate()+startTranslate+diff,s.params.resistanceRatio);}
else if(diff<0&&currentTranslate<s.maxTranslate()){disableParentSwiper=false;if(s.params.resistance)currentTranslate=s.maxTranslate()+1-Math.pow(s.maxTranslate()-startTranslate-diff,s.params.resistanceRatio);}
if(disableParentSwiper){e.preventedByNestedSwiper=true;}
if(!s.params.allowSwipeToNext&&s.swipeDirection==='next'&&currentTranslate<startTranslate){currentTranslate=startTranslate;}
if(!s.params.allowSwipeToPrev&&s.swipeDirection==='prev'&&currentTranslate>startTranslate){currentTranslate=startTranslate;}
if(s.params.threshold>0){if(Math.abs(diff)>s.params.threshold||allowThresholdMove){if(!allowThresholdMove){allowThresholdMove=true;s.touches.startX=s.touches.currentX;s.touches.startY=s.touches.currentY;currentTranslate=startTranslate;s.touches.diff=s.isHorizontal()?s.touches.currentX-s.touches.startX:s.touches.currentY-s.touches.startY;return;}}
else{currentTranslate=startTranslate;return;}}
if(!s.params.followFinger)return;if(s.params.freeMode||s.params.watchSlidesProgress){s.updateActiveIndex();}
if(s.params.freeMode){if(velocities.length===0){velocities.push({position:s.touches[s.isHorizontal()?'startX':'startY'],time:touchStartTime});}
velocities.push({position:s.touches[s.isHorizontal()?'currentX':'currentY'],time:(new window.Date()).getTime()});}
s.updateProgress(currentTranslate);s.setWrapperTranslate(currentTranslate);};s.onTouchEnd=function(e){if(e.originalEvent)e=e.originalEvent;if(allowTouchCallbacks){s.emit('onTouchEnd',s,e);}
allowTouchCallbacks=false;if(!isTouched)return;if(s.params.grabCursor&&isMoved&&isTouched&&(s.params.allowSwipeToNext===true||s.params.allowSwipeToPrev===true)){s.setGrabCursor(false);}
var touchEndTime=Date.now();var timeDiff=touchEndTime-touchStartTime;if(s.allowClick){s.updateClickedSlide(e);s.emit('onTap',s,e);if(timeDiff<300&&(touchEndTime-lastClickTime)>300){if(clickTimeout)clearTimeout(clickTimeout);clickTimeout=setTimeout(function(){if(!s)return;if(s.params.paginationHide&&s.paginationContainer.length>0&&!$(e.target).hasClass(s.params.bulletClass)){s.paginationContainer.toggleClass(s.params.paginationHiddenClass);}
s.emit('onClick',s,e);},300);}
if(timeDiff<300&&(touchEndTime-lastClickTime)<300){if(clickTimeout)clearTimeout(clickTimeout);s.emit('onDoubleTap',s,e);}}
lastClickTime=Date.now();setTimeout(function(){if(s)s.allowClick=true;},0);if(!isTouched||!isMoved||!s.swipeDirection||s.touches.diff===0||currentTranslate===startTranslate){isTouched=isMoved=false;return;}
isTouched=isMoved=false;var currentPos;if(s.params.followFinger){currentPos=s.rtl?s.translate:-s.translate;}
else{currentPos=-currentTranslate;}
if(s.params.freeMode){if(currentPos<-s.minTranslate()){s.slideTo(s.activeIndex);return;}
else if(currentPos>-s.maxTranslate()){if(s.slides.length<s.snapGrid.length){s.slideTo(s.snapGrid.length-1);}
else{s.slideTo(s.slides.length-1);}
return;}
if(s.params.freeModeMomentum){if(velocities.length>1){var lastMoveEvent=velocities.pop(),velocityEvent=velocities.pop();var distance=lastMoveEvent.position-velocityEvent.position;var time=lastMoveEvent.time-velocityEvent.time;s.velocity=distance / time;s.velocity=s.velocity / 2;if(Math.abs(s.velocity)<s.params.freeModeMinimumVelocity){s.velocity=0;}
if(time>150||(new window.Date().getTime()-lastMoveEvent.time)>300){s.velocity=0;}}else{s.velocity=0;}
s.velocity=s.velocity*s.params.freeModeMomentumVelocityRatio;velocities.length=0;var momentumDuration=1000*s.params.freeModeMomentumRatio;var momentumDistance=s.velocity*momentumDuration;var newPosition=s.translate+momentumDistance;if(s.rtl)newPosition=-newPosition;var doBounce=false;var afterBouncePosition;var bounceAmount=Math.abs(s.velocity)*20*s.params.freeModeMomentumBounceRatio;if(newPosition<s.maxTranslate()){if(s.params.freeModeMomentumBounce){if(newPosition+s.maxTranslate()<-bounceAmount){newPosition=s.maxTranslate()-bounceAmount;}
afterBouncePosition=s.maxTranslate();doBounce=true;allowMomentumBounce=true;}
else{newPosition=s.maxTranslate();}}
else if(newPosition>s.minTranslate()){if(s.params.freeModeMomentumBounce){if(newPosition-s.minTranslate()>bounceAmount){newPosition=s.minTranslate()+bounceAmount;}
afterBouncePosition=s.minTranslate();doBounce=true;allowMomentumBounce=true;}
else{newPosition=s.minTranslate();}}
else if(s.params.freeModeSticky){var j=0,nextSlide;for(j=0;j<s.snapGrid.length;j+=1){if(s.snapGrid[j]>-newPosition){nextSlide=j;break;}}
if(Math.abs(s.snapGrid[nextSlide]-newPosition)<Math.abs(s.snapGrid[nextSlide-1]-newPosition)||s.swipeDirection==='next'){newPosition=s.snapGrid[nextSlide];}else{newPosition=s.snapGrid[nextSlide-1];}
if(!s.rtl)newPosition=-newPosition;}
if(s.velocity!==0){if(s.rtl){momentumDuration=Math.abs((-newPosition-s.translate)/ s.velocity);}
else{momentumDuration=Math.abs((newPosition-s.translate)/ s.velocity);}}
else if(s.params.freeModeSticky){s.slideReset();return;}
if(s.params.freeModeMomentumBounce&&doBounce){s.updateProgress(afterBouncePosition);s.setWrapperTransition(momentumDuration);s.setWrapperTranslate(newPosition);s.onTransitionStart();s.animating=true;s.wrapper.transitionEnd(function(){if(!s||!allowMomentumBounce)return;s.emit('onMomentumBounce',s);s.setWrapperTransition(s.params.speed);s.setWrapperTranslate(afterBouncePosition);s.wrapper.transitionEnd(function(){if(!s)return;s.onTransitionEnd();});});}else if(s.velocity){s.updateProgress(newPosition);s.setWrapperTransition(momentumDuration);s.setWrapperTranslate(newPosition);s.onTransitionStart();if(!s.animating){s.animating=true;s.wrapper.transitionEnd(function(){if(!s)return;s.onTransitionEnd();});}}else{s.updateProgress(newPosition);}
s.updateActiveIndex();}
if(!s.params.freeModeMomentum||timeDiff>=s.params.longSwipesMs){s.updateProgress();s.updateActiveIndex();}
return;}
var i,stopIndex=0,groupSize=s.slidesSizesGrid[0];for(i=0;i<s.slidesGrid.length;i+=s.params.slidesPerGroup){if(typeof s.slidesGrid[i+s.params.slidesPerGroup]!=='undefined'){if(currentPos>=s.slidesGrid[i]&&currentPos<s.slidesGrid[i+s.params.slidesPerGroup]){stopIndex=i;groupSize=s.slidesGrid[i+s.params.slidesPerGroup]-s.slidesGrid[i];}}
else{if(currentPos>=s.slidesGrid[i]){stopIndex=i;groupSize=s.slidesGrid[s.slidesGrid.length-1]-s.slidesGrid[s.slidesGrid.length-2];}}}
var ratio=(currentPos-s.slidesGrid[stopIndex])/ groupSize;if(timeDiff>s.params.longSwipesMs){if(!s.params.longSwipes){s.slideTo(s.activeIndex);return;}
if(s.swipeDirection==='next'){if(ratio>=s.params.longSwipesRatio)s.slideTo(stopIndex+s.params.slidesPerGroup);else s.slideTo(stopIndex);}
if(s.swipeDirection==='prev'){if(ratio>(1-s.params.longSwipesRatio))s.slideTo(stopIndex+s.params.slidesPerGroup);else s.slideTo(stopIndex);}}
else{if(!s.params.shortSwipes){s.slideTo(s.activeIndex);return;}
if(s.swipeDirection==='next'){s.slideTo(stopIndex+s.params.slidesPerGroup);}
if(s.swipeDirection==='prev'){s.slideTo(stopIndex);}}};s._slideTo=function(slideIndex,speed){return s.slideTo(slideIndex,speed,true,true);};s.slideTo=function(slideIndex,speed,runCallbacks,internal){if(typeof runCallbacks==='undefined')runCallbacks=true;if(typeof slideIndex==='undefined')slideIndex=0;if(slideIndex<0)slideIndex=0;s.snapIndex=Math.floor(slideIndex / s.params.slidesPerGroup);if(s.snapIndex>=s.snapGrid.length)s.snapIndex=s.snapGrid.length-1;var translate=-s.snapGrid[s.snapIndex];if(s.params.autoplay&&s.autoplaying){if(internal||!s.params.autoplayDisableOnInteraction){s.pauseAutoplay(speed);}
else{s.stopAutoplay();}}
s.updateProgress(translate);if(s.params.normalizeSlideIndex){for(var i=0;i<s.slidesGrid.length;i++){if(-Math.floor(translate*100)>=Math.floor(s.slidesGrid[i]*100)){slideIndex=i;}}}
if(!s.params.allowSwipeToNext&&translate<s.translate&&translate<s.minTranslate()){return false;}
if(!s.params.allowSwipeToPrev&&translate>s.translate&&translate>s.maxTranslate()){if((s.activeIndex||0)!==slideIndex)return false;}
if(typeof speed==='undefined')speed=s.params.speed;s.previousIndex=s.activeIndex||0;s.activeIndex=slideIndex;s.updateRealIndex();if((s.rtl&&-translate===s.translate)||(!s.rtl&&translate===s.translate)){if(s.params.autoHeight){s.updateAutoHeight();}
s.updateClasses();if(s.params.effect!=='slide'){s.setWrapperTranslate(translate);}
return false;}
s.updateClasses();s.onTransitionStart(runCallbacks);if(speed===0||s.browser.lteIE9){s.setWrapperTranslate(translate);s.setWrapperTransition(0);s.onTransitionEnd(runCallbacks);}
else{s.setWrapperTranslate(translate);s.setWrapperTransition(speed);if(!s.animating){s.animating=true;s.wrapper.transitionEnd(function(){if(!s)return;s.onTransitionEnd(runCallbacks);});}}
return true;};s.onTransitionStart=function(runCallbacks){if(typeof runCallbacks==='undefined')runCallbacks=true;if(s.params.autoHeight){s.updateAutoHeight();}
if(s.lazy)s.lazy.onTransitionStart();if(runCallbacks){s.emit('onTransitionStart',s);if(s.activeIndex!==s.previousIndex){s.emit('onSlideChangeStart',s);if(s.activeIndex>s.previousIndex){s.emit('onSlideNextStart',s);}
else{s.emit('onSlidePrevStart',s);}}}};s.onTransitionEnd=function(runCallbacks){s.animating=false;s.setWrapperTransition(0);if(typeof runCallbacks==='undefined')runCallbacks=true;if(s.lazy)s.lazy.onTransitionEnd();if(runCallbacks){s.emit('onTransitionEnd',s);if(s.activeIndex!==s.previousIndex){s.emit('onSlideChangeEnd',s);if(s.activeIndex>s.previousIndex){s.emit('onSlideNextEnd',s);}
else{s.emit('onSlidePrevEnd',s);}}}
if(s.params.history&&s.history){s.history.setHistory(s.params.history,s.activeIndex);}
if(s.params.hashnav&&s.hashnav){s.hashnav.setHash();}};s.slideNext=function(runCallbacks,speed,internal){if(s.params.loop){if(s.animating)return false;s.fixLoop();var clientLeft=s.container[0].clientLeft;return s.slideTo(s.activeIndex+s.params.slidesPerGroup,speed,runCallbacks,internal);}
else return s.slideTo(s.activeIndex+s.params.slidesPerGroup,speed,runCallbacks,internal);};s._slideNext=function(speed){return s.slideNext(true,speed,true);};s.slidePrev=function(runCallbacks,speed,internal){if(s.params.loop){if(s.animating)return false;s.fixLoop();var clientLeft=s.container[0].clientLeft;return s.slideTo(s.activeIndex-1,speed,runCallbacks,internal);}
else return s.slideTo(s.activeIndex-1,speed,runCallbacks,internal);};s._slidePrev=function(speed){return s.slidePrev(true,speed,true);};s.slideReset=function(runCallbacks,speed,internal){return s.slideTo(s.activeIndex,speed,runCallbacks);};s.disableTouchControl=function(){s.params.onlyExternal=true;return true;};s.enableTouchControl=function(){s.params.onlyExternal=false;return true;};s.setWrapperTransition=function(duration,byController){s.wrapper.transition(duration);if(s.params.effect!=='slide'&&s.effects[s.params.effect]){s.effects[s.params.effect].setTransition(duration);}
if(s.params.parallax&&s.parallax){s.parallax.setTransition(duration);}
if(s.params.scrollbar&&s.scrollbar){s.scrollbar.setTransition(duration);}
if(s.params.control&&s.controller){s.controller.setTransition(duration,byController);}
s.emit('onSetTransition',s,duration);};s.setWrapperTranslate=function(translate,updateActiveIndex,byController){var x=0,y=0,z=0;if(s.isHorizontal()){x=s.rtl?-translate:translate;}
else{y=translate;}
if(s.params.roundLengths){x=round(x);y=round(y);}
if(!s.params.virtualTranslate){if(s.support.transforms3d)s.wrapper.transform('translate3d('+x+'px, '+y+'px, '+z+'px)');else s.wrapper.transform('translate('+x+'px, '+y+'px)');}
s.translate=s.isHorizontal()?x:y;var progress;var translatesDiff=s.maxTranslate()-s.minTranslate();if(translatesDiff===0){progress=0;}
else{progress=(translate-s.minTranslate())/(translatesDiff);}
if(progress!==s.progress){s.updateProgress(translate);}
if(updateActiveIndex)s.updateActiveIndex();if(s.params.effect!=='slide'&&s.effects[s.params.effect]){s.effects[s.params.effect].setTranslate(s.translate);}
if(s.params.parallax&&s.parallax){s.parallax.setTranslate(s.translate);}
if(s.params.scrollbar&&s.scrollbar){s.scrollbar.setTranslate(s.translate);}
if(s.params.control&&s.controller){s.controller.setTranslate(s.translate,byController);}
s.emit('onSetTranslate',s,s.translate);};s.getTranslate=function(el,axis){var matrix,curTransform,curStyle,transformMatrix;if(typeof axis==='undefined'){axis='x';}
if(s.params.virtualTranslate){return s.rtl?-s.translate:s.translate;}
curStyle=window.getComputedStyle(el,null);if(window.WebKitCSSMatrix){curTransform=curStyle.transform||curStyle.webkitTransform;if(curTransform.split(',').length>6){curTransform=curTransform.split(', ').map(function(a){return a.replace(',','.');}).join(', ');}
transformMatrix=new window.WebKitCSSMatrix(curTransform==='none'?'':curTransform);}
else{transformMatrix=curStyle.MozTransform||curStyle.OTransform||curStyle.MsTransform||curStyle.msTransform||curStyle.transform||curStyle.getPropertyValue('transform').replace('translate(','matrix(1, 0, 0, 1,');matrix=transformMatrix.toString().split(',');}
if(axis==='x'){if(window.WebKitCSSMatrix)
curTransform=transformMatrix.m41;else if(matrix.length===16)
curTransform=parseFloat(matrix[12]);else
curTransform=parseFloat(matrix[4]);}
if(axis==='y'){if(window.WebKitCSSMatrix)
curTransform=transformMatrix.m42;else if(matrix.length===16)
curTransform=parseFloat(matrix[13]);else
curTransform=parseFloat(matrix[5]);}
if(s.rtl&&curTransform)curTransform=-curTransform;return curTransform||0;};s.getWrapperTranslate=function(axis){if(typeof axis==='undefined'){axis=s.isHorizontal()?'x':'y';}
return s.getTranslate(s.wrapper[0],axis);};s.observers=[];function initObserver(target,options){options=options||{};var ObserverFunc=window.MutationObserver||window.WebkitMutationObserver;var observer=new ObserverFunc(function(mutations){mutations.forEach(function(mutation){s.onResize(true);s.emit('onObserverUpdate',s,mutation);});});observer.observe(target,{attributes:typeof options.attributes==='undefined'?true:options.attributes,childList:typeof options.childList==='undefined'?true:options.childList,characterData:typeof options.characterData==='undefined'?true:options.characterData});s.observers.push(observer);}
s.initObservers=function(){if(s.params.observeParents){var containerParents=s.container.parents();for(var i=0;i<containerParents.length;i++){initObserver(containerParents[i]);}}
initObserver(s.container[0],{childList:false});initObserver(s.wrapper[0],{attributes:false});};s.disconnectObservers=function(){for(var i=0;i<s.observers.length;i++){s.observers[i].disconnect();}
s.observers=[];};s.createLoop=function(){s.wrapper.children('.'+s.params.slideClass+'.'+s.params.slideDuplicateClass).remove();var slides=s.wrapper.children('.'+s.params.slideClass);if(s.params.slidesPerView==='auto'&&!s.params.loopedSlides)s.params.loopedSlides=slides.length;s.loopedSlides=parseInt(s.params.loopedSlides||s.params.slidesPerView,10);s.loopedSlides=s.loopedSlides+s.params.loopAdditionalSlides;if(s.loopedSlides>slides.length){s.loopedSlides=slides.length;}
var prependSlides=[],appendSlides=[],i;slides.each(function(index,el){var slide=$(this);if(index<s.loopedSlides)appendSlides.push(el);if(index<slides.length&&index>=slides.length-s.loopedSlides)prependSlides.push(el);slide.attr('data-swiper-slide-index',index);});for(i=0;i<appendSlides.length;i++){s.wrapper.append($(appendSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass));}
for(i=prependSlides.length-1;i>=0;i--){s.wrapper.prepend($(prependSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass));}};s.destroyLoop=function(){s.wrapper.children('.'+s.params.slideClass+'.'+s.params.slideDuplicateClass).remove();s.slides.removeAttr('data-swiper-slide-index');};s.reLoop=function(updatePosition){var oldIndex=s.activeIndex-s.loopedSlides;s.destroyLoop();s.createLoop();s.updateSlidesSize();if(updatePosition){s.slideTo(oldIndex+s.loopedSlides,0,false);}};s.fixLoop=function(){var newIndex;if(s.activeIndex<s.loopedSlides){newIndex=s.slides.length-s.loopedSlides*3+s.activeIndex;newIndex=newIndex+s.loopedSlides;s.slideTo(newIndex,0,false,true);}
else if((s.params.slidesPerView==='auto'&&s.activeIndex>=s.loopedSlides*2)||(s.activeIndex>s.slides.length-s.params.slidesPerView*2)){newIndex=-s.slides.length+s.activeIndex+s.loopedSlides;newIndex=newIndex+s.loopedSlides;s.slideTo(newIndex,0,false,true);}};s.appendSlide=function(slides){if(s.params.loop){s.destroyLoop();}
if(typeof slides==='object'&&slides.length){for(var i=0;i<slides.length;i++){if(slides[i])s.wrapper.append(slides[i]);}}
else{s.wrapper.append(slides);}
if(s.params.loop){s.createLoop();}
if(!(s.params.observer&&s.support.observer)){s.update(true);}};s.prependSlide=function(slides){if(s.params.loop){s.destroyLoop();}
var newActiveIndex=s.activeIndex+1;if(typeof slides==='object'&&slides.length){for(var i=0;i<slides.length;i++){if(slides[i])s.wrapper.prepend(slides[i]);}
newActiveIndex=s.activeIndex+slides.length;}
else{s.wrapper.prepend(slides);}
if(s.params.loop){s.createLoop();}
if(!(s.params.observer&&s.support.observer)){s.update(true);}
s.slideTo(newActiveIndex,0,false);};s.removeSlide=function(slidesIndexes){if(s.params.loop){s.destroyLoop();s.slides=s.wrapper.children('.'+s.params.slideClass);}
var newActiveIndex=s.activeIndex,indexToRemove;if(typeof slidesIndexes==='object'&&slidesIndexes.length){for(var i=0;i<slidesIndexes.length;i++){indexToRemove=slidesIndexes[i];if(s.slides[indexToRemove])s.slides.eq(indexToRemove).remove();if(indexToRemove<newActiveIndex)newActiveIndex--;}
newActiveIndex=Math.max(newActiveIndex,0);}
else{indexToRemove=slidesIndexes;if(s.slides[indexToRemove])s.slides.eq(indexToRemove).remove();if(indexToRemove<newActiveIndex)newActiveIndex--;newActiveIndex=Math.max(newActiveIndex,0);}
if(s.params.loop){s.createLoop();}
if(!(s.params.observer&&s.support.observer)){s.update(true);}
if(s.params.loop){s.slideTo(newActiveIndex+s.loopedSlides,0,false);}
else{s.slideTo(newActiveIndex,0,false);}};s.removeAllSlides=function(){var slidesIndexes=[];for(var i=0;i<s.slides.length;i++){slidesIndexes.push(i);}
s.removeSlide(slidesIndexes);};s.effects={fade:{setTranslate:function(){for(var i=0;i<s.slides.length;i++){var slide=s.slides.eq(i);var offset=slide[0].swiperSlideOffset;var tx=-offset;if(!s.params.virtualTranslate)tx=tx-s.translate;var ty=0;if(!s.isHorizontal()){ty=tx;tx=0;}
var slideOpacity=s.params.fade.crossFade?Math.max(1-Math.abs(slide[0].progress),0):1+Math.min(Math.max(slide[0].progress,-1),0);slide.css({opacity:slideOpacity}).transform('translate3d('+tx+'px, '+ty+'px, 0px)');}},setTransition:function(duration){s.slides.transition(duration);if(s.params.virtualTranslate&&duration!==0){var eventTriggered=false;s.slides.transitionEnd(function(){if(eventTriggered)return;if(!s)return;eventTriggered=true;s.animating=false;var triggerEvents=['webkitTransitionEnd','transitionend','oTransitionEnd','MSTransitionEnd','msTransitionEnd'];for(var i=0;i<triggerEvents.length;i++){s.wrapper.trigger(triggerEvents[i]);}});}}},flip:{setTranslate:function(){for(var i=0;i<s.slides.length;i++){var slide=s.slides.eq(i);var progress=slide[0].progress;if(s.params.flip.limitRotation){progress=Math.max(Math.min(slide[0].progress,1),-1);}
var offset=slide[0].swiperSlideOffset;var rotate=-180*progress,rotateY=rotate,rotateX=0,tx=-offset,ty=0;if(!s.isHorizontal()){ty=tx;tx=0;rotateX=-rotateY;rotateY=0;}
else if(s.rtl){rotateY=-rotateY;}
slide[0].style.zIndex=-Math.abs(Math.round(progress))+s.slides.length;if(s.params.flip.slideShadows){var shadowBefore=s.isHorizontal()?slide.find('.swiper-slide-shadow-left'):slide.find('.swiper-slide-shadow-top');var shadowAfter=s.isHorizontal()?slide.find('.swiper-slide-shadow-right'):slide.find('.swiper-slide-shadow-bottom');if(shadowBefore.length===0){shadowBefore=$('<div class="swiper-slide-shadow-'+(s.isHorizontal()?'left':'top')+'"></div>');slide.append(shadowBefore);}
if(shadowAfter.length===0){shadowAfter=$('<div class="swiper-slide-shadow-'+(s.isHorizontal()?'right':'bottom')+'"></div>');slide.append(shadowAfter);}
if(shadowBefore.length)shadowBefore[0].style.opacity=Math.max(-progress,0);if(shadowAfter.length)shadowAfter[0].style.opacity=Math.max(progress,0);}
slide.transform('translate3d('+tx+'px, '+ty+'px, 0px) rotateX('+rotateX+'deg) rotateY('+rotateY+'deg)');}},setTransition:function(duration){s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);if(s.params.virtualTranslate&&duration!==0){var eventTriggered=false;s.slides.eq(s.activeIndex).transitionEnd(function(){if(eventTriggered)return;if(!s)return;if(!$(this).hasClass(s.params.slideActiveClass))return;eventTriggered=true;s.animating=false;var triggerEvents=['webkitTransitionEnd','transitionend','oTransitionEnd','MSTransitionEnd','msTransitionEnd'];for(var i=0;i<triggerEvents.length;i++){s.wrapper.trigger(triggerEvents[i]);}});}}},cube:{setTranslate:function(){var wrapperRotate=0,cubeShadow;if(s.params.cube.shadow){if(s.isHorizontal()){cubeShadow=s.wrapper.find('.swiper-cube-shadow');if(cubeShadow.length===0){cubeShadow=$('<div class="swiper-cube-shadow"></div>');s.wrapper.append(cubeShadow);}
cubeShadow.css({height:s.width+'px'});}
else{cubeShadow=s.container.find('.swiper-cube-shadow');if(cubeShadow.length===0){cubeShadow=$('<div class="swiper-cube-shadow"></div>');s.container.append(cubeShadow);}}}
for(var i=0;i<s.slides.length;i++){var slide=s.slides.eq(i);var slideAngle=i*90;var round=Math.floor(slideAngle / 360);if(s.rtl){slideAngle=-slideAngle;round=Math.floor(-slideAngle / 360);}
var progress=Math.max(Math.min(slide[0].progress,1),-1);var tx=0,ty=0,tz=0;if(i%4===0){tx=-round*4*s.size;tz=0;}
else if((i-1)%4===0){tx=0;tz=-round*4*s.size;}
else if((i-2)%4===0){tx=s.size+round*4*s.size;tz=s.size;}
else if((i-3)%4===0){tx=-s.size;tz=3*s.size+s.size*4*round;}
if(s.rtl){tx=-tx;}
if(!s.isHorizontal()){ty=tx;tx=0;}
var transform='rotateX('+(s.isHorizontal()?0:-slideAngle)+'deg) rotateY('+(s.isHorizontal()?slideAngle:0)+'deg) translate3d('+tx+'px, '+ty+'px, '+tz+'px)';if(progress<=1&&progress>-1){wrapperRotate=i*90+progress*90;if(s.rtl)wrapperRotate=-i*90-progress*90;}
slide.transform(transform);if(s.params.cube.slideShadows){var shadowBefore=s.isHorizontal()?slide.find('.swiper-slide-shadow-left'):slide.find('.swiper-slide-shadow-top');var shadowAfter=s.isHorizontal()?slide.find('.swiper-slide-shadow-right'):slide.find('.swiper-slide-shadow-bottom');if(shadowBefore.length===0){shadowBefore=$('<div class="swiper-slide-shadow-'+(s.isHorizontal()?'left':'top')+'"></div>');slide.append(shadowBefore);}
if(shadowAfter.length===0){shadowAfter=$('<div class="swiper-slide-shadow-'+(s.isHorizontal()?'right':'bottom')+'"></div>');slide.append(shadowAfter);}
if(shadowBefore.length)shadowBefore[0].style.opacity=Math.max(-progress,0);if(shadowAfter.length)shadowAfter[0].style.opacity=Math.max(progress,0);}}
s.wrapper.css({'-webkit-transform-origin':'50% 50% -'+(s.size / 2)+'px','-moz-transform-origin':'50% 50% -'+(s.size / 2)+'px','-ms-transform-origin':'50% 50% -'+(s.size / 2)+'px','transform-origin':'50% 50% -'+(s.size / 2)+'px'});if(s.params.cube.shadow){if(s.isHorizontal()){cubeShadow.transform('translate3d(0px, '+(s.width / 2+s.params.cube.shadowOffset)+'px, '+(-s.width / 2)+'px) rotateX(90deg) rotateZ(0deg) scale('+(s.params.cube.shadowScale)+')');}
else{var shadowAngle=Math.abs(wrapperRotate)-Math.floor(Math.abs(wrapperRotate)/ 90)*90;var multiplier=1.5-(Math.sin(shadowAngle*2*Math.PI / 360)/ 2+Math.cos(shadowAngle*2*Math.PI / 360)/ 2);var scale1=s.params.cube.shadowScale,scale2=s.params.cube.shadowScale / multiplier,offset=s.params.cube.shadowOffset;cubeShadow.transform('scale3d('+scale1+', 1, '+scale2+') translate3d(0px, '+(s.height / 2+offset)+'px, '+(-s.height / 2 / scale2)+'px) rotateX(-90deg)');}}
var zFactor=(s.isSafari||s.isUiWebView)?(-s.size / 2):0;s.wrapper.transform('translate3d(0px,0,'+zFactor+'px) rotateX('+(s.isHorizontal()?0:wrapperRotate)+'deg) rotateY('+(s.isHorizontal()?-wrapperRotate:0)+'deg)');},setTransition:function(duration){s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);if(s.params.cube.shadow&&!s.isHorizontal()){s.container.find('.swiper-cube-shadow').transition(duration);}}},coverflow:{setTranslate:function(){var transform=s.translate;var center=s.isHorizontal()?-transform+s.width / 2:-transform+s.height / 2;var rotate=s.isHorizontal()?s.params.coverflow.rotate:-s.params.coverflow.rotate;var translate=s.params.coverflow.depth;for(var i=0,length=s.slides.length;i<length;i++){var slide=s.slides.eq(i);var slideSize=s.slidesSizesGrid[i];var slideOffset=slide[0].swiperSlideOffset;var offsetMultiplier=(center-slideOffset-slideSize / 2)/ slideSize*s.params.coverflow.modifier;var rotateY=s.isHorizontal()?rotate*offsetMultiplier:0;var rotateX=s.isHorizontal()?0:rotate*offsetMultiplier;var translateZ=-translate*Math.abs(offsetMultiplier);var translateY=s.isHorizontal()?0:s.params.coverflow.stretch*(offsetMultiplier);var translateX=s.isHorizontal()?s.params.coverflow.stretch*(offsetMultiplier):0;if(Math.abs(translateX)<0.001)translateX=0;if(Math.abs(translateY)<0.001)translateY=0;if(Math.abs(translateZ)<0.001)translateZ=0;if(Math.abs(rotateY)<0.001)rotateY=0;if(Math.abs(rotateX)<0.001)rotateX=0;var slideTransform='translate3d('+translateX+'px,'+translateY+'px,'+translateZ+'px)  rotateX('+rotateX+'deg) rotateY('+rotateY+'deg)';slide.transform(slideTransform);slide[0].style.zIndex=-Math.abs(Math.round(offsetMultiplier))+1;if(s.params.coverflow.slideShadows){var shadowBefore=s.isHorizontal()?slide.find('.swiper-slide-shadow-left'):slide.find('.swiper-slide-shadow-top');var shadowAfter=s.isHorizontal()?slide.find('.swiper-slide-shadow-right'):slide.find('.swiper-slide-shadow-bottom');if(shadowBefore.length===0){shadowBefore=$('<div class="swiper-slide-shadow-'+(s.isHorizontal()?'left':'top')+'"></div>');slide.append(shadowBefore);}
if(shadowAfter.length===0){shadowAfter=$('<div class="swiper-slide-shadow-'+(s.isHorizontal()?'right':'bottom')+'"></div>');slide.append(shadowAfter);}
if(shadowBefore.length)shadowBefore[0].style.opacity=offsetMultiplier>0?offsetMultiplier:0;if(shadowAfter.length)shadowAfter[0].style.opacity=(-offsetMultiplier)>0?-offsetMultiplier:0;}}
if(s.browser.ie){var ws=s.wrapper[0].style;ws.perspectiveOrigin=center+'px 50%';}},setTransition:function(duration){s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);}}};s.lazy={initialImageLoaded:false,loadImageInSlide:function(index,loadInDuplicate){if(typeof index==='undefined')return;if(typeof loadInDuplicate==='undefined')loadInDuplicate=true;if(s.slides.length===0)return;var slide=s.slides.eq(index);var img=slide.find('.'+s.params.lazyLoadingClass+':not(.'+s.params.lazyStatusLoadedClass+'):not(.'+s.params.lazyStatusLoadingClass+')');if(slide.hasClass(s.params.lazyLoadingClass)&&!slide.hasClass(s.params.lazyStatusLoadedClass)&&!slide.hasClass(s.params.lazyStatusLoadingClass)){img=img.add(slide[0]);}
if(img.length===0)return;img.each(function(){var _img=$(this);_img.addClass(s.params.lazyStatusLoadingClass);var background=_img.attr('data-background');var src=_img.attr('data-src'),srcset=_img.attr('data-srcset'),sizes=_img.attr('data-sizes');s.loadImage(_img[0],(src||background),srcset,sizes,false,function(){if(typeof s==='undefined'||s===null||!s)return;if(background){_img.css('background-image','url("'+background+'")');_img.removeAttr('data-background');}
else{if(srcset){_img.attr('srcset',srcset);_img.removeAttr('data-srcset');}
if(sizes){_img.attr('sizes',sizes);_img.removeAttr('data-sizes');}
if(src){_img.attr('src',src);_img.removeAttr('data-src');}}
_img.addClass(s.params.lazyStatusLoadedClass).removeClass(s.params.lazyStatusLoadingClass);slide.find('.'+s.params.lazyPreloaderClass+', .'+s.params.preloaderClass).remove();if(s.params.loop&&loadInDuplicate){var slideOriginalIndex=slide.attr('data-swiper-slide-index');if(slide.hasClass(s.params.slideDuplicateClass)){var originalSlide=s.wrapper.children('[data-swiper-slide-index="'+slideOriginalIndex+'"]:not(.'+s.params.slideDuplicateClass+')');s.lazy.loadImageInSlide(originalSlide.index(),false);}
else{var duplicatedSlide=s.wrapper.children('.'+s.params.slideDuplicateClass+'[data-swiper-slide-index="'+slideOriginalIndex+'"]');s.lazy.loadImageInSlide(duplicatedSlide.index(),false);}}
s.emit('onLazyImageReady',s,slide[0],_img[0]);});s.emit('onLazyImageLoad',s,slide[0],_img[0]);});},load:function(){var i;var slidesPerView=s.params.slidesPerView;if(slidesPerView==='auto'){slidesPerView=0;}
if(!s.lazy.initialImageLoaded)s.lazy.initialImageLoaded=true;if(s.params.watchSlidesVisibility){s.wrapper.children('.'+s.params.slideVisibleClass).each(function(){s.lazy.loadImageInSlide($(this).index());});}
else{if(slidesPerView>1){for(i=s.activeIndex;i<s.activeIndex+slidesPerView;i++){if(s.slides[i])s.lazy.loadImageInSlide(i);}}
else{s.lazy.loadImageInSlide(s.activeIndex);}}
if(s.params.lazyLoadingInPrevNext){if(slidesPerView>1||(s.params.lazyLoadingInPrevNextAmount&&s.params.lazyLoadingInPrevNextAmount>1)){var amount=s.params.lazyLoadingInPrevNextAmount;var spv=slidesPerView;var maxIndex=Math.min(s.activeIndex+spv+Math.max(amount,spv),s.slides.length);var minIndex=Math.max(s.activeIndex-Math.max(spv,amount),0);for(i=s.activeIndex+slidesPerView;i<maxIndex;i++){if(s.slides[i])s.lazy.loadImageInSlide(i);}
for(i=minIndex;i<s.activeIndex;i++){if(s.slides[i])s.lazy.loadImageInSlide(i);}}
else{var nextSlide=s.wrapper.children('.'+s.params.slideNextClass);if(nextSlide.length>0)s.lazy.loadImageInSlide(nextSlide.index());var prevSlide=s.wrapper.children('.'+s.params.slidePrevClass);if(prevSlide.length>0)s.lazy.loadImageInSlide(prevSlide.index());}}},onTransitionStart:function(){if(s.params.lazyLoading){if(s.params.lazyLoadingOnTransitionStart||(!s.params.lazyLoadingOnTransitionStart&&!s.lazy.initialImageLoaded)){s.lazy.load();}}},onTransitionEnd:function(){if(s.params.lazyLoading&&!s.params.lazyLoadingOnTransitionStart){s.lazy.load();}}};s.scrollbar={isTouched:false,setDragPosition:function(e){var sb=s.scrollbar;var x=0,y=0;var translate;var pointerPosition=s.isHorizontal()?((e.type==='touchstart'||e.type==='touchmove')?e.targetTouches[0].pageX:e.pageX||e.clientX):((e.type==='touchstart'||e.type==='touchmove')?e.targetTouches[0].pageY:e.pageY||e.clientY);var position=(pointerPosition)-sb.track.offset()[s.isHorizontal()?'left':'top']-sb.dragSize / 2;var positionMin=-s.minTranslate()*sb.moveDivider;var positionMax=-s.maxTranslate()*sb.moveDivider;if(position<positionMin){position=positionMin;}
else if(position>positionMax){position=positionMax;}
position=-position / sb.moveDivider;s.updateProgress(position);s.setWrapperTranslate(position,true);},dragStart:function(e){var sb=s.scrollbar;sb.isTouched=true;e.preventDefault();e.stopPropagation();sb.setDragPosition(e);clearTimeout(sb.dragTimeout);sb.track.transition(0);if(s.params.scrollbarHide){sb.track.css('opacity',1);}
s.wrapper.transition(100);sb.drag.transition(100);s.emit('onScrollbarDragStart',s);},dragMove:function(e){var sb=s.scrollbar;if(!sb.isTouched)return;if(e.preventDefault)e.preventDefault();else e.returnValue=false;sb.setDragPosition(e);s.wrapper.transition(0);sb.track.transition(0);sb.drag.transition(0);s.emit('onScrollbarDragMove',s);},dragEnd:function(e){var sb=s.scrollbar;if(!sb.isTouched)return;sb.isTouched=false;if(s.params.scrollbarHide){clearTimeout(sb.dragTimeout);sb.dragTimeout=setTimeout(function(){sb.track.css('opacity',0);sb.track.transition(400);},1000);}
s.emit('onScrollbarDragEnd',s);if(s.params.scrollbarSnapOnRelease){s.slideReset();}},draggableEvents:(function(){if((s.params.simulateTouch===false&&!s.support.touch))return s.touchEventsDesktop;else return s.touchEvents;})(),enableDraggable:function(){var sb=s.scrollbar;var target=s.support.touch?sb.track:document;$(sb.track).on(sb.draggableEvents.start,sb.dragStart);$(target).on(sb.draggableEvents.move,sb.dragMove);$(target).on(sb.draggableEvents.end,sb.dragEnd);},disableDraggable:function(){var sb=s.scrollbar;var target=s.support.touch?sb.track:document;$(sb.track).off(sb.draggableEvents.start,sb.dragStart);$(target).off(sb.draggableEvents.move,sb.dragMove);$(target).off(sb.draggableEvents.end,sb.dragEnd);},set:function(){if(!s.params.scrollbar)return;var sb=s.scrollbar;sb.track=$(s.params.scrollbar);if(s.params.uniqueNavElements&&typeof s.params.scrollbar==='string'&&sb.track.length>1&&s.container.find(s.params.scrollbar).length===1){sb.track=s.container.find(s.params.scrollbar);}
sb.drag=sb.track.find('.swiper-scrollbar-drag');if(sb.drag.length===0){sb.drag=$('<div class="swiper-scrollbar-drag"></div>');sb.track.append(sb.drag);}
sb.drag[0].style.width='';sb.drag[0].style.height='';sb.trackSize=s.isHorizontal()?sb.track[0].offsetWidth:sb.track[0].offsetHeight;sb.divider=s.size / s.virtualSize;sb.moveDivider=sb.divider*(sb.trackSize / s.size);sb.dragSize=sb.trackSize*sb.divider;if(s.isHorizontal()){sb.drag[0].style.width=sb.dragSize+'px';}
else{sb.drag[0].style.height=sb.dragSize+'px';}
if(sb.divider>=1){sb.track[0].style.display='none';}
else{sb.track[0].style.display='';}
if(s.params.scrollbarHide){sb.track[0].style.opacity=0;}},setTranslate:function(){if(!s.params.scrollbar)return;var diff;var sb=s.scrollbar;var translate=s.translate||0;var newPos;var newSize=sb.dragSize;newPos=(sb.trackSize-sb.dragSize)*s.progress;if(s.rtl&&s.isHorizontal()){newPos=-newPos;if(newPos>0){newSize=sb.dragSize-newPos;newPos=0;}
else if(-newPos+sb.dragSize>sb.trackSize){newSize=sb.trackSize+newPos;}}
else{if(newPos<0){newSize=sb.dragSize+newPos;newPos=0;}
else if(newPos+sb.dragSize>sb.trackSize){newSize=sb.trackSize-newPos;}}
if(s.isHorizontal()){if(s.support.transforms3d){sb.drag.transform('translate3d('+(newPos)+'px, 0, 0)');}
else{sb.drag.transform('translateX('+(newPos)+'px)');}
sb.drag[0].style.width=newSize+'px';}
else{if(s.support.transforms3d){sb.drag.transform('translate3d(0px, '+(newPos)+'px, 0)');}
else{sb.drag.transform('translateY('+(newPos)+'px)');}
sb.drag[0].style.height=newSize+'px';}
if(s.params.scrollbarHide){clearTimeout(sb.timeout);sb.track[0].style.opacity=1;sb.timeout=setTimeout(function(){sb.track[0].style.opacity=0;sb.track.transition(400);},1000);}},setTransition:function(duration){if(!s.params.scrollbar)return;s.scrollbar.drag.transition(duration);}};s.controller={LinearSpline:function(x,y){var binarySearch=(function(){var maxIndex,minIndex,guess;return function(array,val){minIndex=-1;maxIndex=array.length;while(maxIndex-minIndex>1)
if(array[guess=maxIndex+minIndex>>1]<=val){minIndex=guess;}else{maxIndex=guess;}
return maxIndex;};})();this.x=x;this.y=y;this.lastIndex=x.length-1;var i1,i3;var l=this.x.length;this.interpolate=function(x2){if(!x2)return 0;i3=binarySearch(this.x,x2);i1=i3-1;return((x2-this.x[i1])*(this.y[i3]-this.y[i1]))/(this.x[i3]-this.x[i1])+this.y[i1];};},getInterpolateFunction:function(c){if(!s.controller.spline)s.controller.spline=s.params.loop?new s.controller.LinearSpline(s.slidesGrid,c.slidesGrid):new s.controller.LinearSpline(s.snapGrid,c.snapGrid);},setTranslate:function(translate,byController){var controlled=s.params.control;var multiplier,controlledTranslate;function setControlledTranslate(c){translate=c.rtl&&c.params.direction==='horizontal'?-s.translate:s.translate;if(s.params.controlBy==='slide'){s.controller.getInterpolateFunction(c);controlledTranslate=-s.controller.spline.interpolate(-translate);}
if(!controlledTranslate||s.params.controlBy==='container'){multiplier=(c.maxTranslate()-c.minTranslate())/(s.maxTranslate()-s.minTranslate());controlledTranslate=(translate-s.minTranslate())*multiplier+c.minTranslate();}
if(s.params.controlInverse){controlledTranslate=c.maxTranslate()-controlledTranslate;}
c.updateProgress(controlledTranslate);c.setWrapperTranslate(controlledTranslate,false,s);c.updateActiveIndex();}
if(Array.isArray(controlled)){for(var i=0;i<controlled.length;i++){if(controlled[i]!==byController&&controlled[i]instanceof Swiper){setControlledTranslate(controlled[i]);}}}
else if(controlled instanceof Swiper&&byController!==controlled){setControlledTranslate(controlled);}},setTransition:function(duration,byController){var controlled=s.params.control;var i;function setControlledTransition(c){c.setWrapperTransition(duration,s);if(duration!==0){c.onTransitionStart();c.wrapper.transitionEnd(function(){if(!controlled)return;if(c.params.loop&&s.params.controlBy==='slide'){c.fixLoop();}
c.onTransitionEnd();});}}
if(Array.isArray(controlled)){for(i=0;i<controlled.length;i++){if(controlled[i]!==byController&&controlled[i]instanceof Swiper){setControlledTransition(controlled[i]);}}}
else if(controlled instanceof Swiper&&byController!==controlled){setControlledTransition(controlled);}}};s.hashnav={onHashCange:function(e,a){var newHash=document.location.hash.replace('#','');var activeSlideHash=s.slides.eq(s.activeIndex).attr('data-hash');if(newHash!==activeSlideHash){s.slideTo(s.wrapper.children('.'+s.params.slideClass+'[data-hash="'+(newHash)+'"]').index());}},attachEvents:function(detach){var action=detach?'off':'on';$(window)[action]('hashchange',s.hashnav.onHashCange);},setHash:function(){if(!s.hashnav.initialized||!s.params.hashnav)return;if(s.params.replaceState&&window.history&&window.history.replaceState){window.history.replaceState(null,null,('#'+s.slides.eq(s.activeIndex).attr('data-hash')||''));}else{var slide=s.slides.eq(s.activeIndex);var hash=slide.attr('data-hash')||slide.attr('data-history');document.location.hash=hash||'';}},init:function(){if(!s.params.hashnav||s.params.history)return;s.hashnav.initialized=true;var hash=document.location.hash.replace('#','');if(hash){var speed=0;for(var i=0,length=s.slides.length;i<length;i++){var slide=s.slides.eq(i);var slideHash=slide.attr('data-hash')||slide.attr('data-history');if(slideHash===hash&&!slide.hasClass(s.params.slideDuplicateClass)){var index=slide.index();s.slideTo(index,speed,s.params.runCallbacksOnInit,true);}}}
if(s.params.hashnavWatchState)s.hashnav.attachEvents();},destroy:function(){if(s.params.hashnavWatchState)s.hashnav.attachEvents(true);}};s.history={init:function(){if(!s.params.history)return;if(!window.history||!window.history.pushState){s.params.history=false;s.params.hashnav=true;return;}
s.history.initialized=true;this.paths=this.getPathValues();if(!this.paths.key&&!this.paths.value)return;this.scrollToSlide(0,this.paths.value,s.params.runCallbacksOnInit);if(!s.params.replaceState){window.addEventListener('popstate',this.setHistoryPopState);}},setHistoryPopState:function(){s.history.paths=s.history.getPathValues();s.history.scrollToSlide(s.params.speed,s.history.paths.value,false);},getPathValues:function(){var pathArray=window.location.pathname.slice(1).split('/');var total=pathArray.length;var key=pathArray[total-2];var value=pathArray[total-1];return{key:key,value:value};},setHistory:function(key,index){if(!s.history.initialized||!s.params.history)return;var slide=s.slides.eq(index);var value=this.slugify(slide.attr('data-history'));if(!window.location.pathname.includes(key)){value=key+'/'+value;}
if(s.params.replaceState){window.history.replaceState(null,null,value);}else{window.history.pushState(null,null,value);}},slugify:function(text){return text.toString().toLowerCase().replace(/\s+/g,'-').replace(/[^\w\-]+/g,'').replace(/\-\-+/g,'-').replace(/^-+/,'').replace(/-+$/,'');},scrollToSlide:function(speed,value,runCallbacks){if(value){for(var i=0,length=s.slides.length;i<length;i++){var slide=s.slides.eq(i);var slideHistory=this.slugify(slide.attr('data-history'));if(slideHistory===value&&!slide.hasClass(s.params.slideDuplicateClass)){var index=slide.index();s.slideTo(index,speed,runCallbacks);}}}else{s.slideTo(0,speed,runCallbacks);}}};function handleKeyboard(e){if(e.originalEvent)e=e.originalEvent;var kc=e.keyCode||e.charCode;if(!s.params.allowSwipeToNext&&(s.isHorizontal()&&kc===39||!s.isHorizontal()&&kc===40)){return false;}
if(!s.params.allowSwipeToPrev&&(s.isHorizontal()&&kc===37||!s.isHorizontal()&&kc===38)){return false;}
if(e.shiftKey||e.altKey||e.ctrlKey||e.metaKey){return;}
if(document.activeElement&&document.activeElement.nodeName&&(document.activeElement.nodeName.toLowerCase()==='input'||document.activeElement.nodeName.toLowerCase()==='textarea')){return;}
if(kc===37||kc===39||kc===38||kc===40){var inView=false;if(s.container.parents('.'+s.params.slideClass).length>0&&s.container.parents('.'+s.params.slideActiveClass).length===0){return;}
var windowScroll={left:window.pageXOffset,top:window.pageYOffset};var windowWidth=window.innerWidth;var windowHeight=window.innerHeight;var swiperOffset=s.container.offset();if(s.rtl)swiperOffset.left=swiperOffset.left-s.container[0].scrollLeft;var swiperCoord=[[swiperOffset.left,swiperOffset.top],[swiperOffset.left+s.width,swiperOffset.top],[swiperOffset.left,swiperOffset.top+s.height],[swiperOffset.left+s.width,swiperOffset.top+s.height]];for(var i=0;i<swiperCoord.length;i++){var point=swiperCoord[i];if(point[0]>=windowScroll.left&&point[0]<=windowScroll.left+windowWidth&&point[1]>=windowScroll.top&&point[1]<=windowScroll.top+windowHeight){inView=true;}}
if(!inView)return;}
if(s.isHorizontal()){if(kc===37||kc===39){if(e.preventDefault)e.preventDefault();else e.returnValue=false;}
if((kc===39&&!s.rtl)||(kc===37&&s.rtl))s.slideNext();if((kc===37&&!s.rtl)||(kc===39&&s.rtl))s.slidePrev();}
else{if(kc===38||kc===40){if(e.preventDefault)e.preventDefault();else e.returnValue=false;}
if(kc===40)s.slideNext();if(kc===38)s.slidePrev();}
s.emit('onKeyPress',s,kc);}
s.disableKeyboardControl=function(){s.params.keyboardControl=false;$(document).off('keydown',handleKeyboard);};s.enableKeyboardControl=function(){s.params.keyboardControl=true;$(document).on('keydown',handleKeyboard);};s.mousewheel={event:false,lastScrollTime:(new window.Date()).getTime()};function isEventSupported(){var eventName='onwheel';var isSupported=eventName in document;if(!isSupported){var element=document.createElement('div');element.setAttribute(eventName,'return;');isSupported=typeof element[eventName]==='function';}
if(!isSupported&&document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature('','')!==true){isSupported=document.implementation.hasFeature('Events.wheel','3.0');}
return isSupported;}
function normalizeWheel(event){var PIXEL_STEP=10;var LINE_HEIGHT=40;var PAGE_HEIGHT=800;var sX=0,sY=0,pX=0,pY=0;if('detail'in event){sY=event.detail;}
if('wheelDelta'in event){sY=-event.wheelDelta / 120;}
if('wheelDeltaY'in event){sY=-event.wheelDeltaY / 120;}
if('wheelDeltaX'in event){sX=-event.wheelDeltaX / 120;}
if('axis'in event&&event.axis===event.HORIZONTAL_AXIS){sX=sY;sY=0;}
pX=sX*PIXEL_STEP;pY=sY*PIXEL_STEP;if('deltaY'in event){pY=event.deltaY;}
if('deltaX'in event){pX=event.deltaX;}
if((pX||pY)&&event.deltaMode){if(event.deltaMode===1){pX*=LINE_HEIGHT;pY*=LINE_HEIGHT;}else{pX*=PAGE_HEIGHT;pY*=PAGE_HEIGHT;}}
if(pX&&!sX){sX=(pX<1)?-1:1;}
if(pY&&!sY){sY=(pY<1)?-1:1;}
return{spinX:sX,spinY:sY,pixelX:pX,pixelY:pY};}
if(s.params.mousewheelControl){s.mousewheel.event=(navigator.userAgent.indexOf('firefox')>-1)?'DOMMouseScroll':isEventSupported()?'wheel':'mousewheel';}
function handleMousewheel(e){if(e.originalEvent)e=e.originalEvent;var delta=0;var rtlFactor=s.rtl?-1:1;var data=normalizeWheel(e);if(s.params.mousewheelForceToAxis){if(s.isHorizontal()){if(Math.abs(data.pixelX)>Math.abs(data.pixelY))delta=data.pixelX*rtlFactor;else return;}
else{if(Math.abs(data.pixelY)>Math.abs(data.pixelX))delta=data.pixelY;else return;}}
else{delta=Math.abs(data.pixelX)>Math.abs(data.pixelY)?-data.pixelX*rtlFactor:-data.pixelY;}
if(delta===0)return;if(s.params.mousewheelInvert)delta=-delta;if(!s.params.freeMode){if((new window.Date()).getTime()-s.mousewheel.lastScrollTime>60){if(delta<0){if((!s.isEnd||s.params.loop)&&!s.animating){s.slideNext();s.emit('onScroll',s,e);}
else if(s.params.mousewheelReleaseOnEdges)return true;}
else{if((!s.isBeginning||s.params.loop)&&!s.animating){s.slidePrev();s.emit('onScroll',s,e);}
else if(s.params.mousewheelReleaseOnEdges)return true;}}
s.mousewheel.lastScrollTime=(new window.Date()).getTime();}
else{var position=s.getWrapperTranslate()+delta*s.params.mousewheelSensitivity;var wasBeginning=s.isBeginning,wasEnd=s.isEnd;if(position>=s.minTranslate())position=s.minTranslate();if(position<=s.maxTranslate())position=s.maxTranslate();s.setWrapperTransition(0);s.setWrapperTranslate(position);s.updateProgress();s.updateActiveIndex();if(!wasBeginning&&s.isBeginning||!wasEnd&&s.isEnd){s.updateClasses();}
if(s.params.freeModeSticky){clearTimeout(s.mousewheel.timeout);s.mousewheel.timeout=setTimeout(function(){s.slideReset();},300);}
else{if(s.params.lazyLoading&&s.lazy){s.lazy.load();}}
s.emit('onScroll',s,e);if(s.params.autoplay&&s.params.autoplayDisableOnInteraction)s.stopAutoplay();if(position===0||position===s.maxTranslate())return;}
if(e.preventDefault)e.preventDefault();else e.returnValue=false;return false;}
s.disableMousewheelControl=function(){if(!s.mousewheel.event)return false;var target=s.container;if(s.params.mousewheelEventsTarged!=='container'){target=$(s.params.mousewheelEventsTarged);}
target.off(s.mousewheel.event,handleMousewheel);s.params.mousewheelControl=false;return true;};s.enableMousewheelControl=function(){if(!s.mousewheel.event)return false;var target=s.container;if(s.params.mousewheelEventsTarged!=='container'){target=$(s.params.mousewheelEventsTarged);}
target.on(s.mousewheel.event,handleMousewheel);s.params.mousewheelControl=true;return true;};function setParallaxTransform(el,progress){el=$(el);var p,pX,pY;var rtlFactor=s.rtl?-1:1;p=el.attr('data-swiper-parallax')||'0';pX=el.attr('data-swiper-parallax-x');pY=el.attr('data-swiper-parallax-y');if(pX||pY){pX=pX||'0';pY=pY||'0';}
else{if(s.isHorizontal()){pX=p;pY='0';}
else{pY=p;pX='0';}}
if((pX).indexOf('%')>=0){pX=parseInt(pX,10)*progress*rtlFactor+'%';}
else{pX=pX*progress*rtlFactor+'px';}
if((pY).indexOf('%')>=0){pY=parseInt(pY,10)*progress+'%';}
else{pY=pY*progress+'px';}
el.transform('translate3d('+pX+', '+pY+',0px)');}
s.parallax={setTranslate:function(){s.container.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){setParallaxTransform(this,s.progress);});s.slides.each(function(){var slide=$(this);slide.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){var progress=Math.min(Math.max(slide[0].progress,-1),1);setParallaxTransform(this,progress);});});},setTransition:function(duration){if(typeof duration==='undefined')duration=s.params.speed;s.container.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){var el=$(this);var parallaxDuration=parseInt(el.attr('data-swiper-parallax-duration'),10)||duration;if(duration===0)parallaxDuration=0;el.transition(parallaxDuration);});}};s.zoom={scale:1,currentScale:1,isScaling:false,gesture:{slide:undefined,slideWidth:undefined,slideHeight:undefined,image:undefined,imageWrap:undefined,zoomMax:s.params.zoomMax},image:{isTouched:undefined,isMoved:undefined,currentX:undefined,currentY:undefined,minX:undefined,minY:undefined,maxX:undefined,maxY:undefined,width:undefined,height:undefined,startX:undefined,startY:undefined,touchesStart:{},touchesCurrent:{}},velocity:{x:undefined,y:undefined,prevPositionX:undefined,prevPositionY:undefined,prevTime:undefined},getDistanceBetweenTouches:function(e){if(e.targetTouches.length<2)return 1;var x1=e.targetTouches[0].pageX,y1=e.targetTouches[0].pageY,x2=e.targetTouches[1].pageX,y2=e.targetTouches[1].pageY;var distance=Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2));return distance;},onGestureStart:function(e){var z=s.zoom;if(!s.support.gestures){if(e.type!=='touchstart'||e.type==='touchstart'&&e.targetTouches.length<2){return;}
z.gesture.scaleStart=z.getDistanceBetweenTouches(e);}
if(!z.gesture.slide||!z.gesture.slide.length){z.gesture.slide=$(this);if(z.gesture.slide.length===0)z.gesture.slide=s.slides.eq(s.activeIndex);z.gesture.image=z.gesture.slide.find('img, svg, canvas');z.gesture.imageWrap=z.gesture.image.parent('.'+s.params.zoomContainerClass);z.gesture.zoomMax=z.gesture.imageWrap.attr('data-swiper-zoom')||s.params.zoomMax;if(z.gesture.imageWrap.length===0){z.gesture.image=undefined;return;}}
z.gesture.image.transition(0);z.isScaling=true;},onGestureChange:function(e){var z=s.zoom;if(!s.support.gestures){if(e.type!=='touchmove'||e.type==='touchmove'&&e.targetTouches.length<2){return;}
z.gesture.scaleMove=z.getDistanceBetweenTouches(e);}
if(!z.gesture.image||z.gesture.image.length===0)return;if(s.support.gestures){z.scale=e.scale*z.currentScale;}
else{z.scale=(z.gesture.scaleMove / z.gesture.scaleStart)*z.currentScale;}
if(z.scale>z.gesture.zoomMax){z.scale=z.gesture.zoomMax-1+Math.pow((z.scale-z.gesture.zoomMax+1),0.5);}
if(z.scale<s.params.zoomMin){z.scale=s.params.zoomMin+1-Math.pow((s.params.zoomMin-z.scale+1),0.5);}
z.gesture.image.transform('translate3d(0,0,0) scale('+z.scale+')');},onGestureEnd:function(e){var z=s.zoom;if(!s.support.gestures){if(e.type!=='touchend'||e.type==='touchend'&&e.changedTouches.length<2){return;}}
if(!z.gesture.image||z.gesture.image.length===0)return;z.scale=Math.max(Math.min(z.scale,z.gesture.zoomMax),s.params.zoomMin);z.gesture.image.transition(s.params.speed).transform('translate3d(0,0,0) scale('+z.scale+')');z.currentScale=z.scale;z.isScaling=false;if(z.scale===1)z.gesture.slide=undefined;},onTouchStart:function(s,e){var z=s.zoom;if(!z.gesture.image||z.gesture.image.length===0)return;if(z.image.isTouched)return;if(s.device.os==='android')e.preventDefault();z.image.isTouched=true;z.image.touchesStart.x=e.type==='touchstart'?e.targetTouches[0].pageX:e.pageX;z.image.touchesStart.y=e.type==='touchstart'?e.targetTouches[0].pageY:e.pageY;},onTouchMove:function(e){var z=s.zoom;if(!z.gesture.image||z.gesture.image.length===0)return;s.allowClick=false;if(!z.image.isTouched||!z.gesture.slide)return;if(!z.image.isMoved){z.image.width=z.gesture.image[0].offsetWidth;z.image.height=z.gesture.image[0].offsetHeight;z.image.startX=s.getTranslate(z.gesture.imageWrap[0],'x')||0;z.image.startY=s.getTranslate(z.gesture.imageWrap[0],'y')||0;z.gesture.slideWidth=z.gesture.slide[0].offsetWidth;z.gesture.slideHeight=z.gesture.slide[0].offsetHeight;z.gesture.imageWrap.transition(0);if(s.rtl)z.image.startX=-z.image.startX;if(s.rtl)z.image.startY=-z.image.startY;}
var scaledWidth=z.image.width*z.scale;var scaledHeight=z.image.height*z.scale;if(scaledWidth<z.gesture.slideWidth&&scaledHeight<z.gesture.slideHeight)return;z.image.minX=Math.min((z.gesture.slideWidth / 2-scaledWidth / 2),0);z.image.maxX=-z.image.minX;z.image.minY=Math.min((z.gesture.slideHeight / 2-scaledHeight / 2),0);z.image.maxY=-z.image.minY;z.image.touchesCurrent.x=e.type==='touchmove'?e.targetTouches[0].pageX:e.pageX;z.image.touchesCurrent.y=e.type==='touchmove'?e.targetTouches[0].pageY:e.pageY;if(!z.image.isMoved&&!z.isScaling){if(s.isHorizontal()&&(Math.floor(z.image.minX)===Math.floor(z.image.startX)&&z.image.touchesCurrent.x<z.image.touchesStart.x)||(Math.floor(z.image.maxX)===Math.floor(z.image.startX)&&z.image.touchesCurrent.x>z.image.touchesStart.x)){z.image.isTouched=false;return;}
else if(!s.isHorizontal()&&(Math.floor(z.image.minY)===Math.floor(z.image.startY)&&z.image.touchesCurrent.y<z.image.touchesStart.y)||(Math.floor(z.image.maxY)===Math.floor(z.image.startY)&&z.image.touchesCurrent.y>z.image.touchesStart.y)){z.image.isTouched=false;return;}}
e.preventDefault();e.stopPropagation();z.image.isMoved=true;z.image.currentX=z.image.touchesCurrent.x-z.image.touchesStart.x+z.image.startX;z.image.currentY=z.image.touchesCurrent.y-z.image.touchesStart.y+z.image.startY;if(z.image.currentX<z.image.minX){z.image.currentX=z.image.minX+1-Math.pow((z.image.minX-z.image.currentX+1),0.8);}
if(z.image.currentX>z.image.maxX){z.image.currentX=z.image.maxX-1+Math.pow((z.image.currentX-z.image.maxX+1),0.8);}
if(z.image.currentY<z.image.minY){z.image.currentY=z.image.minY+1-Math.pow((z.image.minY-z.image.currentY+1),0.8);}
if(z.image.currentY>z.image.maxY){z.image.currentY=z.image.maxY-1+Math.pow((z.image.currentY-z.image.maxY+1),0.8);}
if(!z.velocity.prevPositionX)z.velocity.prevPositionX=z.image.touchesCurrent.x;if(!z.velocity.prevPositionY)z.velocity.prevPositionY=z.image.touchesCurrent.y;if(!z.velocity.prevTime)z.velocity.prevTime=Date.now();z.velocity.x=(z.image.touchesCurrent.x-z.velocity.prevPositionX)/(Date.now()-z.velocity.prevTime)/ 2;z.velocity.y=(z.image.touchesCurrent.y-z.velocity.prevPositionY)/(Date.now()-z.velocity.prevTime)/ 2;if(Math.abs(z.image.touchesCurrent.x-z.velocity.prevPositionX)<2)z.velocity.x=0;if(Math.abs(z.image.touchesCurrent.y-z.velocity.prevPositionY)<2)z.velocity.y=0;z.velocity.prevPositionX=z.image.touchesCurrent.x;z.velocity.prevPositionY=z.image.touchesCurrent.y;z.velocity.prevTime=Date.now();z.gesture.imageWrap.transform('translate3d('+z.image.currentX+'px, '+z.image.currentY+'px,0)');},onTouchEnd:function(s,e){var z=s.zoom;if(!z.gesture.image||z.gesture.image.length===0)return;if(!z.image.isTouched||!z.image.isMoved){z.image.isTouched=false;z.image.isMoved=false;return;}
z.image.isTouched=false;z.image.isMoved=false;var momentumDurationX=300;var momentumDurationY=300;var momentumDistanceX=z.velocity.x*momentumDurationX;var newPositionX=z.image.currentX+momentumDistanceX;var momentumDistanceY=z.velocity.y*momentumDurationY;var newPositionY=z.image.currentY+momentumDistanceY;if(z.velocity.x!==0)momentumDurationX=Math.abs((newPositionX-z.image.currentX)/ z.velocity.x);if(z.velocity.y!==0)momentumDurationY=Math.abs((newPositionY-z.image.currentY)/ z.velocity.y);var momentumDuration=Math.max(momentumDurationX,momentumDurationY);z.image.currentX=newPositionX;z.image.currentY=newPositionY;var scaledWidth=z.image.width*z.scale;var scaledHeight=z.image.height*z.scale;z.image.minX=Math.min((z.gesture.slideWidth / 2-scaledWidth / 2),0);z.image.maxX=-z.image.minX;z.image.minY=Math.min((z.gesture.slideHeight / 2-scaledHeight / 2),0);z.image.maxY=-z.image.minY;z.image.currentX=Math.max(Math.min(z.image.currentX,z.image.maxX),z.image.minX);z.image.currentY=Math.max(Math.min(z.image.currentY,z.image.maxY),z.image.minY);z.gesture.imageWrap.transition(momentumDuration).transform('translate3d('+z.image.currentX+'px, '+z.image.currentY+'px,0)');},onTransitionEnd:function(s){var z=s.zoom;if(z.gesture.slide&&s.previousIndex!==s.activeIndex){z.gesture.image.transform('translate3d(0,0,0) scale(1)');z.gesture.imageWrap.transform('translate3d(0,0,0)');z.gesture.slide=z.gesture.image=z.gesture.imageWrap=undefined;z.scale=z.currentScale=1;}},toggleZoom:function(s,e){var z=s.zoom;if(!z.gesture.slide){z.gesture.slide=s.clickedSlide?$(s.clickedSlide):s.slides.eq(s.activeIndex);z.gesture.image=z.gesture.slide.find('img, svg, canvas');z.gesture.imageWrap=z.gesture.image.parent('.'+s.params.zoomContainerClass);}
if(!z.gesture.image||z.gesture.image.length===0)return;var touchX,touchY,offsetX,offsetY,diffX,diffY,translateX,translateY,imageWidth,imageHeight,scaledWidth,scaledHeight,translateMinX,translateMinY,translateMaxX,translateMaxY,slideWidth,slideHeight;if(typeof z.image.touchesStart.x==='undefined'&&e){touchX=e.type==='touchend'?e.changedTouches[0].pageX:e.pageX;touchY=e.type==='touchend'?e.changedTouches[0].pageY:e.pageY;}
else{touchX=z.image.touchesStart.x;touchY=z.image.touchesStart.y;}
if(z.scale&&z.scale!==1){z.scale=z.currentScale=1;z.gesture.imageWrap.transition(300).transform('translate3d(0,0,0)');z.gesture.image.transition(300).transform('translate3d(0,0,0) scale(1)');z.gesture.slide=undefined;}
else{z.scale=z.currentScale=z.gesture.imageWrap.attr('data-swiper-zoom')||s.params.zoomMax;if(e){slideWidth=z.gesture.slide[0].offsetWidth;slideHeight=z.gesture.slide[0].offsetHeight;offsetX=z.gesture.slide.offset().left;offsetY=z.gesture.slide.offset().top;diffX=offsetX+slideWidth/2-touchX;diffY=offsetY+slideHeight/2-touchY;imageWidth=z.gesture.image[0].offsetWidth;imageHeight=z.gesture.image[0].offsetHeight;scaledWidth=imageWidth*z.scale;scaledHeight=imageHeight*z.scale;translateMinX=Math.min((slideWidth / 2-scaledWidth / 2),0);translateMinY=Math.min((slideHeight / 2-scaledHeight / 2),0);translateMaxX=-translateMinX;translateMaxY=-translateMinY;translateX=diffX*z.scale;translateY=diffY*z.scale;if(translateX<translateMinX){translateX=translateMinX;}
if(translateX>translateMaxX){translateX=translateMaxX;}
if(translateY<translateMinY){translateY=translateMinY;}
if(translateY>translateMaxY){translateY=translateMaxY;}}
else{translateX=0;translateY=0;}
z.gesture.imageWrap.transition(300).transform('translate3d('+translateX+'px, '+translateY+'px,0)');z.gesture.image.transition(300).transform('translate3d(0,0,0) scale('+z.scale+')');}},attachEvents:function(detach){var action=detach?'off':'on';if(s.params.zoom){var target=s.slides;var passiveListener=s.touchEvents.start==='touchstart'&&s.support.passiveListener&&s.params.passiveListeners?{passive:true,capture:false}:false;if(s.support.gestures){s.slides[action]('gesturestart',s.zoom.onGestureStart,passiveListener);s.slides[action]('gesturechange',s.zoom.onGestureChange,passiveListener);s.slides[action]('gestureend',s.zoom.onGestureEnd,passiveListener);}
else if(s.touchEvents.start==='touchstart'){s.slides[action](s.touchEvents.start,s.zoom.onGestureStart,passiveListener);s.slides[action](s.touchEvents.move,s.zoom.onGestureChange,passiveListener);s.slides[action](s.touchEvents.end,s.zoom.onGestureEnd,passiveListener);}
s[action]('touchStart',s.zoom.onTouchStart);s.slides.each(function(index,slide){if($(slide).find('.'+s.params.zoomContainerClass).length>0){$(slide)[action](s.touchEvents.move,s.zoom.onTouchMove);}});s[action]('touchEnd',s.zoom.onTouchEnd);s[action]('transitionEnd',s.zoom.onTransitionEnd);if(s.params.zoomToggle){s.on('doubleTap',s.zoom.toggleZoom);}}},init:function(){s.zoom.attachEvents();},destroy:function(){s.zoom.attachEvents(true);}};s._plugins=[];for(var plugin in s.plugins){var p=s.plugins[plugin](s,s.params[plugin]);if(p)s._plugins.push(p);}
s.callPlugins=function(eventName){for(var i=0;i<s._plugins.length;i++){if(eventName in s._plugins[i]){s._plugins[i][eventName](arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]);}}};function normalizeEventName(eventName){if(eventName.indexOf('on')!==0){if(eventName[0]!==eventName[0].toUpperCase()){eventName='on'+eventName[0].toUpperCase()+eventName.substring(1);}
else{eventName='on'+eventName;}}
return eventName;}
s.emitterEventListeners={};s.emit=function(eventName){if(s.params[eventName]){s.params[eventName](arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]);}
var i;if(s.emitterEventListeners[eventName]){for(i=0;i<s.emitterEventListeners[eventName].length;i++){s.emitterEventListeners[eventName][i](arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]);}}
if(s.callPlugins)s.callPlugins(eventName,arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]);};s.on=function(eventName,handler){eventName=normalizeEventName(eventName);if(!s.emitterEventListeners[eventName])s.emitterEventListeners[eventName]=[];s.emitterEventListeners[eventName].push(handler);return s;};s.off=function(eventName,handler){var i;eventName=normalizeEventName(eventName);if(typeof handler==='undefined'){s.emitterEventListeners[eventName]=[];return s;}
if(!s.emitterEventListeners[eventName]||s.emitterEventListeners[eventName].length===0)return;for(i=0;i<s.emitterEventListeners[eventName].length;i++){if(s.emitterEventListeners[eventName][i]===handler)s.emitterEventListeners[eventName].splice(i,1);}
return s;};s.once=function(eventName,handler){eventName=normalizeEventName(eventName);var _handler=function(){handler(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4]);s.off(eventName,_handler);};s.on(eventName,_handler);return s;};s.a11y={makeFocusable:function($el){$el.attr('tabIndex','0');return $el;},addRole:function($el,role){$el.attr('role',role);return $el;},addLabel:function($el,label){$el.attr('aria-label',label);return $el;},disable:function($el){$el.attr('aria-disabled',true);return $el;},enable:function($el){$el.attr('aria-disabled',false);return $el;},onEnterKey:function(event){if(event.keyCode!==13)return;if($(event.target).is(s.params.nextButton)){s.onClickNext(event);if(s.isEnd){s.a11y.notify(s.params.lastSlideMessage);}
else{s.a11y.notify(s.params.nextSlideMessage);}}
else if($(event.target).is(s.params.prevButton)){s.onClickPrev(event);if(s.isBeginning){s.a11y.notify(s.params.firstSlideMessage);}
else{s.a11y.notify(s.params.prevSlideMessage);}}
if($(event.target).is('.'+s.params.bulletClass)){$(event.target)[0].click();}},liveRegion:$('<span class="'+s.params.notificationClass+'" aria-live="assertive" aria-atomic="true"></span>'),notify:function(message){var notification=s.a11y.liveRegion;if(notification.length===0)return;notification.html('');notification.html(message);},init:function(){if(s.params.nextButton&&s.nextButton&&s.nextButton.length>0){s.a11y.makeFocusable(s.nextButton);s.a11y.addRole(s.nextButton,'button');s.a11y.addLabel(s.nextButton,s.params.nextSlideMessage);}
if(s.params.prevButton&&s.prevButton&&s.prevButton.length>0){s.a11y.makeFocusable(s.prevButton);s.a11y.addRole(s.prevButton,'button');s.a11y.addLabel(s.prevButton,s.params.prevSlideMessage);}
$(s.container).append(s.a11y.liveRegion);},initPagination:function(){if(s.params.pagination&&s.params.paginationClickable&&s.bullets&&s.bullets.length){s.bullets.each(function(){var bullet=$(this);s.a11y.makeFocusable(bullet);s.a11y.addRole(bullet,'button');s.a11y.addLabel(bullet,s.params.paginationBulletMessage.replace(/{{index}}/,bullet.index()+1));});}},destroy:function(){if(s.a11y.liveRegion&&s.a11y.liveRegion.length>0)s.a11y.liveRegion.remove();}};s.init=function(){if(s.params.loop)s.createLoop();s.updateContainerSize();s.updateSlidesSize();s.updatePagination();if(s.params.scrollbar&&s.scrollbar){s.scrollbar.set();if(s.params.scrollbarDraggable){s.scrollbar.enableDraggable();}}
if(s.params.effect!=='slide'&&s.effects[s.params.effect]){if(!s.params.loop)s.updateProgress();s.effects[s.params.effect].setTranslate();}
if(s.params.loop){s.slideTo(s.params.initialSlide+s.loopedSlides,0,s.params.runCallbacksOnInit);}
else{s.slideTo(s.params.initialSlide,0,s.params.runCallbacksOnInit);if(s.params.initialSlide===0){if(s.parallax&&s.params.parallax)s.parallax.setTranslate();if(s.lazy&&s.params.lazyLoading){s.lazy.load();s.lazy.initialImageLoaded=true;}}}
s.attachEvents();if(s.params.observer&&s.support.observer){s.initObservers();}
if(s.params.preloadImages&&!s.params.lazyLoading){s.preloadImages();}
if(s.params.zoom&&s.zoom){s.zoom.init();}
if(s.params.autoplay){s.startAutoplay();}
if(s.params.keyboardControl){if(s.enableKeyboardControl)s.enableKeyboardControl();}
if(s.params.mousewheelControl){if(s.enableMousewheelControl)s.enableMousewheelControl();}
if(s.params.hashnavReplaceState){s.params.replaceState=s.params.hashnavReplaceState;}
if(s.params.history){if(s.history)s.history.init();}
if(s.params.hashnav){if(s.hashnav)s.hashnav.init();}
if(s.params.a11y&&s.a11y)s.a11y.init();s.emit('onInit',s);};s.cleanupStyles=function(){s.container.removeClass(s.classNames.join(' ')).removeAttr('style');s.wrapper.removeAttr('style');if(s.slides&&s.slides.length){s.slides.removeClass([s.params.slideVisibleClass,s.params.slideActiveClass,s.params.slideNextClass,s.params.slidePrevClass].join(' ')).removeAttr('style').removeAttr('data-swiper-column').removeAttr('data-swiper-row');}
if(s.paginationContainer&&s.paginationContainer.length){s.paginationContainer.removeClass(s.params.paginationHiddenClass);}
if(s.bullets&&s.bullets.length){s.bullets.removeClass(s.params.bulletActiveClass);}
if(s.params.prevButton)$(s.params.prevButton).removeClass(s.params.buttonDisabledClass);if(s.params.nextButton)$(s.params.nextButton).removeClass(s.params.buttonDisabledClass);if(s.params.scrollbar&&s.scrollbar){if(s.scrollbar.track&&s.scrollbar.track.length)s.scrollbar.track.removeAttr('style');if(s.scrollbar.drag&&s.scrollbar.drag.length)s.scrollbar.drag.removeAttr('style');}};s.destroy=function(deleteInstance,cleanupStyles){s.detachEvents();s.stopAutoplay();if(s.params.scrollbar&&s.scrollbar){if(s.params.scrollbarDraggable){s.scrollbar.disableDraggable();}}
if(s.params.loop){s.destroyLoop();}
if(cleanupStyles){s.cleanupStyles();}
s.disconnectObservers();if(s.params.zoom&&s.zoom){s.zoom.destroy();}
if(s.params.keyboardControl){if(s.disableKeyboardControl)s.disableKeyboardControl();}
if(s.params.mousewheelControl){if(s.disableMousewheelControl)s.disableMousewheelControl();}
if(s.params.a11y&&s.a11y)s.a11y.destroy();if(s.params.history&&!s.params.replaceState){window.removeEventListener('popstate',s.history.setHistoryPopState);}
if(s.params.hashnav&&s.hashnav){s.hashnav.destroy();}
s.emit('onDestroy');if(deleteInstance!==false)s=null;};s.init();return s;};Swiper.prototype={isSafari:(function(){var ua=window.navigator.userAgent.toLowerCase();return(ua.indexOf('safari')>=0&&ua.indexOf('chrome')<0&&ua.indexOf('android')<0);})(),isUiWebView:/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(window.navigator.userAgent),isArray:function(arr){return Object.prototype.toString.apply(arr)==='[object Array]';},browser:{ie:window.navigator.pointerEnabled||window.navigator.msPointerEnabled,ieTouch:(window.navigator.msPointerEnabled&&window.navigator.msMaxTouchPoints>1)||(window.navigator.pointerEnabled&&window.navigator.maxTouchPoints>1),lteIE9:(function(){var div=document.createElement('div');div.innerHTML='<!--[if lte IE 9]><i></i><![endif]-->';return div.getElementsByTagName('i').length===1;})()},device:(function(){var ua=window.navigator.userAgent;var android=ua.match(/(Android);?[\s\/]+([\d.]+)?/);var ipad=ua.match(/(iPad).*OS\s([\d_]+)/);var ipod=ua.match(/(iPod)(.*OS\s([\d_]+))?/);var iphone=!ipad&&ua.match(/(iPhone\sOS|iOS)\s([\d_]+)/);return{ios:ipad||iphone||ipod,android:android};})(),support:{touch:(window.Modernizr&&Modernizr.touch===true)||(function(){return!!(('ontouchstart'in window)||window.DocumentTouch&&document instanceof DocumentTouch);})(),transforms3d:(window.Modernizr&&Modernizr.csstransforms3d===true)||(function(){var div=document.createElement('div').style;return('webkitPerspective'in div||'MozPerspective'in div||'OPerspective'in div||'MsPerspective'in div||'perspective'in div);})(),flexbox:(function(){var div=document.createElement('div').style;var styles=('alignItems webkitAlignItems webkitBoxAlign msFlexAlign mozBoxAlign webkitFlexDirection msFlexDirection mozBoxDirection mozBoxOrient webkitBoxDirection webkitBoxOrient').split(' ');for(var i=0;i<styles.length;i++){if(styles[i]in div)return true;}})(),observer:(function(){return('MutationObserver'in window||'WebkitMutationObserver'in window);})(),passiveListener:(function(){var supportsPassive=false;try{var opts=Object.defineProperty({},'passive',{get:function(){supportsPassive=true;}});window.addEventListener('testPassiveListener',null,opts);}catch(e){}
return supportsPassive;})(),gestures:(function(){return'ongesturestart'in window;})()},plugins:{}};var Dom7=(function(){var Dom7=function(arr){var _this=this,i=0;for(i=0;i<arr.length;i++){_this[i]=arr[i];}
_this.length=arr.length;return this;};var $=function(selector,context){var arr=[],i=0;if(selector&&!context){if(selector instanceof Dom7){return selector;}}
if(selector){if(typeof selector==='string'){var els,tempParent,html=selector.trim();if(html.indexOf('<')>=0&&html.indexOf('>')>=0){var toCreate='div';if(html.indexOf('<li')===0)toCreate='ul';if(html.indexOf('<tr')===0)toCreate='tbody';if(html.indexOf('<td')===0||html.indexOf('<th')===0)toCreate='tr';if(html.indexOf('<tbody')===0)toCreate='table';if(html.indexOf('<option')===0)toCreate='select';tempParent=document.createElement(toCreate);tempParent.innerHTML=selector;for(i=0;i<tempParent.childNodes.length;i++){arr.push(tempParent.childNodes[i]);}}
else{if(!context&&selector[0]==='#'&&!selector.match(/[ .<>:~]/)){els=[document.getElementById(selector.split('#')[1])];}
else{els=(context||document).querySelectorAll(selector);}
for(i=0;i<els.length;i++){if(els[i])arr.push(els[i]);}}}
else if(selector.nodeType||selector===window||selector===document){arr.push(selector);}
else if(selector.length>0&&selector[0].nodeType){for(i=0;i<selector.length;i++){arr.push(selector[i]);}}}
return new Dom7(arr);};Dom7.prototype={addClass:function(className){if(typeof className==='undefined'){return this;}
var classes=className.split(' ');for(var i=0;i<classes.length;i++){for(var j=0;j<this.length;j++){this[j].classList.add(classes[i]);}}
return this;},removeClass:function(className){var classes=className.split(' ');for(var i=0;i<classes.length;i++){for(var j=0;j<this.length;j++){this[j].classList.remove(classes[i]);}}
return this;},hasClass:function(className){if(!this[0])return false;else return this[0].classList.contains(className);},toggleClass:function(className){var classes=className.split(' ');for(var i=0;i<classes.length;i++){for(var j=0;j<this.length;j++){this[j].classList.toggle(classes[i]);}}
return this;},attr:function(attrs,value){if(arguments.length===1&&typeof attrs==='string'){if(this[0])return this[0].getAttribute(attrs);else return undefined;}
else{for(var i=0;i<this.length;i++){if(arguments.length===2){this[i].setAttribute(attrs,value);}
else{for(var attrName in attrs){this[i][attrName]=attrs[attrName];this[i].setAttribute(attrName,attrs[attrName]);}}}
return this;}},removeAttr:function(attr){for(var i=0;i<this.length;i++){this[i].removeAttribute(attr);}
return this;},data:function(key,value){if(typeof value==='undefined'){if(this[0]){var dataKey=this[0].getAttribute('data-'+key);if(dataKey)return dataKey;else if(this[0].dom7ElementDataStorage&&(key in this[0].dom7ElementDataStorage))return this[0].dom7ElementDataStorage[key];else return undefined;}
else return undefined;}
else{for(var i=0;i<this.length;i++){var el=this[i];if(!el.dom7ElementDataStorage)el.dom7ElementDataStorage={};el.dom7ElementDataStorage[key]=value;}
return this;}},transform:function(transform){for(var i=0;i<this.length;i++){var elStyle=this[i].style;elStyle.webkitTransform=elStyle.MsTransform=elStyle.msTransform=elStyle.MozTransform=elStyle.OTransform=elStyle.transform=transform;}
return this;},transition:function(duration){if(typeof duration!=='string'){duration=duration+'ms';}
for(var i=0;i<this.length;i++){var elStyle=this[i].style;elStyle.webkitTransitionDuration=elStyle.MsTransitionDuration=elStyle.msTransitionDuration=elStyle.MozTransitionDuration=elStyle.OTransitionDuration=elStyle.transitionDuration=duration;}
return this;},on:function(eventName,targetSelector,listener,capture){function handleLiveEvent(e){var target=e.target;if($(target).is(targetSelector))listener.call(target,e);else{var parents=$(target).parents();for(var k=0;k<parents.length;k++){if($(parents[k]).is(targetSelector))listener.call(parents[k],e);}}}
var events=eventName.split(' ');var i,j;for(i=0;i<this.length;i++){if(typeof targetSelector==='function'||targetSelector===false){if(typeof targetSelector==='function'){listener=arguments[1];capture=arguments[2]||false;}
for(j=0;j<events.length;j++){this[i].addEventListener(events[j],listener,capture);}}
else{for(j=0;j<events.length;j++){if(!this[i].dom7LiveListeners)this[i].dom7LiveListeners=[];this[i].dom7LiveListeners.push({listener:listener,liveListener:handleLiveEvent});this[i].addEventListener(events[j],handleLiveEvent,capture);}}}
return this;},off:function(eventName,targetSelector,listener,capture){var events=eventName.split(' ');for(var i=0;i<events.length;i++){for(var j=0;j<this.length;j++){if(typeof targetSelector==='function'||targetSelector===false){if(typeof targetSelector==='function'){listener=arguments[1];capture=arguments[2]||false;}
this[j].removeEventListener(events[i],listener,capture);}
else{if(this[j].dom7LiveListeners){for(var k=0;k<this[j].dom7LiveListeners.length;k++){if(this[j].dom7LiveListeners[k].listener===listener){this[j].removeEventListener(events[i],this[j].dom7LiveListeners[k].liveListener,capture);}}}}}}
return this;},once:function(eventName,targetSelector,listener,capture){var dom=this;if(typeof targetSelector==='function'){targetSelector=false;listener=arguments[1];capture=arguments[2];}
function proxy(e){listener(e);dom.off(eventName,targetSelector,proxy,capture);}
dom.on(eventName,targetSelector,proxy,capture);},trigger:function(eventName,eventData){for(var i=0;i<this.length;i++){var evt;try{evt=new window.CustomEvent(eventName,{detail:eventData,bubbles:true,cancelable:true});}
catch(e){evt=document.createEvent('Event');evt.initEvent(eventName,true,true);evt.detail=eventData;}
this[i].dispatchEvent(evt);}
return this;},transitionEnd:function(callback){var events=['webkitTransitionEnd','transitionend','oTransitionEnd','MSTransitionEnd','msTransitionEnd'],i,j,dom=this;function fireCallBack(e){if(e.target!==this)return;callback.call(this,e);for(i=0;i<events.length;i++){dom.off(events[i],fireCallBack);}}
if(callback){for(i=0;i<events.length;i++){dom.on(events[i],fireCallBack);}}
return this;},width:function(){if(this[0]===window){return window.innerWidth;}
else{if(this.length>0){return parseFloat(this.css('width'));}
else{return null;}}},outerWidth:function(includeMargins){if(this.length>0){if(includeMargins)
return this[0].offsetWidth+parseFloat(this.css('margin-right'))+parseFloat(this.css('margin-left'));else
return this[0].offsetWidth;}
else return null;},height:function(){if(this[0]===window){return window.innerHeight;}
else{if(this.length>0){return parseFloat(this.css('height'));}
else{return null;}}},outerHeight:function(includeMargins){if(this.length>0){if(includeMargins)
return this[0].offsetHeight+parseFloat(this.css('margin-top'))+parseFloat(this.css('margin-bottom'));else
return this[0].offsetHeight;}
else return null;},offset:function(){if(this.length>0){var el=this[0];var box=el.getBoundingClientRect();var body=document.body;var clientTop=el.clientTop||body.clientTop||0;var clientLeft=el.clientLeft||body.clientLeft||0;var scrollTop=window.pageYOffset||el.scrollTop;var scrollLeft=window.pageXOffset||el.scrollLeft;return{top:box.top+scrollTop-clientTop,left:box.left+scrollLeft-clientLeft};}
else{return null;}},css:function(props,value){var i;if(arguments.length===1){if(typeof props==='string'){if(this[0])return window.getComputedStyle(this[0],null).getPropertyValue(props);}
else{for(i=0;i<this.length;i++){for(var prop in props){this[i].style[prop]=props[prop];}}
return this;}}
if(arguments.length===2&&typeof props==='string'){for(i=0;i<this.length;i++){this[i].style[props]=value;}
return this;}
return this;},each:function(callback){for(var i=0;i<this.length;i++){callback.call(this[i],i,this[i]);}
return this;},html:function(html){if(typeof html==='undefined'){return this[0]?this[0].innerHTML:undefined;}
else{for(var i=0;i<this.length;i++){this[i].innerHTML=html;}
return this;}},text:function(text){if(typeof text==='undefined'){if(this[0]){return this[0].textContent.trim();}
else return null;}
else{for(var i=0;i<this.length;i++){this[i].textContent=text;}
return this;}},is:function(selector){if(!this[0])return false;var compareWith,i;if(typeof selector==='string'){var el=this[0];if(el===document)return selector===document;if(el===window)return selector===window;if(el.matches)return el.matches(selector);else if(el.webkitMatchesSelector)return el.webkitMatchesSelector(selector);else if(el.mozMatchesSelector)return el.mozMatchesSelector(selector);else if(el.msMatchesSelector)return el.msMatchesSelector(selector);else{compareWith=$(selector);for(i=0;i<compareWith.length;i++){if(compareWith[i]===this[0])return true;}
return false;}}
else if(selector===document)return this[0]===document;else if(selector===window)return this[0]===window;else{if(selector.nodeType||selector instanceof Dom7){compareWith=selector.nodeType?[selector]:selector;for(i=0;i<compareWith.length;i++){if(compareWith[i]===this[0])return true;}
return false;}
return false;}},index:function(){if(this[0]){var child=this[0];var i=0;while((child=child.previousSibling)!==null){if(child.nodeType===1)i++;}
return i;}
else return undefined;},eq:function(index){if(typeof index==='undefined')return this;var length=this.length;var returnIndex;if(index>length-1){return new Dom7([]);}
if(index<0){returnIndex=length+index;if(returnIndex<0)return new Dom7([]);else return new Dom7([this[returnIndex]]);}
return new Dom7([this[index]]);},append:function(newChild){var i,j;for(i=0;i<this.length;i++){if(typeof newChild==='string'){var tempDiv=document.createElement('div');tempDiv.innerHTML=newChild;while(tempDiv.firstChild){this[i].appendChild(tempDiv.firstChild);}}
else if(newChild instanceof Dom7){for(j=0;j<newChild.length;j++){this[i].appendChild(newChild[j]);}}
else{this[i].appendChild(newChild);}}
return this;},prepend:function(newChild){var i,j;for(i=0;i<this.length;i++){if(typeof newChild==='string'){var tempDiv=document.createElement('div');tempDiv.innerHTML=newChild;for(j=tempDiv.childNodes.length-1;j>=0;j--){this[i].insertBefore(tempDiv.childNodes[j],this[i].childNodes[0]);}}
else if(newChild instanceof Dom7){for(j=0;j<newChild.length;j++){this[i].insertBefore(newChild[j],this[i].childNodes[0]);}}
else{this[i].insertBefore(newChild,this[i].childNodes[0]);}}
return this;},insertBefore:function(selector){var before=$(selector);for(var i=0;i<this.length;i++){if(before.length===1){before[0].parentNode.insertBefore(this[i],before[0]);}
else if(before.length>1){for(var j=0;j<before.length;j++){before[j].parentNode.insertBefore(this[i].cloneNode(true),before[j]);}}}},insertAfter:function(selector){var after=$(selector);for(var i=0;i<this.length;i++){if(after.length===1){after[0].parentNode.insertBefore(this[i],after[0].nextSibling);}
else if(after.length>1){for(var j=0;j<after.length;j++){after[j].parentNode.insertBefore(this[i].cloneNode(true),after[j].nextSibling);}}}},next:function(selector){if(this.length>0){if(selector){if(this[0].nextElementSibling&&$(this[0].nextElementSibling).is(selector))return new Dom7([this[0].nextElementSibling]);else return new Dom7([]);}
else{if(this[0].nextElementSibling)return new Dom7([this[0].nextElementSibling]);else return new Dom7([]);}}
else return new Dom7([]);},nextAll:function(selector){var nextEls=[];var el=this[0];if(!el)return new Dom7([]);while(el.nextElementSibling){var next=el.nextElementSibling;if(selector){if($(next).is(selector))nextEls.push(next);}
else nextEls.push(next);el=next;}
return new Dom7(nextEls);},prev:function(selector){if(this.length>0){if(selector){if(this[0].previousElementSibling&&$(this[0].previousElementSibling).is(selector))return new Dom7([this[0].previousElementSibling]);else return new Dom7([]);}
else{if(this[0].previousElementSibling)return new Dom7([this[0].previousElementSibling]);else return new Dom7([]);}}
else return new Dom7([]);},prevAll:function(selector){var prevEls=[];var el=this[0];if(!el)return new Dom7([]);while(el.previousElementSibling){var prev=el.previousElementSibling;if(selector){if($(prev).is(selector))prevEls.push(prev);}
else prevEls.push(prev);el=prev;}
return new Dom7(prevEls);},parent:function(selector){var parents=[];for(var i=0;i<this.length;i++){if(selector){if($(this[i].parentNode).is(selector))parents.push(this[i].parentNode);}
else{parents.push(this[i].parentNode);}}
return $($.unique(parents));},parents:function(selector){var parents=[];for(var i=0;i<this.length;i++){var parent=this[i].parentNode;while(parent){if(selector){if($(parent).is(selector))parents.push(parent);}
else{parents.push(parent);}
parent=parent.parentNode;}}
return $($.unique(parents));},find:function(selector){var foundElements=[];for(var i=0;i<this.length;i++){var found=this[i].querySelectorAll(selector);for(var j=0;j<found.length;j++){foundElements.push(found[j]);}}
return new Dom7(foundElements);},children:function(selector){var children=[];for(var i=0;i<this.length;i++){var childNodes=this[i].childNodes;for(var j=0;j<childNodes.length;j++){if(!selector){if(childNodes[j].nodeType===1)children.push(childNodes[j]);}
else{if(childNodes[j].nodeType===1&&$(childNodes[j]).is(selector))children.push(childNodes[j]);}}}
return new Dom7($.unique(children));},remove:function(){for(var i=0;i<this.length;i++){if(this[i].parentNode)this[i].parentNode.removeChild(this[i]);}
return this;},add:function(){var dom=this;var i,j;for(i=0;i<arguments.length;i++){var toAdd=$(arguments[i]);for(j=0;j<toAdd.length;j++){dom[dom.length]=toAdd[j];dom.length++;}}
return dom;}};$.fn=Dom7.prototype;$.unique=function(arr){var unique=[];for(var i=0;i<arr.length;i++){if(unique.indexOf(arr[i])===-1)unique.push(arr[i]);}
return unique;};return $;})();var swiperDomPlugins=['jQuery','Zepto','Dom7'];for(var i=0;i<swiperDomPlugins.length;i++){if(window[swiperDomPlugins[i]]){addLibraryPlugin(window[swiperDomPlugins[i]]);}}
var domLib;if(typeof Dom7==='undefined'){domLib=window.Dom7||window.Zepto||window.jQuery;}
else{domLib=Dom7;}
function addLibraryPlugin(lib){lib.fn.swiper=function(params){var firstInstance;lib(this).each(function(){var s=new Swiper(this,params);if(!firstInstance)firstInstance=s;});return firstInstance;};}
if(domLib){if(!('transitionEnd'in domLib.fn)){domLib.fn.transitionEnd=function(callback){var events=['webkitTransitionEnd','transitionend','oTransitionEnd','MSTransitionEnd','msTransitionEnd'],i,j,dom=this;function fireCallBack(e){if(e.target!==this)return;callback.call(this,e);for(i=0;i<events.length;i++){dom.off(events[i],fireCallBack);}}
if(callback){for(i=0;i<events.length;i++){dom.on(events[i],fireCallBack);}}
return this;};}
if(!('transform'in domLib.fn)){domLib.fn.transform=function(transform){for(var i=0;i<this.length;i++){var elStyle=this[i].style;elStyle.webkitTransform=elStyle.MsTransform=elStyle.msTransform=elStyle.MozTransform=elStyle.OTransform=elStyle.transform=transform;}
return this;};}
if(!('transition'in domLib.fn)){domLib.fn.transition=function(duration){if(typeof duration!=='string'){duration=duration+'ms';}
for(var i=0;i<this.length;i++){var elStyle=this[i].style;elStyle.webkitTransitionDuration=elStyle.MsTransitionDuration=elStyle.msTransitionDuration=elStyle.MozTransitionDuration=elStyle.OTransitionDuration=elStyle.transitionDuration=duration;}
return this;};}
if(!('outerWidth'in domLib.fn)){domLib.fn.outerWidth=function(includeMargins){if(this.length>0){if(includeMargins)
return this[0].offsetWidth+parseFloat(this.css('margin-right'))+parseFloat(this.css('margin-left'));else
return this[0].offsetWidth;}
else return null;};}}
window.Swiper=Swiper;})();if(typeof(module)!=='undefined'){module.exports=window.Swiper;}
else if(typeof define==='function'&&define.amd){define('swiper',[],function(){'use strict';return window.Swiper;});}
define('recommend',['components/form','alertify','score.init','score.oop','score.dom','score.ajax.rest'],function(Form,alertify,score){'use strict';return score.oop.Class({__name__:'RecommendBlock',__init__:function(self,node,jobPostingId){self.node=node;self.recommendButton=self.node.find('.button-recommend');self.recommendButton[0].addEventListener('click',function(event){event.preventDefault();if(!score.dom('.recommend-box').hasClass('active')){self._renderData();}
score.dom('.recommend-box').toggleClass('active');});self.closeButton=self.node.find('#recommend-close');self.closeButton[0].addEventListener('click',function(event){event.preventDefault();score.dom('.recommend-box').toggleClass('active');});self.node.find('#recommend-form').on('submit',self._submitHandler);},_submitHandler:function(self,event){event.preventDefault();if(self.postPromise){return;}
var data=Form.serialize(event.currentTarget);if(!self._validate(data)){return;}
self.postPromise=score.ajax.rest.postJSON('/rest/recommend',data).then(function(){score.dom('.recommend-box')[0].innerHTML='Vielen Dank! Ihre Empfehlung wurde erfolgreich per E-Mail versandt.';});},_validate:function(self,data){if(!data.senderName){alertify.alert('Bitte geben Sie Ihren Namen an.');return false;}
if(!data.recipientEmail){alertify.alert('Bitte geben Sie die Empfänger E-Mail Adresse an.');return false;}
return(data.senderName&&data.recipientEmail);},_renderData:function(self){if(typeof self.node.find('#sender-name')[0]!=='undefined'){self.node.find('#sender-name')[0].value='';}
if(typeof self.node.find('#recipient-email')[0]!=='undefined'){self.node.find('#recipient-email')[0].value='';}
if(typeof self.node.find('#recommend-text')[0]!=='undefined'){self.node.find('#recommend-text')[0].value='';}}});});define('selfcare/mainmenu',['statictext','ractive','rv!rvtpl/selfcare/mainmenu','lodash','client','user','score.init','score.oop'],function(StaticText,Ractive,template,_,Client,User,score){return score.oop.Class({__name__:'MainMenu',__static__:{instance:null,LOAD_STATIC_TEXTS:['selfcare_menu_text_meinersterjob'],},__events__:['jobs-click','message-click'],__init__:function(self){self.ractive=new Ractive({el:'[data-component=mainmenu]',template:template});self.ractive.on('menuclick',function(a){if(a.context.href==='#/jobs'){return self.trigger('jobs-click');}
if(a.context.href==='#/nachrichten'){return self.trigger('message-click');}});self._loadPromise=self._loadData().then(function(data){self.ractive.set('menu.entries',data.menu.entries);Client.get().then(self._hasNewMessages);if(self._hash){return self._handleHash();}
self.ractive.set('menu.entries',_.cloneDeep(self._entries));});User.get().then(function(user){if(user.client.meinersterjobEnabled){StaticText.loadTexts(self.ractive,self.LOAD_STATIC_TEXTS);}});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();window.setInterval(function(){Client.get().then(self._hasNewMessages);},5000);},_hashChanged:function(self){self._hash=document.location.hash;self._handleHash();},_handleHash:function(self){var entries=self.ractive.get('menu.entries');if(!self._hash||!entries||self._hash.indexOf('#/')!==0){return;}
_.forEach(entries,function(entry,key){if(self._hash!=='#/'&&entry.href==='#/'){return;}
entry.isActive=self._hash.indexOf(entry.href)===0;});self.ractive.set('menu.entries',entries);},_loadData:function(self){return score.ajax.rest.getJSON('rest/selfcare/mainmenu');},_hasNewMessages:function(self){var entries=self.ractive.get('menu.entries');if(!entries){return;}
score.ajax.rest.getJSON('/rest/selfcare/message').then(function(data){if(!data.messages){return;}
var hasNewMessages=false;for(var i=0;i<data.messages.length;i++){if(data.messages[i].isNew){hasNewMessages=true;break;}}
for(var i=0;i<entries.length;i++){if(entries[i].href==='#/nachrichten'){entries[i].hasNewMessages=hasNewMessages;break;}}
self.ractive.set('menu.entries',entries);});},});});define('selfcare/register',['bluebird','components/form','score.init','score.oop','score.ajax.rest'],function(BPromise,Form,score){'use strict';return score.oop.Class({__name__:'Register',__init__:function(self,form){new BPromise(function(resolve,reject){window.onbeforeunload=null;return resolve();});self.form=form;self.form.addEventListener('submit',function(e){e.preventDefault();var data=Form.serialize(self.form);if(self._validate(data)){score.ajax.rest.postJSON('/rest/client/_register',data).then(function(result){window.location.href='/arbeitgeber/registrieren/done';});}});self.emailInput=self.form.querySelector('input[name=email]');self.emailInput.addEventListener('keyup',self._emailInputHandler);self.emailInput.addEventListener('blur',self._emailInputHandler);self.emailInput.addEventListener('change',self._emailInputHandler);self.emailError=self.form.querySelector('.error-message__email');self.passwordInput=self.form.querySelector('input[name=password]');self.password2Input=self.form.querySelector('input[name=password2]');self.passwordInput.addEventListener('keyup',self._passwordInputHandler);self.passwordInput.addEventListener('blur',self._passwordInputHandler);self.passwordInput.addEventListener('change',self._passwordInputHandler);self.password2Input.addEventListener('keyup',self._passwordInputHandler);self.password2Input.addEventListener('blur',self._passwordInputHandler);self.password2Input.addEventListener('change',self._passwordInputHandler);self.passwordError=self.form.querySelector('.error-message__password');self.nameInput=self.form.querySelector('input[name=name]');self.nameInput.addEventListener('keyup',self._nameInputHandler);self.nameInput.addEventListener('blur',self._nameInputHandler);self.nameInput.addEventListener('change',self._nameInputHandler);self.nameError=self.form.querySelector('.error-message__name');self.atuInput=self.form.querySelector('input[name=atu]');self.atuInput.addEventListener('keyup',self._atuInputHandler);self.atuInput.addEventListener('blur',self._atuInputHandler);self.atuInput.addEventListener('change',self._atuInputHandler);self.atuError=self.form.querySelector('.error-message__atu');self.commercialRegisterInput=self.form.querySelector('input[name=commercialRegister]');self.commercialRegisterInput.addEventListener('keyup',self._commercialRegisterInputHandler);self.commercialRegisterInput.addEventListener('blur',self._commercialRegisterInputHandler);self.commercialRegisterInput.addEventListener('change',self._commercialRegisterInputHandler);self.commercialRegisterError=self.form.querySelector('.error-message__commercialRegister');self.streetInput=self.form.querySelector('input[name=street]');self.streetInput.addEventListener('keyup',self._streetInputHandler);self.streetInput.addEventListener('blur',self._streetInputHandler);self.streetInput.addEventListener('change',self._streetInputHandler);self.streetError=self.form.querySelector('.error-message__street');self.cityInput=self.form.querySelector('input[name=city]');self.cityInput.addEventListener('keyup',self._cityInputHandler);self.cityInput.addEventListener('blur',self._cityInputHandler);self.cityInput.addEventListener('change',self._cityInputHandler);self.cityError=self.form.querySelector('.error-message__city');self.postalCodeInput=self.form.querySelector('input[name=postalCode]');self.postalCodeInput.addEventListener('keyup',self._postalCodeInputHandler);self.postalCodeInput.addEventListener('blur',self._postalCodeInputHandler);self.postalCodeInput.addEventListener('change',self._postalCodeInputHandler);self.postalCodeError=self.form.querySelector('.error-message__postalCode');self.consentInput=self.form.querySelector('input[name=consent]');self.consentInput.addEventListener('keyup',self._validateConsent);self.consentInput.addEventListener('blur',self._validateConsent);self.consentInput.addEventListener('change',self._validateConsent);self.consentError=self.form.querySelector('.error-message__consent');self.gtcInput=self.form.querySelector('input[name=gtc]');self.gtcInput.addEventListener('keyup',self._validateGtc);self.gtcInput.addEventListener('blur',self._validateGtc);self.gtcInput.addEventListener('change',self._validateGtc);self.gtcError=self.form.querySelector('.error-message__gtc');self.form.addEventListener('change',function(){self._validateForm();});self._validateTimeout=setTimeout(function(){self._validateForm();},1000);_.forEach(self.form.querySelectorAll('input[required=required]'),function(field){if(field.name==='password'){return;}
field.classList.add('invalid');});},_passwordInputHandler:function(self,event){if(!self.passwordInput.value&&self.passwordInput.value===self.password2Input.value){self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='';}else if(self.passwordInput.value&&self.passwordInput.value===self.password2Input.value){score.ajax.rest.postJSON('/rest/user/_passwordpolicy',{'value':self.passwordInput.value}).then(function(){self.password2Input.classList.remove('invalid');self.password2Input.classList.add('valid');self.passwordError.classList.remove('visible');}).catch(function(){self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='Das Passwort muss aus mindestens 6 Zeichen bestehen.';});}else{self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='Die Passwörter stimmen nicht überein.';}
self._validateForm();},_emailInputHandler:function(self,event){if(self._keyUpTimeoutEmail){clearTimeout(self._keyUpTimeoutEmail);}
self._keyUpTimeoutEmail=setTimeout(function(){self._validateEmail(self.emailInput.value).then(function(email){self.emailInput.classList.remove('invalid');self.emailInput.classList.add('valid');self.emailError.classList.remove('visible');}).caught(function(email){self.emailInput.classList.add('invalid');self.emailInput.classList.remove('valid');}).finally(function(){self._validateForm();});},600);},_nameInputHandler:function(self,event){if(self._keyUpTimeoutName){clearTimeout(self._keyUpTimeoutName);}
self._keyUpTimeoutName=setTimeout(function(){return self._validateName(self.nameInput.value).then(function(name){self.nameInput.classList.remove('invalid');self.nameInput.classList.add('valid');self.nameError.classList.remove('visible');}).caught(function(error){self.nameInput.classList.add('invalid');self.nameInput.classList.remove('valid');self.nameError.classList.add('visible');if(!error.message){self.nameError.innerHTML='';}else{self.nameError.innerHTML='Dieser Kundenname ist bereits registriert oder ungültig, bitte wenden Sie sich an unseren Support.';}}).finally(function(){self._validateForm();});},600);},_atuInputHandler:function(self,event){if(self._keyUpTimeoutATU){clearTimeout(self._keyUpTimeoutATU);}
self._keyUpTimeoutATU=setTimeout(function(){return self._validateATU(self.atuInput.value).then(function(name){self.atuInput.classList.remove('invalid');self.atuInput.classList.add('valid');self.atuError.classList.remove('visible');}).caught(function(error){self.atuInput.classList.add('invalid');self.atuInput.classList.remove('valid');self.atuError.classList.add('visible');if(!error.message){self.atuError.innerHTML='';}else{self.atuError.innerHTML='Die eingegebene ATU Nummer ist ungültig.';}}).finally(function(){self._validateForm();});},600);},_commercialRegisterInputHandler:function(self,event){if(self._keyUpTimeoutCommercialRegister){clearTimeout(self._keyUpTimeoutCommercialRegister);}
self._keyUpTimeoutCommercialRegister=setTimeout(function(){return self._validateCommercialRegister(self.commercialRegisterInput.value).then(function(value){self.commercialRegisterInput.classList.remove('invalid');self.commercialRegisterInput.classList.add('valid');self.commercialRegisterError.classList.remove('visible');}).caught(function(error){self.commercialRegisterInput.classList.add('invalid');self.commercialRegisterInput.classList.remove('valid');self.commercialRegisterError.classList.add('visible');self.commercialRegisterError.innerHTML='Bitte geben Sie Ihre Firmenbuchnummer an.';}).finally(function(){self._validateForm();});},600);},_streetInputHandler:function(self,event){if(self._keyUpTimeoutStreet){clearTimeout(self._keyUpTimeoutStreet);}
self._keyUpTimeoutStreet=setTimeout(function(){return self._validateStreet(self.streetInput.value).then(function(value){self.streetInput.classList.remove('invalid');self.streetInput.classList.add('valid');self.streetError.classList.remove('visible');}).caught(function(error){self.streetInput.classList.add('invalid');self.streetInput.classList.remove('valid');self.streetError.classList.add('visible');self.streetError.innerHTML='Bitte geben Sie eine Strasse an.';}).finally(function(){self._validateForm();});},600);},_cityInputHandler:function(self,event){if(self._keyUpTimeoutCity){clearTimeout(self._keyUpTimeoutCity);}
self._keyUpTimeoutCity=setTimeout(function(){return self._validateCity(self.cityInput.value).then(function(value){self.cityInput.classList.remove('invalid');self.cityInput.classList.add('valid');self.cityError.classList.remove('visible');}).caught(function(error){self.cityInput.classList.add('invalid');self.cityInput.classList.remove('valid');self.cityError.classList.add('visible');self.cityError.innerHTML='Bitte geben Sie einen Ort oder eine Stadt an.';}).finally(function(){self._validateForm();});},600);},_postalCodeInputHandler:function(self,event){if(self._keyUpTimeoutPostalCode){clearTimeout(self._keyUpTimeoutPostalCode);}
self._keyUpTimeoutPostalCode=setTimeout(function(){return self._validatePostalCode(self.postalCodeInput.value).then(function(value){self.postalCodeInput.classList.remove('invalid');self.postalCodeInput.classList.add('valid');self.postalCodeError.classList.remove('visible');}).caught(function(error){self.postalCodeInput.classList.add('invalid');self.postalCodeInput.classList.remove('valid');self.postalCodeError.classList.add('visible');self.postalCodeError.innerHTML='Bitte geben Sie eine Gültige Postleitzahl ein.';}).finally(function(){self._validateForm();});},600);},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!email){self.emailError.classList.add('visible');self.emailError.innerText='';return reject(Error(email));}
if(!isEmail){self.emailError.classList.add('visible');self.emailError.innerText='Die Mail-Adresse ist ungültig.';return reject(Error(email));}
score.ajax.rest.getJSON('/rest/user/username-unique/'+encodeURIComponent(email)).then(function(data){resolve(email);}).catch(function(error){self.emailError.classList.add('visible');self.emailError.innerText='Die Mail-Adresse ist bereits vorhanden.';return reject(Error(email));});});},_validateName:function(self,name){return new BPromise(function(resolve,reject){if(!name){reject(Error(name));}
score.ajax.rest.getJSON('/rest/client/_search?q='+encodeURIComponent('name='+name)).then(function(data){if(data.client){return reject(Error(name));}
resolve(name);});});},_validateATU:function(self,atu){var isATU=/^(ATU|atu)[0-9]{8}$/.test(atu);return new BPromise(function(resolve,reject){if(!isATU){return reject(Error(atu));}
resolve(atu);});},_validateCommercialRegister:function(self,commercialRegister){return new BPromise(function(resolve,reject){if(!commercialRegister){return reject(Error(commercialRegister));}
resolve(commercialRegister);});},_validateStreet:function(self,street){return new BPromise(function(resolve,reject){if(!street){return reject(Error(street));}
resolve(street);});},_validateCity:function(self,city){return new BPromise(function(resolve,reject){if(!city){return reject(Error(city));}
resolve(city);});},_validatePostalCode:function(self,postalCode){var isPostalCode=/^[0-9]{4}$/.test(postalCode);return new BPromise(function(resolve,reject){if(!isPostalCode){return reject(Error(postalCode));}
resolve(postalCode);});},_validateConsent:function(self){if(self.consentInput.checked){self.consentInput.classList.remove('invalid');self.consentInput.classList.add('valid');self.consentError.classList.remove('visible');}else{self.consentInput.classList.remove('valid');self.consentInput.classList.add('invalid');self.consentError.classList.add('visible');self.consentError.innerHTML='Zustimmung notwendig!';};},_validateGtc:function(self){if(self.gtcInput.checked){self.gtcInput.classList.remove('invalid');self.gtcInput.classList.add('valid');self.gtcError.classList.remove('visible');}else{self.gtcInput.classList.remove('valid');self.gtcInput.classList.add('invalid');self.gtcError.classList.add('visible');self.gtcError.innerHTML='Zustimmung notwendig!';};},_validateForm:function(self){var data=Form.serialize(self.form);return self.form.querySelector('button[type=submit]').disabled=!self._validate(data);},_validate:function(self,data){var noErrors=self.form.querySelectorAll('input.invalid').length===0;return noErrors&&data.email&&data.email.length>=7&&data.atu&&data.atu.length===11&&data.name&&data.street&&data.city&&data.postalCode&&data.county&&data.county!=='0'&&data.country&&data.country!=='0'&&data.password&&data.password===data.password2&&data.gtc&&data.consent;},})});define('selfcare/router',['selfcare/stage','score.init','score.oop','score.router'],function(stage,score){var Router=score.oop.Class({__name__:'Router',__parent__:score.router,__init__:function(self){self.addRoute('intro','/intro',function(){stage.show('intro');});self.addRoute('login','/login',function(){stage.show('login');});self.addRoute('client-data','/daten',function(){stage.show('client-data')});self.addRoute('jobpostings','/jobs',function(){stage.show('jobpostings');});self.addRoute('packages','/pakete',function(){stage.show('packages')});self.addRoute('studentsearch','/schuelersuche',function(){stage.show('studentsearch')});self.addRoute('messages','/nachrichten',function(){stage.show('message');});self.addRoute('message','/nachrichten/{id}',function(vars){stage.show('message',vars.id);});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();},_hashChanged:function(self,event){var hash=document.location.hash;if(!hash||hash==='#'){document.location.hash='#/intro';}
var url=document.location.hash.substr(1);self.load(url);}});return new Router();});define('selfcare/scene',['bluebird','client','score.init','score.oop','score.dom.theater','../transitions/fade'],function(BPromise,Client,score){'use strict';return score.oop.Class({__name__:'BaseClientScene',__parent__:score.dom.theater.Scene,__events__:['createRactive'],__init__:function(self,stage,name){self.name=name;self.__super__(stage,name,score.dom('[data-component="'+name+'"]'));self.on('createRactive',self.onCreateRactive);},onCreateRactive:function(self){self.ractive.set('login',{email:'',password:''});self.ractive.on('clientLogin',function(event){var data=self.ractive.get('login');if(data.email&&data.password){Client.login(data);}});self.ractive.set('_client',Client.get());Client.on('logout',function(){self.ractive.set('_client',BPromise.resolve());});Client.on('login',function(client){self.ractive.set('_client',BPromise.resolve(client));});self.ractive.on('set',function(event,keyPath){self.ractive.set(self.MODEL.name+'.result'+keyPath,event.context);self.ractive.set('search'+keyPath,null);});self.ractive.on('unset',function(event,keyPath){self.ractive.set(self.MODEL.name+'.result'+keyPath,null);});self.ractive.on('add',function(event,keyPath){self.ractive.set('search'+keyPath+'.value',null);if(self.ractive.get(self.MODEL.name+'.result'+keyPath)==null){self.ractive.set(self.MODEL.name+'.result'+keyPath,[]);}
self.ractive.push(self.MODEL.name+'.result'+keyPath,event.context);self.ractive.update(self.MODEL.name+'.result'+keyPath);});self.ractive.on('remove',function(event,keyPath){event.original.preventDefault();if(self.ractive.get(self.MODEL.name+'.result').isDeleted){return;}
self.ractive.splice(self.MODEL.name+'.result'+keyPath,event.index.key,1);self.ractive.update(self.MODEL.name+'.result'+keyPath);});self.ractive.on('navlist',function(event,direction,itemPath){var items=self.ractive.get(itemPath+'.result.result');var active=self.ractive.get(itemPath+'.active');if(direction==='down'){if(active===undefined){active=0;}else{active++;if(active===items.length){active=0;}}}else{if(active===undefined){active=items.length-1;}else{active--;if(active<0){active=items.length-1;}}}
self.ractive.set(itemPath+'.active',active);});self.ractive.on('markActive',function(event,index,path){self.ractive.set(path,index);});self.ractive.on('select',function(event,member,path,append){var active=self.ractive.get(path+'.active');if(active===undefined||active===null){self.ractive.set(path+'.value',null);return;}
var item=self.ractive.get(path+'.result.result.'+active);if(item===undefined){self.ractive.set(path+'.value',null);return;}
if(append){self.ractive.push(self.MODEL.name+'.result'+member,item);self.ractive.set(path+'.value',null);self.ractive.set(path+'.active',null);self.ractive.set(path+'.show',false);self.ractive.update(self.MODEL.name+'.result'+member);}else{self.ractive.set(self.MODEL.name+'.result'+member,item);self.ractive.set(path,null);}});self.ractive.on('hideSearch',function(event,keyPath){window.setTimeout(function(){self.ractive.set(keyPath,false);var path=keyPath.replace('show','');self.ractive.set(path+'value','');},150);});},_getRactive:function(self){if(self.ractive){return BPromise.resolve(self.ractive);}
return new BPromise(function(resolve,reject){require(['ractive','rv!rvtpl/selfcare/'+self.name,'ractive-events-keys','ractive-promise-alt'],function(Ractive,template,keys){var CKEditor=Ractive.extend({template:'<textarea placeholder="{{placeholder}}" disabled="{{disabled}}">{{{text}}}</textarea>',onrender:function(){var _ractive=this;CKEDITOR.timestamp='1578918270';var placeholder='placeholder'in this.find('textarea').attributes?this.find('textarea').attributes['placeholder'].textContent:null;var object={placeholder:placeholder};var editor=this.editor=CKEDITOR.replace(this.find('textarea'),object);editor.on('change',function(evt){_ractive.set('text',evt.editor.getData());});},onteardown:function(){this.editor.destroy();}});var DatetimePicker=Ractive.extend({template:'<input class="flatpickr" data-default-date="{{text}}"/>',onrender:function(){var _ractive=this;new Flatpickr(this.find('input.flatpickr'),{enableTime:true,enableSeconds:false,allowInput:true,weekNumbers:true,onChange:function(dateObj,dateStr,instance){_ractive.set('text',parseInt(dateObj.getTime()/ 1000));}});}});self.ractive=new Ractive({el:self.node,template:template,adapt:['promise-alt'],events:{enter:keys.enter,downarrow:keys.downarrow,uparrow:keys.uparrow},components:{'ck-editor':CKEditor,'datetime-picker':DatetimePicker}});self.trigger('createRactive');resolve(self.ractive);});});},_loadData:function(self){return BPromise.resolve('create a _loadData() function in your Scene');},_loadSearchData:function(self,resource){return score.ajax.rest.getJSON('rest/'+resource+'?q=1');},_search:function(self,type,search,singleType){if(self.searchTimeout){clearTimeout(self.searchTimeout);}
var searchData=self.ractive.get('search.'+type+'.data')||[];var promise;if(!searchData.length){promise=new BPromise(function(resolve){self.searchTimeout=setTimeout(function(){self._loadSearchData(singleType?singleType.toLowerCase():type.toLowerCase()).then(function(data){self.ractive.set('search.'+type+'.data',data.results);return resolve(data.results);});},600);});}else{promise=BPromise.resolve(searchData);}
var p=promise.then(function(data){var ids=_.map(self.ractive.get(self.MODEL.name+'.result.'+type),'id');return _.filter(data,function(object){return ids.indexOf(object.id)===-1;});}).then(function(data){if(search==='*'){return data;}
search=search.toLowerCase();return _.filter(data,function(object){for(var key in object){var value=object[key];if(typeof value==='number'){value+='';}
if(typeof value==='string'&&value.toLowerCase().indexOf(search)>=0){return true;}}});});self.ractive.set('search.'+type+'.result',p);},_registerSearch:function(self,type,singleType){self.ractive.observe('search.'+type+'.show',function(newValue,oldValue){if(newValue){self._search(type,'*',singleType);}});self.ractive.observe('search.'+type+'.value',function(newValue,oldValue){if(newValue){self._search(type,newValue,singleType);}else{self.ractive.set('search.'+type+'.result',newValue);}});},_beforeSave:function(){return true;}});});define('selfcare/scenes/client-data',['selfcare/scene','alertify','client','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,Client,score){'use strict';return score.oop.Class({__name__:'ClientDataScene',__parent__:Scene,__static__:{MODEL:{name:'client'}},onCreateRactive:function(self){self.__super__();self._registerSearch('categories','category');self._registerSearch('contacts','contact');self.ractive.on('addBenefit',function(){var value=self.ractive.get('input.benefits');self.ractive.set('input.benefits',null);self.ractive.push(self.MODEL.name+'.result.benefits',value);self.ractive.update(self.MODEL.name+'.result.benefits');});self.ractive.on('save',function(event){if(self._validate('save',event.context)){self.save(true);}else{alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');}});},save:function(self,byUser){if(self.saveTimeout){clearTimeout(self.saveTimeout);}
var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
self.saveTimeout=setTimeout(function(){if(self.savePromise){return;}
self.savePromise=score.ajax.rest.putJSON('rest/selfcare/client',object).then(function(data){if(byUser){alertify.success('erfolgreich gespeichert');}else{alertify.success('automatisch gespeichert');}
self.savePromise=null;self._beforeSetData(self.MODEL.name,data[self.MODEL.name]);return data[self.MODEL.name];}).catch(function(error){score.ajax.rest.postJSON('/rest/error',error.toString());});self.ractive.set(self.MODEL.name,self.savePromise);},byUser?5:10000);},_load:function(self){return self._getRactive();},_activate:function(self){Client.get().then(function(client){if(!client){return;}
self.ractive.set(self.MODEL.name,self._loadData());});},_loadData:function(self){return score.ajax.rest.getJSON('rest/selfcare/'+self.MODEL.name).then(function(data){return data[self.MODEL.name];});},_parseYoutubeId:function(self,link){if(!link){return null;}
var pattern=/^(?:(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/)))?([^\?&"'>]+)/;var match=link.match(pattern);if(!match||!match[1]){return null;}
return match[1];},_validate:function(self,type,data){if(type==='save'){return data&&data.id&&data.atu&&data.name&&data.city&&data.county&&data.country&&data.email&&data.categories&&data.categories.length>0&&data.postalCode&&data.street&&data.password===data.password2;}},_beforeSave:function(self,client){if(client.password===''){delete client.password;delete client.password2;}
client.youtubeVideoId=self._parseYoutubeId(client.youtubeVideoId);return true;},_beforeCreate:function(self,client){return delete client.password2;},_beforeSetData:function(self,key,value){if(key===self.MODEL.name&&value){value.password='';value.password2='';}},});});define('selfcare/scenes/intro',['statictext','swiper','alertify','bluebird','selfcare/scene','score.init','score.oop','score.ajax.rest','score.dom'],function(StaticText,Swiper,alertify,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'IntroScene',__parent__:Scene,__static__:{MODEL:{'name':'intro',},LOAD_STATIC_TEXTS:['company_intro_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('next',function(event){window.location.href='#/erhebung';});self.ractive.on('clickSlide',function(event,url){window.location.href=url;});StaticText.loadTexts(self.ractive,self.LOAD_STATIC_TEXTS);},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]).then(function(data){var swiper=new Swiper('.swiper-container',{nextButton:'.swiper-button-next',prevButton:'.swiper-button-prev',autoplay:5000,loopedSlides:3});});});},_loadData:function(self){return score.ajax.rest.getJSON('rest/selfcare/'+self.MODEL.name.toLowerCase());},});});var r;define('selfcare/scenes/jobpostings',['selfcare/scene','alertify','bluebird','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,BPromise,score){'use strict';return score.oop.Class({__name__:'JobPostingsScene',__parent__:Scene,__static__:{MODEL:{name:'jobposting'}},onCreateRactive:function(self){self.__super__();self._registerSearch('client');self._registerSearch('categories','category');self._registerSearch('position');self._registerSearch('employmentType');self.ractive.on('edit',function(event){self.ractive.set(self.MODEL.name,self._loadData(event.context.id).then(function(data){return data.jobPosting;}));});self.ractive.on('new',function(event){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));});self.ractive.on('save',function(event){if(self._validate('save',event.context)){self.save(true,!event.context.id);}else{alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');}});self.ractive.on('back',function(event){self.ractive.set(self.MODEL.name);self.ractive.set('publish');self.ractive.set('_data',self._loadData());});self.ractive.on('pre-publish',function(event){var jobPosting=event.context;self.ractive.set('publish',score.ajax.rest.getJSON('rest/selfcare/clientproduct').then(function(result){return{products:result.clientproducts,jobPosting:jobPosting}}));});self.ractive.on('publish',function(event){var url;var payload={};if(event.rootpath==='publish.result.jobPosting.clientProduct'){url='rest/selfcare/jobposting/'+self.ractive.get('publish.result.jobPosting.id')+'/_publish';}else{url='rest/selfcare/jobposting/'+event.context.jobPosting.id+'/_publish';payload={clientProduct:event.context.clientProduct};}
score.ajax.rest.postJSON(url,payload).then(function(result){self.ractive.set('_data',self._loadData());self.ractive.set('publish');alertify.success('Jobanzeige: '+result.jobPosting.title+' ist jetzt Online');});});self.ractive.on('retire',function(event){var url='rest/selfcare/jobposting/'+event.context.id+'/_retire';score.ajax.rest.postJSON(url).then(function(result){self.ractive.set('_data',self._loadData());});});require('selfcare/mainmenu').instance.on('jobs-click',function(){self.ractive.set(self.MODEL.name);self.ractive.set('publish');self.ractive.set('_data',self._loadData());});r=self.ractive;},save:function(self,byUser,create){if(!byUser){return;}
if(self.saveTimeout){clearTimeout(self.saveTimeout);}
var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
self.saveTimeout=setTimeout(function(){if(self.savePromise){return;}
if(create){self.savePromise=score.ajax.rest.postJSON('rest/selfcare/jobposting',object);}else{self.savePromise=score.ajax.rest.putJSON('rest/selfcare/jobposting/'+object.id,object);}
self.ractive.set(self.MODEL.name,self.savePromise.then(function(data){if(byUser){alertify.success('erfolgreich gespeichert');}
self.savePromise=null;return data['jobPosting'];}).catch(function(error){alertify.error('Es ist ein Fehler aufgetreten');score.ajax.rest.postJSON('/rest/error',error.toString());}));},byUser?5:10000);},_load:function(self){return self._getRactive();},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/selfcare/jobposting'+(id?'/'+id:'');return score.ajax.rest.getJSON(url);},_validate:function(self,type,data){if(type==='save'){console.log(data);return data&&data.title&&data.bodyText&&data.contactEmail&&data.categories&&data.categories.length>0&&data.position&&data.employmentType}},});});define('selfcare/scenes/message',['selfcare/scene','alertify','user','bluebird','lodash','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,User,BPromise,_,score){'use strict';return score.oop.Class({__name__:'MessageScene',__parent__:Scene,__static__:{MODEL:{name:'message'}},onCreateRactive:function(self){self.__super__();self.ractive.on('edit',function(event){if(event.context.isNew){self.setRead(event.context.id).then(function(data){window.location.href='#/nachrichten/'+event.context.id;});}else{window.location.href='#/nachrichten/'+event.context.id;}});self.ractive.on('new',function(event){window.location.href='#/nachrichten/new';});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});self.ractive.on('delete',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.delete(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('restore',function(event){event.original.stopPropagation();if(!event.context.isDeleted){return;}
self.restore(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('mark-as-new',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setNew(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('mark-as-read',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setRead(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('back',function(event){window.location.href='#/nachrichten';});require('selfcare/mainmenu').instance.on('message-click',function(){window.location.href='#/nachrichten';});self.ractive.on('toggleIsBlacklisted',self._toggleIsBlacklisted);User.get().then(function(user){if(user){self.ractive.set('isBlacklisted',user.isBlacklisted);}});},_toggleIsBlacklisted:function(self,event){if(event!==undefined){event.original.preventDefault();if(event.context.isBlacklisted){var message='Wirklich keine Emails mehr erhalten?';}else{var message='Wirklich Emails aktivieren?';}
alertify.confirm(message,function(){self.ractive.toggle('isBlacklisted').then(function(result){event.node.checked=!self.ractive.get('isBlacklisted');score.ajax.rest.putJSON('rest/user',{'isBlacklisted':!event.node.checked}).then(function(result){alertify.success('Daten erfolgreich gespeichert.');});});},function(){});}},get:function(self,id){return self._loadData(id);},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
var create=!_event.context.id;_event.node.disabled=true;var promise;if(create){promise=score.ajax.rest.postJSON('rest/selfcare/'+self.MODEL.name.toLowerCase(),object).then(function(data){window.location.href='#/nachrichten/'+data[self.MODEL.name].id;});}else{promise=score.ajax.rest.putJSON('rest/selfcare/'+self.MODEL.name.toLowerCase()+'/'+object.id,object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);});}
promise.catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},delete:function(self,id){return self.setStatus(id,2);},restore:function(self,id){return self.setStatus(id,-1);},setRead:function(self,id){return self.setStatus(id,1);},setNew:function(self,id){return self.setStatus(id,0);},setStatus:function(self,id,status){return score.ajax.rest.putJSON('rest/selfcare/'+self.MODEL.name.toLowerCase()+'/'+id,{'status':status});},_updateMesssage:function(self,message){var messages=self.ractive.get('_data.result.messages');if(messages){var idx=_.findIndex(messages,{'id':message.id});self.ractive.set('_data.result.messages.'+idx,message);}
if(self.ractive.get(self.MODEL.name)){self.ractive.set(self.MODEL.name+'.result',message);}},_load:function(self,id){var ractive=self._getRactive();ractive.then(function(){if(id){if(id==='new'){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));}else{self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data[self.MODEL.name];}));}
self.ractive.update(self.MODEL.name+'.result');}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/selfcare/'+self.MODEL.name.toLowerCase()+(id?'/'+id:'');return score.ajax.rest.getJSON(url);},_validate:function(self,data){if(!data){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.subject||!data.recipient){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},});});define('selfcare/scenes/packages',['selfcare/scene','bluebird','score.init','score.oop','score.ajax.rest'],function(Scene,BPromise,score){'use strict';return score.oop.Class({__name__:'PackagesScene',__parent__:Scene,__static__:{MODEL:{name:'clientproduct'}},onCreateRactive:function(self){self.__super__();self.ractive.on('buy',function(event){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));self.ractive.set('products',score.ajax.rest.getJSON('rest/selfcare/product-for-client').then(function(data){return data.products||[];}));});self.ractive.on('confirm',function(event){console.log(event);});self.ractive.on('selectProduct',function(event){self.ractive.set('order',{product:event.context})});self.ractive.on('back',function(event,destination){if(destination==='list'){self.ractive.set('order',null);}else{self.ractive.set('clientproduct',null);}});self.ractive.on('agb',function(event){if(event.node.checked){self._createOrder();}});self.ractive.on('nowarning',function(){window.onbeforeunload=null;})},_load:function(self){return self._getRactive();},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/selfcare/clientproduct'+(id?'/'+id:'');return score.ajax.rest.getJSON(url);},_createOrder:function(self){var order=self.ractive.get('order');return score.ajax.rest.postJSON('rest/selfcare/order',order).then(function(result){if(result.order&&result.order.id){self.ractive.set('order',result.order);}});}});});define('selfcare/scenes/studentsearch',['statictext','bluebird','selfcare/scene','alertify','client','score.init','score.oop','score.ajax.rest'],function(StaticText,BPromise,Scene,alertify,Client,score){'use strict';return score.oop.Class({__name__:'StudentSearchScene',__parent__:Scene,__static__:{instance:null,LOAD_STATIC_TEXTS:['studentsearch_description'],},onCreateRactive:function(self){self.__super__();self.ractive.set('formatNumber',function(num){return num.toLocaleString('de-DE',{'maximumFractionDigits':2});});self.ractive.on('showInquiry',function(event){self.ractive.set('showInquiry',!self.ractive.get('showInquiry'));});self.ractive.on('search',function(event){self._search(event);});self.ractive.on('requestStudents',function(event){self._requestStudents(event);});StaticText.loadTexts(self.ractive,self.LOAD_STATIC_TEXTS);},_load:function(self){return self._getRactive();},_activate:function(self){Client.get().then(function(client){if(!client){return;}
score.ajax.rest.getJSON('/rest/selfcare/studentsearch').then(function(data){self.ractive.set('choices',data['choices']);self.ractive.set('query',data['query']);});score.ajax.rest.getJSON('/rest/selfcare/student-request').then(function(data){self.ractive.set('studentRequests',data['studentRequests']);});});},_search:function(self,_event){self.ractive.set('result.loading',true);_event.node.disabled=true;(new BPromise(function(resolve,reject){var payload={'query':self.ractive.get('query')};score.ajax.rest.postJSON('/rest/selfcare/studentsearch',payload).then(function(data){resolve(data);}).catch(function(error){reject(error);});})).then(function(data){self.ractive.set('result',data['result']);}).catch(function(error){if(error.request&&error.request.responseJSON&&error.request.responseJSON.message){alertify.error(error.request.responseJSON.message);}}).finally(function(){_event.node.disabled=false;});},_requestStudents:function(self,_event){_event.node.disabled=true;(new BPromise(function(resolve,reject){var request=self.ractive.get('request');if(request.students.length===0){return reject(new Error('Sie müssen eine Auswahl treffen.'));}
var payload={'request':request};var confirmMessage='Möchten Sie die ausgewählten SchülerInnen wirklich anfragen?';alertify.confirm(confirmMessage,function(){score.ajax.rest.postJSON('/rest/selfcare/student-request',payload).then(function(data){data['message']='Die ausgewählten SchülerInnen wurden erfolgreich angefragt.';resolve(data);}).catch(function(error){reject(error);});},function(){reject(new Error())});})).then(function(data){if(data['studentRequests']){self.ractive.set('studentRequests',data['studentRequests']);}
if(data['message']){alertify.success(data['message']);}}).catch(function(error){if(error.request&&error.request.responseJSON&&error.request.responseJSON.message){alertify.error(error.request.responseJSON.message);}}).finally(function(){_event.node.disabled=false;});}});});define('selfcare/stage',['selfcare/scenes/intro','selfcare/scenes/client-data','selfcare/scenes/jobpostings','selfcare/scenes/packages','selfcare/scenes/studentsearch','selfcare/scenes/message','score.init','score.dom.theater'],function(IntroScene,ClientDataScene,JobPostingsScene,PackageScene,StudentSearchScene,MessageScene,score){'use strict';var stage=new score.dom.theater.Stage(score.dom('#stage'));new IntroScene(stage,'intro');new ClientDataScene(stage,'client-data');new JobPostingsScene(stage,'jobpostings');new PackageScene(stage,'packages');new StudentSearchScene(stage,'studentsearch');new MessageScene(stage,'message');return stage;});define('selfcare/student-profile',['bluebird','ractive','rv!/rvtpl/selfcare/student-profile','score.init','score.oop'],function(BPromise,Ractive,template,score){return score.oop.Class({__name__:'StudentProfile',__init__:function(self,id){new BPromise(function(resolve,reject){window.onbeforeunload=null;return resolve();});self.id=id;self.ractive=new Ractive({el:'[data-component=student-profile]',template:template});self._loadData().then(function(data){self.ractive.set('profile',data);});},_loadData:function(self){return score.ajax.rest.getJSON('/rest/selfcare/student-profile/'+self.id);}});});define('selfcare/student-profile-anonymous',['bluebird','ractive','rv!/rvtpl/selfcare/student-profile-anonymous','score.init','score.oop'],function(BPromise,Ractive,template,score){return score.oop.Class({__name__:'StudentProfileAnonymous',__init__:function(self,anonymousId){new BPromise(function(resolve,reject){window.onbeforeunload=null;return resolve();});self.anonymousId=anonymousId;self.ractive=new Ractive({el:'[data-component=student-profile]',template:template});self._loadData().then(function(data){self.ractive.set('profile',data);});},_loadData:function(self){return score.ajax.rest.getJSON('/rest/selfcare/student-profile-anonymous/'+self.anonymousId);}});});define('statictext',['score.init','score.oop','score.dom','score.ajax.rest'],function(score){'use strict';return score.oop.Class({__name__:'StaticText',__init__:function(self){},loadTexts:function(self,ractive,texts){if(texts){texts.forEach(function(name){score.ajax.rest.getJSON('rest/statictext/'+name).then(function(data){if(data.statictext&&data.statictext.text){ractive.set('staticTexts.'+name,data.statictext.text);}});});}}})();});define('student/router',['student/stage','score.init','score.oop','score.router'],function(stage,score){var Router=score.oop.Class({__name__:'Router',__parent__:score.router,__init__:function(self){self.addRoute('intro','/intro',function(){stage.show('intro')});self.addRoute('resume','/lebenslauf',function(){stage.show('resume')});self.addRoute('documents','/dokumente',function(){stage.show('documents')});self.addRoute('messages','/nachrichten',function(){stage.show('message')});self.addRoute('message','/nachrichten/{id}',function(vars){stage.show('message',vars.id);});self.addRoute('student-data','/schuelerdaten',function(){stage.show('student-data')});self.addRoute('inquiries','/erhebung',function(){stage.show('inquiry')});self.addRoute('coach','/coach',function(){stage.show('coach')});self.addRoute('publish','/freigabe',function(){stage.show('publish')});self.addRoute('profilesettings','/profilesettings',function(){stage.show('profilesettings')});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();},_hashChanged:function(self,event){var hash=document.location.hash;if(!hash||hash==='#'){document.location.hash='#/intro';}
var url=document.location.hash.substr(1);self.load(url);},});return new Router();});define('student/stage',['userprofile/scenes/intro','userprofile/scenes/resume','userprofile/scenes/documents','userprofile/scenes/message','userprofile/scenes/student-data','userprofile/scenes/inquiry','userprofile/scenes/coach','userprofile/scenes/publish','userprofile/scenes/profilesettings','score.init','score.dom.theater'],function(IntroScene,ResumeScene,DocumentsScene,MessageScene,StudentDataScene,InquiryScene,CoachScene,PublishScene,SetpasswordScene,score){'use strict';var stage=new score.dom.theater.Stage(score.dom('#stage'));new IntroScene(stage,'intro');new ResumeScene(stage,'resume');new DocumentsScene(stage,'documents');new MessageScene(stage,'message');new StudentDataScene(stage,'student-data');new InquiryScene(stage,'inquiry');new CoachScene(stage,'coach');new PublishScene(stage,'publish');new SetpasswordScene(stage,'profilesettings');return stage;});define('student/student-request-approval',['alertify','bluebird','ractive','rv!/rvtpl/student/student-request-approval','score.init','score.oop'],function(alertify,BPromise,Ractive,template,score){return score.oop.Class({__name__:'StudentRequestApproval',__init__:function(self,clientId){self.clientId=clientId;self._getStudentRequest().then(function(data){if(data.studentRequest){self.ractive=new Ractive({el:'[data-component=student-request-approval]',template:template});self.ractive.on('approve',self._showOverlay);self._update(data.studentRequest);}});},_showOverlay:function(self){require(['components/overlay'],function(Overlay){var scene=Overlay.scenes['student-request-approval'];scene.off('studentApproved');scene.on('studentApproved',self._approveStudentRequest);Overlay.show('student-request-approval');});},_update:function(self,studentRequest){self.ractive.set('studentRequest',studentRequest);},_approveStudentRequest:function(self){score.ajax.rest.postJSON('/rest/student/student-request-approval/'+self.clientId).then(function(data){if(data.studentRequest){self._update(data.studentRequest);alertify.success('Eine Mail wurde an den Arbeitgeber versendet.');}});},_getStudentRequest:function(self){return score.ajax.rest.getJSON('/rest/student/student-request-approval/'+self.clientId);}});});define('teacher',['alertify','bluebird','lib/cookie','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Cookie,score){return score.oop.Class({__name__:'Teacher',__static__:{COOKIEWATCHER_INTERVAL:1000,KEEPALIVE_INTERVAL:600000},__events__:['login','logout'],__init__:function(self){self.on('login',self._login);self.on('logout',self._logout);self._startCookieWatcher();self._keepAlive();window.onbeforeunload=function(e){var message="Your confirmation message goes here.",e=e||window.event;if(e){e.returnValue=message;}
return message;};},get:function(self){if(!Cookie.get('MJESSID')){self.trigger('logout');return BPromise.resolve(null);}
if(self.teacher){return BPromise.resolve(self.teacher);}
if(self.getPromise){return self.getPromise;}
self.getPromise=score.ajax.rest.getJSON('/rest/teachersroom/teacher').then(function(data){self.getPromise=null;if(data.teacher&&data.teacher.id){self.trigger('login',data.teacher,false);return data.teacher;}
self.trigger('logout');return null;}).catch(function(){self.getPromise=null;self.trigger('logout');});return self.getPromise;},login:function(self,data){return score.ajax.rest.postJSON('/rest/teacher/_login',data).then(function(data){if(!data.teacher){alertify.error('Benutzername oder Passwort falsch.');return;}
self.trigger('login',data.teacher,true);alertify.success('Sie haben sich erfolgreich angemeldet.');return data.teacher;});},_login:function(self,teacher){self.teacher=teacher;},_logout:function(self){self.teacher=null;Cookie.remove('MJESSID',{path:'/',domain:'meinjob.at',secure:false});Cookie.remove('MJESSID',{path:'/',secure:false});},_startCookieWatcher:function(self){setInterval(function(){if(!Cookie.get('MJESSID')&&self.teacher){self.trigger('logout');}else if(Cookie.get('MJESSID')&&!self.teacher){self.get();}},self.COOKIEWATCHER_INTERVAL);},_keepAlive:function(self){setInterval(function(){score.ajax('/keepalive');},self.KEEPALIVE_INTERVAL);}})();});define('teachersroom/mainmenu',['ractive','rv!rvtpl/teachersroom/mainmenu','lodash','teacher','score.init','score.oop'],function(Ractive,template,_,Teacher,score){return score.oop.Class({__name__:'MainMenu',__static__:{instance:null},__events__:['schoolclass-click','message-click','student-click'],__init__:function(self){self.ractive=new Ractive({el:'[data-component=mainmenu]',template:template});self.ractive.on('menuclick',function(a){if(a.context.href==='#/schulklassen'){return self.trigger('schoolclass-click');}
if(a.context.href==='#/schueler'){return self.trigger('student-click');}
if(a.context.href==='#/nachrichten'){return self.trigger('message-click');}});self._loadPromise=self._loadData().then(function(data){self.ractive.set('menu.entries',data.menu.entries);Teacher.get().then(self._hasNewMessages);if(self._hash){return self._handleHash();}});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();window.setInterval(function(){Teacher.get().then(self._hasNewMessages);},5000);},_hashChanged:function(self){self._hash=document.location.hash;self._handleHash();},_handleHash:function(self){var entries=self.ractive.get('menu.entries');if(!self._hash||!entries||self._hash.indexOf('#/')!==0){return;}
_.forEach(entries,function(entry,key){if(self._hash!=='#/'&&entry.href==='#/'){return;}
entry.isActive=self._hash.indexOf(entry.href)===0;});self.ractive.set('menu.entries',entries);},_loadData:function(self){return score.ajax.rest.getJSON('rest/teachersroom/mainmenu');},_hasNewMessages:function(self){var entries=self.ractive.get('menu.entries');if(!entries){return;}
score.ajax.rest.getJSON('/rest/teachersroom/message').then(function(data){if(!data.messages){return;}
var hasNewMessages=false;for(var i=0;i<data.messages.length;i++){if(data.messages[i].isNew){hasNewMessages=true;break;}}
for(var i=0;i<entries.length;i++){if(entries[i].href==='#/nachrichten'){entries[i].hasNewMessages=hasNewMessages;break;}}
self.ractive.set('menu.entries',entries);});}});});define('teachersroom/register',['bluebird','components/form','score.init','score.oop','score.ajax.rest'],function(BPromise,Form,score){'use strict';return score.oop.Class({__name__:'Register',__init__:function(self,form){new BPromise(function(resolve,reject){window.onbeforeunload=null;return resolve();});self._timeouts={'_nameInputHandler':null,'_emailInputHandler':null,'_passwordInputHandler':null};self.form=form;self.form.addEventListener('submit',function(e){e.preventDefault();var data=Form.serialize(self.form);if(self._validate(data)){score.ajax.rest.postJSON('/rest/teacher/_register',data).then(function(result){window.location.href='/lehrerzimmer#/daten';});}});self.firstNameInput=self.form.querySelector('input[name=firstName]');self.firstNameInput.addEventListener('keyup',self._nameInputHandler);self.firstNameInput.addEventListener('blur',self._nameInputHandler);self.firstNameInput.addEventListener('change',self._nameInputHandler);self.nameError=self.form.querySelector('.error-message__name');self.lastNameInput=self.form.querySelector('input[name=lastName]');self.lastNameInput.addEventListener('keyup',self._nameInputHandler);self.lastNameInput.addEventListener('blur',self._nameInputHandler);self.lastNameInput.addEventListener('change',self._nameInputHandler);self.emailInput=self.form.querySelector('input[name=email]');self.emailInput.addEventListener('keyup',self._emailInputHandler);self.emailInput.addEventListener('blur',self._emailInputHandler);self.emailInput.addEventListener('change',self._emailInputHandler);self.emailError=self.form.querySelector('.error-message__email');self.passwordInput=self.form.querySelector('input[name=password]');self.password2Input=self.form.querySelector('input[name=password2]');self.passwordInput.addEventListener('keyup',self._passwordInputHandler);self.passwordInput.addEventListener('blur',self._passwordInputHandler);self.passwordInput.addEventListener('change',self._passwordInputHandler);self.password2Input.addEventListener('keyup',self._passwordInputHandler);self.password2Input.addEventListener('blur',self._passwordInputHandler);self.password2Input.addEventListener('change',self._passwordInputHandler);self.passwordError=self.form.querySelector('.error-message__password');self.consentInput=self.form.querySelector('input[name=consent]');self.consentInput.addEventListener('keyup',self._validateConsent);self.consentInput.addEventListener('blur',self._validateConsent);self.consentInput.addEventListener('change',self._validateConsent);self.consentError=self.form.querySelector('.error-message__consent');self.gtcInput=self.form.querySelector('input[name=gtc]');self.gtcInput.addEventListener('keyup',self._validateGtc);self.gtcInput.addEventListener('blur',self._validateGtc);self.gtcInput.addEventListener('change',self._validateGtc);self.gtcError=self.form.querySelector('.error-message__gtc');self.form.addEventListener('change',function(){self._validateForm();});self._validateTimeout=setTimeout(function(){self._validateForm();},1000);_.forEach(self.form.querySelectorAll('input[required=required]'),function(field){if(field.name==='password'){return;}
field.classList.add('invalid');});},_nameInputHandler:function(self,event){clearTimeout(self._timeouts['_nameInputHandler']);self._timeouts['_nameInputHandler']=setTimeout(function(){var payload={'firstName':self.firstNameInput.value,'lastName':self.lastNameInput.value};score.ajax.rest.postJSON('/rest/teacher/_registrationpolicy',payload).then(function(){self.firstNameInput.classList.remove('invalid');self.firstNameInput.classList.add('valid');self.lastNameInput.classList.remove('invalid');self.lastNameInput.classList.add('valid');self.nameError.classList.remove('visible');}).catch(function(){self.firstNameInput.classList.remove('valid');self.firstNameInput.classList.add('invalid');self.lastNameInput.classList.remove('valid');self.lastNameInput.classList.add('invalid');self.nameError.classList.add('visible');self.nameError.innerHTML='Die Daten erfüllen nicht die notwendigen Anforderungen für die Registrierung als Lehrer.';});},500);},_passwordInputHandler:function(self,event){clearTimeout(self._timeouts['_passwordInputHandler']);self._timeouts['_passwordInputHandler']=setTimeout(function(){if(!self.passwordInput.value&&self.passwordInput.value===self.password2Input.value){self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='';}else if(self.passwordInput.value&&self.passwordInput.value===self.password2Input.value){self.password2Input.classList.remove('invalid');self.password2Input.classList.add('valid');self.passwordError.classList.remove('visible');}else{self.password2Input.classList.remove('valid');self.password2Input.classList.add('invalid');self.passwordError.classList.add('visible');self.passwordError.innerHTML='Die Passwörter stimmen nicht überein.';}
self._validateForm();},500);},_emailInputHandler:function(self,event){clearTimeout(self._timeouts['_emailInputHandler']);self._timeouts['_emailInputHandler']=setTimeout(function(){self._validateEmail(self.emailInput.value).then(function(email){self.emailInput.classList.remove('invalid');self.emailInput.classList.add('valid');self.emailError.classList.remove('visible');}).caught(function(email){self.emailInput.classList.add('invalid');self.emailInput.classList.remove('valid');}).finally(function(){self._validateForm();});},500);},_validateEmail:function(self,email){var isEmail=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);return new BPromise(function(resolve,reject){if(!email){self.emailError.classList.add('visible');self.emailError.innerText='';return reject(Error(email));}
if(!isEmail){self.emailError.classList.add('visible');self.emailError.innerText='Die Mail-Adresse ist ungültig.';return reject(Error(email));}
score.ajax.rest.getJSON('/rest/teacher/_search?q='+encodeURIComponent('email='+email)).then(function(data){if(data.teacher){self.emailError.classList.add('visible');self.emailError.innerHTML='Die Mail-Adresse ist bereits vorhanden.';return reject(Error(email));}
resolve(email);});});},_validateConsent:function(self){if(self.consentInput.checked){self.consentInput.classList.remove('invalid');self.consentInput.classList.add('valid');self.consentError.classList.remove('visible');}else{self.consentInput.classList.remove('valid');self.consentInput.classList.add('invalid');self.consentError.classList.add('visible');self.consentError.innerHTML='Zustimmung notwendig!';};},_validateGtc:function(self){if(self.gtcInput.checked){self.gtcInput.classList.remove('invalid');self.gtcInput.classList.add('valid');self.gtcError.classList.remove('visible');}else{self.gtcInput.classList.remove('valid');self.gtcInput.classList.add('invalid');self.gtcError.classList.add('visible');self.gtcError.innerHTML='Zustimmung notwendig!';};},_validateForm:function(self){var data=Form.serialize(self.form);return self.form.querySelector('button[type=submit]').disabled=!self._validate(data);},_validate:function(self,data){var noErrors=self.form.querySelectorAll('input.invalid').length===0;return noErrors&&data.email&&data.email.length>=7&&data.password&&data.password===data.password2&&data.firstName&&data.firstName.length>1&&data.lastName&&data.lastName.length>1;},})});define('teachersroom/router',['teachersroom/stage','score.init','score.oop','score.router'],function(stage,score){var Router=score.oop.Class({__name__:'Router',__parent__:score.router,__init__:function(self){self.addRoute('teacher-data','/daten',function(){stage.show('teacher-data');});self.addRoute('schoolclasses','/schulklassen',function(){stage.show('schoolclass');});self.addRoute('students','/schueler',function(){stage.show('student');});self.addRoute('messages','/nachrichten',function(){stage.show('message');});self.addRoute('schoolclass','/schulklassen/{id}',function(vars){stage.show('schoolclass',vars.id);});self.addRoute('student-profile','/schueler/{id}/profile',function(vars){stage.show('student',{id:vars.id,profile:true});});self.addRoute('student','/schueler/{id}',function(vars){stage.show('student',{id:vars.id});});self.addRoute('message','/nachrichten/{id}',function(vars){stage.show('message',vars.id);});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();},_hashChanged:function(self,event){var hash=document.location.hash;if(!hash||hash==='#'){document.location.hash='#/daten';}
var url=document.location.hash.substr(1);self.load(url);}});return new Router();});define('teachersroom/scene',['bluebird','teacher','score.init','score.oop','score.dom.theater','../transitions/fade'],function(BPromise,Teacher,score){'use strict';return score.oop.Class({__name__:'BaseTeachersroomScene',__parent__:score.dom.theater.Scene,__events__:['createRactive'],__init__:function(self,stage,name){self.name=name;self.__super__(stage,name,score.dom('[data-component="'+name+'"]'));self.on('createRactive',self.onCreateRactive);},onCreateRactive:function(self){self.ractive.set('login',{email:'',password:''});self.ractive.set('_teacher',Teacher.get());Teacher.on('logout',function(){self.ractive.set('_teacher',BPromise.resolve());});Teacher.on('login',function(teacher){self.ractive.set('_teacher',BPromise.resolve(teacher));});self.ractive.on('set',function(event,keyPath){self.ractive.set(self.MODEL.name+'.result'+keyPath,event.context);self.ractive.set('search'+keyPath,null);});self.ractive.on('unset',function(event,keyPath){self.ractive.set(self.MODEL.name+'.result'+keyPath,null);});self.ractive.on('add',function(event,keyPath){self.ractive.set('search'+keyPath+'.value',null);if(self.ractive.get(self.MODEL.name+'.result'+keyPath)==null){self.ractive.set(self.MODEL.name+'.result'+keyPath,[]);}
self.ractive.push(self.MODEL.name+'.result'+keyPath,event.context);self.ractive.update(self.MODEL.name+'.result'+keyPath);});self.ractive.on('remove',function(event,keyPath){event.original.preventDefault();if(self.ractive.get(self.MODEL.name+'.result').isDeleted){return;}
self.ractive.splice(self.MODEL.name+'.result'+keyPath,event.index.key,1);self.ractive.update(self.MODEL.name+'.result'+keyPath);});self.ractive.on('navlist',function(event,direction,itemPath){var items=self.ractive.get(itemPath+'.result.result');var active=self.ractive.get(itemPath+'.active');if(direction==='down'){if(active===undefined){active=0;}else{active++;if(active===items.length){active=0;}}}else{if(active===undefined){active=items.length-1;}else{active--;if(active<0){active=items.length-1;}}}
self.ractive.set(itemPath+'.active',active);});self.ractive.on('markActive',function(event,index,path){self.ractive.set(path,index);});self.ractive.on('select',function(event,member,path,append){var active=self.ractive.get(path+'.active');if(active===undefined){return;}
var item=self.ractive.get(path+'.result.result.'+active);if(append){self.ractive.push(self.MODEL.name+'.result'+member,item);self.ractive.set(path+'.value',null);self.ractive.set(path+'.active',null);self.ractive.set(path+'.show',false);self.ractive.update(self.MODEL.name+'.result'+member);}else{self.ractive.set(self.MODEL.name+'.result'+member,item);self.ractive.set(path,null);}});self.ractive.on('hideSearch',function(event,keyPath){window.setTimeout(function(){self.ractive.set(keyPath,false);},150);})},_getRactive:function(self){if(self.ractive){return BPromise.resolve(self.ractive);}
return new BPromise(function(resolve,reject){require(['ractive','rv!rvtpl/teachersroom/'+self.name,'ractive-events-keys','ractive-promise-alt'],function(Ractive,template,keys){var CKEditor=Ractive.extend({template:'<textarea placeholder="{{placeholder}}" disabled="{{disabled}}">{{{text}}}</textarea>',onrender:function(){var _ractive=this;CKEDITOR.timestamp='1578918270';var placeholder='placeholder'in this.find('textarea').attributes?this.find('textarea').attributes['placeholder'].textContent:null;var object={placeholder:placeholder};var editor=this.editor=CKEDITOR.replace(this.find('textarea'),object);editor.on('change',function(evt){_ractive.set('text',evt.editor.getData());});},onteardown:function(){this.editor.destroy();}});var DatetimePicker=Ractive.extend({template:'<input class="flatpickr" data-default-date="{{text}}"/>',onrender:function(){var _ractive=this;new Flatpickr(this.find('input.flatpickr'),{enableTime:true,enableSeconds:false,allowInput:true,weekNumbers:true,onChange:function(dateObj,dateStr,instance){_ractive.set('text',parseInt(dateObj.getTime()/ 1000));}});}});self.ractive=new Ractive({el:self.node,template:template,adapt:['promise-alt'],events:{enter:keys.enter,downarrow:keys.downarrow,uparrow:keys.uparrow},components:{'ck-editor':CKEditor,'datetime-picker':DatetimePicker}});self.trigger('createRactive');resolve(self.ractive);});});},_loadData:function(self){return BPromise.resolve('create a _loadData() function in your Scene');},_loadSearchData:function(self,resource){return score.ajax.rest.getJSON('rest/'+resource+'?q=1');},_search:function(self,type,search,singleType,forceFetch){if(self.searchTimeout){clearTimeout(self.searchTimeout);}
var searchData=self.ractive.get('search.'+type+'.data')||[];var promise;if(!searchData.length||forceFetch){promise=new BPromise(function(resolve){self.searchTimeout=setTimeout(function(){self._loadSearchData(singleType?singleType.toLowerCase():type.toLowerCase()).then(function(data){self.ractive.set('search.'+type+'.data',data.results);return resolve(data.results);});},600);});}else{promise=BPromise.resolve(searchData);}
var p=promise.then(function(data){var ids=_.map(self.ractive.get(self.MODEL.name+'.result.'+type),'id');return _.filter(data,function(object){return ids.indexOf(object.id)===-1;});}).then(function(data){if(search==='*'){return data;}
search=search.toLowerCase();return _.filter(data,function(object){for(var key in object){var value=object[key];if(typeof value==='number'){value+='';}
if(typeof value==='string'&&value.toLowerCase().indexOf(search)>=0){return true;}}});});self.ractive.set('search.'+type+'.result',p);},_registerSearch:function(self,type,singleType,forceFetch){self.ractive.observe('search.'+type+'.show',function(newValue,oldValue){if(newValue){self._search(type,'*',singleType,forceFetch);}});self.ractive.observe('search.'+type+'.value',function(newValue,oldValue){if(newValue){self._search(type,newValue,singleType,forceFetch);}else{self.ractive.set('search.'+type+'.result',newValue);}});},_beforeSave:function(){return true;}});});define('teachersroom/scenes/message',['teachersroom/scene','alertify','bluebird','lodash','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,BPromise,_,score){'use strict';return score.oop.Class({__name__:'MessageScene',__parent__:Scene,__static__:{MODEL:{name:'message'}},onCreateRactive:function(self){self.__super__();self.ractive.on('edit',function(event){if(event.context.isNew){self.setRead(event.context.id).then(function(data){window.location.href='#/nachrichten/'+event.context.id;});}else{window.location.href='#/nachrichten/'+event.context.id;}});self.ractive.on('new',function(event){window.location.href='#/nachrichten/new';});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});self.ractive.on('delete',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.delete(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('restore',function(event){event.original.stopPropagation();if(!event.context.isDeleted){return;}
self.restore(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('mark-as-new',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setNew(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('mark-as-read',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setRead(event.context.id).then(function(data){self._updateMesssage(data[self.MODEL.name]);});});self.ractive.on('back',function(event){window.location.href='#/nachrichten';});require('teachersroom/mainmenu').instance.on('message-click',function(){window.location.href='#/nachrichten';});},get:function(self,id){return self._loadData(id);},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
var create=!_event.context.id;_event.node.disabled=true;var promise;if(create){promise=score.ajax.rest.postJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase(),object).then(function(data){window.location.href='#/nachrichten/'+data[self.MODEL.name].id;});}else{promise=score.ajax.rest.putJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase()+'/'+object.id,object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);});}
promise.catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},delete:function(self,id){return self.setStatus(id,2);},restore:function(self,id){return self.setStatus(id,-1);},setRead:function(self,id){return self.setStatus(id,1);},setNew:function(self,id){return self.setStatus(id,0);},setStatus:function(self,id,status){return score.ajax.rest.putJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase()+'/'+id,{'status':status});},_updateMesssage:function(self,message){var messages=self.ractive.get('_data.result.messages');if(messages){var idx=_.findIndex(messages,{'id':message.id});self.ractive.set('_data.result.messages.'+idx,message);}
if(self.ractive.get(self.MODEL.name)){self.ractive.set(self.MODEL.name+'.result',message);}},_load:function(self,id){var ractive=self._getRactive();ractive.then(function(){if(id){if(id==='new'){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));}else{self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data[self.MODEL.name];}));}
self.ractive.update(self.MODEL.name+'.result');}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/teachersroom/'+self.MODEL.name.toLowerCase()+(id?'/'+id:'');return score.ajax.rest.getJSON(url);},_validate:function(self,data){if(!data){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.subject||!data.recipient){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},});});define('teachersroom/scenes/schoolclass',['teachersroom/scene','alertify','bluebird','lodash','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,BPromise,_,score){'use strict';return score.oop.Class({__name__:'SchoolClassScene',__parent__:Scene,__static__:{MODEL:{name:'schoolClass'},ROUTE:''},onCreateRactive:function(self){self.__super__();self._registerSearch('school');self.ractive.on('edit',function(event){window.location.href='#/schulklassen/'+event.context.id;});self.ractive.on('new',function(event){window.location.href='#/schulklassen/new';});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});self.ractive.on('back',function(event){window.location.href='#/schulklassen';});self.ractive.on('addStudent',function(event){self._addStudent(event,event.context);});require('teachersroom/mainmenu').instance.on('schoolclass-click',function(){window.location.href='#/schulklassen';});},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
var create=!_event.context.id;_event.node.disabled=true;var promise;if(create){promise=score.ajax.rest.postJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase(),object).then(function(data){window.location.href='#/schulklassen/'+data[self.MODEL.name].id;});}else{promise=score.ajax.rest.putJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase()+'/'+object.id,object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);});}
promise.catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},_load:function(self,id){var ractive=self._getRactive();ractive.then(function(){if(id){if(id==='new'){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));}else{self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data[self.MODEL.name];}));}}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/teachersroom/'+self.MODEL.name.toLowerCase()+(id?'/'+id:'');return score.ajax.rest.getJSON(url);},_validate:function(self,data){if(!data){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.name||!data.school){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},_addStudent:function(self,_event){var email=_event.context._addedStudent;var schoolClassId=_event.context.id;if(!email){alertify.error('Die E-Mail-Adresse darf nicht leer sein.');return;}
if(email.length<7){alertify.error('Die E-Mail-Adresse muss aus mindestens 7 Zeichen bestehen.,');return;}
if(!(email.indexOf('@')>-1)){alertify.error('Ungültige E-Mail-Adresse.');return;}
if(_.find(self.ractive.get(self.MODEL.name+'.result.students'),{'email':email})){alertify.error('Schüler mit der E-Mail "'+email+'" befindet sich bereits in der Liste.');return;}
var payload={'user':{'name':email,'email':email},'schoolClass':schoolClassId};_event.node.disabled=true;score.ajax.rest.postJSON('rest/teachersroom/student-add',payload).then(function(data){self.ractive.push(self.MODEL.name+'.result.students',data.student);self.ractive.update(self.MODEL.name+'.result.students');self.ractive.set(self.MODEL.name+'.result._addedStudent',null);alertify.success(data.message);}).catch(function(error){if(error.request.responseJSON&&error.request.responseJSON.message){alertify.error(error.request.responseJSON.message);return;}
alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},});});define('teachersroom/scenes/student',['teachersroom/scene','alertify','bluebird','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,BPromise,score){'use strict';return score.oop.Class({__name__:'StudentScene',__parent__:Scene,__static__:{MODEL:{name:'student'}},onCreateRactive:function(self){self.__super__();self._registerSearch('schoolClass');self.ractive.on('edit',function(event){window.location.href='#/schueler/'+event.context.id;});self.ractive.on('new',function(event){window.location.href='#/schueler/new';});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});self.ractive.on('back',function(event){if(event.context.student){window.location.href='#/schueler/'+event.context.student.id;}else{window.location.href='#/schueler';}});self.ractive.on('profile',function(event){window.location.href='#/schueler/'+event.context.id+'/profile';});require('teachersroom/mainmenu').instance.on('student-click',function(){window.location.href='#/schueler';});},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(object&&object.student){object=object.student;_event.context=_event.context.student;}
if(!self._beforeSave(object)){return;}
var create=!_event.context.id;_event.node.disabled=true;var promise;if(create){promise=score.ajax.rest.postJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase(),object).then(function(data){window.location.href='#/schueler/'+data[self.MODEL.name].id;});}else{promise=score.ajax.rest.putJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase()+'/'+object.id,object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);});}
promise.catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},_load:function(self,vars){var ractive=self._getRactive();ractive.then(function(){if(vars){var id=vars.id;var profile=vars.profile;if(id==='new'){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));}else{if(profile){self.ractive.set(self.MODEL.name,self._loadProfileData(id).then(function(data){return data;}));self.ractive.set('profile','profile');}else{self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data[self.MODEL.name];}));self.ractive.set('profile',undefined);}}}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());},_loadData:function(self,id){var url='rest/teachersroom/'+self.MODEL.name.toLowerCase()+(id?'/'+id:'');return score.ajax.rest.getJSON(url).then(function(data){if(data.students){data.students.forEach(function(part,index,array){array[index].studentRequestsApprovedCount=_.sumBy(part.studentRequests,function(o){return o.studentApproved?1:0});});}
return data;});},_loadProfileData:function(self,id){return score.ajax.rest.getJSON('/rest/teachersroom/student-profile/'+id);},_validate:function(self,data){if(data&&data.student){data=data.student;}
if(!data||!data.user){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.user.name||!data.user.email){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},});});define('teachersroom/scenes/teacher-data',['teachersroom/scene','alertify','teacher','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,Teacher,score){'use strict';return score.oop.Class({__name__:'TeacherDataScene',__parent__:Scene,__static__:{MODEL:{name:'teacher'}},onCreateRactive:function(self){self.__super__();self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}});},save:function(self,_event){var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
_event.node.disabled=true;score.ajax.rest.putJSON('rest/teachersroom/'+self.MODEL.name.toLowerCase(),object).then(function(data){alertify.success('Daten erfolgreich gespeichert.');self.ractive.set(self.MODEL.name+'.result',data[self.MODEL.name]);}).catch(function(error){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},_load:function(self){return self._getRactive();},_activate:function(self){Teacher.get().then(function(teacher){if(!teacher){return;}
self.ractive.set(self.MODEL.name,self._loadData());});},_loadData:function(self){return score.ajax.rest.getJSON('rest/teachersroom/'+self.MODEL.name).then(function(data){return data[self.MODEL.name];});},_validate:function(self,data){if(data.password!==data.password2){alertify.error('Die beiden Passwörter stimmen nicht überein.');return false;}
if(!data||!data.id){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');return false;}
if(!data.email||!data.firstName||!data.lastName||!data.gender){alertify.error('Es müssen alle mit * markierten Felder ausgefüllt werden.');return false;}
return true;},_beforeSave:function(self,teacher){if(teacher.password===''){delete teacher.password;delete teacher.password2;}
return true;},_beforeCreate:function(self,teacher){return delete teacher.password2;},_beforeSetData:function(self,key,value){if(key===self.MODEL.name&&value){value.password=null;value.password2=null;}},});});define('teachersroom/stage',['teachersroom/scenes/teacher-data','teachersroom/scenes/schoolclass','teachersroom/scenes/student','teachersroom/scenes/message','score.init','score.dom.theater'],function(TeacherDataScene,SchoolClassScene,StudentScene,MessageScene,score){'use strict';var stage=new score.dom.theater.Stage(score.dom('#stage'));new TeacherDataScene(stage,'teacher-data');new SchoolClassScene(stage,'schoolclass');new StudentScene(stage,'student');new MessageScene(stage,'message');return stage;});define('transitions/fade',['ractive'],function(Ractive){'use strict';Ractive.transitions.fade=function(t,params){params=t.processParams(params,{duration:400,opacity:t.isIntro?1:0});t.setStyle("opacity",0);t.animateStyle("opacity",params.opacity,{duration:params.duration,easing:"linear"}).then(t.complete);};});define('user',['alertify','bluebird','lib/cookie','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Cookie,score){return score.oop.Class({__name__:'User',__static__:{COOKIEWATCHER_INTERVAL:1000,KEEPALIVE_INTERVAL:600000},__events__:['login','logout'],__init__:function(self){alertify;self.on('login',self._login);self.on('logout',self._logout);self._startCookieWatcher();self._keepAlive();},get:function(self){if(!Cookie.get('MJESSID')){self.trigger('logout');return BPromise.resolve(null);}
if(self.user){return BPromise.resolve(self.user);}
if(self.getPromise){return self.getPromise;}
self.getPromise=score.ajax.rest.getJSON('/rest/user').then(function(data){self.getPromise=null;if(data.user&&data.user.id){self.trigger('login',data.user,false);return data.user;}
self.trigger('logout');return null;}).catch(function(){self.getPromise=null;self.trigger('logout');});return self.getPromise;},login:function(self,data){return score.ajax.rest.postJSON('/rest/user/_login',data).then(function(data){if(!data.user){alertify.error('Benutzername oder Passwort falsch.');return;}
self.trigger('login',data.user,true);alertify.success('Sie haben sich erfolgreich angemeldet.');return data.user;});},_login:function(self,user){var pathname='/user/username';if(!user.name&&window.location.pathname!==pathname){return window.location.href=pathname;}
self.user=user;},_logout:function(self){self.user=null;Cookie.remove('MJESSID',{path:'/',domain:'meinjob.at',secure:false});Cookie.remove('MJESSID',{path:'/',secure:false});},_startCookieWatcher:function(self){setInterval(function(){if(!Cookie.get('MJESSID')&&self.user){self.trigger('logout');}else if(Cookie.get('MJESSID')&&!self.user){self.get();}},self.COOKIEWATCHER_INTERVAL);},_keepAlive:function(self){setInterval(function(){score.ajax('/keepalive');},self.KEEPALIVE_INTERVAL);}})();});define('userprofile/mainmenu',['statictext','ractive','rv!rvtpl/userprofile/mainmenu','lodash','user','score.init','score.oop'],function(StaticText,Ractive,template,_,User,score){return score.oop.Class({__name__:'MainMenu',__static__:{LOAD_STATIC_TEXTS:['student_menu_text'],},__init__:function(self){self.ractive=new Ractive({el:'[data-component=mainmenu]',template:template});StaticText.loadTexts(self.ractive,self.LOAD_STATIC_TEXTS);self._loadPromise=self._loadData().then(function(data){self.ractive.set('menu.entries',data.menu.entries);User.get().then(function(user){if(user){self._hasNewMessages();}});if(self._hash){return self._handleHash();}});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();window.setInterval(function(){User.get().then(function(user){if(user){self._hasNewMessages();}});},5000);},_hashChanged:function(self){self._hash=document.location.hash;self._handleHash();},_handleHash:function(self){var entries=self.ractive.get('menu.entries');if(!self._hash||!entries||self._hash.indexOf('#/')!==0){return;}
_.forEach(entries,function(entry,key){if(self._hash!=='#/'&&entry.href==='#/'){return;}
entry.isActive=self._hash.indexOf(entry.href)===0;});self.ractive.set('menu.entries',entries);},_loadData:function(self){return score.ajax.rest.getJSON('rest/userprofile/mainmenu');},_hasNewMessages:function(self){var entries=self.ractive.get('menu.entries');if(!entries){return;}
score.ajax.rest.getJSON('/rest/userprofile/message').then(function(data){if(!data.messages){return;}
var hasNewMessages=false;for(var i=0;i<data.messages.length;i++){if(data.messages[i].isNew){hasNewMessages=true;break;}}
for(var i=0;i<entries.length;i++){if(entries[i].href==='#/nachrichten'){entries[i].hasNewMessages=hasNewMessages;break;}}
self.ractive.set('menu.entries',entries);});}});});define('userprofile/router',['userprofile/stage','score.init','score.oop','score.router'],function(stage,score){var Router=score.oop.Class({__name__:'Router',__parent__:score.router,__init__:function(self){self.addRoute('resume','/lebenslauf',function(){stage.show('resume')});self.addRoute('letter-of-application','/bewerbungsschreiben',function(){stage.show('letter-of-application');});self.addRoute('favorites','/merkliste',function(){stage.show('favorites')});self.addRoute('application-for-employment','/bewerbungen',function(){stage.show('application-for-employment')});self.addRoute('documents','/dokumente',function(){stage.show('documents')});self.addRoute('jobalarm','/jobalarm',function(){stage.show('jobalarm')});self.addRoute('newsletter','/newsletter',function(){stage.show('newsletter')});window.addEventListener('hashchange',self._hashChanged);self._hashChanged();},_hashChanged:function(self,event){var hash=document.location.hash;if(!hash||hash==='#'){document.location.hash='#/lebenslauf';}
var url=document.location.hash.substr(1);self.load(url);},});return new Router();});define('userprofile/scene',['statictext','bluebird','user','score.init','score.oop','score.dom.theater','../transitions/fade'],function(StaticText,BPromise,User,score){'use strict';return score.oop.Class({__name__:'BaseScene',__parent__:score.dom.theater.Scene,__events__:['createRactive'],__init__:function(self,stage,name){self.name=name;self.__super__(stage,name,score.dom('[data-component="'+name+'"]'));self.on('createRactive',self.onCreateRactive);},onCreateRactive:function(self){self.ractive.set('_user',User.get());User.on('logout',function(){self.ractive.set('_user',BPromise.resolve());});User.on('login',function(data){if(!data.user){return;}
self.ractive.set('_user',BPromise.resolve(data.user));self._loadData().then(function(result){self._setData(self.MODEL.name,result[self.MODEL.name]);});});StaticText.loadTexts(self.ractive,self.LOAD_STATIC_TEXTS);},_getRactive:function(self){if(self.ractive){return BPromise.resolve(self.ractive);}
return new BPromise(function(resolve,reject){require(['ractive','rv!rvtpl/userprofile/'+self.name,'ractive-promise-alt'],function(Ractive,template){Ractive.DEBUG=false;self.ractive=new Ractive({el:self.node,template:template,adapt:['promise-alt']});self.trigger('createRactive');resolve(self.ractive);});});},_loadData:function(self){return BPromise.resolve('create a _loadData() function in your Scene');}});});define('userprofile/scenes/application-for-employment',['userprofile/scene','user','score.init','score.oop','score.ajax.rest'],function(Scene,User,score){'use strict';return score.oop.Class({__name__:'ApplicationForEmploymentScene',__parent__:Scene,__static__:{MODEL:{'name':'jobapplication',}},onCreateRactive:function(self){self.__super__();},_load:function(self){return self._getRactive();},_activate:function(self){self.ractive.set(self.MODEL.name+'s',self._loadData());},_loadData:function(self){return score.ajax.rest.getJSON('rest/'+self.MODEL.name.toLowerCase()).then(function(result){return self._parse(result[self.MODEL.name+'s']);});},_parse:function(self,data){for(var i=0;i<data.length;i++){var d=new Date(data[i].datetime);data[i].datetime=d.getDate()+'.'+(d.getMonth()+1)+'.'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes();}
return data;}});});define('userprofile/scenes/coach',['bluebird','userprofile/scene','alertify','score.init','score.oop','score.ajax.rest'],function(BPromise,Scene,alertify,score){'use strict';return score.oop.Class({__name__:'CoachScene',__parent__:Scene,__static__:{MODEL:{'name':'student',},LOAD_STATIC_TEXTS:['student_mycoach_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}else{alertify.error('Du musst eine E-Mail Addresse angeben.');}});self.ractive.on('delete',function(event){self.delete(event);});self.ractive.on('revoke',function(event){self.revoke(event);});self.ractive.on('toggle_info',function(event){self.ractive.toggle('hideInfo');self.node.find('.button').toggleClass('button-active');});self.ractive.on('next',function(event){window.location.href='/';});},save:function(self,_event){self._confirmSave('Willst du wirklich deinen derzeitigen Coach entfernen und eine neue Einladung versenden?').then(function(data){var object=self.ractive.get(self.MODEL.name);_event.node.disabled=true;score.ajax.rest.postJSON('rest/userprofile/coach-add',object.email).then(function(data){self.ractive.set(self.MODEL.name,data);alertify.success('Die Einladung wurde erfolgreich verschickt.');}).catch(function(error){if(error.request.responseJSON&&error.request.responseJSON.message){alertify.error(error.request.responseJSON.message);return;}
alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});});},delete:function(self,_event){self._confirmDelete('Willst du wirklich deinen derzeitigen Coach entfernen?').then(function(data){_event.node.disabled=true;score.ajax.rest.deleteJSON('rest/userprofile/coach-delete').then(function(data){self.ractive.set(self.MODEL.name,data);alertify.success('Dein Coach wurde erfolgreich entfernt');}).catch(function(error){if(error.request.responseJSON&&error.request.responseJSON.message){alertify.error(error.request.responseJSON.message);return;}
alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});});},revoke:function(self,_event){_event.node.disabled=true;score.ajax.rest.deleteJSON('rest/userprofile/coach-delete').then(function(data){self.ractive.set(self.MODEL.name,data);alertify.success('Deine Anfrage wurde zurückgezogen.');}).catch(function(error){if(error.request.responseJSON&&error.request.responseJSON.message){alertify.error(error.request.responseJSON.message);return;}
alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');score.ajax.rest.postJSON('/rest/error',error.toString());}).finally(function(){_event.node.disabled=false;});},_confirmSave:function(self,message){return new BPromise(function(resolve,reject){var object=self.ractive.get(self.MODEL.name);if(object.student.coach){alertify.confirm(message,function(){resolve();},function(){reject();});}else{resolve();}});},_confirmDelete:function(self,message){return new BPromise(function(resolve,reject){alertify.confirm(message,function(){resolve();},function(){reject();});});},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data);});self._loadKeyVisual().then(function(data){self.ractive.set('keyvisual',data.keyvisual);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/userprofile/'+self.MODEL.name.toLowerCase());},_loadKeyVisual:function(self){return score.ajax.rest.getJSON('rest/userprofile/keyvisual/2');},_validate:function(self,data){return data&&data.email;},});});define('userprofile/scenes/documents',['bluebird','userprofile/scene','components/studentUpload','score.init','score.oop','score.ajax.rest'],function(BPromise,Scene,StudentUpload,score){'use strict';return score.oop.Class({__name__:'DocumentsScene',__parent__:Scene,__static__:{MODEL:{'name':'document',}},onCreateRactive:function(self){self.__super__();self.ractive.observe('upload',function(upload){self.ractive.set('uploadFile',{});var inputEl=self.node.find('input[type=file]');if(inputEl.length===1){inputEl[0].value='';}
if(!self.upload&&upload){self.upload=new StudentUpload(self.node.find('input[type=file]'),undefined,209715200,self._hasVideo());self.upload.on('change',function(files){self.ractive.set('uploadFile',files);});}});self.ractive.on('upload',function(event){self.ractive.set('uploadFile',{pending:true});self._upload(event.context).then(function(obj){self.ractive.set('uploadFile',{pending:false});self.ractive.push('documents.result',obj);self.upload.setDenyVideo(self._hasVideo());self.ractive.toggle('upload');});});self.ractive.on('delete',function(event){score.ajax.rest.delete('/rest/'+self.MODEL.name+'/'+event.context.id).then(function(deleted){if(!deleted){return;}
self.ractive.splice(self.MODEL.name+'s.result',event.index.key,1);if(self.upload){self.upload.setDenyVideo(self._hasVideo());}});});self.ractive.on('toggle-comment-active',function(event){self._toggleCommentActive(event);});},_toggleCommentActive:function(self,event){event.original.preventDefault();var commentNode=self.node.find('.comment');var buttonNode=self.node.find('button.comment__button')[0];commentNode.toggleClass('active');if(commentNode.hasClass('active')){buttonNode.innerHTML='Weniger anzeigen';window.scrollTo({top:0,behavior:"smooth"});}else{buttonNode.innerHTML='Mehr anzeigen';}},_load:function(self){return self._getRactive();},_activate:function(self){self.ractive.set('documents',self._loadData());},_hasVideo:function(self){var documents=self.ractive.get('documents');for(var i=0;i<documents.result.length;i++){if(documents.result[i].mimeType.indexOf('video')!==-1){return true;}}
return false;},_loadData:function(self){var url='rest/'+self.MODEL.name.toLowerCase();return score.ajax.rest.getJSON(url).then(function(data){for(var i=0;i<data.documents.length;i++){data.documents[i].uploadDateTime=new Date(data.documents[i].uploadDateTime);data.documents[i].isVideo=data.documents[i].mimeType.indexOf('video')!==-1;}
return data.documents;});},_upload:function(self,file){return score.ajax.rest.postJSON('/rest/document',file).then(function(data){self.upload.remove(file.uuid);return data.document;});},});});define('userprofile/scenes/favorites',['components/myfavorites','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest'],function(myFavorites,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'FavoritesScene',__parent__:Scene,onCreateRactive:function(self){myFavorites.on('remove',function(id){self._loadData().then(function(data){return self.ractive.set('favorites',data);});});self.ractive.on('removeFavorite',function(event){event.original.preventDefault();myFavorites.toggle(event.context.id);});},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){return self.ractive.set('favorites',data);});},_loadData:function(self){if(self.ractive){self.ractive.set('favorites',null);}
return myFavorites.get().then(function(data){for(var i=0;i<data.length;i++){data[i].isFavorite=true;}
return data;});}});});define('userprofile/scenes/inquiry',['alertify','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'InquiryScene',__parent__:Scene,__static__:{MODEL:{'name':'inquiry',},LOAD_STATIC_TEXTS:['student_inquiry_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('save',function(event){event.original.preventDefault();self.save(event);});self.ractive.on('check',function(event){var question=self.ractive.get(event.rootpath.split('.').slice(0,-2).join('.'));var count=0;for(var i=0;i<question.answers.length;i++){if(question.answers[i].checked){count++;}}
if(count>=question.maxChoices&&!self.ractive.get(event.rootpath).checked){event.original.preventDefault();alertify.error('Du hast bereits '+question.maxChoices+' Antworten ausgewählt.');}});self.ractive.on('toggle-comment-active',function(event){self._toggleCommentActive(event);});self.ractive.on('toggle_info',function(event){self.ractive.toggle('hideInfo');self.node.find('.button').toggleClass('button-active');});},_toggleCommentActive:function(self,event){event.original.preventDefault();var commentNode=self.node.find('.comment');var buttonNode=self.node.find('button.comment__button')[0];commentNode.toggleClass('active');if(commentNode.hasClass('active')){buttonNode.innerHTML='Weniger anzeigen';window.scrollTo({top:0,behavior:"smooth"});}else{buttonNode.innerHTML='Mehr anzeigen';}},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){alertify.maxLogItems(data[self.MODEL.name].questions.length);self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});self._loadKeyVisual().then(function(data){self.ractive.set('keyvisual',data.keyvisual);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/userprofile/'+self.MODEL.name.toLowerCase());},_loadKeyVisual:function(self){return score.ajax.rest.getJSON('rest/userprofile/keyvisual/0');},_validate:function(self){var valid=true;var questions=self.ractive.get(self.MODEL.name+'.questions');for(var i=0;i<questions.length;i++){var checkedAnswerCount=0;for(var j=0;j<questions[i].answers.length;j++){if(questions[i].answers[j].checked){checkedAnswerCount++;}}
if(checkedAnswerCount>questions[i].maxChoices){alertify.error('Du hast bei der '+(i+1)+'. Frage zu viel ausgewählt.');valid=false;}
if(checkedAnswerCount<questions[i].minChoices){alertify.error('Du hast bei der '+(i+1)+'. Frage zu wenig ausgewählt.');valid=false;}}
return valid;},save:function(self,_event){if(!self._validate()){return;}
var object=self.ractive.get(self.MODEL.name);_event.node.disabled=true;score.ajax.rest.putJSON('rest/userprofile/'+self.MODEL.name.toLowerCase(),object).then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);alertify.success('Deine Daten wurden gespeichert.');window.location.href='#/lebenslauf';}).catch(function(){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');}).finally(function(){_event.node.disabled=false;});}});});define('userprofile/scenes/intro',['swiper','alertify','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest','score.dom'],function(Swiper,alertify,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'IntroScene',__parent__:Scene,__static__:{MODEL:{'name':'intro',},LOAD_STATIC_TEXTS:['student_intro_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('next',function(event){window.location.href='#/erhebung';});self.ractive.on('clickSlide',function(event,url){window.location.href=url;});},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]).then(function(data){var swiper=new Swiper('.swiper-container',{nextButton:'.swiper-button-next',prevButton:'.swiper-button-prev',pagination:'.swiper-pagination',autoplay:5000,loopedSlides:3});});});},_loadData:function(self){return score.ajax.rest.getJSON('rest/userprofile/'+self.MODEL.name.toLowerCase());},});});define('userprofile/scenes/jobalarm',['alertify','components/form','components/myjobalarm','lodash','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest'],function(alertify,Form,JobAlarm,_,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'JobalarmScene',__parent__:Scene,__static__:{MODEL:{'name':'userjobalarm',}},onCreateRactive:function(self){self.__super__();self.ractive.on('submit',self._onSubmitHandler);self.ractive.on('cancelConfig',function(){self.ractive.set(self.MODEL.name,BPromise.resolve({keywords:'',location:'',employmentTypeIds:[],categoryIds:[],positionIds:[]}));});},_onSubmitHandler:function(self,event){event.original.preventDefault();var fdata=Form.serialize(self.node.find('#job-alarm-settings')[0]);var lists=['employmentTypes','positions','categories'];_.forEach(fdata,function(value,key){if(key.indexOf('Ids')>-1&&!_.isArray(value)){value=[value];}
self.ractive.set(self.MODEL.name+'.result.'+key,value);});var data=self.ractive.get(self.MODEL.name+'.result');_.forEach(lists,function(key){var idKey=(key==='categories')?'categoryIds':key.slice(0,-1)+'Ids';if(data[idKey]&&fdata[idKey]){data[key]=_.map(data[idKey],function(i){return{id:i}});}else{data[key]=[];}});var p=score.ajax.rest.postJSON('/rest/'+self.MODEL.name,data).then(function(data){alertify.success('Ihr Job-Alarm wurde gespeichert');return self._getData(data);}).caught(function(){alertify.error('Ihr Job-Alarm wurde nicht gespeichert');});self.ractive.set(self.MODEL.name,p);},_load:function(self){return self._getRactive();},_activate:function(self){self.ractive.set('userjobalarm',self._loadData());},_loadData:function(self){var url='rest/'+self.MODEL.name.toLowerCase();return score.ajax.rest.getJSON(url).then(function(data){return self._getData(data);});},_getData:function(self,data){data=data[self.MODEL.name];data.employmentTypeIds=_.map(data.employmentTypes,function(o){return o.id+'';});data.categoryIds=_.map(data.categories,function(o){return o.id+'';});data.positionIds=_.map(data.positions,function(o){return o.id+'';});return data;},_setData:function(self,key,value){console.log(key,value);return;},});});define('userprofile/scenes/letter-of-application',['alertify','bluebird','userprofile/scene','user','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Scene,User,score){'use strict';return score.oop.Class({__name__:'LetterOfApplicationScene',__parent__:Scene,__static__:{MODEL:{'name':'letterofapplication',}},onCreateRactive:function(self){self.__super__();self.ractive.on('restore',function(){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});});self.ractive.on('save',function(){self.save();});},_load:function(self){return self._getRactive();},_activate:function(self){alertify;self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/'+self.MODEL.name.toLowerCase());},save:function(self){if(self.saveTimeout){clearTimeout(self.saveTimeout);}
var object=self.ractive.get(self.MODEL.name);self.saveTimeout=setTimeout(function(){score.ajax.rest.postJSON('rest/'+self.MODEL.name.toLowerCase(),object).then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});},800);alertify.success('Ihr Bewerbungsschreiben wurde gespeichert.');},});});define('userprofile/scenes/message',['alertify','user','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest'],function(alertify,User,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'MessageScene',__parent__:Scene,__static__:{MODEL:{'name':'message',},LOAD_STATIC_TEXTS:['student_message_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('edit',function(event){if(event.context.isNew){self.setRead(event.context.id).then(function(data){window.location.href='#/nachrichten/'+event.context.id;});}else{window.location.href='#/nachrichten/'+event.context.id;}});self.ractive.on('new',function(event){self.ractive.set(self.MODEL.name,BPromise.resolve({id:null}));});self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(!event.context.id);}});self.ractive.on('delete',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.delete(event.context.id).then(function(data){self._updateMesssage(data.message);});});self.ractive.on('restore',function(event){event.original.stopPropagation();if(!event.context.isDeleted){return;}
self.restore(event.context.id).then(function(data){self._updateMesssage(data.message);});});self.ractive.on('mark-as-new',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setNew(event.context.id).then(function(data){self._updateMesssage(data.message);});});self.ractive.on('mark-as-read',function(event){event.original.stopPropagation();if(event.context.isDeleted){return;}
self.setRead(event.context.id).then(function(data){self._updateMesssage(data.message);});});self.ractive.on('back',function(event){window.location.href='#/nachrichten';});self.ractive.on('toggleIsBlacklisted',self._toggleIsBlacklisted);User.get().then(function(user){if(user){self.ractive.set('isBlacklisted',user.isBlacklisted);}});self.ractive.on('next',function(event){window.location.href='#/intro';});self.ractive.on('toggle_info',function(event){self.ractive.toggle('hideInfo');self.node.find('.button').toggleClass('button-active');});},_toggleIsBlacklisted:function(self,event){if(event!==undefined){event.original.preventDefault();if(event.context.isBlacklisted){var message='Wirklich keine Emails mehr erhalten?';}else{var message='Wirklich Emails aktivieren?';}
alertify.confirm(message,function(){self.ractive.toggle('isBlacklisted').then(function(result){event.node.checked=!self.ractive.get('isBlacklisted');score.ajax.rest.putJSON('rest/user',{'isBlacklisted':!event.node.checked}).then(function(result){alertify.success('Daten erfolgreich gespeichert.');});});},function(){});}},get:function(self,id){return self._loadData(id);},save:function(self,create){if(self.saveTimeout){clearTimeout(self.saveTimeout);}
var object=self.ractive.get(self.MODEL.name+'.result');if(!self._beforeSave(object)){return;}
self.saveTimeout=setTimeout(function(){if(self.savePromise){return;}
if(create){self.savePromise=score.ajax.rest.postJSON('rest/userprofile/'+self.MODEL.name.toLowerCase(),object);}else{self.savePromise=score.ajax.rest.putJSON('rest/userprofile/'+self.MODEL.name.toLowerCase()+'/'+object.id,object);}
self.ractive.set(self.MODEL.name,self.savePromise.then(function(data){alertify.success('erfolgreich gespeichert');self.savePromise=null;return data['message'];}).catch(function(error){alertify.error('Es ist ein Fehler aufgetreten');score.ajax.rest.postJSON('/rest/error',error.toString());}));},5);},delete:function(self,id){return self.setStatus(id,2);},restore:function(self,id){return self.setStatus(id,-1);},setRead:function(self,id){return self.setStatus(id,1);},setNew:function(self,id){return self.setStatus(id,0);},setStatus:function(self,id,status){return score.ajax.rest.putJSON('rest/userprofile/'+self.MODEL.name.toLowerCase()+'/'+id,{'status':status});},_updateMesssage:function(self,message){var messages=self.ractive.get('_data.result.messages');if(messages){var idx=_.findIndex(messages,{'id':message.id});self.ractive.set('_data.result.messages.'+idx,message);}
if(self.ractive.get(self.MODEL.name)){self.ractive.set(self.MODEL.name+'.result',message);}},_load:function(self,id){var ractive=self._getRactive();ractive.then(function(){if(id){self.ractive.set(self.MODEL.name,self._loadData(id).then(function(data){return data.message;}));self.ractive.update(self.MODEL.name+'.result');}else{self.ractive.set(self.MODEL.name);self.ractive.set('_data',self._loadData());}});return ractive;},_activate:function(self){self.ractive.set('_data',self._loadData());self._loadKeyVisual().then(function(data){self.ractive.set('keyvisual',data.keyvisual);});},_loadData:function(self,id){return score.ajax.rest.getJSON('rest/userprofile/'+self.MODEL.name.toLowerCase()+(id?'/'+id:''));},_loadKeyVisual:function(self){return score.ajax.rest.getJSON('rest/userprofile/keyvisual/3');},_validate:function(self,data){return data&&data.subject&&data.recipient},});});define('userprofile/scenes/newsletter',['alertify','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'NewsletterScene',__parent__:Scene,__static__:{MODEL:{'name':'newsletter',}},onCreateRactive:function(self){self.__super__();self.ractive.on('subscribe',function(event){self._confirmAction('Wollen Sie sich wirklich zum Newsletter anmelden?');});self.ractive.on('unsubscribe',function(event){self._confirmAction('Wollen Sie sich wirklich vom Newsletter abmelden?');});},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/usernewsletter');},save:function(self){if(self.saveTimeout){clearTimeout(self.saveTimeout);}
var object=self.ractive.get(self.MODEL.name);object.newsletter=!object.newsletter;self.saveTimeout=setTimeout(function(){score.ajax.rest.postJSON('rest/usernewsletter',object).then(function(data){if(data.redirectUrl){alertify.success('Sie werden weitergeleitet...');window.location.href=data.redirectUrl;}});},50);},_confirmAction:function(self,message){alertify.confirm(message,function(){self.save();},function(){});},});});define('userprofile/scenes/profilesettings',['userprofile/scene','alertify','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,score){'use strict';return score.oop.Class({__name__:'SetpasswordScene',__parent__:Scene,__static__:{MODEL:{'name':'user',},LOAD_STATIC_TEXTS:['student_settings_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('save',function(event){if(self._validate(event.context)){self.save(event);}else{alertify.error('Die eingegebenen Passwörter stimmten nicht überein.');}});self.ractive.on('delete',function(event){self.delete(event);});self.ractive.on('next',function(event){window.location.href='#/intro';});self.ractive.on('toggle_info',function(event){self.ractive.toggle('hideInfo');self.node.find('.button').toggleClass('button-active');});},save:function(self,_event){var object=self.ractive.get(self.MODEL.name);_event.node.disabled=true;score.ajax.rest.putJSON('rest/'+self.MODEL.name.toLowerCase(),object).then(function(data){self._beforeSetData(data[self.MODEL.name]);self.ractive.set(self.MODEL.name,data[self.MODEL.name]);alertify.success('Deine Daten wurden gespeichert.');}).catch(function(){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');}).finally(function(){_event.node.disabled=false;});},delete:function(self){self._confirmDelete('Bist du sicher, dass du dein Profil löschen möchtest?');},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});self._loadKeyVisual().then(function(data){self.ractive.set('keyvisual',data.keyvisual);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/'+self.MODEL.name.toLowerCase());},_loadKeyVisual:function(self){return score.ajax.rest.getJSON('rest/userprofile/keyvisual/4');},_validate:function(self,data){return data&&data.id&&data.password&&data.password2&&data.password===data.password2;},_beforeSetData:function(self,data){if(!data){return;}
delete data.password;delete data.password2;},_confirmDelete:function(self,message){alertify.confirm(message,function(){score.ajax.rest.deleteJSON('rest/'+self.MODEL.name.toLowerCase()+'?permanent=permanent').then(function(data){alertify.success("Profil wurde gelöscht");window.location.href='/';});},function(){});},});});define('userprofile/scenes/publish',['userprofile/scene','alertify','bluebird','score.init','score.oop','score.ajax.rest'],function(Scene,alertify,BPromise,score){'use strict';return score.oop.Class({__name__:'PublishScene',__parent__:Scene,__static__:{MODEL:{'name':'student',},LOAD_STATIC_TEXTS:['student_publishprofile_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('togglePublished',self._togglePublished);},_togglePublished:function(self,event){if(event!==undefined){event.original.preventDefault();if(event.context.student.student.profilePublished){var message='Wirklich nicht mehr veröffentlichen?';}else{var message='Wirklich veröffentlichen?';}
alertify.confirm(message,function(){self.ractive.toggle('student.student.profilePublished').then(function(result){event.node.checked=event.context.student.student.profilePublished;score.ajax.rest.putJSON('rest/userprofile/'+self.MODEL.name.toLowerCase(),self.ractive.get('student.student')).then(function(result){alertify.success('Daten erfolgreich gespeichert.');});});},function(){});}},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/userprofile/'+self.MODEL.name.toLowerCase());},});});define('userprofile/scenes/resume',['bluebird','userprofile/scene','alertify','score.init','score.oop','score.ajax.rest'],function(BPromise,Scene,alertify,score){'use strict';return score.oop.Class({__name__:'ResumeScene',__parent__:Scene,__static__:{MODEL:{'name':'resume',},LOAD_STATIC_TEXTS:['student_resume_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('showIfNotFilledOut',function(event){if(self.ractive.get('resume.user.isProfileFilledOut')){return;}
var html='<h4>Bitte vervollständigen Sie zunächst Ihr Profil!</h4><div class="msg">benötigt wird noch:<ul>';if(!self.ractive.get('resume.contact.firstName')){html+='<li>Vorname</li>';}
if(!self.ractive.get('resume.contact.lastName')){html+='<li>Nachname</li>';}
if(!self.ractive.get('resume.contact.email')){html+='<li>Email</li>';}
if(!self.ractive.get('resume.user.street')){html+='<li>Strasse</li>';}
if(!self.ractive.get('resume.user.postalCode')){html+='<li>Postleitzahl</li>';}
if(!self.ractive.get('resume.user.city')){html+='<li>Stadt/Ort</li>';}
if(!self.ractive.get('resume.contact.phone')){html+='<li>Telefonnummer</li>';}
if(!self.ractive.get('resume.user.birthdate')){html+='<li>Geburtstag</li>';}
if(!self.ractive.get('resume.qualifications').length){html+='<li>Schul- und Berufsbildung</li>';}
if(!self.ractive.get('resume.nativeLanguages').length){html+='<li>Muttersprache(n)</li>';}
html+='</ul></div>';alertify.alert(html);});self.ractive.on('edit',function(event,keypath){var current=self.ractive.get('edit'+keypath);if(current!==event.index.key){return self.ractive.set('edit'+keypath,event.index.key);}
self.ractive.set('edit'+keypath,null);if(event.context.toDate||event.context.fromDate){if(keypath=='.experiences'){if(typeof event.context.title=='undefined'){event.context.title=""}}
else if(keypath=='.qualifications'){if(typeof event.context.title=='undefined'){event.context.title=""}
if(typeof event.context.subject=='undefined'){event.context.subject=""}
if(typeof event.context.schoolType=='undefined'){event.context.schoolType=""}
if(typeof event.context.institution=='undefined'){event.context.institution=""}
if(typeof event.context.school=='undefined'){event.context.school=""}}
var data;data=self._parseFromToDate(event.context);self.ractive.set(event.keypath,data);if(!data.from){return self.ractive.splice(self.MODEL.name+keypath,event.index.key,1).then(function(spliced){if(spliced[0]&&spliced[0].id){self.save();}});}
self.ractive.set(self.MODEL.name+keypath,_.reverse(_.sortBy(self.ractive.get(self.MODEL.name+keypath),'from'))).then(function(){self.save();});}
self.save();});self.ractive.observe('resume.contact.firstName',function(after,before){var firstName=self.ractive.get('resume.user.firstName');if(after){firstName=after;}
self.ractive.set('resume.contact.firstName',firstName);self.ractive.set('resume.user.firstName',firstName);});self.ractive.observe('resume.contact.lastName',function(after,before){var lastName=self.ractive.get('resume.user.lastName');if(after){lastName=after;}
self.ractive.set('resume.contact.lastName',lastName);self.ractive.set('resume.user.lastName',lastName);});self.ractive.observe('resume.user.birthday',function(bday,before){if(bday&&bday.day&&bday.month&&bday.year){var d=bday.day
if(d<10){d='0'+d;}
var m=bday.month
if(m<10){m='0'+m;}
var date=new Date(bday.year+'-'+m+'-'+d);self.ractive.set('resume.user.birthdate',date.getTime()/ 1000);}else{self.ractive.set('resume.user.birthdate',null);}});self.ractive.observe('edit.drivingLicence',function(edit,before){if(edit==true){self._loadCheckboxItems('drivingLicence','drivingLicenceCategory');}
else if(before&&edit==false){self._setCheckedItems('drivingLicence');self.save();}});self.ractive.observe('edit.msOfficeSkills',function(edit,before){if(edit==true){self._loadCheckboxItems('msOfficeSkills','msOfficeSkill');}
else if(before&&edit==false){self._setCheckedItems('msOfficeSkills');self.save();}});_.forEach(['contact','nativeLanguages','communicationSkill','organisationalSkill','digitalSkill','languageSkills','training','trainings','driverLicence','hobbies','itSkills','msOfficeSkills','certificates','interests'],function(member){self.ractive.observe('edit.'+member,function(edit,before){if(before&&!edit){self.save();}});});self.ractive.on('add',function(event,keypath){self.ractive.unshift(self.MODEL.name+keypath,{});self.ractive.set('edit'+keypath,0);});self._registerSearch('category',null,'id');self._registerSearch('position',null,'id');self._registerSearch('employmentType',null,'id');self._registerSearch('nativeLanguages','language','id');self._registerSearch('language',null,'id');self._registerSearch('trainings','training','name',0);self._registerSearch('title',null,null,0);self._registerSearch('subject',null,null,0);self._registerSearch('schoolType',null,null,0);self._registerSearch('institution',null,null,0);self._registerSearch('school',null,null,0);self._registerSearch('nationality',null,null,0);self._registerSearch('worktitle',null,null,0);self.ractive.on('append',function(event,keyPath){self.ractive.set('search'+keyPath+'.value',null);self.ractive.push(self.MODEL.name+keyPath,event.context);self.ractive.update(self.MODEL.name);});self.ractive.on('input-append',function(event,keyPath){var value=self.ractive.get('inputval'+keyPath+'.value');self.ractive.set('inputval'+keyPath+'.value',null);if(!value||!value.trim()){return;}
self.ractive.push(self.MODEL.name+keyPath,value.trim());self.ractive.update(self.MODEL.name);});self.ractive.on('append_new_entry',function(event,keyPath,is_li_tag){if((event.original.keyCode==13)||(is_li_tag==true)){if(is_li_tag){var value=event.node.textContent;}
else{var value=event.node.value;}
var current_items=self.ractive.get(self.MODEL.name+keyPath);self.ractive.set('search'+keyPath+'.value',null);if(!value||!value.trim()||current_items.indexOf(value)!=-1){return;}
self.ractive.push(self.MODEL.name+keyPath,value.trim());self.ractive.update(self.MODEL.name);}});self.ractive.on('set_new_entry',function(event,keyPath,is_li_tag){if(event.original.keyCode==13||is_li_tag==true||(event.original.type=='blur'&&self.ractive.get('search'+keyPath+'.result.result')&&!self.ractive.get('search'+keyPath+'.result.result').length)){if(is_li_tag){var value=event.node.textContent;}
else{var value=event.node.value;}
if(!value||!value.trim()){return;}
self.ractive.set('search'+keyPath+'.value',null);self.ractive.set('search'+keyPath+'.result',null);if(keyPath=='.worktitle'){keyPath='.title';}
console.log(value);self.ractive.set(event.keypath+keyPath,value.trim());if(keyPath=='.subject'){self.ractive.set(event.keypath+'.schoolType',value.trim());}
if(keyPath=='.schoolType'){self.ractive.set(event.keypath+'.subject',value.trim());}
if(keyPath=='.institution'){self.ractive.set(event.keypath+'.school',value.trim());}
if(keyPath=='.school'){self.ractive.set(event.keypath+'.institution',value.trim());}}});self.ractive.on('append_string',function(event,keyPath){self.ractive.set('search'+keyPath+'.value',null);self.ractive.push(self.MODEL.name+keyPath,event.context.name);self.ractive.update(self.MODEL.name);});self.ractive.on('remove',function(event,keyPath){if(self.ractive.get(self.MODEL.name).isDeleted){return;}
self.ractive.splice(self.MODEL.name+keyPath,event.index.key,1);self.ractive.update(self.MODEL.name);if(keyPath==='.languageSkills'){self.save();}});self.ractive.on('set',function(event,keyPath){if(keyPath==='.category'||keyPath==='.position'||keyPath==='.employmentType'){self.ractive.set(self.MODEL.name+'.experiences.'+event.index.key+keyPath,event.context);}else if(keyPath==='.worktitle'){self.ractive.set(self.MODEL.name+'.experiences.'+event.index.key+'.title',event.context.name);}else if(keyPath==='.language'){self.ractive.set(self.MODEL.name+'.languageSkills.'+event.index.key+keyPath,event.context);}else if(keyPath==='.title'||keyPath==='.subject'||keyPath==='.schoolType'||keyPath==='.institution'||keyPath==='.school'){self.ractive.set(self.MODEL.name+'.qualifications.'+event.index.key+keyPath,event.context.name);if(keyPath=='.subject'){self.ractive.set(self.MODEL.name+'.qualifications.'+event.index.key+'.schoolType',event.context.name);}
if(keyPath=='.schoolType'){self.ractive.set(self.MODEL.name+'.qualifications.'+event.index.key+'.subject',event.context.name);}
if(keyPath=='.institution'){self.ractive.set(self.MODEL.name+'.qualifications.'+event.index.key+'.school',event.context.name);}
if(keyPath=='.school'){self.ractive.set(self.MODEL.name+'.qualifications.'+event.index.key+'.institution',event.context.name);}}else if(keyPath==='.nationality'){self.ractive.set(self.MODEL.name+'.user'+keyPath,event.context.name);}else{self.ractive.set(self.MODEL.name+keyPath,event.context);}
self.ractive.set('search'+keyPath,null);});self.ractive.on('unset',function(event,subItem){if(subItem){self.ractive.set(event.keypath+subItem,"");if(subItem=='.subject'){self.ractive.set(event.keypath+'.schoolType',"");}
if(subItem=='.schoolType'){self.ractive.set(event.keypath+'.subject',"");}
if(subItem=='.institution'){self.ractive.set(event.keypath+'.school',"");}
if(subItem=='.school'){self.ractive.set(event.keypath+'.institution',"");}}
else{self.ractive.set(event.keypath,null);}
if((event.index.key||event.index.key===0)&&(event.keypath===self.MODEL.name+'.languageSkills.'+event.index.key+'.language')){self.ractive.splice(self.MODEL.name+'.languageSkills',event.index.key,1);self.ractive.update(self.MODEL.name);self.ractive.set('edit',null);return self.save();}});self.ractive.on('contact-picture-upload',function(event){require(['contact-picture-upload'],function(ContactPictureUpload){ContactPictureUpload.show().then(function(data){self.ractive.set(self.MODEL.name+'.contact.image',data);self.save();});})});self.ractive.on('hide',function(event){if(event.index.key===0&&(event.keypath.indexOf('qualifications')>=0||event.keypath.indexOf('experiences')>=0)&&(!event.context.fromDate.month||!event.context.fromDate.year)){self.ractive.splice(event.keypath.replace('.0',''),0,1);self.ractive.update(self.MODEL.name);}
self.ractive.set('edit',null);});self.ractive.on('deactivate-account',function(event){alertify.cancelBtn('Abbrechen').okBtn('OK').confirm('Willst Du deinen Account wirklich deaktivieren? Danach ist es dir nicht mehr möglich den Account selbst zu reaktivieren oder die E-Mail-Adresse für einen neuen Account zu verwenden!',function(){score.ajax.rest.deleteJSON('rest/user').then(function(data){if(!data){return;}
alertify.success('Dein Account wurde erfolgreich deaktiviert. Du wirst nun ausgeloggt.');setTimeout(function(){window.location.href='/logout';},5000);});},function(){});});self.ractive.on('save',function(event){return self.save(event);});self.ractive.on('release-resume',function(event){self.save(event);if(self.ractive.get(self.MODEL.name).user.hasAcceptedDsgvo!==true){alertify.alert('Du hast der DSGVO noch nicht zugestimmt. Du kannst das Formular dazu '+'<a href="/images/documents/Zustimmungserklärung%20Initiative%20meinersterjob.pdf" target="_blank">hier downloaden.</a>');}else{score.ajax.rest.postJSON('rest/meinersterjob/release-resume').then(function(){alertify.success('Deine Anfrage wurde erfolgreich verschickt.');});}});self.ractive.on('toggle-comment-active',function(event){self._toggleCommentActive(event);});self.ractive.on('request-coach-feedback',function(event){self._requestCoachFeedback(event);});self.ractive.on('toggle_info',function(event){self.ractive.toggle('hideInfo');self.node.find('.button').toggleClass('button-active');});self.ractive.on('next',function(event){window.location.href='#/coach';});},_requestCoachFeedback:function(self,event){score.ajax.rest.postJSON('rest/userprofile/coach-feedback').then(function(data){alertify.success('E-Mail erfolgreich gesendet.');});},_toggleCommentActive:function(self,event){event.original.preventDefault();var commentNode=self.node.find('.comment');var buttonNode=self.node.find('button.comment__button')[0];commentNode.toggleClass('active');if(commentNode.hasClass('active')){buttonNode.innerHTML='Weniger anzeigen';window.scrollTo({top:0,behavior:"smooth"});}else{buttonNode.innerHTML='Mehr anzeigen';}},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(result){self._setData(self.MODEL.name,result[self.MODEL.name]);});self._loadKeyVisual().then(function(data){self.ractive.set('keyvisual',data.keyvisual);});},_loadData:function(self){var url='rest/'+self.MODEL.name.toLowerCase();self.loadPromise=score.ajax.rest.getJSON(url).then(function(data){var userData=self.ractive.get('_user.result');if(userData&&!data.resume.contact){data.resume.contact={};if(userData.email){data.resume.contact.email=userData.email;}
if(userData.firstName){data.resume.contact.firstName=userData.firstName;}
if(userData.lastName){data.resume.contact.lastName=userData.lastName;}}
return data;});return self.loadPromise;},_loadKeyVisual:function(self){return score.ajax.rest.getJSON('rest/userprofile/keyvisual/1');},_loadCheckboxItems:function(self,type,singleType){var checkBoxItems=self.ractive.get('selected.'+type)||[];var ids=_.map(self.ractive.get(self.MODEL.name+'.'+type),'id');if(!checkBoxItems.length){self._loadSearchData(singleType?singleType.toLowerCase():type.toLowerCase()).then(function(data){var arrInitialized=[];data.results.forEach(function(object){arrInitialized.push({'data':object,'checked':(ids.indexOf(object.id)>-1)?true:false});});self.ractive.set('selected.'+type,arrInitialized);});}
else{checkBoxItems.forEach(function(object){object.checked=(ids.indexOf(object.data.id)>-1)?true:false;});self.ractive.set('selected.'+type,checkBoxItems);}},_setCheckedItems:function(self,type){var checkBoxItems=self.ractive.get('selected.'+type)||[];var selectedItems=_.filter(checkBoxItems,function(object){return object.checked;});self.ractive.set(self.MODEL.name+'.'+type,_.map(selectedItems,'data'));},save:function(self,_event){if(_event){_event.node.disabled=true;}
var object=self.ractive.get(self.MODEL.name);score.ajax.rest.postJSON('rest/'+self.MODEL.name.toLowerCase(),object).then(function(data){self._setData(self.MODEL.name,data[self.MODEL.name]);}).finally(function(){if(_event){_event.node.disabled=false;}});},_setData:function(self,key,value){self._beforeSetData(key,value);self.ractive.set(key,value);},_beforeSetData:function(self,key,value){if(key!==self.MODEL.name){return;}
if(!value){return;}
if(!value.contact){value.contact={}}
if(value.user&&value.user.birthdate){var d=new Date(value.user.birthdate);value.user.birthday={day:d.getDate(),month:d.getMonth()+1,year:d.getFullYear()}}
for(var i=0;i<value.experiences.length;i++){if(value.experiences[i].from){value.experiences[i].from=new Date(value.experiences[i].from);value.experiences[i].fromDate=self._createEditDateObject(value.experiences[i].from);}
if(value.experiences[i].to){value.experiences[i].to=new Date(value.experiences[i].to);value.experiences[i].toDate=self._createEditDateObject(value.experiences[i].to);}}
for(var i=0;i<value.qualifications.length;i++){if(value.qualifications[i].from){value.qualifications[i].from=new Date(value.qualifications[i].from);value.qualifications[i].fromDate=self._createEditDateObject(value.qualifications[i].from);}
if(value.qualifications[i].to){value.qualifications[i].to=new Date(value.qualifications[i].to);value.qualifications[i].toDate=self._createEditDateObject(value.qualifications[i].to);}}},_createEditDateObject:function(self,date){return{month:date.getMonth()+1,year:date.getFullYear()}},_parseFromToDate:function(self,data){if(data&&data.fromDate&&data.fromDate.month&&data.fromDate.year){var date=new Date();date.setFullYear(parseInt(data.fromDate.year));date.setDate(1);date.setMonth(parseInt(data.fromDate.month)-1);data.from=date;}else{data.from=null;delete(data.fromDate);}
if(data&&data.toDate&&data.toDate.month&&data.toDate.year){var date=new Date();date.setFullYear(parseInt(data.toDate.year));date.setDate(1);date.setMonth(parseInt(data.toDate.month)-1);data.to=date;}else{data.to=null;delete(data.toDate);}
return data;},_registerSearch:function(self,type,singleType,key,min_length){self.ractive.observe('search.'+type+'.value',function(newValue,oldValue){if(newValue){self._search(type,newValue,singleType,key,min_length);}else{self.ractive.set('search.'+type+'.result',newValue);}});},_search:function(self,type,search,singleType,key,min_length){if(self.searchTimeout){clearTimeout(self.searchTimeout);}
var searchData=self.ractive.get('search.'+type+'.data')||[];var promise;if(!searchData.length){promise=new BPromise(function(resolve){self.searchTimeout=setTimeout(function(){self._loadSearchData(singleType?singleType.toLowerCase():type.toLowerCase()).then(function(data){self.ractive.set('search.'+type+'.data',data.results);return resolve(data.results);});},600);});}else{promise=BPromise.resolve(searchData);}
min_length=(typeof min_length!=='undefined')?min_length:0;if(search.length>min_length){var p=promise.then(function(data){if(key=='name'){var names=self.ractive.get(self.MODEL.name+'.'+type);return _.filter(data,function(object){return names.indexOf(object.name)===-1;});}
else if(key=='id'){var ids=_.map(self.ractive.get(self.MODEL.name+'.'+type),'id');return _.filter(data,function(object){return ids.indexOf(object.id)===-1;});}
else{return data;}}).then(function(data){if(search==='*'){return data;}
search=search.toLowerCase();return _.filter(data,function(object){for(var key in object){var value=object[key];if(typeof value==='number'){value+='';}
if(typeof value==='string'&&value.toLowerCase().indexOf(search)>=0){return true;}}});});self.ractive.set('search.'+type+'.result',p);}},_loadSearchData:function(self,resource){return score.ajax.rest.getJSON('rest/'+resource+'?q=1');},_getRactive:function(self){return self.__super__();},});});define('userprofile/scenes/student-data',['alertify','bluebird','userprofile/scene','score.init','score.oop','score.ajax.rest'],function(alertify,BPromise,Scene,score){'use strict';return score.oop.Class({__name__:'StudentDataScene',__parent__:Scene,__static__:{MODEL:{'name':'student',},LOAD_STATIC_TEXTS:['student_studentdata_description'],},onCreateRactive:function(self){self.__super__();self.ractive.on('save',function(event){self.save(event);});self.ractive.on('toggle-comment-active',function(event){self._toggleCommentActive(event);});self.ractive.on('request-coach-feedback',function(event){self._requestCoachFeedback(event);});self.ractive.on('toggle_info',function(event){self.ractive.toggle('hideInfo');self.node.find('.button').toggleClass('button-active');});},_requestCoachFeedback:function(self,event){score.ajax.rest.postJSON('rest/userprofile/coach-feedback').then(function(data){alertify.success('E-Mail erfolgreich gesendet.');});},_toggleCommentActive:function(self,event){event.original.preventDefault();var commentNode=self.node.find('.comment');var buttonNode=self.node.find('button.comment__button')[0];commentNode.toggleClass('active');if(commentNode.hasClass('active')){buttonNode.innerHTML='Weniger anzeigen';window.scrollTo({top:0,behavior:"smooth"});}else{buttonNode.innerHTML='Mehr anzeigen';}},_load:function(self){return self._getRactive();},_activate:function(self){self._loadData().then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);});},_loadData:function(self){return score.ajax.rest.getJSON('rest/userprofile/'+self.MODEL.name.toLowerCase());},_validate:function(self){var object=self.ractive.get(self.MODEL.name);if(!object.user.firstName){alertify.error('Vorname darf nicht leer sein');return false;}
if(!object.user.lastName){alertify.error('Nachname darf nicht leer sein');return false;}
return true;},save:function(self,_event){var object=self.ractive.get(self.MODEL.name);if(!self._validate()){return;}
_event.node.disabled=true;score.ajax.rest.putJSON('rest/userprofile/'+self.MODEL.name.toLowerCase(),object).then(function(data){self.ractive.set(self.MODEL.name,data[self.MODEL.name]);alertify.success('Deine Daten wurden gespeichert.');}).catch(function(){alertify.error('Es ist ein unerwarteter Fehler aufgetreten.');}).finally(function(){_event.node.disabled=false;});},});});define('userprofile/stage',['userprofile/scenes/resume','userprofile/scenes/jobalarm','userprofile/scenes/letter-of-application','userprofile/scenes/favorites','userprofile/scenes/application-for-employment','userprofile/scenes/documents','userprofile/scenes/newsletter','score.init','score.dom.theater'],function(ResumeScene,JobalarmScene,LetterOfApplicationScene,FavoritesScene,ApplicationForEmploymentScene,DocumentsScene,NewsletterScene,score){'use strict';var stage=new score.dom.theater.Stage(score.dom('#stage'));new ResumeScene(stage,'resume');new JobalarmScene(stage,'jobalarm');new LetterOfApplicationScene(stage,'letter-of-application');new FavoritesScene(stage,'favorites');new ApplicationForEmploymentScene(stage,'application-for-employment');new DocumentsScene(stage,'documents');new NewsletterScene(stage,'newsletter');return stage;});define('meinersterjob-header',['components/myfavorites','user','score.init','score.oop','score.dom'],function(myFavorites,User,score){'use strict';return score.oop.Class({__name__:'Header',__init__:function(self){self.node=score.dom('#header');self.favButton=self.node.find('.favorites');self.userMenu=self.node.find('.usermenu');self.profileButtonStudent=self.node.find('.profile');self.profileButtonCoach=self.node.find('.coach');self.profileButtonClient=self.node.find('.client');self.jobSearchStudent=self.node.find('.jobsearch');self.logoutButton=self.node.find('.logout');myFavorites.on('add',function(){self.favButton[0].setAttribute('data-count',myFavorites.count());});myFavorites.on('remove',function(){self.favButton[0].setAttribute('data-count',myFavorites.count());});User.on('login',self._showUserMenu);User.on('logout',self._hideUserMenu);User.get();self.mobileNavigationButton=self.node.find('.header__button-mobile-navigation');self.mobileNavigationButton[0].addEventListener('click',self._toggleMobileNavigation);self.menuContainer=self.node.find('.header__menu-container');document.addEventListener('click',self._globalClickHandler);},_showUserMenu:function(self,user){self.logoutButton.addClass('active');if(user){if(user.coach){self.profileButtonCoach.addClass('active');}else if(user.client){self.profileButtonClient.addClass('active');}else{self.profileButtonStudent.addClass('active');self.jobSearchStudent.addClass('active');}}},_hideUserMenu:function(self){self.logoutButton.removeClass('active');self.profileButtonStudent.removeClass('active');self.profileButtonCoach.removeClass('active');self.profileButtonClient.removeClass('active');self.jobSearchStudent.removeClass('active');},_toggleUserMenu:function(self,event){event.preventDefault();self.userMenu.toggleClass('active');},_toggleMobileNavigation:function(self,event){event.preventDefault();self.mobileNavigationButton.toggleClass('active');self.menuContainer.toggleClass('active');},_globalClickHandler:function(self,event){if(event.target!==self.mobileNavigationButton[0]&&!self.mobileNavigationButton[0].contains(event.target)&&self.menuContainer.hasClass('active')&&!self.menuContainer[0].contains(event.target)){self.menuContainer.removeClass('active');self.mobileNavigationButton.removeClass('active');}}})();});define('meinersterjob-login',['score.init','score.oop','score.dom'],function(score){'use strict';return score.oop.Class({__name__:'MeinersterjobLogin',__init__:function(self){self.node=score.dom('#participant-login');self.node.find('.student-login')[0].addEventListener('click',function(event){event.preventDefault();require(['components/overlay'],function(Overlay){Overlay.scenes['login'].node.find("p.not-yet-registered")[0].style.display="";Overlay.scenes['login'].setIsStudent(true);Overlay.show('login');});});self.node.find('.client-login')[0].addEventListener('click',function(event){event.preventDefault();window.location.href='/arbeitgeber/login';});},})();});define('slider/slider',['swiper','score.init','score.oop','score.dom'],function(Swiper,score){return score.oop.Class({__name__:'SlideShow',__init__:function(self,node){self.node=node;var Slider=node[0];self.swiper=new Swiper(Slider,{nextButton:'.swiper-button-next',prevButton:'.swiper-button-prev',pagination:'.swiper-pagination',loop:true,autoplay:5000});}});});