Update requirejs to 2.0.6
Update requirejs to 2.0.6

/* /*
RequireJS 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. RequireJS 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license. Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details see: http://github.com/jrburke/requirejs for details
*/ */
var requirejs,require,define; var requirejs,require,define;
(function(){function J(a){return M.call(a)==="[object Function]"}function E(a){return M.call(a)==="[object Array]"}function Z(a,c,h){for(var k in c)if(!(k in K)&&(!(k in a)||h))a[k]=c[k];return d}function N(a,c,d){a=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+a);if(d)a.originalError=d;return a}function $(a,c,d){var k,j,q;for(k=0;q=c[k];k++){q=typeof q==="string"?{name:q}:q;j=q.location;if(d&&(!j||j.indexOf("/")!==0&&j.indexOf(":")===-1))j=d+"/"+(j||q.name);a[q.name]={name:q.name,location:j|| (function(Z){function x(b){return J.call(b)==="[object Function]"}function E(b){return J.call(b)==="[object Array]"}function o(b,e){if(b){var f;for(f=0;f<b.length;f+=1)if(b[f]&&e(b[f],f,b))break}}function M(b,e){if(b){var f;for(f=b.length-1;f>-1;f-=1)if(b[f]&&e(b[f],f,b))break}}function y(b,e){for(var f in b)if(b.hasOwnProperty(f)&&e(b[f],f))break}function N(b,e,f,h){e&&y(e,function(e,j){if(f||!F.call(b,j))h&&typeof e!=="string"?(b[j]||(b[j]={}),N(b[j],e,f,h)):b[j]=e});return b}function t(b,e){return function(){return e.apply(b,
q.name,main:(q.main||"main").replace(ea,"").replace(aa,"")}}}function V(a,c){a.holdReady?a.holdReady(c):c?a.readyWait+=1:a.ready(!0)}function fa(a){function c(b,l){var f,a;if(b&&b.charAt(0)===".")if(l){p.pkgs[l]?l=[l]:(l=l.split("/"),l=l.slice(0,l.length-1));f=b=l.concat(b.split("/"));var c;for(a=0;c=f[a];a++)if(c===".")f.splice(a,1),a-=1;else if(c==="..")if(a===1&&(f[2]===".."||f[0]===".."))break;else a>0&&(f.splice(a-1,2),a-=2);a=p.pkgs[f=b[0]];b=b.join("/");a&&b===f+"/"+a.main&&(b=f)}else b.indexOf("./")=== arguments)}}function $(b){if(!b)return b;var e=Z;o(b.split("."),function(b){e=e[b]});return e}function aa(b,e,f){return function(){var h=ga.call(arguments,0),c;if(f&&x(c=h[h.length-1]))c.__requireJsBuild=!0;h.push(e);return b.apply(null,h)}}function ba(b,e,f){o([["toUrl"],["undef"],["defined","requireDefined"],["specified","requireSpecified"]],function(h){var c=h[1]||h[0];b[h[0]]=e?aa(e[c],f):function(){var b=z[O];return b[c].apply(b,arguments)}})}function G(b,e,f,h){e=Error(e+"\nhttp://requirejs.org/docs/errors.html#"+
0&&(b=b.substring(2));return b}function h(b,l){var f=b?b.indexOf("!"):-1,a=null,d=l?l.name:null,i=b,e,h;f!==-1&&(a=b.substring(0,f),b=b.substring(f+1,b.length));a&&(a=c(a,d));b&&(a?e=(f=m[a])&&f.normalize?f.normalize(b,function(b){return c(b,d)}):c(b,d):(e=c(b,d),h=E[e],h||(h=g.nameToUrl(e,null,l),E[e]=h)));return{prefix:a,name:e,parentMap:l,url:h,originalName:i,fullName:a?a+"!"+(e||""):e}}function k(){var b=!0,l=p.priorityWait,f,a;if(l){for(a=0;f=l[a];a++)if(!s[f]){b=!1;break}b&&delete p.priorityWait}return b} b);e.requireType=b;e.requireModules=h;if(f)e.originalError=f;return e}function ha(){if(H&&H.readyState==="interactive")return H;M(document.getElementsByTagName("script"),function(b){if(b.readyState==="interactive")return H=b});return H}var j,p,u,B,s,C,H,I,ca,da,ia=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ja=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/\.js$/,ka=/^\.\//;p=Object.prototype;var J=p.toString,F=p.hasOwnProperty;p=Array.prototype;var ga=p.slice,la=p.splice,w=!!(typeof window!==
function j(b,l,f){return function(){var a=ga.call(arguments,0),c;if(f&&J(c=a[a.length-1]))c.__requireJsBuild=!0;a.push(l);return b.apply(null,a)}}function q(b,l){var a=j(g.require,b,l);Z(a,{nameToUrl:j(g.nameToUrl,b),toUrl:j(g.toUrl,b),defined:j(g.requireDefined,b),specified:j(g.requireSpecified,b),isBrowser:d.isBrowser});return a}function o(b){var l,a,c,C=b.callback,i=b.map,e=i.fullName,ba=b.deps;c=b.listeners;if(C&&J(C)){if(p.catchError.define)try{a=d.execCb(e,b.callback,ba,m[e])}catch(k){l=k}else a= "undefined"&&navigator&&document),fa=!w&&typeof importScripts!=="undefined",ma=w&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,O="_",S=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",z={},r={},P=[],K=!1;if(typeof define==="undefined"){if(typeof requirejs!=="undefined"){if(x(requirejs))return;r=requirejs;requirejs=void 0}typeof require!=="undefined"&&!x(require)&&(r=require,require=void 0);j=requirejs=function(b,e,f,h){var c,o=O;!E(b)&&typeof b!=="string"&&
d.execCb(e,b.callback,ba,m[e]);if(e)(C=b.cjsModule)&&C.exports!==void 0&&C.exports!==m[e]?a=m[e]=b.cjsModule.exports:a===void 0&&b.usingExports?a=m[e]:(m[e]=a,F[e]&&(Q[e]=!0))}else e&&(a=m[e]=C,F[e]&&(Q[e]=!0));if(D[b.id])delete D[b.id],b.isDone=!0,g.waitCount-=1,g.waitCount===0&&(I=[]);delete R[e];if(d.onResourceLoad&&!b.placeholder)d.onResourceLoad(g,i,b.depArray);if(l)return a=(e?h(e).url:"")||l.fileName||l.sourceURL,c=l.moduleTree,l=N("defineerror",'Error evaluating module "'+e+'" at location "'+ (c=b,E(e)?(b=e,e=f,f=h):b=[]);if(c&&c.context)o=c.context;(h=z[o])||(h=z[o]=j.s.newContext(o));c&&h.configure(c);return h.require(b,e,f)};j.config=function(b){return j(b)};require||(require=j);j.version="2.0.6";j.jsExtRegExp=/^\/|:|\?|\.js$/;j.isBrowser=w;p=j.s={contexts:z,newContext:function(b){function e(a,d,k){var l,b,i,v,e,c,f,g=d&&d.split("/");l=g;var h=m.map,j=h&&h["*"];if(a&&a.charAt(0)===".")if(d){l=m.pkgs[d]?g=[d]:g.slice(0,g.length-1);d=a=l.concat(a.split("/"));for(l=0;d[l];l+=1)if(b=d[l],
a+'":\n'+l+"\nfileName:"+a+"\nlineNumber: "+(l.lineNumber||l.line),l),l.moduleName=e,l.moduleTree=c,d.onError(l);for(l=0;C=c[l];l++)C(a)}function r(b,a){return function(f){b.depDone[a]||(b.depDone[a]=!0,b.deps[a]=f,b.depCount-=1,b.depCount||o(b))}}function u(b,a){var f=a.map,c=f.fullName,h=f.name,i=L[b]||(L[b]=m[b]),e;if(!a.loading)a.loading=!0,e=function(b){a.callback=function(){return b};o(a);s[a.id]=!0;w()},e.fromText=function(b,a){var l=O;s[b]=!1;g.scriptCount+=1;g.fake[b]=!0;l&&(O=!1);d.exec(a); b===".")d.splice(l,1),l-=1;else if(b==="..")if(l===1&&(d[2]===".."||d[0]===".."))break;else l>0&&(d.splice(l-1,2),l-=2);l=m.pkgs[d=a[0]];a=a.join("/");l&&a===d+"/"+l.main&&(a=d)}else a.indexOf("./")===0&&(a=a.substring(2));if(k&&(g||j)&&h){d=a.split("/");for(l=d.length;l>0;l-=1){i=d.slice(0,l).join("/");if(g)for(b=g.length;b>0;b-=1)if(k=h[g.slice(0,b).join("/")])if(k=k[i]){v=k;e=l;break}if(v)break;!c&&j&&j[i]&&(c=j[i],f=l)}!v&&c&&(v=c,e=f);v&&(d.splice(0,e,v),a=d.join("/"))}return a}function f(a){w&&
l&&(O=!0);g.completeLoad(b)},c in m?e(m[c]):i.load(h,q(f.parentMap,!0),e,p)}function v(b){D[b.id]||(D[b.id]=b,I.push(b),g.waitCount+=1)}function B(b){this.listeners.push(b)}function t(b,a){var f=b.fullName,c=b.prefix,d=c?L[c]||(L[c]=m[c]):null,i,e;f&&(i=R[f]);if(!i&&(e=!0,i={id:(c&&!d?M++ +"__p@:":"")+(f||"__r@"+M++),map:b,depCount:0,depDone:[],depCallbacks:[],deps:[],listeners:[],add:B},y[i.id]=!0,f&&(!c||L[c])))R[f]=i;c&&!d?(f=t(h(c),!0),f.add(function(){var a=h(b.originalName,b.parentMap),a=t(a, o(document.getElementsByTagName("script"),function(d){if(d.getAttribute("data-requiremodule")===a&&d.getAttribute("data-requirecontext")===g.contextName)return d.parentNode.removeChild(d),!0})}function h(a){var d=m.paths[a];if(d&&E(d)&&d.length>1)return f(a),d.shift(),g.undef(a),g.require([a]),!0}function c(a,d,k,l){var b,i,v=a?a.indexOf("!"):-1,c=null,f=d?d.name:null,h=a,j=!0,m="";a||(j=!1,a="_@r"+(M+=1));v!==-1&&(c=a.substring(0,v),a=a.substring(v+1,a.length));c&&(c=e(c,f,l),i=q[c]);a&&(c?m=i&&
!0);i.placeholder=!0;a.add(function(b){i.callback=function(){return b};o(i)})})):e&&a&&(s[i.id]=!1,g.paused.push(i),v(i));return i}function x(b,a,f,c){var b=h(b,c),d=b.name,i=b.fullName,e=t(b),k=e.id,j=e.deps,n;if(i){if(i in m||s[k]===!0||i==="jquery"&&p.jQuery&&p.jQuery!==f().fn.jquery)return;y[k]=!0;s[k]=!0;i==="jquery"&&f&&S(f())}e.depArray=a;e.callback=f;for(f=0;f<a.length;f++)if(k=a[f])k=h(k,d?b:c),n=k.fullName,a[f]=n,n==="require"?j[f]=q(b):n==="exports"?(j[f]=m[i]={},e.usingExports=!0):n=== i.normalize?i.normalize(a,function(a){return e(a,f,l)}):e(a,f,l):(m=e(a,f,l),b=g.nameToUrl(m)));a=c&&!i&&!k?"_unnormalized"+(O+=1):"";return{prefix:c,name:m,parentMap:d,unnormalized:!!a,url:b,originalName:h,isDefine:j,id:(c?c+"!"+m:m)+a}}function p(a){var d=a.id,k=n[d];k||(k=n[d]=new g.Module(a));return k}function r(a,d,k){var b=a.id,c=n[b];if(F.call(q,b)&&(!c||c.defineEmitComplete))d==="defined"&&k(q[b]);else p(a).on(d,k)}function A(a,d){var k=a.requireModules,b=!1;if(d)d(a);else if(o(k,function(d){if(d=
"module"?e.cjsModule=j[f]={id:d,uri:d?g.nameToUrl(d,null,c):void 0,exports:m[i]}:n in m&&!(n in D)&&(!(i in F)||i in F&&Q[n])?j[f]=m[n]:(i in F&&(F[n]=!0,delete m[n],T[k.url]=!1),e.depCount+=1,e.depCallbacks[f]=r(e,f),t(k,!0).add(e.depCallbacks[f]));e.depCount?v(e):o(e)}function n(b){x.apply(null,b)}function z(b,a){if(!b.isDone){var c=b.map.fullName,d=b.depArray,g,i,e,k;if(c){if(a[c])return m[c];a[c]=!0}if(d)for(g=0;g<d.length;g++)if(i=d[g])if((e=h(i).prefix)&&(k=D[e])&&z(k,a),(e=D[i])&&!e.isDone&& n[d])d.error=a,d.events.error&&(b=!0,d.emit("error",a))}),!b)j.onError(a)}function s(){P.length&&(la.apply(D,[D.length-1,0].concat(P)),P=[])}function u(a,d,k){a=a&&a.map;d=aa(k||g.require,a,d);ba(d,g,a);d.isBrowser=w;return d}function z(a){delete n[a];o(L,function(d,k){if(d.map.id===a)return L.splice(k,1),d.defined||(g.waitCount-=1),!0})}function B(a,d,k){var b=a.map.id,c=a.depMaps,i;if(a.inited){if(d[b])return a;d[b]=!0;o(c,function(a){var a=a.id,b=n[a];return!b||k[a]||!b.inited||!b.enabled?void 0:
s[i])i=z(e,a),b.depCallbacks[g](i);return c?m[c]:void 0}}function A(){var b=p.waitSeconds*1E3,a=b&&g.startTime+b<(new Date).getTime(),b="",c=!1,h=!1,j;if(!(g.pausedCount>0)){if(p.priorityWait)if(k())w();else return;for(j in s)if(!(j in K)&&(c=!0,!s[j]))if(a)b+=j+" ";else{h=!0;break}if(c||g.waitCount){if(a&&b)return j=N("timeout","Load timeout for modules: "+b),j.requireType="timeout",j.requireModules=b,d.onError(j);if(h||g.scriptCount){if((G||ca)&&!W)W=setTimeout(function(){W=0;A()},50)}else{if(g.waitCount){for(H= i=B(b,d,k)});k[b]=!0;return i}}function C(a,d,b){var l=a.map.id,c=a.depMaps;if(a.inited&&a.map.isDefine){if(d[l])return q[l];d[l]=a;o(c,function(i){var i=i.id,c=n[i];!Q[i]&&c&&(!c.inited||!c.enabled?b[l]=!0:(c=C(c,d,b),b[i]||a.defineDepById(i,c)))});a.check(!0);return q[l]}}function I(a){a.check()}function T(){var a,d,b,l,c=(b=m.waitSeconds*1E3)&&g.startTime+b<(new Date).getTime(),i=[],e=!1,j=!0;if(!U){U=!0;y(n,function(b){a=b.map;d=a.id;if(b.enabled&&!b.error)if(!b.inited&&c)h(d)?e=l=!0:(i.push(d),
0;b=I[H];H++)z(b,{});g.paused.length&&w();X<5&&(X+=1,A())}X=0;d.checkReadyState()}}}}var g,w,p={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},catchError:{}},P=[],y={require:!0,exports:!0,module:!0},E={},m={},s={},D={},I=[],T={},M=0,R={},L={},F={},Q={},Y=0;S=function(b){if(!g.jQuery&&(b=b||(typeof jQuery!=="undefined"?jQuery:null))&&!(p.jQuery&&b.fn.jquery!==p.jQuery)&&("holdReady"in b||"readyWait"in b))if(g.jQuery=b,n(["jquery",[],function(){return jQuery}]),g.scriptCount)V(b,!0),g.jQueryIncremented= f(d));else if(!b.inited&&b.fetched&&a.isDefine&&(e=!0,!a.prefix))return j=!1});if(c&&i.length)return b=G("timeout","Load timeout for modules: "+i,null,i),b.contextName=g.contextName,A(b);j&&(o(L,function(a){if(!a.defined){var a=B(a,{},{}),d={};a&&(C(a,d,{}),y(d,I))}}),y(n,I));if((!c||l)&&e)if((w||fa)&&!V)V=setTimeout(function(){V=0;T()},50);U=!1}}function W(a){p(c(a[0],null,!0)).init(a[1],a[2])}function J(a){var a=a.currentTarget||a.srcElement,d=g.onScriptLoad;a.detachEvent&&!S?a.detachEvent("onreadystatechange",
!0};w=function(){var b,a,c,h,j,i;Y+=1;if(g.scriptCount<=0)g.scriptCount=0;for(;P.length;)if(b=P.shift(),b[0]===null)return d.onError(N("mismatch","Mismatched anonymous define() module: "+b[b.length-1]));else n(b);if(!p.priorityWait||k())for(;g.paused.length;){j=g.paused;g.pausedCount+=j.length;g.paused=[];for(h=0;b=j[h];h++)a=b.map,c=a.url,i=a.fullName,a.prefix?u(a.prefix,b):!T[c]&&!s[i]&&(d.load(g,i,c),c.indexOf("empty:")!==0&&(T[c]=!0));g.startTime=(new Date).getTime();g.pausedCount-=j.length}Y=== d):a.removeEventListener("load",d,!1);d=g.onScriptError;a.detachEvent&&!S||a.removeEventListener("error",d,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}var U,X,g,Q,V,m={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{}},n={},Y={},D=[],q={},R={},M=1,O=1,L=[];Q={require:function(a){return u(a)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports=q[a.map.id]={}},module:function(a){return a.module={id:a.map.id,uri:a.map.url,config:function(){return m.config&&m.config[a.map.id]||
1&&A();Y-=1};g={contextName:a,config:p,defQueue:P,waiting:D,waitCount:0,specified:y,loaded:s,urlMap:E,urlFetched:T,scriptCount:0,defined:m,paused:[],pausedCount:0,plugins:L,needFullExec:F,fake:{},fullExec:Q,managerCallbacks:R,makeModuleMap:h,normalize:c,configure:function(b){var a,c,d;b.baseUrl&&b.baseUrl.charAt(b.baseUrl.length-1)!=="/"&&(b.baseUrl+="/");a=p.paths;d=p.pkgs;Z(p,b,!0);if(b.paths){for(c in b.paths)c in K||(a[c]=b.paths[c]);p.paths=a}if((a=b.packagePaths)||b.packages){if(a)for(c in a)c in {}},exports:q[a.map.id]}}};X=function(a){this.events=Y[a.id]||{};this.map=a;this.shim=m.shim[a.id];this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};X.prototype={init:function(a,d,b,c){c=c||{};if(!this.inited){this.factory=d;if(b)this.on("error",b);else this.events.error&&(b=t(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.depMaps.rjsSkipMap=a.rjsSkipMap;this.errback=b;this.inited=!0;this.ignore=c.ignore;c.enabled||this.enabled?this.enable():
K||$(d,a[c],c);b.packages&&$(d,b.packages);p.pkgs=d}if(b.priority)c=g.requireWait,g.requireWait=!1,g.takeGlobalQueue(),w(),g.require(b.priority),w(),g.requireWait=c,p.priorityWait=b.priority;if(b.deps||b.callback)g.require(b.deps||[],b.callback)},requireDefined:function(b,a){return h(b,a).fullName in m},requireSpecified:function(b,a){return h(b,a).fullName in y},require:function(b,c,f){if(typeof b==="string"){if(J(c))return d.onError(N("requireargs","Invalid require call"));if(d.get)return d.get(g, this.check()}},defineDepById:function(a,d){var b;o(this.depMaps,function(d,c){if(d.id===a)return b=c,!0});return this.defineDep(b,d)},defineDep:function(a,d){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=d)},fetch:function(){if(!this.fetched){this.fetched=!0;g.startTime=(new Date).getTime();var a=this.map;if(this.shim)u(this,!0)(this.shim.deps||[],t(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},
b,c);c=h(b,c);b=c.fullName;return!(b in m)?d.onError(N("notloaded","Module name '"+c.fullName+"' has not been loaded yet for context: "+a)):m[b]}(b&&b.length||c)&&x(null,b,c,f);if(!g.requireWait)for(;!g.scriptCount&&g.paused.length;)g.takeGlobalQueue(),w();return g.require},takeGlobalQueue:function(){U.length&&(ha.apply(g.defQueue,[g.defQueue.length-1,0].concat(U)),U=[])},completeLoad:function(b){var a;for(g.takeGlobalQueue();P.length;)if(a=P.shift(),a[0]===null){a[0]=b;break}else if(a[0]===b)break; load:function(){var a=this.map.url;R[a]||(R[a]=!0,g.load(this.map.id,a))},check:function(a){if(this.enabled&&!this.enabling){var d,b,c=this.map.id;b=this.depExports;var e=this.exports,i=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(this.depCount<1&&!this.defined){if(x(i)){if(this.events.error)try{e=g.execCb(c,i,b,e)}catch(f){d=f}else e=g.execCb(c,i,b,e);if(this.map.isDefine)if((b=this.module)&&b.exports!==void 0&&b.exports!==this.exports)e=
else n(a),a=null;a?n(a):n([b,[],b==="jquery"&&typeof jQuery!=="undefined"?function(){return jQuery}:null]);S();d.isAsync&&(g.scriptCount-=1);w();d.isAsync||(g.scriptCount-=1)},toUrl:function(a,c){var d=a.lastIndexOf("."),h=null;d!==-1&&(h=a.substring(d,a.length),a=a.substring(0,d));return g.nameToUrl(a,h,c)},nameToUrl:function(a,h,f){var j,k,i,e,m=g.config,a=c(a,f&&f.fullName);if(d.jsExtRegExp.test(a))h=a+(h?h:"");else{j=m.paths;k=m.pkgs;f=a.split("/");for(e=f.length;e>0;e--)if(i=f.slice(0,e).join("/"), b.exports;else if(e===void 0&&this.usingExports)e=this.exports;if(d)return d.requireMap=this.map,d.requireModules=[this.map.id],d.requireType="define",A(this.error=d)}else e=i;this.exports=e;if(this.map.isDefine&&!this.ignore&&(q[c]=e,j.onResourceLoad))j.onResourceLoad(g,this.map,this.depMaps);delete n[c];this.defined=!0;g.waitCount-=1;g.waitCount===0&&(L=[])}this.defining=!1;if(!a&&this.defined&&!this.defineEmitted)this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0}}else this.fetch()}},
j[i]){f.splice(0,e,j[i]);break}else if(i=k[i]){a=a===i.name?i.location+"/"+i.main:i.location;f.splice(0,e,a);break}h=f.join("/")+(h||".js");h=(h.charAt(0)==="/"||h.match(/^\w+:/)?"":m.baseUrl)+h}return m.urlArgs?h+((h.indexOf("?")===-1?"?":"&")+m.urlArgs):h}};g.jQueryCheck=S;g.resume=w;return g}function ia(){var a,c,d;if(n&&n.readyState==="interactive")return n;a=document.getElementsByTagName("script");for(c=a.length-1;c>-1&&(d=a[c]);c--)if(d.readyState==="interactive")return n=d;return null}var ja= callPlugin:function(){var a=this.map,d=a.id,b=c(a.prefix,null,!1,!0);r(b,"defined",t(this,function(b){var k;k=this.map.name;var i=this.map.parentMap?this.map.parentMap.name:null;if(this.map.unnormalized){if(b.normalize&&(k=b.normalize(k,function(a){return e(a,i,!0)})||""),b=c(a.prefix+"!"+k,this.map.parentMap,!1,!0),r(b,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),b=n[b.id]){if(this.events.error)b.on("error",t(this,function(a){this.emit("error",a)}));
/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ka=/require\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/^\.\//,aa=/\.js$/,M=Object.prototype.toString,r=Array.prototype,ga=r.slice,ha=r.splice,G=!!(typeof window!=="undefined"&&navigator&&document),ca=!G&&typeof importScripts!=="undefined",la=G&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,da=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",K={},t={},U=[],n=null,X=0,O=!1,d,r={},I,v,x,y,u,z,A,H,B,S,W;if(typeof define==="undefined"){if(typeof requirejs!== b.enable()}}else k=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),k.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[d];y(n,function(a){a.map.id.indexOf(d+"_unnormalized")===0&&z(a.map.id)});A(a)}),k.fromText=function(a,b){var d=K;d&&(K=!1);p(c(a));j.exec(b);d&&(K=!0);g.completeLoad(a)},b.load(a.name,u(a.parentMap,!0,function(a,b,d){a.rjsSkipMap=!0;return g.require(a,b,d)}),k,m)}));g.enable(b,this);this.pluginMaps[b.id]=b},enable:function(){this.enabled=
"undefined")if(J(requirejs))return;else r=requirejs,requirejs=void 0;typeof require!=="undefined"&&!J(require)&&(r=require,require=void 0);d=requirejs=function(a,c,d){var k="_",j;!E(a)&&typeof a!=="string"&&(j=a,E(c)?(a=c,c=d):a=[]);if(j&&j.context)k=j.context;d=t[k]||(t[k]=fa(k));j&&d.configure(j);return d.require(a,c)};d.config=function(a){return d(a)};require||(require=d);d.toUrl=function(a){return t._.toUrl(a)};d.version="1.0.2";d.jsExtRegExp=/^\/|:|\?|\.js$/;v=d.s={contexts:t,skipAsync:{}};if(d.isAsync= !0;if(!this.waitPushed)L.push(this),g.waitCount+=1,this.waitPushed=!0;this.enabling=!0;o(this.depMaps,t(this,function(a,b){var k,e;if(typeof a==="string"){a=c(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.depMaps.rjsSkipMap);this.depMaps[b]=a;if(k=Q[a.id]){this.depExports[b]=k(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b,a);this.check()}));this.errback&&r(a,"error",this.errback)}k=a.id;e=n[k];!Q[k]&&e&&!e.enabled&&g.enable(a,this)}));y(this.pluginMaps,
d.isBrowser=G)if(x=v.head=document.getElementsByTagName("head")[0],y=document.getElementsByTagName("base")[0])x=v.head=y.parentNode;d.onError=function(a){throw a;};d.load=function(a,c,h){d.resourcesReady(!1);a.scriptCount+=1;d.attach(h,a,c);if(a.jQuery&&!a.jQueryIncremented)V(a.jQuery,!0),a.jQueryIncremented=!0};define=function(a,c,d){var k,j;typeof a!=="string"&&(d=c,c=a,a=null);E(c)||(d=c,c=[]);!c.length&&J(d)&&d.length&&(d.toString().replace(ja,"").replace(ka,function(a,d){c.push(d)}),c=(d.length=== t(this,function(a){var b=n[a.id];b&&!b.enabled&&g.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){o(this.events[a],function(a){a(b)});a==="error"&&delete this.events[a]}};return g={config:m,contextName:b,registry:n,defined:q,urlFetched:R,waitCount:0,defQueue:D,Module:X,makeModuleMap:c,configure:function(a){a.baseUrl&&a.baseUrl.charAt(a.baseUrl.length-1)!=="/"&&(a.baseUrl+="/");var b=m.pkgs,e=m.shim,f=m.paths,
1?["require"]:["require","exports","module"]).concat(c));if(O&&(k=I||ia()))a||(a=k.getAttribute("data-requiremodule")),j=t[k.getAttribute("data-requirecontext")];(j?j.defQueue:U).push([a,c,d])};define.amd={multiversion:!0,plugins:!0,jQuery:!0};d.exec=function(a){return eval(a)};d.execCb=function(a,c,d,k){return c.apply(k,d)};d.addScriptToDom=function(a){I=a;y?x.insertBefore(a,y):x.appendChild(a);I=null};d.onScriptLoad=function(a){var c=a.currentTarget||a.srcElement,h;if(a.type==="load"||c&&la.test(c.readyState))n= j=m.map;N(m,a,!0);m.paths=N(f,a.paths,!0);if(a.map)m.map=N(j||{},a.map,!0,!0);if(a.shim)y(a.shim,function(a,b){E(a)&&(a={deps:a});if(a.exports&&!a.exports.__buildReady)a.exports=g.makeShimExports(a.exports);e[b]=a}),m.shim=e;if(a.packages)o(a.packages,function(a){a=typeof a==="string"?{name:a}:a;b[a.name]={name:a.name,location:a.location||a.name,main:(a.main||"main").replace(ka,"").replace(ea,"")}}),m.pkgs=b;y(n,function(a,b){if(!a.inited&&!a.map.unnormalized)a.map=c(b)});if(a.deps||a.callback)g.require(a.deps||
null,a=c.getAttribute("data-requirecontext"),h=c.getAttribute("data-requiremodule"),t[a].completeLoad(h),c.detachEvent&&!da?c.detachEvent("onreadystatechange",d.onScriptLoad):c.removeEventListener("load",d.onScriptLoad,!1)};d.attach=function(a,c,h,k,j,n){var o;if(G)return k=k||d.onScriptLoad,o=c&&c.config&&c.config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script"),o.type=j||"text/javascript",o.charset="utf-8",o.async=!v.skipAsync[a],c&&o.setAttribute("data-requirecontext", [],a.callback)},makeShimExports:function(a){var b;return typeof a==="string"?(b=function(){return $(a)},b.exports=a,b):function(){return a.apply(Z,arguments)}},requireDefined:function(a,b){var e=c(a,b,!1,!0).id;return F.call(q,e)},requireSpecified:function(a,b){a=c(a,b,!1,!0).id;return F.call(q,a)||F.call(n,a)},require:function(a,d,e,f){var h;if(typeof a==="string"){if(x(d))return A(G("requireargs","Invalid require call"),e);if(j.get)return j.get(g,a,d);a=c(a,d,!1,!0);a=a.id;return!F.call(q,a)?A(G("notloaded",
c.contextName),o.setAttribute("data-requiremodule",h),o.attachEvent&&!da?(O=!0,n?o.onreadystatechange=function(){if(o.readyState==="loaded")o.onreadystatechange=null,o.attachEvent("onreadystatechange",k),n(o)}:o.attachEvent("onreadystatechange",k)):o.addEventListener("load",k,!1),o.src=a,n||d.addScriptToDom(o),o;else ca&&(importScripts(a),c.completeLoad(h));return null};if(G){u=document.getElementsByTagName("script");for(H=u.length-1;H>-1&&(z=u[H]);H--){if(!x)x=z.parentNode;if(A=z.getAttribute("data-main")){if(!r.baseUrl)u= 'Module name "'+a+'" has not been loaded yet for context: '+b)):q[a]}e&&!x(e)&&(f=e,e=void 0);d&&!x(d)&&(f=d,d=void 0);for(s();D.length;)if(h=D.shift(),h[0]===null)return A(G("mismatch","Mismatched anonymous define() module: "+h[h.length-1]));else W(h);p(c(null,f)).init(a,d,e,{enabled:!0});T();return g.require},undef:function(a){s();var b=c(a,null,!0),e=n[a];delete q[a];delete R[b.url];delete Y[a];if(e){if(e.events.defined)Y[a]=e.events;z(a)}},enable:function(a){n[a.id]&&p(a).enable()},completeLoad:function(a){var b,
A.split("/"),z=u.pop(),u=u.length?u.join("/")+"/":"./",r.baseUrl=u,A=z.replace(aa,"");r.deps=r.deps?r.deps.concat(A):[A];break}}}d.checkReadyState=function(){var a=v.contexts,c;for(c in a)if(!(c in K)&&a[c].waitCount)return;d.resourcesReady(!0)};d.resourcesReady=function(a){var c,h;d.resourcesDone=a;if(d.resourcesDone)for(h in a=v.contexts,a)if(!(h in K)&&(c=a[h],c.jQueryIncremented))V(c.jQuery,!1),c.jQueryIncremented=!1};d.pageLoaded=function(){if(document.readyState!=="complete")document.readyState= c,e=m.shim[a]||{},f=e.exports&&e.exports.exports;for(s();D.length;){c=D.shift();if(c[0]===null){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);W(c)}c=n[a];if(!b&&!q[a]&&c&&!c.inited)if(m.enforceDefine&&(!f||!$(f)))if(h(a))return;else return A(G("nodefine","No define call for "+a,null,[a]));else W([a,e.deps||[],e.exports]);T()},toUrl:function(a,b){var c=a.lastIndexOf("."),f=null;c!==-1&&(f=a.substring(c,a.length),a=a.substring(0,c));return g.nameToUrl(e(a,b&&b.id,!0),f)},nameToUrl:function(a,b){var c,
"complete"};if(G&&document.addEventListener&&!document.readyState)document.readyState="loading",window.addEventListener("load",d.pageLoaded,!1);d(r);if(d.isAsync&&typeof setTimeout!=="undefined")B=v.contexts[r.context||"_"],B.requireWait=!0,setTimeout(function(){B.requireWait=!1;B.takeGlobalQueue();B.jQueryCheck();B.scriptCount||B.resume();d.checkReadyState()},0)}})(); e,f,i,h,g;if(j.jsExtRegExp.test(a))i=a+(b||"");else{c=m.paths;e=m.pkgs;i=a.split("/");for(h=i.length;h>0;h-=1)if(g=i.slice(0,h).join("/"),f=e[g],g=c[g]){E(g)&&(g=g[0]);i.splice(0,h,g);break}else if(f){c=a===f.name?f.location+"/"+f.main:f.location;i.splice(0,h,c);break}i=i.join("/");i+=b||(/\?/.test(i)?"":".js");i=(i.charAt(0)==="/"||i.match(/^[\w\+\.\-]+:/)?"":m.baseUrl)+i}return m.urlArgs?i+((i.indexOf("?")===-1?"?":"&")+m.urlArgs):i},load:function(a,b){j.load(g,a,b)},execCb:function(a,b,c,e){return b.apply(e,
  c)},onScriptLoad:function(a){if(a.type==="load"||ma.test((a.currentTarget||a.srcElement).readyState))H=null,a=J(a),g.completeLoad(a.id)},onScriptError:function(a){var b=J(a);if(!h(b.id))return A(G("scripterror","Script error",a,[b.id]))}}}};j({});ba(j);if(w&&(u=p.head=document.getElementsByTagName("head")[0],B=document.getElementsByTagName("base")[0]))u=p.head=B.parentNode;j.onError=function(b){throw b;};j.load=function(b,e,f){var h=b&&b.config||{},c;if(w)return c=h.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml",
  "html:script"):document.createElement("script"),c.type=h.scriptType||"text/javascript",c.charset="utf-8",c.async=!0,c.setAttribute("data-requirecontext",b.contextName),c.setAttribute("data-requiremodule",e),c.attachEvent&&!(c.attachEvent.toString&&c.attachEvent.toString().indexOf("[native code")<0)&&!S?(K=!0,c.attachEvent("onreadystatechange",b.onScriptLoad)):(c.addEventListener("load",b.onScriptLoad,!1),c.addEventListener("error",b.onScriptError,!1)),c.src=f,I=c,B?u.insertBefore(c,B):u.appendChild(c),
  I=null,c;else fa&&(importScripts(f),b.completeLoad(e))};w&&M(document.getElementsByTagName("script"),function(b){if(!u)u=b.parentNode;if(s=b.getAttribute("data-main")){if(!r.baseUrl)C=s.split("/"),ca=C.pop(),da=C.length?C.join("/")+"/":"./",r.baseUrl=da,s=ca;s=s.replace(ea,"");r.deps=r.deps?r.deps.concat(s):[s];return!0}});define=function(b,e,f){var h,c;typeof b!=="string"&&(f=e,e=b,b=null);E(e)||(f=e,e=[]);!e.length&&x(f)&&f.length&&(f.toString().replace(ia,"").replace(ja,function(b,c){e.push(c)}),
  e=(f.length===1?["require"]:["require","exports","module"]).concat(e));if(K&&(h=I||ha()))b||(b=h.getAttribute("data-requiremodule")),c=z[h.getAttribute("data-requirecontext")];(c?c.defQueue:P).push([b,e,f])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(r)}})(this);
   
