assets.js.libs.atmosphere-min.js Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of groupdocs-annotation Show documentation
Show all versions of groupdocs-annotation Show documentation
GroupDocs.Annotation is an HTML5-based document & image annotator designed to be easily integrated into web, mobile and desktop apps.
It allows developers to provide end users with the ability to annotate documents and images of more than 50 file formats,
including PDF and Microsoft Office documents, Visio diagrams, CAD and raster images.
(function(root,factory){if(typeof define==="function"&&define.amd){define(factory);}else{root.atmosphere=factory();}}(this,function(){var version="2.2.5-javascript",atmosphere={},guid,requests=[],callbacks=[],uuid=0,hasOwn=Object.prototype.hasOwnProperty;atmosphere={onError:function(response){},onClose:function(response){},onOpen:function(response){},onReopen:function(response){},onMessage:function(response){},onReconnect:function(request,response){},onMessagePublished:function(response){},onTransportFailure:function(errorMessage,_request){},onLocalMessage:function(response){},onFailureToReconnect:function(request,response){},onClientTimeout:function(request){},onOpenAfterResume:function(request){},WebsocketApiAdapter:function(request){var _socket,_adapter;request.onMessage=function(e){_adapter.onmessage({data:e.responseBody});};request.onMessagePublished=function(e){_adapter.onmessage({data:e.responseBody});};request.onOpen=function(e){_adapter.onopen(e);};_adapter={close:function(){_socket.close();},send:function(data){_socket.push(data);},onmessage:function(e){},onopen:function(e){},onclose:function(e){},onerror:function(e){}};_socket=new atmosphere.subscribe(request);return _adapter;},AtmosphereRequest:function(options){var _request={timeout:300000,method:"GET",headers:{},contentType:"",callback:null,url:"",data:"",suspend:true,maxRequest:-1,reconnect:true,maxStreamingLength:10000000,lastIndex:0,logLevel:"info",requestCount:0,fallbackMethod:"GET",fallbackTransport:"streaming",transport:"long-polling",webSocketImpl:null,webSocketBinaryType:null,dispatchUrl:null,webSocketPathDelimiter:"@@",enableXDR:false,rewriteURL:false,attachHeadersAsQueryString:true,executeCallbackBeforeReconnect:false,readyState:0,withCredentials:false,trackMessageLength:false,messageDelimiter:"|",connectTimeout:-1,reconnectInterval:0,dropHeaders:true,uuid:0,async:true,shared:false,readResponsesHeaders:false,maxReconnectOnClose:5,enableProtocol:true,pollingInterval:0,heartbeat:{client:null,server:null},ackInterval:0,closeAsync:false,reconnectOnServerError:true,onError:function(response){},onClose:function(response){},onOpen:function(response){},onMessage:function(response){},onReopen:function(request,response){},onReconnect:function(request,response){},onMessagePublished:function(response){},onTransportFailure:function(reason,request){},onLocalMessage:function(request){},onFailureToReconnect:function(request,response){},onClientTimeout:function(request){},onOpenAfterResume:function(request){}};var _response={status:200,reasonPhrase:"OK",responseBody:"",messages:[],headers:[],state:"messageReceived",transport:"polling",error:null,request:null,partialMessage:"",errorHandled:false,closedByClientTimeout:false,ffTryingReconnect:false};var _websocket=null;var _sse=null;var _activeRequest=null;var _ieStream=null;var _jqxhr=null;var _subscribed=true;var _requestCount=0;var _heartbeatPadding=" ";var _abordingConnection=false;var _localSocketF=null;var _storageService;var _localStorageService=null;var guid=atmosphere.util.now();var _traceTimer;var _sharingKey;_subscribe(options);function _init(){_subscribed=true;_abordingConnection=false;_requestCount=0;_websocket=null;_sse=null;_activeRequest=null;_ieStream=null;}function _reinit(){_clearState();_init();}function _verifyStreamingLength(ajaxRequest,rq){if(_response.partialMessage===""&&(rq.transport==="streaming")&&(ajaxRequest.responseText.length>rq.maxStreamingLength)){return true;}return false;}function _disconnect(){if(_request.enableProtocol&&!_request.firstMessage){var query="X-Atmosphere-Transport=close&X-Atmosphere-tracking-id="+_request.uuid;atmosphere.util.each(_request.headers,function(name,value){var h=atmosphere.util.isFunction(value)?value.call(this,_request,_request,_response):value;if(h!=null){query+="&"+encodeURIComponent(name)+"="+encodeURIComponent(h);}});var url=_request.url.replace(/([?&])_=[^&]*/,query);url=url+(url===_request.url?(/\?/.test(_request.url)?"&":"?")+query:"");var rq={connected:false};var closeR=new atmosphere.AtmosphereRequest(rq);closeR.attachHeadersAsQueryString=false;closeR.dropHeaders=true;closeR.url=url;closeR.contentType="text/plain";closeR.transport="polling";closeR.method="GET";closeR.data="";if(_request.enableXDR){closeR.enableXDR=_request.enableXDR;}closeR.async=rq.closeAsync;_pushOnClose("",closeR);}}function _close(){if(_request.logLevel==="debug"){atmosphere.util.debug("Closing");}_abordingConnection=true;if(_request.reconnectId){clearTimeout(_request.reconnectId);delete _request.reconnectId;}if(_request.heartbeatTimer){clearTimeout(_request.heartbeatTimer);}_request.reconnect=false;_response.request=_request;_response.state="unsubscribe";_response.responseBody="";_response.status=408;_response.partialMessage="";_invokeCallback();_disconnect();_clearState();}function _clearState(){_response.partialMessage="";if(_request.id){clearTimeout(_request.id);}if(_request.heartbeatTimer){clearTimeout(_request.heartbeatTimer);}if(_ieStream!=null){_ieStream.close();_ieStream=null;}if(_jqxhr!=null){_jqxhr.abort();_jqxhr=null;}if(_activeRequest!=null){_activeRequest.abort();_activeRequest=null;}if(_websocket!=null){if(_websocket.canSendMessage){_websocket.close();}_websocket=null;}if(_sse!=null){_sse.close();_sse=null;}_clearStorage();}function _clearStorage(){if(_storageService!=null){clearInterval(_traceTimer);document.cookie=_sharingKey+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";_storageService.signal("close",{reason:"",heir:!_abordingConnection?guid:(_storageService.get("children")||[])[0]});_storageService.close();}if(_localStorageService!=null){_localStorageService.close();}}function _subscribe(options){_reinit();_request=atmosphere.util.extend(_request,options);_request.mrequest=_request.reconnect;if(!_request.reconnect){_request.reconnect=true;}}function _supportWebsocket(){return _request.webSocketImpl!=null||window.WebSocket||window.MozWebSocket;}function _supportSSE(){return window.EventSource;}function _execute(){if(_request.shared){_localStorageService=_local(_request);if(_localStorageService!=null){if(_request.logLevel==="debug"){atmosphere.util.debug("Storage service available. All communication will be local");}if(_localStorageService.open(_request)){return;}}if(_request.logLevel==="debug"){atmosphere.util.debug("No Storage service available.");}_localStorageService=null;}_request.firstMessage=uuid==0?true:false;_request.isOpen=false;_request.ctime=atmosphere.util.now();if(_request.uuid===0){_request.uuid=uuid;}_response.closedByClientTimeout=false;if(_request.transport!=="websocket"&&_request.transport!=="sse"){_executeRequest(_request);}else{if(_request.transport==="websocket"){if(!_supportWebsocket()){_reconnectWithFallbackTransport("Websocket is not supported, using request.fallbackTransport ("+_request.fallbackTransport+")");}else{_executeWebSocket(false);}}else{if(_request.transport==="sse"){if(!_supportSSE()){_reconnectWithFallbackTransport("Server Side Events(SSE) is not supported, using request.fallbackTransport ("+_request.fallbackTransport+")");}else{_executeSSE(false);}}}}}function _local(request){var trace,connector,orphan,name="atmosphere-"+request.url,connectors={storage:function(){function onstorage(event){if(event.key===name&&event.newValue){listener(event.newValue);}}if(!atmosphere.util.storage){return;}var storage=window.localStorage,get=function(key){return atmosphere.util.parseJSON(storage.getItem(name+"-"+key));},set=function(key,value){storage.setItem(name+"-"+key,atmosphere.util.stringifyJSON(value));};return{init:function(){set("children",get("children").concat([guid]));atmosphere.util.on(window,"storage",onstorage);return get("opened");},signal:function(type,data){storage.setItem(name,atmosphere.util.stringifyJSON({target:"p",type:type,data:data}));},close:function(){var children=get("children");atmosphere.util.off(window,"storage",onstorage);if(children){if(removeFromArray(children,request.id)){set("children",children);}}}};},windowref:function(){var win=window.open("",name.replace(/\W/g,""));if(!win||win.closed||!win.callbacks){return;}return{init:function(){win.callbacks.push(listener);win.children.push(guid);return win.opened;},signal:function(type,data){if(!win.closed&&win.fire){win.fire(atmosphere.util.stringifyJSON({target:"p",type:type,data:data}));}},close:function(){if(!orphan){removeFromArray(win.callbacks,listener);removeFromArray(win.children,guid);}}};}};function removeFromArray(array,val){var i,length=array.length;for(i=0;i1000){return;}connector=connectors.storage()||connectors.windowref();if(!connector){return;}return{open:function(){var parentOpened;_traceTimer=setInterval(function(){var oldTrace=trace;trace=findTrace();if(!trace||oldTrace.ts===trace.ts){listener(atmosphere.util.stringifyJSON({target:"c",type:"close",data:{reason:"error",heir:oldTrace.heir}}));}},1000);parentOpened=connector.init();if(parentOpened){setTimeout(function(){_open("opening","local",request);},50);}return parentOpened;},send:function(event){connector.signal("send",event);},localSend:function(event){connector.signal("localSend",atmosphere.util.stringifyJSON({id:guid,event:event}));},close:function(){if(!_abordingConnection){clearInterval(_traceTimer);connector.signal("close");connector.close();}}};}function share(){var storageService,name="atmosphere-"+_request.url,servers={storage:function(){function onstorage(event){if(event.key===name&&event.newValue){listener(event.newValue);}}if(!atmosphere.util.storage){return;}var storage=window.localStorage;return{init:function(){atmosphere.util.on(window,"storage",onstorage);},signal:function(type,data){storage.setItem(name,atmosphere.util.stringifyJSON({target:"c",type:type,data:data}));},get:function(key){return atmosphere.util.parseJSON(storage.getItem(name+"-"+key));},set:function(key,value){storage.setItem(name+"-"+key,atmosphere.util.stringifyJSON(value));},close:function(){atmosphere.util.off(window,"storage",onstorage);storage.removeItem(name);storage.removeItem(name+"-opened");storage.removeItem(name+"-children");}};},windowref:function(){var neim=name.replace(/\W/g,""),container=document.getElementById(neim),win;if(!container){container=document.createElement("div");container.id=neim;container.style.display="none";container.innerHTML='';document.body.appendChild(container);}win=container.firstChild.contentWindow;return{init:function(){win.callbacks=[listener];win.fire=function(string){var i;for(i=0;i0&&state==="re-connecting"){request.isReopen=true;_tryingToReconnect(_response);}else{if(_response.error==null){_response.request=request;var prevState=_response.state;_response.state=state;var prevTransport=_response.transport;_response.transport=transport;var _body=_response.responseBody;_invokeCallback();_response.responseBody=_body;_response.state=prevState;_response.transport=prevTransport;}}}function _jsonp(request){request.transport="jsonp";var rq=_request,script;if((request!=null)&&(typeof(request)!=="undefined")){rq=request;}_jqxhr={open:function(){var callback="atmosphere"+(++guid);function poll(){var url=rq.url;if(rq.dispatchUrl!=null){url+=rq.dispatchUrl;}var data=rq.data;if(rq.attachHeadersAsQueryString){url=_attachHeaders(rq);if(data!==""){url+="&X-Atmosphere-Post-Body="+encodeURIComponent(data);}data="";}var head=document.head||document.getElementsByTagName("head")[0]||document.documentElement;script=document.createElement("script");script.src=url+"&jsonpTransport="+callback;script.clean=function(){script.clean=script.onerror=script.onload=script.onreadystatechange=null;if(script.parentNode){script.parentNode.removeChild(script);}};script.onload=script.onreadystatechange=function(){if(!script.readyState||/loaded|complete/.test(script.readyState)){script.clean();}};script.onerror=function(){script.clean();rq.lastIndex=0;if(rq.openId){clearTimeout(rq.openId);}if(rq.heartbeatTimer){clearTimeout(rq.heartbeatTimer);}if(rq.reconnect&&_requestCount++0){_request.id=setTimeout(function(){if(!sseOpened){_clearState();}},_request.connectTimeout);}_sse.onopen=function(event){_timeout(_request);if(_request.logLevel==="debug"){atmosphere.util.debug("SSE successfully opened");}if(!_request.enableProtocol){if(!sseOpened){_open("opening","sse",_request);}else{_open("re-opening","sse",_request);}}else{if(_request.isReopen){_request.isReopen=false;_open("re-opening",_request.transport,_request);}}sseOpened=true;if(_request.method==="POST"){_response.state="messageReceived";_sse.send(_request.data);}};_sse.onmessage=function(message){_timeout(_request);if(!_request.enableXDR&&message.origin&&message.origin!==window.location.protocol+"//"+window.location.host){atmosphere.util.log(_request.logLevel,["Origin was not "+window.location.protocol+"//"+window.location.host]);return;}_response.state="messageReceived";_response.status=200;message=message.data;var skipCallbackInvocation=_trackMessageSize(message,_request,_response);if(!skipCallbackInvocation){_invokeCallback();_response.responseBody="";_response.messages=[];}};_sse.onerror=function(message){clearTimeout(_request.id);if(_request.heartbeatTimer){clearTimeout(_request.heartbeatTimer);}if(_response.closedByClientTimeout){return;}_invokeClose(sseOpened);_clearState();if(_abordingConnection){atmosphere.util.log(_request.logLevel,["SSE closed normally"]);}else{if(!sseOpened){_reconnectWithFallbackTransport("SSE failed. Downgrading to fallback transport and resending");}else{if(_request.reconnect&&(_response.transport==="sse")){if(_requestCount++<_request.maxReconnectOnClose){_open("re-connecting",_request.transport,_request);if(_request.reconnectInterval>0){_request.reconnectId=setTimeout(function(){_executeSSE(true);},_request.reconnectInterval);}else{_executeSSE(true);}_response.responseBody="";_response.messages=[];}else{atmosphere.util.log(_request.logLevel,["SSE reconnect maximum try reached "+_requestCount]);_onError(0,"maxReconnectOnClose reached");}}}}};}function _executeWebSocket(webSocketOpened){_response.transport="websocket";var location=_buildWebSocketUrl(_request.url);if(_request.logLevel==="debug"){atmosphere.util.debug("Invoking executeWebSocket");atmosphere.util.debug("Using URL: "+location);}if(webSocketOpened&&!_request.reconnect){if(_websocket!=null){_clearState();}return;}_websocket=_getWebSocket(location);if(_request.webSocketBinaryType!=null){_websocket.binaryType=_request.webSocketBinaryType;}if(_request.connectTimeout>0){_request.id=setTimeout(function(){if(!webSocketOpened){var _message={code:1002,reason:"",wasClean:false};_websocket.onclose(_message);try{_clearState();}catch(e){}return;}},_request.connectTimeout);}_websocket.onopen=function(message){_timeout(_request);if(_request.logLevel==="debug"){atmosphere.util.debug("Websocket successfully opened");}var reopening=webSocketOpened;if(_websocket!=null){_websocket.canSendMessage=true;}if(!_request.enableProtocol){webSocketOpened=true;if(reopening){_open("re-opening","websocket",_request);}else{_open("opening","websocket",_request);}}if(_websocket!=null){if(_request.method==="POST"){_response.state="messageReceived";_websocket.send(_request.data);}}};_websocket.onmessage=function(message){_timeout(_request);if(_request.enableProtocol){webSocketOpened=true;}_response.state="messageReceived";_response.status=200;message=message.data;var isString=typeof(message)==="string";if(isString){var skipCallbackInvocation=_trackMessageSize(message,_request,_response);if(!skipCallbackInvocation){_invokeCallback();_response.responseBody="";_response.messages=[];}}else{message=_handleProtocol(_request,message);if(message===""){return;}_response.responseBody=message;_invokeCallback();_response.responseBody=null;}};_websocket.onerror=function(message){clearTimeout(_request.id);if(_request.heartbeatTimer){clearTimeout(_request.heartbeatTimer);}};_websocket.onclose=function(message){clearTimeout(_request.id);if(_response.state==="closed"){return;}var reason=message.reason;if(reason===""){switch(message.code){case 1000:reason="Normal closure; the connection successfully completed whatever purpose for which it was created.";break;case 1001:reason="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:reason="The endpoint is terminating the connection due to a protocol error.";break;case 1003:reason="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:reason="The endpoint is terminating the connection because a data frame was received that is too large.";break;case 1005:reason="Unknown: no status code was provided even though one was expected.";break;case 1006:reason="Connection was closed abnormally (that is, with no close frame being sent).";break;}}if(_request.logLevel==="warn"){atmosphere.util.warn("Websocket closed, reason: "+reason);atmosphere.util.warn("Websocket closed, wasClean: "+message.wasClean);}if(_response.closedByClientTimeout){return;}_invokeClose(webSocketOpened);_response.state="closed";if(_abordingConnection){atmosphere.util.log(_request.logLevel,["Websocket closed normally"]);}else{if(!webSocketOpened){_reconnectWithFallbackTransport("Websocket failed. Downgrading to Comet and resending");}else{if(_request.reconnect&&_response.transport==="websocket"&&message.code!==1001){_clearState();if(_requestCount++<_request.maxReconnectOnClose){_open("re-connecting",_request.transport,_request);if(_request.reconnectInterval>0){_request.reconnectId=setTimeout(function(){_response.responseBody="";_response.messages=[];_executeWebSocket(true);},_request.reconnectInterval);}else{_response.responseBody="";_response.messages=[];_executeWebSocket(true);}}else{atmosphere.util.log(_request.logLevel,["Websocket reconnect maximum try reached "+_request.requestCount]);if(_request.logLevel==="warn"){atmosphere.util.warn("Websocket error, reason: "+message.reason);}_onError(0,"maxReconnectOnClose reached");}}}}};var ua=navigator.userAgent.toLowerCase();var isAndroid=ua.indexOf("android")>-1;if(isAndroid&&_websocket.url===undefined){_websocket.onclose({reason:"Android 4.1 does not support websockets.",wasClean:false});}}function _handleProtocol(request,message){var nMessage=message;if(request.transport==="polling"){return nMessage;}if(atmosphere.util.trim(message).length!==0&&request.enableProtocol&&request.firstMessage){var pos=request.trackMessageLength?1:0;var messages=message.split(request.messageDelimiter);if(messages.length<=pos+1){return nMessage;}request.firstMessage=false;request.uuid=atmosphere.util.trim(messages[pos]);if(messages.length<=pos+2){atmosphere.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 interval=parseInt(atmosphere.util.trim(messages[pos+1]),10);_heartbeatPadding=messages[pos+2];if(!isNaN(interval)&&interval>0){var _pushHeartbeat=function(){_push(_heartbeatPadding);request.heartbeatTimer=setTimeout(_pushHeartbeat,interval);};request.heartbeatTimer=setTimeout(_pushHeartbeat,interval);}if(request.transport!=="long-polling"){_triggerOpen(request);}uuid=request.uuid;nMessage="";pos=request.trackMessageLength?4:3;if(messages.length>pos+1){for(var i=pos;i0&&_request.transport!=="polling"){_request.id=setTimeout(function(){_request.timedOut=true;_onClientTimeout(_request);_disconnect();_clearState();},_request.timeout);}}function _onClientTimeout(_request){_response.closedByClientTimeout=true;_response.state="closedByClient";_response.responseBody="";_response.status=408;_response.messages=[];_invokeCallback();}function _onError(code,reason){_clearState();clearTimeout(_request.id);_response.state="error";_response.reasonPhrase=reason;_response.responseBody="";_response.status=code;_response.messages=[];_invokeCallback();}function _trackMessageSize(message,request,response){message=_handleProtocol(request,message);if(message.length===0){return true;}response.responseBody=message;if(request.trackMessageLength){message=response.partialMessage+message;var messages=[];var messageStart=message.indexOf(request.messageDelimiter);while(messageStart!==-1){var str=message.substring(0,messageStart);var messageLength=+str;if(isNaN(messageLength)){throw new Error('message length "'+str+'" is not a number');}messageStart+=request.messageDelimiter.length;if(messageStart+messageLength>message.length){messageStart=-1;}else{messages.push(message.substring(messageStart,messageStart+messageLength));message=message.substring(messageStart+messageLength,message.length);messageStart=message.indexOf(request.messageDelimiter);}}response.partialMessage=message;if(messages.length!==0){response.responseBody=messages.join(request.messageDelimiter);response.messages=messages;return false;}else{response.responseBody="";response.messages=[];return true;}}else{response.responseBody=message;}return false;}function _reconnectWithFallbackTransport(errorMessage){atmosphere.util.log(_request.logLevel,[errorMessage]);if(typeof(_request.onTransportFailure)!=="undefined"){_request.onTransportFailure(errorMessage,_request);}else{if(typeof(atmosphere.util.onTransportFailure)!=="undefined"){atmosphere.util.onTransportFailure(errorMessage,_request);}}_request.transport=_request.fallbackTransport;var reconnectInterval=_request.connectTimeout===-1?0:_request.connectTimeout;if(_request.reconnect&&_request.transport!=="none"||_request.transport==null){_request.method=_request.fallbackMethod;_response.transport=_request.fallbackTransport;_request.fallbackTransport="none";if(reconnectInterval>0){_request.reconnectId=setTimeout(function(){_execute();},reconnectInterval);}else{_execute();}}else{_onError(500,"Unable to reconnect with fallback transport");}}function _attachHeaders(request,url){var rq=_request;if((request!=null)&&(typeof(request)!=="undefined")){rq=request;}if(url==null){url=rq.url;}if(!rq.attachHeadersAsQueryString){return url;}if(url.indexOf("X-Atmosphere-Framework")!==-1){return url;}url+=(url.indexOf("?")!==-1)?"&":"?";url+="X-Atmosphere-tracking-id="+rq.uuid;url+="&X-Atmosphere-Framework="+version;url+="&X-Atmosphere-Transport="+rq.transport;if(rq.trackMessageLength){url+="&X-Atmosphere-TrackMessageSize=true";}if(rq.heartbeat!==null&&rq.heartbeat.server!==null){url+="&X-Heartbeat-Server="+rq.heartbeat.server;}if(rq.contentType!==""){url+="&Content-Type="+(rq.transport==="websocket"?rq.contentType:encodeURIComponent(rq.contentType));}if(rq.enableProtocol){url+="&X-atmo-protocol=true";}atmosphere.util.each(rq.headers,function(name,value){var h=atmosphere.util.isFunction(value)?value.call(this,rq,request,_response):value;if(h!=null){url+="&"+encodeURIComponent(name)+"="+encodeURIComponent(h);}});return url;}function _triggerOpen(rq){if(!rq.isOpen){rq.isOpen=true;_open("opening",rq.transport,rq);}else{if(rq.isReopen){rq.isReopen=false;_open("re-opening",rq.transport,rq);}else{if(_response.state==="messageReceived"&&(rq.transport==="jsonp"||rq.transport==="long-polling")){_openAfterResume(_response);}}}}function _executeRequest(request){var rq=_request;if((request!=null)||(typeof(request)!=="undefined")){rq=request;}rq.lastIndex=0;rq.readyState=0;if((rq.transport==="jsonp")||((rq.enableXDR)&&(atmosphere.util.checkCORSSupport()))){_jsonp(rq);return;}if(atmosphere.util.browser.msie&&+atmosphere.util.browser.version.split(".")[0]<10){if((rq.transport==="streaming")){if(rq.enableXDR&&window.XDomainRequest){_ieXDR(rq);}else{_ieStreaming(rq);}return;}if((rq.enableXDR)&&(window.XDomainRequest)){_ieXDR(rq);return;}}var reconnectF=function(){rq.lastIndex=0;if(rq.reconnect&&_requestCount++2&&ajaxRequest.readyState===4){_clearState();reconnectF();return;}rq.readyState=ajaxRequest.readyState;if(rq.transport==="streaming"&&ajaxRequest.readyState>=3){update=true;}else{if(rq.transport==="long-polling"&&ajaxRequest.readyState===4){update=true;}}_timeout(_request);if(rq.transport!=="polling"){var status=200;if(ajaxRequest.readyState===4){status=ajaxRequest.status>1000?0:ajaxRequest.status;}if(!rq.reconnectOnServerError&&(status>=300&&status<600)){_onError(status,ajaxRequest.statusText);return;}if(status>=300||status===0){disconnected();return;}if((!rq.enableProtocol||!request.firstMessage)&&ajaxRequest.readyState===2){if(atmosphere.util.browser.mozilla&&_response.ffTryingReconnect){_response.ffTryingReconnect=false;setTimeout(function(){if(!_response.ffTryingReconnect){_triggerOpen(rq);}},500);}else{_triggerOpen(rq);}}}else{if(ajaxRequest.readyState===4){update=true;}}if(update){var responseText=ajaxRequest.responseText;_response.errorHandled=false;if(atmosphere.util.trim(responseText).length===0&&rq.transport==="long-polling"){if(!ajaxRequest.hasData){_reconnect(ajaxRequest,rq,rq.pollingInterval);}else{ajaxRequest.hasData=false;}return;}ajaxRequest.hasData=true;_readHeaders(ajaxRequest,_request);if(rq.transport==="streaming"){if(!atmosphere.util.browser.opera){var message=responseText.substring(rq.lastIndex,responseText.length);skipCallbackInvocation=_trackMessageSize(message,rq,_response);rq.lastIndex=responseText.length;if(skipCallbackInvocation){return;}}else{atmosphere.util.iterate(function(){if(_response.status!==500&&ajaxRequest.responseText.length>rq.lastIndex){try{_response.status=ajaxRequest.status;_response.headers=atmosphere.util.parseHeaders(ajaxRequest.getAllResponseHeaders());_readHeaders(ajaxRequest,_request);}catch(e){_response.status=404;}_timeout(_request);_response.state="messageReceived";var message=ajaxRequest.responseText.substring(rq.lastIndex);rq.lastIndex=ajaxRequest.responseText.length;skipCallbackInvocation=_trackMessageSize(message,rq,_response);if(!skipCallbackInvocation){_invokeCallback();}if(_verifyStreamingLength(ajaxRequest,rq)){_reconnectOnMaxStreamingLength(ajaxRequest,rq);return;}}else{if(_response.status>400){rq.lastIndex=ajaxRequest.responseText.length;return false;}}},0);}}else{skipCallbackInvocation=_trackMessageSize(responseText,rq,_response);}var closeStream=_verifyStreamingLength(ajaxRequest,rq);try{_response.status=ajaxRequest.status;_response.headers=atmosphere.util.parseHeaders(ajaxRequest.getAllResponseHeaders());_readHeaders(ajaxRequest,rq);}catch(e){_response.status=404;}if(rq.suspend){_response.state=_response.status===0?"closed":"messageReceived";}else{_response.state="messagePublished";}var isAllowedToReconnect=!closeStream&&request.transport!=="streaming"&&request.transport!=="polling";if(isAllowedToReconnect&&!rq.executeCallbackBeforeReconnect){_reconnect(ajaxRequest,rq,rq.pollingInterval);}if(_response.responseBody.length!==0&&!skipCallbackInvocation){_invokeCallback();}if(isAllowedToReconnect&&rq.executeCallbackBeforeReconnect){_reconnect(ajaxRequest,rq,rq.pollingInterval);}if(closeStream){_reconnectOnMaxStreamingLength(ajaxRequest,rq);}}};try{ajaxRequest.send(rq.data);_subscribed=true;}catch(e){atmosphere.util.log(rq.logLevel,["Unable to connect to "+rq.url]);_onError(0,e);}}else{if(rq.logLevel==="debug"){atmosphere.util.log(rq.logLevel,["Max re-connection reached."]);}_onError(0,"maxRequest reached");}}function _reconnectOnMaxStreamingLength(ajaxRequest,rq){_close();_abordingConnection=false;_reconnect(ajaxRequest,rq,500);}function _doRequest(ajaxRequest,request,create){var url=request.url;if(request.dispatchUrl!=null&&request.method==="POST"){url+=request.dispatchUrl;}url=_attachHeaders(request,url);url=atmosphere.util.prepareURL(url);if(create){ajaxRequest.open(request.method,url,request.async);if(request.connectTimeout>0){request.id=setTimeout(function(){if(request.requestCount===0){_clearState();_prepareCallback("Connect timeout","closed",200,request.transport);}},request.connectTimeout);}}if(_request.withCredentials&&_request.transport!=="websocket"){if("withCredentials" in ajaxRequest){ajaxRequest.withCredentials=true;}}if(!_request.dropHeaders){ajaxRequest.setRequestHeader("X-Atmosphere-Framework",atmosphere.util.version);ajaxRequest.setRequestHeader("X-Atmosphere-Transport",request.transport);if(ajaxRequest.heartbeat!==null&&ajaxRequest.heartbeat.server!==null){ajaxRequest.setRequestHeader("X-Heartbeat-Server",ajaxRequest.heartbeat.server);}if(request.trackMessageLength){ajaxRequest.setRequestHeader("X-Atmosphere-TrackMessageSize","true");}ajaxRequest.setRequestHeader("X-Atmosphere-tracking-id",request.uuid);atmosphere.util.each(request.headers,function(name,value){var h=atmosphere.util.isFunction(value)?value.call(this,ajaxRequest,request,create,_response):value;if(h!=null){ajaxRequest.setRequestHeader(name,h);}});}if(request.contentType!==""){ajaxRequest.setRequestHeader("Content-Type",request.contentType);}}function _reconnect(ajaxRequest,request,reconnectInterval){if(request.reconnect||(request.suspend&&_subscribed)){var status=0;if(ajaxRequest&&ajaxRequest.readyState>1){status=ajaxRequest.status>1000?0:ajaxRequest.status;}_response.status=status===0?204:status;_response.reason=status===0?"Server resumed the connection or down.":"OK";clearTimeout(request.id);if(request.reconnectId){clearTimeout(request.reconnectId);delete request.reconnectId;}if(reconnectInterval>0){_request.reconnectId=setTimeout(function(){_executeRequest(request);},reconnectInterval);}else{_executeRequest(request);}}}function _tryingToReconnect(response){response.state="re-connecting";_invokeFunction(response);}function _openAfterResume(response){response.state="openAfterResume";_invokeFunction(response);response.state="messageReceived";}function _ieXDR(request){if(request.transport!=="polling"){_ieStream=_configureXDR(request);_ieStream.open();}else{_configureXDR(request).open();}}function _configureXDR(request){var rq=_request;if((request!=null)&&(typeof(request)!=="undefined")){rq=request;}var transport=rq.transport;var lastIndex=0;var xdr=new window.XDomainRequest();var reconnect=function(){if(rq.transport==="long-polling"&&(rq.reconnect&&(rq.maxRequest===-1||rq.requestCount++0){rq.reconnectId=setTimeout(function(){_open("re-connecting",request.transport,request);_ieXDR(rq);},rq.reconnectInterval);}else{_open("re-connecting",request.transport,request);_ieXDR(rq);}}else{_onError(0,"maxReconnectOnClose reached");}}};xdr.onload=function(){if(_request.timedOut){_request.timedOut=false;_clearState();rq.lastIndex=0;if(rq.reconnect&&_requestCount++0){rq.id=setTimeout(function(){if(rq.requestCount===0){_clearState();_prepareCallback("Connect timeout","closed",200,rq.transport);}},rq.connectTimeout);}},close:function(){xdr.abort();}};}function _ieStreaming(request){_ieStream=_configureIE(request);_ieStream.open();}function _configureIE(request){var rq=_request;if((request!=null)&&(typeof(request)!=="undefined")){rq=request;}var stop;var doc=new window.ActiveXObject("htmlfile");doc.open();doc.close();var url=rq.url;if(rq.dispatchUrl!=null){url+=rq.dispatchUrl;}if(rq.transport!=="polling"){_response.transport=rq.transport;}return{open:function(){var iframe=doc.createElement("iframe");url=_attachHeaders(rq);if(rq.data!==""){url+="&X-Atmosphere-Post-Body="+encodeURIComponent(rq.data);}url=atmosphere.util.prepareURL(url);iframe.src=url;doc.body.appendChild(iframe);var cdoc=iframe.contentDocument||iframe.contentWindow.document;stop=atmosphere.util.iterate(function(){try{if(!cdoc.firstChild){return;}var res=cdoc.body?cdoc.body.lastChild:cdoc;var readResponse=function(){var clone=res.cloneNode(true);clone.appendChild(cdoc.createTextNode("."));var text=clone.innerText;text=text.substring(0,text.length-1);return text;};if(!cdoc.body||!cdoc.body.firstChild||cdoc.body.firstChild.nodeName.toLowerCase()!=="pre"){var head=cdoc.head||cdoc.getElementsByTagName("head")[0]||cdoc.documentElement||cdoc;var script=cdoc.createElement("script");script.text="document.write('')";head.insertBefore(script,head.firstChild);head.removeChild(script);res=cdoc.body.lastChild;}if(rq.closed){rq.isReopen=true;}stop=atmosphere.util.iterate(function(){var text=readResponse();if(text.length>rq.lastIndex){_timeout(_request);_response.status=200;_response.error=null;res.innerText="";var skipCallbackInvocation=_trackMessageSize(text,rq,_response);if(skipCallbackInvocation){return"";}_prepareCallback(_response.responseBody,"messageReceived",200,rq.transport);}rq.lastIndex=0;if(cdoc.readyState==="complete"){_invokeClose(true);_open("re-connecting",rq.transport,rq);if(rq.reconnectInterval>0){rq.reconnectId=setTimeout(function(){_ieStreaming(rq);},rq.reconnectInterval);}else{_ieStreaming(rq);}return false;}},null);return false;}catch(err){_response.error=true;_open("re-connecting",rq.transport,rq);if(_requestCount++0){rq.reconnectId=setTimeout(function(){_ieStreaming(rq);},rq.reconnectInterval);}else{_ieStreaming(rq);}}else{_onError(0,"maxReconnectOnClose reached");}doc.execCommand("Stop");doc.close();return false;}});},close:function(){if(stop){stop();}doc.execCommand("Stop");_invokeClose(true);}};}function _push(message){if(_localStorageService!=null){_pushLocal(message);}else{if(_activeRequest!=null||_sse!=null){_pushAjaxMessage(message);}else{if(_ieStream!=null){_pushIE(message);}else{if(_jqxhr!=null){_pushJsonp(message);}else{if(_websocket!=null){_pushWebSocket(message);}else{_onError(0,"No suspended connection available");atmosphere.util.error("No suspended connection available. Make sure atmosphere.subscribe has been called and request.onOpen invoked before invoking this method");}}}}}}function _pushOnClose(message,rq){if(!rq){rq=_getPushRequest(message);}rq.transport="polling";rq.method="GET";rq.withCredentials=false;rq.reconnect=false;rq.force=true;rq.suspend=false;rq.timeout=1000;_executeRequest(rq);}function _pushLocal(message){_localStorageService.send(message);}function _intraPush(message){if(message.length===0){return;}try{if(_localStorageService){_localStorageService.localSend(message);}else{if(_storageService){_storageService.signal("localMessage",atmosphere.util.stringifyJSON({id:guid,event:message}));}}}catch(err){atmosphere.util.error(err);}}function _pushAjaxMessage(message){var rq=_getPushRequest(message);_executeRequest(rq);}function _pushIE(message){if(_request.enableXDR&&atmosphere.util.checkCORSSupport()){var rq=_getPushRequest(message);rq.reconnect=false;_jsonp(rq);}else{_pushAjaxMessage(message);}}function _pushJsonp(message){_pushAjaxMessage(message);}function _getStringMessage(message){var msg=message;if(typeof(msg)==="object"){msg=message.data;}return msg;}function _getPushRequest(message){var msg=_getStringMessage(message);var rq={connected:false,timeout:60000,method:"POST",url:_request.url,contentType:_request.contentType,headers:_request.headers,reconnect:true,callback:null,data:msg,suspend:false,maxRequest:-1,logLevel:"info",requestCount:0,withCredentials:_request.withCredentials,async:_request.async,transport:"polling",isOpen:true,attachHeadersAsQueryString:true,enableXDR:_request.enableXDR,uuid:_request.uuid,dispatchUrl:_request.dispatchUrl,enableProtocol:false,messageDelimiter:"|",trackMessageLength:_request.trackMessageLength,maxReconnectOnClose:_request.maxReconnectOnClose,heartbeatTimer:_request.heartbeatTimer,heartbeat:_request.heartbeat};if(typeof(message)==="object"){rq=atmosphere.util.extend(rq,message);}return rq;}function _pushWebSocket(message){var msg=atmosphere.util.isBinary(message)?message:_getStringMessage(message);var data;try{if(_request.dispatchUrl!=null){data=_request.webSocketPathDelimiter+_request.dispatchUrl+_request.webSocketPathDelimiter+msg;}else{data=msg;}if(!_websocket.canSendMessage){atmosphere.util.error("WebSocket not connected.");return;}_websocket.send(data);}catch(e){_websocket.onclose=function(message){};_clearState();_reconnectWithFallbackTransport("Websocket failed. Downgrading to Comet and resending "+message);_pushAjaxMessage(message);}}function _localMessage(message){var m=atmosphere.util.parseJSON(message);if(m.id!==guid){if(typeof(_request.onLocalMessage)!=="undefined"){_request.onLocalMessage(m.event);}else{if(typeof(atmosphere.util.onLocalMessage)!=="undefined"){atmosphere.util.onLocalMessage(m.event);}}}}function _prepareCallback(messageBody,state,errorCode,transport){_response.responseBody=messageBody;_response.transport=transport;_response.status=errorCode;_response.state=state;_invokeCallback();}function _readHeaders(xdr,request){if(!request.readResponsesHeaders){if(!request.enableProtocol){request.uuid=guid;}}else{try{var tempUUID=xdr.getResponseHeader("X-Atmosphere-tracking-id");if(tempUUID&&tempUUID!=null){request.uuid=tempUUID.split(" ").pop();}}catch(e){}}}function _invokeFunction(response){_f(response,_request);_f(response,atmosphere.util);}function _f(response,f){switch(response.state){case"messageReceived":_requestCount=0;if(typeof(f.onMessage)!=="undefined"){f.onMessage(response);}if(typeof(f.onmessage)!=="undefined"){f.onmessage(response);}break;case"error":if(typeof(f.onError)!=="undefined"){f.onError(response);}if(typeof(f.onerror)!=="undefined"){f.onerror(response);}break;case"opening":delete _request.closed;if(typeof(f.onOpen)!=="undefined"){f.onOpen(response);}if(typeof(f.onopen)!=="undefined"){f.onopen(response);}break;case"messagePublished":if(typeof(f.onMessagePublished)!=="undefined"){f.onMessagePublished(response);}break;case"re-connecting":if(typeof(f.onReconnect)!=="undefined"){f.onReconnect(_request,response);}break;case"closedByClient":if(typeof(f.onClientTimeout)!=="undefined"){f.onClientTimeout(_request);}break;case"re-opening":delete _request.closed;if(typeof(f.onReopen)!=="undefined"){f.onReopen(_request,response);}break;case"fail-to-reconnect":if(typeof(f.onFailureToReconnect)!=="undefined"){f.onFailureToReconnect(_request,response);}break;case"unsubscribe":case"closed":var closed=typeof(_request.closed)!=="undefined"?_request.closed:false;if(!closed){if(typeof(f.onClose)!=="undefined"){f.onClose(response);}if(typeof(f.onclose)!=="undefined"){f.onclose(response);}}_request.closed=true;break;case"openAfterResume":if(typeof(f.onOpenAfterResume)!=="undefined"){f.onOpenAfterResume(_request);}break;}}function _invokeClose(wasOpen){if(_response.state!=="closed"){_response.state="closed";_response.responseBody="";_response.messages=[];_response.status=!wasOpen?501:200;_invokeCallback();}}function _invokeCallback(){var call=function(index,func){func(_response);};if(_localStorageService==null&&_localSocketF!=null){_localSocketF(_response.responseBody);}_request.reconnect=_request.mrequest;var isString=typeof(_response.responseBody)==="string";var messages=(isString&&_request.trackMessageLength)?(_response.messages.length>0?_response.messages:[""]):new Array(_response.responseBody);for(var i=0;i1&&messages[i].length===0){continue;}_response.responseBody=(isString)?atmosphere.util.trim(messages[i]):messages[i];if(_localStorageService==null&&_localSocketF!=null){_localSocketF(_response.responseBody);}if((_response.responseBody.length===0||(isString&&_heartbeatPadding===_response.responseBody))&&_response.state==="messageReceived"){continue;}_invokeFunction(_response);if(callbacks.length>0){if(_request.logLevel==="debug"){atmosphere.util.debug("Invoking "+callbacks.length+" global callbacks: "+_response.state);}try{atmosphere.util.each(callbacks,call);}catch(e){atmosphere.util.log(_request.logLevel,["Callback exception"+e]);}}if(typeof(_request.callback)==="function"){if(_request.logLevel==="debug"){atmosphere.util.debug("Invoking request callbacks");}try{_request.callback(_response);}catch(e){atmosphere.util.log(_request.logLevel,["Callback exception"+e]);}}}}this.subscribe=function(options){_subscribe(options);_execute();};this.execute=function(){_execute();};this.close=function(){_close();};this.disconnect=function(){_disconnect();};this.getUrl=function(){return _request.url;};this.push=function(message,dispatchUrl){if(dispatchUrl!=null){var originalDispatchUrl=_request.dispatchUrl;_request.dispatchUrl=dispatchUrl;_push(message);_request.dispatchUrl=originalDispatchUrl;}else{_push(message);}};this.getUUID=function(){return _request.uuid;};this.pushLocal=function(message){_intraPush(message);};this.enableProtocol=function(message){return _request.enableProtocol;};this.request=_request;this.response=_response;}};atmosphere.subscribe=function(url,callback,request){if(typeof(callback)==="function"){atmosphere.addCallback(callback);}if(typeof(url)!=="string"){request=url;}else{request.url=url;}uuid=((typeof(request)!=="undefined")&&typeof(request.uuid)!=="undefined")?request.uuid:0;var rq=new atmosphere.AtmosphereRequest(request);rq.execute();requests[requests.length]=rq;return rq;};atmosphere.unsubscribe=function(){if(requests.length>0){var requestsClone=[].concat(requests);for(var i=0;i0){for(var i=0;i=0){requests.splice(idx,1);}};atmosphere.addCallback=function(func){if(atmosphere.util.inArray(func,callbacks)===-1){callbacks.push(func);}};atmosphere.removeCallback=function(func){var index=atmosphere.util.inArray(func,callbacks);if(index!==-1){callbacks.splice(index,1);}};atmosphere.util={browser:{},parseHeaders:function(headerString){var match,rheaders=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,headers={};while(match=rheaders.exec(headerString)){headers[match[1]]=match[2];}return headers;},now:function(){return new Date().getTime();},isArray:function(array){return Object.prototype.toString.call(array)==="[object Array]";},inArray:function(elem,array){if(!Array.prototype.indexOf){var len=array.length;for(var i=0;i ';return encodeURI(decodeURI(div.firstChild.href));},prepareURL:function(url){var ts=atmosphere.util.now();var ret=url.replace(/([?&])_=[^&]*/,"$1_="+ts);return ret+(ret===url?(/\?/.test(url)?"&":"?")+"_="+ts:"");},trim:function(str){if(!String.prototype.trim){return str.toString().replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");}else{return str.toString().trim();}},param:function(params){var prefix,s=[];function add(key,value){value=atmosphere.util.isFunction(value)?value():(value==null?"":value);s.push(encodeURIComponent(key)+"="+encodeURIComponent(value));}function buildParams(prefix,obj){var name;if(atmosphere.util.isArray(obj)){atmosphere.util.each(obj,function(i,v){if(/\[\]$/.test(prefix)){add(prefix,v);}else{buildParams(prefix+"["+(typeof v==="object"?i:"")+"]",v);}});}else{if(Object.prototype.toString.call(obj)==="[object Object]"){for(name in obj){buildParams(prefix+"["+name+"]",obj[name]);}}else{add(prefix,obj);}}}for(prefix in params){buildParams(prefix,params[prefix]);}return s.join("&").replace(/%20/g,"+");},storage:function(){try{return !!(window.localStorage&&window.StorageEvent);}catch(e){return false;}},iterate:function(fn,interval){var timeoutId;interval=interval||0;(function loop(){timeoutId=setTimeout(function(){if(fn()===false){return;}loop();},interval);})();return function(){clearTimeout(timeoutId);};},each:function(obj,callback,args){if(!obj){return;}var value,i=0,length=obj.length,isArray=atmosphere.util.isArray(obj);if(args){if(isArray){for(;i-1;if(isAndroid){return true;}return false;}};guid=atmosphere.util.now();(function(){var ua=navigator.userAgent.toLowerCase(),match=/(chrome)[ \/]([\w.]+)/.exec(ua)||/(webkit)[ \/]([\w.]+)/.exec(ua)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua)||/(msie) ([\w.]+)/.exec(ua)||/(trident)(?:.*? rv:([\w.]+)|)/.exec(ua)||ua.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua)||[];atmosphere.util.browser[match[1]||""]=true;atmosphere.util.browser.version=match[2]||"0";if(atmosphere.util.browser.trident){atmosphere.util.browser.msie=true;}if(atmosphere.util.browser.msie||(atmosphere.util.browser.mozilla&&+atmosphere.util.browser.version.split(".")[0]===1)){atmosphere.util.storage=false;}})();atmosphere.util.on(window,"unload",function(event){atmosphere.unsubscribe();});atmosphere.util.on(window,"keypress",function(event){if(event.charCode===27||event.keyCode===27){if(event.preventDefault){event.preventDefault();}}});atmosphere.util.on(window,"offline",function(){if(requests.length>0){var requestsClone=[].concat(requests);for(var i=0;i0){for(var i=0;i