Skip to content

Instantly share code, notes, and snippets.

@kumavis kumavis/index.js
Last active Aug 29, 2015

Embed
What would you like to do?
requirebin sketch
Rx = require('rx-dom')
main()
// Search Wikipedia for a given term
function searchWikipedia(term) {
var cleanTerm = window.encodeURIComponent(term)
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=' + cleanTerm + '&callback=JSONPCallback'
return Rx.DOM.jsonpRequest(url)
}
function clearChildren(element) {
while (element.firstChild) {
element.removeChild(element.firstChild)
}
}
function buildPage() {
var label = document.createElement('label')
label.textContent = 'Enter Query for Wikipedia'
document.body.appendChild(label)
var input = document.createElement('input')
input.id = 'textInput'
input.type = 'text'
input.placeholder = 'Enter Query...'
document.body.appendChild(input)
var results = document.createElement('ul')
results.id = 'results'
document.body.appendChild(results)
}
function main() {
buildPage()
var input = document.querySelector('#textInput')
var results = document.querySelector('#results')
// Get changes to the input
var keyup = Rx.DOM.fromEvent(input, 'keyup')
// Project the text from the input
.map(function (e) { return e.target.value })
// Only if the text is longer than 2 characters
.filter(function (text) { return text.length > 2 })
/* Pause for 750ms */
.throttle(750)
// Only if the value has changed
.distinctUntilChanged()
// Search wikipedia
var searcher = keyup
.map(function (text) { return searchWikipedia(text) })
.switchLatest() // Ensure no out of order results
// Render results to DOM
var subscription = searcher.subscribe(
function (data) {
// Append the results
clearChildren(results)
var res = data[1]
var i, len, li
for (i = 0, len = res.length; i < len; i++) {
li = document.createElement('li')
li.innerHTML = res[i]
results.appendChild(li)
}
},
function (error) {
// Handle any errors
clearChildren(results)
var li = document.createElement('li')
li.innerHTML = 'Error: ' + error
results.appendChild(li)
}
)
}
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{throw TypeError('Uncaught, unspecified "error" event.')}return false}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){(function(global){(function(factory){var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var root=objectTypes[typeof window]&&window||this,freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}if(typeof define==="function"&&define.amd){define(["./rx","exports"],function(Rx,exports){root.Rx=factory(root,exports,Rx);return root.Rx})}else if(typeof module==="object"&&module&&module.exports===freeExports){module.exports=factory(root,module.exports,require("rx"))}else{root.Rx=factory(root,{},root.Rx)}}).call(this,function(root,exp,Rx,undefined){var Observable=Rx.Observable,observableProto=Observable.prototype,AnonymousObservable=Rx.AnonymousObservable,disposableCreate=Rx.Disposable.create,CompositeDisposable=Rx.CompositeDisposable,SingleAssignmentDisposable=Rx.SingleAssignmentDisposable,AsynsSubject=Rx.AsynsSubject,Subject=Rx.Subject,Scheduler=Rx.Scheduler,defaultNow=function(){return!!Date.now?Date.now:function(){return+new Date}}(),dom=Rx.DOM={},hasOwnProperty={}.hasOwnProperty,noop=Rx.helpers.noop;function createListener(element,name,handler){if(element.addEventListener){element.addEventListener(name,handler,false);return disposableCreate(function(){element.removeEventListener(name,handler,false)})}throw new Error("No listener found")}function createEventListener(el,eventName,handler){var disposables=new CompositeDisposable;if(Object.prototype.toString.call(el)==="[object NodeList]"){for(var i=0,len=el.length;i<len;i++){disposables.add(createEventListener(el.item(i),eventName,handler))}}else if(el){disposables.add(createListener(el,eventName,handler))}return disposables}var fromEvent=dom.fromEvent=function(element,eventName,selector){return new AnonymousObservable(function(observer){return createEventListener(element,eventName,function handler(e){var results=e;if(selector){try{results=selector(arguments)}catch(err){observer.onError(err);return}}observer.onNext(results)})}).publish().refCount()};(function(){var events="blur focus focusin focusout load resize scroll unload click dblclick "+"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave "+"change select submit keydown keypress keyup error contextmenu";if(root.PointerEvent){events+=" pointerdown pointerup pointermove pointerover pointerout pointerenter pointerleave"}if(root.TouchEvent){events+=" touchstart touchend touchmove touchcancel"}events=events.split(" ");for(var i=0,len=events.length;i<len;i++){(function(e){dom[e]=function(element,selector){return fromEvent(element,e,selector)}})(events[i])}})();dom.ready=function(){return new AnonymousObservable(function(observer){function handler(){observer.onNext();observer.onCompleted()}if(document.readyState==="complete"){setTimeout(handler,0)}else{document.addEventListener("DOMContentLoaded",handler,false);root.addEventListener("load",handler,false)}return function(){document.removeEventListener("DOMContentLoaded",handler,false);root.removeEventListener("load",handler,false)}}).publish().refCount()};function getXMLHttpRequest(){if(root.XMLHttpRequest){return new root.XMLHttpRequest}else{try{return new root.ActiveXObject("Microsoft.XMLHTTP")}catch(e){throw new Error("XMLHttpRequest is not supported by your browser")}}}var ajaxRequest=dom.ajax=function(settings){return new AnonymousObservable(function(observer){var isDone=false;if(typeof settings==="string"){settings={method:"GET",url:settings,async:true}}settings.method||(settings.method="GET");if(settings.async===undefined){settings.async=true}var xhr;try{xhr=getXMLHttpRequest()}catch(err){observer.onError(err)}try{if(settings.user){xhr.open(settings.method,settings.url,settings.async,settings.user,settings.password)}else{xhr.open(settings.method,settings.url,settings.async)}if(settings.headers){var headers=settings.headers;for(var header in headers){if(hasOwnProperty.call(headers,header)){xhr.setRequestHeader(header,headers[header])}}}xhr.onreadystatechange=xhr.onload=function(){if(xhr.readyState===4){var status=xhr.status;if(status>=200&&status<=300||status===0||status===""){observer.onNext(xhr);observer.onCompleted()}else{observer.onError(xhr)}isDone=true}};xhr.onerror=function(){observer.onError(xhr)};xhr.send(settings.body||null)}catch(e){observer.onError(e)}return function(){if(!isDone&&xhr.readyState!==4){xhr.abort()}}})};dom.post=function(url,body){return ajaxRequest({url:url,body:body,method:"POST",async:true})};var observableGet=dom.get=function(url){return ajaxRequest({url:url,method:"GET",async:true})};if(typeof JSON!=="undefined"&&typeof JSON.parse==="function"){dom.getJSON=function(url){return observableGet(url).map(function(xhr){return JSON.parse(xhr.responseText)})}}var destroy=function(){var trash=document.createElement("div");return function(element){trash.appendChild(element);trash.innerHTML=""}}();dom.jsonpRequest=function(){var uniqueId=0;var defaultCallback=function _defaultCallback(observer,data){observer.onNext(data);observer.onCompleted()};return function(settings){return new AnonymousObservable(function(observer){typeof settings==="string"&&(settings={url:settings});!settings.jsonp&&(settings.jsonp="JSONPCallback");var head=document.getElementsByTagName("head")[0]||document.documentElement,tag=document.createElement("script"),handler="rxjscallback"+uniqueId++;var prevFn;if(typeof settings.jsonpCallback==="string"){handler=settings.jsonpCallback;prevFn=root[handler]}settings.url=settings.url.replace("="+settings.jsonp,"="+handler);root[handler]=function(data){if(prevFn&&typeof prevFn==="function"){prevFn(observer,data)}else{defaultCallback(observer,data)}};var cleanup=function _cleanup(){tag.onload=tag.onreadystatechange=null;head&&tag.parentNode&&destroy(tag);tag=undefined;root[handler]=prevFn};tag.src=settings.url;tag.async=true;tag.onload=tag.onreadystatechange=function(_,abort){if(abort||!tag.readyState||/loaded|complete/.test(tag.readyState)){cleanup()}};head.insertBefore(tag,head.firstChild);return function(){if(!tag){return}cleanup()}})}}();if(!!root.WebSocket){dom.fromWebSocket=function(url,protocol,openObserver){var socket=new root.WebSocket(url,protocol);var observable=new AnonymousObservable(function(obs){if(observerOrOnNext){socket.onopen=function(openEvent){openObserver.onNext(openEvent);openObserver.onCompleted()}}socket.onmessage=function(data){obs.onNext(data)};socket.onerror=function(err){obs.onError(err)};socket.onclose=function(){obs.onCompleted()};return function(){socket.close()}});var observer=observerCreate(function(data){if(socket.readyState===WebSocket.OPEN){socket.send(data)}});return Subject.create(observer,observable)}}if(!!root.Worker){dom.fromWebWorker=function(url){var worker=new root.Worker(url);var observable=new AnonymousObservable(function(obs){worker.onmessage=function(data){obs.onNext(data)};worker.onerror=function(err){obs.onError(err)};return function(){worker.close()}});var observer=observerCreate(function(data){worker.postMessage(data)});return Subject.create(observer,observable)}}if(window.MutationObserver){dom.fromMutationObserver=function(target,options){return observableCreate(function(observer){var mutationObserver=new MutationObserver(function(mutations){observer.onNext(mutations)});mutationObserver.observe(target,options);return function(){mutationObserver.disconnect()}})}}var requestAnimFrame,cancelAnimFrame;if(root.requestAnimationFrame){requestAnimFrame=root.requestAnimationFrame;cancelAnimFrame=root.cancelAnimationFrame}else if(root.mozRequestAnimationFrame){requestAnimFrame=root.mozRequestAnimationFrame;cancelAnimFrame=root.mozCancelAnimationFrame}else if(root.webkitRequestAnimationFrame){requestAnimFrame=root.webkitRequestAnimationFrame;cancelAnimFrame=root.webkitCancelAnimationFrame}else if(root.msRequestAnimationFrame){requestAnimFrame=root.msRequestAnimationFrame;cancelAnimFrame=root.msCancelAnimationFrame}else if(root.oRequestAnimationFrame){requestAnimFrame=root.oRequestAnimationFrame;cancelAnimFrame=root.oCancelAnimationFrame}else{requestAnimFrame=function(cb){root.setTimeout(cb,1e3/60)};cancelAnimFrame=root.clearTimeout}Scheduler.requestAnimationFrame=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=requestAnimFrame(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))});return new CompositeDisposable(disposable,disposableCreate(function(){cancelAnimFrame(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime);if(dt===0){return scheduler.scheduleWithState(state,action)}var disposable=new SingleAssignmentDisposable,id;var scheduleFunc=function(){if(id){cancelAnimFrame(id)}if(dt-scheduler.now()<=0){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))}else{id=requestAnimFrame(scheduleFunc)}};id=requestAnimFrame(scheduleFunc);return new CompositeDisposable(disposable,disposableCreate(function(){cancelAnimFrame(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var BrowserMutationObserver=root.MutationObserver||root.WebKitMutationObserver;if(BrowserMutationObserver){Scheduler.mutationObserver=function(){var queue=[],queueId=0;var observer=new BrowserMutationObserver(function(){var toProcess=queue.slice(0);queue=[];toProcess.forEach(function(func){func()})});var element=document.createElement("div");observer.observe(element,{attributes:true});root.addEventListener("unload",function(){observer.disconnect();observer=null},false);function scheduleMethod(action){var id=queueId++;queue[id]=action;element.setAttribute("drainQueue","drainQueue");return id}function clearMethod(id){delete queue[id]}function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime);if(dt===0){return scheduler.scheduleWithState(state,action)}var disposable=new SingleAssignmentDisposable,id;var scheduleFunc=function(){if(id){clearMethod(id)}if(dt-scheduler.now()<=0){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))}else{id=scheduleMethod(scheduleFunc)}};id=scheduleMethod(scheduleFunc);return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}()}if("navigator"in root&&"geolocation"in root.navigator){Rx.DOM.geolocation={getCurrentPosition:function(geolocationOptions){return new AnonymousObservable(function(observer){root.navigator.geolocation.getCurrentPosition(observer.onNext.bind(observer),observer.onError.bind(observer),geolocationOptions)})},watchPosition:function(geolocationOptions){return new AnonymousObservable(function(observer){var watchId=root.navigator.geolocation.watchPosition(observer.onNext.bind(observer),observer.onError.bind(observer),geolocationOptions);return function(){root.navigator.geolocation.clearWatch(watchId)}}).publish().refCount()}}}return Rx})}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{rx:6}],4:[function(require,module,exports){(function(process,global){(function(undefined){var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var root=objectTypes[typeof window]&&window||this,freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}var Rx={internals:{},config:{Promise:root.Promise},helpers:{}};var noop=Rx.helpers.noop=function(){},notDefined=Rx.helpers.notDefined=function(x){return typeof x==="undefined"},isScheduler=Rx.helpers.isScheduler=function(x){return x instanceof Rx.Scheduler},identity=Rx.helpers.identity=function(x){return x},pluck=Rx.helpers.pluck=function(property){return function(x){return x[property]}},just=Rx.helpers.just=function(value){return function(){return value}},defaultNow=Rx.helpers.defaultNow=Date.now,defaultComparer=Rx.helpers.defaultComparer=function(x,y){return isEqual(x,y)},defaultSubComparer=Rx.helpers.defaultSubComparer=function(x,y){return x>y?1:x<y?-1:0},defaultKeySerializer=Rx.helpers.defaultKeySerializer=function(x){return x.toString()},defaultError=Rx.helpers.defaultError=function(err){throw err},isPromise=Rx.helpers.isPromise=function(p){return!!p&&typeof p.then==="function"},asArray=Rx.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},not=Rx.helpers.not=function(a){return!a},isFunction=Rx.helpers.isFunction=function(){var isFn=function(value){return typeof value=="function"||false};if(isFn(/x/)){isFn=function(value){return typeof value=="function"&&toString.call(value)=="[object Function]"}}return isFn}();var sequenceContainsNoElements="Sequence contains no elements.";var argumentOutOfRange="Argument out of range";var objectDisposed="Object has been disposed";function checkDisposed(){if(this.isDisposed){throw new Error(objectDisposed)}}var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(root.Set&&typeof(new root.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var doneEnumerator=Rx.doneEnumerator={done:true,value:undefined};Rx.iterator=$iterator$;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",errorClass="[object Error]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var toString=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,supportsArgsClass=toString.call(arguments)==argsClass,suportNodeClass,errorProto=Error.prototype,objectProto=Object.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable;try{suportNodeClass=!(toString.call(document)==objectClass&&!({toString:0}+""))}catch(e){suportNodeClass=true}var shadowedProps=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"];var nonEnumProps={};nonEnumProps[arrayClass]=nonEnumProps[dateClass]=nonEnumProps[numberClass]={constructor:true,toLocaleString:true,toString:true,valueOf:true};nonEnumProps[boolClass]=nonEnumProps[stringClass]={constructor:true,toString:true,valueOf:true};nonEnumProps[errorClass]=nonEnumProps[funcClass]=nonEnumProps[regexpClass]={constructor:true,toString:true};nonEnumProps[objectClass]={constructor:true};var support={};(function(){var ctor=function(){this.x=1},props=[];ctor.prototype={valueOf:1,y:1};for(var key in new ctor){props.push(key)}for(key in arguments){}support.enumErrorProps=propertyIsEnumerable.call(errorProto,"message")||propertyIsEnumerable.call(errorProto,"name");support.enumPrototypes=propertyIsEnumerable.call(ctor,"prototype");support.nonEnumArgs=key!=0;support.nonEnumShadows=!/valueOf/.test(props)})(1);function isObject(value){var type=typeof value;return value&&(type=="function"||type=="object")||false}function keysIn(object){var result=[];if(!isObject(object)){return result}if(support.nonEnumArgs&&object.length&&isArguments(object)){object=slice.call(object)}var skipProto=support.enumPrototypes&&typeof object=="function",skipErrorProps=support.enumErrorProps&&(object===errorProto||object instanceof Error);for(var key in object){if(!(skipProto&&key=="prototype")&&!(skipErrorProps&&(key=="message"||key=="name"))){result.push(key)}}if(support.nonEnumShadows&&object!==objectProto){var ctor=object.constructor,index=-1,length=shadowedProps.length;if(object===(ctor&&ctor.prototype)){var className=object===stringProto?stringClass:object===errorProto?errorClass:toString.call(object),nonEnum=nonEnumProps[className]}while(++index<length){key=shadowedProps[index];if(!(nonEnum&&nonEnum[key])&&hasOwnProperty.call(object,key)){result.push(key)}}}return result}function internalFor(object,callback,keysFunc){var index=-1,props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(callback(object[key],key,object)===false){break}}return object}function internalForIn(object,callback){return internalFor(object,callback,keysIn)}function isNode(value){return typeof value.toString!="function"&&typeof(value+"")=="string"}function isArguments(value){return value&&typeof value=="object"?toString.call(value)==argsClass:false}if(!supportsArgsClass){isArguments=function(value){return value&&typeof value=="object"?hasOwnProperty.call(value,"callee"):false}}var isEqual=Rx.internals.isEqual=function(x,y){return deepEquals(x,y,[],[])};function deepEquals(a,b,stackA,stackB){if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&(a==null||b==null||type!="function"&&type!="object"&&otherType!="function"&&otherType!="object")){return false}var className=toString.call(a),otherClass=toString.call(b);if(className==argsClass){className=objectClass}if(otherClass==argsClass){otherClass=objectClass}if(className!=otherClass){return false}switch(className){case boolClass:case dateClass:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){if(className!=objectClass||!support.nodeClass&&(isNode(a)||isNode(b))){return false}var ctorA=!support.argsObject&&isArguments(a)?Object:a.constructor,ctorB=!support.argsObject&&isArguments(b)?Object:b.constructor;if(ctorA!=ctorB&&!(hasOwnProperty.call(a,"constructor")&&hasOwnProperty.call(b,"constructor"))&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result){while(size--){var index=length,value=b[size];if(!(result=deepEquals(a[size],value,stackA,stackB))){break}}}}else{internalForIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&deepEquals(a[key],value,stackA,stackB)}});if(result){internalForIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();return result}var slice=Array.prototype.slice;function argsOrArray(args,idx){return args.length===1&&Array.isArray(args[idx])?args[idx]:slice.call(args)}var hasProp={}.hasOwnProperty;var inherits=this.inherits=Rx.internals.inherits=function(child,parent){function __(){this.constructor=child}__.prototype=parent.prototype;child.prototype=new __};var addProperties=Rx.internals.addProperties=function(obj){var sources=slice.call(arguments,1);for(var i=0,len=sources.length;i<len;i++){var source=sources[i];for(var prop in source){obj[prop]=source[prop]}}};var addRef=Rx.internals.addRef=function(xs,r){return new AnonymousObservable(function(observer){return new CompositeDisposable(r.getDisposable(),xs.subscribe(observer))})};function arrayInitialize(count,factory){var a=new Array(count);for(var i=0;i<count;i++){a[i]=factory()}return a}function IndexedItem(id,value){this.id=id;this.value=value}IndexedItem.prototype.compareTo=function(other){var c=this.value.compareTo(other.value);c===0&&(c=this.id-other.id);return c};var PriorityQueue=Rx.internals.PriorityQueue=function(capacity){this.items=new Array(capacity);this.length=0};var priorityProto=PriorityQueue.prototype;priorityProto.isHigherPriority=function(left,right){return this.items[left].compareTo(this.items[right])<0};priorityProto.percolate=function(index){if(index>=this.length||index<0){return}var parent=index-1>>1;if(parent<0||parent===index){return}if(this.isHigherPriority(index,parent)){var temp=this.items[index];this.items[index]=this.items[parent];this.items[parent]=temp;this.percolate(parent)}};priorityProto.heapify=function(index){+index||(index=0);if(index>=this.length||index<0){return}var left=2*index+1,right=2*index+2,first=index;if(left<this.length&&this.isHigherPriority(left,first)){first=left}if(right<this.length&&this.isHigherPriority(right,first)){first=right}if(first!==index){var temp=this.items[index];this.items[index]=this.items[first];this.items[first]=temp;this.heapify(first)}};priorityProto.peek=function(){return this.items[0].value};priorityProto.removeAt=function(index){this.items[index]=this.items[--this.length];delete this.items[this.length];this.heapify()};priorityProto.dequeue=function(){var result=this.peek();this.removeAt(0);return result};priorityProto.enqueue=function(item){var index=this.length++;this.items[index]=new IndexedItem(PriorityQueue.count++,item);this.percolate(index)};priorityProto.remove=function(item){for(var i=0;i<this.length;i++){if(this.items[i].value===item){this.removeAt(i);return true}}return false};PriorityQueue.count=0;var CompositeDisposable=Rx.CompositeDisposable=function(){this.disposables=argsOrArray(arguments,0);this.isDisposed=false;this.length=this.disposables.length};var CompositeDisposablePrototype=CompositeDisposable.prototype;CompositeDisposablePrototype.add=function(item){if(this.isDisposed){item.dispose()}else{this.disposables.push(item);this.length++}};CompositeDisposablePrototype.remove=function(item){var shouldDispose=false;if(!this.isDisposed){var idx=this.disposables.indexOf(item);if(idx!==-1){shouldDispose=true;this.disposables.splice(idx,1);this.length--;item.dispose()}}return shouldDispose};CompositeDisposablePrototype.dispose=function(){if(!this.isDisposed){this.isDisposed=true;var currentDisposables=this.disposables.slice(0);this.disposables=[];this.length=0;for(var i=0,len=currentDisposables.length;i<len;i++){currentDisposables[i].dispose()}}};CompositeDisposablePrototype.toArray=function(){return this.disposables.slice(0)};var Disposable=Rx.Disposable=function(action){this.isDisposed=false;this.action=action||noop};Disposable.prototype.dispose=function(){if(!this.isDisposed){this.action();this.isDisposed=true}};var disposableCreate=Disposable.create=function(action){return new Disposable(action)};var disposableEmpty=Disposable.empty={dispose:noop};var SingleAssignmentDisposable=Rx.SingleAssignmentDisposable=function(){function BooleanDisposable(){this.isDisposed=false;this.current=null}var booleanDisposablePrototype=BooleanDisposable.prototype;booleanDisposablePrototype.getDisposable=function(){return this.current};booleanDisposablePrototype.setDisposable=function(value){var shouldDispose=this.isDisposed,old;if(!shouldDispose){old=this.current;this.current=value}old&&old.dispose();shouldDispose&&value&&value.dispose()};booleanDisposablePrototype.dispose=function(){var old;if(!this.isDisposed){this.isDisposed=true;old=this.current;this.current=null}old&&old.dispose()};return BooleanDisposable}();var SerialDisposable=Rx.SerialDisposable=SingleAssignmentDisposable;var RefCountDisposable=Rx.RefCountDisposable=function(){function InnerDisposable(disposable){this.disposable=disposable;this.disposable.count++;this.isInnerDisposed=false}InnerDisposable.prototype.dispose=function(){if(!this.disposable.isDisposed){if(!this.isInnerDisposed){this.isInnerDisposed=true;this.disposable.count--;if(this.disposable.count===0&&this.disposable.isPrimaryDisposed){this.disposable.isDisposed=true;this.disposable.underlyingDisposable.dispose()}}}};function RefCountDisposable(disposable){this.underlyingDisposable=disposable;this.isDisposed=false;this.isPrimaryDisposed=false;this.count=0}RefCountDisposable.prototype.dispose=function(){if(!this.isDisposed){if(!this.isPrimaryDisposed){this.isPrimaryDisposed=true;if(this.count===0){this.isDisposed=true;this.underlyingDisposable.dispose()}}}};RefCountDisposable.prototype.getDisposable=function(){return this.isDisposed?disposableEmpty:new InnerDisposable(this)};return RefCountDisposable}();function ScheduledDisposable(scheduler,disposable){this.scheduler=scheduler;this.disposable=disposable;this.isDisposed=false}ScheduledDisposable.prototype.dispose=function(){var parent=this;this.scheduler.schedule(function(){if(!parent.isDisposed){parent.isDisposed=true;parent.disposable.dispose()}})};var ScheduledItem=Rx.internals.ScheduledItem=function(scheduler,state,action,dueTime,comparer){this.scheduler=scheduler;this.state=state;this.action=action;this.dueTime=dueTime;this.comparer=comparer||defaultSubComparer;this.disposable=new SingleAssignmentDisposable};ScheduledItem.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())};ScheduledItem.prototype.compareTo=function(other){return this.comparer(this.dueTime,other.dueTime)};ScheduledItem.prototype.isCancelled=function(){return this.disposable.isDisposed
};ScheduledItem.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Scheduler=Rx.Scheduler=function(){function Scheduler(now,schedule,scheduleRelative,scheduleAbsolute){this.now=now;this._schedule=schedule;this._scheduleRelative=scheduleRelative;this._scheduleAbsolute=scheduleAbsolute}function invokeRecImmediate(scheduler,pair){var state=pair.first,action=pair.second,group=new CompositeDisposable,recursiveAction=function(state1){action(state1,function(state2){var isAdded=false,isDone=false,d=scheduler.scheduleWithState(state2,function(scheduler1,state3){if(isAdded){group.remove(d)}else{isDone=true}recursiveAction(state3);return disposableEmpty});if(!isDone){group.add(d);isAdded=true}})};recursiveAction(state);return group}function invokeRecDate(scheduler,pair,method){var state=pair.first,action=pair.second,group=new CompositeDisposable,recursiveAction=function(state1){action(state1,function(state2,dueTime1){var isAdded=false,isDone=false,d=scheduler[method].call(scheduler,state2,dueTime1,function(scheduler1,state3){if(isAdded){group.remove(d)}else{isDone=true}recursiveAction(state3);return disposableEmpty});if(!isDone){group.add(d);isAdded=true}})};recursiveAction(state);return group}function invokeAction(scheduler,action){action();return disposableEmpty}var schedulerProto=Scheduler.prototype;schedulerProto.schedule=function(action){return this._schedule(action,invokeAction)};schedulerProto.scheduleWithState=function(state,action){return this._schedule(state,action)};schedulerProto.scheduleWithRelative=function(dueTime,action){return this._scheduleRelative(action,dueTime,invokeAction)};schedulerProto.scheduleWithRelativeAndState=function(state,dueTime,action){return this._scheduleRelative(state,dueTime,action)};schedulerProto.scheduleWithAbsolute=function(dueTime,action){return this._scheduleAbsolute(action,dueTime,invokeAction)};schedulerProto.scheduleWithAbsoluteAndState=function(state,dueTime,action){return this._scheduleAbsolute(state,dueTime,action)};Scheduler.now=defaultNow;Scheduler.normalize=function(timeSpan){timeSpan<0&&(timeSpan=0);return timeSpan};return Scheduler}();var normalizeTime=Scheduler.normalize;(function(schedulerProto){function invokeRecImmediate(scheduler,pair){var state=pair.first,action=pair.second,group=new CompositeDisposable,recursiveAction=function(state1){action(state1,function(state2){var isAdded=false,isDone=false,d=scheduler.scheduleWithState(state2,function(scheduler1,state3){if(isAdded){group.remove(d)}else{isDone=true}recursiveAction(state3);return disposableEmpty});if(!isDone){group.add(d);isAdded=true}})};recursiveAction(state);return group}function invokeRecDate(scheduler,pair,method){var state=pair.first,action=pair.second,group=new CompositeDisposable,recursiveAction=function(state1){action(state1,function(state2,dueTime1){var isAdded=false,isDone=false,d=scheduler[method].call(scheduler,state2,dueTime1,function(scheduler1,state3){if(isAdded){group.remove(d)}else{isDone=true}recursiveAction(state3);return disposableEmpty});if(!isDone){group.add(d);isAdded=true}})};recursiveAction(state);return group}function scheduleInnerRecursive(action,self){action(function(dt){self(action,dt)})}schedulerProto.scheduleRecursive=function(action){return this.scheduleRecursiveWithState(action,function(_action,self){_action(function(){self(_action)})})};schedulerProto.scheduleRecursiveWithState=function(state,action){return this.scheduleWithState({first:state,second:action},invokeRecImmediate)};schedulerProto.scheduleRecursiveWithRelative=function(dueTime,action){return this.scheduleRecursiveWithRelativeAndState(action,dueTime,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithRelativeAndState=function(state,dueTime,action){return this._scheduleRelative({first:state,second:action},dueTime,function(s,p){return invokeRecDate(s,p,"scheduleWithRelativeAndState")})};schedulerProto.scheduleRecursiveWithAbsolute=function(dueTime,action){return this.scheduleRecursiveWithAbsoluteAndState(action,dueTime,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithAbsoluteAndState=function(state,dueTime,action){return this._scheduleAbsolute({first:state,second:action},dueTime,function(s,p){return invokeRecDate(s,p,"scheduleWithAbsoluteAndState")})}})(Scheduler.prototype);(function(schedulerProto){Scheduler.prototype.schedulePeriodic=function(period,action){return this.schedulePeriodicWithState(null,period,action)};Scheduler.prototype.schedulePeriodicWithState=function(state,period,action){if(typeof root.setInterval==="undefined"){throw new Error("Periodic scheduling not supported.")}var s=state;var id=root.setInterval(function(){s=action(s)},period);return disposableCreate(function(){root.clearInterval(id)})}})(Scheduler.prototype);(function(schedulerProto){schedulerProto.catchError=schedulerProto["catch"]=function(handler){return new CatchScheduler(this,handler)}})(Scheduler.prototype);var SchedulePeriodicRecursive=Rx.internals.SchedulePeriodicRecursive=function(){function tick(command,recurse){recurse(0,this._period);try{this._state=this._action(this._state)}catch(e){this._cancel.dispose();throw e}}function SchedulePeriodicRecursive(scheduler,state,period,action){this._scheduler=scheduler;this._state=state;this._period=period;this._action=action}SchedulePeriodicRecursive.prototype.start=function(){var d=new SingleAssignmentDisposable;this._cancel=d;d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,tick.bind(this)));return d};return SchedulePeriodicRecursive}();var immediateScheduler=Scheduler.immediate=function(){function scheduleNow(state,action){return action(this,state)}function scheduleRelative(state,dueTime,action){var dt=normalizeTime(dt);while(dt-this.now()>0){}return action(this,state)}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var currentThreadScheduler=Scheduler.currentThread=function(){var queue;function runTrampoline(q){var item;while(q.length>0){item=q.dequeue();if(!item.isCancelled()){while(item.dueTime-Scheduler.now()>0){}if(!item.isCancelled()){item.invoke()}}}}function scheduleNow(state,action){return this.scheduleWithRelativeAndState(state,0,action)}function scheduleRelative(state,dueTime,action){var dt=this.now()+Scheduler.normalize(dueTime),si=new ScheduledItem(this,state,action,dt);if(!queue){queue=new PriorityQueue(4);queue.enqueue(si);try{runTrampoline(queue)}catch(e){throw e}finally{queue=null}}else{queue.enqueue(si)}return si.disposable}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}var currentScheduler=new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute);currentScheduler.scheduleRequired=function(){return!queue};currentScheduler.ensureTrampoline=function(action){if(!queue){this.schedule(action)}else{action()}};return currentScheduler}();var scheduleMethod,clearMethod=noop;var localTimer=function(){var localSetTimeout,localClearTimeout=noop;if("WScript"in this){localSetTimeout=function(fn,time){WScript.Sleep(time);fn()}}else if(!!root.setTimeout){localSetTimeout=root.setTimeout;localClearTimeout=root.clearTimeout}else{throw new Error("No concurrency detected!")}return{setTimeout:localSetTimeout,clearTimeout:localClearTimeout}}();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var setImmediate=typeof(setImmediate=freeGlobal&&moduleExports&&freeGlobal.setImmediate)=="function"&&!reNative.test(setImmediate)&&setImmediate,clearImmediate=typeof(clearImmediate=freeGlobal&&moduleExports&&freeGlobal.clearImmediate)=="function"&&!reNative.test(clearImmediate)&&clearImmediate;function postMessageSupported(){if(!root.postMessage||root.importScripts){return false}var isAsync=false,oldHandler=root.onmessage;root.onmessage=function(){isAsync=true};root.postMessage("","*");root.onmessage=oldHandler;return isAsync}if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){scheduleMethod=process.nextTick}else if(typeof setImmediate==="function"){scheduleMethod=setImmediate;clearMethod=clearImmediate}else if(postMessageSupported()){var MSG_PREFIX="ms.rx.schedule"+Math.random(),tasks={},taskId=0;function onGlobalPostMessage(event){if(typeof event.data==="string"&&event.data.substring(0,MSG_PREFIX.length)===MSG_PREFIX){var handleId=event.data.substring(MSG_PREFIX.length),action=tasks[handleId];action();delete tasks[handleId]}}if(root.addEventListener){root.addEventListener("message",onGlobalPostMessage,false)}else{root.attachEvent("onmessage",onGlobalPostMessage,false)}scheduleMethod=function(action){var currentId=taskId++;tasks[currentId]=action;root.postMessage(MSG_PREFIX+currentId,"*")}}else if(!!root.MessageChannel){var channel=new root.MessageChannel,channelTasks={},channelTaskId=0;channel.port1.onmessage=function(event){var id=event.data,action=channelTasks[id];action();delete channelTasks[id]};scheduleMethod=function(action){var id=channelTaskId++;channelTasks[id]=action;channel.port2.postMessage(id)}}else if("document"in root&&"onreadystatechange"in root.document.createElement("script")){scheduleMethod=function(action){var scriptElement=root.document.createElement("script");scriptElement.onreadystatechange=function(){action();scriptElement.onreadystatechange=null;scriptElement.parentNode.removeChild(scriptElement);scriptElement=null};root.document.documentElement.appendChild(scriptElement)}}else{scheduleMethod=function(action){return localSetTimeout(action,0)};clearMethod=localClearTimeout}})();var timeoutScheduler=Scheduler.timeout=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){if(!disposable.isDisposed){disposable.setDisposable(action(scheduler,state))}});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime);if(dt===0){return scheduler.scheduleWithState(state,action)}var disposable=new SingleAssignmentDisposable;var id=localSetTimeout(function(){if(!disposable.isDisposed){disposable.setDisposable(action(scheduler,state))}},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var CatchScheduler=function(_super){function localNow(){return this._scheduler.now()}function scheduleNow(state,action){return this._scheduler.scheduleWithState(state,this._wrap(action))}function scheduleRelative(state,dueTime,action){return this._scheduler.scheduleWithRelativeAndState(state,dueTime,this._wrap(action))}function scheduleAbsolute(state,dueTime,action){return this._scheduler.scheduleWithAbsoluteAndState(state,dueTime,this._wrap(action))}inherits(CatchScheduler,_super);function CatchScheduler(scheduler,handler){this._scheduler=scheduler;this._handler=handler;this._recursiveOriginal=null;this._recursiveWrapper=null;_super.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}CatchScheduler.prototype._clone=function(scheduler){return new CatchScheduler(scheduler,this._handler)};CatchScheduler.prototype._wrap=function(action){var parent=this;return function(self,state){try{return action(parent._getRecursiveWrapper(self),state)}catch(e){if(!parent._handler(e)){throw e}return disposableEmpty}}};CatchScheduler.prototype._getRecursiveWrapper=function(scheduler){if(this._recursiveOriginal!==scheduler){this._recursiveOriginal=scheduler;var wrapper=this._clone(scheduler);wrapper._recursiveOriginal=scheduler;wrapper._recursiveWrapper=wrapper;this._recursiveWrapper=wrapper}return this._recursiveWrapper};CatchScheduler.prototype.schedulePeriodicWithState=function(state,period,action){var self=this,failed=false,d=new SingleAssignmentDisposable;d.setDisposable(this._scheduler.schedulePeriodicWithState(state,period,function(state1){if(failed){return null}try{return action(state1)}catch(e){failed=true;if(!self._handler(e)){throw e}d.dispose();return null}}));return d};return CatchScheduler}(Scheduler);var Notification=Rx.Notification=function(){function Notification(kind,hasValue){this.hasValue=hasValue==null?false:hasValue;this.kind=kind}Notification.prototype.accept=function(observerOrOnNext,onError,onCompleted){return observerOrOnNext&&typeof observerOrOnNext==="object"?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted)};Notification.prototype.toObservable=function(scheduler){var notification=this;isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){notification._acceptObservable(observer);notification.kind==="N"&&observer.onCompleted()})})};return Notification}();var notificationCreateOnNext=Notification.createOnNext=function(){function _accept(onNext){return onNext(this.value)}function _acceptObservable(observer){return observer.onNext(this.value)}function toString(){return"OnNext("+this.value+")"}return function(value){var notification=new Notification("N",true);notification.value=value;notification._accept=_accept;notification._acceptObservable=_acceptObservable;notification.toString=toString;return notification}}();var notificationCreateOnError=Notification.createOnError=function(){function _accept(onNext,onError){return onError(this.exception)}function _acceptObservable(observer){return observer.onError(this.exception)}function toString(){return"OnError("+this.exception+")"}return function(exception){var notification=new Notification("E");notification.exception=exception;notification._accept=_accept;notification._acceptObservable=_acceptObservable;notification.toString=toString;return notification}}();var notificationCreateOnCompleted=Notification.createOnCompleted=function(){function _accept(onNext,onError,onCompleted){return onCompleted()}function _acceptObservable(observer){return observer.onCompleted()}function toString(){return"OnCompleted()"}return function(){var notification=new Notification("C");notification._accept=_accept;notification._acceptObservable=_acceptObservable;notification.toString=toString;return notification}}();var Enumerator=Rx.internals.Enumerator=function(next){this._next=next};Enumerator.prototype.next=function(){return this._next()};Enumerator.prototype[$iterator$]=function(){return this};var Enumerable=Rx.internals.Enumerable=function(iterator){this._iterator=iterator};Enumerable.prototype[$iterator$]=function(){return this._iterator()};Enumerable.prototype.concat=function(){var sources=this;return new AnonymousObservable(function(observer){var e;try{e=sources[$iterator$]()}catch(err){observer.onError();return}var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){var currentItem;if(isDisposed){return}try{currentItem=e.next()}catch(ex){observer.onError(ex);return}if(currentItem.done){observer.onCompleted();return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){self()}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};Enumerable.prototype.catchException=function(){var sources=this;return new AnonymousObservable(function(observer){var e;try{e=sources[$iterator$]()}catch(err){observer.onError();return}var isDisposed,lastException,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}var currentItem;try{currentItem=e.next()}catch(ex){observer.onError(ex);return}if(currentItem.done){if(lastException){observer.onError(lastException)}else{observer.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(observer.onNext.bind(observer),function(exn){lastException=exn;self()},observer.onCompleted.bind(observer)))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};var enumerableRepeat=Enumerable.repeat=function(value,repeatCount){if(repeatCount==null){repeatCount=-1}return new Enumerable(function(){var left=repeatCount;return new Enumerator(function(){if(left===0){return doneEnumerator}if(left>0){left--}return{done:false,value:value}})})};var enumerableOf=Enumerable.of=function(source,selector,thisArg){selector||(selector=identity);return new Enumerable(function(){var index=-1;return new Enumerator(function(){return++index<source.length?{done:false,value:selector.call(thisArg,source[index],index,source)}:doneEnumerator})})};var Observer=Rx.Observer=function(){};Observer.prototype.toNotifier=function(){var observer=this;return function(n){return n.accept(observer)}};Observer.prototype.asObserver=function(){return new AnonymousObserver(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))};Observer.prototype.checked=function(){return new CheckedObserver(this)};var observerCreate=Observer.create=function(onNext,onError,onCompleted){onNext||(onNext=noop);onError||(onError=defaultError);onCompleted||(onCompleted=noop);return new AnonymousObserver(onNext,onError,onCompleted)};Observer.fromNotifier=function(handler,thisArg){return new AnonymousObserver(function(x){return handler.call(thisArg,notificationCreateOnNext(x))},function(e){return handler.call(thisArg,notificationCreateOnError(e))},function(){return handler.call(thisArg,notificationCreateOnCompleted())})};Observer.notifyOn=function(scheduler){return new ObserveOnObserver(scheduler,this)};var AbstractObserver=Rx.internals.AbstractObserver=function(__super__){inherits(AbstractObserver,__super__);function AbstractObserver(){this.isStopped=false;__super__.call(this)}AbstractObserver.prototype.onNext=function(value){if(!this.isStopped){this.next(value)}};AbstractObserver.prototype.onError=function(error){if(!this.isStopped){this.isStopped=true;this.error(error)}};AbstractObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.completed()}};AbstractObserver.prototype.dispose=function(){this.isStopped=true};AbstractObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.error(e);return true}return false};return AbstractObserver}(Observer);var AnonymousObserver=Rx.AnonymousObserver=function(__super__){inherits(AnonymousObserver,__super__);function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext=onNext;this._onError=onError;this._onCompleted=onCompleted}AnonymousObserver.prototype.next=function(value){this._onNext(value)};AnonymousObserver.prototype.error=function(error){this._onError(error)};AnonymousObserver.prototype.completed=function(){this._onCompleted()};return AnonymousObserver}(AbstractObserver);var CheckedObserver=function(_super){inherits(CheckedObserver,_super);function CheckedObserver(observer){_super.call(this);this._observer=observer;this._state=0}var CheckedObserverPrototype=CheckedObserver.prototype;CheckedObserverPrototype.onNext=function(value){this.checkAccess();try{this._observer.onNext(value)}catch(e){throw e}finally{this._state=0}};CheckedObserverPrototype.onError=function(err){this.checkAccess();try{this._observer.onError(err)}catch(e){throw e}finally{this._state=2}};CheckedObserverPrototype.onCompleted=function(){this.checkAccess();try{this._observer.onCompleted()}catch(e){throw e}finally{this._state=2}};CheckedObserverPrototype.checkAccess=function(){if(this._state===1){throw new Error("Re-entrancy detected")}if(this._state===2){throw new Error("Observer completed")}if(this._state===0){this._state=1}};return CheckedObserver}(Observer);var ScheduledObserver=Rx.internals.ScheduledObserver=function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler=scheduler;this.observer=observer;this.isAcquired=false;this.hasFaulted=false;this.queue=[];this.disposable=new SerialDisposable}ScheduledObserver.prototype.next=function(value){var self=this;this.queue.push(function(){self.observer.onNext(value)})};ScheduledObserver.prototype.error=function(err){var self=this;this.queue.push(function(){self.observer.onError(err)})};ScheduledObserver.prototype.completed=function(){var self=this;this.queue.push(function(){self.observer.onCompleted()})};ScheduledObserver.prototype.ensureActive=function(){var isOwner=false,parent=this;if(!this.hasFaulted&&this.queue.length>0){isOwner=!this.isAcquired;this.isAcquired=true}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(self){var work;if(parent.queue.length>0){work=parent.queue.shift()}else{parent.isAcquired=false;return}try{work()}catch(ex){parent.queue=[];parent.hasFaulted=true;throw ex}self()}))}};ScheduledObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this.disposable.dispose()};return ScheduledObserver}(AbstractObserver);var ObserveOnObserver=function(__super__){inherits(ObserveOnObserver,__super__);function ObserveOnObserver(){__super__.apply(this,arguments)}ObserveOnObserver.prototype.next=function(value){__super__.prototype.next.call(this,value);this.ensureActive()};ObserveOnObserver.prototype.error=function(e){__super__.prototype.error.call(this,e);this.ensureActive()};ObserveOnObserver.prototype.completed=function(){__super__.prototype.completed.call(this);this.ensureActive()};return ObserveOnObserver}(ScheduledObserver);var observableProto;var Observable=Rx.Observable=function(){function Observable(subscribe){this._subscribe=subscribe}observableProto=Observable.prototype;observableProto.subscribe=observableProto.forEach=function(observerOrOnNext,onError,onCompleted){return this._subscribe(typeof observerOrOnNext==="object"?observerOrOnNext:observerCreate(observerOrOnNext,onError,onCompleted))};observableProto.subscribeOnNext=function(onNext,thisArg){return this._subscribe(observerCreate(arguments.length===2?function(x){onNext.call(thisArg,x)}:onNext))};observableProto.subscribeOnError=function(onError,thisArg){return this._subscribe(observerCreate(null,arguments.length===2?function(e){onError.call(thisArg,e)}:onError))};observableProto.subscribeOnCompleted=function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,arguments.length===2?function(){onCompleted.call(thisArg)}:onCompleted))};return Observable}();observableProto.observeOn=function(scheduler){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(new ObserveOnObserver(scheduler,observer))})};observableProto.subscribeOn=function(scheduler){var source=this;return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,d=new SerialDisposable;d.setDisposable(m);m.setDisposable(scheduler.schedule(function(){d.setDisposable(new ScheduledDisposable(scheduler,source.subscribe(observer)))}));return d})};var observableFromPromise=Observable.fromPromise=function(promise){return observableDefer(function(){var subject=new Rx.AsyncSubject;promise.then(function(value){if(!subject.isDisposed){subject.onNext(value);subject.onCompleted()}},subject.onError.bind(subject));return subject})};observableProto.toPromise=function(promiseCtor){promiseCtor||(promiseCtor=Rx.config.Promise);if(!promiseCtor){throw new TypeError("Promise type not provided nor in Rx.config.Promise")}var source=this;return new promiseCtor(function(resolve,reject){var value,hasValue=false;source.subscribe(function(v){value=v;hasValue=true},reject,function(){hasValue&&resolve(value)})})};observableProto.toArray=function(){var self=this;return new AnonymousObservable(function(observer){var arr=[];return self.subscribe(arr.push.bind(arr),observer.onError.bind(observer),function(){observer.onNext(arr);observer.onCompleted()})})};Observable.create=Observable.createWithDisposable=function(subscribe){return new AnonymousObservable(subscribe)};var observableDefer=Observable.defer=function(observableFactory){return new AnonymousObservable(function(observer){var result;try{result=observableFactory()}catch(e){return observableThrow(e).subscribe(observer)}isPromise(result)&&(result=observableFromPromise(result));return result.subscribe(observer)})};var observableEmpty=Observable.empty=function(scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){observer.onCompleted()})})};var maxSafeInteger=Math.pow(2,53)-1;function numberIsFinite(value){return typeof value==="number"&&root.isFinite(value)}function isNan(n){return n!==n}function isIterable(o){return o[$iterator$]!==undefined}function sign(value){var number=+value;if(number===0){return number}if(isNaN(number)){return number}return number<0?-1:1}function toLength(o){var len=+o.length;if(isNaN(len)){return 0}if(len===0||!numberIsFinite(len)){return len}len=sign(len)*Math.floor(Math.abs(len));if(len<=0){return 0}if(len>maxSafeInteger){return maxSafeInteger}return len}function isCallable(f){return Object.prototype.toString.call(f)==="[object Function]"&&typeof f==="function"}Observable.from=function(iterable,mapFn,thisArg,scheduler){if(iterable==null){throw new Error("iterable cannot be null.")}if(mapFn&&!isCallable(mapFn)){throw new Error("mapFn when provided must be a function")}isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new AnonymousObservable(function(observer){var list=Object(iterable),objIsIterable=isIterable(list),len=objIsIterable?0:toLength(list),it=objIsIterable?list[$iterator$]():null,i=0;return scheduler.scheduleRecursive(function(self){if(i<len||objIsIterable){var result;if(objIsIterable){var next=it.next();if(next.done){observer.onCompleted();return}result=next.value}else{result=list[i]}if(mapFn&&isCallable(mapFn)){try{result=thisArg?mapFn.call(thisArg,result,i):mapFn(result,i)}catch(e){observer.onError(e);return}}observer.onNext(result);i++;self()}else{observer.onCompleted()}})})};var observableFromArray=Observable.fromArray=function(array,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new AnonymousObservable(function(observer){var count=0,len=array.length;return scheduler.scheduleRecursive(function(self){if(count<len){observer.onNext(array[count++]);self()}else{observer.onCompleted()}})})};Observable.generate=function(initialState,condition,iterate,resultSelector,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new AnonymousObservable(function(observer){var first=true,state=initialState;return scheduler.scheduleRecursive(function(self){var hasResult,result;try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){result=resultSelector(state)}}catch(exception){observer.onError(exception);return}if(hasResult){observer.onNext(result);self()}else{observer.onCompleted()}})})};Observable.of=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}return observableFromArray(args)};var observableOf=Observable.ofWithScheduler=function(scheduler){var len=arguments.length-1,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i+1]}return observableFromArray(args,scheduler)};var observableNever=Observable.never=function(){return new AnonymousObservable(function(){return disposableEmpty})};Observable.range=function(start,count,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleRecursiveWithState(0,function(i,self){if(i<count){observer.onNext(start+i);self(i+1)}else{observer.onCompleted()}})})};Observable.repeat=function(value,repeatCount,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return observableReturn(value,scheduler).repeat(repeatCount==null?-1:repeatCount)};var observableReturn=Observable["return"]=Observable.returnValue=Observable.just=function(value,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){observer.onNext(value);observer.onCompleted()})})};var observableThrow=Observable["throw"]=Observable.throwException=Observable.throwError=function(exception,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.schedule(function(){observer.onError(exception)})})};Observable.using=function(resourceFactory,observableFactory){return new AnonymousObservable(function(observer){var disposable=disposableEmpty,resource,source;try{resource=resourceFactory();resource&&(disposable=resource);source=observableFactory(resource)}catch(exception){return new CompositeDisposable(observableThrow(exception).subscribe(observer),disposable)}return new CompositeDisposable(source.subscribe(observer),disposable)})};observableProto.amb=function(rightSource){var leftSource=this;return new AnonymousObservable(function(observer){var choice,leftChoice="L",rightChoice="R",leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(rightSource)&&(rightSource=observableFromPromise(rightSource));function choiceL(){if(!choice){choice=leftChoice;rightSubscription.dispose()}}function choiceR(){if(!choice){choice=rightChoice;leftSubscription.dispose()}}leftSubscription.setDisposable(leftSource.subscribe(function(left){choiceL();if(choice===leftChoice){observer.onNext(left)}},function(err){choiceL();if(choice===leftChoice){observer.onError(err)}},function(){choiceL();if(choice===leftChoice){observer.onCompleted()}}));rightSubscription.setDisposable(rightSource.subscribe(function(right){choiceR();if(choice===rightChoice){observer.onNext(right)}},function(err){choiceR();if(choice===rightChoice){observer.onError(err)}},function(){choiceR();if(choice===rightChoice){observer.onCompleted()}}));return new CompositeDisposable(leftSubscription,rightSubscription)})};Observable.amb=function(){var acc=observableNever(),items=argsOrArray(arguments,0);function func(previous,current){return previous.amb(current)}for(var i=0,len=items.length;i<len;i++){acc=func(acc,items[i])}return acc};function observableCatchHandler(source,handler){return new AnonymousObservable(function(observer){var d1=new SingleAssignmentDisposable,subscription=new SerialDisposable;subscription.setDisposable(d1);d1.setDisposable(source.subscribe(observer.onNext.bind(observer),function(exception){var d,result;try{result=handler(exception)}catch(ex){observer.onError(ex);return}isPromise(result)&&(result=observableFromPromise(result));d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(result.subscribe(observer))},observer.onCompleted.bind(observer)));return subscription})}observableProto["catch"]=observableProto.catchError=observableProto.catchException=function(handlerOrSecond){return typeof handlerOrSecond==="function"?observableCatchHandler(this,handlerOrSecond):observableCatch([this,handlerOrSecond])};var observableCatch=Observable.catchException=Observable.catchError=Observable["catch"]=function(){return enumerableOf(argsOrArray(arguments,0)).catchException()};observableProto.combineLatest=function(){var args=slice.call(arguments);if(Array.isArray(args[0])){args[0].unshift(this)
}else{args.unshift(this)}return combineLatest.apply(this,args)};var combineLatest=Observable.combineLatest=function(){var args=slice.call(arguments),resultSelector=args.pop();if(Array.isArray(args[0])){args=args[0]}return new AnonymousObservable(function(observer){var falseFactory=function(){return false},n=args.length,hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,isDone=arrayInitialize(n,falseFactory),values=new Array(n);function next(i){var res;hasValue[i]=true;if(hasValueAll||(hasValueAll=hasValue.every(identity))){try{res=resultSelector.apply(null,values)}catch(ex){observer.onError(ex);return}observer.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){observer.onCompleted()}}function done(i){isDone[i]=true;if(isDone.every(identity)){observer.onCompleted()}}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){var source=args[i],sad=new SingleAssignmentDisposable;isPromise(source)&&(source=observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){values[i]=x;next(i)},observer.onError.bind(observer),function(){done(i)}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)})};observableProto.concat=function(){var items=slice.call(arguments,0);items.unshift(this);return observableConcat.apply(this,items)};var observableConcat=Observable.concat=function(){return enumerableOf(argsOrArray(arguments,0)).concat()};observableProto.concatObservable=observableProto.concatAll=function(){return this.merge(1)};observableProto.merge=function(maxConcurrentOrOther){if(typeof maxConcurrentOrOther!=="number"){return observableMerge(this,maxConcurrentOrOther)}var sources=this;return new AnonymousObservable(function(observer){var activeCount=0,group=new CompositeDisposable,isStopped=false,q=[];function subscribe(xs){var subscription=new SingleAssignmentDisposable;group.add(subscription);isPromise(xs)&&(xs=observableFromPromise(xs));subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){group.remove(subscription);if(q.length>0){subscribe(q.shift())}else{activeCount--;isStopped&&activeCount===0&&observer.onCompleted()}}))}group.add(sources.subscribe(function(innerSource){if(activeCount<maxConcurrentOrOther){activeCount++;subscribe(innerSource)}else{q.push(innerSource)}},observer.onError.bind(observer),function(){isStopped=true;activeCount===0&&observer.onCompleted()}));return group})};var observableMerge=Observable.merge=function(){var scheduler,sources;if(!arguments[0]){scheduler=immediateScheduler;sources=slice.call(arguments,1)}else if(arguments[0].now){scheduler=arguments[0];sources=slice.call(arguments,1)}else{scheduler=immediateScheduler;sources=slice.call(arguments,0)}if(Array.isArray(sources[0])){sources=sources[0]}return observableFromArray(sources,scheduler).mergeObservable()};observableProto.mergeObservable=observableProto.mergeAll=function(){var sources=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable,isStopped=false,m=new SingleAssignmentDisposable;group.add(m);m.setDisposable(sources.subscribe(function(innerSource){var innerSubscription=new SingleAssignmentDisposable;group.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){group.remove(innerSubscription);isStopped&&group.length===1&&observer.onCompleted()}))},observer.onError.bind(observer),function(){isStopped=true;group.length===1&&observer.onCompleted()}));return group})};observableProto.onErrorResumeNext=function(second){if(!second){throw new Error("Second observable is required")}return onErrorResumeNext([this,second])};var onErrorResumeNext=Observable.onErrorResumeNext=function(){var sources=argsOrArray(arguments,0);return new AnonymousObservable(function(observer){var pos=0,subscription=new SerialDisposable,cancelable=immediateScheduler.scheduleRecursive(function(self){var current,d;if(pos<sources.length){current=sources[pos++];isPromise(current)&&(current=observableFromPromise(current));d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(current.subscribe(observer.onNext.bind(observer),self,self))}else{observer.onCompleted()}});return new CompositeDisposable(subscription,cancelable)})};observableProto.skipUntil=function(other){var source=this;return new AnonymousObservable(function(observer){var isOpen=false;var disposables=new CompositeDisposable(source.subscribe(function(left){isOpen&&observer.onNext(left)},observer.onError.bind(observer),function(){isOpen&&observer.onCompleted()}));isPromise(other)&&(other=observableFromPromise(other));var rightSubscription=new SingleAssignmentDisposable;disposables.add(rightSubscription);rightSubscription.setDisposable(other.subscribe(function(){isOpen=true;rightSubscription.dispose()},observer.onError.bind(observer),function(){rightSubscription.dispose()}));return disposables})};observableProto["switch"]=observableProto.switchLatest=function(){var sources=this;return new AnonymousObservable(function(observer){var hasLatest=false,innerSubscription=new SerialDisposable,isStopped=false,latest=0,subscription=sources.subscribe(function(innerSource){var d=new SingleAssignmentDisposable,id=++latest;hasLatest=true;innerSubscription.setDisposable(d);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));d.setDisposable(innerSource.subscribe(function(x){latest===id&&observer.onNext(x)},function(e){latest===id&&observer.onError(e)},function(){if(latest===id){hasLatest=false;isStopped&&observer.onCompleted()}}))},observer.onError.bind(observer),function(){isStopped=true;!hasLatest&&observer.onCompleted()});return new CompositeDisposable(subscription,innerSubscription)})};observableProto.takeUntil=function(other){var source=this;return new AnonymousObservable(function(observer){isPromise(other)&&(other=observableFromPromise(other));return new CompositeDisposable(source.subscribe(observer),other.subscribe(observer.onCompleted.bind(observer),observer.onError.bind(observer),noop))})};function zipArray(second,resultSelector){var first=this;return new AnonymousObservable(function(observer){var index=0,len=second.length;return first.subscribe(function(left){if(index<len){var right=second[index++],result;try{result=resultSelector(left,right)}catch(e){observer.onError(e);return}observer.onNext(result)}else{observer.onCompleted()}},observer.onError.bind(observer),observer.onCompleted.bind(observer))})}observableProto.zip=function(){if(Array.isArray(arguments[0])){return zipArray.apply(this,arguments)}var parent=this,sources=slice.call(arguments),resultSelector=sources.pop();sources.unshift(parent);return new AnonymousObservable(function(observer){var n=sources.length,queues=arrayInitialize(n,function(){return[]}),isDone=arrayInitialize(n,function(){return false});function next(i){var res,queuedValues;if(queues.every(function(x){return x.length>0})){try{queuedValues=queues.map(function(x){return x.shift()});res=resultSelector.apply(parent,queuedValues)}catch(ex){observer.onError(ex);return}observer.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){observer.onCompleted()}}function done(i){isDone[i]=true;if(isDone.every(function(x){return x})){observer.onCompleted()}}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){var source=sources[i],sad=new SingleAssignmentDisposable;isPromise(source)&&(source=observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){queues[i].push(x);next(i)},observer.onError.bind(observer),function(){done(i)}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)})};Observable.zip=function(){var args=slice.call(arguments,0),first=args.shift();return first.zip.apply(first,args)};Observable.zipArray=function(){var sources=argsOrArray(arguments,0);return new AnonymousObservable(function(observer){var n=sources.length,queues=arrayInitialize(n,function(){return[]}),isDone=arrayInitialize(n,function(){return false});function next(i){if(queues.every(function(x){return x.length>0})){var res=queues.map(function(x){return x.shift()});observer.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){observer.onCompleted();return}}function done(i){isDone[i]=true;if(isDone.every(identity)){observer.onCompleted();return}}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){subscriptions[i]=new SingleAssignmentDisposable;subscriptions[i].setDisposable(sources[i].subscribe(function(x){queues[i].push(x);next(i)},observer.onError.bind(observer),function(){done(i)}))})(idx)}var compositeDisposable=new CompositeDisposable(subscriptions);compositeDisposable.add(disposableCreate(function(){for(var qIdx=0,qLen=queues.length;qIdx<qLen;qIdx++){queues[qIdx]=[]}}));return compositeDisposable})};observableProto.asObservable=function(){return new AnonymousObservable(this.subscribe.bind(this))};observableProto.bufferWithCount=function(count,skip){if(typeof skip!=="number"){skip=count}return this.windowWithCount(count,skip).selectMany(function(x){return x.toArray()}).where(function(x){return x.length>0})};observableProto.dematerialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(x){return x.accept(observer)},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.distinctUntilChanged=function(keySelector,comparer){var source=this;keySelector||(keySelector=identity);comparer||(comparer=defaultComparer);return new AnonymousObservable(function(observer){var hasCurrentKey=false,currentKey;return source.subscribe(function(value){var comparerEquals=false,key;try{key=keySelector(value)}catch(exception){observer.onError(exception);return}if(hasCurrentKey){try{comparerEquals=comparer(currentKey,key)}catch(exception){observer.onError(exception);return}}if(!hasCurrentKey||!comparerEquals){hasCurrentKey=true;currentKey=key;observer.onNext(value)}},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto["do"]=observableProto.doAction=observableProto.tap=function(observerOrOnNext,onError,onCompleted){var source=this,onNextFunc;if(typeof observerOrOnNext==="function"){onNextFunc=observerOrOnNext}else{onNextFunc=observerOrOnNext.onNext.bind(observerOrOnNext);onError=observerOrOnNext.onError.bind(observerOrOnNext);onCompleted=observerOrOnNext.onCompleted.bind(observerOrOnNext)}return new AnonymousObservable(function(observer){return source.subscribe(function(x){try{onNextFunc(x)}catch(e){observer.onError(e)}observer.onNext(x)},function(err){if(onError){try{onError(err)}catch(e){observer.onError(e)}}observer.onError(err)},function(){if(onCompleted){try{onCompleted()}catch(e){observer.onError(e)}}observer.onCompleted()})})};observableProto.doOnNext=observableProto.tapOnNext=function(onNext,thisArg){return this.tap(arguments.length===2?function(x){onNext.call(thisArg,x)}:onNext)};observableProto.doOnError=observableProto.tapOnError=function(onError,thisArg){return this.tap(noop,arguments.length===2?function(e){onError.call(thisArg,e)}:onError)};observableProto.doOnCompleted=observableProto.tapOnCompleted=function(onCompleted,thisArg){return this.tap(noop,null,arguments.length===2?function(){onCompleted.call(thisArg)}:onCompleted)};observableProto["finally"]=observableProto.finallyAction=function(action){var source=this;return new AnonymousObservable(function(observer){var subscription;try{subscription=source.subscribe(observer)}catch(e){action();throw e}return disposableCreate(function(){try{subscription.dispose()}catch(e){throw e}finally{action()}})})};observableProto.ignoreElements=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(noop,observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.materialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value))},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted()},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted()})})};observableProto.repeat=function(repeatCount){return enumerableRepeat(this,repeatCount).concat()};observableProto.retry=function(retryCount){return enumerableRepeat(this,retryCount).catchException()};observableProto.scan=function(){var hasSeed=false,seed,accumulator,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new AnonymousObservable(function(observer){var hasAccumulation,accumulation,hasValue;return source.subscribe(function(x){!hasValue&&(hasValue=true);try{if(hasAccumulation){accumulation=accumulator(accumulation,x)}else{accumulation=hasSeed?accumulator(seed,x):x;hasAccumulation=true}}catch(e){observer.onError(e);return}observer.onNext(accumulation)},observer.onError.bind(observer),function(){!hasValue&&hasSeed&&observer.onNext(seed);observer.onCompleted()})})};observableProto.skipLast=function(count){var source=this;return new AnonymousObservable(function(observer){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&observer.onNext(q.shift())},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.startWith=function(){var values,scheduler,start=0;if(!!arguments.length&&isScheduler(arguments[0])){scheduler=arguments[0];start=1}else{scheduler=immediateScheduler}values=slice.call(arguments,start);return enumerableOf([observableFromArray(values,scheduler),this]).concat()};observableProto.takeLast=function(count){var source=this;return new AnonymousObservable(function(observer){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},observer.onError.bind(observer),function(){while(q.length>0){observer.onNext(q.shift())}observer.onCompleted()})})};observableProto.takeLastBuffer=function(count){var source=this;return new AnonymousObservable(function(observer){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},observer.onError.bind(observer),function(){observer.onNext(q);observer.onCompleted()})})};observableProto.windowWithCount=function(count,skip){var source=this;+count||(count=0);Math.abs(count)===Infinity&&(count=0);if(count<=0){throw new Error(argumentOutOfRange)}skip==null&&(skip=count);+skip||(skip=0);Math.abs(skip)===Infinity&&(skip=0);if(skip<=0){throw new Error(argumentOutOfRange)}return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,refCountDisposable=new RefCountDisposable(m),n=0,q=[];function createWindow(){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}createWindow();m.setDisposable(source.subscribe(function(x){for(var i=0,len=q.length;i<len;i++){q[i].onNext(x)}var c=n-count+1;c>=0&&c%skip===0&&q.shift().onCompleted();++n%skip===0&&createWindow()},function(e){while(q.length>0){q.shift().onError(e)}observer.onError(e)},function(){while(q.length>0){q.shift().onCompleted()}observer.onCompleted()}));return refCountDisposable})};function concatMap(source,selector,thisArg){return source.map(function(x,i){var result=selector.call(thisArg,x,i);return isPromise(result)?observableFromPromise(result):result}).concatAll()}observableProto.selectConcat=observableProto.concatMap=function(selector,resultSelector,thisArg){if(resultSelector){return this.concatMap(function(x,i){var selectorResult=selector(x,i),result=isPromise(selectorResult)?observableFromPromise(selectorResult):selectorResult;return result.map(function(y){return resultSelector(x,y,i)})})}return typeof selector==="function"?concatMap(this,selector,thisArg):concatMap(this,function(){return selector})};observableProto.concatMapObserver=observableProto.selectConcatObserver=function(onNext,onError,onCompleted,thisArg){var source=this;return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNext.call(thisArg,x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onError.call(thisArg,err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompleted.call(thisArg)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})}).concatAll()};observableProto.defaultIfEmpty=function(defaultValue){var source=this;if(defaultValue===undefined){defaultValue=null}return new AnonymousObservable(function(observer){var found=false;return source.subscribe(function(x){found=true;observer.onNext(x)},observer.onError.bind(observer),function(){if(!found){observer.onNext(defaultValue)}observer.onCompleted()})})};function arrayIndexOfComparer(array,item,comparer){for(var i=0,len=array.length;i<len;i++){if(comparer(array[i],item)){return i}}return-1}function HashSet(comparer){this.comparer=comparer;this.set=[]}HashSet.prototype.push=function(value){var retValue=arrayIndexOfComparer(this.set,value,this.comparer)===-1;retValue&&this.set.push(value);return retValue};observableProto.distinct=function(keySelector,comparer){var source=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(observer){var hashSet=new HashSet(comparer);return source.subscribe(function(x){var key=x;if(keySelector){try{key=keySelector(x)}catch(e){observer.onError(e);return}}hashSet.push(key)&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.groupBy=function(keySelector,elementSelector,comparer){return this.groupByUntil(keySelector,elementSelector,observableNever,comparer)};observableProto.groupByUntil=function(keySelector,elementSelector,durationSelector,comparer){var source=this;elementSelector||(elementSelector=identity);comparer||(comparer=defaultComparer);return new AnonymousObservable(function(observer){function handleError(e){return function(item){item.onError(e)}}var map=new Dictionary(0,comparer),groupDisposable=new CompositeDisposable,refCountDisposable=new RefCountDisposable(groupDisposable);groupDisposable.add(source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){map.getValues().forEach(handleError(e));observer.onError(e);return}var fireNewMapEntry=false,writer=map.tryGetValue(key);if(!writer){writer=new Subject;map.set(key,writer);fireNewMapEntry=true}if(fireNewMapEntry){var group=new GroupedObservable(key,writer,refCountDisposable),durationGroup=new GroupedObservable(key,writer);try{duration=durationSelector(durationGroup)}catch(e){map.getValues().forEach(handleError(e));observer.onError(e);return}observer.onNext(group);var md=new SingleAssignmentDisposable;groupDisposable.add(md);var expire=function(){map.remove(key)&&writer.onCompleted();groupDisposable.remove(md)};md.setDisposable(duration.take(1).subscribe(noop,function(exn){map.getValues().forEach(handleError(exn));observer.onError(exn)},expire))}var element;try{element=elementSelector(x)}catch(e){map.getValues().forEach(handleError(e));observer.onError(e);return}writer.onNext(element)},function(ex){map.getValues().forEach(handleError(ex));observer.onError(ex)},function(){map.getValues().forEach(function(item){item.onCompleted()});observer.onCompleted()}));return refCountDisposable})};observableProto.select=observableProto.map=function(selector,thisArg){var parent=this;return new AnonymousObservable(function(observer){var count=0;return parent.subscribe(function(value){var result;try{result=selector.call(thisArg,value,count++,parent)}catch(e){observer.onError(e);return}observer.onNext(result)},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.pluck=function(prop){return this.map(function(x){return x[prop]})};function flatMap(source,selector,thisArg){return source.map(function(x,i){var result=selector.call(thisArg,x,i);return isPromise(result)?observableFromPromise(result):result}).mergeObservable()}observableProto.selectMany=observableProto.flatMap=function(selector,resultSelector,thisArg){if(resultSelector){return this.flatMap(function(x,i){var selectorResult=selector(x,i),result=isPromise(selectorResult)?observableFromPromise(selectorResult):selectorResult;return result.map(function(y){return resultSelector(x,y,i)})},thisArg)}return typeof selector==="function"?flatMap(this,selector,thisArg):flatMap(this,function(){return selector})};observableProto.flatMapObserver=observableProto.selectManyObserver=function(onNext,onError,onCompleted,thisArg){var source=this;return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNext.call(thisArg,x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onError.call(thisArg,err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompleted.call(thisArg)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})}).mergeAll()};observableProto.selectSwitch=observableProto.flatMapLatest=observableProto.switchMap=function(selector,thisArg){return this.select(selector,thisArg).switchLatest()};observableProto.skip=function(count){if(count<0){throw new Error(argumentOutOfRange)}var source=this;return new AnonymousObservable(function(observer){var remaining=count;return source.subscribe(function(x){if(remaining<=0){observer.onNext(x)}else{remaining--}},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.skipWhile=function(predicate,thisArg){var source=this;return new AnonymousObservable(function(observer){var i=0,running=false;return source.subscribe(function(x){if(!running){try{running=!predicate.call(thisArg,x,i++,source)}catch(e){observer.onError(e);return}}running&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.take=function(count,scheduler){if(count<0){throw new RangeError(argumentOutOfRange)}if(count===0){return observableEmpty(scheduler)}var observable=this;return new AnonymousObservable(function(observer){var remaining=count;return observable.subscribe(function(x){if(remaining-->0){observer.onNext(x);remaining===0&&observer.onCompleted()}},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.takeWhile=function(predicate,thisArg){var observable=this;return new AnonymousObservable(function(observer){var i=0,running=true;return observable.subscribe(function(x){if(running){try{running=predicate.call(thisArg,x,i++,observable)}catch(e){observer.onError(e);return}if(running){observer.onNext(x)}else{observer.onCompleted()}}},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.where=observableProto.filter=function(predicate,thisArg){var parent=this;return new AnonymousObservable(function(observer){var count=0;return parent.subscribe(function(value){var shouldRun;try{shouldRun=predicate.call(thisArg,value,count++,parent)}catch(e){observer.onError(e);return}shouldRun&&observer.onNext(value)},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.finalValue=function(){var source=this;return new AnonymousObservable(function(observer){var hasValue=false,value;return source.subscribe(function(x){hasValue=true;value=x},observer.onError.bind(observer),function(){if(!hasValue){observer.onError(new Error(sequenceContainsNoElements))}else{observer.onNext(value);observer.onCompleted()}})})};function extremaBy(source,keySelector,comparer){return new AnonymousObservable(function(observer){var hasValue=false,lastKey=null,list=[];return source.subscribe(function(x){var comparison,key;try{key=keySelector(x)}catch(ex){observer.onError(ex);return}comparison=0;if(!hasValue){hasValue=true;lastKey=key}else{try{comparison=comparer(key,lastKey)}catch(ex1){observer.onError(ex1);return}}if(comparison>0){lastKey=key;list=[]}if(comparison>=0){list.push(x)}},observer.onError.bind(observer),function(){observer.onNext(list);observer.onCompleted()})})}function firstOnly(x){if(x.length===0){throw new Error(sequenceContainsNoElements)}return x[0]}observableProto.aggregate=function(){var seed,hasSeed,accumulator;if(arguments.length===2){seed=arguments[0];hasSeed=true;accumulator=arguments[1]}else{accumulator=arguments[0]}return hasSeed?this.scan(seed,accumulator).startWith(seed).finalValue():this.scan(accumulator).finalValue()};observableProto.reduce=function(accumulator){var seed,hasSeed;if(arguments.length===2){hasSeed=true;seed=arguments[1]}return hasSeed?this.scan(seed,accumulator).startWith(seed).finalValue():this.scan(accumulator).finalValue()};observableProto.some=observableProto.any=function(predicate,thisArg){var source=this;return predicate?source.where(predicate,thisArg).any():new AnonymousObservable(function(observer){return source.subscribe(function(){observer.onNext(true);observer.onCompleted()},observer.onError.bind(observer),function(){observer.onNext(false);observer.onCompleted()})})};observableProto.isEmpty=function(){return this.any().map(not)};observableProto.every=observableProto.all=function(predicate,thisArg){return this.where(function(v){return!predicate(v)},thisArg).any().select(function(b){return!b})};observableProto.contains=function(searchElement,fromIndex){var source=this;function comparer(a,b){return a===0&&b===0||(a===b||isNaN(a)&&isNaN(b))}return new AnonymousObservable(function(observer){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){observer.onNext(false);observer.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i++>=n&&comparer(x,searchElement)){observer.onNext(true);observer.onCompleted()}},observer.onError.bind(observer),function(){observer.onNext(false);observer.onCompleted()})})};observableProto.count=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).count():this.aggregate(0,function(count){return count+1})};observableProto.indexOf=function(searchElement,fromIndex){var source=this;return new AnonymousObservable(function(observer){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){observer.onNext(-1);observer.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i>=n&&x===searchElement){observer.onNext(i);observer.onCompleted()}i++},observer.onError.bind(observer),function(){observer.onNext(-1);observer.onCompleted()})})};observableProto.sum=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).sum():this.aggregate(0,function(prev,curr){return prev+curr})};observableProto.minBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,function(x,y){return comparer(x,y)*-1})};observableProto.min=function(comparer){return this.minBy(identity,comparer).select(function(x){return firstOnly(x)})};observableProto.maxBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,comparer)};observableProto.max=function(comparer){return this.maxBy(identity,comparer).select(function(x){return firstOnly(x)})};observableProto.average=function(keySelector,thisArg){return keySelector?this.select(keySelector,thisArg).average():this.scan({sum:0,count:0},function(prev,cur){return{sum:prev.sum+cur,count:prev.count+1}}).finalValue().select(function(s){if(s.count===0){throw new Error("The input sequence was empty")}return s.sum/s.count})};function sequenceEqualArray(first,second,comparer){return new AnonymousObservable(function(observer){var count=0,len=second.length;return first.subscribe(function(value){var equal=false;try{count<len&&(equal=comparer(value,second[count++]))}catch(e){observer.onError(e);return}if(!equal){observer.onNext(false);observer.onCompleted()}},observer.onError.bind(observer),function(){observer.onNext(count===len);observer.onCompleted()})})}observableProto.sequenceEqual=function(second,comparer){var first=this;comparer||(comparer=defaultComparer);if(Array.isArray(second)){return sequenceEqualArray(first,second,comparer)}return new AnonymousObservable(function(observer){var donel=false,doner=false,ql=[],qr=[];var subscription1=first.subscribe(function(x){var equal,v;if(qr.length>0){v=qr.shift();try{equal=comparer(v,x)}catch(e){observer.onError(e);return}if(!equal){observer.onNext(false);observer.onCompleted()}}else if(doner){observer.onNext(false);observer.onCompleted()}else{ql.push(x)}},observer.onError.bind(observer),function(){donel=true;if(ql.length===0){if(qr.length>0){observer.onNext(false);observer.onCompleted()}else if(doner){observer.onNext(true);observer.onCompleted()}}});isPromise(second)&&(second=observableFromPromise(second));var subscription2=second.subscribe(function(x){var equal;if(ql.length>0){var v=ql.shift();try{equal=comparer(v,x)}catch(exception){observer.onError(exception);return}if(!equal){observer.onNext(false);observer.onCompleted()}}else if(donel){observer.onNext(false);observer.onCompleted()}else{qr.push(x)}},observer.onError.bind(observer),function(){doner=true;if(qr.length===0){if(ql.length>0){observer.onNext(false);observer.onCompleted()}else if(donel){observer.onNext(true);observer.onCompleted()}}});return new CompositeDisposable(subscription1,subscription2)})};function elementAtOrDefault(source,index,hasDefault,defaultValue){if(index<0){throw new Error(argumentOutOfRange)}return new AnonymousObservable(function(observer){var i=index;return source.subscribe(function(x){if(i===0){observer.onNext(x);observer.onCompleted()}i--},observer.onError.bind(observer),function(){if(!hasDefault){observer.onError(new Error(argumentOutOfRange))}else{observer.onNext(defaultValue);observer.onCompleted()}})})}observableProto.elementAt=function(index){return elementAtOrDefault(this,index,false)};observableProto.elementAtOrDefault=function(index,defaultValue){return elementAtOrDefault(this,index,true,defaultValue)};function singleOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(observer){var value=defaultValue,seenValue=false;return source.subscribe(function(x){if(seenValue){observer.onError(new Error("Sequence contains more than one element"))}else{value=x;seenValue=true}},observer.onError.bind(observer),function(){if(!seenValue&&!hasDefault){observer.onError(new Error(sequenceContainsNoElements))}else{observer.onNext(value);observer.onCompleted()}})})}observableProto.single=function(predicate,thisArg){return predicate&&isFunction(predicate)?this.where(predicate,thisArg).single():singleOrDefaultAsync(this,false)};observableProto.singleOrDefault=function(predicate,defaultValue,thisArg){return predicate&&isFunction(predicate)?this.where(predicate,thisArg).singleOrDefault(null,defaultValue):singleOrDefaultAsync(this,true,defaultValue)};function firstOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(observer){return source.subscribe(function(x){observer.onNext(x);observer.onCompleted()},observer.onError.bind(observer),function(){if(!hasDefault){observer.onError(new Error(sequenceContainsNoElements))}else{observer.onNext(defaultValue);observer.onCompleted()}})})}observableProto.first=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).first():firstOrDefaultAsync(this,false)};observableProto.firstOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate).firstOrDefault(null,defaultValue):firstOrDefaultAsync(this,true,defaultValue)
};function lastOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(observer){var value=defaultValue,seenValue=false;return source.subscribe(function(x){value=x;seenValue=true},observer.onError.bind(observer),function(){if(!seenValue&&!hasDefault){observer.onError(new Error(sequenceContainsNoElements))}else{observer.onNext(value);observer.onCompleted()}})})}observableProto.last=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).last():lastOrDefaultAsync(this,false)};observableProto.lastOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate,thisArg).lastOrDefault(null,defaultValue):lastOrDefaultAsync(this,true,defaultValue)};function findValue(source,predicate,thisArg,yieldIndex){return new AnonymousObservable(function(observer){var i=0;return source.subscribe(function(x){var shouldRun;try{shouldRun=predicate.call(thisArg,x,i,source)}catch(e){observer.onError(e);return}if(shouldRun){observer.onNext(yieldIndex?i:x);observer.onCompleted()}else{i++}},observer.onError.bind(observer),function(){observer.onNext(yieldIndex?-1:undefined);observer.onCompleted()})})}observableProto.find=function(predicate,thisArg){return findValue(this,predicate,thisArg,false)};observableProto.findIndex=function(predicate,thisArg){return findValue(this,predicate,thisArg,true)};if(!!root.Set){observableProto.toSet=function(){var source=this;return new AnonymousObservable(function(observer){var s=new root.Set;return source.subscribe(s.add.bind(s),observer.onError.bind(observer),function(){observer.onNext(s);observer.onCompleted()})})}}if(!!root.Map){observableProto.toMap=function(keySelector,elementSelector){var source=this;return new AnonymousObservable(function(observer){var m=new root.Map;return source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){observer.onError(e);return}var element=x;if(elementSelector){try{element=elementSelector(x)}catch(e){observer.onError(e);return}}m.set(key,element)},observer.onError.bind(observer),function(){observer.onNext(m);observer.onCompleted()})})}}var fnString="function";function toThunk(obj,ctx){if(Array.isArray(obj)){return objectToThunk.call(ctx,obj)}if(isGeneratorFunction(obj)){return observableSpawn(obj.call(ctx))}if(isGenerator(obj)){return observableSpawn(obj)}if(isObservable(obj)){return observableToThunk(obj)}if(isPromise(obj)){return promiseToThunk(obj)}if(typeof obj===fnString){return obj}if(isObject(obj)||Array.isArray(obj)){return objectToThunk.call(ctx,obj)}return obj}function objectToThunk(obj){var ctx=this;return function(done){var keys=Object.keys(obj),pending=keys.length,results=new obj.constructor,finished;if(!pending){timeoutScheduler.schedule(function(){done(null,results)});return}for(var i=0,len=keys.length;i<len;i++){run(obj[keys[i]],keys[i])}function run(fn,key){if(finished){return}try{fn=toThunk(fn,ctx);if(typeof fn!==fnString){results[key]=fn;return--pending||done(null,results)}fn.call(ctx,function(err,res){if(finished){return}if(err){finished=true;return done(err)}results[key]=res;--pending||done(null,results)})}catch(e){finished=true;done(e)}}}}function observableToThink(observable){return function(fn){var value,hasValue=false;observable.subscribe(function(v){value=v;hasValue=true},fn,function(){hasValue&&fn(null,value)})}}function promiseToThunk(promise){return function(fn){promise.then(function(res){fn(null,res)},fn)}}function isObservable(obj){return obj&&obj.prototype.subscribe===fnString}function isGeneratorFunction(obj){return obj&&obj.constructor&&obj.constructor.name==="GeneratorFunction"}function isGenerator(obj){return obj&&typeof obj.next===fnString&&typeof obj.throw===fnString}function isObject(val){return val&&val.constructor===Object}var observableSpawn=Rx.spawn=function(fn){var isGenFun=isGeneratorFunction(fn);return function(done){var ctx=this,gen=fan;if(isGenFun){var args=slice.call(arguments),len=args.length,hasCallback=len&&typeof args[len-1]===fnString;done=hasCallback?args.pop():error;gen=fn.apply(this,args)}else{done=done||error}next();function exit(err,res){timeoutScheduler.schedule(done.bind(ctx,err,res))}function next(err,res){var ret;if(arguments.length>2)res=slice.call(arguments,1);if(err){try{ret=gen.throw(err)}catch(e){return exit(e)}}if(!err){try{ret=gen.next(res)}catch(e){return exit(e)}}if(ret.done){return exit(null,ret.value)}ret.value=toThunk(ret.value,ctx);if(typeof ret.value===fnString){var called=false;try{ret.value.call(ctx,function(){if(called){return}called=true;next.apply(ctx,arguments)})}catch(e){timeoutScheduler.schedule(function(){if(called){return}called=true;next.call(ctx,e)})}return}next(new TypeError("Rx.spawn only supports a function, Promise, Observable, Object or Array."))}}};Rx.denodify=function(fn){return function(){var args=slice.call(arguments),results,called,callback;args.push(function(){results=arguments;if(callback&&!called){called=true;cb.apply(this,results)}});fn.apply(this,args);return function(fn){callback=fn;if(results&&!called){called=true;fn.apply(this,results)}}}};Observable.start=function(func,context,scheduler){return observableToAsync(func,context,scheduler)()};var observableToAsync=Observable.toAsync=function(func,context,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return function(){var args=arguments,subject=new AsyncSubject;scheduler.schedule(function(){var result;try{result=func.apply(context,args)}catch(e){subject.onError(e);return}subject.onNext(result);subject.onCompleted()});return subject.asObservable()}};Observable.fromCallback=function(func,context,selector){return function(){var args=slice.call(arguments,0);return new AnonymousObservable(function(observer){function handler(e){var results=e;if(selector){try{results=selector(arguments)}catch(err){observer.onError(err);return}observer.onNext(results)}else{if(results.length<=1){observer.onNext.apply(observer,results)}else{observer.onNext(results)}}observer.onCompleted()}args.push(handler);func.apply(context,args)}).publishLast().refCount()}};Observable.fromNodeCallback=function(func,context,selector){return function(){var args=slice.call(arguments,0);return new AnonymousObservable(function(observer){function handler(err){if(err){observer.onError(err);return}var results=slice.call(arguments,1);if(selector){try{results=selector(results)}catch(e){observer.onError(e);return}observer.onNext(results)}else{if(results.length<=1){observer.onNext.apply(observer,results)}else{observer.onNext(results)}}observer.onCompleted()}args.push(handler);func.apply(context,args)}).publishLast().refCount()}};function createListener(element,name,handler){if(element.addEventListener){element.addEventListener(name,handler,false);return disposableCreate(function(){element.removeEventListener(name,handler,false)})}throw new Error("No listener found")}function createEventListener(el,eventName,handler){var disposables=new CompositeDisposable;if(Object.prototype.toString.call(el)==="[object NodeList]"){for(var i=0,len=el.length;i<len;i++){disposables.add(createEventListener(el.item(i),eventName,handler))}}else if(el){disposables.add(createListener(el,eventName,handler))}return disposables}Rx.config.useNativeEvents=false;var jq=!!root.angular&&!!angular.element?angular.element:!!root.jQuery?root.jQuery:!!root.Zepto?root.Zepto:null;var ember=!!root.Ember&&typeof root.Ember.addListener==="function";var marionette=!!root.Backbone&&!!root.Backbone.Marionette;Observable.fromEvent=function(element,eventName,selector){if(element.addListener){return fromEventPattern(function(h){element.addListener(eventName,h)},function(h){element.removeListener(eventName,h)},selector)}if(!Rx.config.useNativeEvents){if(marionette){return fromEventPattern(function(h){element.on(eventName,h)},function(h){element.off(eventName,h)},selector)}if(ember){return fromEventPattern(function(h){Ember.addListener(element,eventName,h)},function(h){Ember.removeListener(element,eventName,h)},selector)}if(jq){var $elem=jq(element);return fromEventPattern(function(h){$elem.on(eventName,h)},function(h){$elem.off(eventName,h)},selector)}}return new AnonymousObservable(function(observer){return createEventListener(element,eventName,function handler(e){var results=e;if(selector){try{results=selector(arguments)}catch(err){observer.onError(err);return}}observer.onNext(results)})}).publish().refCount()};var fromEventPattern=Observable.fromEventPattern=function(addHandler,removeHandler,selector){return new AnonymousObservable(function(observer){function innerHandler(e){var result=e;if(selector){try{result=selector(arguments)}catch(err){observer.onError(err);return}}observer.onNext(result)}var returnValue=addHandler(innerHandler);return disposableCreate(function(){if(removeHandler){removeHandler(innerHandler,returnValue)}})}).publish().refCount()};Observable.startAsync=function(functionAsync){var promise;try{promise=functionAsync()}catch(e){return observableThrow(e)}return observableFromPromise(promise)};var PausableObservable=function(_super){inherits(PausableObservable,_super);function subscribe(observer){var conn=this.source.publish(),subscription=conn.subscribe(observer),connection=disposableEmpty;var pausable=this.pauser.distinctUntilChanged().subscribe(function(b){if(b){connection=conn.connect()}else{connection.dispose();connection=disposableEmpty}});return new CompositeDisposable(subscription,connection,pausable)}function PausableObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}_super.call(this,subscribe)}PausableObservable.prototype.pause=function(){this.controller.onNext(false)};PausableObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableObservable}(Observable);observableProto.pausable=function(pauser){return new PausableObservable(this,pauser)};function combineLatestSource(source,subject,resultSelector){return new AnonymousObservable(function(observer){var n=2,hasValue=[false,false],hasValueAll=false,isDone=false,values=new Array(n);function next(x,i){values[i]=x;var res;hasValue[i]=true;if(hasValueAll||(hasValueAll=hasValue.every(identity))){try{res=resultSelector.apply(null,values)}catch(ex){observer.onError(ex);return}observer.onNext(res)}else if(isDone){observer.onCompleted()}}return new CompositeDisposable(source.subscribe(function(x){next(x,0)},observer.onError.bind(observer),function(){isDone=true;observer.onCompleted()}),subject.subscribe(function(x){next(x,1)},observer.onError.bind(observer)))})}var PausableBufferedObservable=function(_super){inherits(PausableBufferedObservable,_super);function subscribe(observer){var q=[],previousShouldFire;var subscription=combineLatestSource(this.source,this.pauser.distinctUntilChanged().startWith(false),function(data,shouldFire){return{data:data,shouldFire:shouldFire}}).subscribe(function(results){if(previousShouldFire!==undefined&&results.shouldFire!=previousShouldFire){previousShouldFire=results.shouldFire;if(results.shouldFire){while(q.length>0){observer.onNext(q.shift())}}}else{previousShouldFire=results.shouldFire;if(results.shouldFire){observer.onNext(results.data)}else{q.push(results.data)}}},function(err){while(q.length>0){observer.onNext(q.shift())}observer.onError(err)},function(){while(q.length>0){observer.onNext(q.shift())}observer.onCompleted()});return subscription}function PausableBufferedObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}_super.call(this,subscribe)}PausableBufferedObservable.prototype.pause=function(){this.controller.onNext(false)};PausableBufferedObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableBufferedObservable}(Observable);observableProto.pausableBuffered=function(subject){return new PausableBufferedObservable(this,subject)};observableProto.controlled=function(enableQueue){if(enableQueue==null){enableQueue=true}return new ControlledObservable(this,enableQueue)};var ControlledObservable=function(_super){inherits(ControlledObservable,_super);function subscribe(observer){return this.source.subscribe(observer)}function ControlledObservable(source,enableQueue){_super.call(this,subscribe);this.subject=new ControlledSubject(enableQueue);this.source=source.multicast(this.subject).refCount()}ControlledObservable.prototype.request=function(numberOfItems){if(numberOfItems==null){numberOfItems=-1}return this.subject.request(numberOfItems)};return ControlledObservable}(Observable);var ControlledSubject=Rx.ControlledSubject=function(_super){function subscribe(observer){return this.subject.subscribe(observer)}inherits(ControlledSubject,_super);function ControlledSubject(enableQueue){if(enableQueue==null){enableQueue=true}_super.call(this,subscribe);this.subject=new Subject;this.enableQueue=enableQueue;this.queue=enableQueue?[]:null;this.requestedCount=0;this.requestedDisposable=disposableEmpty;this.error=null;this.hasFailed=false;this.hasCompleted=false;this.controlledDisposable=disposableEmpty}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function(){checkDisposed.call(this);this.hasCompleted=true;if(!this.enableQueue||this.queue.length===0){this.subject.onCompleted()}},onError:function(error){checkDisposed.call(this);this.hasFailed=true;this.error=error;if(!this.enableQueue||this.queue.length===0){this.subject.onError(error)}},onNext:function(value){checkDisposed.call(this);var hasRequested=false;if(this.requestedCount===0){if(this.enableQueue){this.queue.push(value)}}else{if(this.requestedCount!==-1){if(this.requestedCount--===0){this.disposeCurrentRequest()}}hasRequested=true}if(hasRequested){this.subject.onNext(value)}},_processRequest:function(numberOfItems){if(this.enableQueue){while(this.queue.length>=numberOfItems&&numberOfItems>0){this.subject.onNext(this.queue.shift());numberOfItems--}if(this.queue.length!==0){return{numberOfItems:numberOfItems,returnValue:true}}else{return{numberOfItems:numberOfItems,returnValue:false}}}if(this.hasFailed){this.subject.onError(this.error);this.controlledDisposable.dispose();this.controlledDisposable=disposableEmpty}else if(this.hasCompleted){this.subject.onCompleted();this.controlledDisposable.dispose();this.controlledDisposable=disposableEmpty}return{numberOfItems:numberOfItems,returnValue:false}},request:function(number){checkDisposed.call(this);this.disposeCurrentRequest();var self=this,r=this._processRequest(number);number=r.numberOfItems;if(!r.returnValue){this.requestedCount=number;this.requestedDisposable=disposableCreate(function(){self.requestedCount=0});return this.requestedDisposable}else{return disposableEmpty}},disposeCurrentRequest:function(){this.requestedDisposable.dispose();this.requestedDisposable=disposableEmpty},dispose:function(){this.isDisposed=true;this.error=null;this.subject.dispose();this.requestedDisposable.dispose()}});return ControlledSubject}(Observable);observableProto.multicast=function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector==="function"?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect())}):new ConnectableObservable(source,subjectOrSubjectSelector)};observableProto.publish=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new Subject},selector):this.multicast(new Subject)};observableProto.share=function(){return this.publish().refCount()};observableProto.publishLast=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new AsyncSubject},selector):this.multicast(new AsyncSubject)};observableProto.publishValue=function(initialValueOrSelector,initialValue){return arguments.length===2?this.multicast(function(){return new BehaviorSubject(initialValue)},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector))};observableProto.shareValue=function(initialValue){return this.publishValue(initialValue).refCount()};observableProto.replay=function(selector,bufferSize,window,scheduler){return selector&&isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,window,scheduler)},selector):this.multicast(new ReplaySubject(bufferSize,window,scheduler))};observableProto.shareReplay=function(bufferSize,window,scheduler){return this.replay(null,bufferSize,window,scheduler).refCount()};var InnerSubscription=function(subject,observer){this.subject=subject;this.observer=observer};InnerSubscription.prototype.dispose=function(){if(!this.subject.isDisposed&&this.observer!==null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer=null}};var BehaviorSubject=Rx.BehaviorSubject=function(__super__){function subscribe(observer){checkDisposed.call(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer)}var ex=this.exception;if(ex){observer.onError(ex)}else{observer.onCompleted()}return disposableEmpty}inherits(BehaviorSubject,__super__);function BehaviorSubject(value){__super__.call(this,subscribe);this.value=value,this.observers=[],this.isDisposed=false,this.isStopped=false,this.exception=null}addProperties(BehaviorSubject.prototype,Observer,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed.call(this);if(this.isStopped){return}this.isStopped=true;for(var i=0,os=this.observers.slice(0),len=os.length;i<len;i++){os[i].onCompleted()}this.observers=[]},onError:function(error){checkDisposed.call(this);if(this.isStopped){return}this.isStopped=true;this.exception=error;for(var i=0,os=this.observers.slice(0),len=os.length;i<len;i++){os[i].onError(error)}this.observers=[]},onNext:function(value){checkDisposed.call(this);if(this.isStopped){return}this.value=value;for(var i=0,os=this.observers.slice(0),len=os.length;i<len;i++){os[i].onNext(value)}},dispose:function(){this.isDisposed=true;this.observers=null;this.value=null;this.exception=null}});return BehaviorSubject}(Observable);var ReplaySubject=Rx.ReplaySubject=function(__super__){function createRemovableDisposable(subject,observer){return disposableCreate(function(){observer.dispose();!subject.isDisposed&&subject.observers.splice(subject.observers.indexOf(observer),1)})}function subscribe(observer){var so=new ScheduledObserver(this.scheduler,observer),subscription=createRemovableDisposable(this,so);checkDisposed.call(this);this._trim(this.scheduler.now());this.observers.push(so);var n=this.q.length;for(var i=0,len=this.q.length;i<len;i++){so.onNext(this.q[i].value)}if(this.hasError){n++;so.onError(this.error)}else if(this.isStopped){n++;so.onCompleted()}so.ensureActive(n);return subscription}inherits(ReplaySubject,__super__);function ReplaySubject(bufferSize,windowSize,scheduler){this.bufferSize=bufferSize==null?Number.MAX_VALUE:bufferSize;this.windowSize=windowSize==null?Number.MAX_VALUE:windowSize;this.scheduler=scheduler||currentThreadScheduler;this.q=[];this.observers=[];this.isStopped=false;this.isDisposed=false;this.hasError=false;this.error=null;__super__.call(this,subscribe)}addProperties(ReplaySubject.prototype,Observer,{hasObservers:function(){return this.observers.length>0},_trim:function(now){while(this.q.length>this.bufferSize){this.q.shift()}while(this.q.length>0&&now-this.q[0].interval>this.windowSize){this.q.shift()}},onNext:function(value){checkDisposed.call(this);if(this.isStopped){return}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);var o=this.observers.slice(0);for(var i=0,len=o.length;i<len;i++){var observer=o[i];observer.onNext(value);observer.ensureActive()}},onError:function(error){checkDisposed.call(this);if(this.isStopped){return}this.isStopped=true;this.error=error;this.hasError=true;var now=this.scheduler.now();this._trim(now);var o=this.observers.slice(0);for(var i=0,len=o.length;i<len;i++){var observer=o[i];observer.onError(error);observer.ensureActive()}this.observers=[]},onCompleted:function(){checkDisposed.call(this);if(this.isStopped){return}this.isStopped=true;var now=this.scheduler.now();this._trim(now);var o=this.observers.slice(0);for(var i=0,len=o.length;i<len;i++){var observer=o[i];observer.onCompleted();observer.ensureActive()}this.observers=[]},dispose:function(){this.isDisposed=true;this.observers=null}});return ReplaySubject}(Observable);var ConnectableObservable=Rx.ConnectableObservable=function(__super__){inherits(ConnectableObservable,__super__);function ConnectableObservable(source,subject){var hasSubscription=false,subscription,sourceObservable=source.asObservable();this.connect=function(){if(!hasSubscription){hasSubscription=true;subscription=new CompositeDisposable(sourceObservable.subscribe(subject),disposableCreate(function(){hasSubscription=false}))}return subscription};__super__.call(this,subject.subscribe.bind(subject))}ConnectableObservable.prototype.refCount=function(){var connectableSubscription,count=0,source=this;return new AnonymousObservable(function(observer){var shouldConnect=++count===1,subscription=source.subscribe(observer);shouldConnect&&(connectableSubscription=source.connect());return function(){subscription.dispose();--count===0&&connectableSubscription.dispose()}})};return ConnectableObservable}(Observable);var Dictionary=function(){var primes=[1,3,7,13,31,61,127,251,509,1021,2039,4093,8191,16381,32749,65521,131071,262139,524287,1048573,2097143,4194301,8388593,16777213,33554393,67108859,134217689,268435399,536870909,1073741789,2147483647],noSuchkey="no such key",duplicatekey="duplicate key";function isPrime(candidate){if(candidate&1===0){return candidate===2}var num1=Math.sqrt(candidate),num2=3;while(num2<=num1){if(candidate%num2===0){return false}num2+=2}return true}function getPrime(min){var index,num,candidate;for(index=0;index<primes.length;++index){num=primes[index];if(num>=min){return num}}candidate=min|1;while(candidate<primes[primes.length-1]){if(isPrime(candidate)){return candidate}candidate+=2}return min}function stringHashFn(str){var hash=757602046;if(!str.length){return hash}for(var i=0,len=str.length;i<len;i++){var character=str.charCodeAt(i);hash=(hash<<5)-hash+character;hash=hash&hash}return hash}function numberHashFn(key){var c2=668265261;key=key^61^key>>>16;key=key+(key<<3);key=key^key>>>4;key=key*c2;key=key^key>>>15;return key}var getHashCode=function(){var uniqueIdCounter=0;return function(obj){if(obj==null){throw new Error(noSuchkey)}if(typeof obj==="string"){return stringHashFn(obj)}if(typeof obj==="number"){return numberHashFn(obj)}if(typeof obj==="boolean"){return obj===true?1:0}if(obj instanceof Date){return numberHashFn(obj.valueOf())}if(obj instanceof RegExp){return stringHashFn(obj.toString())}if(typeof obj.valueOf==="function"){var valueOf=obj.valueOf();if(typeof valueOf==="number"){return numberHashFn(valueOf)}if(typeof obj==="string"){return stringHashFn(valueOf)}}if(obj.getHashCode){return obj.getHashCode()}var id=17*uniqueIdCounter++;obj.getHashCode=function(){return id};return id}}();function newEntry(){return{key:null,value:null,next:0,hashCode:0}}function Dictionary(capacity,comparer){if(capacity<0){throw new Error("out of range")}if(capacity>0){this._initialize(capacity)}this.comparer=comparer||defaultComparer;this.freeCount=0;this.size=0;this.freeList=-1}var dictionaryProto=Dictionary.prototype;dictionaryProto._initialize=function(capacity){var prime=getPrime(capacity),i;this.buckets=new Array(prime);this.entries=new Array(prime);for(i=0;i<prime;i++){this.buckets[i]=-1;this.entries[i]=newEntry()}this.freeList=-1};dictionaryProto.add=function(key,value){return this._insert(key,value,true)};dictionaryProto._insert=function(key,value,add){if(!this.buckets){this._initialize(0)}var index3,num=getHashCode(key)&2147483647,index1=num%this.buckets.length;for(var index2=this.buckets[index1];index2>=0;index2=this.entries[index2].next){if(this.entries[index2].hashCode===num&&this.comparer(this.entries[index2].key,key)){if(add){throw new Error(duplicatekey)}this.entries[index2].value=value;return}}if(this.freeCount>0){index3=this.freeList;this.freeList=this.entries[index3].next;--this.freeCount}else{if(this.size===this.entries.length){this._resize();index1=num%this.buckets.length}index3=this.size;++this.size}this.entries[index3].hashCode=num;this.entries[index3].next=this.buckets[index1];this.entries[index3].key=key;this.entries[index3].value=value;this.buckets[index1]=index3};dictionaryProto._resize=function(){var prime=getPrime(this.size*2),numArray=new Array(prime);for(index=0;index<numArray.length;++index){numArray[index]=-1}var entryArray=new Array(prime);for(index=0;index<this.size;++index){entryArray[index]=this.entries[index]}for(var index=this.size;index<prime;++index){entryArray[index]=newEntry()}for(var index1=0;index1<this.size;++index1){var index2=entryArray[index1].hashCode%prime;entryArray[index1].next=numArray[index2];numArray[index2]=index1}this.buckets=numArray;this.entries=entryArray};dictionaryProto.remove=function(key){if(this.buckets){var num=getHashCode(key)&2147483647,index1=num%this.buckets.length,index2=-1;for(var index3=this.buckets[index1];index3>=0;index3=this.entries[index3].next){if(this.entries[index3].hashCode===num&&this.comparer(this.entries[index3].key,key)){if(index2<0){this.buckets[index1]=this.entries[index3].next}else{this.entries[index2].next=this.entries[index3].next}this.entries[index3].hashCode=-1;this.entries[index3].next=this.freeList;this.entries[index3].key=null;this.entries[index3].value=null;this.freeList=index3;++this.freeCount;return true}else{index2=index3}}}return false};dictionaryProto.clear=function(){var index,len;if(this.size<=0){return}for(index=0,len=this.buckets.length;index<len;++index){this.buckets[index]=-1}for(index=0;index<this.size;++index){this.entries[index]=newEntry()}this.freeList=-1;this.size=0};dictionaryProto._findEntry=function(key){if(this.buckets){var num=getHashCode(key)&2147483647;for(var index=this.buckets[num%this.buckets.length];index>=0;index=this.entries[index].next){if(this.entries[index].hashCode===num&&this.comparer(this.entries[index].key,key)){return index}}}return-1};dictionaryProto.count=function(){return this.size-this.freeCount};dictionaryProto.tryGetValue=function(key){var entry=this._findEntry(key);return entry>=0?this.entries[entry].value:undefined};dictionaryProto.getValues=function(){var index=0,results=[];if(this.entries){for(var index1=0;index1<this.size;index1++){if(this.entries[index1].hashCode>=0){results[index++]=this.entries[index1].value}}}return results};dictionaryProto.get=function(key){var entry=this._findEntry(key);if(entry>=0){return this.entries[entry].value}throw new Error(noSuchkey)};dictionaryProto.set=function(key,value){this._insert(key,value,false)};dictionaryProto.containskey=function(key){return this._findEntry(key)>=0};return Dictionary}();observableProto.join=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var leftDone=false,rightDone=false;var leftId=0,rightId=0;var leftMap=new Dictionary,rightMap=new Dictionary;group.add(left.subscribe(function(value){var id=leftId++;var md=new SingleAssignmentDisposable;leftMap.add(id,value);group.add(md);var expire=function(){leftMap.remove(id)&&leftMap.count()===0&&leftDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));rightMap.getValues().forEach(function(v){var result;try{result=resultSelector(value,v)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){leftDone=true;(rightDone||leftMap.count()===0)&&observer.onCompleted()}));group.add(right.subscribe(function(value){var id=rightId++;var md=new SingleAssignmentDisposable;rightMap.add(id,value);group.add(md);var expire=function(){rightMap.remove(id)&&rightMap.count()===0&&rightDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));leftMap.getValues().forEach(function(v){var result;try{result=resultSelector(v,value)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){rightDone=true;(leftDone||rightMap.count()===0)&&observer.onCompleted()}));return group})};observableProto.groupJoin=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var r=new RefCountDisposable(group);var leftMap=new Dictionary,rightMap=new Dictionary;var leftId=0,rightId=0;function handleError(e){return function(v){v.onError(e)}}group.add(left.subscribe(function(value){var s=new Subject;var id=leftId++;leftMap.add(id,s);var result;try{result=resultSelector(value,addRef(s,r))}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}observer.onNext(result);rightMap.getValues().forEach(function(v){s.onNext(v)});var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){leftMap.remove(id)&&s.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire))},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},observer.onCompleted.bind(observer)));group.add(right.subscribe(function(value){var id=rightId++;rightMap.add(id,value);var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){rightMap.remove(id);group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire));leftMap.getValues().forEach(function(v){v.onNext(value)})},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)}));return r})};observableProto.buffer=function(bufferOpeningsOrClosingSelector,bufferClosingSelector){return this.window.apply(this,arguments).selectMany(function(x){return x.toArray()})};observableProto.window=function(windowOpeningsOrClosingSelector,windowClosingSelector){if(arguments.length===1&&typeof arguments[0]!=="function"){return observableWindowWithBounaries.call(this,windowOpeningsOrClosingSelector)}return typeof windowOpeningsOrClosingSelector==="function"?observableWindowWithClosingSelector.call(this,windowOpeningsOrClosingSelector):observableWindowWithOpenings.call(this,windowOpeningsOrClosingSelector,windowClosingSelector)};function observableWindowWithOpenings(windowOpenings,windowClosingSelector){return windowOpenings.groupJoin(this,windowClosingSelector,observableEmpty,function(_,win){return win})}function observableWindowWithBounaries(windowBoundaries){var source=this;return new AnonymousObservable(function(observer){var win=new Subject,d=new CompositeDisposable,r=new RefCountDisposable(d);observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));isPromise(windowBoundaries)&&(windowBoundaries=observableFromPromise(windowBoundaries));d.add(windowBoundaries.subscribe(function(w){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r))
},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));return r})}function observableWindowWithClosingSelector(windowClosingSelector){var source=this;return new AnonymousObservable(function(observer){var m=new SerialDisposable,d=new CompositeDisposable(m),r=new RefCountDisposable(d),win=new Subject;observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));function createWindowClose(){var windowClose;try{windowClose=windowClosingSelector()}catch(e){observer.onError(e);return}isPromise(windowClose)&&(windowClose=observableFromPromise(windowClose));var m1=new SingleAssignmentDisposable;m.setDisposable(m1);m1.setDisposable(windowClose.take(1).subscribe(noop,function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r));createWindowClose()}))}createWindowClose();return r})}observableProto.pairwise=function(){var source=this;return new AnonymousObservable(function(observer){var previous,hasPrevious=false;return source.subscribe(function(x){if(hasPrevious){observer.onNext([previous,x])}else{hasPrevious=true}previous=x},observer.onError.bind(observer),observer.onCompleted.bind(observer))})};observableProto.partition=function(predicate,thisArg){var published=this.publish().refCount();return[published.filter(predicate,thisArg),published.filter(function(x,i,o){return!predicate.call(thisArg,x,i,o)})]};function enumerableWhile(condition,source){return new Enumerable(function(){return new Enumerator(function(){return condition()?{done:false,value:source}:{done:true,value:undefined}})})}observableProto.letBind=observableProto["let"]=function(func){return func(this)};Observable["if"]=Observable.ifThen=function(condition,thenSource,elseSourceOrScheduler){return observableDefer(function(){elseSourceOrScheduler||(elseSourceOrScheduler=observableEmpty());isPromise(thenSource)&&(thenSource=observableFromPromise(thenSource));isPromise(elseSourceOrScheduler)&&(elseSourceOrScheduler=observableFromPromise(elseSourceOrScheduler));typeof elseSourceOrScheduler.now==="function"&&(elseSourceOrScheduler=observableEmpty(elseSourceOrScheduler));return condition()?thenSource:elseSourceOrScheduler})};Observable["for"]=Observable.forIn=function(sources,resultSelector,thisArg){return enumerableOf(sources,resultSelector,thisArg).concat()};var observableWhileDo=Observable["while"]=Observable.whileDo=function(condition,source){isPromise(source)&&(source=observableFromPromise(source));return enumerableWhile(condition,source).concat()};observableProto.doWhile=function(condition){return observableConcat([this,observableWhileDo(condition,this)])};Observable["case"]=Observable.switchCase=function(selector,sources,defaultSourceOrScheduler){return observableDefer(function(){isPromise(defaultSourceOrScheduler)&&(defaultSourceOrScheduler=observableFromPromise(defaultSourceOrScheduler));defaultSourceOrScheduler||(defaultSourceOrScheduler=observableEmpty());typeof defaultSourceOrScheduler.now==="function"&&(defaultSourceOrScheduler=observableEmpty(defaultSourceOrScheduler));var result=sources[selector()];isPromise(result)&&(result=observableFromPromise(result));return result||defaultSourceOrScheduler})};observableProto.expand=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return new AnonymousObservable(function(observer){var q=[],m=new SerialDisposable,d=new CompositeDisposable(m),activeCount=0,isAcquired=false;var ensureActive=function(){var isOwner=false;if(q.length>0){isOwner=!isAcquired;isAcquired=true}if(isOwner){m.setDisposable(scheduler.scheduleRecursive(function(self){var work;if(q.length>0){work=q.shift()}else{isAcquired=false;return}var m1=new SingleAssignmentDisposable;d.add(m1);m1.setDisposable(work.subscribe(function(x){observer.onNext(x);var result=null;try{result=selector(x)}catch(e){observer.onError(e)}q.push(result);activeCount++;ensureActive()},observer.onError.bind(observer),function(){d.remove(m1);activeCount--;if(activeCount===0){observer.onCompleted()}}));self()}))}};q.push(source);activeCount++;ensureActive();return d})};Observable.forkJoin=function(){var allSources=argsOrArray(arguments,0);return new AnonymousObservable(function(subscriber){var count=allSources.length;if(count===0){subscriber.onCompleted();return disposableEmpty}var group=new CompositeDisposable,finished=false,hasResults=new Array(count),hasCompleted=new Array(count),results=new Array(count);for(var idx=0;idx<count;idx++){(function(i){var source=allSources[i];isPromise(source)&&(source=observableFromPromise(source));group.add(source.subscribe(function(value){if(!finished){hasResults[i]=true;results[i]=value}},function(e){finished=true;subscriber.onError(e);group.dispose()},function(){if(!finished){if(!hasResults[i]){subscriber.onCompleted();return}hasCompleted[i]=true;for(var ix=0;ix<count;ix++){if(!hasCompleted[ix]){return}}finished=true;subscriber.onNext(results);subscriber.onCompleted()}}))})(idx)}return group})};observableProto.forkJoin=function(second,resultSelector){var first=this;return new AnonymousObservable(function(observer){var leftStopped=false,rightStopped=false,hasLeft=false,hasRight=false,lastLeft,lastRight,leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(second)&&(second=observableFromPromise(second));leftSubscription.setDisposable(first.subscribe(function(left){hasLeft=true;lastLeft=left},function(err){rightSubscription.dispose();observer.onError(err)},function(){leftStopped=true;if(rightStopped){if(!hasLeft){observer.onCompleted()}else if(!hasRight){observer.onCompleted()}else{var result;try{result=resultSelector(lastLeft,lastRight)}catch(e){observer.onError(e);return}observer.onNext(result);observer.onCompleted()}}}));rightSubscription.setDisposable(second.subscribe(function(right){hasRight=true;lastRight=right},function(err){leftSubscription.dispose();observer.onError(err)},function(){rightStopped=true;if(leftStopped){if(!hasLeft){observer.onCompleted()}else if(!hasRight){observer.onCompleted()}else{var result;try{result=resultSelector(lastLeft,lastRight)}catch(e){observer.onError(e);return}observer.onNext(result);observer.onCompleted()}}}));return new CompositeDisposable(leftSubscription,rightSubscription)})};observableProto.manySelect=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return observableDefer(function(){var chain;return source.map(function(x){var curr=new ChainObservable(x);chain&&chain.onNext(x);chain=curr;return curr}).tap(noop,function(e){chain&&chain.onError(e)},function(){chain&&chain.onCompleted()}).observeOn(scheduler).map(selector)})};var ChainObservable=function(__super__){function subscribe(observer){var self=this,g=new CompositeDisposable;g.add(currentThreadScheduler.schedule(function(){observer.onNext(self.head);g.add(self.tail.mergeObservable().subscribe(observer))}));return g}inherits(ChainObservable,__super__);function ChainObservable(head){__super__.call(this,subscribe);this.head=head;this.tail=new AsyncSubject}addProperties(ChainObservable.prototype,Observer,{onCompleted:function(){this.onNext(Observable.empty())},onError:function(e){this.onNext(Observable.throwException(e))},onNext:function(v){this.tail.onNext(v);this.tail.onCompleted()}});return ChainObservable}(Observable);var Map=root.Map||function(){function Map(){this._keys=[];this._values=[]}Map.prototype.get=function(key){var i=this._keys.indexOf(key);return i!==-1?this._values[i]:undefined};Map.prototype.set=function(key,value){var i=this._keys.indexOf(key);i!==-1&&(this._values[i]=value);this._values[this._keys.push(key)-1]=value};Map.prototype.forEach=function(callback,thisArg){for(var i=0,len=this._keys.length;i<len;i++){callback.call(thisArg,this._values[i],this._keys[i])}};return Map}();function Pattern(patterns){this.patterns=patterns}Pattern.prototype.and=function(other){return new Pattern(this.patterns.concat(other))};Pattern.prototype.thenDo=function(selector){return new Plan(this,selector)};function Plan(expression,selector){this.expression=expression;this.selector=selector}Plan.prototype.activate=function(externalSubscriptions,observer,deactivate){var self=this;var joinObservers=[];for(var i=0,len=this.expression.patterns.length;i<len;i++){joinObservers.push(planCreateObserver(externalSubscriptions,this.expression.patterns[i],observer.onError.bind(observer)))}var activePlan=new ActivePlan(joinObservers,function(){var result;try{result=self.selector.apply(self,arguments)}catch(e){observer.onError(e);return}observer.onNext(result)},function(){for(var j=0,jlen=joinObservers.length;j<jlen;j++){joinObservers[j].removeActivePlan(activePlan)}deactivate(activePlan)});for(i=0,len=joinObservers.length;i<len;i++){joinObservers[i].addActivePlan(activePlan)}return activePlan};function planCreateObserver(externalSubscriptions,observable,onError){var entry=externalSubscriptions.get(observable);if(!entry){var observer=new JoinObserver(observable,onError);externalSubscriptions.set(observable,observer);return observer}return entry}function ActivePlan(joinObserverArray,onNext,onCompleted){this.joinObserverArray=joinObserverArray;this.onNext=onNext;this.onCompleted=onCompleted;this.joinObservers=new Map;for(var i=0,len=this.joinObserverArray.length;i<len;i++){var joinObserver=this.joinObserverArray[i];this.joinObservers.set(joinObserver,joinObserver)}}ActivePlan.prototype.dequeue=function(){this.joinObservers.forEach(function(v){v.queue.shift()})};ActivePlan.prototype.match=function(){var i,len,hasValues=true;for(i=0,len=this.joinObserverArray.length;i<len;i++){if(this.joinObserverArray[i].queue.length===0){hasValues=false;break}}if(hasValues){var firstValues=[],isCompleted=false;for(i=0,len=this.joinObserverArray.length;i<len;i++){firstValues.push(this.joinObserverArray[i].queue[0]);this.joinObserverArray[i].queue[0].kind==="C"&&(isCompleted=true)}if(isCompleted){this.onCompleted()}else{this.dequeue();var values=[];for(i=0,len=firstValues.length;i<firstValues.length;i++){values.push(firstValues[i].value)}this.onNext.apply(this,values)}}};var JoinObserver=function(__super__){inherits(JoinObserver,__super__);function JoinObserver(source,onError){__super__.call(this);this.source=source;this.onError=onError;this.queue=[];this.activePlans=[];this.subscription=new SingleAssignmentDisposable;this.isDisposed=false}var JoinObserverPrototype=JoinObserver.prototype;JoinObserverPrototype.next=function(notification){if(!this.isDisposed){if(notification.kind==="E"){this.onError(notification.exception);return}this.queue.push(notification);var activePlans=this.activePlans.slice(0);for(var i=0,len=activePlans.length;i<len;i++){activePlans[i].match()}}};JoinObserverPrototype.error=noop;JoinObserverPrototype.completed=noop;JoinObserverPrototype.addActivePlan=function(activePlan){this.activePlans.push(activePlan)};JoinObserverPrototype.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))};JoinObserverPrototype.removeActivePlan=function(activePlan){this.activePlans.splice(this.activePlans.indexOf(activePlan),1);this.activePlans.length===0&&this.dispose()};JoinObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);if(!this.isDisposed){this.isDisposed=true;this.subscription.dispose()}};return JoinObserver}(AbstractObserver);observableProto.and=function(right){return new Pattern([this,right])};observableProto.thenDo=function(selector){return new Pattern([this]).thenDo(selector)};Observable.when=function(){var plans=argsOrArray(arguments,0);return new AnonymousObservable(function(observer){var activePlans=[],externalSubscriptions=new Map;var outObserver=observerCreate(observer.onNext.bind(observer),function(err){externalSubscriptions.forEach(function(v){v.onError(err)});observer.onError(err)},observer.onCompleted.bind(observer));try{for(var i=0,len=plans.length;i<len;i++){activePlans.push(plans[i].activate(externalSubscriptions,outObserver,function(activePlan){var idx=activePlans.indexOf(activePlan);activePlans.splice(idx,1);activePlans.length===0&&observer.onCompleted()}))}}catch(e){observableThrow(e).subscribe(observer)}var group=new CompositeDisposable;externalSubscriptions.forEach(function(joinObserver){joinObserver.subscribe();group.add(joinObserver)});return group})};function observableTimerDate(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithAbsolute(dueTime,function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerDateAndPeriod(dueTime,period,scheduler){return new AnonymousObservable(function(observer){var count=0,d=dueTime,p=normalizeTime(period);return scheduler.scheduleRecursiveWithAbsolute(d,function(self){if(p>0){var now=scheduler.now();d=d+p;d<=now&&(d=now+p)}observer.onNext(count++);self(d)})})}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime===period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count+1})}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now()+dueTime,period,scheduler)})}var observableinterval=Observable.interval=function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler)};var observableTimer=Observable.timer=function(dueTime,periodOrScheduler,scheduler){var period;isScheduler(scheduler)||(scheduler=timeoutScheduler);if(periodOrScheduler!==undefined&&typeof periodOrScheduler==="number"){period=periodOrScheduler}else if(isScheduler(periodOrScheduler)){scheduler=periodOrScheduler}if(dueTime instanceof Date&&period===undefined){return observableTimerDate(dueTime.getTime(),scheduler)}if(dueTime instanceof Date&&period!==undefined){period=periodOrScheduler;return observableTimerDateAndPeriod(dueTime.getTime(),period,scheduler)}return period===undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler)};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable,exception=null,q=[],running=false,subscription;subscription=source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind==="E"){q=[];q.push(notification);exception=notification.value.exception;shouldRun=!running}else{q.push({value:notification.value,timestamp:notification.timestamp+dueTime});shouldRun=!active;active=true}if(shouldRun){if(exception!==null){observer.onError(exception)}else{d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception!==null){return}running=true;do{result=null;if(q.length>0&&q[0].timestamp-scheduler.now()<=0){result=q.shift().value}if(result!==null){result.accept(observer)}}while(result!==null);shouldRecurse=false;recurseDueTime=0;if(q.length>0){shouldRecurse=true;recurseDueTime=Math.max(0,q[0].timestamp-scheduler.now())}else{active=false}e=exception;running=false;if(e!==null){observer.onError(e)}else if(shouldRecurse){self(recurseDueTime)}}))}}});return new CompositeDisposable(subscription,cancelable)})}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime-scheduler.now(),scheduler)})}observableProto.delay=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler)};observableProto.throttle=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable,hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue=true;value=x;id++;var currentId=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue&&id===currentId&&observer.onNext(value);hasvalue=false}))},function(e){cancelable.dispose();observer.onError(e);hasvalue=false;id++},function(){cancelable.dispose();hasvalue&&observer.onNext(value);observer.onCompleted();hasvalue=false;id++});return new CompositeDisposable(subscription,cancelable)})};observableProto.windowWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){var source=this,timeShift;timeShiftOrScheduler==null&&(timeShift=timeSpan);isScheduler(scheduler)||(scheduler=timeoutScheduler);if(typeof timeShiftOrScheduler==="number"){timeShift=timeShiftOrScheduler}else if(isScheduler(timeShiftOrScheduler)){timeShift=timeSpan;scheduler=timeShiftOrScheduler}return new AnonymousObservable(function(observer){var groupDisposable,nextShift=timeShift,nextSpan=timeSpan,q=[],refCountDisposable,timerD=new SerialDisposable,totalTime=0;groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable);function createTimer(){var m=new SingleAssignmentDisposable,isSpan=false,isShift=false;timerD.setDisposable(m);if(nextSpan===nextShift){isSpan=true;isShift=true}else if(nextSpan<nextShift){isSpan=true}else{isShift=true}var newTotalTime=isSpan?nextSpan:nextShift,ts=newTotalTime-totalTime;totalTime=newTotalTime;if(isSpan){nextSpan+=timeShift}if(isShift){nextShift+=timeShift}m.setDisposable(scheduler.scheduleWithRelative(ts,function(){if(isShift){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}isSpan&&q.shift().onCompleted();createTimer()}))}q.push(new Subject);observer.onNext(addRef(q[0],refCountDisposable));createTimer();groupDisposable.add(source.subscribe(function(x){for(var i=0,len=q.length;i<len;i++){q[i].onNext(x)}},function(e){for(var i=0,len=q.length;i<len;i++){q[i].onError(e)}observer.onError(e)},function(){for(var i=0,len=q.length;i<len;i++){q[i].onCompleted()}observer.onCompleted()}));return refCountDisposable})};observableProto.windowWithTimeOrCount=function(timeSpan,count,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var timerD=new SerialDisposable,groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable),n=0,windowId=0,s=new Subject;function createTimer(id){var m=new SingleAssignmentDisposable;timerD.setDisposable(m);m.setDisposable(scheduler.scheduleWithRelative(timeSpan,function(){if(id!==windowId){return}n=0;var newId=++windowId;s.onCompleted();s=new Subject;observer.onNext(addRef(s,refCountDisposable));createTimer(newId)}))}observer.onNext(addRef(s,refCountDisposable));createTimer(0);groupDisposable.add(source.subscribe(function(x){var newId=0,newWindow=false;s.onNext(x);if(++n===count){newWindow=true;n=0;newId=++windowId;s.onCompleted();s=new Subject;observer.onNext(addRef(s,refCountDisposable))}newWindow&&createTimer(newId)},function(e){s.onError(e);observer.onError(e)},function(){s.onCompleted();observer.onCompleted()}));return refCountDisposable})};observableProto.bufferWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){return this.windowWithTime.apply(this,arguments).selectMany(function(x){return x.toArray()})};observableProto.bufferWithTimeOrCount=function(timeSpan,count,scheduler){return this.windowWithTimeOrCount(timeSpan,count,scheduler).selectMany(function(x){return x.toArray()})};observableProto.timeInterval=function(scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return observableDefer(function(){var last=scheduler.now();return source.map(function(x){var now=scheduler.now(),span=now-last;last=now;return{value:x,interval:span}})})};observableProto.timestamp=function(scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return this.map(function(x){return{value:x,timestamp:scheduler.now()}})};function sampleObservable(source,sampler){return new AnonymousObservable(function(observer){var atEnd,value,hasValue;function sampleSubscribe(){if(hasValue){hasValue=false;observer.onNext(value)}atEnd&&observer.onCompleted()}return new CompositeDisposable(source.subscribe(function(newValue){hasValue=true;value=newValue},observer.onError.bind(observer),function(){atEnd=true}),sampler.subscribe(sampleSubscribe,observer.onError.bind(observer),sampleSubscribe))})}observableProto.sample=function(intervalOrSampler,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return typeof intervalOrSampler==="number"?sampleObservable(this,observableinterval(intervalOrSampler,scheduler)):sampleObservable(this,intervalOrSampler)};observableProto.timeout=function(dueTime,other,scheduler){other||(other=observableThrow(new Error("Timeout")));isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=dueTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(observer){var id=0,original=new SingleAssignmentDisposable,subscription=new SerialDisposable,switched=false,timer=new SerialDisposable;subscription.setDisposable(original);function createTimer(){var myId=id;timer.setDisposable(scheduler[schedulerMethod](dueTime,function(){if(id===myId){isPromise(other)&&(other=observableFromPromise(other));subscription.setDisposable(other.subscribe(observer))}}))}createTimer();original.setDisposable(source.subscribe(function(x){if(!switched){id++;observer.onNext(x);createTimer()}},function(e){if(!switched){id++;observer.onError(e)}},function(){if(!switched){id++;observer.onCompleted()}}));return new CompositeDisposable(subscription,timer)})};Observable.generateWithAbsoluteTime=function(initialState,condition,iterate,resultSelector,timeSelector,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var first=true,hasResult=false,result,state=initialState,time;return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(),function(self){hasResult&&observer.onNext(result);try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){result=resultSelector(state);time=timeSelector(state)}}catch(e){observer.onError(e);return}if(hasResult){self(time)}else{observer.onCompleted()}})})};Observable.generateWithRelativeTime=function(initialState,condition,iterate,resultSelector,timeSelector,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var first=true,hasResult=false,result,state=initialState,time;return scheduler.scheduleRecursiveWithRelative(0,function(self){hasResult&&observer.onNext(result);try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){result=resultSelector(state);time=timeSelector(state)}}catch(e){observer.onError(e);return}if(hasResult){self(time)}else{observer.onCompleted()}})})};observableProto.delaySubscription=function(dueTime,scheduler){return this.delayWithSelector(observableTimer(dueTime,isScheduler(scheduler)?scheduler:timeoutScheduler),observableEmpty)};observableProto.delayWithSelector=function(subscriptionDelay,delayDurationSelector){var source=this,subDelay,selector;if(typeof subscriptionDelay==="function"){selector=subscriptionDelay}else{subDelay=subscriptionDelay;selector=delayDurationSelector}return new AnonymousObservable(function(observer){var delays=new CompositeDisposable,atEnd=false,done=function(){if(atEnd&&delays.length===0){observer.onCompleted()}},subscription=new SerialDisposable,start=function(){subscription.setDisposable(source.subscribe(function(x){var delay;try{delay=selector(x)}catch(error){observer.onError(error);return}var d=new SingleAssignmentDisposable;delays.add(d);d.setDisposable(delay.subscribe(function(){observer.onNext(x);delays.remove(d);done()},observer.onError.bind(observer),function(){observer.onNext(x);delays.remove(d);done()}))},observer.onError.bind(observer),function(){atEnd=true;subscription.dispose();done()}))};if(!subDelay){start()}else{subscription.setDisposable(subDelay.subscribe(function(){start()},observer.onError.bind(observer),function(){start()}))}return new CompositeDisposable(subscription,delays)})};observableProto.timeoutWithSelector=function(firstTimeout,timeoutdurationSelector,other){if(arguments.length===1){timeoutdurationSelector=firstTimeout;firstTimeout=observableNever()}other||(other=observableThrow(new Error("Timeout")));var source=this;return new AnonymousObservable(function(observer){var subscription=new SerialDisposable,timer=new SerialDisposable,original=new SingleAssignmentDisposable;subscription.setDisposable(original);var id=0,switched=false;function setTimer(timeout){var myId=id;function timerWins(){return id===myId}var d=new SingleAssignmentDisposable;timer.setDisposable(d);d.setDisposable(timeout.subscribe(function(){timerWins()&&subscription.setDisposable(other.subscribe(observer));d.dispose()},function(e){timerWins()&&observer.onError(e)},function(){timerWins()&&subscription.setDisposable(other.subscribe(observer))}))}setTimer(firstTimeout);function observerWins(){var res=!switched;if(res){id++}return res}original.setDisposable(source.subscribe(function(x){if(observerWins()){observer.onNext(x);var timeout;try{timeout=timeoutdurationSelector(x)}catch(e){observer.onError(e);return}setTimer(isPromise(timeout)?observableFromPromise(timeout):timeout)}},function(e){observerWins()&&observer.onError(e)},function(){observerWins()&&observer.onCompleted()}));return new CompositeDisposable(subscription,timer)})};observableProto.throttleWithSelector=function(throttleDurationSelector){var source=this;return new AnonymousObservable(function(observer){var value,hasValue=false,cancelable=new SerialDisposable,id=0;var subscription=source.subscribe(function(x){var throttle;try{throttle=throttleDurationSelector(x)}catch(e){observer.onError(e);return}isPromise(throttle)&&(throttle=observableFromPromise(throttle));hasValue=true;value=x;id++;var currentid=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(throttle.subscribe(function(){hasValue&&id===currentid&&observer.onNext(value);hasValue=false;d.dispose()},observer.onError.bind(observer),function(){hasValue&&id===currentid&&observer.onNext(value);hasValue=false;d.dispose()}))},function(e){cancelable.dispose();observer.onError(e);hasValue=false;id++},function(){cancelable.dispose();hasValue&&observer.onNext(value);observer.onCompleted();hasValue=false;id++});return new CompositeDisposable(subscription,cancelable)})};observableProto.skipLastWithTime=function(duration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){observer.onNext(q.shift().value)}},observer.onError.bind(observer),function(){var now=scheduler.now();while(q.length>0&&now-q[0].interval>=duration){observer.onNext(q.shift().value)}observer.onCompleted()})})};observableProto.takeLastWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},observer.onError.bind(observer),function(){var now=scheduler.now();while(q.length>0){var next=q.shift();if(now-next.interval<=duration){observer.onNext(next.value)}}observer.onCompleted()})})};observableProto.takeLastBufferWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},observer.onError.bind(observer),function(){var now=scheduler.now(),res=[];while(q.length>0){var next=q.shift();if(now-next.interval<=duration){res.push(next.value)}}observer.onNext(res);observer.onCompleted()})})};observableProto.takeWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){return new CompositeDisposable(scheduler.scheduleWithRelative(duration,observer.onCompleted.bind(observer)),source.subscribe(observer))})};observableProto.skipWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))})};observableProto.skipUntilWithTime=function(startTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=startTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler[schedulerMethod](startTime,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))})};observableProto.takeUntilWithTime=function(endTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=endTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(observer){return new CompositeDisposable(scheduler[schedulerMethod](endTime,observer.onCompleted.bind(observer)),source.subscribe(observer))})};observableProto.exclusive=function(){var sources=this;return new AnonymousObservable(function(observer){var hasCurrent=false,isStopped=false,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));var innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},observer.onError.bind(observer),function(){isStopped=true;if(!hasCurrent&&g.length===1){observer.onCompleted()}}));return g})};observableProto.exclusiveMap=function(selector,thisArg){var sources=this;return new AnonymousObservable(function(observer){var index=0,hasCurrent=false,isStopped=true,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){var result;try{result=selector.call(thisArg,x,index++,innerSource)}catch(e){observer.onError(e);return}observer.onNext(result)},observer.onError.bind(observer),function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},observer.onError.bind(observer),function(){isStopped=true;
if(g.length===1&&!hasCurrent){observer.onCompleted()}}));return g})};Rx.VirtualTimeScheduler=function(__super__){function notImplemented(){throw new Error("Not implemented")}function localNow(){return this.toDateTimeOffset(this.clock)}function scheduleNow(state,action){return this.scheduleAbsoluteWithState(state,this.clock,action)}function scheduleRelative(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime),action)}function scheduleAbsolute(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime-this.now()),action)}function invokeAction(scheduler,action){action();return disposableEmpty}inherits(VirtualTimeScheduler,__super__);function VirtualTimeScheduler(initialClock,comparer){this.clock=initialClock;this.comparer=comparer;this.isEnabled=false;this.queue=new PriorityQueue(1024);__super__.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}var VirtualTimeSchedulerPrototype=VirtualTimeScheduler.prototype;VirtualTimeSchedulerPrototype.add=notImplemented;VirtualTimeSchedulerPrototype.toDateTimeOffset=notImplemented;VirtualTimeSchedulerPrototype.toRelative=notImplemented;VirtualTimeSchedulerPrototype.schedulePeriodicWithState=function(state,period,action){var s=new SchedulePeriodicRecursive(this,state,period,action);return s.start()};VirtualTimeSchedulerPrototype.scheduleRelativeWithState=function(state,dueTime,action){var runAt=this.add(this.clock,dueTime);return this.scheduleAbsoluteWithState(state,runAt,action)};VirtualTimeSchedulerPrototype.scheduleRelative=function(dueTime,action){return this.scheduleRelativeWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.start=function(){if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled)}};VirtualTimeSchedulerPrototype.stop=function(){this.isEnabled=false};VirtualTimeSchedulerPrototype.advanceTo=function(time){var dueToClock=this.comparer(this.clock,time);if(this.comparer(this.clock,time)>0){throw new Error(argumentOutOfRange)}if(dueToClock===0){return}if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null&&this.comparer(next.dueTime,time)<=0){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled);this.clock=time}};VirtualTimeSchedulerPrototype.advanceBy=function(time){var dt=this.add(this.clock,time),dueToClock=this.comparer(this.clock,dt);if(dueToClock>0){throw new Error(argumentOutOfRange)}if(dueToClock===0){return}this.advanceTo(dt)};VirtualTimeSchedulerPrototype.sleep=function(time){var dt=this.add(this.clock,time);if(this.comparer(this.clock,dt)>=0){throw new Error(argumentOutOfRange)}this.clock=dt};VirtualTimeSchedulerPrototype.getNext=function(){while(this.queue.length>0){var next=this.queue.peek();if(next.isCancelled()){this.queue.dequeue()}else{return next}}return null};VirtualTimeSchedulerPrototype.scheduleAbsolute=function(dueTime,action){return this.scheduleAbsoluteWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState=function(state,dueTime,action){var self=this;function run(scheduler,state1){self.queue.remove(si);return action(scheduler,state1)}var si=new ScheduledItem(this,state,run,dueTime,this.comparer);this.queue.enqueue(si);return si.disposable};return VirtualTimeScheduler}(Scheduler);Rx.HistoricalScheduler=function(__super__){inherits(HistoricalScheduler,__super__);function HistoricalScheduler(initialClock,comparer){var clock=initialClock==null?0:initialClock;var cmp=comparer||defaultSubComparer;__super__.call(this,clock,cmp)}var HistoricalSchedulerProto=HistoricalScheduler.prototype;HistoricalSchedulerProto.add=function(absolute,relative){return absolute+relative};HistoricalSchedulerProto.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};HistoricalSchedulerProto.toRelative=function(timeSpan){return timeSpan};return HistoricalScheduler}(Rx.VirtualTimeScheduler);var AnonymousObservable=Rx.AnonymousObservable=function(__super__){inherits(AnonymousObservable,__super__);function fixSubscriber(subscriber){if(subscriber&&typeof subscriber.dispose==="function"){return subscriber}return typeof subscriber==="function"?disposableCreate(subscriber):disposableEmpty}function AnonymousObservable(subscribe){if(!(this instanceof AnonymousObservable)){return new AnonymousObservable(subscribe)}function s(observer){var setDisposable=function(){try{autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)))}catch(e){if(!autoDetachObserver.fail(e)){throw e}}};var autoDetachObserver=new AutoDetachObserver(observer);if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.schedule(setDisposable)}else{setDisposable()}return autoDetachObserver}__super__.call(this,s)}return AnonymousObservable}(Observable);var AutoDetachObserver=function(_super){inherits(AutoDetachObserver,_super);function AutoDetachObserver(observer){_super.call(this);this.observer=observer;this.m=new SingleAssignmentDisposable}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next=function(value){var noError=false;try{this.observer.onNext(value);noError=true}catch(e){throw e}finally{if(!noError){this.dispose()}}};AutoDetachObserverPrototype.error=function(exn){try{this.observer.onError(exn)}catch(e){throw e}finally{this.dispose()}};AutoDetachObserverPrototype.completed=function(){try{this.observer.onCompleted()}catch(e){throw e}finally{this.dispose()}};AutoDetachObserverPrototype.setDisposable=function(value){this.m.setDisposable(value)};AutoDetachObserverPrototype.getDisposable=function(value){return this.m.getDisposable()};AutoDetachObserverPrototype.disposable=function(value){return arguments.length?this.getDisposable():setDisposable(value)};AutoDetachObserverPrototype.dispose=function(){_super.prototype.dispose.call(this);this.m.dispose()};return AutoDetachObserver}(AbstractObserver);var GroupedObservable=function(__super__){inherits(GroupedObservable,__super__);function subscribe(observer){return this.underlyingObservable.subscribe(observer)}function GroupedObservable(key,underlyingObservable,mergedDisposable){__super__.call(this,subscribe);this.key=key;this.underlyingObservable=!mergedDisposable?underlyingObservable:new AnonymousObservable(function(observer){return new CompositeDisposable(mergedDisposable.getDisposable(),underlyingObservable.subscribe(observer))})}return GroupedObservable}(Observable);var Subject=Rx.Subject=function(_super){function subscribe(observer){checkDisposed.call(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.exception){observer.onError(this.exception);return disposableEmpty}observer.onCompleted();return disposableEmpty}inherits(Subject,_super);function Subject(){_super.call(this,subscribe);this.isDisposed=false,this.isStopped=false,this.observers=[]}addProperties(Subject.prototype,Observer,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed.call(this);if(!this.isStopped){var os=this.observers.slice(0);this.isStopped=true;for(var i=0,len=os.length;i<len;i++){os[i].onCompleted()}this.observers=[]}},onError:function(exception){checkDisposed.call(this);if(!this.isStopped){var os=this.observers.slice(0);this.isStopped=true;this.exception=exception;for(var i=0,len=os.length;i<len;i++){os[i].onError(exception)}this.observers=[]}},onNext:function(value){checkDisposed.call(this);if(!this.isStopped){var os=this.observers.slice(0);for(var i=0,len=os.length;i<len;i++){os[i].onNext(value)}}},dispose:function(){this.isDisposed=true;this.observers=null}});Subject.create=function(observer,observable){return new AnonymousSubject(observer,observable)};return Subject}(Observable);var AsyncSubject=Rx.AsyncSubject=function(__super__){function subscribe(observer){checkDisposed.call(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}var ex=this.exception,hv=this.hasValue,v=this.value;if(ex){observer.onError(ex)}else if(hv){observer.onNext(v);observer.onCompleted()}else{observer.onCompleted()}return disposableEmpty}inherits(AsyncSubject,__super__);function AsyncSubject(){__super__.call(this,subscribe);this.isDisposed=false;this.isStopped=false;this.value=null;this.hasValue=false;this.observers=[];this.exception=null}addProperties(AsyncSubject.prototype,Observer,{hasObservers:function(){checkDisposed.call(this);return this.observers.length>0},onCompleted:function(){var o,i,len;checkDisposed.call(this);if(!this.isStopped){this.isStopped=true;var os=this.observers.slice(0),v=this.value,hv=this.hasValue;if(hv){for(i=0,len=os.length;i<len;i++){o=os[i];o.onNext(v);o.onCompleted()}}else{for(i=0,len=os.length;i<len;i++){os[i].onCompleted()}}this.observers=[]}},onError:function(error){checkDisposed.call(this);if(!this.isStopped){var os=this.observers.slice(0);this.isStopped=true;this.exception=error;for(var i=0,len=os.length;i<len;i++){os[i].onError(error)}this.observers=[]}},onNext:function(value){checkDisposed.call(this);if(this.isStopped){return}this.value=value;this.hasValue=true},dispose:function(){this.isDisposed=true;this.observers=null;this.exception=null;this.value=null}});return AsyncSubject}(Observable);var AnonymousSubject=Rx.AnonymousSubject=function(__super__){inherits(AnonymousSubject,__super__);function AnonymousSubject(observer,observable){this.observer=observer;this.observable=observable;__super__.call(this,this.observable.subscribe.bind(this.observable))}addProperties(AnonymousSubject.prototype,Observer,{onCompleted:function(){this.observer.onCompleted()},onError:function(exception){this.observer.onError(exception)},onNext:function(value){this.observer.onNext(value)}});return AnonymousSubject}(Observable);if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root.Rx=Rx;define(function(){return Rx})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=Rx).Rx=Rx}else{freeExports.Rx=Rx}}else{root.Rx=Rx}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:2}],5:[function(require,module,exports){(function(global){(function(factory){var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var root=objectTypes[typeof window]&&window||this,freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}if(typeof define==="function"&&define.amd){define(["rx.virtualtime","exports"],function(Rx,exports){root.Rx=factory(root,exports,Rx);return root.Rx})}else if(typeof module==="object"&&module&&module.exports===freeExports){module.exports=factory(root,module.exports,require("./rx.all"))}else{root.Rx=factory(root,{},root.Rx)}}).call(this,function(root,exp,Rx,undefined){var Observer=Rx.Observer,Observable=Rx.Observable,Notification=Rx.Notification,VirtualTimeScheduler=Rx.VirtualTimeScheduler,Disposable=Rx.Disposable,disposableEmpty=Disposable.empty,disposableCreate=Disposable.create,CompositeDisposable=Rx.CompositeDisposable,SingleAssignmentDisposable=Rx.SingleAssignmentDisposable,slice=Array.prototype.slice,inherits=Rx.internals.inherits,defaultComparer=Rx.internals.isEqual;function argsOrArray(args,idx){return args.length===1&&Array.isArray(args[idx])?args[idx]:slice.call(args)}function OnNextPredicate(predicate){this.predicate=predicate}OnNextPredicate.prototype.equals=function(other){if(other===this){return true}if(other==null){return false}if(other.kind!=="N"){return false}return this.predicate(other.value)};function OnErrorPredicate(predicate){this.predicate=predicate}OnErrorPredicate.prototype.equals=function(other){if(other===this){return true}if(other==null){return false}if(other.kind!=="E"){return false}return this.predicate(other.exception)};var ReactiveTest=Rx.ReactiveTest={created:100,subscribed:200,disposed:1e3,onNext:function(ticks,value){if(typeof value==="function"){return new Recorded(ticks,new OnNextPredicate(value))}return new Recorded(ticks,Notification.createOnNext(value))},onError:function(ticks,exception){if(typeof exception==="function"){return new Recorded(ticks,new OnErrorPredicate(exception))}return new Recorded(ticks,Notification.createOnError(exception))},onCompleted:function(ticks){return new Recorded(ticks,Notification.createOnCompleted())},subscribe:function(start,end){return new Subscription(start,end)}};var Recorded=Rx.Recorded=function(time,value,comparer){this.time=time;this.value=value;this.comparer=comparer||defaultComparer};Recorded.prototype.equals=function(other){return this.time===other.time&&this.comparer(this.value,other.value)};Recorded.prototype.toString=function(){return this.value.toString()+"@"+this.time};var Subscription=Rx.Subscription=function(start,end){this.subscribe=start;this.unsubscribe=end||Number.MAX_VALUE};Subscription.prototype.equals=function(other){return this.subscribe===other.subscribe&&this.unsubscribe===other.unsubscribe};Subscription.prototype.toString=function(){return"("+this.subscribe+", "+(this.unsubscribe===Number.MAX_VALUE?"Infinite":this.unsubscribe)+")"};var MockDisposable=Rx.MockDisposable=function(scheduler){this.scheduler=scheduler;this.disposes=[];this.disposes.push(this.scheduler.clock)};MockDisposable.prototype.dispose=function(){this.disposes.push(this.scheduler.clock)};var MockObserver=function(_super){inherits(MockObserver,_super);function MockObserver(scheduler){_super.call(this);this.scheduler=scheduler;this.messages=[]}var MockObserverPrototype=MockObserver.prototype;MockObserverPrototype.onNext=function(value){this.messages.push(new Recorded(this.scheduler.clock,Notification.createOnNext(value)))};MockObserverPrototype.onError=function(exception){this.messages.push(new Recorded(this.scheduler.clock,Notification.createOnError(exception)))};MockObserverPrototype.onCompleted=function(){this.messages.push(new Recorded(this.scheduler.clock,Notification.createOnCompleted()))};return MockObserver}(Observer);var HotObservable=function(_super){function subscribe(observer){var observable=this;this.observers.push(observer);this.subscriptions.push(new Subscription(this.scheduler.clock));var index=this.subscriptions.length-1;return disposableCreate(function(){var idx=observable.observers.indexOf(observer);observable.observers.splice(idx,1);observable.subscriptions[index]=new Subscription(observable.subscriptions[index].subscribe,observable.scheduler.clock)})}inherits(HotObservable,_super);function HotObservable(scheduler,messages){_super.call(this,subscribe);var message,notification,observable=this;this.scheduler=scheduler;this.messages=messages;this.subscriptions=[];this.observers=[];for(var i=0,len=this.messages.length;i<len;i++){message=this.messages[i];notification=message.value;(function(innerNotification){scheduler.scheduleAbsoluteWithState(null,message.time,function(){var obs=observable.observers.slice(0);for(var j=0,jLen=obs.length;j<jLen;j++){innerNotification.accept(obs[j])}return disposableEmpty})})(notification)}}return HotObservable}(Observable);var ColdObservable=function(_super){function subscribe(observer){var message,notification,observable=this;this.subscriptions.push(new Subscription(this.scheduler.clock));var index=this.subscriptions.length-1;var d=new CompositeDisposable;for(var i=0,len=this.messages.length;i<len;i++){message=this.messages[i];notification=message.value;(function(innerNotification){d.add(observable.scheduler.scheduleRelativeWithState(null,message.time,function(){innerNotification.accept(observer);return disposableEmpty}))})(notification)}return disposableCreate(function(){observable.subscriptions[index]=new Subscription(observable.subscriptions[index].subscribe,observable.scheduler.clock);d.dispose()})}inherits(ColdObservable,_super);function ColdObservable(scheduler,messages){_super.call(this,subscribe);this.scheduler=scheduler;this.messages=messages;this.subscriptions=[]}return ColdObservable}(Observable);Rx.TestScheduler=function(_super){inherits(TestScheduler,_super);function baseComparer(x,y){return x>y?1:x<y?-1:0}function TestScheduler(){_super.call(this,0,baseComparer)}TestScheduler.prototype.scheduleAbsoluteWithState=function(state,dueTime,action){if(dueTime<=this.clock){dueTime=this.clock+1}return _super.prototype.scheduleAbsoluteWithState.call(this,state,dueTime,action)};TestScheduler.prototype.add=function(absolute,relative){return absolute+relative};TestScheduler.prototype.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};TestScheduler.prototype.toRelative=function(timeSpan){return timeSpan};TestScheduler.prototype.startWithTiming=function(create,created,subscribed,disposed){var observer=this.createObserver(),source,subscription;this.scheduleAbsoluteWithState(null,created,function(){source=create();return disposableEmpty});this.scheduleAbsoluteWithState(null,subscribed,function(){subscription=source.subscribe(observer);return disposableEmpty});this.scheduleAbsoluteWithState(null,disposed,function(){subscription.dispose();return disposableEmpty});this.start();return observer};TestScheduler.prototype.startWithDispose=function(create,disposed){return this.startWithTiming(create,ReactiveTest.created,ReactiveTest.subscribed,disposed)};TestScheduler.prototype.startWithCreate=function(create){return this.startWithTiming(create,ReactiveTest.created,ReactiveTest.subscribed,ReactiveTest.disposed)};TestScheduler.prototype.createHotObservable=function(){var messages=argsOrArray(arguments,0);return new HotObservable(this,messages)};TestScheduler.prototype.createColdObservable=function(){var messages=argsOrArray(arguments,0);return new ColdObservable(this,messages)};TestScheduler.prototype.createObserver=function(){return new MockObserver(this)};return TestScheduler}(VirtualTimeScheduler);return Rx})}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./rx.all":4}],6:[function(require,module,exports){var Rx=require("./dist/rx.all");require("./dist/rx.testing");var EventEmitter=require("events").EventEmitter,Observable=Rx.Observable;Rx.Node={fromCallback:function(func,context,selector){return Observable.fromCallback(func,context,selector)},fromNodeCallback:function(func,context,selector){return Observable.fromNodeCallback(func,context,selector)},fromEvent:function(eventEmitter,eventName,selector){return Observable.fromEvent(eventEmitter,eventName,selector)},toEventEmitter:function(observable,eventName,selector){var e=new EventEmitter;e.publish=function(){e.subscription=observable.subscribe(function(x){var result=x;if(selector){try{result=selector(x)}catch(e){e.emit("error",e);return}}e.emit(eventName,result)},function(err){e.emit("error",err)},function(){e.emit("end")})};return e},fromStream:function(stream,finishEventName){return Observable.create(function(observer){function dataHandler(data){observer.onNext(data)}function errorHandler(err){observer.onError(err)}function endHandler(){observer.onCompleted()}if(!finishEventName){finishEventName="end"}stream.addListener("data",dataHandler);stream.addListener("error",errorHandler);stream.addListener(finishEventName,endHandler);return function(){stream.removeListener("data",dataHandler);stream.removeListener("error",errorHandler);stream.removeListener(finishEventName,endHandler)}}).publish().refCount()},fromReadableStream:function(stream){return this.fromStream(stream,"end")},fromWritableStream:function(stream){return this.fromStream(stream,"finish")},fromTransformStream:function(stream){return this.fromStream(stream,"finish")},writeToStream:function(observable,stream,encoding){return observable.subscribe(function(x){stream.write(x,encoding)},function(err){stream.emit("error",err)},function(){!stream._isStdio&&stream.end()})}};module.exports=Rx},{"./dist/rx.all":4,"./dist/rx.testing":5,events:1}],"rx-dom":[function(require,module,exports){var Rx=require("rx");require("./dist/rx.dom");module.exports=Rx},{"./dist/rx.dom":3,rx:6}]},{},[]);Rx=require("rx-dom");main();function searchWikipedia(term){var cleanTerm=window.encodeURIComponent(term);var url="http://en.wikipedia.org/w/api.php?action=opensearch&format=json&search="+cleanTerm+"&callback=JSONPCallback";return Rx.DOM.jsonpRequest(url)}function clearChildren(element){while(element.firstChild){element.removeChild(element.firstChild)}}function buildPage(){var label=document.createElement("label");label.textContent="Enter Query for Wikipedia";document.body.appendChild(label);var input=document.createElement("input");input.id="textInput";input.type="text";input.placeholder="Enter Query...";document.body.appendChild(input);var results=document.createElement("ul");results.id="results";document.body.appendChild(results)}function main(){buildPage();var input=document.querySelector("#textInput");var results=document.querySelector("#results");var keyup=Rx.DOM.fromEvent(input,"keyup").map(function(e){return e.target.value}).filter(function(text){return text.length>2}).throttle(750).distinctUntilChanged();var searcher=keyup.map(function(text){return searchWikipedia(text)}).switchLatest();var subscription=searcher.subscribe(function(data){clearChildren(results);var res=data[1];var i,len,li;for(i=0,len=res.length;i<len;i++){li=document.createElement("li");li.innerHTML=res[i];results.appendChild(li)}},function(error){clearChildren(results);var li=document.createElement("li");li.innerHTML="Error: "+error;results.appendChild(li)})}
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"rx-dom": "4.0.1"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.