forked from lytup/atmosphere-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
atmosphere.min.js
95 lines (95 loc) · 36.1 KB
/
atmosphere.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* Copyright 2014 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Atmosphere.js
* https://github.com/Atmosphere/atmosphere-javascript
*
* API reference
* https://github.com/Atmosphere/atmosphere/wiki/jQuery.atmosphere.js-API
*
* Highly inspired by
* - Portal by Donghwan Kim http://flowersinthesand.github.io/portal/
*/
(function(d,q){"function"===typeof define&&define.amd?define(q):d.atmosphere=q()})(this,function(){var d={},q=[],D=[],U=0,X=Object.prototype.hasOwnProperty,d={onError:function(d){},onClose:function(d){},onOpen:function(d){},onReopen:function(d){},onMessage:function(d){},onReconnect:function(d,g){},onMessagePublished:function(d){},onTransportFailure:function(d,g){},onLocalMessage:function(d){},onFailureToReconnect:function(d,g){},onClientTimeout:function(d){},WebsocketApiAdapter:function(f){var g,
k;f.onMessage=function(d){k.onmessage({data:d.responseBody})};f.onMessagePublished=function(d){k.onmessage({data:d.responseBody})};f.onOpen=function(d){k.onopen(d)};k={close:function(){g.close()},send:function(d){g.push(d)},onmessage:function(d){},onopen:function(d){},onclose:function(d){},onerror:function(d){}};g=new d.subscribe(f);return k},AtmosphereRequest:function(f){function g(b,a){return""===e.partialMessage&&"streaming"===a.transport&&b.responseText.length>a.maxStreamingLength?!0:!1}function k(){if(c.enableProtocol&&
!c.firstMessage){var b="X-Atmosphere-Transport=close&X-Atmosphere-tracking-id="+c.uuid;d.util.each(c.headers,function(a,h){var f=d.util.isFunction(h)?h.call(this,c,c,e):h;null!=f&&(b+="&"+encodeURIComponent(a)+"="+encodeURIComponent(f))});var a=c.url.replace(/([?&])_=[^&]*/,b),a=a+(a===c.url?(/\?/.test(c.url)?"&":"?")+b:""),h=new d.AtmosphereRequest({connected:!1});h.attachHeadersAsQueryString=!1;h.dropHeaders=!0;h.url=a;h.contentType="text/plain";h.transport="polling";h.method="GET";h.data="";h.async=
!1;ma("",h)}}function l(){"debug"===c.logLevel&&d.util.debug("Closing");E=!0;c.reconnectId&&(clearTimeout(c.reconnectId),delete c.reconnectId);c.heartbeatTimer&&clearTimeout(c.heartbeatTimer);c.reconnect=!1;e.request=c;e.state="unsubscribe";e.responseBody="";e.status=408;e.partialMessage="";v();k();m()}function m(){e.partialMessage="";c.id&&clearTimeout(c.id);c.heartbeatTimer&&clearTimeout(c.heartbeatTimer);null!=A&&(A.close(),A=null);null!=B&&(B.abort(),B=null);null!=J&&(J.abort(),J=null);null!=
s&&(s.canSendMessage&&s.close(),s=null);null!=w&&(w.close(),w=null);null!=C&&(clearInterval(V),document.cookie=Y+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/",C.signal("close",{reason:"",heir:E?(C.get("children")||[])[0]:x}),C.close());null!=t&&t.close()}function da(b){m();Z=!0;E=!1;y=0;A=J=w=s=null;c=d.util.extend(c,b);c.mrequest=c.reconnect;c.reconnect||(c.reconnect=!0)}function z(){if(c.shared){t=q(c);if(null!=t&&("debug"===c.logLevel&&d.util.debug("Storage service available. All communication will be local"),
t.open(c)))return;"debug"===c.logLevel&&d.util.debug("No Storage service available.");t=null}c.firstMessage=0==U?!0:!1;c.isOpen=!1;c.ctime=d.util.now();0===c.uuid&&(c.uuid=U);e.closedByClientTimeout=!1;"websocket"!==c.transport&&"sse"!==c.transport?N(c):"websocket"===c.transport?null!=c.webSocketImpl||window.WebSocket||window.MozWebSocket?$(!1):K("Websocket is not supported, using request.fallbackTransport ("+c.fallbackTransport+")"):"sse"===c.transport&&(window.EventSource?p(!1):K("Server Side Events(SSE) is not supported, using request.fallbackTransport ("+
c.fallbackTransport+")"))}function q(b){function a(a,b){var c,d=a.length;for(c=0;c<d;c++)a[c]===b&&a.splice(c,1);return d!==a.length}function h(a){a=d.util.parseJSON(a);var h=a.data;if("c"===a.target)switch(a.type){case "open":r("opening","local",c);break;case "close":aa||(aa=!0,"aborted"===h.reason?l():h.heir===x?z():setTimeout(function(){z()},100));break;case "message":L(h,"messageReceived",200,b.transport);break;case "localMessage":ea(h)}}function e(){var a=(new RegExp("(?:^|; )("+encodeURIComponent(g)+
")=([^;]*)")).exec(document.cookie);if(a)return d.util.parseJSON(decodeURIComponent(a[2]))}var f,I,aa,g="atmosphere-"+b.url,k={storage:function(){function c(a){a.key===g&&a.newValue&&h(a.newValue)}if(d.util.storage){var e=window.localStorage,n=function(a){return d.util.parseJSON(e.getItem(g+"-"+a))};return{init:function(){var a=n("children").concat([x]);e.setItem(g+"-children",d.util.stringifyJSON(a));d.util.on(window,"storage",c);return n("opened")},signal:function(a,b){e.setItem(g,d.util.stringifyJSON({target:"p",
type:a,data:b}))},close:function(){var h=n("children");d.util.off(window,"storage",c);h&&a(h,b.id)&&e.setItem(g+"-children",d.util.stringifyJSON(h))}}}},windowref:function(){var b=window.open("",g.replace(/\W/g,""));if(b&&!b.closed&&b.callbacks)return{init:function(){b.callbacks.push(h);b.children.push(x);return b.opened},signal:function(a,c){!b.closed&&b.fire&&b.fire(d.util.stringifyJSON({target:"p",type:a,data:c}))},close:function(){aa||(a(b.callbacks,h),a(b.children,x))}}}};if((f=e())&&!(1E3<d.util.now()-
f.ts)&&(I=k.storage()||k.windowref()))return{open:function(){var a;V=setInterval(function(){var a=f;(f=e())&&a.ts!==f.ts||h(d.util.stringifyJSON({target:"c",type:"close",data:{reason:"error",heir:a.heir}}))},1E3);(a=I.init())&&setTimeout(function(){r("opening","local",b)},50);return a},send:function(a){I.signal("send",a)},localSend:function(a){I.signal("localSend",d.util.stringifyJSON({id:x,event:a}))},close:function(){E||(clearInterval(V),I.signal("close"),I.close())}}}function na(){function b(a){a=
d.util.parseJSON(a);var b=a.data;if("p"===a.target)switch(a.type){case "send":O(b);break;case "localSend":ea(b);break;case "close":l()}}function a(){document.cookie=Y+"="+encodeURIComponent(d.util.stringifyJSON({ts:d.util.now()+1,heir:(h.get("children")||[])[0]}))+"; path=/"}var h,e="atmosphere-"+c.url,f={storage:function(){function a(c){c.key===e&&c.newValue&&b(c.newValue)}if(d.util.storage){var c=window.localStorage;return{init:function(){d.util.on(window,"storage",a)},signal:function(a,b){c.setItem(e,
d.util.stringifyJSON({target:"c",type:a,data:b}))},get:function(a){return d.util.parseJSON(c.getItem(e+"-"+a))},set:function(a,b){c.setItem(e+"-"+a,d.util.stringifyJSON(b))},close:function(){d.util.off(window,"storage",a);c.removeItem(e);c.removeItem(e+"-opened");c.removeItem(e+"-children")}}}},windowref:function(){var a=e.replace(/\W/g,""),c=document.getElementById(a),h;c||(c=document.createElement("div"),c.id=a,c.style.display="none",c.innerHTML='<iframe name="'+a+'" />',document.body.appendChild(c));
h=c.firstChild.contentWindow;return{init:function(){h.callbacks=[b];h.fire=function(a){var b;for(b=0;b<h.callbacks.length;b++)h.callbacks[b](a)}},signal:function(a,b){!h.closed&&h.fire&&h.fire(d.util.stringifyJSON({target:"c",type:a,data:b}))},get:function(a){return h.closed?null:h[a]},set:function(a,b){h.closed||(h[a]=b)},close:function(){}}}};P=function(a){h.signal("message",a)};h=f.storage()||f.windowref();h.init();"debug"===c.logLevel&&d.util.debug("Installed StorageService "+h);h.set("children",
[]);null==h.get("opened")||h.get("opened")||h.set("opened",!1);Y=encodeURIComponent(e);a();V=setInterval(a,1E3);C=h}function r(b,a,h){c.shared&&"local"!==a&&na();null!=C&&C.set("opened",!0);h.close=function(){l()};0<y&&"re-connecting"===b?(h.isReopen=!0,oa(e)):null==e.error&&(e.request=h,h=e.state,e.state=b,b=e.transport,e.transport=a,a=e.responseBody,v(),e.responseBody=a,e.state=h,e.transport=b)}function fa(b){b.transport="jsonp";var a=c,h;null!=b&&"undefined"!==typeof b&&(a=b);B={open:function(){function f(){var c=
a.url;null!=a.dispatchUrl&&(c+=a.dispatchUrl);var d=a.data;a.attachHeadersAsQueryString&&(c=M(a),""!==d&&(c+="&X-Atmosphere-Post-Body="+encodeURIComponent(d)),d="");d=document.head||document.getElementsByTagName("head")[0]||document.documentElement;h=document.createElement("script");h.src=c+"&jsonpTransport="+g;h.clean=function(){h.clean=h.onerror=h.onload=h.onreadystatechange=null;h.parentNode&&h.parentNode.removeChild(h)};h.onload=h.onreadystatechange=function(){h.readyState&&!/loaded|complete/.test(h.readyState)||
h.clean()};h.onerror=function(){h.clean();a.lastIndex=0;a.openId&&clearTimeout(a.openId);a.heartbeatTimer&&clearTimeout(a.heartbeatTimer);a.reconnect&&y++<a.maxReconnectOnClose?(r("re-connecting",a.transport,a),H(B,a,b.reconnectInterval),a.openId=setTimeout(function(){Q(a)},a.reconnectInterval+1E3)):u(0,"maxReconnectOnClose reached")};d.insertBefore(h,d.firstChild)}var g="atmosphere"+ ++x;window[g]=function(b){if(a.reconnect)if(-1===a.maxRequest||a.requestCount++<a.maxRequest){a.executeCallbackBeforeReconnect||
H(B,a,a.pollingInterval);if(null!=b&&"string"!==typeof b)try{b=b.message}catch(h){}F(b,a,e)||L(e.responseBody,"messageReceived",200,a.transport);a.executeCallbackBeforeReconnect&&H(B,a,a.pollingInterval)}else d.util.log(c.logLevel,["JSONP reconnect maximum try reached "+c.requestCount]),u(0,"maxRequest reached")};setTimeout(function(){f()},50)},abort:function(){h&&h.clean&&h.clean()}};B.open()}function pa(b){return null!=c.webSocketImpl?c.webSocketImpl:window.WebSocket?new WebSocket(b):new MozWebSocket(b)}
function p(b){e.transport="sse";var a=M(c);"debug"===c.logLevel&&(d.util.debug("Invoking executeSSE"),d.util.debug("Using URL: "+a));if(b&&!c.reconnect)null!=w&&m();else{try{w=new EventSource(a,{withCredentials:c.withCredentials})}catch(h){u(0,h);K("SSE failed. Downgrading to fallback transport and resending");return}0<c.connectTimeout&&(c.id=setTimeout(function(){b||m()},c.connectTimeout));w.onopen=function(a){G(c);"debug"===c.logLevel&&d.util.debug("SSE successfully opened");c.enableProtocol?c.isReopen&&
(c.isReopen=!1,r("re-opening",c.transport,c)):b?r("re-opening","sse",c):r("opening","sse",c);b=!0;"POST"===c.method&&(e.state="messageReceived",w.send(c.data))};w.onmessage=function(a){G(c);!c.enableXDR&&a.origin&&a.origin!==window.location.protocol+"//"+window.location.host?d.util.log(c.logLevel,["Origin was not "+window.location.protocol+"//"+window.location.host]):(e.state="messageReceived",e.status=200,a=a.data,F(a,c,e)||(v(),e.responseBody="",e.messages=[]))};w.onerror=function(a){clearTimeout(c.id);
c.heartbeatTimer&&clearTimeout(c.heartbeatTimer);e.closedByClientTimeout||((R(b),m(),E)?d.util.log(c.logLevel,["SSE closed normally"]):b?c.reconnect&&"sse"===e.transport&&(y++<c.maxReconnectOnClose?(r("re-connecting",c.transport,c),0<c.reconnectInterval?c.reconnectId=setTimeout(function(){p(!0)},c.reconnectInterval):p(!0),e.responseBody="",e.messages=[]):(d.util.log(c.logLevel,["SSE reconnect maximum try reached "+y]),u(0,"maxReconnectOnClose reached"))):K("SSE failed. Downgrading to fallback transport and resending"))}}}
function $(b){e.transport="websocket";var a=M(c,d.util.getAbsoluteURL(c.webSocketUrl||c.url)).replace(/^http/,"ws");"debug"===c.logLevel&&(d.util.debug("Invoking executeWebSocket"),d.util.debug("Using URL: "+a));if(b&&!c.reconnect)null!=s&&m();else if(s=pa(a),null!=c.webSocketBinaryType&&(s.binaryType=c.webSocketBinaryType),0<c.connectTimeout&&(c.id=setTimeout(function(){if(!b){s.onclose({code:1002,reason:"",wasClean:!1});try{m()}catch(a){}}},c.connectTimeout)),s.onopen=function(a){G(c);"debug"===
c.logLevel&&d.util.debug("Websocket successfully opened");a=b;null!=s&&(s.canSendMessage=!0);c.enableProtocol||(b=!0,a?r("re-opening","websocket",c):r("opening","websocket",c));null!=s&&"POST"===c.method&&(e.state="messageReceived",s.send(c.data))},s.onmessage=function(a){G(c);c.enableProtocol&&(b=!0);e.state="messageReceived";e.status=200;a=a.data;"string"===typeof a?F(a,c,e)||(v(),e.responseBody="",e.messages=[]):(a=ga(c,a),""!==a&&(e.responseBody=a,v(),e.responseBody=null))},s.onerror=function(a){clearTimeout(c.id);
c.heartbeatTimer&&clearTimeout(c.heartbeatTimer)},s.onclose=function(a){clearTimeout(c.id);if("closed"!==e.state){var f=a.reason;if(""===f)switch(a.code){case 1E3:f="Normal closure; the connection successfully completed whatever purpose for which it was created.";break;case 1001:f="The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection.";break;case 1002:f="The endpoint is terminating the connection due to a protocol error.";
break;case 1003:f="The connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data).";break;case 1004:f="The endpoint is terminating the connection because a data frame was received that is too large.";break;case 1005:f="Unknown: no status code was provided even though one was expected.";break;case 1006:f="Connection was closed abnormally (that is, with no close frame being sent)."}"warn"===c.logLevel&&(d.util.warn("Websocket closed, reason: "+
f),d.util.warn("Websocket closed, wasClean: "+a.wasClean));e.closedByClientTimeout||((R(b),e.state="closed",E)?d.util.log(c.logLevel,["Websocket closed normally"]):b?c.reconnect&&"websocket"===e.transport&&1001!==a.code&&(m(),y++<c.maxReconnectOnClose?(r("re-connecting",c.transport,c),0<c.reconnectInterval?c.reconnectId=setTimeout(function(){e.responseBody="";e.messages=[];$(!0)},c.reconnectInterval):(e.responseBody="",e.messages=[],$(!0))):(d.util.log(c.logLevel,["Websocket reconnect maximum try reached "+
c.requestCount]),"warn"===c.logLevel&&d.util.warn("Websocket error, reason: "+a.reason),u(0,"maxReconnectOnClose reached"))):K("Websocket failed. Downgrading to Comet and resending"))}},-1<navigator.userAgent.toLowerCase().indexOf("android")&&void 0===s.url)s.onclose({reason:"Android 4.1 does not support websockets.",wasClean:!1})}function ga(b,a){var h=a;if("polling"===b.transport)return h;if(0!==d.util.trim(a).length&&b.enableProtocol&&b.firstMessage){var e=b.trackMessageLength?1:0,f=a.split(b.messageDelimiter);
if(f.length<=e+1)return h;b.firstMessage=!1;b.uuid=d.util.trim(f[e]);f.length<=e+2&&d.util.log("error",["Protocol data not sent by the server. If you enable protocol on client side, be sure to install JavascriptProtocol interceptor on server side.Also note that atmosphere-runtime 2.2+ should be used."]);var g=parseInt(d.util.trim(f[e+1]),10),k=f[e+2];if(!isNaN(g)&&0<g){var l=function(){O(k);b.heartbeatTimer=setTimeout(l,g)};b.heartbeatTimer=setTimeout(l,g)}"long-polling"!==b.transport&&Q(b);U=b.uuid;
h="";e=b.trackMessageLength?4:3;if(f.length>e+1)for(;e<f.length;e++)h+=f[e],e+1!==f.length&&(h+=b.messageDelimiter);0!==b.ackInterval&&setTimeout(function(){O("...ACK...")},b.ackInterval)}else b.enableProtocol&&b.firstMessage&&d.util.browser.msie&&10>+d.util.browser.version.split(".")[0]?d.util.log(c.logLevel,["Receiving unexpected data from IE"]):Q(b);return h}function G(b){clearTimeout(b.id);0<b.timeout&&"polling"!==b.transport&&(b.id=setTimeout(function(){e.closedByClientTimeout=!0;e.state="closedByClient";
e.responseBody="";e.status=408;e.messages=[];v();k();m()},b.timeout))}function u(b,a){m();clearTimeout(c.id);e.state="error";e.reasonPhrase=a;e.responseBody="";e.status=b;e.messages=[];v()}function F(b,a,c){b=ga(a,b);if(0===b.length)return!0;c.responseBody=b;if(a.trackMessageLength){b=c.partialMessage+b;for(var d=[],e=b.indexOf(a.messageDelimiter);-1!==e;){var f=b.substring(0,e),g=+f;if(isNaN(g))throw Error('message length "'+f+'" is not a number');e+=a.messageDelimiter.length;e+g>b.length?e=-1:(d.push(b.substring(e,
e+g)),b=b.substring(e+g,b.length),e=b.indexOf(a.messageDelimiter))}c.partialMessage=b;if(0!==d.length)c.responseBody=d.join(a.messageDelimiter),c.messages=d;else return c.responseBody="",c.messages=[],!0}else c.responseBody=b;return!1}function K(b){d.util.log(c.logLevel,[b]);if("undefined"!==typeof c.onTransportFailure)c.onTransportFailure(b,c);else if("undefined"!==typeof d.util.onTransportFailure)d.util.onTransportFailure(b,c);c.transport=c.fallbackTransport;b=-1===c.connectTimeout?0:c.connectTimeout;
c.reconnect&&"none"!==c.transport||null==c.transport?(c.method=c.fallbackMethod,e.transport=c.fallbackTransport,c.fallbackTransport="none",0<b?c.reconnectId=setTimeout(function(){z()},b):z()):u(500,"Unable to reconnect with fallback transport")}function M(b,a){var h=c;null!=b&&"undefined"!==typeof b&&(h=b);null==a&&(a=h.url);if(!h.attachHeadersAsQueryString||-1!==a.indexOf("X-Atmosphere-Framework"))return a;a+=-1!==a.indexOf("?")?"&":"?";a+="X-Atmosphere-tracking-id="+h.uuid;a+="&X-Atmosphere-Framework=2.2.2-javascript";
a+="&X-Atmosphere-Transport="+h.transport;h.trackMessageLength&&(a+="&X-Atmosphere-TrackMessageSize=true");null!==h.heartbeat&&null!==h.heartbeat.server&&(a+="&X-Heartbeat-Server="+h.heartbeat.server);""!==h.contentType&&(a+="&Content-Type="+("websocket"===h.transport?h.contentType:encodeURIComponent(h.contentType)));h.enableProtocol&&(a+="&X-atmo-protocol=true");d.util.each(h.headers,function(c,f){var g=d.util.isFunction(f)?f.call(this,h,b,e):f;null!=g&&(a+="&"+encodeURIComponent(c)+"="+encodeURIComponent(g))});
return a}function Q(b){b.isOpen?b.isReopen&&(b.isReopen=!1,r("re-opening",b.transport,b)):(b.isOpen=!0,r("opening",b.transport,b))}function N(b){var a=c;if(null!=b||"undefined"!==typeof b)a=b;a.lastIndex=0;a.readyState=0;if("jsonp"===a.transport||a.enableXDR&&d.util.checkCORSSupport())fa(a);else{if(d.util.browser.msie&&10>+d.util.browser.version.split(".")[0]){if("streaming"===a.transport){a.enableXDR&&window.XDomainRequest?S(a):T(a);return}if(a.enableXDR&&window.XDomainRequest){S(a);return}}var f=
function(){a.lastIndex=0;a.reconnect&&y++<a.maxReconnectOnClose?(r("re-connecting",b.transport,b),H(n,a,b.reconnectInterval)):u(0,"maxReconnectOnClose reached")};if(a.force||a.reconnect&&(-1===a.maxRequest||a.requestCount++<a.maxRequest)){a.force=!1;var n=d.util.xhr();n.hasData=!1;X(n,a,!0);a.suspend&&(J=n);"polling"!==a.transport&&(e.transport=a.transport,n.onabort=function(){R(!0)},n.onerror=function(){e.error=!0;e.ffTryingReconnect=!0;try{e.status=XMLHttpRequest.status}catch(a){e.status=500}e.status||
(e.status=500);e.errorHandled||(m(),f())});n.onreadystatechange=function(){if(!E){e.error=null;var k=!1,l=!1;if("streaming"===a.transport&&2<a.readyState&&4===n.readyState)m(),f();else{a.readyState=n.readyState;"streaming"===a.transport&&3<=n.readyState?l=!0:"long-polling"===a.transport&&4===n.readyState&&(l=!0);G(c);if("polling"!==a.transport){var r=200;4===n.readyState&&(r=1E3<n.status?0:n.status);if(300<=r||0===r){e.errorHandled=!0;m();f();return}a.enableProtocol&&b.firstMessage||2!==n.readyState||
(d.util.browser.mozilla&&e.ffTryingReconnect?(e.ffTryingReconnect=!1,setTimeout(function(){e.ffTryingReconnect||Q(a)},500)):Q(a))}else 4===n.readyState&&(l=!0);if(l)if(l=n.responseText,e.errorHandled=!1,0===d.util.trim(l).length&&"long-polling"===a.transport)n.hasData?n.hasData=!1:(e.errorHandled=!0,m(),f());else{n.hasData=!0;ba(n,c);if("streaming"===a.transport)if(d.util.browser.opera)d.util.iterate(function(){if(500!==e.status&&n.responseText.length>a.lastIndex){try{e.status=n.status,e.headers=
d.util.parseHeaders(n.getAllResponseHeaders()),ba(n,c)}catch(b){e.status=404}G(c);e.state="messageReceived";var f=n.responseText.substring(a.lastIndex);a.lastIndex=n.responseText.length;(k=F(f,a,e))||v();g(n,a)&&ha(n,a)}else if(400<e.status)return a.lastIndex=n.responseText.length,!1},0);else{if(r=l.substring(a.lastIndex,l.length),k=F(r,a,e),a.lastIndex=l.length,k)return}else k=F(l,a,e);l=g(n,a);try{e.status=n.status,e.headers=d.util.parseHeaders(n.getAllResponseHeaders()),ba(n,a)}catch(p){e.status=
404}e.state=a.suspend?0===e.status?"closed":"messageReceived":"messagePublished";(r=!l&&"streaming"!==b.transport&&"polling"!==b.transport)&&!a.executeCallbackBeforeReconnect&&H(n,a,a.pollingInterval);0===e.responseBody.length||k||v();r&&a.executeCallbackBeforeReconnect&&H(n,a,a.pollingInterval);l&&ha(n,a)}}}};try{n.send(a.data),Z=!0}catch(k){d.util.log(a.logLevel,["Unable to connect to "+a.url]),u(0,k)}}else"debug"===a.logLevel&&d.util.log(a.logLevel,["Max re-connection reached."]),u(0,"maxRequest reached")}}
function ha(b,a){l();E=!1;H(b,a,500)}function X(b,a,f){var g=a.url;null!=a.dispatchUrl&&"POST"===a.method&&(g+=a.dispatchUrl);g=M(a,g);g=d.util.prepareURL(g);f&&(b.open(a.method,g,a.async),0<a.connectTimeout&&(a.id=setTimeout(function(){0===a.requestCount&&(m(),L("Connect timeout","closed",200,a.transport))},a.connectTimeout)));c.withCredentials&&"websocket"!==c.transport&&"withCredentials"in b&&(b.withCredentials=!0);c.dropHeaders||(b.setRequestHeader("X-Atmosphere-Framework",d.util.version),b.setRequestHeader("X-Atmosphere-Transport",
a.transport),null!==b.heartbeat&&null!==b.heartbeat.server&&b.setRequestHeader("X-Heartbeat-Server",b.heartbeat.server),a.trackMessageLength&&b.setRequestHeader("X-Atmosphere-TrackMessageSize","true"),b.setRequestHeader("X-Atmosphere-tracking-id",a.uuid),d.util.each(a.headers,function(c,g){var k=d.util.isFunction(g)?g.call(this,b,a,f,e):g;null!=k&&b.setRequestHeader(c,k)}));""!==a.contentType&&b.setRequestHeader("Content-Type",a.contentType)}function H(b,a,d){if(a.reconnect||a.suspend&&Z){var f=0;
b&&1<b.readyState&&(f=1E3<b.status?0:b.status);e.status=0===f?204:f;e.reason=0===f?"Server resumed the connection or down.":"OK";clearTimeout(a.id);a.reconnectId&&(clearTimeout(a.reconnectId),delete a.reconnectId);0<d?c.reconnectId=setTimeout(function(){N(a)},d):N(a)}}function oa(b){b.state="re-connecting";ia(b)}function S(b){"polling"!==b.transport?(A=ja(b),A.open()):ja(b).open()}function ja(b){var a=c;null!=b&&"undefined"!==typeof b&&(a=b);var f=a.transport,g=0,k=new window.XDomainRequest,l=function(){"long-polling"===
a.transport&&a.reconnect&&(-1===a.maxRequest||a.requestCount++<a.maxRequest)&&(k.status=200,S(a))},p=a.rewriteURL||function(a){var b=/(?:^|;\s*)(JSESSIONID|PHPSESSID)=([^;]*)/.exec(document.cookie);switch(b&&b[1]){case "JSESSIONID":return a.replace(/;jsessionid=[^\?]*|(\?)|$/,";jsessionid="+b[2]+"$1");case "PHPSESSID":return a.replace(/\?PHPSESSID=[^&]*&?|\?|$/,"?PHPSESSID="+b[2]+"&").replace(/&$/,"")}return a};k.onprogress=function(){clearTimeout(a.id);var b=k.responseText,b=b.substring(g);g+=b.length;
if("polling"!==f){G(a);var c=F(b,a,e);if("long-polling"!==f||0!==d.util.trim(b).length)a.executeCallbackBeforeReconnect&&l(),c||L(e.responseBody,"messageReceived",200,f),a.executeCallbackBeforeReconnect||l()}};k.onerror=function(){"polling"!==a.transport&&(m(),y++<a.maxReconnectOnClose?0<a.reconnectInterval?a.reconnectId=setTimeout(function(){r("re-connecting",b.transport,b);S(a)},a.reconnectInterval):(r("re-connecting",b.transport,b),S(a)):u(0,"maxReconnectOnClose reached"))};k.onload=function(){};
return{open:function(){var b=a.url;null!=a.dispatchUrl&&(b+=a.dispatchUrl);b=M(a,b);k.open(a.method,p(b));"GET"===a.method?k.send():k.send(a.data);0<a.connectTimeout&&(a.id=setTimeout(function(){0===a.requestCount&&(m(),L("Connect timeout","closed",200,a.transport))},a.connectTimeout))},close:function(){k.abort()}}}function T(b){A=qa(b);A.open()}function qa(b){var a=c;null!=b&&"undefined"!==typeof b&&(a=b);var f,g=new window.ActiveXObject("htmlfile");g.open();g.close();var k=a.url;null!=a.dispatchUrl&&
(k+=a.dispatchUrl);"polling"!==a.transport&&(e.transport=a.transport);return{open:function(){var b=g.createElement("iframe");k=M(a);""!==a.data&&(k+="&X-Atmosphere-Post-Body="+encodeURIComponent(a.data));k=d.util.prepareURL(k);b.src=k;g.body.appendChild(b);var l=b.contentDocument||b.contentWindow.document;f=d.util.iterate(function(){try{if(l.firstChild){var b=l.body?l.body.lastChild:l,k=function(){var a=b.cloneNode(!0);a.appendChild(l.createTextNode("."));a=a.innerText;return a=a.substring(0,a.length-
1)};if(!l.body||!l.body.firstChild||"pre"!==l.body.firstChild.nodeName.toLowerCase()){var m=l.head||l.getElementsByTagName("head")[0]||l.documentElement||l,p=l.createElement("script");p.text="document.write('<plaintext>')";m.insertBefore(p,m.firstChild);m.removeChild(p);b=l.body.lastChild}a.closed&&(a.isReopen=!0);f=d.util.iterate(function(){var d=k();if(d.length>a.lastIndex){G(c);e.status=200;e.error=null;b.innerText="";if(F(d,a,e))return"";L(e.responseBody,"messageReceived",200,a.transport)}a.lastIndex=
0;if("complete"===l.readyState)return R(!0),r("re-connecting",a.transport,a),0<a.reconnectInterval?a.reconnectId=setTimeout(function(){T(a)},a.reconnectInterval):T(a),!1},null);return!1}}catch(z){return e.error=!0,r("re-connecting",a.transport,a),y++<a.maxReconnectOnClose?0<a.reconnectInterval?a.reconnectId=setTimeout(function(){T(a)},a.reconnectInterval):T(a):u(0,"maxReconnectOnClose reached"),g.execCommand("Stop"),g.close(),!1}})},close:function(){f&&f();g.execCommand("Stop");R(!0)}}}function O(b){null!=
t?t.send(b):null!=J||null!=w?W(b):null!=A?c.enableXDR&&d.util.checkCORSSupport()?(b=ca(b),b.reconnect=!1,fa(b)):W(b):null!=B?W(b):null!=s?ra(b):(u(0,"No suspended connection available"),d.util.error("No suspended connection available. Make sure atmosphere.subscribe has been called and request.onOpen invoked before invoking this method"))}function ma(b,a){a||(a=ca(b));a.transport="polling";a.method="GET";a.async=!1;a.withCredentials=!1;a.reconnect=!1;a.force=!0;a.suspend=!1;a.timeout=1E3;N(a)}function W(b){b=
ca(b);N(b)}function ka(b){var a=b;"object"===typeof a&&(a=b.data);return a}function ca(b){var a=ka(b),a={connected:!1,timeout:6E4,method:"POST",url:c.url,contentType:c.contentType,headers:c.headers,reconnect:!0,callback:null,data:a,suspend:!1,maxRequest:-1,logLevel:"info",requestCount:0,withCredentials:c.withCredentials,async:c.async,transport:"polling",isOpen:!0,attachHeadersAsQueryString:!0,enableXDR:c.enableXDR,uuid:c.uuid,dispatchUrl:c.dispatchUrl,enableProtocol:!1,messageDelimiter:"|",trackMessageLength:c.trackMessageLength,
maxReconnectOnClose:c.maxReconnectOnClose,heartbeatTimer:c.heartbeatTimer,heartbeat:c.heartbeat};"object"===typeof b&&(a=d.util.extend(a,b));return a}function ra(b){var a=d.util.isBinary(b)?b:ka(b),f;try{f=null!=c.dispatchUrl?c.webSocketPathDelimiter+c.dispatchUrl+c.webSocketPathDelimiter+a:a,s.canSendMessage?s.send(f):d.util.error("WebSocket not connected.")}catch(e){s.onclose=function(a){},m(),K("Websocket failed. Downgrading to Comet and resending "+b),W(b)}}function ea(b){b=d.util.parseJSON(b);
if(b.id!==x)if("undefined"!==typeof c.onLocalMessage)c.onLocalMessage(b.event);else if("undefined"!==typeof d.util.onLocalMessage)d.util.onLocalMessage(b.event)}function L(b,a,c,d){e.responseBody=b;e.transport=d;e.status=c;e.state=a;v()}function ba(b,a){if(a.readResponsesHeaders)try{var c=b.getResponseHeader("X-Atmosphere-tracking-id");c&&null!=c&&(a.uuid=c.split(" ").pop())}catch(d){}else a.enableProtocol||(a.uuid=x)}function ia(b){la(b,c);la(b,d.util)}function la(b,a){switch(b.state){case "messageReceived":y=
0;if("undefined"!==typeof a.onMessage)a.onMessage(b);if("undefined"!==typeof a.onmessage)a.onmessage(b);break;case "error":if("undefined"!==typeof a.onError)a.onError(b);if("undefined"!==typeof a.onerror)a.onerror(b);break;case "opening":delete c.closed;if("undefined"!==typeof a.onOpen)a.onOpen(b);if("undefined"!==typeof a.onopen)a.onopen(b);break;case "messagePublished":if("undefined"!==typeof a.onMessagePublished)a.onMessagePublished(b);break;case "re-connecting":if("undefined"!==typeof a.onReconnect)a.onReconnect(c,
b);break;case "closedByClient":if("undefined"!==typeof a.onClientTimeout)a.onClientTimeout(c);break;case "re-opening":delete c.closed;if("undefined"!==typeof a.onReopen)a.onReopen(c,b);break;case "fail-to-reconnect":if("undefined"!==typeof a.onFailureToReconnect)a.onFailureToReconnect(c,b);break;case "unsubscribe":case "closed":if("undefined"===typeof c.closed||!c.closed){if("undefined"!==typeof a.onClose)a.onClose(b);if("undefined"!==typeof a.onclose)a.onclose(b)}c.closed=!0}}function R(b){"closed"!==
e.state&&(e.state="closed",e.responseBody="",e.messages=[],e.status=b?200:501,v())}function v(){var b=function(a,b){b(e)};null==t&&null!=P&&P(e.responseBody);c.reconnect=c.mrequest;for(var a="string"===typeof e.responseBody,f=a&&c.trackMessageLength?0<e.messages.length?e.messages:[""]:Array(e.responseBody),g=0;g<f.length;g++)if(!(1<f.length&&0===f[g].length)&&(e.responseBody=a?d.util.trim(f[g]):f[g],null==t&&null!=P&&P(e.responseBody),0!==e.responseBody.length||"messageReceived"!==e.state)){ia(e);
if(0<D.length){"debug"===c.logLevel&&d.util.debug("Invoking "+D.length+" global callbacks: "+e.state);try{d.util.each(D,b)}catch(k){d.util.log(c.logLevel,["Callback exception"+k])}}if("function"===typeof c.callback){"debug"===c.logLevel&&d.util.debug("Invoking request callbacks");try{c.callback(e)}catch(l){d.util.log(c.logLevel,["Callback exception"+l])}}}}var c={timeout:3E5,method:"GET",headers:{},contentType:"",callback:null,url:"",data:"",suspend:!0,maxRequest:-1,reconnect:!0,maxStreamingLength:1E7,
lastIndex:0,logLevel:"info",requestCount:0,fallbackMethod:"GET",fallbackTransport:"streaming",transport:"long-polling",webSocketImpl:null,webSocketBinaryType:null,dispatchUrl:null,webSocketPathDelimiter:"@@",enableXDR:!1,rewriteURL:!1,attachHeadersAsQueryString:!0,executeCallbackBeforeReconnect:!1,readyState:0,withCredentials:!1,trackMessageLength:!1,messageDelimiter:"|",connectTimeout:-1,reconnectInterval:0,dropHeaders:!0,uuid:0,async:!0,shared:!1,readResponsesHeaders:!1,maxReconnectOnClose:5,enableProtocol:!0,
pollingInterval:0,heartbeat:{client:null,server:null},ackInterval:0,onError:function(b){},onClose:function(b){},onOpen:function(b){},onMessage:function(b){},onReopen:function(b,a){},onReconnect:function(b,a){},onMessagePublished:function(b){},onTransportFailure:function(b,a){},onLocalMessage:function(b){},onFailureToReconnect:function(b,a){},onClientTimeout:function(b){}},e={status:200,reasonPhrase:"OK",responseBody:"",messages:[],headers:[],state:"messageReceived",transport:"polling",error:null,
request:null,partialMessage:"",errorHandled:!1,closedByClientTimeout:!1,ffTryingReconnect:!1},s=null,w=null,J=null,A=null,B=null,Z=!0,y=0,E=!1,P=null,C,t=null,x=d.util.now(),V,Y;da(f);this.subscribe=function(b){da(b);z()};this.execute=function(){z()};this.close=function(){l()};this.disconnect=function(){k()};this.getUrl=function(){return c.url};this.push=function(b,a){if(null!=a){var d=c.dispatchUrl;c.dispatchUrl=a;O(b);c.dispatchUrl=d}else O(b)};this.getUUID=function(){return c.uuid};this.pushLocal=
function(b){if(0!==b.length)try{t?t.localSend(b):C&&C.signal("localMessage",d.util.stringifyJSON({id:x,event:b}))}catch(a){d.util.error(a)}};this.enableProtocol=function(b){return c.enableProtocol};this.request=c;this.response=e},subscribe:function(f,g,k){"function"===typeof g&&d.addCallback(g);"string"!==typeof f?k=f:k.url=f;U="undefined"!==typeof k&&"undefined"!==typeof k.uuid?k.uuid:0;f=new d.AtmosphereRequest(k);f.execute();return q[q.length]=f},unsubscribe:function(){if(0<q.length)for(var d=
[].concat(q),g=0;g<d.length;g++){var k=d[g];k.close();clearTimeout(k.response.request.id);k.heartbeatTimer&&clearTimeout(k.heartbeatTimer)}q=[];D=[]},unsubscribeUrl:function(d){var g=-1;if(0<q.length)for(var k=0;k<q.length;k++){var l=q[k];if(l.getUrl()===d){l.close();clearTimeout(l.response.request.id);l.heartbeatTimer&&clearTimeout(l.heartbeatTimer);g=k;break}}0<=g&&q.splice(g,1)},addCallback:function(f){-1===d.util.inArray(f,D)&&D.push(f)},removeCallback:function(f){f=d.util.inArray(f,D);-1!==f&&
D.splice(f,1)},util:{browser:{},parseHeaders:function(d){for(var g,k=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,l={};g=k.exec(d);)l[g[1]]=g[2];return l},now:function(){return(new Date).getTime()},isArray:function(d){return"[object Array]"===Object.prototype.toString.call(d)},inArray:function(d,g){if(!Array.prototype.indexOf){for(var k=g.length,l=0;l<k;++l)if(g[l]===d)return l;return-1}return g.indexOf(d)},isBinary:function(d){return/^\[object\s(?:Blob|ArrayBuffer|.+Array)\]$/.test(Object.prototype.toString.call(d))},
isFunction:function(d){return"[object Function]"===Object.prototype.toString.call(d)},getAbsoluteURL:function(d){var g=document.createElement("div");g.innerHTML='<a href="'+d+'"/>';return encodeURI(decodeURI(g.firstChild.href))},prepareURL:function(f){var g=d.util.now(),k=f.replace(/([?&])_=[^&]*/,"$1_="+g);return k+(k===f?(/\?/.test(f)?"&":"?")+"_="+g:"")},trim:function(d){return String.prototype.trim?d.toString().trim():d.toString().replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ")},
param:function(f){function g(f,g){g=d.util.isFunction(g)?g():null==g?"":g;m.push(encodeURIComponent(f)+"="+encodeURIComponent(g))}function k(f,l){var m;if(d.util.isArray(l))d.util.each(l,function(d,l){/\[\]$/.test(f)?g(f,l):k(f+"["+("object"===typeof l?d:"")+"]",l)});else if("[object Object]"===Object.prototype.toString.call(l))for(m in l)k(f+"["+m+"]",l[m]);else g(f,l)}var l,m=[];for(l in f)k(l,f[l]);return m.join("&").replace(/%20/g,"+")},storage:function(){try{return!(!window.localStorage||!window.StorageEvent)}catch(d){return!1}},
iterate:function(d,g){var k;g=g||0;(function m(){k=setTimeout(function(){!1!==d()&&m()},g)})();return function(){clearTimeout(k)}},each:function(f,g,k){if(f){var l,m=0,q=f.length;l=d.util.isArray(f);if(k)if(l)for(;m<q&&(l=g.apply(f[m],k),!1!==l);m++);else for(m in f){if(l=g.apply(f[m],k),!1===l)break}else if(l)for(;m<q&&(l=g.call(f[m],m,f[m]),!1!==l);m++);else for(m in f)if(l=g.call(f[m],m,f[m]),!1===l)break;return f}},extend:function(d){var g,k,l;for(g=1;g<arguments.length;g++)if(null!=(k=arguments[g]))for(l in k)d[l]=
k[l];return d},on:function(d,g,k){d.addEventListener?d.addEventListener(g,k,!1):d.attachEvent&&d.attachEvent("on"+g,k)},off:function(d,g,k){d.removeEventListener?d.removeEventListener(g,k,!1):d.detachEvent&&d.detachEvent("on"+g,k)},log:function(d,g){if(window.console){var k=window.console[d];"function"===typeof k&&k.apply(window.console,g)}},warn:function(){d.util.log("warn",arguments)},info:function(){d.util.log("info",arguments)},debug:function(){d.util.log("debug",arguments)},error:function(){d.util.log("error",
arguments)},xhr:function(){try{return new window.XMLHttpRequest}catch(d){try{return new window.ActiveXObject("Microsoft.XMLHTTP")}catch(g){}}},parseJSON:function(d){return d?window.JSON&&window.JSON.parse?window.JSON.parse(d):(new Function("return "+d))():null},stringifyJSON:function(d){function g(d){return'"'+d.replace(l,function(d){var f=m[d];return"string"===typeof f?f:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"'}function k(d){return 10>d?"0"+d:d}var l=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return window.JSON&&window.JSON.stringify?window.JSON.stringify(d):function z(d,f){var l,m,q,p=f[d];q=typeof p;p&&"object"===typeof p&&"function"===typeof p.toJSON&&(p=p.toJSON(d),q=typeof p);switch(q){case "string":return g(p);case "number":return isFinite(p)?String(p):"null";case "boolean":return String(p);case "object":if(!p)return"null";switch(Object.prototype.toString.call(p)){case "[object Date]":return isFinite(p.valueOf())?
'"'+p.getUTCFullYear()+"-"+k(p.getUTCMonth()+1)+"-"+k(p.getUTCDate())+"T"+k(p.getUTCHours())+":"+k(p.getUTCMinutes())+":"+k(p.getUTCSeconds())+'Z"':"null";case "[object Array]":m=p.length;q=[];for(l=0;l<m;l++)q.push(z(l,p)||"null");return"["+q.join(",")+"]";default:q=[];for(l in p)X.call(p,l)&&(m=z(l,p))&&q.push(g(l)+":"+m);return"{"+q.join(",")+"}"}}}("",{"":d})},checkCORSSupport:function(){return d.util.browser.msie&&!window.XDomainRequest&&11>+d.util.browser.version.split(".")[0]||d.util.browser.opera&&
12>+d.util.browser.version.split(".")||"KreaTVWebKit/531"===d.util.trim(navigator.userAgent).slice(0,16)||"kreatel"===d.util.trim(navigator.userAgent).slice(-7).toLowerCase()?!0:-1<navigator.userAgent.toLowerCase().indexOf("android")?!0:!1}}};d.util.now();(function(){var f=navigator.userAgent.toLowerCase(),f=/(chrome)[ \/]([\w.]+)/.exec(f)||/(webkit)[ \/]([\w.]+)/.exec(f)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(f)||/(msie) ([\w.]+)/.exec(f)||/(trident)(?:.*? rv:([\w.]+)|)/.exec(f)||0>f.indexOf("compatible")&&
/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(f)||[];d.util.browser[f[1]||""]=!0;d.util.browser.version=f[2]||"0";d.util.browser.trident&&(d.util.browser.msie=!0);if(d.util.browser.msie||d.util.browser.mozilla&&1===+d.util.browser.version.split(".")[0])d.util.storage=!1})();d.util.on(window,"unload",function(f){d.unsubscribe()});d.util.on(window,"keypress",function(d){(27===d.charCode||27===d.keyCode)&&d.preventDefault&&d.preventDefault()});d.util.on(window,"offline",function(){d.unsubscribe()});return d});