/** /**
* @license r.js 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license r.js 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/* /*
* This is a bootstrap script to allow running RequireJS in the command line * This is a bootstrap script to allow running RequireJS in the command line
* in either a Java/Rhino or Node environment. It is modified by the top-level * in either a Java/Rhino or Node environment. It is modified by the top-level
* dist.js file to inject other files to completely enable this file. It is * dist.js file to inject other files to completely enable this file. It is
* the shell of the r.js file. * the shell of the r.js file.
*/ */
   
/*jslint strict: false, evil: true, nomen: false */ /*jslint evil: true, nomen: true, sloppy: true */
/*global readFile: true, process: false, Packages: false, print: false, /*global readFile: true, process: false, Packages: false, print: false,
console: false, java: false, module: false */ console: false, java: false, module: false, requirejsVars */
   
var requirejs, require, define; var requirejs, require, define;
(function (console, args, readFileFunc) { (function (console, args, readFileFunc) {
   
var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire, var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
nodeDefine, exists, reqMain, loadedOptimizedLib, nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode,
version = '1.0.2', version = '2.0.6',
jsSuffixRegExp = /\.js$/, jsSuffixRegExp = /\.js$/,
commandOption = '', commandOption = '',
  useLibLoaded = {},
//Used by jslib/rhino/args.js //Used by jslib/rhino/args.js
rhinoArgs = args, rhinoArgs = args,
readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null; readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
   
function showHelp() { function showHelp() {
console.log('See https://github.com/jrburke/r.js for usage.'); console.log('See https://github.com/jrburke/r.js for usage.');
} }
   
if (typeof Packages !== 'undefined') { if (typeof Packages !== 'undefined') {
env = 'rhino'; env = 'rhino';
   
fileName = args[0]; fileName = args[0];
   
if (fileName && fileName.indexOf('-') === 0) { if (fileName && fileName.indexOf('-') === 0) {
commandOption = fileName.substring(1); commandOption = fileName.substring(1);
fileName = args[1]; fileName = args[1];
} }
   
//Set up execution context. //Set up execution context.
rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext(); rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
   
exec = function (string, name) { exec = function (string, name) {
return rhinoContext.evaluateString(this, string, name, 0, null); return rhinoContext.evaluateString(this, string, name, 0, null);
}; };
   
exists = function (fileName) { exists = function (fileName) {
return (new java.io.File(fileName)).exists(); return (new java.io.File(fileName)).exists();
}; };
   
//Define a console.log for easier logging. Don't //Define a console.log for easier logging. Don't
//get fancy though. //get fancy though.
if (typeof console === 'undefined') { if (typeof console === 'undefined') {
console = { console = {
log: function () { log: function () {
print.apply(undefined, arguments); print.apply(undefined, arguments);
} }
}; };
} }
} else if (typeof process !== 'undefined') { } else if (typeof process !== 'undefined') {
env = 'node'; env = 'node';
   
//Get the fs module via Node's require before it //Get the fs module via Node's require before it
//gets replaced. Used in require/node.js //gets replaced. Used in require/node.js
fs = require('fs'); fs = require('fs');
vm = require('vm'); vm = require('vm');
path = require('path'); path = require('path');
  //In Node 0.7+ existsSync is on fs.
  existsForNode = fs.existsSync || path.existsSync;
   
nodeRequire = require; nodeRequire = require;
nodeDefine = define; nodeDefine = define;
reqMain = require.main; reqMain = require.main;
   
//Temporarily hide require and define to allow require.js to define //Temporarily hide require and define to allow require.js to define
//them. //them.
require = undefined; require = undefined;
define = undefined; define = undefined;
   
readFile = function (path) { readFile = function (path) {
return fs.readFileSync(path, 'utf8'); return fs.readFileSync(path, 'utf8');
}; };
   
exec = function (string, name) { exec = function (string, name) {
return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string), return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
name ? fs.realpathSync(name) : ''); name ? fs.realpathSync(name) : '');
}; };
   
exists = function (fileName) { exists = function (fileName) {
return path.existsSync(fileName); return existsForNode(fileName);
}; };
   
   
fileName = process.argv[2]; fileName = process.argv[2];
   
if (fileName && fileName.indexOf('-') === 0) { if (fileName && fileName.indexOf('-') === 0) {
commandOption = fileName.substring(1); commandOption = fileName.substring(1);
fileName = process.argv[3]; fileName = process.argv[3];
} }
} }
   
/** vim: et:ts=4:sw=4:sts=4 /** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
/*jslint strict: false, plusplus: false, sub: true */ //Not using strict: uneven strict support in browsers, #392, and causes
/*global window: false, navigator: false, document: false, importScripts: false, //problems with requirejs.exec()/transpiler plugins that may not be strict.
jQuery: false, clearInterval: false, setInterval: false, self: false, /*jslint regexp: true, nomen: true, sloppy: true */
setTimeout: false, opera: false */ /*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
   
   
(function () { (function (global) {
//Change this version number for each release. var req, s, head, baseElement, dataMain, src,
var version = "1.0.2", interactiveScript, currentlyAddingScript, mainScript, subPath,
  version = '2.0.6',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /require\(\s*["']([^'"\s]+)["']\s*\)/g, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//, currDirRegExp = /^\.\//,
jsSuffixRegExp = /\.js$/, op = Object.prototype,
ostring = Object.prototype.toString, ostring = op.toString,
  hasOwn = op.hasOwnProperty,
ap = Array.prototype, ap = Array.prototype,
aps = ap.slice, aps = ap.slice,
apsp = ap.splice, apsp = ap.splice,
isBrowser = !!(typeof window !== "undefined" && navigator && document), isBrowser = !!(typeof window !== 'undefined' && navigator && document),
isWebWorker = !isBrowser && typeof importScripts !== "undefined", isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete //PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is "loading", "loaded", execution, //specifically. Sequence is 'loading', 'loaded', execution,
// then "complete". The UA check is unfortunate, but not sure how // then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues. //to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/, /^complete$/ : /^(complete|loaded)$/,
defContextName = "_", defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== "undefined" && opera.toString() === "[object Opera]", isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
empty = {},  
contexts = {}, contexts = {},
  cfg = {},
globalDefQueue = [], globalDefQueue = [],
interactiveScript = null, useInteractive = false;
checkLoadedDepth = 0,  
useInteractive = false,  
req, cfg = {}, currentlyAddingScript, s, head, baseElement, scripts, script,  
src, subPath, mainScript, dataMain, i, ctx, jQueryCheck, checkLoadedTimeoutId;  
   
function isFunction(it) { function isFunction(it) {
return ostring.call(it) === "[object Function]"; return ostring.call(it) === '[object Function]';
} }
   
function isArray(it) { function isArray(it) {
return ostring.call(it) === "[object Array]"; return ostring.call(it) === '[object Array]';
  }
   
  /**
  * Helper function for iterating over an array. If the func returns
  * a true value, it will break out of the loop.
  */
  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;
  }
  }
  }
  }
   
  /**
  * Helper function for iterating over an array backwards. If the func
  * returns a true value, it will break out of the loop.
  */
  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);
  }
   
  /**
  * Cycles over properties in an object and calls a function for each
  * property value. If the function returns a truthy value, then the
  * iteration is stopped.
  */
  function eachProp(obj, func) {
  var prop;
  for (prop in obj) {
  if (obj.hasOwnProperty(prop)) {
  if (func(obj[prop], prop)) {
  break;
  }
  }
  }
} }
   
/** /**
* Simple function to mix in properties from source into target, * Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name. * but only if target does not already have a property of the same name.
* This is not robust in IE for transferring methods that match * This is not robust in IE for transferring methods that match
* Object.prototype names, but the uses of mixin here seem unlikely to * Object.prototype names, but the uses of mixin here seem unlikely to
* trigger a problem related to that. * trigger a problem related to that.
*/ */
function mixin(target, source, force) { function mixin(target, source, force, deepStringMixin) {
for (var prop in source) { if (source) {
if (!(prop in empty) && (!(prop in target) || force)) { eachProp(source, function (value, prop) {
target[prop] = source[prop]; if (force || !hasProp(target, prop)) {
} if (deepStringMixin && typeof value !== 'string') {
} if (!target[prop]) {
return req; target[prop] = {};
  }
  mixin(target[prop], value, force, deepStringMixin);
  } else {
  target[prop] = value;
  }
  }
  });
  }
  return target;
  }
   
  //Similar to Function.prototype.bind, but the 'this' object is specified
  //first, since it is easier to read/figure out what 'this' will be.
  function bind(obj, fn) {
  return function () {
  return fn.apply(obj, arguments);
  };
  }
   
  function scripts() {
  return document.getElementsByTagName('script');
  }
   
  //Allow getting a global that expressed in
  //dot notation, like 'a.b.c'.
  function getGlobal(value) {
  if (!value) {
  return value;
  }
  var g = global;
  each(value.split('.'), function (part) {
  g = g[part];
  });
  return g;
  }
   
  function makeContextModuleFunc(func, relMap, enableBuildCallback) {
  return function () {
  //A version of a require function that passes a moduleName
  //value for items that may need to
  //look up paths relative to the moduleName
  var args = aps.call(arguments, 0), lastArg;
  if (enableBuildCallback &&
  isFunction((lastArg = args[args.length - 1]))) {
  lastArg.__requireJsBuild = true;
  }
  args.push(relMap);
  return func.apply(null, args);
  };
  }
   
  function addRequireMethods(req, context, relMap) {
  each([
  ['toUrl'],
  ['undef'],
  ['defined', 'requireDefined'],
  ['specified', 'requireSpecified']
  ], function (item) {
  var prop = item[1] || item[0];
  req[item[0]] = context ? makeContextModuleFunc(context[prop], relMap) :
  //If no context, then use default context. Reference from
  //contexts instead of early binding to default context, so
  //that during builds, the latest instance of the default
  //context with its config gets used.
  function () {
  var ctx = contexts[defContextName];
  return ctx[prop].apply(ctx, arguments);
  };
  });
} }
   
/** /**
* Constructs an error with a pointer to an URL with more information. * Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page. * @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error. * @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one. * @param {Error} [err] the original error, if there is one.
* *
* @returns {Error} * @returns {Error}
*/ */
function makeError(id, msg, err) { function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  e.requireType = id;
  e.requireModules = requireModules;
if (err) { if (err) {
e.originalError = err; e.originalError = err;
} }
return e; return e;
} }
   
/** if (typeof define !== 'undefined') {
* Used to set up package paths from a packagePaths or packages config object.  
* @param {Object} pkgs the object to store the new package config  
* @param {Array} currentPackages an array of packages to configure  
* @param {String} [dir] a prefix dir to use.  
*/  
function configurePackageDir(pkgs, currentPackages, dir) {  
var i, location, pkgObj;  
   
for (i = 0; (pkgObj = currentPackages[i]); i++) {  
pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj;  
location = pkgObj.location;  
   
//Add dir to the path, but avoid paths that start with a slash  
//or have a colon (indicates a protocol)  
if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) {  
location = dir + "/" + (location || pkgObj.name);  
}  
   
//Create a brand new object on pkgs, since currentPackages can  
//be passed in again, and config.pkgs is the internal transformed  
//state for all package configs.  
pkgs[pkgObj.name] = {  
name: pkgObj.name,  
location: location || pkgObj.name,  
//Remove leading dot in main, so main paths are normalized,  
//and remove any trailing .js, since different package  
//envs have different conventions: some use a module name,  
//some use a file name.  
main: (pkgObj.main || "main")  
.replace(currDirRegExp, '')  
.replace(jsSuffixRegExp, '')  
};  
}  
}  
   
/**  
* jQuery 1.4.3-1.5.x use a readyWait/ready() pairing to hold DOM  
* ready callbacks, but jQuery 1.6 supports a holdReady() API instead.  
* At some point remove the readyWait/ready() support and just stick  
* with using holdReady.  
*/  
function jQueryHoldReady($, shouldHold) {  
if ($.holdReady) {  
$.holdReady(shouldHold);  
} else if (shouldHold) {  
$.readyWait += 1;  
} else {  
$.ready(true);  
}  
}  
   
if (typeof define !== "undefined") {  
//If a define is already in play via another AMD loader, //If a define is already in play via another AMD loader,
//do not overwrite. //do not overwrite.
return; return;
} }
   
if (typeof requirejs !== "undefined") { if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) { if (isFunction(requirejs)) {
//Do not overwrite and existing requirejs instance. //Do not overwrite and existing requirejs instance.
return; return;
} else { }
cfg = requirejs; cfg = requirejs;
requirejs = undefined; requirejs = undefined;
}  
} }
   
//Allow for a require config object //Allow for a require config object
if (typeof require !== "undefined" && !isFunction(require)) { if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object. //assume it is a config object.
cfg = require; cfg = require;
require = undefined; require = undefined;
} }
   
/**  
* Creates a new context for use in require and define calls.  
* Handle most of the heavy lifting. Do not want to use an object  
* with prototype here to avoid using "this" in require, in case it  
* needs to be used in more super secure envs that do not want this.  
* Also there should not be that many contexts in the page. Usually just  
* one for the default context, but could be extra for multiversion cases  
* or if a package needs a special context for a dependency that conflicts  
* with the standard context.  
*/  
function newContext(contextName) { function newContext(contextName) {
var context, resume, var inCheckLoaded, Module, context, handlers,
  checkLoadedTimeoutId,
config = { config = {
waitSeconds: 7, waitSeconds: 7,
baseUrl: "./", baseUrl: './',
paths: {}, paths: {},
pkgs: {}, pkgs: {},
catchError: {} shim: {}
}, },
  registry = {},
  undefEvents = {},
defQueue = [], defQueue = [],
specified = {  
"require": true,  
"exports": true,  
"module": true  
},  
urlMap = {},  
defined = {}, defined = {},
loaded = {},  
waiting = {},  
waitAry = [],  
urlFetched = {}, urlFetched = {},
managerCounter = 0, requireCounter = 1,
managerCallbacks = {}, unnormalizedCounter = 1,
plugins = {}, //Used to track the order in which modules
//Used to indicate which modules in a build scenario //should be executed, by the order they
//need to be full executed. //load. Important for consistent cycle resolution
needFullExec = {}, //behavior.
fullExec = {}, waitAry = [];
resumeDepth = 0;  
   
/** /**
* Trims the . and .. from an array of path segments. * Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become * It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups, * the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result, * which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized. * all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array. * NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments. * @param {Array} ary the array of path segments.
*/ */
function trimDots(ary) { function trimDots(ary) {
var i, part; var i, part;
for (i = 0; (part = ary[i]); i++) { for (i = 0; ary[i]; i += 1) {
if (part === ".") { part = ary[i];
  if (part === '.') {
ary.splice(i, 1); ary.splice(i, 1);
i -= 1; i -= 1;
} else if (part === "..") { } else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot //End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped //path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely //correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'. //no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable //This can still fail, but catches the most reasonable
//uses of .. //uses of ..
break; break;
} else if (i > 0) { } else if (i > 0) {
ary.splice(i - 1, 2); ary.splice(i - 1, 2);
i -= 2; i -= 2;
} }
} }
} }
} }
   
