forked from lytup/atmosphere-jquery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.atmosphere.min.js
100 lines (100 loc) · 36.8 KB
/
jquery.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
96
97
98
99
100
/*
* 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
*
* Requires
* - jQuery 2.0.3 http://jquery.com/
*
* 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){"function"===typeof define&&define.amd?define(["jquery"],d):d(jQuery)})(function(d){d(window).bind("unload.atmosphere",function(){d.atmosphere.unsubscribe()});d(window).bind("offline",function(){d.atmosphere.offline=!0;for(var k=[].concat(d.atmosphere.requests),l=0;l<k.length;l++){var g=k[l];g.close();clearTimeout(g.response.request.id);g.heartbeatTimer&&clearTimeout(g.heartbeatTimer)}});d(window).bind("online",function(){d.atmosphere.offline=!1;if(0<d.atmosphere.requests.length)for(var k=
0;k<d.atmosphere.requests.length;k++)d.atmosphere.requests[k].init(),d.atmosphere.requests[k].execute()});d(window).keypress(function(d){27===d.keyCode&&d.preventDefault()});var ka=function(d){for(var l,g=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,p={};l=g.exec(d);)p[l[1]]=l[2];return p};d.atmosphere={version:"2.2.6-jquery",uuid:0,offline:!1,requests:[],callbacks:[],onError:function(d){},onClose:function(d){},onOpen:function(d){},onMessage:function(d){},onReconnect:function(d,l){},onMessagePublished:function(d){},
onTransportFailure:function(d,l){},onLocalMessage:function(d){},onClientTimeout:function(d){},onFailureToReconnect:function(d,l){},WebsocketApiAdapter:function(d){var l,g;d.onMessage=function(d){g.onmessage({data:d.responseBody})};d.onMessagePublished=function(d){g.onmessage({data:d.responseBody})};d.onOpen=function(d){g.onopen(d)};g={close:function(){l.close()},send:function(d){l.push(d)},onmessage:function(d){},onopen:function(d){},onclose:function(d){},onerror:function(d){}};l=new $.atmosphere.subscribe(d);
return g},AtmosphereRequest:function(k){function l(){ca=!0;K=!1;E=0;G=O=z=n=null}function g(c){return"debug"==c?"debug"===e.logLevel:"info"==c?"info"===e.logLevel||"debug"===e.logLevel:"warn"==c?"warn"===e.logLevel||"info"===e.logLevel||"debug"===e.logLevel:"error"==c?"error"===e.logLevel||"warn"===e.logLevel||"info"===e.logLevel||"debug"===e.logLevel:!1}function p(c){r();l();e=d.extend(e,c);e.mrequest=e.reconnect;e.reconnect||(e.reconnect=!0)}function u(){if(e.shared){x=F(e);if(null!=x&&(g("debug")&&
d.atmosphere.debug("Storage service available. All communication will be local"),x.open(e)))return;g("debug")&&d.atmosphere.debug("No Storage service available.");x=null}e.firstMessage=0==d.atmosphere.uuid?!0:!1;e.isOpen=!1;e.ctime=d.now();0===e.uuid&&(e.uuid=d.atmosphere.uuid);e.closedByClientTimeout=!1;"websocket"!==e.transport&&"sse"!==e.transport?Y(e):"websocket"===e.transport?null!=e.webSocketImpl||window.WebSocket||window.MozWebSocket?da(!1):P("Websocket is not supported, using request.fallbackTransport ("+
e.fallbackTransport+")"):"sse"===e.transport&&(window.EventSource?ea(!1):P("Server Side Events(SSE) is not supported, using request.fallbackTransport ("+e.fallbackTransport+")"))}function F(c){function a(a){a=d.parseJSON(a);var h=a.data;if("c"===a.target)switch(a.type){case "open":t("opening","local",e);break;case "close":fa||(fa=!0,"aborted"===h.reason?Q():h.heir===L?u():setTimeout(function(){u()},100));break;case "message":M(h,"messageReceived",200,c.transport);break;case "localMessage":la(h)}}
function f(){var a=(new RegExp("(?:^|; )("+encodeURIComponent(q)+")=([^;]*)")).exec(document.cookie);if(a)return d.parseJSON(decodeURIComponent(a[2]))}var h,g,fa,q="atmosphere-"+c.url,k={storage:function(){if(d.atmosphere.supportStorage()){var e=window.localStorage,h=function(a){return d.parseJSON(e.getItem(q+"-"+a))},f=function(a,c){e.setItem(q+"-"+a,d.stringifyJSON(c))};return{init:function(){f("children",h("children").concat([L]));d(window).on("storage.socket",function(c){c=c.originalEvent;c.key===
q&&c.newValue&&a(c.newValue)});return h("opened")},signal:function(a,c){e.setItem(q,d.stringifyJSON({target:"p",type:a,data:c}))},close:function(){var a,e=h("children");d(window).off("storage.socket");e&&(a=d.inArray(c.id,e),-1<a&&(e.splice(a,1),f("children",e)))}}}},windowref:function(){var c=window.open("",q.replace(/\W/g,""));if(c&&!c.closed&&c.callbacks)return{init:function(){c.callbacks.push(a);c.children.push(L);return c.opened},signal:function(a,e){!c.closed&&c.fire&&c.fire(d.stringifyJSON({target:"p",
type:a,data:e}))},close:function(){if(!fa){var e=c.callbacks,h=d.inArray(a,e);-1<h&&e.splice(h,1);e=c.children;h=d.inArray(L,e);-1<h&&e.splice(h,1)}}}}};if((h=f())&&!(1E3<d.now()-h.ts)&&(g=k.storage()||k.windowref()))return{open:function(){var e;Z=setInterval(function(){var c=h;(h=f())&&c.ts!==h.ts||a(d.stringifyJSON({target:"c",type:"close",data:{reason:"error",heir:c.heir}}))},1E3);(e=g.init())&&setTimeout(function(){t("opening","local",c)},50);return e},send:function(a){g.signal("send",a)},localSend:function(a){g.signal("localSend",
d.stringifyJSON({id:L,event:a}))},close:function(){K||(clearInterval(Z),g.signal("close"),g.close())}}}function va(){function c(a){a=d.parseJSON(a);var c=a.data;if("p"===a.target)switch(a.type){case "send":R(c);break;case "localSend":la(c);break;case "close":Q()}}function a(){document.cookie=ga+"="+encodeURIComponent(d.stringifyJSON({ts:d.now()+1,heir:(f.get("children")||[])[0]}))+"; path=/"}var f,h="atmosphere-"+e.url,ma={storage:function(){if(d.atmosphere.supportStorage()){var a=window.localStorage;
return{init:function(){d(window).on("storage.socket",function(a){a=a.originalEvent;a.key===h&&a.newValue&&c(a.newValue)})},signal:function(c,e){a.setItem(h,d.stringifyJSON({target:"c",type:c,data:e}))},get:function(c){return d.parseJSON(a.getItem(h+"-"+c))},set:function(c,e){a.setItem(h+"-"+c,d.stringifyJSON(e))},close:function(){d(window).off("storage.socket");a.removeItem(h);a.removeItem(h+"-opened");a.removeItem(h+"-children")}}}},windowref:function(){var a=h.replace(/\W/g,""),e=(d('iframe[name="'+
a+'"]')[0]||d('<iframe name="'+a+'" />').hide().appendTo("body")[0]).contentWindow;return{init:function(){e.callbacks=[c];e.fire=function(a){var c;for(c=0;c<e.callbacks.length;c++)e.callbacks[c](a)}},signal:function(a,c){!e.closed&&e.fire&&e.fire(d.stringifyJSON({target:"c",type:a,data:c}))},get:function(a){return e.closed?null:e[a]},set:function(a,c){e.closed||(e[a]=c)},close:function(){}}}};S=function(a){f.signal("message",a)};f=ma.storage()||ma.windowref();f.init();g("debug")&&d.atmosphere.debug("Installed StorageService "+
f);f.set("children",[]);null==f.get("opened")||f.get("opened")||f.set("opened",!1);ga=encodeURIComponent(h);a();Z=setInterval(a,1E3);H=f}function t(c,a,d){e.shared&&"local"!==a&&va();null!=H&&H.set("opened",!0);d.close=function(){Q()};0<E&&"re-connecting"===c?(d.isReopen=!0,wa(f)):null==f.error&&(f.request=d,d=f.state,f.state=c,c=f.transport,f.transport=a,a=f.responseBody,y(),f.responseBody=a,f.state=d,f.transport=c)}function B(c){c.transport="jsonp";var a=e;null!=c&&"undefined"!==typeof c&&(a=c);
c=a.url;null!=a.dispatchUrl&&(c+=a.dispatchUrl);var A=a.data;a.attachHeadersAsQueryString&&(c=N(a),""!==A&&(c+="&X-Atmosphere-Post-Body="+encodeURIComponent(A)),A="");w=d.ajax({url:c,type:a.method,dataType:"jsonp",error:function(c,e,d){f.error=!0;a.openId&&clearTimeout(a.openId);a.heartbeatTimer&&clearTimeout(a.heartbeatTimer);a.reconnect&&E++<a.maxReconnectOnClose?(t("re-connecting",a.transport,a),C(w,a,a.reconnectInterval),a.openId=setTimeout(function(){T(a)},a.reconnectInterval+1E3)):v(c.status,
d)},jsonp:"jsonpTransport",success:function(c){if(a.reconnect)if(-1===a.maxRequest||a.requestCount++<a.maxRequest){aa(w,a);a.executeCallbackBeforeReconnect||C(w,a,a.pollingInterval);c=c.message;if(null!=c&&"string"!==typeof c)try{c=d.stringifyJSON(c)}catch(A){}I(c,a,f)||M(f.responseBody,"messageReceived",200,a.transport);a.executeCallbackBeforeReconnect&&C(w,a,a.pollingInterval);J(a)}else d.atmosphere.log(e.logLevel,["JSONP reconnect maximum try reached "+e.requestCount]),v(0,"maxRequest reached")},
data:a.data,beforeSend:function(c){ha(c,a,!1)}})}function xa(c){var a=e;null!=c&&"undefined"!==typeof c&&(a=c);c=a.url;null!=a.dispatchUrl&&(c+=a.dispatchUrl);var A=a.data;a.attachHeadersAsQueryString&&(c=N(a),""!==A&&(c+="&X-Atmosphere-Post-Body="+encodeURIComponent(A)),A="");w=d.ajax({url:c,type:a.method,error:function(c,e,d){f.error=!0;300>c.status?C(w,a):v(c.status,d)},success:function(c,A,g){a.reconnect&&(-1===a.maxRequest||a.requestCount++<a.maxRequest?(a.executeCallbackBeforeReconnect||C(w,
a,a.pollingInterval),I(c,a,f)||M(f.responseBody,"messageReceived",200,a.transport),a.executeCallbackBeforeReconnect&&C(w,a,a.pollingInterval)):(d.atmosphere.log(e.logLevel,["AJAX reconnect maximum try reached "+e.requestCount]),v(0,"maxRequest reached")))},beforeSend:function(c){ha(c,a,!1)},crossDomain:a.enableXDR,async:"undefined"!==typeof a.async?a.async:!0})}function D(c){return null!=e.webSocketImpl?e.webSocketImpl:window.WebSocket?new WebSocket(c):new MozWebSocket(c)}function m(){var c=N(e);
return decodeURI(d('<a href="'+c+'"/>')[0].href.replace(/^http/,"ws"))}function ea(c){f.transport="sse";var a=N(e);g("debug")&&(d.atmosphere.debug("Invoking executeSSE"),d.atmosphere.debug("Using URL: "+a));if(c&&!e.reconnect)null!=z&&r();else{try{z=new EventSource(a,{withCredentials:e.withCredentials})}catch(A){v(0,A);P("SSE failed. Downgrading to fallback transport and resending");return}0<e.connectTimeout&&(e.id=setTimeout(function(){c||r()},e.connectTimeout));z.onopen=function(a){J(e);g("debug")&&
d.atmosphere.debug("SSE successfully opened");e.enableProtocol?e.isReopen&&(e.isReopen=!1,t("re-opening",e.transport,e)):c?t("re-opening","sse",e):t("opening","sse",e);c=!0;"POST"===e.method&&(f.state="messageReceived",z.send(e.data))};z.onmessage=function(a){J(e);e.enableXDR||a.origin===window.location.protocol+"//"+window.location.host?(f.state="messageReceived",f.status=200,a=a.data,I(a,e,f)||(y(),f.responseBody="",f.messages=[])):d.atmosphere.log(e.logLevel,["Origin was not "+window.location.protocol+
"//"+window.location.host])};z.onerror=function(a){clearTimeout(e.id);e.heartbeatTimer&&clearTimeout(e.heartbeatTimer);f.closedByClientTimeout||((U(c),r(),K)?d.atmosphere.log(e.logLevel,["SSE closed normally"]):c?e.reconnect&&"sse"===f.transport&&(E++<e.maxReconnectOnClose?(t("re-connecting",e.transport,e),0<e.reconnectInterval?e.reconnectId=setTimeout(function(){ea(!0)},e.reconnectInterval):ea(!0),f.responseBody="",f.messages=[]):(d.atmosphere.log(e.logLevel,["SSE reconnect maximum try reached "+
E]),v(0,"maxReconnectOnClose reached"))):P("SSE failed. Downgrading to fallback transport and resending"))}}}function da(c){f.transport="websocket";var a=m(e.url);g("debug")&&(d.atmosphere.debug("Invoking executeWebSocket"),d.atmosphere.debug("Using URL: "+a));if(c&&!e.reconnect)null!=n&&r();else if(n=D(a),null!=e.webSocketBinaryType&&(n.binaryType=e.webSocketBinaryType),0<e.connectTimeout&&(e.id=setTimeout(function(){if(!c){n.onclose({code:1002,reason:"",wasClean:!1});try{r()}catch(a){}}},e.connectTimeout)),
n.onopen=function(a){J(e);g("debug")&&d.atmosphere.debug("Websocket successfully opened");d.atmosphere.offline=!1;a=c;null!=n&&(n.canSendMessage=!0);e.enableProtocol||(c=!0,a?t("re-opening","websocket",e):t("opening","websocket",e));null!=n&&"POST"===e.method&&(f.state="messageReceived",n.send(e.data))},n.onmessage=function(a){J(e);e.enableProtocol&&(c=!0);f.state="messageReceived";f.status=200;a=a.data;"string"===typeof a?I(a,e,f)||(y(),f.responseBody="",f.messages=[]):(a=na(e,a),""!==a&&(f.responseBody=
a,y(),f.responseBody=null))},n.onerror=function(a){clearTimeout(e.id);e.heartbeatTimer&&clearTimeout(e.heartbeatTimer)},n.onclose=function(a){if("closed"!==f.state){clearTimeout(e.id);var h=a.reason;if(""===h)switch(a.code){case 1E3:h="Normal closure; the connection successfully completed whatever purpose for which it was created.";break;case 1001:h="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:h="The endpoint is terminating the connection due to a protocol error.";break;case 1003:h="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:h="The endpoint is terminating the connection because a data frame was received that is too large.";break;case 1005:h="Unknown: no status code was provided even though one was expected.";break;case 1006:h="Connection was closed abnormally (that is, with no close frame being sent)."}g("warn")&&
(d.atmosphere.warn("Websocket closed, reason: "+h),d.atmosphere.warn("Websocket closed, wasClean: "+a.wasClean));f.closedByClientTimeout||d.atmosphere.offline?e.reconnectId&&(clearTimeout(e.reconnectId),delete e.reconnectId):(U(c),f.state="closed",K)?d.atmosphere.log(e.logLevel,["Websocket closed normally"]):c?e.reconnect&&"websocket"===f.transport&&1001!==a.code&&(r(),E++<e.maxReconnectOnClose?(t("re-connecting",e.transport,e),0<e.reconnectInterval?e.reconnectId=setTimeout(function(){f.responseBody=
"";f.messages=[];da(!0)},e.reconnectInterval):(f.responseBody="",f.messages=[],da(!0))):(d.atmosphere.log(e.logLevel,["Websocket reconnect maximum try reached "+e.requestCount]),g("warn")&&d.atmosphere.warn("Websocket error, reason: "+a.reason),v(0,"maxReconnectOnClose reached"))):P("Websocket failed. Downgrading to Comet and resending")}},-1<navigator.userAgent.toLowerCase().indexOf("android")&&void 0===n.url)n.onclose({reason:"Android 4.1 does not support websockets.",wasClean:!1})}function na(c,
a){var f=a;if("polling"===c.transport)return f;if(0!==d.trim(a).length&&c.enableProtocol&&c.firstMessage){var h=c.trackMessageLength?1:0,g=a.split(c.messageDelimiter);if(g.length<=h+1)return f;c.firstMessage=!1;c.uuid=d.trim(g[h]);g.length<=h+2&&d.atmosphere.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."]);V=parseInt(d.trim(g[h+1]),10);
ia=g[h+2];b=!1;"long-polling"!==c.transport&&T(c);d.atmosphere.uuid=c.uuid;f="";h=c.trackMessageLength?4:3;if(g.length>h+1)for(;h<g.length;h++)f+=g[h],h+1!==g.length&&(f+=c.messageDelimiter);0!==c.ackInterval&&setTimeout(function(){R("...ACK...")},c.ackInterval)}else c.enableProtocol&&c.firstMessage&&d.browser.msie&&10>+d.browser.version.split(".")[0]?d.atmosphere.log(e.logLevel,["Receiving unexpected data from IE"]):T(c);return f}function J(c){clearTimeout(c.id);0<c.timeout&&"polling"!==c.transport&&
(c.id=setTimeout(function(){f.closedByClientTimeout=!0;f.state="closedByClient";f.responseBody="";f.status=408;f.messages=[];y();ja();r()},c.timeout))}function v(c,a){r();clearTimeout(e.id);f.state="error";f.reasonPhrase=a;f.responseBody="";f.status=c;f.messages=[];y()}function I(c,a,e){c=na(a,c);if(0===c.length)return!0;e.responseBody=c;if(a.trackMessageLength){c=e.partialMessage+c;var d=[],f=c.indexOf(a.messageDelimiter);if(-1!=f){for(;-1!==f;){var g=c.substring(0,f),k=parseInt(g,10);if(isNaN(k))throw'message length "'+
g+'" is not a number';f+=a.messageDelimiter.length;f+k>c.length?f=-1:(d.push(c.substring(f,f+k)),c=c.substring(f+k,c.length),f=c.indexOf(a.messageDelimiter))}e.partialMessage=c;if(0!==d.length)return e.responseBody=d.join(a.messageDelimiter),e.messages=d,!1;e.responseBody="";e.messages=[];return!0}}e.responseBody=c;e.messages=[c];return!1}function P(c){d.atmosphere.log(e.logLevel,[c]);if("undefined"!==typeof e.onTransportFailure)e.onTransportFailure(c,e);else if("undefined"!==typeof d.atmosphere.onTransportFailure)d.atmosphere.onTransportFailure(c,
e);e.transport=e.fallbackTransport;c=-1===e.connectTimeout?0:e.connectTimeout;e.reconnect&&"none"!==e.transport||null==e.transport?(e.method=e.fallbackMethod,f.transport=e.fallbackTransport,e.fallbackTransport="none",0<c?e.reconnectId=setTimeout(function(){u()},c):u()):v(500,"Unable to reconnect with fallback transport")}function N(c,a){var g=e;null!=c&&"undefined"!==typeof c&&(g=c);null==a&&(a=g.url);if(!g.attachHeadersAsQueryString||-1!==a.indexOf("X-Atmosphere-Framework"))return a;a+=-1!==a.indexOf("?")?
"&":"?";a+="X-Atmosphere-tracking-id="+g.uuid;a+="&X-Atmosphere-Framework="+d.atmosphere.version;a+="&X-Atmosphere-Transport="+g.transport;g.trackMessageLength&&(a+="&X-Atmosphere-TrackMessageSize=true");null!==g.heartbeat&&null!==g.heartbeat.server&&(a+="&X-Heartbeat-Server="+g.heartbeat.server);""!==g.contentType&&(a+="&Content-Type="+("websocket"===g.transport?g.contentType:encodeURIComponent(g.contentType)));g.enableProtocol&&(a+="&X-atmo-protocol=true");d.each(g.headers,function(e,k){var l=d.isFunction(k)?
k.call(this,g,c,f):k;null!=l&&(a+="&"+encodeURIComponent(e)+"="+encodeURIComponent(l))});return a}function T(c){if(c.isOpen)if(c.isReopen)c.isReopen=!1,t("re-opening",c.transport,c);else return;else c.isOpen=!0,t("opening",c.transport,c);ya(c)}function ya(c){null!=c.heartbeatTimer&&clearTimeout(c.heartbeatTimer);if(!isNaN(V)&&0<V){var a=function(){g("debug")&&atmosphere.util.debug("Sending heartbeat");R(ia);c.heartbeatTimer=setTimeout(a,V)};c.heartbeatTimer=setTimeout(a,V)}}function Y(c){var a=e;
if(null!=c||"undefined"!==typeof c)a=c;a.lastIndex=0;a.readyState=0;if("jsonp"===a.transport||a.enableXDR&&d.atmosphere.checkCORSSupport())B(a);else if("ajax"===a.transport)xa(c);else{if(d.browser.msie&&10>+d.browser.version.split(".")[0]){if("streaming"===a.transport){a.enableXDR&&window.XDomainRequest?W(a):X(a);return}if(a.enableXDR&&window.XDomainRequest){W(a);return}}var g=function(){a.lastIndex=0;a.reconnect&&E++<a.maxReconnectOnClose?(f.ffTryingReconnect=!0,t("re-connecting",c.transport,c),
C(h,a,c.reconnectInterval)):v(0,"maxReconnectOnClose reached")};if(a.reconnect&&(-1===a.maxRequest||a.requestCount++<a.maxRequest)){var h=d.ajaxSettings.xhr();h.hasData=!1;ha(h,a,!0);a.suspend&&(O=h);"polling"!==a.transport&&(f.transport=a.transport,h.onabort=function(){U(!0)},h.onerror=function(){f.error=!0;f.ffTryingReconnect=!0;try{f.status=XMLHttpRequest.status}catch(a){f.status=500}f.status||(f.status=500);f.errorHandled||(r(),g())});h.onreadystatechange=function(){if(!K){f.error=null;var k=
!1,l=!1;if("streaming"===a.transport&&2<a.readyState&&4===h.readyState)r(),g();else{a.readyState=h.readyState;"streaming"===a.transport&&3<=h.readyState?l=!0:"long-polling"===a.transport&&4===h.readyState&&(l=!0);J(e);if("polling"!==a.transport){var q=200;4===h.readyState&&(q=1E3<h.status?0:h.status);if(!a.reconnectOnServerError&&300<=q&&600>q){v(q,h.statusText);return}if(300<=q||0===q){f.errorHandled=!0;r();g();return}a.enableProtocol&&c.firstMessage||2!==h.readyState||(d.browser.mozilla&&f.ffTryingReconnect?
(f.ffTryingReconnect=!1,setTimeout(function(){f.ffTryingReconnect||T(a)},500)):T(a))}else 4===h.readyState&&(l=!0);if(l)if(l=h.responseText,0===d.trim(l).length&&"long-polling"===a.transport)h.hasData?h.hasData=!1:C(h,a,a.pollingInterval);else{h.hasData=!0;aa(h,e);if("streaming"===a.transport)if(d.browser.opera)d.atmosphere.iterate(function(){if(500!==f.status&&h.responseText.length>a.lastIndex){try{f.status=h.status,f.headers=ka(h.getAllResponseHeaders()),aa(h,e)}catch(c){f.status=404}J(e);f.state=
"messageReceived";var d=h.responseText.substring(a.lastIndex);a.lastIndex=h.responseText.length;(k=I(d,a,f))||y();oa(h,a)&&pa(h,a)}else if(400<f.status)return a.lastIndex=h.responseText.length,!1},0);else{if(q=l.substring(a.lastIndex,l.length),k=I(q,a,f),a.lastIndex=l.length,k)return}else k=I(l,a,f);l=oa(h,a);try{f.status=h.status,f.headers=ka(h.getAllResponseHeaders()),aa(h,a)}catch(m){f.status=404}f.state=a.suspend?0===f.status?"closed":"messageReceived":"messagePublished";(q=!l&&"streaming"!==
c.transport&&"polling"!==c.transport)&&!a.executeCallbackBeforeReconnect&&C(h,a,a.pollingInterval);0===f.responseBody.length||k||y();q&&a.executeCallbackBeforeReconnect&&C(h,a,a.pollingInterval);l&&pa(h,a)}}}};h.send(a.data);ca=!0}else"debug"===a.logLevel&&d.atmosphere.log(a.logLevel,["Max re-connection reached."]),v(0,"maxRequest reached")}}function pa(c,a){f.messages=[];a.isReopen=!0;Q();K=!1;C(c,a,500)}function ha(c,a,g){var h=a.url;null!=a.dispatchUrl&&"POST"===a.method&&(h+=a.dispatchUrl);h=
N(a,h);h=d.atmosphere.prepareURL(h);g&&(c.open(a.method,h,!0),0<a.connectTimeout&&(a.id=setTimeout(function(){0===a.requestCount&&(r(),M("Connect timeout","closed",200,a.transport))},a.connectTimeout)));e.withCredentials&&"websocket"!==e.transport&&"withCredentials"in c&&(c.withCredentials=!0);e.dropHeaders||(c.setRequestHeader("X-Atmosphere-Framework",d.atmosphere.version),c.setRequestHeader("X-Atmosphere-Transport",a.transport),null!==a.heartbeat&&null!==a.heartbeat.server&&c.setRequestHeader("X-Heartbeat-Server",
c.heartbeat.server),a.trackMessageLength&&c.setRequestHeader("X-Atmosphere-TrackMessageSize","true"),c.setRequestHeader("X-Atmosphere-tracking-id",a.uuid),d.each(a.headers,function(e,h){var k=d.isFunction(h)?h.call(this,c,a,g,f):h;null!=k&&c.setRequestHeader(e,k)}));""!==a.contentType&&c.setRequestHeader("Content-Type",a.contentType)}function C(c,a,d){if(!f.closedByClientTimeout&&(a.reconnect||a.suspend&&ca)){var h=0;1<c.readyState&&(h=1E3<c.status?0:c.status);f.status=0===h?204:h;f.reason=0===h?
"Server resumed the connection or down.":"OK";clearTimeout(a.id);a.reconnectId&&(clearTimeout(a.reconnectId),delete a.reconnectId);0<d?setTimeout(function(){e.reconnectId=Y(a)},d):Y(a)}}function wa(c){c.state="re-connecting";qa(c)}function W(c){"polling"!==c.transport?(G=ra(c),G.open()):ra(c).open()}function ra(c){var a=e;null!=c&&"undefined"!==typeof c&&(a=c);var g=a.transport,h=0,k=new window.XDomainRequest,l=function(){"long-polling"===a.transport&&a.reconnect&&(-1===a.maxRequest||a.requestCount++<
a.maxRequest)&&(k.status=200,t("re-connecting",c.transport,c),W(a))},q=a.rewriteURL||function(a){var c=/(?:^|;\s*)(JSESSIONID|PHPSESSID)=([^;]*)/.exec(document.cookie);switch(c&&c[1]){case "JSESSIONID":return a.replace(/;jsessionid=[^\?]*|(\?)|$/,";jsessionid="+c[2]+"$1");case "PHPSESSID":return a.replace(/\?PHPSESSID=[^&]*&?|\?|$/,"?PHPSESSID="+c[2]+"&").replace(/&$/,"")}return a};k.onprogress=function(){clearTimeout(a.id);var c=k.responseText,c=c.substring(h);h+=c.length;if("polling"!==g){J(a);
var e=I(c,a,f);if("long-polling"!==g||0!==d.trim(c).length)a.executeCallbackBeforeReconnect&&l(),e||M(f.responseBody,"messageReceived",200,g),a.executeCallbackBeforeReconnect||l()}};k.onerror=function(){"polling"!==a.transport&&(r(),E++<a.maxReconnectOnClose?0<a.reconnectInterval?a.reconnectId=setTimeout(function(){t("re-connecting",c.transport,c);W(a)},a.reconnectInterval):(t("re-connecting",c.transport,c),W(a)):v(0,"maxReconnectOnClose reached"))};k.onload=function(){};return{open:function(){var c=
a.url;null!=a.dispatchUrl&&(c+=a.dispatchUrl);c=N(a,c);k.open(a.method,q(c));"GET"===a.method?k.send():k.send(a.data);0<a.connectTimeout&&(a.id=setTimeout(function(){0===a.requestCount&&(r(),M("Connect timeout","closed",200,a.transport))},a.connectTimeout))},close:function(){k.abort()}}}function X(c){G=za(c);G.open()}function za(c){var a=e;null!=c&&"undefined"!==typeof c&&(a=c);var g,h=new window.ActiveXObject("htmlfile");h.open();h.close();var k=a.url;null!=a.dispatchUrl&&(k+=a.dispatchUrl);"polling"!==
a.transport&&(f.transport=a.transport);return{open:function(){var c=h.createElement("iframe");k=N(a);""!==a.data&&(k+="&X-Atmosphere-Post-Body="+encodeURIComponent(a.data));k=d.atmosphere.prepareURL(k);c.src=k;h.body.appendChild(c);var l=c.contentDocument||c.contentWindow.document;g=d.atmosphere.iterate(function(){try{if(l.firstChild){if("complete"===l.readyState)try{d.noop(l.fileSize)}catch(c){return M("Connection Failure","error",500,a.transport),!1}var k=l.body?l.body.lastChild:l,m=function(){var a=
k.cloneNode(!0);a.appendChild(l.createTextNode("."));a=a.innerText;return a=a.substring(0,a.length-1)};if(!d.nodeName(k,"pre")){var n=l.head||l.getElementsByTagName("head")[0]||l.documentElement||l,p=l.createElement("script");p.text="document.write('<plaintext>')";n.insertBefore(p,n.firstChild);n.removeChild(p);k=l.body.lastChild}a.closed&&(a.isReopen=!0);g=d.atmosphere.iterate(function(){var c=m();if(c.length>a.lastIndex){J(e);f.status=200;f.error=null;k.innerText="";if(I(c,a,f))return"";M(f.responseBody,
"messageReceived",200,a.transport)}a.lastIndex=0;if("complete"===l.readyState)return U(!0),t("re-connecting",a.transport,a),0<a.reconnectInterval?a.reconnectId=setTimeout(function(){X(a)},a.reconnectInterval):X(a),!1},null);return!1}}catch(r){return f.error=!0,t("re-connecting",a.transport,a),E++<a.maxReconnectOnClose?0<a.reconnectInterval?a.reconnectId=setTimeout(function(){X(a)},a.reconnectInterval):X(a):v(0,"maxReconnectOnClose reached"),h.execCommand("Stop"),h.close(),!1}})},close:function(){g&&
g();h.execCommand("Stop");U(!0)}}}function R(c){null!=x?x.send(c):null!=O||null!=z?ba(c):null!=G?e.enableXDR&&d.atmosphere.checkCORSSupport()?(c=sa(c),c.reconnect=!1,B(c)):ba(c):null!=w?ba(c):null!=n?Aa(c):(v(0,"No suspended connection available"),d.atmosphere.error("No suspended connection available. Make sure atmosphere.subscribe has been called and request.onOpen invoked before invoking this method"))}function ba(c){c=sa(c);Y(c)}function ta(c){var a=c;"object"===typeof a&&(a=c.data);return a}function sa(c){var a=
ta(c),a={connected:!1,timeout:6E4,method:"POST",url:e.url,contentType:e.contentType,headers:e.headers,reconnect:!0,callback:null,data:a,suspend:!1,maxRequest:-1,logLevel:"info",requestCount:0,withCredentials:e.withCredentials,transport:"polling",isOpen:!0,attachHeadersAsQueryString:!0,enableXDR:e.enableXDR,uuid:e.uuid,dispatchUrl:e.dispatchUrl,enableProtocol:!1,messageDelimiter:"|",trackMessageLength:e.trackMessageLength,maxReconnectOnClose:e.maxReconnectOnClose,heartbeatTimer:e.heartbeatTimer,heartbeat:e.heartbeat};
"object"===typeof c&&(a=d.extend(a,c));return a}function Aa(c){var a=d.atmosphere.isBinary(c)?c:ta(c),f;try{f=null!=e.dispatchUrl?e.webSocketPathDelimiter+e.dispatchUrl+e.webSocketPathDelimiter+a:a,n.canSendMessage?n.send(f):d.atmosphere.error("WebSocket not connected.")}catch(g){n.onclose=function(a){},r(),P("Websocket failed. Downgrading to Comet and resending "+c),ba(c)}}function la(c){c=d.parseJSON(c);if(c.id!==L)if("undefined"!==typeof e.onLocalMessage)e.onLocalMessage(c.event);else if("undefined"!==
typeof d.atmosphere.onLocalMessage)d.atmosphere.onLocalMessage(c.event)}function M(c,a,e,d){f.responseBody=c;f.transport=d;f.status=e;f.state=a;y()}function aa(c,a){if(a.readResponsesHeaders)try{var e=c.getResponseHeader("X-Atmosphere-tracking-id");e&&null!=e&&(a.uuid=e.split(" ").pop())}catch(f){}else a.enableProtocol||(a.uuid=d.atmosphere.guid())}function qa(c){ua(c,e);ua(c,d.atmosphere)}function ua(c,a){switch(c.state){case "messageReceived":E=0;if("undefined"!==typeof a.onMessage)a.onMessage(c);
break;case "error":if("undefined"!==typeof a.onError)a.onError(c);break;case "opening":delete e.closed;if("undefined"!==typeof a.onOpen)a.onOpen(c);break;case "messagePublished":if("undefined"!==typeof a.onMessagePublished)a.onMessagePublished(c);break;case "re-connecting":if("undefined"!==typeof a.onReconnect)a.onReconnect(e,c);break;case "closedByClient":if("undefined"!==typeof a.onClientTimeout)a.onClientTimeout(e);break;case "re-opening":delete e.closed;if("undefined"!==typeof a.onReopen)a.onReopen(e,
c);break;case "fail-to-reconnect":if("undefined"!==typeof a.onFailureToReconnect)a.onFailureToReconnect(e,c);break;case "unsubscribe":case "closed":if(("undefined"===typeof e.closed||!e.closed)&&"undefined"!==typeof a.onClose)a.onClose(c);e.closed=!0}}function U(c){"closed"!==f.state&&(f.state="closed",f.responseBody="",f.messages=[],f.status=c?200:501,y())}function y(){var c=function(a,c){c(f)};null==x&&null!=S&&S(f.responseBody);e.reconnect=e.mrequest;for(var a="string"===typeof f.responseBody,
k=a&&e.trackMessageLength?0<f.messages.length?f.messages:[""]:Array(f.responseBody),h=0;h<k.length;h++)if(!(1<k.length&&0===k[h].length||(f.responseBody=a?d.trim(k[h]):k[h],null==x&&null!=S&&S(f.responseBody),(0===f.responseBody.length||a&&ia===f.responseBody)&&"messageReceived"===f.state))){qa(f);if(0<d.atmosphere.callbacks.length){g("debug")&&d.atmosphere.debug("Invoking "+d.atmosphere.callbacks.length+" global callbacks: "+f.state);try{d.each(d.atmosphere.callbacks,c)}catch(l){d.atmosphere.log(e.logLevel,
["Callback exception"+l])}}if("function"===typeof e.callback){g("debug")&&d.atmosphere.debug("Invoking request callbacks");try{e.callback(f)}catch(m){d.atmosphere.log(e.logLevel,["Callback exception"+m])}}}}function oa(c,a){return""===f.partialMessage&&"streaming"===a.transport&&c.responseText.length>a.maxStreamingLength?!0:!1}function ja(){if(e.enableProtocol&&!e.firstMessage){var c="X-Atmosphere-Transport=close&X-Atmosphere-tracking-id="+e.uuid;d.each(e.headers,function(a,g){var k=d.isFunction(g)?
g.call(this,e,e,f):g;null!=k&&(c+="&"+encodeURIComponent(a)+"="+encodeURIComponent(k))});var a=e.url.replace(/([?&])_=[^&]*/,c),a=a+(a===e.url?(/\?/.test(e.url)?"&":"?")+c:"");0<e.connectTimeout?d.ajax({url:a,async:e.closeAsync,timeout:e.connectTimeout,cache:!1,crossDomain:e.enableXDR}):d.ajax({url:a,async:e.closeAsync,cache:!1,crossDomain:e.enableXDR})}}function Q(){e.reconnectId&&(clearTimeout(e.reconnectId),delete e.reconnectId);e.heartbeatTimer&&clearTimeout(e.heartbeatTimer);e.reconnect=!1;K=
!0;f.request=e;f.state="unsubscribe";f.responseBody="";f.status=408;y();ja();r()}function r(){f.partialMessage="";e.id&&clearTimeout(e.id);e.heartbeatTimer&&clearTimeout(e.heartbeatTimer);null!=G&&(G.close(),G=null);null!=w&&(w.abort(),w=null);null!=O&&(O.abort(),O=null);null!=n&&(n.canSendMessage&&n.close(),n=null);null!=z&&(z.close(),z=null);null!=H&&(clearInterval(Z),document.cookie=ga+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/",H.signal("close",{reason:"",heir:K?(H.get("children")||[])[0]:
L}),H.close());null!=x&&x.close()}var e={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,shared:!1,readResponsesHeaders:!1,maxReconnectOnClose:5,enableProtocol:!0,pollingInterval:0,heartbeat:{client:null,server:null},ackInterval:0,closeAsync:!1,reconnectOnServerError:!0,onError:function(c){},onClose:function(c){},onOpen:function(c){},onMessage:function(c){},onReopen:function(c,a){},onReconnect:function(c,a){},onMessagePublished:function(c){},onTransportFailure:function(c,a){},onLocalMessage:function(c){},
onFailureToReconnect:function(c,a){},onClientTimeout:function(c){}},f={status:200,reasonPhrase:"OK",responseBody:"",messages:[],headers:[],state:"messageReceived",transport:"polling",error:null,request:null,partialMessage:"",errorHandled:!1,closedByClientTimeout:!1,ffTryingReconnect:!1},n=null,z=null,O=null,G=null,w=null,ca=!0,E=0,V=0,ia=" ",K=!1,S=null,H,x=null,L=d.now(),Z,ga;p(k);this.subscribe=function(c){p(c);u()};this.execute=function(){u()};this.invokeCallback=function(){y()};this.close=function(){Q()};
this.disconnect=function(){ja()};this.getUrl=function(){return e.url};this.push=function(c,a){if(null!=a){var d=e.dispatchUrl;e.dispatchUrl=a;R(c);e.dispatchUrl=d}else R(c)};this.getUUID=function(){return e.uuid};this.pushLocal=function(c){if(0!==c.length)try{x?x.localSend(c):H&&H.signal("localMessage",d.stringifyJSON({id:L,event:c}))}catch(a){d.atmosphere.error(a)}};this.enableProtocol=function(c){return e.enableProtocol};this.init=function(){l()};this.request=e;this.response=f},subscribe:function(k,
l,g){"function"===typeof l&&d.atmosphere.addCallback(l);"string"!==typeof k?g=k:g.url=k;d.atmosphere.uuid="undefined"!==typeof g&&"undefined"!==typeof g.uuid?g.uuid:0;k=new d.atmosphere.AtmosphereRequest(g);k.execute();return d.atmosphere.requests[d.atmosphere.requests.length]=k},addCallback:function(k){-1===d.inArray(k,d.atmosphere.callbacks)&&d.atmosphere.callbacks.push(k)},removeCallback:function(k){k=d.inArray(k,d.atmosphere.callbacks);-1!==k&&d.atmosphere.callbacks.splice(k,1)},unsubscribe:function(){if(0<
d.atmosphere.requests.length)for(var k=[].concat(d.atmosphere.requests),l=0;l<k.length;l++){var g=k[l];g.close();clearTimeout(g.response.request.id);g.heartbeatTimer&&clearTimeout(g.heartbeatTimer)}d.atmosphere.requests=[];d.atmosphere.callbacks=[]},unsubscribeUrl:function(k){var l=-1;if(0<d.atmosphere.requests.length)for(var g=0;g<d.atmosphere.requests.length;g++){var p=d.atmosphere.requests[g];if(p.getUrl()===k){p.close();clearTimeout(p.response.request.id);p.heartbeatTimer&&clearTimeout(p.heartbeatTimer);
l=g;break}}0<=l&&d.atmosphere.requests.splice(l,1)},publish:function(k){"function"===typeof k.callback&&d.atmosphere.addCallback(k.callback);k.transport="polling";k=new d.atmosphere.AtmosphereRequest(k);return d.atmosphere.requests[d.atmosphere.requests.length]=k},checkCORSSupport:function(){return d.browser.msie&&!window.XDomainRequest&&11>+d.browser.version.split(".")[0]||d.browser.opera&&12>+d.browser.version.split(".")[0]||"KreaTVWebKit/531"===d.trim(navigator.userAgent).slice(0,16)||"kreatel"===
d.trim(navigator.userAgent).slice(-7).toLowerCase()?!0:-1<navigator.userAgent.toLowerCase().indexOf("android")?!0:!1},S4:function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},guid:function(){return d.atmosphere.S4()+d.atmosphere.S4()+"-"+d.atmosphere.S4()+"-"+d.atmosphere.S4()+"-"+d.atmosphere.S4()+"-"+d.atmosphere.S4()+d.atmosphere.S4()+d.atmosphere.S4()},prepareURL:function(k){var l=d.now(),g=k.replace(/([?&])_=[^&]*/,"$1_="+l);return g+(g===k?(/\?/.test(k)?"&":"?")+"_="+l:"")},
param:function(k){return d.param(k,d.ajaxSettings.traditional)},supportStorage:function(){var k=window.localStorage;if(k)try{return k.setItem("t","t"),k.removeItem("t"),window.StorageEvent&&!d.browser.msie&&!(d.browser.mozilla&&"1"===d.browser.version.split(".")[0])}catch(l){}return!1},iterate:function(d,l){var g;l=l||0;(function u(){g=setTimeout(function(){!1!==d()&&u()},l)})();return function(){clearTimeout(g)}},log:function(d,l){if(window.console){var g=window.console[d];"function"===typeof g&&
g.apply(window.console,l)}},warn:function(){d.atmosphere.log("warn",arguments)},info:function(){d.atmosphere.log("info",arguments)},debug:function(){d.atmosphere.log("debug",arguments)},error:function(){d.atmosphere.log("error",arguments)},isBinary:function(d){return/^\[object\s(?:Blob|ArrayBuffer|.+Array)\]$/.test(Object.prototype.toString.call(d))}};(function(){var k,l;d.uaMatch=function(d){d=d.toLowerCase();d=/(chrome)[ \/]([\w.]+)/.exec(d)||/(webkit)[ \/]([\w.]+)/.exec(d)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(d)||
/(msie) ([\w.]+)/.exec(d)||/(trident)(?:.*? rv:([\w.]+)|)/.exec(d)||0>d.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(d)||[];return{browser:d[1]||"",version:d[2]||"0"}};k=d.uaMatch(navigator.userAgent);l={};k.browser&&(l[k.browser]=!0,l.version=k.version);l.chrome?l.webkit=!0:l.webkit&&(l.safari=!0);l.trident&&(l.msie=!0);d.browser=l;d.sub=function(){function g(d,k){return new g.fn.init(d,k)}d.extend(!0,g,this);g.superclass=this;g.fn=g.prototype=this();g.fn.constructor=g;g.sub=this.sub;
g.fn.init=function(l,F){F&&F instanceof d&&!(F instanceof g)&&(F=g(F));return d.fn.init.call(this,l,F,k)};g.fn.init.prototype=g.fn;var k=g(document);return g}})();(function(d){function l(d){return'"'+d.replace(u,function(d){var g=F[d];return"string"===typeof g?g:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"'}function g(d){return 10>d?"0"+d:d}function p(d,k){var B,u,D,m=k[d];D=typeof m;m&&"object"===typeof m&&"function"===typeof m.toJSON&&(m=m.toJSON(d),D=typeof m);switch(D){case "string":return l(m);
case "number":return isFinite(m)?String(m):"null";case "boolean":return String(m);case "object":if(!m)return"null";switch(Object.prototype.toString.call(m)){case "[object Date]":return isFinite(m.valueOf())?'"'+m.getUTCFullYear()+"-"+g(m.getUTCMonth()+1)+"-"+g(m.getUTCDate())+"T"+g(m.getUTCHours())+":"+g(m.getUTCMinutes())+":"+g(m.getUTCSeconds())+'Z"':"null";case "[object Array]":u=m.length;D=[];for(B=0;B<u;B++)D.push(p(B,m)||"null");return"["+D.join(",")+"]";default:D=[];for(B in m)Object.prototype.hasOwnProperty.call(m,
B)&&(u=p(B,m))&&D.push(l(B)+":"+u);return"{"+D.join(",")+"}"}}}var u=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,F={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};d.stringifyJSON=function(d){return window.JSON&&window.JSON.stringify?window.JSON.stringify(d):p("",{"":d})}})(d)});