/** /**
* Given a relative module name, like ./something, normalize it to * Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path. * a real name that can be mapped to a path.
* @param {String} name the relative name * @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative * @param {String} baseName a real name that the name arg is relative
* to. * to.
  * @param {Boolean} applyMap apply the map config to the value. Should
  * only be done if this normalization is for a dependency ID.
* @returns {String} normalized name * @returns {String} normalized name
*/ */
function normalize(name, baseName) { function normalize(name, baseName, applyMap) {
var pkgName, pkgConfig; var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
  foundMap, foundI, foundStarMap, starI,
  baseParts = baseName && baseName.split('/'),
  normalizedBaseParts = baseParts,
  map = config.map,
  starMap = map && map['*'];
   
//Adjust any relative paths. //Adjust any relative paths.
if (name && name.charAt(0) === ".") { if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it, //If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will //otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end. //be relative to baseUrl in the end.
if (baseName) { if (baseName) {
if (config.pkgs[baseName]) { if (config.pkgs[baseName]) {
//If the baseName is a package name, then just treat it as one //If the baseName is a package name, then just treat it as one
//name to concat the name with. //name to concat the name with.
baseName = [baseName]; normalizedBaseParts = baseParts = [baseName];
} else { } else {
//Convert baseName to array, and lop off the last part, //Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's //so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to //module. For instance, baseName of 'one/two/three', maps to
//"one/two/three.js", but we want the directory, "one/two" for //'one/two/three.js', but we want the directory, 'one/two' for
//this normalization. //this normalization.
baseName = baseName.split("/"); normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
baseName = baseName.slice(0, baseName.length - 1);  
} }
   
name = baseName.concat(name.split("/")); name = normalizedBaseParts.concat(name.split('/'));
trimDots(name); trimDots(name);
   
//Some use of packages may use a . path to reference the //Some use of packages may use a . path to reference the
//"main" module name, so normalize for that. //'main' module name, so normalize for that.
pkgConfig = config.pkgs[(pkgName = name[0])]; pkgConfig = config.pkgs[(pkgName = name[0])];
name = name.join("/"); name = name.join('/');
if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
name = pkgName; name = pkgName;
} }
} else if (name.indexOf("./") === 0) { } else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative // No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot. // to baseUrl, pull off the leading dot.
name = name.substring(2); name = name.substring(2);
} }
} }
   
  //Apply map config if available.
  if (applyMap && (baseParts || starMap) && map) {
  nameParts = name.split('/');
   
  for (i = nameParts.length; i > 0; i -= 1) {
  nameSegment = nameParts.slice(0, i).join('/');
   
  if (baseParts) {
  //Find the longest baseName segment match in the config.
  //So, do joins on the biggest to smallest lengths of baseParts.
  for (j = baseParts.length; j > 0; j -= 1) {
  mapValue = map[baseParts.slice(0, j).join('/')];
   
  //baseName segment has config, find if it has one for
  //this name.
  if (mapValue) {
  mapValue = mapValue[nameSegment];
  if (mapValue) {
  //Match, update name to the new value.
  foundMap = mapValue;
  foundI = i;
  break;
  }
  }
  }
  }
   
  if (foundMap) {
  break;
  }
   
  //Check for a star map match, but just hold on to it,
  //if there is a shorter segment match later in a matching
  //config, then favor over this star map.
  if (!foundStarMap && starMap && starMap[nameSegment]) {
  foundStarMap = starMap[nameSegment];
  starI = i;
  }
  }
   
  if (!foundMap && foundStarMap) {
  foundMap = foundStarMap;
  foundI = starI;
  }
   
  if (foundMap) {
  nameParts.splice(0, foundI, foundMap);
  name = nameParts.join('/');
  }
  }
   
return name; return 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 = config.paths[id];
  if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  removeScript(id);
  //Pop off the first array value, since it failed, and
  //retry
  pathConfig.shift();
  context.undef(id);
  context.require([id]);
  return true;
  }
} }
   
/** /**
* Creates a module mapping that includes plugin prefix, module * Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will * name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize() * also normalize the name via require.normalize()
* *
* @param {String} name the module name * @param {String} name the module name
* @param {String} [parentModuleMap] parent module map * @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names. * for the module name, used to resolve relative names.
  * @param {Boolean} isNormalized: is the ID already normalized.
  * This is true if this call is done for a define() module ID.
  * @param {Boolean} applyMap: apply the map config to the ID.
  * Should only be true if this map is for a dependency.
* *
* @returns {Object} * @returns {Object}
*/ */
function makeModuleMap(name, parentModuleMap) { function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var index = name ? name.indexOf("!") : -1, var url, pluginModule, suffix,
  index = name ? name.indexOf('!') : -1,
prefix = null, prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null, parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name, originalName = name,
normalizedName, url, pluginModule; isDefine = true,
  normalizedName = '';
   
  //If no name, then it means it is a require call, generate an
  //internal name.
  if (!name) {
  isDefine = false;
  name = '_@r' + (requireCounter += 1);
  }
   
if (index !== -1) { if (index !== -1) {
prefix = name.substring(0, index); prefix = name.substring(0, index);
name = name.substring(index + 1, name.length); name = name.substring(index + 1, name.length);
} }
   
if (prefix) { if (prefix) {
prefix = normalize(prefix, parentName); prefix = normalize(prefix, parentName, applyMap);
  pluginModule = defined[prefix];
} }
   
//Account for relative paths if there is a base name. //Account for relative paths if there is a base name.
if (name) { if (name) {
if (prefix) { if (prefix) {
pluginModule = defined[prefix];  
if (pluginModule && pluginModule.normalize) { if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method. //Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) { normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName); return normalize(name, parentName, applyMap);
}); });
} else { } else {
normalizedName = normalize(name, parentName); normalizedName = normalize(name, parentName, applyMap);
} }
} else { } else {
//A regular module. //A regular module.
normalizedName = normalize(name, parentName); normalizedName = normalize(name, parentName, applyMap);
  url = context.nameToUrl(normalizedName);
url = urlMap[normalizedName]; }
if (!url) { }
//Calculate url for the module, if it has a name.  
url = context.nameToUrl(normalizedName, null, parentModuleMap); //If the id is a plugin id that cannot be determined if it needs
  //normalization, stamp it with a unique ID so two matching relative
//Store the URL mapping for later. //ids that may conflict can be separate.
urlMap[normalizedName] = url; suffix = prefix && !pluginModule && !isNormalized ?
} '_unnormalized' + (unnormalizedCounter += 1) :
} '';
}  
   
return { return {
prefix: prefix, prefix: prefix,
name: normalizedName, name: normalizedName,
parentMap: parentModuleMap, parentMap: parentModuleMap,
  unnormalized: !!suffix,
url: url, url: url,
originalName: originalName, originalName: originalName,
fullName: prefix ? prefix + "!" + (normalizedName || '') : normalizedName isDefine: isDefine,
  id: (prefix ?
  prefix + '!' + normalizedName :
  normalizedName) + suffix
}; };
} }
   
  function getModule(depMap) {
  var id = depMap.id,
  mod = registry[id];
   
  if (!mod) {
  mod = registry[id] = new context.Module(depMap);
  }
   
  return mod;
  }
   
  function on(depMap, name, fn) {
  var id = depMap.id,
  mod = registry[id];
   
  if (hasProp(defined, id) &&
  (!mod || mod.defineEmitComplete)) {
  if (name === 'defined') {
  fn(defined[id]);
  }
  } else {
  getModule(depMap).on(name, fn);
  }
  }
   
  function onError(err, errback) {
  var ids = err.requireModules,
  notified = false;
   
  if (errback) {
  errback(err);
  } else {
  each(ids, function (id) {
  var mod = registry[id];
  if (mod) {
  //Set error on module, so it skips timeout checks.
  mod.error = err;
  if (mod.events.error) {
  notified = true;
  mod.emit('error', err);
  }
  }
  });
   
  if (!notified) {
  req.onError(err);
  }
  }
  }
   
/** /**
* Determine if priority loading is done. If so clear the priorityWait * Internal method to transfer globalQueue items to this context's
  * defQueue.
*/ */
function isPriorityDone() { function takeGlobalQueue() {
var priorityDone = true, //Push all the globalDefQueue items into the context's defQueue
priorityWait = config.priorityWait, if (globalDefQueue.length) {
priorityName, i; //Array splice in the values since the context code has a
if (priorityWait) { //local var ref to defQueue, so cannot just reassign the one
for (i = 0; (priorityName = priorityWait[i]); i++) { //on context.
if (!loaded[priorityName]) { apsp.apply(defQueue,
priorityDone = false; [defQueue.length - 1, 0].concat(globalDefQueue));
break; globalDefQueue = [];
} }
}  
if (priorityDone) {  
delete config.priorityWait;  
}  
}  
return priorityDone;  
}  
   
function makeContextModuleFunc(func, relModuleMap, enableBuildCallback) {  
return function () {  
//A version of a require function that passes a moduleName  
//value for items that may need to  
//look up paths relative to the moduleName  
var args = aps.call(arguments, 0), lastArg;  
if (enableBuildCallback &&  
isFunction((lastArg = args[args.length - 1]))) {  
lastArg.__requireJsBuild = true;  
}  
args.push(relModuleMap);  
return func.apply(null, args);  
};  
} }
   
/** /**
* Helper function that creates a require function object to give to * Helper function that creates a require function object to give to
* modules that ask for it as a dependency. It needs to be specific * modules that ask for it as a dependency. It needs to be specific
* per module because of the implication of path mappings that may * per module because of the implication of path mappings that may
* need to be relative to the module name. * need to be relative to the module name.
*/ */
function makeRequire(relModuleMap, enableBuildCallback) { function makeRequire(mod, enableBuildCallback, altRequire) {
var modRequire = makeContextModuleFunc(context.require, relModuleMap, enableBuildCallback); var relMap = mod && mod.map,
  modRequire = makeContextModuleFunc(altRequire || context.require,
mixin(modRequire, { relMap,
nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap), enableBuildCallback);
toUrl: makeContextModuleFunc(context.toUrl, relModuleMap),  
defined: makeContextModuleFunc(context.requireDefined, relModuleMap), addRequireMethods(modRequire, context, relMap);
specified: makeContextModuleFunc(context.requireSpecified, relModuleMap), modRequire.isBrowser = isBrowser;
isBrowser: req.isBrowser  
  return modRequire;
  }
   
  handlers = {
  'require': function (mod) {
  return makeRequire(mod);
  },
  'exports': function (mod) {
  mod.usingExports = true;
  if (mod.map.isDefine) {
  return (mod.exports = defined[mod.map.id] = {});
  }
  },
  'module': function (mod) {
  return (mod.module = {
  id: mod.map.id,
  uri: mod.map.url,
  config: function () {
  return (config.config && config.config[mod.map.id]) || {};
  },
  exports: defined[mod.map.id]
  });
  }
  };
   
  function removeWaiting(id) {
  //Clean up machinery used for waiting modules.
  delete registry[id];
   
  each(waitAry, function (mod, i) {
  if (mod.map.id === id) {
  waitAry.splice(i, 1);
  if (!mod.defined) {
  context.waitCount -= 1;
  }
  return true;
  }
}); });
return modRequire; }
}  
  function findCycle(mod, traced, processed) {
/* var id = mod.map.id,
* Queues a dependency for checking after the loader is out of a depArray = mod.depMaps,
* "paused" state, for example while a script file is being loaded foundModule;
* in the browser, where it may have many modules defined in it.  
*/ //Do not bother with unitialized modules or not yet enabled
function queueDependency(manager) { //modules.
context.paused.push(manager); if (!mod.inited) {
} return;
  }
function execManager(manager) {  
var i, ret, err, errFile, errModuleTree, //Found the cycle.
cb = manager.callback, if (traced[id]) {
map = manager.map, return mod;
fullName = map.fullName, }
args = manager.deps,  
listeners = manager.listeners, traced[id] = true;
cjsModule;  
  //Trace through the dependencies.
//Call the callback to define the module, if necessary. each(depArray, function (depMap) {
if (cb && isFunction(cb)) { var depId = depMap.id,
if (config.catchError.define) { depMod = registry[depId];
try {  
ret = req.execCb(fullName, manager.callback, args, defined[fullName]); if (!depMod || processed[depId] ||
} catch (e) { !depMod.inited || !depMod.enabled) {
err = e; return;
  }
   
  return (foundModule = findCycle(depMod, traced, processed));
  });
   
  processed[id] = true;
   
  return foundModule;
  }
   
  function forceExec(mod, traced, uninited) {
  var id = mod.map.id,
  depArray = mod.depMaps;
   
  if (!mod.inited || !mod.map.isDefine) {
  return;
  }
   
  if (traced[id]) {
  return defined[id];
  }
   
  traced[id] = mod;
   
  each(depArray, function (depMap) {
  var depId = depMap.id,
  depMod = registry[depId],
  value;
   
  if (handlers[depId]) {
  return;
  }
   
  if (depMod) {
  if (!depMod.inited || !depMod.enabled) {
  //Dependency is not inited,
  //so this module cannot be
  //given a forced value yet.
  uninited[id] = true;
  return;
} }
} else {  
ret = req.execCb(fullName, manager.callback, args, defined[fullName]); //Get the value for the current dependency
} value = forceExec(depMod, traced, uninited);
   
if (fullName) { //Even with forcing it may not be done,
//If setting exports via "module" is in play, //in particular if the module is waiting
//favor that over return value and exports. After that, //on a plugin resource.
//favor a non-undefined return value over exports use. if (!uninited[depId]) {
cjsModule = manager.cjsModule; mod.defineDepById(depId, value);
if (cjsModule && }
cjsModule.exports !== undefined && }
//Make sure it is not already the exports value });
cjsModule.exports !== defined[fullName]) {  
ret = defined[fullName] = manager.cjsModule.exports; mod.check(true);
} else if (ret === undefined && manager.usingExports) {  
//exports already set the defined value. return defined[id];
ret = defined[fullName]; }
} else {  
//Use the return value from the function. function modCheck(mod) {
defined[fullName] = ret; mod.check();
//If this module needed full execution in a build }
//environment, mark that now.  
if (needFullExec[fullName]) { function checkLoaded() {
fullExec[fullName] = true; var map, modId, err, usingPathFallback,
  waitInterval = config.waitSeconds * 1000,
  //It is possible to disable the wait interval by using waitSeconds of 0.
  expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  noLoads = [],
  stillLoading = false,
  needCycleCheck = true;
   
  //Do not bother if this call was a result of a cycle break.
  if (inCheckLoaded) {
  return;
  }
   
  inCheckLoaded = true;
   
  //Figure out the state of all the modules.
  eachProp(registry, function (mod) {
  map = mod.map;
  modId = map.id;
   
  //Skip things that are not enabled or in error state.
  if (!mod.enabled) {
  return;
  }
   
  if (!mod.error) {
  //If the module should be executed, and it has not
  //been inited and time is up, remember it.
  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) {
  //No reason to keep looking for unfinished
  //loading. If the only stillLoading is a
  //plugin resource though, keep going,
  //because it may be that a plugin resource
  //is waiting on a non-plugin cycle.
  return (needCycleCheck = false);
} }
} }
} }
} else if (fullName) { });
//May just be an object definition for the module. Only  
//worry about defining if have a module name. if (expired && noLoads.length) {
ret = defined[fullName] = cb; //If wait time expired, throw error of unloaded modules.
  err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
//If this module needed full execution in a build err.contextName = context.contextName;
//environment, mark that now. return onError(err);
if (needFullExec[fullName]) { }
fullExec[fullName] = true;  
} //Not expired, check for a cycle.
} if (needCycleCheck) {
   
//Clean up waiting. Do this before error calls, and before each(waitAry, function (mod) {
//calling back listeners, so that bookkeeping is correct if (mod.defined) {
//in the event of an error and error is reported in correct order,  
//since the listeners will likely have errors if the  
//onError function does not throw.  
if (waiting[manager.id]) {  
delete waiting[manager.id];  
manager.isDone = true;  
context.waitCount -= 1;  
if (context.waitCount === 0) {  
//Clear the wait array used for cycles.  
waitAry = [];  
}  
}  
   
//Do not need to track manager callback now that it is defined.  
delete managerCallbacks[fullName];  
   
//Allow instrumentation like the optimizer to know the order  
//of modules executed and their dependencies.  
if (req.onResourceLoad && !manager.placeholder) {  
req.onResourceLoad(context, map, manager.depArray);  
}  
   
if (err) {  
errFile = (fullName ? makeModuleMap(fullName).url : '') ||  
err.fileName || err.sourceURL;  
errModuleTree = err.moduleTree;  
err = makeError('defineerror', 'Error evaluating ' +  
'module "' + fullName + '" at location "' +  
errFile + '":\n' +  
err + '\nfileName:' + errFile +  
'\nlineNumber: ' + (err.lineNumber || err.line), err);  
err.moduleName = fullName;  
err.moduleTree = errModuleTree;  
return req.onError(err);  
}  
   
//Let listeners know of this manager's value.  
for (i = 0; (cb = listeners[i]); i++) {  
cb(ret);  
}  
   
return undefined;  
}  
   
/**  
* Helper that creates a callack function that is called when a dependency  
* is ready, and sets the i-th dependency for the manager as the  
* value passed to the callback generated by this function.  
*/  
function makeArgCallback(manager, i) {  
return function (value) {  
//Only do the work if it has not been done  
//already for a dependency. Cycle breaking  
//logic in forceExec could mean this function  
//is called more than once for a given dependency.  
if (!manager.depDone[i]) {  
manager.depDone[i] = true;  
manager.deps[i] = value;  
manager.depCount -= 1;  
if (!manager.depCount) {  
//All done, execute!  
execManager(manager);  
}  
}  
};  
}  
   
function callPlugin(pluginName, depManager) {  
var map = depManager.map,  
fullName = map.fullName,  
name = map.name,  
plugin = plugins[pluginName] ||  
(plugins[pluginName] = defined[pluginName]),  
load;  
   
//No need to continue if the manager is already  
//in the process of loading.  
if (depManager.loading) {  
return;  
}  
depManager.loading = true;  
   
load = function (ret) {  
depManager.callback = function () {  
return ret;  
};  
execManager(depManager);  
   
loaded[depManager.id] = true;  
   
//The loading of this plugin  
//might have placed other things  
//in the paused queue. In particular,  
//a loader plugin that depends on  
//a different plugin loaded resource.  
resume();  
};  
   
//Allow plugins to load other code without having to know the  
//context or how to "complete" the load.  
load.fromText = function (moduleName, text) {  
/*jslint evil: true */  
var hasInteractive = useInteractive;  
   
//Indicate a the module is in process of loading.  
loaded[moduleName] = false;  
context.scriptCount += 1;  
   
//Indicate this is not a "real" module, so do not track it  
//for builds, it does not map to a real file.  
context.fake[moduleName] = true;  
   
//Turn off interactive script matching for IE for any define  
//calls in the text, then turn it back on at the end.  
if (hasInteractive) {  
useInteractive = false;  
}  
   
req.exec(text);  
   
if (hasInteractive) {  
useInteractive = true;  
}  
   
//Support anonymous modules.  
context.completeLoad(moduleName);  
};  
   
//No need to continue if the plugin value has already been  
//defined by a build.  
if (fullName in defined) {  
load(defined[fullName]);  
} else {  
//Use parentName here since the plugin's name is not reliable,  
//could be some weird string with no path that actually wants to  
//reference the parentName's path.  
plugin.load(name, makeRequire(map.parentMap, true), load, config);  
}  
}  
   
/**  
* Adds the manager to the waiting queue. Only fully  
* resolved items should be in the waiting queue.  
*/  
function addWait(manager) {  
if (!waiting[manager.id]) {  
waiting[manager.id] = manager;  
waitAry.push(manager);  
context.waitCount += 1;  
}  
}  
   
/**  
* Function added to every manager object. Created out here  
* to avoid new function creation for each manager instance.  
*/  
function managerAdd(cb) {  
this.listeners.push(cb);  
}  
   
function getManager(map, shouldQueue) {  
var fullName = map.fullName,  
prefix = map.prefix,  
plugin = prefix ? plugins[prefix] ||  
(plugins[prefix] = defined[prefix]) : null,  
manager, created, pluginManager;  
   
if (fullName) {  
manager = managerCallbacks[fullName];  
}  
   
if (!manager) {  
created = true;  
manager = {  
//ID is just the full name, but if it is a plugin resource  
//for a plugin that has not been loaded,  
//then add an ID counter to it.  
id: (prefix && !plugin ?  
(managerCounter++) + '__p@:' : '') +  
(fullName || '__r@' + (managerCounter++)),  
map: map,  
depCount: 0,  
depDone: [],  
depCallbacks: [],  
deps: [],  
listeners: [],  
add: managerAdd  
};  
   
specified[manager.id] = true;  
   
//Only track the manager/reuse it if this is a non-plugin  
//resource. Also only track plugin resources once  
//the plugin has been loaded, and so the fullName is the  
//true normalized value.  
if (fullName && (!prefix || plugins[prefix])) {  
managerCallbacks[fullName] = manager;  
}  
}  
   
//If there is a plugin needed, but it is not loaded,  
//first load the plugin, then continue on.  
if (prefix && !plugin) {  
pluginManager = getManager(makeModuleMap(prefix), true);  
pluginManager.add(function (plugin) {  
//Create a new manager for the normalized  
//resource ID and have it call this manager when  
//done.  
var newMap = makeModuleMap(map.originalName, map.parentMap),  
normalizedManager = getManager(newMap, true);  
   
//Indicate this manager is a placeholder for the real,  
//normalized thing. Important for when trying to map  
//modules and dependencies, for instance, in a build.  
manager.placeholder = true;  
   
normalizedManager.add(function (resource) {  
manager.callback = function () {  
return resource;  
};  
execManager(manager);  
});  
});  
} else if (created && shouldQueue) {  
//Indicate the resource is not loaded yet if it is to be  
//queued.  
loaded[manager.id] = false;  
queueDependency(manager);  
addWait(manager);  
}  
   
return manager;  
}  
   
function main(inName, depArray, callback, relModuleMap) {  
var moduleMap = makeModuleMap(inName, relModuleMap),  
name = moduleMap.name,  
fullName = moduleMap.fullName,  
manager = getManager(moduleMap),  
id = manager.id,  
deps = manager.deps,  
i, depArg, depName, depPrefix, cjsMod;  
   
if (fullName) {  
//If module already defined for context, or already loaded,  
//then leave. Also leave if jQuery is registering but it does  
//not match the desired version number in the config.  
if (fullName in defined || loaded[id] === true ||  
(fullName === "jquery" && config.jQuery &&  
config.jQuery !== callback().fn.jquery)) {  
return;  
}  
   
//Set specified/loaded here for modules that are also loaded  
//as part of a layer, where onScriptLoad is not fired  
//for those cases. Do this after the inline define and  
//dependency tracing is done.  
specified[id] = true;  
loaded[id] = true;  
   
//If module is jQuery set up delaying its dom ready listeners.  
if (fullName === "jquery" && callback) {  
jQueryCheck(callback());  
}  
}  
   
//Attach real depArray and callback to the manager. Do this  
//only if the module has not been defined already, so do this after  
//the fullName checks above. IE can call main() more than once  
//for a module.  
manager.depArray = depArray;  
manager.callback = callback;  
   
//Add the dependencies to the deps field, and register for callbacks  
//on the dependencies.  
for (i = 0; i < depArray.length; i++) {  
depArg = depArray[i];  
//There could be cases like in IE, where a trailing comma will  
//introduce a null dependency, so only treat a real dependency  
//value as a dependency.  
if (depArg) {  
//Split the dependency name into plugin and name parts  
depArg = makeModuleMap(depArg, (name ? moduleMap : relModuleMap));  
depName = depArg.fullName;  
depPrefix = depArg.prefix;  
   
//Fix the name in depArray to be just the name, since  
//that is how it will be called back later.  
depArray[i] = depName;  
   
//Fast path CommonJS standard dependencies.  
if (depName === "require") {  
deps[i] = makeRequire(moduleMap);  
} else if (depName === "exports") {  
//CommonJS module spec 1.1  
deps[i] = defined[fullName] = {};  
manager.usingExports = true;  
} else if (depName === "module") {  
//CommonJS module spec 1.1  
manager.cjsModule = cjsMod = deps[i] = {  
id: name,  
uri: name ? context.nameToUrl(name, null, relModuleMap) : undefined,  
exports: defined[fullName]  
};  
} else if (depName in defined && !(depName in waiting) &&  
(!(fullName in needFullExec) ||  
(fullName in needFullExec && fullExec[depName]))) {  
//Module already defined, and not in a build situation  
//where the module is a something that needs full  
//execution and this dependency has not been fully  
//executed. See r.js's requirePatch.js for more info  
//on fullExec.  
deps[i] = defined[depName];  
} else {  
//Mark this dependency as needing full exec if  
//the current module needs full exec.  
if (fullName in needFullExec) {  
needFullExec[depName] = true;  
//Reset state so fully executed code will get  
//picked up correctly.  
delete defined[depName];  
urlFetched[depArg.url] = false;  
}  
   
//Either a resource that is not loaded yet, or a plugin  
//resource for either a plugin that has not  
//loaded yet.  
manager.depCount += 1;  
manager.depCallbacks[i] = makeArgCallback(manager, i);  
getManager(depArg, true).add(manager.depCallbacks[i]);  
}  
}  
}  
   
//Do not bother tracking the manager if it is all done.  
if (!manager.depCount) {  
//All done, execute!  
execManager(manager);  
} else {  
addWait(manager);  
}  
}  
   
/**  
* Convenience method to call main for a define call that was put on  
* hold in the defQueue.  
*/  
function callDefMain(args) {  
main.apply(null, args);  
}  
   
/**  
* jQuery 1.4.3+ supports ways to hold off calling  
* calling jQuery ready callbacks until all scripts are loaded. Be sure  
* to track it if the capability exists.. Also, since jQuery 1.4.3 does  
* not register as a module, need to do some global inference checking.  
* Even if it does register as a module, not guaranteed to be the precise  
* name of the global. If a jQuery is tracked for this context, then go  
* ahead and register it as a module too, if not already in process.  
*/  
jQueryCheck = function (jqCandidate) {  
if (!context.jQuery) {  
var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null);  
   
if ($) {  
//If a specific version of jQuery is wanted, make sure to only  
//use this jQuery if it matches.  
if (config.jQuery && $.fn.jquery !== config.jQuery) {  
return; return;
} }
   
if ("holdReady" in $ || "readyWait" in $) { var cycleMod = findCycle(mod, {}, {}),
context.jQuery = $; traced = {};
   
//Manually create a "jquery" module entry if not one already if (cycleMod) {
//or in process. Note this could trigger an attempt at forceExec(cycleMod, traced, {});
//a second jQuery registration, but does no harm since  
//the first one wins, and it is the same value anyway. //traced modules may have been
callDefMain(["jquery", [], function () { //removed from the registry, but
return jQuery; //their listeners still need to
}]); //be called.
  eachProp(traced, modCheck);
//Ask jQuery to hold DOM ready callbacks.  
if (context.scriptCount) {  
jQueryHoldReady($, true);  
context.jQueryIncremented = true;  
}  
} }
} });
}  
}; //Now that dependencies have
  //been satisfied, trigger the
function forceExec(manager, traced) { //completion check that then
if (manager.isDone) { //notifies listeners.
return undefined; eachProp(registry, modCheck);
} }
   
var fullName = manager.map.fullName, //If still waiting on loads, and the waiting load is something
depArray = manager.depArray, //other than a plugin resource, or there are still outstanding
i, depName, depManager, prefix, prefixManager, value; //scripts, then just try back later.
  if ((!expired || usingPathFallback) && stillLoading) {
if (fullName) {  
if (traced[fullName]) {  
return defined[fullName];  
}  
   
traced[fullName] = true;  
}  
   
//Trace through the dependencies.  
if (depArray) {  
for (i = 0; i < depArray.length; i++) {  
//Some array members may be null, like if a trailing comma  
//IE, so do the explicit [i] access and check if it has a value.  
depName = depArray[i];  
if (depName) {  
//First, make sure if it is a plugin resource that the  
//plugin is not blocked.  
prefix = makeModuleMap(depName).prefix;  
if (prefix && (prefixManager = waiting[prefix])) {  
forceExec(prefixManager, traced);  
}  
depManager = waiting[depName];  
if (depManager && !depManager.isDone && loaded[depName]) {  
value = forceExec(depManager, traced);  
manager.depCallbacks[i](value);  
}  
}  
}  
}  
   
return fullName ? defined[fullName] : undefined;  
}  
   
/**  
* Checks if all modules for a context are loaded, and if so, evaluates the  
* new ones in right dependency order.  
*  
* @private  
*/  
function checkLoaded() {  
var waitInterval = config.waitSeconds * 1000,  
//It is possible to disable the wait interval by using waitSeconds of 0.  
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),  
noLoads = "", hasLoadedProp = false, stillLoading = false, prop,  
err, manager;  
   
//If there are items still in the paused queue processing wait.  
//This is particularly important in the sync case where each paused  
//item is processed right away but there may be more waiting.  
if (context.pausedCount > 0) {  
return undefined;  
}  
   
//Determine if priority loading is done. If so clear the priority. If  
//not, then do not check  
if (config.priorityWait) {  
if (isPriorityDone()) {  
//Call resume, since it could have  
//some waiting dependencies to trace.  
resume();  
} else {  
return undefined;  
}  
}  
   
//See if anything is still in flight.  
for (prop in loaded) {  
if (!(prop in empty)) {  
hasLoadedProp = true;  
if (!loaded[prop]) {  
if (expired) {  
noLoads += prop + " ";  
} else {  
stillLoading = true;  
break;  
}  
}  
}  
}  
   
//Check for exit conditions.  
if (!hasLoadedProp && !context.waitCount) {  
//If the loaded object had no items, then the rest of  
//the work below does not need to be done.  
return undefined;  
}  
if (expired && noLoads) {  
//If wait time expired, throw error of unloaded modules.  
err = makeError("timeout", "Load timeout for modules: " + noLoads);  
err.requireType = "timeout";  
err.requireModules = noLoads;  
return req.onError(err);  
}  
if (stillLoading || context.scriptCount) {  
//Something is still waiting to load. Wait for it, but only //Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect. //if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0; checkLoadedTimeoutId = 0;
checkLoaded(); checkLoaded();
}, 50); }, 50);
} }
return undefined; }
}  
  inCheckLoaded = false;
//If still have items in the waiting cue, but all modules have }
//been loaded, then it means there are some circular dependencies  
//that need to be broken. Module = function (map) {
//However, as a waiting thing is fired, then it can add items to this.events = undefEvents[map.id] || {};
//the waiting cue, and those items should not be fired yet, so this.map = map;
//make sure to redo the checkLoaded call after breaking a single this.shim = config.shim[map.id];
//cycle, if nothing else loaded then this logic will pick it up this.depExports = [];
//again. this.depMaps = [];
if (context.waitCount) { this.depMatched = [];
//Cycle through the waitAry, and call items in sequence. this.pluginMaps = {};
for (i = 0; (manager = waitAry[i]); i++) { this.depCount = 0;
forceExec(manager, {});  
} /* this.exports this.factory
  this.depMaps = [],
//If anything got placed in the paused queue, run it down. this.enabled, this.fetched
if (context.paused.length) { */
resume(); };
}  
  Module.prototype = {
//Only allow this recursion to a certain depth. Only init: function (depMaps, factory, errback, options) {
//triggered by errors in calling a module in which its options = options || {};
//modules waiting on it cannot finish loading, or some circular  
//dependencies that then may add more dependencies. //Do not do more inits if already done. Can happen if there
//The value of 5 is a bit arbitrary. Hopefully just one extra //are multiple define calls for the same module. That is not
//pass, or two for the case of circular dependencies generating //a normal, common case, but it is also not unexpected.
//more work that gets resolved in the sync node case. if (this.inited) {
if (checkLoadedDepth < 5) { return;
checkLoadedDepth += 1; }
checkLoaded();  
} this.factory = factory;
}  
  if (errback) {
checkLoadedDepth = 0; //Register for errors on this module.
  this.on('error', errback);
//Check for DOM ready, and nothing is waiting across contexts. } else if (this.events.error) {
req.checkReadyState(); //If no errback already, but there are error listeners
  //on this module, set up an errback to pass to the deps.
return undefined; errback = bind(this, function (err) {
} this.emit('error', err);
  });
/** }
* Resumes tracing of dependencies and then checks if everything is loaded.  
*/ //Do a copy of the dependency array, so that
resume = function () { //source inputs are not modified. For example
var manager, map, url, i, p, args, fullName; //"shim" deps are passed in here directly, and
  //doing a direct modification of the depMaps array
resumeDepth += 1; //would affect that config.
  this.depMaps = depMaps && depMaps.slice(0);
if (context.scriptCount <= 0) { this.depMaps.rjsSkipMap = depMaps.rjsSkipMap;
//Synchronous envs will push the number below zero with the  
//decrement above, be sure to set it back to zero for good measure. this.errback = errback;
//require() calls that also do not end up loading scripts could  
//push the number negative too. //Indicate this module has be initialized
context.scriptCount = 0; this.inited = true;
}  
  this.ignore = options.ignore;
//Make sure any remaining defQueue items get properly processed.  
while (defQueue.length) { //Could have option to init this module in enabled mode,
args = defQueue.shift(); //or could have been previously marked as enabled. However,
if (args[0] === null) { //the dependencies are not known until init is called. So
return req.onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); //if enabled previously, now trigger dependencies as enabled.
  if (options.enabled || this.enabled) {
  //Enable this module and dependencies.
  //Will call this.check()
  this.enable();
} else { } else {
callDefMain(args); this.check();
} }
} },
   
//Skip the resume of paused dependencies defineDepById: function (id, depExports) {
//if current context is in priority wait. var i;
if (!config.priorityWait || isPriorityDone()) {  
while (context.paused.length) { //Find the index for this dependency.
p = context.paused; each(this.depMaps, function (map, index) {
context.pausedCount += p.length; if (map.id === id) {
//Reset paused list i = index;
context.paused = []; return true;
  }
for (i = 0; (manager = p[i]); i++) { });
map = manager.map;  
url = map.url; return this.defineDep(i, depExports);
fullName = map.fullName; },
   
//If the manager is for a plugin managed resource, defineDep: function (i, depExports) {
//ask the plugin to load it now. //Because of cycles, defined callback for a given
if (map.prefix) { //export can be called more than once.
callPlugin(map.prefix, manager); if (!this.depMatched[i]) {
} else { this.depMatched[i] = true;
//Regular dependency. this.depCount -= 1;
if (!urlFetched[url] && !loaded[fullName]) { this.depExports[i] = depExports;
req.load(context, fullName, url); }
  },
//Mark the URL as fetched, but only if it is  
//not an empty: URL, used by the optimizer. fetch: function () {
//In that case we need to be sure to call if (this.fetched) {
//load() for each module that is mapped to return;
//empty: so that dependencies are satisfied }
//correctly. this.fetched = true;
if (url.indexOf('empty:') !== 0) {  
urlFetched[url] = true; context.startTime = (new Date()).getTime();
   
  var map = this.map;
   
  //If the manager is for a plugin managed resource,
  //ask the plugin to load it now.
  if (this.shim) {
  makeRequire(this, true)(this.shim.deps || [], bind(this, function () {
  return map.prefix ? this.callPlugin() : this.load();
  }));
  } else {
  //Regular dependency.
  return map.prefix ? this.callPlugin() : this.load();
  }
  },
   
  load: function () {
  var url = this.map.url;
   
  //Regular dependency.
  if (!urlFetched[url]) {
  urlFetched[url] = true;
  context.load(this.map.id, url);
  }
  },
   
  /**
  * Checks is the module is ready to define itself, and if so,
  * define it. If the silent argument is true, then it will just
  * define, but not notify listeners, and not ask for a context-wide
  * check of all loaded modules. That is useful for cycle breaking.
  */
  check: function (silent) {
  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) {
  this.fetch();
  } else if (this.error) {
  this.emit('error', this.error);
  } else if (!this.defining) {
  //The factory could trigger another require call
  //that would result in checking this module to
  //define itself again. If already in the process
  //of doing that, skip this work.
  this.defining = true;
   
  if (this.depCount < 1 && !this.defined) {
  if (isFunction(factory)) {
  //If there is an error listener, favor passing
  //to that instead of throwing an error.
  if (this.events.error) {
  try {
  exports = context.execCb(id, factory, depExports, exports);
  } catch (e) {
  err = e;
  }
  } else {
  exports = context.execCb(id, factory, depExports, exports);
  }
   
  if (this.map.isDefine) {
  //If setting exports via 'module' is in play,
  //favor that over return value and exports. After that,
  //favor a non-undefined return value over exports use.
  cjsModule = this.module;
  if (cjsModule &&
  cjsModule.exports !== undefined &&
  //Make sure it is not already the exports value
  cjsModule.exports !== this.exports) {
  exports = cjsModule.exports;
  } else if (exports === undefined && this.usingExports) {
  //exports already set the defined value.
  exports = this.exports;
} }
} }
   
  if (err) {
  err.requireMap = this.map;
  err.requireModules = [this.map.id];
  err.requireType = 'define';
  return onError((this.error = err));
  }
   
  } else {
  //Just a literal value
  exports = factory;
  }
   
  this.exports = exports;
   
  if (this.map.isDefine && !this.ignore) {
  defined[id] = exports;
   
  if (req.onResourceLoad) {
  req.onResourceLoad(context, this.map, this.depMaps);
  }
  }
   
  //Clean up
  delete registry[id];
   
  this.defined = true;
  context.waitCount -= 1;
  if (context.waitCount === 0) {
  //Clear the wait array used for cycles.
  waitAry = [];
} }
} }
   
//Move the start time for timeout forward. //Finished the define stage. Allow calling check again
context.startTime = (new Date()).getTime(); //to allow define notifications below in the case of a
context.pausedCount -= p.length; //cycle.
} this.defining = false;
}  
  if (!silent) {
//Only check if loaded when resume depth is 1. It is likely that if (this.defined && !this.defineEmitted) {
//it is only greater than 1 in sync environments where a factory this.defineEmitted = true;
//function also then calls the callback-style require. In those this.emit('defined', this.exports);
//cases, the checkLoaded should not occur until the resume this.defineEmitComplete = true;
//depth is back at the top level. }
if (resumeDepth === 1) { }
checkLoaded(); }
} },
   
resumeDepth -= 1; callPlugin: function () {
  var map = this.map,
return undefined; id = map.id,
}; pluginMap = makeModuleMap(map.prefix, null, false, true);
   
//Define the context object. Many of these fields are on here on(pluginMap, 'defined', bind(this, function (plugin) {
//just to make debugging easier. var load, normalizedMap, normalizedMod,
context = { name = this.map.name,
  parentName = this.map.parentMap ? this.map.parentMap.name : null;
   
  //If current map is not normalized, wait for that
  //normalized name to load instead of continuing.
  if (this.map.unnormalized) {
  //Normalize the ID if the plugin allows it.
  if (plugin.normalize) {
  name = plugin.normalize(name, function (name) {
  return normalize(name, parentName, true);
  }) || '';
  }
   
  normalizedMap = makeModuleMap(map.prefix + '!' + name,
  this.map.parentMap,
  false,
  true);
  on(normalizedMap,
  'defined', bind(this, function (value) {
  this.init([], function () { return value; }, null, {
  enabled: true,
  ignore: true
  });
  }));
  normalizedMod = registry[normalizedMap.id];
  if (normalizedMod) {
  if (this.events.error) {
  normalizedMod.on('error', bind(this, function (err) {
  this.emit('error', err);
  }));
  }
  normalizedMod.enable();
  }
   
  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];
   
  //Remove temp unnormalized modules for this module,
  //since they will never be resolved otherwise now.
  eachProp(registry, function (mod) {
  if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  removeWaiting(mod.map.id);
  }
  });
   
  onError(err);
  });
   
  //Allow plugins to load other code without having to know the
  //context or how to 'complete' the load.
  load.fromText = function (moduleName, text) {
  /*jslint evil: true */
  var hasInteractive = useInteractive;
   
  //Turn off interactive script matching for IE for any define
  //calls in the text, then turn it back on at the end.
  if (hasInteractive) {
  useInteractive = false;
  }
   
  //Prime the system by creating a module instance for
  //it.
  getModule(makeModuleMap(moduleName));
   
  req.exec(text);
   
  if (hasInteractive) {
  useInteractive = true;
  }
   
  //Support anonymous modules.
  context.completeLoad(moduleName);
  };
   
  //Use parentName here since the plugin's name is not reliable,
  //could be some weird string with no path that actually wants to
  //reference the parentName's path.
  plugin.load(map.name, makeRequire(map.parentMap, true, function (deps, cb, er) {
  deps.rjsSkipMap = true;
  return context.require(deps, cb, er);
  }), load, config);
  }));
   
  context.enable(pluginMap, this);
  this.pluginMaps[pluginMap.id] = pluginMap;
  },
   
  enable: function () {
  this.enabled = true;
   
  if (!this.waitPushed) {
  waitAry.push(this);
  context.waitCount += 1;
  this.waitPushed = true;
  }
   
  //Set flag mentioning that the module is enabling,
  //so that immediate calls to the defined callbacks
  //for dependencies do not trigger inadvertent load
  //with the depCount still being zero.
  this.enabling = true;
   
  //Enable each dependency
  each(this.depMaps, bind(this, function (depMap, i) {
  var id, mod, handler;
   
  if (typeof depMap === 'string') {
  //Dependency needs to be converted to a depMap
  //and wired up to this module.
  depMap = makeModuleMap(depMap,
  (this.map.isDefine ? this.map : this.map.parentMap),
  false,
  !this.depMaps.rjsSkipMap);
  this.depMaps[i] = depMap;
   
  handler = handlers[depMap.id];
   
  if (handler) {
  this.depExports[i] = handler(this);
  return;
  }
   
  this.depCount += 1;
   
  on(depMap, 'defined', bind(this, function (depExports) {
  this.defineDep(i, depExports);
  this.check();
  }));
   
  if (this.errback) {
  on(depMap, 'error', this.errback);
  }
  }
   
  id = depMap.id;
  mod = registry[id];
   
  //Skip special modules like 'require', 'exports', 'module'
  //Also, don't call enable if it is already enabled,
  //important in circular dependency cases.
  if (!handlers[id] && mod && !mod.enabled) {
  context.enable(depMap, this);
  }
  }));
   
  //Enable each plugin that is used in
  //a dependency
  eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  var mod = 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') {
  //Now that the error handler was triggered, remove
  //the listeners, since this broken Module instance
  //can stay around for a while in the registry/waitAry.
  delete this.events[name];
  }
  }
  };
   
  function callGetModule(args) {
  getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  }
   
  function removeListener(node, func, name, ieName) {
  //Favor detachEvent because of IE9
  //issue, see attachEvent/addEventListener comment elsewhere
  //in this file.
  if (node.detachEvent && !isOpera) {
  //Probably IE. If not it will throw an error, which will be
  //useful to know.
  if (ieName) {
  node.detachEvent(ieName, func);
  }
  } else {
  node.removeEventListener(name, func, false);
  }
  }
   
  /**
  * Given an event from a script node, get the requirejs info from it,
  * and then removes the event listeners on the node.
  * @param {Event} evt
  * @returns {Object}
  */
  function getScriptData(evt) {
  //Using currentTarget instead of target for Firefox 2.0's sake. Not
  //all old browsers will be supported, but this one was easy enough
  //to support and still makes sense.
  var node = evt.currentTarget || evt.srcElement;
   
  //Remove the listeners once here.
  removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  removeListener(node, context.onScriptError, 'error');
   
  return {
  node: node,
  id: node && node.getAttribute('data-requiremodule')
  };
  }
   
  return (context = {
  config: config,
contextName: contextName, contextName: contextName,
config: config, registry: registry,
  defined: defined,
  urlFetched: urlFetched,
  waitCount: 0,
defQueue: defQueue, defQueue: defQueue,
waiting: waiting, Module: Module,
waitCount: 0,  
specified: specified,  
loaded: loaded,  
urlMap: urlMap,  
urlFetched: urlFetched,  
scriptCount: 0,  
defined: defined,  
paused: [],  
pausedCount: 0,  
plugins: plugins,  
needFullExec: needFullExec,  
fake: {},  
fullExec: fullExec,  
managerCallbacks: managerCallbacks,  
makeModuleMap: makeModuleMap, makeModuleMap: makeModuleMap,
normalize: normalize,  
/** /**
* Set a configuration for the context. * Set a configuration for the context.
* @param {Object} cfg config object to integrate. * @param {Object} cfg config object to integrate.
*/ */
configure: function (cfg) { configure: function (cfg) {
var paths, prop, packages, pkgs, packagePaths, requireWait;  
   
//Make sure the baseUrl ends in a slash. //Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) { if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== "/") { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += "/"; cfg.baseUrl += '/';
} }
} }
   
//Save off the paths and packages since they require special processing, //Save off the paths and packages since they require special processing,
//they are additive. //they are additive.
paths = config.paths; var pkgs = config.pkgs,
packages = config.packages; shim = config.shim,
pkgs = config.pkgs; paths = config.paths,
  map = config.map;
   
//Mix in the config values, favoring the new values over //Mix in the config values, favoring the new values over
//existing ones in context.config. //existing ones in context.config.
mixin(config, cfg, true); mixin(config, cfg, true);
   
//Adjust paths if necessary. //Merge paths.
if (cfg.paths) { config.paths = mixin(paths, cfg.paths, true);
for (prop in cfg.paths) {  
if (!(prop in empty)) { //Merge map
paths[prop] = cfg.paths[prop]; if (cfg.map) {
  config.map = mixin(map || {}, cfg.map, true, true);
  }
   
  //Merge shim
  if (cfg.shim) {
  eachProp(cfg.shim, function (value, id) {
  //Normalize the structure
  if (isArray(value)) {
  value = {
  deps: value
  };
} }
} if (value.exports && !value.exports.__buildReady) {
config.paths = paths; value.exports = context.makeShimExports(value.exports);
}  
   
packagePaths = cfg.packagePaths;  
if (packagePaths || cfg.packages) {  
//Convert packagePaths into a packages config.  
if (packagePaths) {  
for (prop in packagePaths) {  
if (!(prop in empty)) {  
configurePackageDir(pkgs, packagePaths[prop], prop);  
}  
} }
} shim[id] = value;
  });
//Adjust packages if necessary. config.shim = shim;
if (cfg.packages) { }
configurePackageDir(pkgs, cfg.packages);  
} //Adjust packages if necessary.
  if (cfg.packages) {
  each(cfg.packages, function (pkgObj) {
  var location;
   
  pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
  location = pkgObj.location;
   
  //Create a brand new object on pkgs, since currentPackages can
  //be passed in again, and config.pkgs is the internal transformed
  //state for all package configs.
  pkgs[pkgObj.name] = {
  name: pkgObj.name,
  location: location || pkgObj.name,
  //Remove leading dot in main, so main paths are normalized,
  //and remove any trailing .js, since different package
  //envs have different conventions: some use a module name,
  //some use a file name.
  main: (pkgObj.main || 'main')
  .replace(currDirRegExp, '')
  .replace(jsSuffixRegExp, '')
  };
  });
   
//Done with modifications, assing packages back to context config //Done with modifications, assing packages back to context config
config.pkgs = pkgs; config.pkgs = pkgs;
} }
   
//If priority loading is in effect, trigger the loads now //If there are any "waiting to execute" modules in the registry,
if (cfg.priority) { //update the maps for them, since their info, like URLs to load,
//Hold on to requireWait value, and reset it after done //may have changed.
requireWait = context.requireWait; eachProp(registry, function (mod, id) {
  //If module already has init called, since it is too
//Allow tracing some require calls to allow the fetching //late to modify them, and ignore unnormalized ones
//of the priority config. //since they are transient.
context.requireWait = false; if (!mod.inited && !mod.map.unnormalized) {
//But first, call resume to register any defined modules that may mod.map = makeModuleMap(id);
//be in a data-main built file before the priority config }
//call. Also grab any waiting define calls for this context. });
context.takeGlobalQueue();  
resume();  
   
context.require(cfg.priority);  
   
//Trigger a resume right away, for the case when  
//the script with the priority load is done as part  
//of a data-main call. In that case the normal resume  
//call will not happen because the scriptCount will be  
//at 1, since the script for data-main is being processed.  
resume();  
   
//Restore previous state.  
context.requireWait = requireWait;  
config.priorityWait = cfg.priority;  
}  
   
//If a deps array or a config callback is specified, then call //If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a //require with those args. This is useful when require is defined as a
//config object before require.js is loaded. //config object before require.js is loaded.
if (cfg.deps || cfg.callback) { if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback); context.require(cfg.deps || [], cfg.callback);
} }
}, },
   
requireDefined: function (moduleName, relModuleMap) { makeShimExports: function (exports) {
return makeModuleMap(moduleName, relModuleMap).fullName in defined; var func;
  if (typeof exports === 'string') {
  func = function () {
  return getGlobal(exports);
  };
  //Save the exports for use in nodefine checking.
  func.exports = exports;
  return func;
  } else {
  return function () {
  return exports.apply(global, arguments);
  };
  }
}, },
   
requireSpecified: function (moduleName, relModuleMap) { requireDefined: function (id, relMap) {
return makeModuleMap(moduleName, relModuleMap).fullName in specified; return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
}, },
   
require: function (deps, callback, relModuleMap) { requireSpecified: function (id, relMap) {
var moduleName, fullName, moduleMap; id = makeModuleMap(id, relMap, false, true).id;
if (typeof deps === "string") { return hasProp(defined, id) || hasProp(registry, id);
  },
   
  require: function (deps, callback, errback, relMap) {
  var moduleName, id, map, requireMod, args;
  if (typeof deps === 'string') {
if (isFunction(callback)) { if (isFunction(callback)) {
//Invalid call //Invalid call
return req.onError(makeError("requireargs", "Invalid require call")); return onError(makeError('requireargs', 'Invalid require call'), errback);
} }
   
//Synchronous access to one module. If require.get is //Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that. //available (as in the Node adapter), prefer that.
//In this case deps is the moduleName and callback is //In this case deps is the moduleName and callback is
//the relModuleMap //the relMap
if (req.get) { if (req.get) {
return req.get(context, deps, callback); return req.get(context, deps, callback);
} }
   
//Just return the module wanted. In this scenario, the //Just return the module wanted. In this scenario, the
//second arg (if passed) is just the relModuleMap. //second arg (if passed) is just the relMap.
moduleName = deps; moduleName = deps;
relModuleMap = callback; relMap = callback;
   
//Normalize module name, if it contains . or .. //Normalize module name, if it contains . or ..
moduleMap = makeModuleMap(moduleName, relModuleMap); map = makeModuleMap(moduleName, relMap, false, true);
fullName = moduleMap.fullName; id = map.id;
   
if (!(fullName in defined)) { if (!hasProp(defined, id)) {
return req.onError(makeError("notloaded", "Module name '" + return onError(makeError('notloaded', 'Module name "' +
moduleMap.fullName + id +
"' has not been loaded yet for context: " + '" has not been loaded yet for context: ' +
contextName)); contextName));
} }
return defined[fullName]; return defined[id];
} }
   
//Call main but only if there are dependencies or //Callback require. Normalize args. if callback or errback is
//a callback to call. //not a function, it means it is a relMap. Test errback first.
if (deps && deps.length || callback) { if (errback && !isFunction(errback)) {
main(null, deps, callback, relModuleMap); relMap = errback;
} errback = undefined;
  }
//If the require call does not trigger anything new to load, if (callback && !isFunction(callback)) {
//then resume the dependency processing. relMap = callback;
if (!context.requireWait) { callback = undefined;
while (!context.scriptCount && context.paused.length) { }
//For built layers, there can be some defined  
//modules waiting for intake into the context, //Any defined modules in the global queue, intake them now.
//in particular module plugins. Take them. takeGlobalQueue();
context.takeGlobalQueue();  
resume(); //Make sure any remaining defQueue items get properly processed.
  while (defQueue.length) {
  args = defQueue.shift();
  if (args[0] === null) {
  return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
  } else {
  //args are id, deps, factory. Should be normalized by the
  //define() function.
  callGetModule(args);
} }
} }
   
  //Mark all the dependencies as needing to be loaded.
  requireMod = getModule(makeModuleMap(null, relMap));
   
  requireMod.init(deps, callback, errback, {
  enabled: true
  });
   
  checkLoaded();
   
return context.require; return context.require;
}, },
   
  undef: function (id) {
  //Bind any waiting define() calls to this context,
  //fix for #408
  takeGlobalQueue();
   
  var map = makeModuleMap(id, null, true),
  mod = registry[id];
   
  delete defined[id];
  delete urlFetched[map.url];
  delete undefEvents[id];
   
  if (mod) {
  //Hold on to listeners in case the
  //module will be attempted to be reloaded
  //using a different config.
  if (mod.events.defined) {
  undefEvents[id] = mod.events;
  }
   
  removeWaiting(id);
  }
  },
   
/** /**
* Internal method to transfer globalQueue items to this context's * Called to enable a module if it is still in the registry
* defQueue. * awaiting enablement. parent module is passed in for context,
  * used by the optimizer.
*/ */
takeGlobalQueue: function () { enable: function (depMap, parent) {
//Push all the globalDefQueue items into the context's defQueue var mod = registry[depMap.id];
if (globalDefQueue.length) { if (mod) {
//Array splice in the values since the context code has a getModule(depMap).enable();
//local var ref to defQueue, so cannot just reassign the one  
//on context.  
apsp.apply(context.defQueue,  
[context.defQueue.length - 1, 0].concat(globalDefQueue));  
globalDefQueue = [];  
} }
}, },
   
/** /**
* Internal method used by environment adapters to complete a load event. * Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous * A load event could be a script load or just a load pass from a synchronous
* load call. * load call.
* @param {String} moduleName the name of the module to potentially complete. * @param {String} moduleName the name of the module to potentially complete.
*/ */
completeLoad: function (moduleName) { completeLoad: function (moduleName) {
var args; var found, args, mod,
  shim = config.shim[moduleName] || {},
context.takeGlobalQueue(); shExports = shim.exports && shim.exports.exports;
   
  takeGlobalQueue();
   
while (defQueue.length) { while (defQueue.length) {
args = defQueue.shift(); args = defQueue.shift();
   
if (args[0] === null) { if (args[0] === null) {
args[0] = moduleName; args[0] = moduleName;
break; //If already found an anonymous module and bound it
  //to this name, then this is some other anon module
  //waiting for its completeLoad to fire.
  if (found) {
  break;
  }
  found = true;
} else if (args[0] === moduleName) { } else if (args[0] === moduleName) {
//Found matching define call for this script! //Found matching define call for this script!
break; found = true;
  }
   
  callGetModule(args);
  }
   
  //Do this after the cycle of callGetModule in case the result
  //of those calls/init calls changes the registry.
  mod = registry[moduleName];
   
  if (!found && !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 { } else {
//Some other named define call, most likely the result //A script that does not call define(), so just simulate
//of a build layer that included many define calls. //the call for it.
callDefMain(args); callGetModule([moduleName, (shim.deps || []), shim.exports]);
args = null;  
} }
} }
if (args) {  
callDefMain(args); checkLoaded();
} else {  
//A script that does not call define(), so just simulate  
//the call for it. Special exception for jQuery dynamic load.  
callDefMain([moduleName, [],  
moduleName === "jquery" && typeof jQuery !== "undefined" ?  
function () {  
return jQuery;  
} : null]);  
}  
   
//If a global jQuery is defined, check for it. Need to do it here  
//instead of main() since stock jQuery does not register as  
//a module via define.  
jQueryCheck();  
   
//Doing this scriptCount decrement branching because sync envs  
//need to decrement after resume, otherwise it looks like  
//loading is complete after the first dependency is fetched.  
//For browsers, it works fine to decrement after, but it means  
//the checkLoaded setTimeout 50 ms cost is taken. To avoid  
//that cost, decrement beforehand.  
if (req.isAsync) {  
context.scriptCount -= 1;  
}  
resume();  
if (!req.isAsync) {  
context.scriptCount -= 1;  
}  
}, },
   
/** /**
* Converts a module name + .extension into an URL path. * Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using * *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl. * plain URLs like nameToUrl.
*/ */
toUrl: function (moduleNamePlusExt, relModuleMap) { toUrl: function (moduleNamePlusExt, relModuleMap) {
var index = moduleNamePlusExt.lastIndexOf("."), var index = moduleNamePlusExt.lastIndexOf('.'),
ext = null; ext = null;
   
if (index !== -1) { if (index !== -1) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index); moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
} }
   
return context.nameToUrl(moduleNamePlusExt, ext, relModuleMap); return context.nameToUrl(normalize(moduleNamePlusExt, relModuleMap && relModuleMap.id, true),
  ext);
}, },
   
/** /**
* Converts a module name to a file path. Supports cases where * Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL. * moduleName may actually be just an URL.
  * Note that it **does not** call normalize on the moduleName,
  * it is assumed to have already been normalized. This is an
  * internal API, not a public one. Use toUrl for the public API.
*/ */
nameToUrl: function (moduleName, ext, relModuleMap) { nameToUrl: function (moduleName, ext) {
var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
config = context.config; parentPath;
   
//Normalize module name if have a base relative module name to work from.  
moduleName = normalize(moduleName, relModuleMap && relModuleMap.fullName);  
   
//If a colon is in the URL, it indicates a protocol is used and it is just //If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  //or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths. //The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) { if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it. //Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass //Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked. //an extension, this method probably needs to be reworked.
url = moduleName + (ext ? ext : ""); url = moduleName + (ext || '');
} else { } else {
//A module that needs to be converted to a path. //A module that needs to be converted to a path.
paths = config.paths; paths = config.paths;
pkgs = config.pkgs; pkgs = config.pkgs;
   
syms = moduleName.split("/"); syms = moduleName.split('/');
//For each module name segment, see if there is a path //For each module name segment, see if there is a path
//registered for it. Start with most specific name //registered for it. Start with most specific name
//and work up from it. //and work up from it.
for (i = syms.length; i > 0; i--) { for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join("/"); parentModule = syms.slice(0, i).join('/');
if (paths[parentModule]) { pkg = pkgs[parentModule];
syms.splice(0, i, paths[parentModule]); parentPath = paths[parentModule];
  if (parentPath) {
  //If an array, it means there are a few choices,
  //Choose the one that is desired
  if (isArray(parentPath)) {
  parentPath = parentPath[0];
  }
  syms.splice(0, i, parentPath);
break; break;
} else if ((pkg = pkgs[parentModule])) { } else if (pkg) {
//If module name is just the package name, then looking //If module name is just the package name, then looking
//for the main module. //for the main module.
if (moduleName === pkg.name) { if (moduleName === pkg.name) {
pkgPath = pkg.location + '/' + pkg.main; pkgPath = pkg.location + '/' + pkg.main;
} else { } else {
pkgPath = pkg.location; pkgPath = pkg.location;
} }
syms.splice(0, i, pkgPath); syms.splice(0, i, pkgPath);
break; break;
} }
} }
   
//Join the path parts together, then figure out if baseUrl is needed. //Join the path parts together, then figure out if baseUrl is needed.
url = syms.join("/") + (ext || ".js"); url = syms.join('/');
url = (url.charAt(0) === '/' || url.match(/^\w+:/) ? "" : config.baseUrl) + url; url += (ext || (/\?/.test(url) ? '' : '.js'));
  url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
} }
   
return config.urlArgs ? url + return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') + ((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url; config.urlArgs) : url;
} },
};  
  //Delegates to req.load. Broken out as a separate function to
//Make these visible on the context so can be called at the very //allow overriding in the optimizer.
//end of the file to bootstrap load: function (id, url) {
context.jQueryCheck = jQueryCheck; req.load(context, id, url);
context.resume = resume; },
   
return context; /**
  * Executes a module callack function. Broken out as a separate function
  * solely to allow the build system to sequence the files in the built
  * layer in the right sequence.
  *
  * @private
  */
  execCb: function (name, callback, args, exports) {
  return callback.apply(exports, args);
  },
   
  /**
  * callback for script loads, used to check status of loading.
  *
  * @param {Event} evt the event from the browser for the script
  * that was loaded.
  */
  onScriptLoad: function (evt) {
  //Using currentTarget instead of target for Firefox 2.0's sake. Not
  //all old browsers will be supported, but this one was easy enough
  //to support and still makes sense.
  if (evt.type === 'load' ||
  (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  //Reset interactive script so a script node is not held onto for
  //to long.
  interactiveScript = null;
   
  //Pull out the name of the module and the context.
  var data = getScriptData(evt);
  context.completeLoad(data.id);
  }
  },
   
  /**
  * Callback for script errors.
  */
  onScriptError: function (evt) {
  var data = getScriptData(evt);
  if (!hasPathFallback(data.id)) {
  return onError(makeError('scripterror', 'Script error', evt, [data.id]));
  }
  }
  });
} }
   
/** /**
* Main entry point. * Main entry point.
* *
* If the only argument to require is a string, then the module that * If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context. * is represented by that string is fetched for the appropriate context.
* *
* If the first argument is an array, then it will be treated as an array * If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can * of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available. * be specified to execute when all of those dependencies are available.
* *
* Make a local req variable to help Caja compliance (it assumes things * Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short * on a require that are not standardized), and to give a short
* name for minification/local scope use. * name for minification/local scope use.
*/ */
req = requirejs = function (deps, callback) { req = requirejs = function (deps, callback, errback, optional) {
   
//Find the right context, use default //Find the right context, use default
var contextName = defContextName, var context, config,
context, config; contextName = defContextName;
   
// Determine if have config object in the call. // Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== "string") { if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object // deps is a config object
config = deps; config = deps;
if (isArray(callback)) { if (isArray(callback)) {
// Adjust args if there are dependencies // Adjust args if there are dependencies
deps = callback; deps = callback;
callback = arguments[2]; callback = errback;
  errback = optional;
} else { } else {
deps = []; deps = [];
} }
} }
   
if (config && config.context) { if (config && config.context) {
contextName = config.context; contextName = config.context;
} }
   
context = contexts[contextName] || context = contexts[contextName];
(contexts[contextName] = newContext(contextName)); if (!context) {
  context = contexts[contextName] = req.s.newContext(contextName);
  }
   
if (config) { if (config) {
context.configure(config); context.configure(config);
} }
   
return context.require(deps, callback); return context.require(deps, callback, errback);
}; };
   
/** /**
* Support require.config() to make it easier to cooperate with other * Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names. * AMD loaders on globally agreed names.
*/ */
req.config = function (config) { req.config = function (config) {
return req(config); return req(config);
}; };
   
/** /**
* Export require as a global, but only if it does not already exist. * Export require as a global, but only if it does not already exist.
*/ */
if (!require) { if (!require) {
require = req; require = req;
} }
   
/**  
* Global require.toUrl(), to match global require, mostly useful  
* for debugging/work in the global space.  
*/  
req.toUrl = function (moduleNamePlusExt) {  
return contexts[defContextName].toUrl(moduleNamePlusExt);  
};  
   
req.version = version; req.version = version;
   
//Used to filter out dependencies that are already paths. //Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/; req.jsExtRegExp = /^\/|:|\?|\.js$/;
  req.isBrowser = isBrowser;
s = req.s = { s = req.s = {
contexts: contexts, contexts: contexts,
//Stores a list of URLs that should not get async script tag treatment. newContext: newContext
skipAsync: {}  
}; };
   
req.isAsync = req.isBrowser = isBrowser; //Create default context.
  req({});
   
  //Exports some context-sensitive methods on global require, using
  //default context if no context specified.
  addRequireMethods(req);
   
if (isBrowser) { if (isBrowser) {
head = s.head = document.getElementsByTagName("head")[0]; head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6. //If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug: //When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709 //http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName("base")[0]; baseElement = document.getElementsByTagName('base')[0];
if (baseElement) { if (baseElement) {
head = s.head = baseElement.parentNode; head = s.head = baseElement.parentNode;
} }
} }
   
/** /**
* Any errors that require explicitly generates will be passed to this * Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling. * function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object. * @param {Error} err the error object.
*/ */
req.onError = function (err) { req.onError = function (err) {
throw err; throw err;
}; };
   
/** /**
* Does the request to load a module for the browser case. * Does the request to load a module for the browser case.
* Make this a separate function to allow other environments * Make this a separate function to allow other environments
* to override it. * to override it.
* *
* @param {Object} context the require context to find state. * @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module. * @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module. * @param {Object} url the URL to the module.
*/ */
req.load = function (context, moduleName, url) { req.load = function (context, moduleName, url) {
req.resourcesReady(false); var config = (context && context.config) || {},
  node;
context.scriptCount += 1; if (isBrowser) {
req.attach(url, context, moduleName); //In the browser so use a script tag
  node = config.xhtml ?
//If tracking a jQuery, then make sure its ready callbacks document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
//are put on hold to prevent its ready callbacks from document.createElement('script');
//triggering too soon. node.type = config.scriptType || 'text/javascript';
if (context.jQuery && !context.jQueryIncremented) { node.charset = 'utf-8';
jQueryHoldReady(context.jQuery, true); node.async = true;
context.jQueryIncremented = true;  
  node.setAttribute('data-requirecontext', context.contextName);
  node.setAttribute('data-requiremodule', moduleName);
   
  //Set up load listener. Test attachEvent first because IE9 has
  //a subtle issue in its addEventListener and script onload firings
  //that do not match the behavior of all other browsers with
  //addEventListener support, which fire the onload event for a
  //script right after the script execution. See:
  //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  //script execution mode.
  if (node.attachEvent &&
  //Check if node.attachEvent is artificially added by custom script or
  //natively supported by browser
  //read https://github.com/jrburke/requirejs/issues/187
  //if we can NOT find [native code] then it must NOT natively supported.
  //in IE8, node.attachEvent does not have toString()
  //Note the test for "[native code" with no closing brace, see:
  //https://github.com/jrburke/requirejs/issues/273
  !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  !isOpera) {
  //Probably IE. IE (at least 6-8) do not fire
  //script onload right after executing the script, so
  //we cannot tie the anonymous define call to a name.
  //However, IE reports the script as being in 'interactive'
  //readyState at the time of the define call.
  useInteractive = true;
   
  node.attachEvent('onreadystatechange', context.onScriptLoad);
  //It would be great to add an error handler here to catch
  //404s in IE9+. However, onreadystatechange will fire before
  //the error handler, so that does not help. If addEvenListener
  //is used, then IE will fire error before load, but we cannot
  //use that pathway given the connect.microsoft.com issue
  //mentioned above about not doing the 'script execute,
  //then fire the script load event listener before execute
  //next script' that other browsers do.
  //Best hope: IE10 fixes the issues,
  //and then destroys all installs of IE 6-9.
  //node.attachEvent('onerror', context.onScriptError);
  } else {
  node.addEventListener('load', context.onScriptLoad, false);
  node.addEventListener('error', context.onScriptError, false);
  }
  node.src = url;
   
  //For some cache cases in IE 6-8, the script executes before the end
  //of the appendChild execution, so to tie an anonymous define
  //call to the module name (which is stored on the node), hold on
  //to a reference to this node, but clear after the DOM insertion.
  currentlyAddingScript = node;
  if (baseElement) {
  head.insertBefore(node, baseElement);
  } else {
  head.appendChild(node);
  }
  currentlyAddingScript = null;
   
  return node;
  } else if (isWebWorker) {
  //In a web worker, use importScripts. This is not a very
  //efficient use of importScripts, importScripts will block until
  //its script is downloaded and evaluated. However, if web workers
  //are in play, the expectation that a build has been done so that
  //only one script needs to be loaded anyway. This may need to be
  //reevaluated if other use cases become common.
  importScripts(url);
   
  //Account for anonymous modules
  context.completeLoad(moduleName);
} }
}; };
   
function getInteractiveScript() { function getInteractiveScript() {
var scripts, i, script;  
if (interactiveScript && interactiveScript.readyState === 'interactive') { if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript; return interactiveScript;
} }
   
scripts = document.getElementsByTagName('script'); eachReverse(scripts(), function (script) {
for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) {  
if (script.readyState === 'interactive') { if (script.readyState === 'interactive') {
return (interactiveScript = script); return (interactiveScript = script);
} }
} });
  return interactiveScript;
return null; }
   
  //Look for a data-main script attribute, which could also adjust the baseUrl.
  if (isBrowser) {
  //Figure out baseUrl. Get it from the script tag with require.js in it.
  eachReverse(scripts(), function (script) {
  //Set the 'head' where we can append children by
  //using the script's parent.
  if (!head) {
  head = script.parentNode;
  }
   
  //Look for a data-main attribute to set main script for the page
  //to load. If it is there, the path to data main becomes the
  //baseUrl, if it is not already set.
  dataMain = script.getAttribute('data-main');
  if (dataMain) {
  //Set final baseUrl if there is not already an explicit one.
  if (!cfg.baseUrl) {
  //Pull off the directory of data-main for use as the
  //baseUrl.
  src = dataMain.split('/');
  mainScript = src.pop();
  subPath = src.length ? src.join('/') + '/' : './';
   
  cfg.baseUrl = subPath;
  dataMain = mainScript;
  }
   
  //Strip off any trailing .js since dataMain is now
  //like a module name.
  dataMain = dataMain.replace(jsSuffixRegExp, '');
   
  //Put the data-main script in the files to load.
  cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
   
  return true;
  }
  });
} }
   
/** /**
* The function that handles definitions of modules. Differs from * The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument, * require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should * and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's * return a value to define the module corresponding to the first argument's
* name. * name.
*/ */
define = function (name, deps, callback) { define = function (name, deps, callback) {
var node, context; var node, context;
   
//Allow for anonymous functions //Allow for anonymous functions
if (typeof name !== 'string') { if (typeof name !== 'string') {
//Adjust args appropriately //Adjust args appropriately
callback = deps; callback = deps;
deps = name; deps = name;
name = null; name = null;
} }
   
//This module may not have dependencies //This module may not have dependencies
if (!isArray(deps)) { if (!isArray(deps)) {
callback = deps; callback = deps;
deps = []; deps = [];
} }
   
//If no name, and callback is a function, then figure out if it a //If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies. //CommonJS thing with dependencies.
if (!deps.length && isFunction(callback)) { if (!deps.length && isFunction(callback)) {
//Remove comments from the callback string, //Remove comments from the callback string,
//look for require calls, and pull them into the dependencies, //look for require calls, and pull them into the dependencies,
//but only if there are function args. //but only if there are function args.
if (callback.length) { if (callback.length) {
callback callback
.toString() .toString()
.replace(commentRegExp, "") .replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) { .replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep); deps.push(dep);
}); });
   
//May be a CommonJS thing even without require calls, but still //May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module //could use exports, and module. Avoid doing exports and module
//work though if it just needs require. //work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the //REQUIRES the function to expect the CommonJS variables in the
//order listed below. //order listed below.
deps = (callback.length === 1 ? ["require"] : ["require", "exports", "module"]).concat(deps); deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
} }
} }
   
//If in IE 6-8 and hit an anonymous define() call, do the interactive //If in IE 6-8 and hit an anonymous define() call, do the interactive
//work. //work.
if (useInteractive) { if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript(); node = currentlyAddingScript || getInteractiveScript();
if (node) { if (node) {
if (!name) { if (!name) {
name = node.getAttribute("data-requiremodule"); name = node.getAttribute('data-requiremodule');
} }
context = contexts[node.getAttribute("data-requirecontext")]; context = contexts[node.getAttribute('data-requirecontext')];
} }
} }
   
//Always save off evaluating the def call until the script onload handler. //Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely //This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support, //tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event //where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed //occurs. If no context, use the global queue, and get it processed
//in the onscript load callback. //in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]); (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
   
return undefined;  
}; };
   
define.amd = { define.amd = {
multiversion: true,  
plugins: true,  
jQuery: true jQuery: true
}; };
   
   
/** /**
* Executes the text. Normally just uses eval, but can be modified * Executes the text. Normally just uses eval, but can be modified
* to use a more environment specific call. * to use a better, environment-specific call. Only used for transpiling
  * loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate. * @param {String} text the text to execute/evaluate.
*/ */
req.exec = function (text) { req.exec = function (text) {
  /*jslint evil: true */
return eval(text); return eval(text);
}; };
   
/** //Set up with config info.
* Executes a module callack function. Broken out as a separate function  
* solely to allow the build system to sequence the files in the built  
* layer in the right sequence.  
*  
* @private  
*/  
req.execCb = function (name, callback, args, exports) {  
return callback.apply(exports, args);  
};  
   
   
/**  
* Adds a node to the DOM. Public function since used by the order plugin.  
* This method should not normally be called by outside code.  
*/  
req.addScriptToDom = function (node) {  
//For some cache cases in IE 6-8, the script executes before the end  
//of the appendChild execution, so to tie an anonymous define  
//call to the module name (which is stored on the node), hold on  
//to a reference to this node, but clear after the DOM insertion.  
currentlyAddingScript = node;  
if (baseElement) {  
head.insertBefore(node, baseElement);  
} else {  
head.appendChild(node);  
}  
currentlyAddingScript = null;  
};  
   
/**  
* callback for script loads, used to check status of loading.  
*  
* @param {Event} evt the event from the browser for the script  
* that was loaded.  
*  
* @private  
*/  
req.onScriptLoad = function (evt) {  
//Using currentTarget instead of target for Firefox 2.0's sake. Not  
//all old browsers will be supported, but this one was easy enough  
//to support and still makes sense.  
var node = evt.currentTarget || evt.srcElement, contextName, moduleName,  
context;  
   
if (evt.type === "load" || (node && readyRegExp.test(node.readyState))) {  
//Reset interactive script so a script node is not held onto for  
//to long.  
interactiveScript = null;  
   
//Pull out the name of the module and the context.  
contextName = node.getAttribute("data-requirecontext");  
moduleName = node.getAttribute("data-requiremodule");  
context = contexts[contextName];  
   
contexts[contextName].completeLoad(moduleName);  
   
//Clean up script binding. Favor detachEvent because of IE9  
//issue, see attachEvent/addEventListener comment elsewhere  
//in this file.  
if (node.detachEvent && !isOpera) {  
//Probably IE. If not it will throw an error, which will be  
//useful to know.  
node.detachEvent("onreadystatechange", req.onScriptLoad);  
} else {  
node.removeEventListener("load", req.onScriptLoad, false);  
}  
}  
};  
   
/**  
* Attaches the script represented by the URL to the current  
* environment. Right now only supports browser loading,  
* but can be redefined in other environments to do the right thing.  
* @param {String} url the url of the script to attach.  
* @param {Object} context the context that wants the script.  
* @param {moduleName} the name of the module that is associated with the script.  
* @param {Function} [callback] optional callback, defaults to require.onScriptLoad  
* @param {String} [type] optional type, defaults to text/javascript  
* @param {Function} [fetchOnlyFunction] optional function to indicate the script node  
* should be set up to fetch the script but do not attach it to the DOM  
* so that it can later be attached to execute it. This is a way for the  
* order plugin to support ordered loading in IE. Once the script is fetched,  
* but not executed, the fetchOnlyFunction will be called.  
*/  
req.attach = function (url, context, moduleName, callback, type, fetchOnlyFunction) {  
var node;  
if (isBrowser) {  
//In the browser so use a script tag  
callback = callback || req.onScriptLoad;  
node = context && context.config && context.config.xhtml ?  
document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") :  
document.createElement("script");  
node.type = type || "text/javascript";  
node.charset = "utf-8";  
//Use async so Gecko does not block on executing the script if something  
//like a long-polling comet tag is being run first. Gecko likes  
//to evaluate scripts in DOM order, even for dynamic scripts.  
//It will fetch them async, but only evaluate the contents in DOM  
//order, so a long-polling script tag can delay execution of scripts  
//after it. But telling Gecko we expect async gets us the behavior  
//we want -- execute it whenever it is finished downloading. Only  
//Helps Firefox 3.6+  
//Allow some URLs to not be fetched async. Mostly helps the order!  
//plugin  
node.async = !s.skipAsync[url];  
   
if (context) {  
node.setAttribute("data-requirecontext", context.contextName);  
}  
node.setAttribute("data-requiremodule", moduleName);  
   
//Set up load listener. Test attachEvent first because IE9 has  
//a subtle issue in its addEventListener and script onload firings  
//that do not match the behavior of all other browsers with  
//addEventListener support, which fire the onload event for a  
//script right after the script execution. See:  
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution  
//UNFORTUNATELY Opera implements attachEvent but does not follow the script  
//script execution mode.  
if (node.attachEvent && !isOpera) {  
//Probably IE. IE (at least 6-8) do not fire  
//script onload right after executing the script, so  
//we cannot tie the anonymous define call to a name.  
//However, IE reports the script as being in "interactive"  
//readyState at the time of the define call.  
useInteractive = true;  
   
   
if (fetchOnlyFunction) {  
//Need to use old school onreadystate here since  
//when the event fires and the node is not attached  
//to the DOM, the evt.srcElement is null, so use  
//a closure to remember the node.  
node.onreadystatechange = function (evt) {  
//Script loaded but not executed.  
//Clear loaded handler, set the real one that  
//waits for script execution.  
if (node.readyState === 'loaded') {  
node.onreadystatechange = null;  
node.attachEvent("onreadystatechange", callback);  
fetchOnlyFunction(node);  
}  
};  
} else {  
node.attachEvent("onreadystatechange", callback);  
}  
} else {  
node.addEventListener("load", callback, false);  
}  
node.src = url;  
   
//Fetch only means waiting to attach to DOM after loaded.  
if (!fetchOnlyFunction) {  
req.addScriptToDom(node);  
}  
   
return node;  
} else if (isWebWorker) {  
//In a web worker, use importScripts. This is not a very  
//efficient use of importScripts, importScripts will block until  
//its script is downloaded and evaluated. However, if web workers  
//are in play, the expectation that a build has been done so that  
//only one script needs to be loaded anyway. This may need to be  
//reevaluated if other use cases become common.  
importScripts(url);  
   
//Account for anonymous modules  
context.completeLoad(moduleName);  
}  
return null;  
};  
   
//Look for a data-main script attribute, which could also adjust the baseUrl.  
if (isBrowser) {  
//Figure out baseUrl. Get it from the script tag with require.js in it.  
scripts = document.getElementsByTagName("script");  
   
for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) {  
//Set the "head" where we can append children by  
//using the script's parent.  
if (!head) {  
head = script.parentNode;  
}  
   
//Look for a data-main attribute to set main script for the page  
//to load. If it is there, the path to data main becomes the  
//baseUrl, if it is not already set.  
if ((dataMain = script.getAttribute('data-main'))) {  
if (!cfg.baseUrl) {  
//Pull off the directory of data-main for use as the  
//baseUrl.  
src = dataMain.split('/');  
mainScript = src.pop();  
subPath = src.length ? src.join('/') + '/' : './';  
   
//Set final config.  
cfg.baseUrl = subPath;  
//Strip off any trailing .js since dataMain is now  
//like a module name.  
dataMain = mainScript.replace(jsSuffixRegExp, '');  
}  
   
//Put the data-main script in the files to load.  
cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];  
   
break;  
}  
}  
}  
   
//See if there is nothing waiting across contexts, and if not, trigger  
//resourcesReady.  
req.checkReadyState = function () {  
var contexts = s.contexts, prop;  
for (prop in contexts) {  
if (!(prop in empty)) {  
if (contexts[prop].waitCount) {  
return;  
}  
}  
}  
req.resourcesReady(true);  
};  
   
/**  
* Internal function that is triggered whenever all scripts/resources  
* have been loaded by the loader. Can be overridden by other, for  
* instance the domReady plugin, which wants to know when all resources  
* are loaded.  
*/  
req.resourcesReady = function (isReady) {  
var contexts, context, prop;  
   
//First, set the public variable indicating that resources are loading.  
req.resourcesDone = isReady;  
   
if (req.resourcesDone) {  
//If jQuery with DOM ready delayed, release it now.  
contexts = s.contexts;  
for (prop in contexts) {  
if (!(prop in empty)) {  
context = contexts[prop];  
if (context.jQueryIncremented) {  
jQueryHoldReady(context.jQuery, false);  
context.jQueryIncremented = false;  
}  
}  
}  
}  
};  
   
//FF < 3.6 readyState fix. Needed so that domReady plugin  
//works well in that environment, since require.js is normally  
//loaded via an HTML script tag so it will be there before window load,  
//where the domReady plugin is more likely to be loaded after window load.  
req.pageLoaded = function () {  
if (document.readyState !== "complete") {  
document.readyState = "complete";  
}  
};  
if (isBrowser) {  
if (document.addEventListener) {  
if (!document.readyState) {  
document.readyState = "loading";  
window.addEventListener("load", req.pageLoaded, false);  
}  
}  
}  
   
//Set up default context. If require was a configuration object, use that as base config.  
req(cfg); req(cfg);
  }(this));
//If modules are built into require.js, then need to make sure dependencies are  
//traced. Use a setTimeout in the browser world, to allow all the modules to register  
//themselves. In a non-browser env, assume that modules are not built into require.js,  
//which seems odd to do on the server.  
if (req.isAsync && typeof setTimeout !== "undefined") {  
ctx = s.contexts[(cfg.context || defContextName)];  
//Indicate that the script that includes require() is still loading,  
//so that require()'d dependencies are not traced until the end of the  
//file is parsed (approximated via the setTimeout call).  
ctx.requireWait = true;  
setTimeout(function () {  
ctx.requireWait = false;  
   
//Any modules included with the require.js file will be in the  
//global queue, assign them to this context.  
ctx.takeGlobalQueue();  
   
//Allow for jQuery to be loaded/already in the page, and if jQuery 1.4.3,  
//make sure to hold onto it for readyWait triggering.  
ctx.jQueryCheck();  
   
if (!ctx.scriptCount) {  
ctx.resume();  
}  
req.checkReadyState();  
}, 0);  
}  
}());  
   
   
if (env === 'rhino') { if (env === 'rhino') {
/** /**
* @license RequireJS rhino Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS rhino Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint */
/*global require: false, java: false, load: false */ /*global require: false, java: false, load: false */
   
(function () { (function () {
  'use strict';
require.load = function (context, moduleName, url) { require.load = function (context, moduleName, url) {
//Indicate a the module is in process of loading.  
context.scriptCount += 1;  
   
load(url); load(url);
   
//Support anonymous modules. //Support anonymous modules.
context.completeLoad(moduleName); context.completeLoad(moduleName);
}; };
   
}()); }());
} else if (env === 'node') { } else if (env === 'node') {
this.requirejsVars = { this.requirejsVars = {
require: require, require: require,
requirejs: require, requirejs: require,
define: define, define: define,
nodeRequire: nodeRequire nodeRequire: nodeRequire
}; };
require.nodeRequire = nodeRequire; require.nodeRequire = nodeRequire;
   
/** /**
* @license RequireJS node Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS node Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint regexp: false, strict: false */ /*jslint regexp: false */
/*global require: false, define: false, requirejsVars: false, process: false */ /*global require: false, define: false, requirejsVars: false, process: false */
   
/** /**
* This adapter assumes that x.js has loaded it and set up * This adapter assumes that x.js has loaded it and set up
* some variables. This adapter just allows limited RequireJS * some variables. This adapter just allows limited RequireJS
* usage from within the requirejs directory. The general * usage from within the requirejs directory. The general
* node adapater is r.js. * node adapater is r.js.
*/ */
   
(function () { (function () {
  'use strict';
   
var nodeReq = requirejsVars.nodeRequire, var nodeReq = requirejsVars.nodeRequire,
req = requirejsVars.require, req = requirejsVars.require,
def = requirejsVars.define, def = requirejsVars.define,
fs = nodeReq('fs'), fs = nodeReq('fs'),
path = nodeReq('path'), path = nodeReq('path'),
vm = nodeReq('vm'); vm = nodeReq('vm'),
  //In Node 0.7+ existsSync is on fs.
  exists = fs.existsSync || path.existsSync;
   
//Supply an implementation that allows synchronous get of a module. //Supply an implementation that allows synchronous get of a module.
req.get = function (context, moduleName, relModuleMap) { req.get = function (context, moduleName, relModuleMap) {
if (moduleName === "require" || moduleName === "exports" || moduleName === "module") { if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
req.onError(new Error("Explicit require of " + moduleName + " is not allowed.")); req.onError(new Error("Explicit require of " + moduleName + " is not allowed."));
} }
   
var ret, var ret,
moduleMap = context.makeModuleMap(moduleName, relModuleMap); moduleMap = context.makeModuleMap(moduleName, relModuleMap);
   
//Normalize module name, if it contains . or .. //Normalize module name, if it contains . or ..
moduleName = moduleMap.fullName; moduleName = moduleMap.id;
   
if (moduleName in context.defined) { if (context.defined.hasOwnProperty(moduleName)) {
ret = context.defined[moduleName]; ret = context.defined[moduleName];
} else { } else {
if (ret === undefined) { if (ret === undefined) {
//Try to dynamically fetch it. //Try to dynamically fetch it.
req.load(context, moduleName, moduleMap.url); req.load(context, moduleName, moduleMap.url);
//The above call is sync, so can do the next thing safely. //The above call is sync, so can do the next thing safely.
ret = context.defined[moduleName]; ret = context.defined[moduleName];
} }
} }
   
return ret; return ret;
}; };
   
//Add wrapper around the code so that it gets the requirejs //Add wrapper around the code so that it gets the requirejs
//API instead of the Node API, and it is done lexically so //API instead of the Node API, and it is done lexically so
//that it survives later execution. //that it survives later execution.
req.makeNodeWrapper = function (contents) { req.makeNodeWrapper = function (contents) {
return '(function (require, requirejs, define) { ' + return '(function (require, requirejs, define) { ' +
contents + contents +
'\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));'; '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
}; };
   
req.load = function (context, moduleName, url) { req.load = function (context, moduleName, url) {
var contents, err; var contents, err;
   
//Indicate a the module is in process of loading. if (exists(url)) {
context.scriptCount += 1;  
   
if (path.existsSync(url)) {  
contents = fs.readFileSync(url, 'utf8'); contents = fs.readFileSync(url, 'utf8');
   
contents = req.makeNodeWrapper(contents); contents = req.makeNodeWrapper(contents);
try { try {
vm.runInThisContext(contents, fs.realpathSync(url)); vm.runInThisContext(contents, fs.realpathSync(url));
} catch (e) { } catch (e) {
err = new Error('Evaluating ' + url + ' as module "' + err = new Error('Evaluating ' + url + ' as module "' +
moduleName + '" failed with error: ' + e); moduleName + '" failed with error: ' + e);
err.originalError = e; err.originalError = e;
err.moduleName = moduleName; err.moduleName = moduleName;
err.fileName = url; err.fileName = url;
return req.onError(err); return req.onError(err);
} }
} else { } else {
def(moduleName, function () { def(moduleName, function () {
  //Get the original name, since relative requires may be
  //resolved differently in node (issue #202)
  var originalName = context.registry[moduleName] &&
  context.registry[moduleName].map.originalName;
   
try { try {
return (context.config.nodeRequire || req.nodeRequire)(moduleName); return (context.config.nodeRequire || req.nodeRequire)(originalName);
} catch (e) { } catch (e) {
err = new Error('Calling node\'s require("' + err = new Error('Calling node\'s require("' +
moduleName + '") failed with error: ' + e); originalName + '") failed with error: ' + e);
err.originalError = e; err.originalError = e;
err.moduleName = moduleName; err.moduleName = originalName;
return req.onError(err); return req.onError(err);
} }
}); });
} }
   
//Support anonymous modules. //Support anonymous modules.
context.completeLoad(moduleName); context.completeLoad(moduleName);
   
return undefined;  
}; };
   
//Override to provide the function wrapper for define/require. //Override to provide the function wrapper for define/require.
req.exec = function (text) { req.exec = function (text) {
/*jslint evil: true */ /*jslint evil: true */
text = req.makeNodeWrapper(text); text = req.makeNodeWrapper(text);
return eval(text); return eval(text);
}; };
}()); }());
   
} }
   
//Support a default file name to execute. Useful for hosted envs //Support a default file name to execute. Useful for hosted envs
//like Joyent where it defaults to a server.js as the only executed //like Joyent where it defaults to a server.js as the only executed
//script. But only do it if this is not an optimization run. //script. But only do it if this is not an optimization run.
if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) { if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
fileName = 'main.js'; fileName = 'main.js';
} }
   
/** /**
* Loads the library files that can be used for the optimizer, or for other * Loads the library files that can be used for the optimizer, or for other
* tasks. * tasks.
*/ */
function loadLib() { function loadLib() {
/** /**
* @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global Packages: false, process: false, window: false, navigator: false, /*global Packages: false, process: false, window: false, navigator: false,
document: false, define: false */ document: false, define: false */
   
/** /**
* A plugin that modifies any /env/ path to be the right path based on * A plugin that modifies any /env/ path to be the right path based on
* the host environment. Right now only works for Node, Rhino and browser. * the host environment. Right now only works for Node, Rhino and browser.
*/ */
(function () { (function () {
var pathRegExp = /(\/|^)env\/|\{env\}/, var pathRegExp = /(\/|^)env\/|\{env\}/,
env = 'unknown'; env = 'unknown';
   
if (typeof Packages !== 'undefined') { if (typeof Packages !== 'undefined') {
env = 'rhino'; env = 'rhino';
} else if (typeof process !== 'undefined') { } else if (typeof process !== 'undefined') {
env = 'node'; env = 'node';
} else if (typeof window !== "undefined" && navigator && document) { } else if (typeof window !== "undefined" && navigator && document) {
env = 'browser'; env = 'browser';
} }
   
define('env', { define('env', {
load: function (name, req, load, config) { load: function (name, req, load, config) {
//Allow override in the config. //Allow override in the config.
if (config.env) { if (config.env) {
env = config.env; env = config.env;
} }
   
name = name.replace(pathRegExp, function (match, prefix) { name = name.replace(pathRegExp, function (match, prefix) {
if (match.indexOf('{') === -1) { if (match.indexOf('{') === -1) {
return prefix + env + '/'; return prefix + env + '/';
} else { } else {
return env; return env;
} }
}); });
   
req([name], function (mod) { req([name], function (mod) {
load(mod); load(mod);
}); });
} }
}); });
}()); }());
if(env === 'node') { if(env === 'node') {
/** /**
  * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  * Available via the MIT or new BSD license.
  * see: http://github.com/jrburke/requirejs for details
  */
   
  /*jslint strict: false */
  /*global define: false, load: false */
   
  //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  define('node/assert', ['assert'], function (assert) {
  return assert;
  });
   
  }
   
  if(env === 'rhino') {
  /**
  * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  * Available via the MIT or new BSD license.
  * see: http://github.com/jrburke/requirejs for details
  */
   
  /*jslint strict: false */
  /*global define: false, load: false */
   
  //Just a stub for use with uglify's consolidator.js
  define('rhino/assert', function () {
  return {};
  });
   
  }
   
  if(env === 'node') {
  /**
* @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global define: false, process: false */ /*global define: false, process: false */
   
define('node/args', function () { define('node/args', function () {
//Do not return the "node" or "r.js" arguments //Do not return the "node" or "r.js" arguments
var args = process.argv.slice(2); var args = process.argv.slice(2);
   
//Ignore any command option used for rq.js //Ignore any command option used for rq.js
if (args[0] && args[0].indexOf('-' === 0)) { if (args[0] && args[0].indexOf('-' === 0)) {
args = args.slice(1); args = args.slice(1);
} }
   
return args; return args;
}); });
   
} }
   
if(env === 'rhino') { if(env === 'rhino') {
/** /**
* @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global define: false, process: false */ /*global define: false, process: false */
   
var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
   
define('rhino/args', function () { define('rhino/args', function () {
var args = jsLibRhinoArgs; var args = jsLibRhinoArgs;
   
//Ignore any command option used for rq.js //Ignore any command option used for rq.js
if (args[0] && args[0].indexOf('-' === 0)) { if (args[0] && args[0].indexOf('-' === 0)) {
args = args.slice(1); args = args.slice(1);
} }
   
return args; return args;
}); });
   
} }
   
if(env === 'node') { if(env === 'node') {
/** /**
* @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global define: false, console: false */ /*global define: false, console: false */
   
define('node/load', ['fs'], function (fs) { define('node/load', ['fs'], function (fs) {
function load(fileName) { function load(fileName) {
var contents = fs.readFileSync(fileName, 'utf8'); var contents = fs.readFileSync(fileName, 'utf8');
process.compile(contents, fileName); process.compile(contents, fileName);
} }
   
return load; return load;
}); });
   
} }
   
if(env === 'rhino') { if(env === 'rhino') {
/** /**
* @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global define: false, load: false */ /*global define: false, load: false */
   
define('rhino/load', function () { define('rhino/load', function () {
return load; return load;
}); });
   
} }
   
if(env === 'node') { if(env === 'node') {
/** /**
* @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint plusplus: false, octal:false, strict: false */ /*jslint plusplus: false, octal:false, strict: false */
/*global define: false, process: false */ /*global define: false, process: false */
   
define('node/file', ['fs', 'path'], function (fs, path) { define('node/file', ['fs', 'path'], function (fs, path) {
   
var isWindows = process.platform === 'win32', var isWindows = process.platform === 'win32',
  windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
file; file;
   
function frontSlash(path) { function frontSlash(path) {
return path.replace(/\\/g, '/'); return path.replace(/\\/g, '/');
} }
   
function exists(path) { function exists(path) {
if (isWindows && path.charAt(path.length - 1) === '/' && if (isWindows && path.charAt(path.length - 1) === '/' &&
path.charAt(path.length - 2) !== ':') { path.charAt(path.length - 2) !== ':') {
path = path.substring(0, path.length - 1); path = path.substring(0, path.length - 1);
} }
   
try { try {
fs.statSync(path); fs.statSync(path);
return true; return true;
} catch (e) { } catch (e) {
return false; return false;
} }
} }
   
function mkDir(dir) { function mkDir(dir) {
if (!exists(dir)) { if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
fs.mkdirSync(dir, 0777); fs.mkdirSync(dir, 511);
} }
} }
   
function mkFullDir(dir) { function mkFullDir(dir) {
var parts = dir.split('/'), var parts = dir.split('/'),
currDir = '', currDir = '',
first = true; first = true;
   
parts.forEach(function (part) { parts.forEach(function (part) {
//First part may be empty string if path starts with a slash. //First part may be empty string if path starts with a slash.
currDir += part + '/'; currDir += part + '/';
first = false; first = false;
   
if (part) { if (part) {
mkDir(currDir); mkDir(currDir);
} }
}); });
} }
   
file = { file = {
backSlashRegExp: /\\/g, backSlashRegExp: /\\/g,
exclusionRegExp: /^\./, exclusionRegExp: /^\./,
getLineSeparator: function () { getLineSeparator: function () {
return '/'; return '/';
}, },
   
exists: function (fileName) { exists: function (fileName) {
return exists(fileName); return exists(fileName);
}, },
   
parent: function (fileName) { parent: function (fileName) {
var parts = fileName.split('/'); var parts = fileName.split('/');
parts.pop(); parts.pop();
return parts.join('/'); return parts.join('/');
}, },
   
/** /**
* Gets the absolute file path as a string, normalized * Gets the absolute file path as a string, normalized
* to using front slashes for path separators. * to using front slashes for path separators.
* @param {String} fileName * @param {String} fileName
*/ */
absPath: function (fileName) { absPath: function (fileName) {
return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName)))); return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
}, },
   
normalize: function (fileName) { normalize: function (fileName) {
return frontSlash(path.normalize(fileName)); return frontSlash(path.normalize(fileName));
}, },
   
isFile: function (path) { isFile: function (path) {
return fs.statSync(path).isFile(); return fs.statSync(path).isFile();
}, },
   
isDirectory: function (path) { isDirectory: function (path) {
return fs.statSync(path).isDirectory(); return fs.statSync(path).isDirectory();
}, },
   
getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) { getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
//summary: Recurses startDir and finds matches to the files that match regExpFilters.include //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
//and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
//and it will be treated as the "include" case. //and it will be treated as the "include" case.
//Ignores files/directories that start with a period (.) unless exclusionRegExp //Ignores files/directories that start with a period (.) unless exclusionRegExp
//is set to another value. //is set to another value.
var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
i, stat, filePath, ok, dirFiles, fileName; i, stat, filePath, ok, dirFiles, fileName;
   
topDir = startDir; topDir = startDir;
   
regExpInclude = regExpFilters.include || regExpFilters; regExpInclude = regExpFilters.include || regExpFilters;
regExpExclude = regExpFilters.exclude || null; regExpExclude = regExpFilters.exclude || null;
   
if (file.exists(topDir)) { if (file.exists(topDir)) {
dirFileArray = fs.readdirSync(topDir); dirFileArray = fs.readdirSync(topDir);
for (i = 0; i < dirFileArray.length; i++) { for (i = 0; i < dirFileArray.length; i++) {
fileName = dirFileArray[i]; fileName = dirFileArray[i];
filePath = path.join(topDir, fileName); filePath = path.join(topDir, fileName);
stat = fs.statSync(filePath); stat = fs.statSync(filePath);
if (stat.isFile()) { if (stat.isFile()) {
if (makeUnixPaths) { if (makeUnixPaths) {
//Make sure we have a JS string. //Make sure we have a JS string.
if (filePath.indexOf("/") === -1) { if (filePath.indexOf("/") === -1) {
filePath = frontSlash(filePath); filePath = frontSlash(filePath);
} }
} }
   
ok = true; ok = true;
if (regExpInclude) { if (regExpInclude) {
ok = filePath.match(regExpInclude); ok = filePath.match(regExpInclude);
} }
if (ok && regExpExclude) { if (ok && regExpExclude) {
ok = !filePath.match(regExpExclude); ok = !filePath.match(regExpExclude);
} }
   
if (ok && (!file.exclusionRegExp || if (ok && (!file.exclusionRegExp ||
!file.exclusionRegExp.test(fileName))) { !file.exclusionRegExp.test(fileName))) {
files.push(filePath); files.push(filePath);
} }
} else if (stat.isDirectory() && } else if (stat.isDirectory() &&
(!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) { (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths); dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
files.push.apply(files, dirFiles); files.push.apply(files, dirFiles);
} }
} }
} }
   
return files; //Array return files; //Array
}, },
   
copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
//summary: copies files from srcDir to destDir using the regExpFilter to determine if the //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
//file should be copied. Returns a list file name strings of the destinations that were copied. //file should be copied. Returns a list file name strings of the destinations that were copied.
regExpFilter = regExpFilter || /\w/; regExpFilter = regExpFilter || /\w/;
   
//Normalize th directory names, but keep front slashes. //Normalize th directory names, but keep front slashes.
//path module on windows now returns backslashed paths. //path module on windows now returns backslashed paths.
srcDir = frontSlash(path.normalize(srcDir)); srcDir = frontSlash(path.normalize(srcDir));
destDir = frontSlash(path.normalize(destDir)); destDir = frontSlash(path.normalize(destDir));
   
var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
copiedFiles = [], i, srcFileName, destFileName; copiedFiles = [], i, srcFileName, destFileName;
   
for (i = 0; i < fileNames.length; i++) { for (i = 0; i < fileNames.length; i++) {
srcFileName = fileNames[i]; srcFileName = fileNames[i];
destFileName = srcFileName.replace(srcDir, destDir); destFileName = srcFileName.replace(srcDir, destDir);
   
if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
copiedFiles.push(destFileName); copiedFiles.push(destFileName);
} }
} }
   
return copiedFiles.length ? copiedFiles : null; //Array or null return copiedFiles.length ? copiedFiles : null; //Array or null
}, },
   
copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
//summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
//srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
var parentDir; var parentDir;
   
//logger.trace("Src filename: " + srcFileName); //logger.trace("Src filename: " + srcFileName);
//logger.trace("Dest filename: " + destFileName); //logger.trace("Dest filename: " + destFileName);
   
//If onlyCopyNew is true, then compare dates and only copy if the src is newer //If onlyCopyNew is true, then compare dates and only copy if the src is newer
//than dest. //than dest.
if (onlyCopyNew) { if (onlyCopyNew) {
if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) { if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
return false; //Boolean return false; //Boolean
} }
} }
   
//Make sure destination dir exists. //Make sure destination dir exists.
parentDir = path.dirname(destFileName); parentDir = path.dirname(destFileName);
if (!file.exists(parentDir)) { if (!file.exists(parentDir)) {
mkFullDir(parentDir); mkFullDir(parentDir);
} }
   
fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary'); fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
   
return true; //Boolean return true; //Boolean
}, },
   
/** /**
  * Renames a file. May fail if "to" already exists or is on another drive.
  */
  renameFile: function (from, to) {
  return fs.renameSync(from, to);
  },
   
  /**
* Reads a *text* file. * Reads a *text* file.
*/ */
readFile: function (/*String*/path, /*String?*/encoding) { readFile: function (/*String*/path, /*String?*/encoding) {
if (encoding === 'utf-8') { if (encoding === 'utf-8') {
encoding = 'utf8'; encoding = 'utf8';
} }
if (!encoding) { if (!encoding) {
encoding = 'utf8'; encoding = 'utf8';
} }
   
var text = fs.readFileSync(path, encoding); var text = fs.readFileSync(path, encoding);
   
//Hmm, would not expect to get A BOM, but it seems to happen, //Hmm, would not expect to get A BOM, but it seems to happen,
//remove it just in case. //remove it just in case.
if (text.indexOf('\uFEFF') === 0) { if (text.indexOf('\uFEFF') === 0) {
text = text.substring(1, text.length); text = text.substring(1, text.length);
} }
   
return text; return text;
}, },
   
saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
//summary: saves a *text* file using UTF-8 encoding. //summary: saves a *text* file using UTF-8 encoding.
file.saveFile(fileName, fileContents, "utf8"); file.saveFile(fileName, fileContents, "utf8");
}, },
   
saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
//summary: saves a *text* file. //summary: saves a *text* file.
var parentDir; var parentDir;
   
if (encoding === 'utf-8') { if (encoding === 'utf-8') {
encoding = 'utf8'; encoding = 'utf8';
} }
if (!encoding) { if (!encoding) {
encoding = 'utf8'; encoding = 'utf8';
} }
   
//Make sure destination directories exist. //Make sure destination directories exist.
parentDir = path.dirname(fileName); parentDir = path.dirname(fileName);
if (!file.exists(parentDir)) { if (!file.exists(parentDir)) {
mkFullDir(parentDir); mkFullDir(parentDir);
} }
   
fs.writeFileSync(fileName, fileContents, encoding); fs.writeFileSync(fileName, fileContents, encoding);
}, },
   
deleteFile: function (/*String*/fileName) { deleteFile: function (/*String*/fileName) {
//summary: deletes a file or directory if it exists. //summary: deletes a file or directory if it exists.
var files, i, stat; var files, i, stat;
if (file.exists(fileName)) { if (file.exists(fileName)) {
stat = fs.statSync(fileName); stat = fs.statSync(fileName);
if (stat.isDirectory()) { if (stat.isDirectory()) {
files = fs.readdirSync(fileName); files = fs.readdirSync(fileName);
for (i = 0; i < files.length; i++) { for (i = 0; i < files.length; i++) {
this.deleteFile(path.join(fileName, files[i])); this.deleteFile(path.join(fileName, files[i]));
} }
fs.rmdirSync(fileName); fs.rmdirSync(fileName);
} else { } else {
fs.unlinkSync(fileName); fs.unlinkSync(fileName);
} }
} }
  },
   
   
  /**
  * Deletes any empty directories under the given directory.
  */
  deleteEmptyDirs: function (startDir) {
  var dirFileArray, i, fileName, filePath, stat;
   
  if (file.exists(startDir)) {
  dirFileArray = fs.readdirSync(startDir);
  for (i = 0; i < dirFileArray.length; i++) {
  fileName = dirFileArray[i];
  filePath = path.join(startDir, fileName);
  stat = fs.statSync(filePath);
  if (stat.isDirectory()) {
  file.deleteEmptyDirs(filePath);
  }
  }
   
  //If directory is now empty, remove it.
  if (fs.readdirSync(startDir).length === 0) {
  file.deleteFile(startDir);
  }
  }
} }
}; };
   
return file; return file;
   
}); });
   
} }
   
if(env === 'rhino') { if(env === 'rhino') {
/** /**
* @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
//Helper functions to deal with file I/O. //Helper functions to deal with file I/O.
   
/*jslint plusplus: false, strict: false */ /*jslint plusplus: false, strict: true */
/*global java: false, define: false */ /*global java: false, define: false */
   
define('rhino/file', function () { define('rhino/file', function () {
var file = { var file = {
backSlashRegExp: /\\/g, backSlashRegExp: /\\/g,
   
exclusionRegExp: /^\./, exclusionRegExp: /^\./,
   
getLineSeparator: function () { getLineSeparator: function () {
return file.lineSeparator; return file.lineSeparator;
}, },
   
lineSeparator: java.lang.System.getProperty("line.separator"), //Java String lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
   
exists: function (fileName) { exists: function (fileName) {
return (new java.io.File(fileName)).exists(); return (new java.io.File(fileName)).exists();
}, },
   
parent: function (fileName) { parent: function (fileName) {
return file.absPath((new java.io.File(fileName)).getParentFile()); return file.absPath((new java.io.File(fileName)).getParentFile());
}, },
   
normalize: function (fileName) { normalize: function (fileName) {
return file.absPath(fileName); return file.absPath(fileName);
}, },
   
isFile: function (path) { isFile: function (path) {
return (new java.io.File(path)).isFile(); return (new java.io.File(path)).isFile();
}, },
   
isDirectory: function (path) { isDirectory: function (path) {
return (new java.io.File(path)).isDirectory(); return (new java.io.File(path)).isDirectory();
}, },
   
/** /**
* Gets the absolute file path as a string, normalized * Gets the absolute file path as a string, normalized
* to using front slashes for path separators. * to using front slashes for path separators.
* @param {java.io.File||String} file * @param {java.io.File||String} file
*/ */
absPath: function (fileObj) { absPath: function (fileObj) {
if (typeof fileObj === "string") { if (typeof fileObj === "string") {
fileObj = new java.io.File(fileObj); fileObj = new java.io.File(fileObj);
} }
return (fileObj.getAbsolutePath() + "").replace(file.backSlashRegExp, "/"); return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
}, },
   
getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) { getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
//summary: Recurses startDir and finds matches to the files that match regExpFilters.include //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
//and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
//and it will be treated as the "include" case. //and it will be treated as the "include" case.
//Ignores files/directories that start with a period (.) unless exclusionRegExp //Ignores files/directories that start with a period (.) unless exclusionRegExp
//is set to another value. //is set to another value.
var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
i, fileObj, filePath, ok, dirFiles; i, fileObj, filePath, ok, dirFiles;
   
topDir = startDir; topDir = startDir;
if (!startDirIsJavaObject) { if (!startDirIsJavaObject) {
topDir = new java.io.File(startDir); topDir = new java.io.File(startDir);
} }
   
regExpInclude = regExpFilters.include || regExpFilters; regExpInclude = regExpFilters.include || regExpFilters;
regExpExclude = regExpFilters.exclude || null; regExpExclude = regExpFilters.exclude || null;
   
if (topDir.exists()) { if (topDir.exists()) {
dirFileArray = topDir.listFiles(); dirFileArray = topDir.listFiles();
for (i = 0; i < dirFileArray.length; i++) { for (i = 0; i < dirFileArray.length; i++) {
fileObj = dirFileArray[i]; fileObj = dirFileArray[i];
if (fileObj.isFile()) { if (fileObj.isFile()) {
filePath = fileObj.getPath(); filePath = fileObj.getPath();
if (makeUnixPaths) { if (makeUnixPaths) {
//Make sure we have a JS string. //Make sure we have a JS string.
filePath = String(filePath); filePath = String(filePath);
if (filePath.indexOf("/") === -1) { if (filePath.indexOf("/") === -1) {
filePath = filePath.replace(/\\/g, "/"); filePath = filePath.replace(/\\/g, "/");
} }
} }
   
ok = true; ok = true;
if (regExpInclude) { if (regExpInclude) {
ok = filePath.match(regExpInclude); ok = filePath.match(regExpInclude);
} }
if (ok && regExpExclude) { if (ok && regExpExclude) {
ok = !filePath.match(regExpExclude); ok = !filePath.match(regExpExclude);
} }
   
if (ok && (!file.exclusionRegExp || if (ok && (!file.exclusionRegExp ||
!file.exclusionRegExp.test(fileObj.getName()))) { !file.exclusionRegExp.test(fileObj.getName()))) {
files.push(filePath); files.push(filePath);
} }
} else if (fileObj.isDirectory() && } else if (fileObj.isDirectory() &&
(!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) { (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
files.push.apply(files, dirFiles); files.push.apply(files, dirFiles);
} }
} }
} }
   
return files; //Array return files; //Array
}, },
   
copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
//summary: copies files from srcDir to destDir using the regExpFilter to determine if the //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
//file should be copied. Returns a list file name strings of the destinations that were copied. //file should be copied. Returns a list file name strings of the destinations that were copied.
regExpFilter = regExpFilter || /\w/; regExpFilter = regExpFilter || /\w/;
   
var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
copiedFiles = [], i, srcFileName, destFileName; copiedFiles = [], i, srcFileName, destFileName;
   
for (i = 0; i < fileNames.length; i++) { for (i = 0; i < fileNames.length; i++) {
srcFileName = fileNames[i]; srcFileName = fileNames[i];
destFileName = srcFileName.replace(srcDir, destDir); destFileName = srcFileName.replace(srcDir, destDir);
   
if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
copiedFiles.push(destFileName); copiedFiles.push(destFileName);
} }
} }
   
return copiedFiles.length ? copiedFiles : null; //Array or null return copiedFiles.length ? copiedFiles : null; //Array or null
}, },
   
copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
//summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
//srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
var destFile = new java.io.File(destFileName), srcFile, parentDir, var destFile = new java.io.File(destFileName), srcFile, parentDir,
srcChannel, destChannel; srcChannel, destChannel;
   
//logger.trace("Src filename: " + srcFileName); //logger.trace("Src filename: " + srcFileName);
//logger.trace("Dest filename: " + destFileName); //logger.trace("Dest filename: " + destFileName);
   
//If onlyCopyNew is true, then compare dates and only copy if the src is newer //If onlyCopyNew is true, then compare dates and only copy if the src is newer
//than dest. //than dest.
if (onlyCopyNew) { if (onlyCopyNew) {
srcFile = new java.io.File(srcFileName); srcFile = new java.io.File(srcFileName);
if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) { if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
return false; //Boolean return false; //Boolean
} }
} }
   
//Make sure destination dir exists. //Make sure destination dir exists.
parentDir = destFile.getParentFile(); parentDir = destFile.getParentFile();
if (!parentDir.exists()) { if (!parentDir.exists()) {
if (!parentDir.mkdirs()) { if (!parentDir.mkdirs()) {
throw "Could not create directory: " + parentDir.getAbsolutePath(); throw "Could not create directory: " + parentDir.getCanonicalPath();
} }
} }
   
//Java's version of copy file. //Java's version of copy file.
srcChannel = new java.io.FileInputStream(srcFileName).getChannel(); srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
destChannel = new java.io.FileOutputStream(destFileName).getChannel(); destChannel = new java.io.FileOutputStream(destFileName).getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size()); destChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close(); srcChannel.close();
destChannel.close(); destChannel.close();
   
return true; //Boolean return true; //Boolean
  },
   
  /**
  * Renames a file. May fail if "to" already exists or is on another drive.
  */
  renameFile: function (from, to) {
  return (new java.io.File(from)).renameTo((new java.io.File(to)));
}, },
   
readFile: function (/*String*/path, /*String?*/encoding) { readFile: function (/*String*/path, /*String?*/encoding) {
//A file read function that can deal with BOMs //A file read function that can deal with BOMs
encoding = encoding || "utf-8"; encoding = encoding || "utf-8";
var fileObj = new java.io.File(path), var fileObj = new java.io.File(path),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
stringBuffer, line; stringBuffer, line;
try { try {
stringBuffer = new java.lang.StringBuffer(); stringBuffer = new java.lang.StringBuffer();
line = input.readLine(); line = input.readLine();
   
// Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
// http://www.unicode.org/faq/utf_bom.html // http://www.unicode.org/faq/utf_bom.html
   
// Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
if (line && line.length() && line.charAt(0) === 0xfeff) { if (line && line.length() && line.charAt(0) === 0xfeff) {
// Eat the BOM, since we've already found the encoding on this file, // Eat the BOM, since we've already found the encoding on this file,
// and we plan to concatenating this buffer with others; the BOM should // and we plan to concatenating this buffer with others; the BOM should
// only appear at the top of a file. // only appear at the top of a file.
line = line.substring(1); line = line.substring(1);
} }
while (line !== null) { while (line !== null) {
stringBuffer.append(line); stringBuffer.append(line);
stringBuffer.append(file.lineSeparator); stringBuffer.append(file.lineSeparator);
line = input.readLine(); line = input.readLine();
} }
//Make sure we return a JavaScript string and not a Java string. //Make sure we return a JavaScript string and not a Java string.
return String(stringBuffer.toString()); //String return String(stringBuffer.toString()); //String
} finally { } finally {
input.close(); input.close();
} }
}, },
   
saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
//summary: saves a file using UTF-8 encoding. //summary: saves a file using UTF-8 encoding.
file.saveFile(fileName, fileContents, "utf-8"); file.saveFile(fileName, fileContents, "utf-8");
}, },
   
saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
//summary: saves a file. //summary: saves a file.
var outFile = new java.io.File(fileName), outWriter, parentDir, os; var outFile = new java.io.File(fileName), outWriter, parentDir, os;
   
parentDir = outFile.getAbsoluteFile().getParentFile(); parentDir = outFile.getAbsoluteFile().getParentFile();
if (!parentDir.exists()) { if (!parentDir.exists()) {
if (!parentDir.mkdirs()) { if (!parentDir.mkdirs()) {
throw "Could not create directory: " + parentDir.getAbsolutePath(); throw "Could not create directory: " + parentDir.getAbsolutePath();
} }
} }
   
if (encoding) { if (encoding) {
outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
} else { } else {
outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
} }
   
os = new java.io.BufferedWriter(outWriter); os = new java.io.BufferedWriter(outWriter);
try { try {
os.write(fileContents); os.write(fileContents);
} finally { } finally {
os.close(); os.close();
} }
}, },
   
deleteFile: function (/*String*/fileName) { deleteFile: function (/*String*/fileName) {
//summary: deletes a file or directory if it exists. //summary: deletes a file or directory if it exists.
var fileObj = new java.io.File(fileName), files, i; var fileObj = new java.io.File(fileName), files, i;
if (fileObj.exists()) { if (fileObj.exists()) {
if (fileObj.isDirectory()) { if (fileObj.isDirectory()) {
files = fileObj.listFiles(); files = fileObj.listFiles();
for (i = 0; i < files.length; i++) { for (i = 0; i < files.length; i++) {
this.deleteFile(files[i]); this.deleteFile(files[i]);
} }
} }
fileObj["delete"](); fileObj["delete"]();
} }
  },
   
  /**
  * Deletes any empty directories under the given directory.
  * The startDirIsJavaObject is private to this implementation's
  * recursion needs.
  */
  deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  var topDir = startDir,
  dirFileArray, i, fileObj;
   
  if (!startDirIsJavaObject) {
  topDir = new java.io.File(startDir);
  }
   
  if (topDir.exists()) {
  dirFileArray = topDir.listFiles();
  for (i = 0; i < dirFileArray.length; i++) {
  fileObj = dirFileArray[i];
  if (fileObj.isDirectory()) {
  file.deleteEmptyDirs(fileObj, true);
  }
  }
   
  //If the directory is empty now, delete it.
  if (topDir.listFiles().length === 0) {
  file.deleteFile(String(topDir.getPath()));
  }
  }
} }
}; };
   
return file; return file;
  });
   
  }
   
  if(env === 'node') {
  /*global process */
  define('node/quit', function () {
  'use strict';
  return function (code) {
  return process.exit(code);
  };
  });
  }
   
  if(env === 'rhino') {
  /*global quit */
  define('rhino/quit', function () {
  'use strict';
  return function (code) {
  return quit(code);
  };
}); });
   
} }
/** /**
* @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint plusplus: false, strict: false */ /*jslint plusplus: true */
/*global define: false */ /*global define */
   
define('lang', function () { define('lang', function () {
  'use strict';
   
var lang = { var lang = {
backSlashRegExp: /\\/g, backSlashRegExp: /\\/g,
ostring: Object.prototype.toString, ostring: Object.prototype.toString,
   
isArray: Array.isArray ? Array.isArray : function (it) { isArray: Array.isArray || function (it) {
return lang.ostring.call(it) === "[object Array]"; return lang.ostring.call(it) === "[object Array]";
}, },
   
  isFunction: function(it) {
  return lang.ostring.call(it) === "[object Function]";
  },
   
  isRegExp: function(it) {
  return it && it instanceof RegExp;
  },
   
  _mixin: function(dest, source, override){
  var name;
  for (name in source) {
  if(source.hasOwnProperty(name)
  && (override || !dest.hasOwnProperty(name))) {
  dest[name] = source[name];
  }
  }
   
  return dest; // Object
  },
   
/** /**
* Simple function to mix in properties from source into target, * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
* but only if target does not already have a property of the same name. * then the source objects properties are force copied over to dest.
*/ */
mixin: function (target, source, override) { mixin: function(dest){
//Use an empty object to avoid other bad JS code that modifies var parameters = Array.prototype.slice.call(arguments),
//Object.prototype. override, i, l;
var empty = {}, prop;  
for (prop in source) { if (!dest) { dest = {}; }
if (override || !(prop in target)) {  
target[prop] = source[prop]; if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
} override = parameters.pop();
} }
   
  for (i = 1, l = parameters.length; i < l; i++) {
  lang._mixin(dest, parameters[i], override);
  }
  return dest; // Object
}, },
   
delegate: (function () { delegate: (function () {
// boodman/crockford delegation w/ cornford optimization // boodman/crockford delegation w/ cornford optimization
function TMP() {} function TMP() {}
return function (obj, props) { return function (obj, props) {
TMP.prototype = obj; TMP.prototype = obj;
var tmp = new TMP(); var tmp = new TMP();
TMP.prototype = null; TMP.prototype = null;
if (props) { if (props) {
lang.mixin(tmp, props); lang.mixin(tmp, props);
} }
return tmp; // Object return tmp; // Object
}; };
}()) }()),
   
  /**
  * Helper function for iterating over an array. If the func returns
  * a true value, it will break out of the loop.
  */
  each: function each(ary, func) {
  if (ary) {
  var i;
  for (i = 0; i < ary.length; i += 1) {
  if (func(ary[i], i, ary)) {
  break;
  }
  }
  }
  },
   
  /**
  * Cycles over properties in an object and calls a function for each
  * property value. If the function returns a truthy value, then the
  * iteration is stopped.
  */
  eachProp: function eachProp(obj, func) {
  var prop;
  for (prop in obj) {
  if (obj.hasOwnProperty(prop)) {
  if (func(obj[prop], prop)) {
  break;
  }
  }
  }
  },
   
  //Similar to Function.prototype.bind, but the "this" object is specified
  //first, since it is easier to read/figure out what "this" will be.
  bind: function bind(obj, fn) {
  return function () {
  return fn.apply(obj, arguments);
  };
  },
   
  //Escapes a content string to be be a string that has characters escaped
  //for inclusion as part of a JS string.
  jsEscape: function (content) {
  return content.replace(/(["'\\])/g, '\\$1')
  .replace(/[\f]/g, "\\f")
  .replace(/[\b]/g, "\\b")
  .replace(/[\n]/g, "\\n")
  .replace(/[\t]/g, "\\t")
  .replace(/[\r]/g, "\\r");
  }
}; };
return lang; return lang;
}); });
   
if(env === 'node') { if(env === 'node') {
/** /**
* @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global define: false, console: false */ /*global define: false, console: false */
   
define('node/print', function () { define('node/print', function () {
function print(msg) { function print(msg) {
console.log(msg); console.log(msg);
} }
   
return print; return print;
}); });
   
} }
   
if(env === 'rhino') { if(env === 'rhino') {
/** /**
* @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint strict: false */ /*jslint strict: false */
/*global define: false, print: false */ /*global define: false, print: false */
   
define('rhino/print', function () { define('rhino/print', function () {
return print; return print;
}); });
   
} }
/** /**
* @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details * see: http://github.com/jrburke/requirejs for details
*/ */
   
/*jslint nomen: false, strict: false */ /*jslint nomen: false, strict: false */
/*global define: false */ /*global define: false */
   
define('logger', ['env!env/print'], function (print) { define('logger', ['env!env/print'], function (print) {
var logger = { var logger = {
TRACE: 0, TRACE: 0,
INFO: 1, INFO: 1,
WARN: 2, WARN: 2,
ERROR: 3, ERROR: 3,
SILENT: 4, SILENT: 4,
level: 0, level: 0,
logPrefix: "", logPrefix: "",
   
logLevel: function( level ) { logLevel: function( level ) {
this.level = level; this.level = level;
}, },
   
trace: function (message) { trace: function (message) {
if (this.level <= this.TRACE) { if (this.level <= this.TRACE) {
this._print(message); this._print(message);
} }
}, },
   
info: function (message) { info: function (message) {
if (this.level <= this.INFO) { if (this.level <= this.INFO) {
this._print(message); this._print(message);
} }
}, },
   
warn: function (message) { warn: function (message) {
if (this.level <= this.WARN) { if (this.level <= this.WARN) {
this._print(message); this._print(message);
} }
}, },
   
error: function (message) { error: function (message) {
if (this.level <= this.ERROR) { if (this.level <= this.ERROR) {
this._print(message); this._print(message);
} }
}, },
   
_print: function (message) { _print: function (message) {
this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message); this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
}, },
   
_sysPrint: function (message) { _sysPrint: function (message) {
print(message); print(message);
} }
}; };
   
return logger; return logger;
}); });
//Just a blank file to use when building the optimizer with the optimizer, //Just a blank file to use when building the optimizer with the optimizer,
//so that the build does not attempt to inline some env modules, //so that the build does not attempt to inline some env modules,
//like Node's fs and path. //like Node's fs and path.
   
//Just a blank file to use when building the optimizer with the optimizer, //Just a blank file to use when building the optimizer with the optimizer,
//so that the build does not attempt to inline some env modules, //so that the build does not attempt to inline some env modules,
//like Node's fs and path. //like Node's fs and path.
   
define('uglifyjs/parse-js', ["require", "exports", "module"], function(require, exports, module) { //Commit 465a4eae86c7bae191b1ee427571543ace777117 on July 19, 2012
  define('esprima', ['exports'], function(exports) {
  /*
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
   
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
   
  * Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
   
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
   
  /*jslint bitwise:true plusplus:true */
  /*global esprima:true, exports:true,
  throwError: true, createLiteral: true, generateStatement: true,
  parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
  parseFunctionDeclaration: true, parseFunctionExpression: true,
  parseFunctionSourceElements: true, parseVariableIdentifier: true,
  parseLeftHandSideExpression: true,
  parseStatement: true, parseSourceElement: true */
   
  (function (exports) {
  'use strict';
   
  var Token,
  TokenName,
  Syntax,
  PropertyKind,
  Messages,
  Regex,
  source,
  strict,
  index,
  lineNumber,
  lineStart,
  length,
  buffer,
  state,
  extra;
   
  Token = {
  BooleanLiteral: 1,
  EOF: 2,
  Identifier: 3,
  Keyword: 4,
  NullLiteral: 5,
  NumericLiteral: 6,
  Punctuator: 7,
  StringLiteral: 8
  };
   
  TokenName = {};
  TokenName[Token.BooleanLiteral] = 'Boolean';
  TokenName[Token.EOF] = '<end>';
  TokenName[Token.Identifier] = 'Identifier';
  TokenName[Token.Keyword] = 'Keyword';
  TokenName[Token.NullLiteral] = 'Null';
  TokenName[Token.NumericLiteral] = 'Numeric';
  TokenName[Token.Punctuator] = 'Punctuator';
  TokenName[Token.StringLiteral] = 'String';
   
  Syntax = {
  AssignmentExpression: 'AssignmentExpression',
  ArrayExpression: 'ArrayExpression',
  BlockStatement: 'BlockStatement',
  BinaryExpression: 'BinaryExpression',
  BreakStatement: 'BreakStatement',
  CallExpression: 'CallExpression',
  CatchClause: 'CatchClause',
  ConditionalExpression: 'ConditionalExpression',
  ContinueStatement: 'ContinueStatement',
  DoWhileStatement: 'DoWhileStatement',
  DebuggerStatement: 'DebuggerStatement',
  EmptyStatement: 'EmptyStatement',
  ExpressionStatement: 'ExpressionStatement',
  ForStatement: 'ForStatement',
  ForInStatement: 'ForInStatement',
  FunctionDeclaration: 'FunctionDeclaration',
  FunctionExpression: 'FunctionExpression',
  Identifier: 'Identifier',
  IfStatement: 'IfStatement',
  Literal: 'Literal',
  LabeledStatement: 'LabeledStatement',
  LogicalExpression: 'LogicalExpression',
  MemberExpression: 'MemberExpression',
  NewExpression: 'NewExpression',
  ObjectExpression: 'ObjectExpression',
  Program: 'Program',
  Property: 'Property',
  ReturnStatement: 'ReturnStatement',
  SequenceExpression: 'SequenceExpression',
  SwitchStatement: 'SwitchStatement',
  SwitchCase: 'SwitchCase',
  ThisExpression: 'ThisExpression',
  ThrowStatement: 'ThrowStatement',
  TryStatement: 'TryStatement',
  UnaryExpression: 'UnaryExpression',
  UpdateExpression: 'UpdateExpression',
  VariableDeclaration: 'VariableDeclaration',
  VariableDeclarator: 'VariableDeclarator',
  WhileStatement: 'WhileStatement',
  WithStatement: 'WithStatement'
  };
   
  PropertyKind = {
  Data: 1,
  Get: 2,
  Set: 4
  };
   
  // Error messages should be identical to V8.
  Messages = {
  UnexpectedToken: 'Unexpected token %0',
  UnexpectedNumber: 'Unexpected number',
  UnexpectedString: 'Unexpected string',
  UnexpectedIdentifier: 'Unexpected identifier',
  UnexpectedReserved: 'Unexpected reserved word',
  UnexpectedEOS: 'Unexpected end of input',
  NewlineAfterThrow: 'Illegal newline after throw',
  InvalidRegExp: 'Invalid regular expression',
  UnterminatedRegExp: 'Invalid regular expression: missing /',
  InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  NoCatchOrFinally: 'Missing catch or finally after try',
  UnknownLabel: 'Undefined label \'%0\'',
  Redeclaration: '%0 \'%1\' has already been declared',
  IllegalContinue: 'Illegal continue statement',
  IllegalBreak: 'Illegal break statement',
  IllegalReturn: 'Illegal return statement',
  StrictModeWith: 'Strict mode code may not include a with statement',
  StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
  AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
  AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
  StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  StrictReservedWord: 'Use of future reserved word in strict mode'
  };
   
  // See also tools/generate-unicode-regex.py.
  Regex = {
  NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
  NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
  };
   
  // Ensure the condition is true, otherwise throw an error.
  // This is only to have a better contract semantic, i.e. another safety net
  // to catch a logic error. The condition shall be fulfilled in normal case.
  // Do NOT use this to enforce a certain condition on any user input.
   
  function assert(condition, message) {
  if (!condition) {
  throw new Error('ASSERT: ' + message);
  }
  }
   
  function sliceSource(from, to) {
  return source.slice(from, to);
  }
   
  if (typeof 'esprima'[0] === 'undefined') {
  sliceSource = function sliceArraySource(from, to) {
  return source.slice(from, to).join('');
  };
  }
   
  function isDecimalDigit(ch) {
  return '0123456789'.indexOf(ch) >= 0;
  }
   
  function isHexDigit(ch) {
  return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  }
   
  function isOctalDigit(ch) {
  return '01234567'.indexOf(ch) >= 0;
  }
   
   
  // 7.2 White Space
   
  function isWhiteSpace(ch) {
  return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
  (ch === '\u000C') || (ch === '\u00A0') ||
  (ch.charCodeAt(0) >= 0x1680 &&
  '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
  }
   
  // 7.3 Line Terminators
   
  function isLineTerminator(ch) {
  return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
  }
   
  // 7.6 Identifier Names and Identifiers
   
  function isIdentifierStart(ch) {
  return (ch === '$') || (ch === '_') || (ch === '\\') ||
  (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
  }
   
  function isIdentifierPart(ch) {
  return (ch === '$') || (ch === '_') || (ch === '\\') ||
  (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  ((ch >= '0') && (ch <= '9')) ||
  ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
  }
   
  // 7.6.1.2 Future Reserved Words
   
  function isFutureReservedWord(id) {
  switch (id) {
   
  // Future reserved words.
  case 'class':
  case 'enum':
  case 'export':
  case 'extends':
  case 'import':
  case 'super':
  return true;
  }
   
  return false;
  }
   
  function isStrictModeReservedWord(id) {
  switch (id) {
   
  // Strict Mode reserved words.
  case 'implements':
  case 'interface':
  case 'package':
  case 'private':
  case 'protected':
  case 'public':
  case 'static':
  case 'yield':
  case 'let':
  return true;
  }
   
  return false;
  }
   
  function isRestrictedWord(id) {
  return id === 'eval' || id === 'arguments';
  }
   
  // 7.6.1.1 Keywords
   
  function isKeyword(id) {
  var keyword = false;
  switch (id.length) {
  case 2:
  keyword = (id === 'if') || (id === 'in') || (id === 'do');
  break;
  case 3:
  keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
  break;
  case 4:
  keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
  break;
  case 5:
  keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
  break;
  case 6:
  keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
  break;
  case 7:
  keyword = (id === 'default') || (id === 'finally');
  break;
  case 8:
  keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
  break;
  case 10:
  keyword = (id === 'instanceof');
  break;
  }
   
  if (keyword) {
  return true;
  }
   
  switch (id) {
  // Future reserved words.
  // 'const' is specialized as Keyword in V8.
  case 'const':
  return true;
   
  // For compatiblity to SpiderMonkey and ES.next
  case 'yield':
  case 'let':
  return true;
  }
   
  if (strict && isStrictModeReservedWord(id)) {
  return true;
  }
   
  return isFutureReservedWord(id);
  }
   
  // Return the next character and move forward.
   
  function nextChar() {
  return source[index++];
  }
   
  // 7.4 Comments
   
  function skipComment() {
  var ch, blockComment, lineComment;
   
  blockComment = false;
  lineComment = false;
   
  while (index < length) {
  ch = source[index];
   
  if (lineComment) {
  ch = nextChar();
  if (isLineTerminator(ch)) {
  lineComment = false;
  if (ch === '\r' && source[index] === '\n') {
  ++index;
  }
  ++lineNumber;
  lineStart = index;
  }
  } else if (blockComment) {
  if (isLineTerminator(ch)) {
  if (ch === '\r' && source[index + 1] === '\n') {
  ++index;
  }
  ++lineNumber;
  ++index;
  lineStart = index;
  if (index >= length) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  } else {
  ch = nextChar();
  if (index >= length) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  if (ch === '*') {
  ch = source[index];
  if (ch === '/') {
  ++index;
  blockComment = false;
  }
  }
  }
  } else if (ch === '/') {
  ch = source[index + 1];
  if (ch === '/') {
  index += 2;
  lineComment = true;
  } else if (ch === '*') {
  index += 2;
  blockComment = true;
  if (index >= length) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  } else {
  break;
  }
  } else if (isWhiteSpace(ch)) {
  ++index;
  } else if (isLineTerminator(ch)) {
  ++index;
  if (ch === '\r' && source[index] === '\n') {
  ++index;
  }
  ++lineNumber;
  lineStart = index;
  } else {
  break;
  }
  }
  }
   
  function scanHexEscape(prefix) {
  var i, len, ch, code = 0;
   
  len = (prefix === 'u') ? 4 : 2;
  for (i = 0; i < len; ++i) {
  if (index < length && isHexDigit(source[index])) {
  ch = nextChar();
  code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  } else {
  return '';
  }
  }
  return String.fromCharCode(code);
  }
   
  function scanIdentifier() {
  var ch, start, id, restore;
   
  ch = source[index];
  if (!isIdentifierStart(ch)) {
  return;
  }
   
  start = index;
  if (ch === '\\') {
  ++index;
  if (source[index] !== 'u') {
  return;
  }
  ++index;
  restore = index;
  ch = scanHexEscape('u');
  if (ch) {
  if (ch === '\\' || !isIdentifierStart(ch)) {
  return;
  }
  id = ch;
  } else {
  index = restore;
  id = 'u';
  }
  } else {
  id = nextChar();
  }
   
  while (index < length) {
  ch = source[index];
  if (!isIdentifierPart(ch)) {
  break;
  }
  if (ch === '\\') {
  ++index;
  if (source[index] !== 'u') {
  return;
  }
  ++index;
  restore = index;
  ch = scanHexEscape('u');
  if (ch) {
  if (ch === '\\' || !isIdentifierPart(ch)) {
  return;
  }
  id += ch;
  } else {
  index = restore;
  id += 'u';
  }
  } else {
  id += nextChar();
  }
  }
   
  // There is no keyword or literal with only one character.
  // Thus, it must be an identifier.
  if (id.length === 1) {
  return {
  type: Token.Identifier,
  value: id,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  if (isKeyword(id)) {
  return {
  type: Token.Keyword,
  value: id,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // 7.8.1 Null Literals
   
  if (id === 'null') {
  return {
  type: Token.NullLiteral,
  value: id,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // 7.8.2 Boolean Literals
   
  if (id === 'true' || id === 'false') {
  return {
  type: Token.BooleanLiteral,
  value: id,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  return {
  type: Token.Identifier,
  value: id,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // 7.7 Punctuators
   
  function scanPunctuator() {
  var start = index,
  ch1 = source[index],
  ch2,
  ch3,
  ch4;
   
  // Check for most common single-character punctuators.
   
  if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
  ++index;
  return {
  type: Token.Punctuator,
  value: ch1,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
  ++index;
  return {
  type: Token.Punctuator,
  value: ch1,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // Dot (.) can also start a floating-point number, hence the need
  // to check the next character.
   
  ch2 = source[index + 1];
  if (ch1 === '.' && !isDecimalDigit(ch2)) {
  return {
  type: Token.Punctuator,
  value: nextChar(),
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // Peek more characters.
   
  ch3 = source[index + 2];
  ch4 = source[index + 3];
   
  // 4-character punctuator: >>>=
   
  if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
  if (ch4 === '=') {
  index += 4;
  return {
  type: Token.Punctuator,
  value: '>>>=',
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
  }
   
  // 3-character punctuators: === !== >>> <<= >>=
   
  if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
  index += 3;
  return {
  type: Token.Punctuator,
  value: '===',
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
  index += 3;
  return {
  type: Token.Punctuator,
  value: '!==',
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
  index += 3;
  return {
  type: Token.Punctuator,
  value: '>>>',
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
  index += 3;
  return {
  type: Token.Punctuator,
  value: '<<=',
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
  index += 3;
  return {
  type: Token.Punctuator,
  value: '>>=',
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // 2-character punctuators: <= >= == != ++ -- << >> && ||
  // += -= *= %= &= |= ^= /=
   
  if (ch2 === '=') {
  if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
  index += 2;
  return {
  type: Token.Punctuator,
  value: ch1 + ch2,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
  }
   
  if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
  if ('+-<>&|'.indexOf(ch2) >= 0) {
  index += 2;
  return {
  type: Token.Punctuator,
  value: ch1 + ch2,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
  }
   
  // The remaining 1-character punctuators.
   
  if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
  return {
  type: Token.Punctuator,
  value: nextChar(),
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
  }
   
  // 7.8.3 Numeric Literals
   
  function scanNumericLiteral() {
  var number, start, ch;
   
  ch = source[index];
  assert(isDecimalDigit(ch) || (ch === '.'),
  'Numeric literal must start with a decimal digit or a decimal point');
   
  start = index;
  number = '';
  if (ch !== '.') {
  number = nextChar();
  ch = source[index];
   
  // Hex number starts with '0x'.
  // Octal number starts with '0'.
  if (number === '0') {
  if (ch === 'x' || ch === 'X') {
  number += nextChar();
  while (index < length) {
  ch = source[index];
  if (!isHexDigit(ch)) {
  break;
  }
  number += nextChar();
  }
   
  if (number.length <= 2) {
  // only 0x
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
   
  if (index < length) {
  ch = source[index];
  if (isIdentifierStart(ch)) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  }
  return {
  type: Token.NumericLiteral,
  value: parseInt(number, 16),
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  } else if (isOctalDigit(ch)) {
  number += nextChar();
  while (index < length) {
  ch = source[index];
  if (!isOctalDigit(ch)) {
  break;
  }
  number += nextChar();
  }
   
  if (index < length) {
  ch = source[index];
  if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  }
  return {
  type: Token.NumericLiteral,
  value: parseInt(number, 8),
  octal: true,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // decimal number starts with '0' such as '09' is illegal.
  if (isDecimalDigit(ch)) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  }
   
  while (index < length) {
  ch = source[index];
  if (!isDecimalDigit(ch)) {
  break;
  }
  number += nextChar();
  }
  }
   
  if (ch === '.') {
  number += nextChar();
  while (index < length) {
  ch = source[index];
  if (!isDecimalDigit(ch)) {
  break;
  }
  number += nextChar();
  }
  }
   
  if (ch === 'e' || ch === 'E') {
  number += nextChar();
   
  ch = source[index];
  if (ch === '+' || ch === '-') {
  number += nextChar();
  }
   
  ch = source[index];
  if (isDecimalDigit(ch)) {
  number += nextChar();
  while (index < length) {
  ch = source[index];
  if (!isDecimalDigit(ch)) {
  break;
  }
  number += nextChar();
  }
  } else {
  ch = 'character ' + ch;
  if (index >= length) {
  ch = '<end>';
  }
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  }
   
  if (index < length) {
  ch = source[index];
  if (isIdentifierStart(ch)) {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
  }
   
  return {
  type: Token.NumericLiteral,
  value: parseFloat(number),
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  // 7.8.4 String Literals
   
  function scanStringLiteral() {
  var str = '', quote, start, ch, code, unescaped, restore, octal = false;
   
  quote = source[index];
  assert((quote === '\'' || quote === '"'),
  'String literal must starts with a quote');
   
  start = index;
  ++index;
   
  while (index < length) {
  ch = nextChar();
   
  if (ch === quote) {
  quote = '';
  break;
  } else if (ch === '\\') {
  ch = nextChar();
  if (!isLineTerminator(ch)) {
  switch (ch) {
  case 'n':
  str += '\n';
  break;
  case 'r':
  str += '\r';
  break;
  case 't':
  str += '\t';
  break;
  case 'u':
  case 'x':
  restore = index;
  unescaped = scanHexEscape(ch);
  if (unescaped) {
  str += unescaped;
  } else {
  index = restore;
  str += ch;
  }
  break;
  case 'b':
  str += '\b';
  break;
  case 'f':
  str += '\f';
  break;
  case 'v':
  str += '\v';
  break;
   
  default:
  if (isOctalDigit(ch)) {
  code = '01234567'.indexOf(ch);
   
  // \0 is not octal escape sequence
  if (code !== 0) {
  octal = true;
  }
   
  if (index < length && isOctalDigit(source[index])) {
  octal = true;
  code = code * 8 + '01234567'.indexOf(nextChar());
   
  // 3 digits are only allowed when string starts
  // with 0, 1, 2, 3
  if ('0123'.indexOf(ch) >= 0 &&
  index < length &&
  isOctalDigit(source[index])) {
  code = code * 8 + '01234567'.indexOf(nextChar());
  }
  }
  str += String.fromCharCode(code);
  } else {
  str += ch;
  }
  break;
  }
  } else {
  ++lineNumber;
  if (ch === '\r' && source[index] === '\n') {
  ++index;
  }
  }
  } else if (isLineTerminator(ch)) {
  break;
  } else {
  str += ch;
  }
  }
   
  if (quote !== '') {
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
   
  return {
  type: Token.StringLiteral,
  value: str,
  octal: octal,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [start, index]
  };
  }
   
  function scanRegExp() {
  var str = '', ch, start, pattern, flags, value, classMarker = false, restore;
   
  buffer = null;
  skipComment();
   
  start = index;
  ch = source[index];
  assert(ch === '/', 'Regular expression literal must start with a slash');
  str = nextChar();
   
  while (index < length) {
  ch = nextChar();
  str += ch;
  if (classMarker) {
  if (ch === ']') {
  classMarker = false;
  }
  } else {
  if (ch === '\\') {
  ch = nextChar();
  // ECMA-262 7.8.5
  if (isLineTerminator(ch)) {
  throwError({}, Messages.UnterminatedRegExp);
  }
  str += ch;
  } else if (ch === '/') {
  break;
  } else if (ch === '[') {
  classMarker = true;
  } else if (isLineTerminator(ch)) {
  throwError({}, Messages.UnterminatedRegExp);
  }
  }
  }
   
  if (str.length === 1) {
  throwError({}, Messages.UnterminatedRegExp);
  }
   
  // Exclude leading and trailing slash.
  pattern = str.substr(1, str.length - 2);
   
  flags = '';
  while (index < length) {
  ch = source[index];
  if (!isIdentifierPart(ch)) {
  break;
  }
   
  ++index;
  if (ch === '\\' && index < length) {
  ch = source[index];
  if (ch === 'u') {
  ++index;
  restore = index;
  ch = scanHexEscape('u');
  if (ch) {
  flags += ch;
  str += '\\u';
  for (; restore < index; ++restore) {
  str += source[restore];
  }
  } else {
  index = restore;
  flags += 'u';
  str += '\\u';
  }
  } else {
  str += '\\';
  }
  } else {
  flags += ch;
  str += ch;
  }
  }
   
  try {
  value = new RegExp(pattern, flags);
  } catch (e) {
  throwError({}, Messages.InvalidRegExp);
  }
   
  return {
  literal: str,
  value: value,
  range: [start, index]
  };
  }
   
  function isIdentifierName(token) {
  return token.type === Token.Identifier ||
  token.type === Token.Keyword ||
  token.type === Token.BooleanLiteral ||
  token.type === Token.NullLiteral;
  }
   
  function advance() {
  var ch, token;
   
  skipComment();
   
  if (index >= length) {
  return {
  type: Token.EOF,
  lineNumber: lineNumber,
  lineStart: lineStart,
  range: [index, index]
  };
  }
   
  token = scanPunctuator();
  if (typeof token !== 'undefined') {
  return token;
  }
   
  ch = source[index];
   
  if (ch === '\'' || ch === '"') {
  return scanStringLiteral();
  }
   
  if (ch === '.' || isDecimalDigit(ch)) {
  return scanNumericLiteral();
  }
   
  token = scanIdentifier();
  if (typeof token !== 'undefined') {
  return token;
  }
   
  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  }
   
  function lex() {
  var token;
   
  if (buffer) {
  index = buffer.range[1];
  lineNumber = buffer.lineNumber;
  lineStart = buffer.lineStart;
  token = buffer;
  buffer = null;
  return token;
  }
   
  buffer = null;
  return advance();
  }
   
  function lookahead() {
  var pos, line, start;
   
  if (buffer !== null) {
  return buffer;
  }
   
  pos = index;
  line = lineNumber;
  start = lineStart;
  buffer = advance();
  index = pos;
  lineNumber = line;
  lineStart = start;
   
  return buffer;
  }
   
  // Return true if there is a line terminator before the next token.
   
  function peekLineTerminator() {
  var pos, line, start, found;
   
  pos = index;
  line = lineNumber;
  start = lineStart;
  skipComment();
  found = lineNumber !== line;
  index = pos;
  lineNumber = line;
  lineStart = start;
   
  return found;
  }
   
  // Throw an exception
   
  function throwError(token, messageFormat) {
  var error,
  args = Array.prototype.slice.call(arguments, 2),
  msg = messageFormat.replace(
  /%(\d)/g,
  function (whole, index) {
  return args[index] || '';
  }
  );
   
  if (typeof token.lineNumber === 'number') {
  error = new Error('Line ' + token.lineNumber + ': ' + msg);
  error.index = token.range[0];
  error.lineNumber = token.lineNumber;
  error.column = token.range[0] - lineStart + 1;
  } else {
  error = new Error('Line ' + lineNumber + ': ' + msg);
  error.index = index;
  error.lineNumber = lineNumber;
  error.column = index - lineStart + 1;
  }
   
  throw error;
  }
   
  function throwErrorTolerant() {
  var error;
  try {
  throwError.apply(null, arguments);
  } catch (e) {
  if (extra.errors) {
  extra.errors.push(e);
  } else {
  throw e;
  }
  }
  }
   
   
  // Throw an exception because of the token.
   
  function throwUnexpected(token) {
  var s;
   
  if (token.type === Token.EOF) {
  throwError(token, Messages.UnexpectedEOS);
  }
   
  if (token.type === Token.NumericLiteral) {
  throwError(token, Messages.UnexpectedNumber);
  }
   
  if (token.type === Token.StringLiteral) {
  throwError(token, Messages.UnexpectedString);
  }
   
  if (token.type === Token.Identifier) {
  throwError(token, Messages.UnexpectedIdentifier);
  }
   
  if (token.type === Token.Keyword) {
  if (isFutureReservedWord(token.value)) {
  throwError(token, Messages.UnexpectedReserved);
  } else if (strict && isStrictModeReservedWord(token.value)) {
  throwError(token, Messages.StrictReservedWord);
  }
  throwError(token, Messages.UnexpectedToken, token.value);
  }
   
  // BooleanLiteral, NullLiteral, or Punctuator.
  throwError(token, Messages.UnexpectedToken, token.value);
  }
   
  // Expect the next token to match the specified punctuator.
  // If not, an exception will be thrown.
   
  function expect(value) {
  var token = lex();
  if (token.type !== Token.Punctuator || token.value !== value) {
  throwUnexpected(token);
  }
  }
   
  // Expect the next token to match the specified keyword.
  // If not, an exception will be thrown.
   
  function expectKeyword(keyword) {
  var token = lex();
  if (token.type !== Token.Keyword || token.value !== keyword) {
  throwUnexpected(token);
  }
  }
   
  // Return true if the next token matches the specified punctuator.
   
  function match(value) {
  var token = lookahead();
  return token.type === Token.Punctuator && token.value === value;
  }
   
  // Return true if the next token matches the specified keyword
   
  function matchKeyword(keyword) {
  var token = lookahead();
  return token.type === Token.Keyword && token.value === keyword;
  }
   
  // Return true if the next token is an assignment operator
   
  function matchAssign() {
  var token = lookahead(),
  op = token.value;
   
  if (token.type !== Token.Punctuator) {
  return false;
  }
  return op === '=' ||
  op === '*=' ||
  op === '/=' ||
  op === '%=' ||
  op === '+=' ||
  op === '-=' ||
  op === '<<=' ||
  op === '>>=' ||
  op === '>>>=' ||
  op === '&=' ||
  op === '^=' ||
  op === '|=';
  }
   
  function consumeSemicolon() {
  var token, line;
   
  // Catch the very common case first.
  if (source[index] === ';') {
  lex();
  return;
  }
   
  line = lineNumber;
  skipComment();
  if (lineNumber !== line) {
  return;
  }
   
  if (match(';')) {
  lex();
  return;
  }
   
  token = lookahead();
  if (token.type !== Token.EOF && !match('}')) {
  throwUnexpected(token);
  }
  return;
  }
   
  // Return true if provided expression is LeftHandSideExpression
   
  function isLeftHandSide(expr) {
  return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
  }
   
  // 11.1.4 Array Initialiser
   
  function parseArrayInitialiser() {
  var elements = [],
  undef;
   
  expect('[');
   
  while (!match(']')) {
  if (match(',')) {
  lex();
  elements.push(undef);
  } else {
  elements.push(parseAssignmentExpression());
   
  if (!match(']')) {
  expect(',');
  }
  }
  }
   
  expect(']');
   
  return {
  type: Syntax.ArrayExpression,
  elements: elements
  };
  }
   
  // 11.1.5 Object Initialiser
   
  function parsePropertyFunction(param, first) {
  var previousStrict, body;
   
  previousStrict = strict;
  body = parseFunctionSourceElements();
  if (first && strict && isRestrictedWord(param[0].name)) {
  throwError(first, Messages.StrictParamName);
  }
  strict = previousStrict;
   
  return {
  type: Syntax.FunctionExpression,
  id: null,
  params: param,
  body: body
  };
  }
   
  function parseObjectPropertyKey() {
  var token = lex();
   
  // Note: This function is called only from parseObjectProperty(), where
  // EOF and Punctuator tokens are already filtered out.
   
  if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
  if (strict && token.octal) {
  throwError(token, Messages.StrictOctalLiteral);
  }
  return createLiteral(token);
  }
   
  return {
  type: Syntax.Identifier,
  name: token.value
  };
  }
   
  function parseObjectProperty() {
  var token, key, id, param;
   
  token = lookahead();
   
  if (token.type === Token.Identifier) {
   
  id = parseObjectPropertyKey();
   
  // Property Assignment: Getter and Setter.
   
  if (token.value === 'get' && !match(':')) {
  key = parseObjectPropertyKey();
  expect('(');
  expect(')');
  return {
  type: Syntax.Property,
  key: key,
  value: parsePropertyFunction([]),
  kind: 'get'
  };
  } else if (token.value === 'set' && !match(':')) {
  key = parseObjectPropertyKey();
  expect('(');
  token = lookahead();
  if (token.type !== Token.Identifier) {
  throwUnexpected(lex());
  }
  param = [ parseVariableIdentifier() ];
  expect(')');
  return {
  type: Syntax.Property,
  key: key,
  value: parsePropertyFunction(param, token),
  kind: 'set'
  };
  } else {
  expect(':');
  return {
  type: Syntax.Property,
  key: id,
  value: parseAssignmentExpression(),
  kind: 'init'
  };
  }
  } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
  throwUnexpected(token);
  } else {
  key = parseObjectPropertyKey();
  expect(':');
  return {
  type: Syntax.Property,
  key: key,
  value: parseAssignmentExpression(),
  kind: 'init'
  };
  }
  }
   
  function parseObjectInitialiser() {
  var token, properties = [], property, name, kind, map = {}, toString = String;
   
  expect('{');
   
  while (!match('}')) {
  property = parseObjectProperty();
   
  if (property.key.type === Syntax.Identifier) {
  name = property.key.name;
  } else {
  name = toString(property.key.value);
  }
  kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
  if (Object.prototype.hasOwnProperty.call(map, name)) {
  if (map[name] === PropertyKind.Data) {
  if (strict && kind === PropertyKind.Data) {
  throwErrorTolerant({}, Messages.StrictDuplicateProperty);
  } else if (kind !== PropertyKind.Data) {
  throwError({}, Messages.AccessorDataProperty);
  }
  } else {
  if (kind === PropertyKind.Data) {
  throwError({}, Messages.AccessorDataProperty);
  } else if (map[name] & kind) {
  throwError({}, Messages.AccessorGetSet);
  }
  }
  map[name] |= kind;
  } else {
  map[name] = kind;
  }
   
  properties.push(property);
   
  if (!match('}')) {
  expect(',');
  }
  }
   
  expect('}');
   
  return {
  type: Syntax.ObjectExpression,
  properties: properties
  };
  }
   
  // 11.1 Primary Expressions
   
  function parsePrimaryExpression() {
  var expr,
  token = lookahead(),
  type = token.type;
   
  if (type === Token.Identifier) {
  return {
  type: Syntax.Identifier,
  name: lex().value
  };
  }
   
  if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  if (strict && token.octal) {
  throwErrorTolerant(token, Messages.StrictOctalLiteral);
  }
  return createLiteral(lex());
  }
   
  if (type === Token.Keyword) {
  if (matchKeyword('this')) {
  lex();
  return {
  type: Syntax.ThisExpression
  };
  }
   
  if (matchKeyword('function')) {
  return parseFunctionExpression();
  }
  }
   
  if (type === Token.BooleanLiteral) {
  lex();
  token.value = (token.value === 'true');
  return createLiteral(token);
  }
   
  if (type === Token.NullLiteral) {
  lex();
  token.value = null;
  return createLiteral(token);
  }
   
  if (match('[')) {
  return parseArrayInitialiser();
  }
   
  if (match('{')) {
  return parseObjectInitialiser();
  }
   
  if (match('(')) {
  lex();
  state.lastParenthesized = expr = parseExpression();
  expect(')');
  return expr;
  }
   
  if (match('/') || match('/=')) {
  return createLiteral(scanRegExp());
  }
   
  return throwUnexpected(lex());
  }
   
  // 11.2 Left-Hand-Side Expressions
   
  function parseArguments() {
  var args = [];
   
  expect('(');
   
  if (!match(')')) {
  while (index < length) {
  args.push(parseAssignmentExpression());
  if (match(')')) {
  break;
  }
  expect(',');
  }
  }
   
  expect(')');
   
  return args;
  }
   
  function parseNonComputedProperty() {
  var token = lex();
   
  if (!isIdentifierName(token)) {
  throwUnexpected(token);
  }
   
  return {
  type: Syntax.Identifier,
  name: token.value
  };
  }
   
  function parseNonComputedMember(object) {
  return {
  type: Syntax.MemberExpression,
  computed: false,
  object: object,
  property: parseNonComputedProperty()
  };
  }
   
  function parseComputedMember(object) {
  var property, expr;
   
  expect('[');
  property = parseExpression();
  expr = {
  type: Syntax.MemberExpression,
  computed: true,
  object: object,
  property: property
  };
  expect(']');
  return expr;
  }
   
  function parseCallMember(object) {
  return {
  type: Syntax.CallExpression,
  callee: object,
  'arguments': parseArguments()
  };
  }
   
  function parseNewExpression() {
  var expr;
   
  expectKeyword('new');
   
  expr = {
  type: Syntax.NewExpression,
  callee: parseLeftHandSideExpression(),
  'arguments': []
  };
   
  if (match('(')) {
  expr['arguments'] = parseArguments();
  }
   
  return expr;
  }
   
  function parseLeftHandSideExpressionAllowCall() {
  var useNew, expr;
   
  useNew = matchKeyword('new');
  expr = useNew ? parseNewExpression() : parsePrimaryExpression();
   
  while (index < length) {
  if (match('.')) {
  lex();
  expr = parseNonComputedMember(expr);
  } else if (match('[')) {
  expr = parseComputedMember(expr);
  } else if (match('(')) {
  expr = parseCallMember(expr);
  } else {
  break;
  }
  }
   
  return expr;
  }
   
  function parseLeftHandSideExpression() {
  var useNew, expr;
   
  useNew = matchKeyword('new');
  expr = useNew ? parseNewExpression() : parsePrimaryExpression();
   
  while (index < length) {
  if (match('.')) {
  lex();
  expr = parseNonComputedMember(expr);
  } else if (match('[')) {
  expr = parseComputedMember(expr);
  } else {
  break;
  }
  }
   
  return expr;
  }
   
  // 11.3 Postfix Expressions
   
  function parsePostfixExpression() {
  var expr = parseLeftHandSideExpressionAllowCall();
   
  if ((match('++') || match('--')) && !peekLineTerminator()) {
  // 11.3.1, 11.3.2
  if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  throwError({}, Messages.StrictLHSPostfix);
  }
   
  if (!isLeftHandSide(expr)) {
  throwError({}, Messages.InvalidLHSInAssignment);
  }
   
  expr = {
  type: Syntax.UpdateExpression,
  operator: lex().value,
  argument: expr,
  prefix: false
  };
  }
   
  return expr;
  }
   
  // 11.4 Unary Operators
   
  function parseUnaryExpression() {
  var token, expr;
   
  if (match('++') || match('--')) {
  token = lex();
  expr = parseUnaryExpression();
  // 11.4.4, 11.4.5
  if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  throwError({}, Messages.StrictLHSPrefix);
  }
   
  if (!isLeftHandSide(expr)) {
  throwError({}, Messages.InvalidLHSInAssignment);
  }
   
  expr = {
  type: Syntax.UpdateExpression,
  operator: token.value,
  argument: expr,
  prefix: true
  };
  return expr;
  }
   
  if (match('+') || match('-') || match('~') || match('!')) {
  expr = {
  type: Syntax.UnaryExpression,
  operator: lex().value,
  argument: parseUnaryExpression()
  };
  return expr;
  }
   
  if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  expr = {
  type: Syntax.UnaryExpression,
  operator: lex().value,
  argument: parseUnaryExpression()
  };
  if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  throwErrorTolerant({}, Messages.StrictDelete);
  }
  return expr;
  }
   
  return parsePostfixExpression();
  }
   
  // 11.5 Multiplicative Operators
   
  function parseMultiplicativeExpression() {
  var expr = parseUnaryExpression();
   
  while (match('*') || match('/') || match('%')) {
  expr = {
  type: Syntax.BinaryExpression,
  operator: lex().value,
  left: expr,
  right: parseUnaryExpression()
  };
  }
   
  return expr;
  }
   
  // 11.6 Additive Operators
   
  function parseAdditiveExpression() {
  var expr = parseMultiplicativeExpression();
   
  while (match('+') || match('-')) {
  expr = {
  type: Syntax.BinaryExpression,
  operator: lex().value,
  left: expr,
  right: parseMultiplicativeExpression()
  };
  }
   
  return expr;
  }
   
  // 11.7 Bitwise Shift Operators
   
  function parseShiftExpression() {
  var expr = parseAdditiveExpression();
   
  while (match('<<') || match('>>') || match('>>>')) {
  expr = {
  type: Syntax.BinaryExpression,
  operator: lex().value,
  left: expr,
  right: parseAdditiveExpression()
  };
  }
   
  return expr;
  }
  // 11.8 Relational Operators
   
  function parseRelationalExpression() {
  var expr, previousAllowIn;
   
  previousAllowIn = state.allowIn;
  state.allowIn = true;
   
  expr = parseShiftExpression();
   
  while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
  expr = {
  type: Syntax.BinaryExpression,
  operator: lex().value,
  left: expr,
  right: parseShiftExpression()
  };
  }
   
  state.allowIn = previousAllowIn;
  return expr;
  }
   
  // 11.9 Equality Operators
   
  function parseEqualityExpression() {
  var expr = parseRelationalExpression();
   
  while (match('==') || match('!=') || match('===') || match('!==')) {
  expr = {