text: (function(){BX.namespace("BX.Call");var e={invite:"im.call.invite",cancel:"im.call.cancel",answer:"im.call.answer",decline:"im.call.decline",hangup:"im.call.hangup",ping:"im.call.ping",negotiationNeeded:"im.call.negotiationNeeded",connectionOffer:"im.call.connectionOffer",connectionAnswer:"im.call.connectionAnswer",iceCandidate:"im.call.iceCandidate"};var t={ping:"Call::ping",negotiationNeeded:"Call::negotiationNeeded",connectionOffer:"Call::connectionOffer",connectionAnswer:"Call::connectionAnswer",iceCandidate:"Call::iceCandidate",voiceStarted:"Call::voiceStarted",voiceStopped:"Call::voiceStopped"};var n={offerToReceiveVideo:true,offerToReceiveAudio:true};var i=3e4;var a=25e3;BX.Call.PlainCall=function(e){this.superclass.constructor.apply(this,arguments);this.state=e.state||"";this.peers=this.initPeers(this.users);this.voiceDetection=null;this.signaling=new BX.Call.PlainCall.Signaling({call:this});this.deviceList=[];this.turnServer=(BX.browser.IsFirefox()?BX.message("turn_server_firefox"):BX.message("turn_server"))||"turn.calls.bitrix24.com";this.turnServerLogin=BX.message("turn_server_login")||"bitrix";this.turnServerPassword=BX.message("turn_server_password")||"bitrix";this.ping();this.pingInterval=setInterval(this.ping.bind(this),a);this._onUnloadHandler=this._onUnload.bind(this);this.enableMicAutoParameters=e.enableMicAutoParameters!==false;window.addEventListener("unload",this._onUnloadHandler)};BX.extend(BX.Call.PlainCall,BX.Call.AbstractCall);BX.Call.PlainCall.prototype.initPeers=function(e){var t={};for(var n=0;n<e.length;n++){var i=e[n];if(i==this.userId)continue;t[i]=this.createPeer(i)}return t};BX.Call.PlainCall.prototype.createPeer=function(e){var t=this;return new BX.Call.PlainCall.Peer({call:this,userId:e,ready:e==this.initiatorId,signalingConnected:e==this.initiatorId,onStreamReceived:function(e){t.runCallback(BX.Call.Event.onStreamReceived,e)},onStreamRemoved:function(e){t.runCallback(BX.Call.Event.onStreamRemoved,e)},onStateChanged:this.__onPeerStateChanged.bind(this),onRTCStatsReceived:this.__onPeerRTCStatsReceived.bind(this)})};BX.Call.PlainCall.prototype.getUsers=function(){var e={};for(var t in this.peers){e[t]=this.peers[t].calculatedState}return e};BX.Call.PlainCall.prototype.isReady=function(){return this.ready};BX.Call.PlainCall.prototype.setVideoEnabled=function(e){e=e===true;if(this.videoEnabled==e){return}this.videoEnabled=e;if(this.ready){this.replaceLocalMediaStream()}};BX.Call.PlainCall.prototype.setMuted=function(e){e=!!e;if(this.muted==e){return}this.muted=e;if(this.localStreams["main"]){var t=this.localStreams["main"].getAudioTracks();if(t[0]){t[0].enabled=!this.muted}}};BX.Call.PlainCall.prototype.setCameraId=function(e){if(this.cameraId==e){return}this.cameraId=e;if(this.ready&&this.videoEnabled){this.replaceLocalMediaStream()}};BX.Call.PlainCall.prototype.setMicrophoneId=function(e){if(this.microphoneId==e){return}this.microphoneId=e;if(this.ready){this.replaceLocalMediaStream()}};BX.Call.PlainCall.prototype.stopSendingStream=function(e){};BX.Call.PlainCall.prototype.inviteUsers=function(e){var t=this;if(!BX.type.isPlainObject(e)){e={}}var n=BX.type.isArray(e.users)?e.users:Object.keys(this.peers);this.ready=true;if(e.localStream instanceof MediaStream&&!this.localStreams["main"]){this.localStreams["main"]=e.localStream}this.getLocalMediaStream().then(function(){return t.signaling.inviteUsers({userIds:n,video:t.videoEnabled?"Y":"N"})}).then(function(e){for(var i=0;i<n.length;i++){if(!t.peers[n[i]]){t.peers[n[i]]=t.createPeer(n[i]);t.runCallback(BX.Call.Event.onUserInvited,{userId:n[i]})}t.peers[n[i]].onInvited()}}).catch(function(e){t.runCallback(BX.Call.Event.onCallFailure,e)})};BX.Call.PlainCall.prototype.getMediaConstraints=function(){var e={};var t=this.videoEnabled?{}:false;var n=navigator.mediaDevices.getSupportedConstraints?navigator.mediaDevices.getSupportedConstraints():{};if(this.microphoneId){e.deviceId={ideal:this.microphoneId}}if(!this.enableMicAutoParameters){if(n.echoCancellation){e.echoCancellation=false}if(n.noiseSuppression){e.noiseSuppression=false}if(n.autoGainControl){e.autoGainControl=false}}if(t){t.aspectRatio=1.7777777778;if(this.cameraId){t.deviceId={ideal:this.cameraId}}}return{audio:e,video:t}};BX.Call.PlainCall.prototype.getLocalMediaStream=function(e){var t=this;if(!BX.type.isNotEmptyString(e)){e="main"}this.log("Requesting access to media devices");return new Promise(function(n,i){if(t.localStreams[e]){return n(t.localStreams[e])}var a=t.getMediaConstraints();navigator.mediaDevices.getUserMedia(a).then(function(i){t.log("Local media stream received");t.localStreams[e]=i;t.runCallback(BX.Call.Event.onLocalMediaReceived,{tag:e,stream:i});if(e==="main"){t.attachVoiceDetection();if(t.muted){var a=i.getAudioTracks();if(a[0]){a[0].enabled=false}}}if(t.deviceList.length===0){navigator.mediaDevices.enumerateDevices().then(function(e){t.deviceList=e;t.runCallback(BX.Call.Event.onDeviceListUpdated,{deviceList:t.deviceList})})}n(t.localStreams[e])}).catch(function(n){t.log("Could not get local media stream.",n);t.log("Request constraints: .",a);t.runCallback("onLocalMediaError",{tag:e,error:n});i(n)})})};BX.Call.PlainCall.prototype.startMediaCapture=function(){return this.getLocalMediaStream()};BX.Call.PlainCall.prototype.attachVoiceDetection=function(){if(this.voiceDetection){this.voiceDetection.destroy()}try{this.voiceDetection=new BX.SimpleVAD({mediaStream:this.localStreams["main"],onVoiceStarted:this.onLocalVoiceStarted.bind(this),onVoiceStopped:this.onLocalVoiceStopped.bind(this)})}catch(e){this.log("Could not attach voice detection to media stream")}};BX.Call.PlainCall.prototype.startScreenSharing=function(){var e=this;if(this.localStreams["screen"]){return}navigator.mediaDevices.getUserMedia({video:{mandatory:{chromeMediaSource:"screen",maxWidth:1920,maxHeight:1080,maxFrameRate:5}}}).then(function(t){e.localStreams["screen"]=t;e.runCallback(BX.Call.Event.onLocalMediaReceived,{tag:"screen",stream:t});if(e.ready){for(var n in e.peers){if(e.peers[n].calculatedState===BX.Call.UserState.Connected){e.peers[n].sendMedia()}}}}).catch(function(e){this.log(e)})};BX.Call.PlainCall.prototype.stopScreenSharing=function(){if(!this.localStreams["screen"]){return}this.localStreams["screen"].getTracks().forEach(function(e){e.stop()});this.localStreams["screen"]=null;this.runCallback(BX.Call.Event.onLocalMediaStopped,{tag:"screen"});for(var e in this.peers){if(this.peers[e].calculatedState===BX.Call.UserState.Connected){this.peers[e].sendMedia()}}};BX.Call.PlainCall.prototype.isScreenSharingStarted=function(){return this.localStreams["screen"]instanceof MediaStream};BX.Call.PlainCall.prototype.onLocalVoiceStarted=function(){this.signaling.sendVoiceStarted({userId:this.users})};BX.Call.PlainCall.prototype.onLocalVoiceStopped=function(){this.signaling.sendVoiceStopped({userId:this.users})};BX.Call.PlainCall.prototype.answer=function(e){var t=this;if(!BX.type.isPlainObject(e)){e={}}if(this.direction!==BX.Call.Direction.Incoming){throw new Error("Only incoming call could be answered")}this.ready=true;this.videoEnabled=e.useVideo==true;this.enableMicAutoParameters=e.enableMicAutoParameters!==false;if(e.localStream instanceof MediaStream){this.localStreams["main"]=e.localStream}return new Promise(function(e,n){t.getLocalMediaStream().then(function(){return t.signaling.sendAnswer()},function(e){t.runCallback(BX.Call.Event.onCallFailure,e)}).then(function(){e()})})};BX.Call.PlainCall.prototype.decline=function(t,n){this.ready=false;var i={callId:this.id,callInstanceId:this.instanceId};if(typeof t!="undefined"){i.code=t}if(typeof n!="undefined"){i.reason=n}BX.ajax.runAction(e.decline,{data:i}).then(function(){this.destroy()}.bind(this))};BX.Call.PlainCall.prototype.hangup=function(){this.ready=false;var t=this;return new Promise(function(n,i){BX.ajax.runAction(e.hangup,{data:{callId:t.id,callInstanceId:t.instanceId}}).then(function(){for(var e in t.peers){t.peers[e].disconnect()}n()})})};BX.Call.PlainCall.prototype.ping=function(){this.signaling.sendPing({userId:this.users})};BX.Call.PlainCall.prototype.getState=function(){};BX.Call.PlainCall.prototype.replaceLocalMediaStream=function(e){var t=this;e=e||"main";if(this.localStreams[e]){BX.webrtc.stopMediaStream(this.localStreams[e]);this.localStreams[e]=null}this.getLocalMediaStream(e).then(function(){if(t.ready){for(var n in t.peers){if(t.peers[n].isReady()){t.peers[n].replaceMediaStream(e)}}}}).catch(function(e){console.error("Could not get access to hardware; don't really know what to do. error:",e)}.bind(this))};BX.Call.PlainCall.prototype.sendAllStreams=function(e){if(!this.peers[e])return;if(!this.peers[e].isReady())return;for(var t in this.localStreams){if(this.localStreams[t]){this.peers[e].sendMedia()}}};BX.Call.PlainCall.prototype.isAnyoneParticipating=function(){for(var e in this.peers){if(this.peers[e].isParticipating()){return true}}return false};BX.Call.PlainCall.prototype.__onPullEvent=function(e,t,n){var i={"Call::answer":this.__onPullEventAnswer.bind(this),"Call::hangup":this.__onPullEventHangup.bind(this),"Call::ping":this.__onPullEventPing.bind(this),"Call::negotiationNeeded":this.__onPullEventNegotiationNeeded.bind(this),"Call::connectionOffer":this.__onPullEventConnectionOffer.bind(this),"Call::connectionAnswer":this.__onPullEventConnectionAnswer.bind(this),"Call::iceCandidate":this.__onPullEventIceCandidate.bind(this),"Call::voiceStarted":this.__onPullEventVoiceStarted.bind(this),"Call::voiceStopped":this.__onPullEventVoiceStopped.bind(this),"Call::usersInvited":this.__onPullEventUsersInvited.bind(this),"Call::associatedEntityReplaced":this.__onPullEventAssociatedEntityReplaced.bind(this),"Call::finish":this.__onPullEventFinish.bind(this)};if(i[e]){this.log("Signaling: "+e+"; Parameters: "+JSON.stringify(t));i[e].call(this,t)}};BX.Call.PlainCall.prototype.__onPullEventUsersInvited=function(e){var t=e.users;for(var n=0;n<t.length;n++){var i=t[n];if(this.peers[i]){if(this.peers[i].calculatedState===BX.Call.UserState.Failed||this.peers[i].calculatedState===BX.Call.UserState.Idle){this.peers[i].onInvited()}}else{this.peers[i]=this.createPeer(i);this.runCallback(BX.Call.Event.onUserInvited,{userId:i});this.peers[i].onInvited()}}};BX.Call.PlainCall.prototype.__onPullEventAnswer=function(e){var t=e.senderId;if(t===this.userId){return this.__onPullEventAnswerSelf(e)}if(!this.peers[t]){return}this.peers[t].setSignalingConnected(true);this.peers[t].setReady(true);if(this.ready){this.sendAllStreams(t)}};BX.Call.PlainCall.prototype.__onPullEventAnswerSelf=function(e){if(e.callInstanceId===this.instanceId)return;this.destroy()};BX.Call.PlainCall.prototype.__onPullEventHangup=function(e){var t=e.senderId;if(this.userId==t){if(this.instanceId!=e.callInstanceId){this.destroy()}}if(!this.peers[t])return;this.peers[t].disconnect(e.code);this.peers[t].setReady(false);if(e.code==603){this.peers[t].setDeclined(true)}if(!this.isAnyoneParticipating()){this.destroy()}};BX.Call.PlainCall.prototype.__onPullEventPing=function(e){var t=this.peers[e.senderId];if(!t)return;t.setSignalingConnected(true)};BX.Call.PlainCall.prototype.__onPullEventNegotiationNeeded=function(e){var t=this.peers[e.senderId];if(!t){return}t.setReady(true);if(e.restart){t.reconnect()}else{t.onNegotiationNeeded()}};BX.Call.PlainCall.prototype.__onPullEventConnectionOffer=function(e){var t=this.peers[e.senderId];if(!t){return}t.setReady(true);t.setUserAgent(e.userAgent);t.setConnectionOffer(e.connectionId,e.sdp)};BX.Call.PlainCall.prototype.__onPullEventConnectionAnswer=function(e){var t=this.peers[e.senderId];if(!t)return;t.setUserAgent(e.userAgent);t.setConnectionAnswer(e.sdp)};BX.Call.PlainCall.prototype.__onPullEventIceCandidate=function(e){var t=this.peers[e.senderId];var n;if(!t)return;try{n=e.candidates;for(var i=0;i<n.length;i++){t.addIceCandidate(n[i])}}catch(e){this.log("Error parsing serialized candidate: ",e)}};BX.Call.PlainCall.prototype.__onPullEventVoiceStarted=function(e){this.runCallback(BX.Call.Event.onUserVoiceStarted,{userId:e.senderId})};BX.Call.PlainCall.prototype.__onPullEventVoiceStopped=function(e){this.runCallback(BX.Call.Event.onUserVoiceStopped,{userId:e.senderId})};BX.Call.PlainCall.prototype.__onPullEventAssociatedEntityReplaced=function(e){if(e.call&&e.call.ASSOCIATED_ENTITY){this.associatedEntity=e.call.ASSOCIATED_ENTITY}};BX.Call.PlainCall.prototype.__onPullEventFinish=function(e){this.destroy()};BX.Call.PlainCall.prototype.__onPeerStateChanged=function(e){this.runCallback(BX.Call.Event.onUserStateChanged,e);if(e.state==BX.Call.UserState.Failed){if(!this.isAnyoneParticipating()){this.hangup().then(this.destroy.bind(this))}}};BX.Call.PlainCall.prototype.__onPeerRTCStatsReceived=function(e){this.runCallback(BX.Call.Event.onRTCStatsReceived,e)};BX.Call.PlainCall.prototype._onUnload=function(t){BX.ajax.runAction(e.hangup,{data:{callId:this.id,callInstanceId:this.instanceId}});for(var n in this.peers){this.peers[n].disconnect()}};BX.Call.PlainCall.prototype.destroy=function(){for(var e in this.peers){if(this.peers[e]){this.peers[e].destroy()}}for(var t in this.localStreams){if(this.localStreams[t]){BX.webrtc.stopMediaStream(this.localStreams[t]);this.localStreams[t]=null}}window.removeEventListener("unload",this._onUnloadHandler);clearInterval(this.pingInterval);this.runCallback(BX.Call.Event.onDestroy)};BX.Call.PlainCall.Signaling=function(e){this.call=e.call};BX.Call.PlainCall.Signaling.prototype.isIceTricklingAllowed=function(){return BX.PULL.isPublishingSupported()};BX.Call.PlainCall.Signaling.prototype.inviteUsers=function(t){return this.__runAjaxAction(e.invite,t)};BX.Call.PlainCall.Signaling.prototype.sendAnswer=function(t){return this.__runAjaxAction(e.answer,t)};BX.Call.PlainCall.Signaling.prototype.sendConnectionOffer=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.connectionOffer,n)}else{return this.__runAjaxAction(e.connectionOffer,n)}};BX.Call.PlainCall.Signaling.prototype.sendConnectionAnswer=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.connectionAnswer,n)}else{return this.__runAjaxAction(e.connectionAnswer,n)}};BX.Call.PlainCall.Signaling.prototype.sendIceCandidate=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.iceCandidate,n)}else{return this.__runAjaxAction(e.iceCandidate,n)}};BX.Call.PlainCall.Signaling.prototype.sendNegotiationNeeded=function(n){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.negotiationNeeded,n)}else{return this.__runAjaxAction(e.negotiationNeeded,n)}};BX.Call.PlainCall.Signaling.prototype.sendVoiceStarted=function(e){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.voiceStarted,e)}};BX.Call.PlainCall.Signaling.prototype.sendVoiceStopped=function(e){if(BX.PULL.isPublishingSupported()){return this.__sendPullEvent(t.voiceStopped,e)}};BX.Call.PlainCall.Signaling.prototype.sendPing=function(n){if(BX.PULL.isPublishingSupported()){this.__sendPullEvent(t.ping,n);this.__runAjaxAction(e.ping,{retransmit:false})}else{this.__runAjaxAction(e.ping,{retransmit:true})}};BX.Call.PlainCall.Signaling.prototype.__sendPullEvent=function(e,t){if(!t.userId){throw new Error("userId is not found in data")}if(!BX.type.isArray(t.userId)){t.userId=[t.userId]}t.senderId=this.call.userId;t.callId=this.call.id;t.requestId=BX.Call.Engine.getInstance().getUuidv4();this.call.log("Sending p2p signaling event "+e+"; "+JSON.stringify(t));BX.PULL.sendMessage(t.userId,"im",e,t,10)};BX.Call.PlainCall.Signaling.prototype.__runAjaxAction=function(e,t){if(!BX.type.isPlainObject(t)){t={}}t.callId=this.call.id;t.callInstanceId=this.call.instanceId;t.requestId=BX.Call.Engine.getInstance().getUuidv4();this.call.log("Sending ajax-based signaling event "+e+"; "+JSON.stringify(t));return BX.ajax.runAction(e,{data:t}).catch(function(e){console.error(e)})};BX.Call.PlainCall.Peer=function(e){this.call=e.call;this.userId=e.userId;this.ready=e.ready===true;this.calling=false;this.inviteTimeout=false;this.declined=false;this.signalingConnected=e.signalingConnected===true;this.failureReason="";this.userAgent="";this.isFirefox=false;this.isChrome=false;this.isMobile=false;this.calculatedState=this.calculateState();this.localStreams={main:null,screen:null};this.senderMediaStream=null;this.peerConnection=null;this.pendingIceCandidates=[];this.localIceCandidates=[];this.callbacks={onStateChanged:BX.type.isFunction(e.onStateChanged)?e.onStateChanged:BX.DoNothing,onStreamReceived:BX.type.isFunction(e.onStreamReceived)?e.onStreamReceived:BX.DoNothing,onStreamRemoved:BX.type.isFunction(e.onStreamRemoved)?e.onStreamRemoved:BX.DoNothing,onRTCStatsReceived:BX.type.isFunction(e.onRTCStatsReceived)?e.onRTCStatsReceived:BX.DoNothing};this.answerTimeout=null;this.callingTimeout=null;this.connectionTimeout=null;this.signalingConnectionTimeout=null;this.candidatesTimeout=null;this.statsInterval=null;this._onPeerConnectionIceCandidateHandler=this._onPeerConnectionIceCandidate.bind(this);this._onPeerConnectionIceConnectionStateChangeHandler=this._onPeerConnectionIceConnectionStateChange.bind(this);this._onPeerConnectionIceGatheringStateChangeHandler=this._onPeerConnectionIceGatheringStateChange.bind(this);this._onPeerConnectionNegotiationNeededHandler=BX.debounce(this._onPeerConnectionNegotiationNeeded,100,this);this._onPeerConnectionTrackHandler=this._onPeerConnectionTrack.bind(this);this._onPeerConnectionRemoveStreamHandler=this._onPeerConnectionRemoveStream.bind(this)};BX.Call.PlainCall.Peer.prototype.sendMedia=function(){var e=[];if(this.call.localStreams["main"]){e=e.concat(this.call.localStreams["main"].getAudioTracks())}if(this.call.localStreams["screen"]){e=e.concat(this.call.localStreams["screen"].getVideoTracks())}else if(this.call.localStreams["main"]){e=e.concat(this.call.localStreams["main"].getVideoTracks())}this.log("User: "+this.userId+"; Sending media streams. Tracks: "+e.map(function(e){return e.id}).join("; "));if(e.length===0){this.log("No media streams to send");return}if(this.peerConnection){this.peerConnection.getSenders().forEach(function(e){this.peerConnection.removeTrack(e)}.bind(this))}if(this.senderMediaStream&&this.senderMediaStream.getTracks().length>0){this.log("removing old tracks");this.senderMediaStream.getTracks().forEach(function(e){this.senderMediaStream.removeTrack(e)},this)}if(!this.peerConnection){if(!this.isInitiator()){this.log("waiting for the other side to send connection offer");this.getSignaling().sendNegotiationNeeded({userId:this.userId});return}var t=BX.Call.Engine.getInstance().getUuidv4();this._createPeerConnection(t)}this.senderMediaStream=new MediaStream;e.forEach(function(e){this.senderMediaStream.addTrack(e);this.peerConnection.addTrack(e,this.senderMediaStream)},this)};BX.Call.PlainCall.Peer.prototype.replaceMediaStream=function(e){if(this.isRenegotiationSupported()){this.sendMedia()}else{this.localStreams[e]=this.call.getLocalStream(e);this.reconnect()}};BX.Call.PlainCall.Peer.prototype.isInitiator=function(){return this.call.userId<this.userId};BX.Call.PlainCall.Peer.prototype.isRenegotiationSupported=function(){return BX.browser.IsChrome()&&this.isChrome};BX.Call.PlainCall.Peer.prototype.setReady=function(e){this.ready=e;if(this.ready){this.declined=false}if(this.calling){clearTimeout(this.callingTimeout);this.calling=false}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.isReady=function(){return this.ready};BX.Call.PlainCall.Peer.prototype.onInvited=function(){this.ready=false;this.inviteTimeout=false;this.declined=false;this.calling=true;if(this.callingTimeout){clearTimeout(this.callingTimeout)}this.callingTimeout=setTimeout(this.onInviteTimeout.bind(this),3e4);this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.onInviteTimeout=function(){clearTimeout(this.callingTimeout);this.calling=false;this.inviteTimeout=true;this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.setUserAgent=function(e){this.userAgent=e;this.isFirefox=e.toLowerCase().indexOf("firefox")!=-1;this.isChrome=e.toLowerCase().indexOf("chrome")!=-1;this.isMobile=e==="Bitrix Mobile"};BX.Call.PlainCall.Peer.prototype.getUserAgent=function(){return this.userAgent};BX.Call.PlainCall.Peer.prototype.isParticipating=function(){if(this.calling)return true;if(this.declined)return false;if(this.peerConnection){var e=this.peerConnection.iceConnectionState;if(e=="checking"||e=="connected"||e=="completed"){return true}}return false};BX.Call.PlainCall.Peer.prototype.setSignalingConnected=function(e){this.signalingConnected=e;this.updateCalculatedState();if(this.signalingConnected)this.refreshSignalingTimeout();else this.stopSignalingTimeout()};BX.Call.PlainCall.Peer.prototype.isSignalingConnected=function(){return this.signalingConnected};BX.Call.PlainCall.Peer.prototype.setDeclined=function(e){this.declined=e;if(this.calling){clearTimeout(this.callingTimeout);this.calling=false}this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype.isDeclined=function(){return this.declined};BX.Call.PlainCall.Peer.prototype.updateCalculatedState=function(){var e=this.calculateState();if(this.calculatedState!=e){this.callbacks.onStateChanged({userId:this.userId,state:e,previousState:this.calculatedState,isMobile:this.isMobile});this.calculatedState=e}};BX.Call.PlainCall.Peer.prototype.calculateState=function(){if(this.peerConnection){if(this.peerConnection.iceConnectionState==="failed"){return BX.Call.UserState.Failed}if(this.peerConnection.iceConnectionState==="connected"||this.peerConnection.iceConnectionState==="completed"){return BX.Call.UserState.Connected}return BX.Call.UserState.Connecting}if(this.calling)return BX.Call.UserState.Calling;if(this.inviteTimeout)return BX.Call.UserState.Failed;if(this.declined)return BX.Call.UserState.Declined;if(this.ready)return BX.Call.UserState.Ready;return BX.Call.UserState.Idle};BX.Call.PlainCall.Peer.prototype.getSignaling=function(){return this.call.signaling};BX.Call.PlainCall.Peer.prototype.startStatisticsGathering=function(){clearInterval(this.statsInterval);this.statsInterval=setInterval(function(){if(!this.peerConnection){return false}this.peerConnection.getStats().then(function(e){this.callbacks.onRTCStatsReceived({userId:this.userId,stats:e})}.bind(this))}.bind(this),1e3)};BX.Call.PlainCall.Peer.prototype.stopStatisticsGathering=function(){clearInterval(this.statsInterval);this.statsInterval=null};BX.Call.PlainCall.Peer.prototype.updateCandidatesTimeout=function(){if(this.candidatesTimeout){clearTimeout(this.candidatesTimeout)}this.candidatesTimeout=setTimeout(this.sendIceCandidates.bind(this),500)};BX.Call.PlainCall.Peer.prototype.sendIceCandidates=function(){this.candidatesTimeout=null;this.log("User "+this.userId+": sending ICE candidates due to the timeout");if(this.localIceCandidates.length>0){this.getSignaling().sendIceCandidate({userId:this.userId,candidates:this.localIceCandidates});this.localIceCandidates=[]}else{this.log("User "+this.userId+": ICE candidates pool is empty")}};BX.Call.PlainCall.Peer.prototype._createPeerConnection=function(e){this.log("User "+this.userId+": Creating peer connection");var t={iceServers:[{url:"stun:"+this.call.turnServer},{url:"turn:"+this.call.turnServer,username:this.call.turnServerLogin,credential:this.call.turnServerPassword}]};this.localIceCandidates=[];var n=new RTCPeerConnection(t);n._id=e;n.addEventListener("icecandidate",this._onPeerConnectionIceCandidateHandler);n.addEventListener("iceconnectionstatechange",this._onPeerConnectionIceConnectionStateChangeHandler);n.addEventListener("icegatheringstatechange",this._onPeerConnectionIceGatheringStateChangeHandler);n.addEventListener("negotiationneeded",this._onPeerConnectionNegotiationNeededHandler);n.addEventListener("track",this._onPeerConnectionTrackHandler);n.addEventListener("removestream",this._onPeerConnectionRemoveStreamHandler);this.peerConnection=n;this.updateCalculatedState();this.startStatisticsGathering()};BX.Call.PlainCall.Peer.prototype._destroyPeerConnection=function(){if(!this.peerConnection)return;this.log("User "+this.userId+": Destroying peer connection");this.stopStatisticsGathering();this.peerConnection.removeEventListener("icecandidate",this._onPeerConnectionIceCandidateHandler);this.peerConnection.removeEventListener("iceconnectionstatechange",this._onPeerConnectionIceConnectionStateChangeHandler);this.peerConnection.removeEventListener("icegatheringstatechange",this._onPeerConnectionIceGatheringStateChangeHandler);this.peerConnection.removeEventListener("negotiationneeded",this._onPeerConnectionNegotiationNeededHandler);this.peerConnection.removeEventListener("track",this._onPeerConnectionTrackHandler);this.peerConnection.removeEventListener("removestream",this._onPeerConnectionRemoveStreamHandler);this.peerConnection.close();this.peerConnection=null};BX.Call.PlainCall.Peer.prototype._onPeerConnectionIceCandidate=function(e){var t=e.candidate;this.log("User "+this.userId+": ICE candidate discovered. Candidate: "+(t?t.candidate:t));if(t){if(this.getSignaling().isIceTricklingAllowed()){this.getSignaling().sendIceCandidate({userId:this.userId,candidates:[t.toJSON()]})}else{this.localIceCandidates.push(t.toJSON());this.updateCandidatesTimeout()}}};BX.Call.PlainCall.Peer.prototype._onPeerConnectionIceConnectionStateChange=function(e){this.log("User "+this.userId+": ICE connection state changed. New state: "+this.peerConnection.iceConnectionState);this.updateCalculatedState()};BX.Call.PlainCall.Peer.prototype._onPeerConnectionIceGatheringStateChange=function(e){var t=e.target;this.log("User "+this.userId+": ICE gathering state changed to : "+t.iceGatheringState);if(t.iceGatheringState==="complete"){this.log("User "+this.userId+": ICE gathering complete");if(!this.getSignaling().isIceTricklingAllowed()){if(this.localIceCandidates.length>0){this.getSignaling().sendIceCandidate({userId:this.userId,candidates:this.localIceCandidates});this.localIceCandidates=[]}else{this.log("User "+this.userId+": ICE candidates already sent")}}}};BX.Call.PlainCall.Peer.prototype._onPeerConnectionNegotiationNeeded=function(e){this.log("User "+this.userId+": needed negotiation for peer connection");this.log("signaling state: ",e.target.signalingState);this.log("ice connection state: ",e.target.iceConnectionState);this.log("pendingRemoteDescription: ",e.target.pendingRemoteDescription);if(e.target.iceConnectionState!=="new"&&e.target.iceConnectionState!=="connected"&&e.target.iceConnectionState!=="completed"){this.log("User "+this.userId+": wrong connection state");return}if(this.isInitiator()){this.createAndSendOffer()}else{this.getSignaling().sendNegotiationNeeded({userId:this.userId})}};BX.Call.PlainCall.Peer.prototype._onPeerConnectionTrack=function(e){this.log("User "+this.userId+": media track received: ",e.track.id+" ("+e.track.kind+")");this.callbacks.onStreamReceived({userId:this.userId,kind:e.track.kind,stream:e.streams[0]})};BX.Call.PlainCall.Peer.prototype._onPeerConnectionRemoveStream=function(e){this.log("User: "+this.userId+"_onPeerConnectionRemoveStream: ",e);this.callbacks.onStreamRemoved({userId:this.userId,stream:e.stream})};BX.Call.PlainCall.Peer.prototype.stopSignalingTimeout=function(){clearTimeout(this.signalingConnectionTimeout)};BX.Call.PlainCall.Peer.prototype.refreshSignalingTimeout=function(){clearTimeout(this.signalingConnectionTimeout);this.signalingConnectionTimeout=setTimeout(this._onLostSignalingConnection.bind(this),i)};BX.Call.PlainCall.Peer.prototype._onLostSignalingConnection=function(){this.setSignalingConnected(false)};BX.Call.PlainCall.Peer.prototype.setConnectionOffer=function(e,t){this.log("User "+this.userId+": applying connection offer for connection "+e);if(!this.call.isReady())return;if(!this.isReady())return;if(this.peerConnection){if(this.peerConnection._id!==e){this._destroyPeerConnection();this._createPeerConnection(e)}}else{this._createPeerConnection(e)}this.applyOfferAndSendAnswer(t)};BX.Call.PlainCall.Peer.prototype.createAndSendOffer=function(e){var t=this;connectionConfig=n;for(var i in e){connectionConfig[i]=e[i]}t.peerConnection.createOffer(connectionConfig).then(function(e){t.log("User "+t.userId+": Created connection offer.");t.log("Applying local description");return t.peerConnection.setLocalDescription(e)}).then(function(){t.sendOffer()})};BX.Call.PlainCall.Peer.prototype.sendOffer=function(){this.getSignaling().sendConnectionOffer({userId:this.userId,connectionId:this.peerConnection._id,sdp:this.peerConnection.localDescription.sdp,userAgent:navigator.userAgent})};BX.Call.PlainCall.Peer.prototype.applyOfferAndSendAnswer=function(e){var t=this;var n=new RTCSessionDescription({type:"offer",sdp:e});var i=this.peerConnection;this.log("User: "+this.userId+"; Applying remote offer");this.log("User: "+this.userId+"; Peer ice connection state ",i.iceConnectionState);i.setRemoteDescription(n).then(function(){if(i.iceConnectionState==="new"){t.sendMedia()}return t.peerConnection.createAnswer()}).then(function(e){t.log("Created connection answer.");t.log("Applying local description.");return t.peerConnection.setLocalDescription(e)}).then(function(){t.applyPendingIceCandidates();t.getSignaling().sendConnectionAnswer({userId:t.userId,connectionId:t.peerConnection._id,sdp:t.peerConnection.localDescription.sdp,userAgent:navigator.userAgent})}).catch(function(e){t.log(e)})};BX.Call.PlainCall.Peer.prototype.setConnectionAnswer=function(e){var t=this;if(!this.peerConnection)return;if(this.peerConnection.signalingState!=="have-local-offer")return;var n=new RTCSessionDescription({type:"answer",sdp:e});this.log("User: "+this.userId+"; Applying remote answer");this.peerConnection.setRemoteDescription(n).then(function(){t.applyPendingIceCandidates()})};BX.Call.PlainCall.Peer.prototype.addIceCandidate=function(e){if(!this.peerConnection)return;if(this.peerConnection.remoteDescription&&this.peerConnection.remoteDescription.type){this.peerConnection.addIceCandidate(e).then(function(){this.log("User: "+this.userId+"; Added remote ICE candidate: "+(e?e.candidate:e))}.bind(this)).catch(function(e){this.log(e)}.bind(this))}else{this.pendingIceCandidates.push(e)}};BX.Call.PlainCall.Peer.prototype.applyPendingIceCandidates=function(){var e=this;if(!this.peerConnection||!this.peerConnection.remoteDescription.type)return;if(BX.type.isArray(this.pendingIceCandidates)){this.pendingIceCandidates.forEach(function(t){e.peerConnection.addIceCandidate(t).then(function(){this.log("User: "+this.userId+"; Added remote ICE candidate: "+(t?t.candidate:t))}.bind(this))});e.pendingIceCandidates=[]}};BX.Call.PlainCall.Peer.prototype.onNegotiationNeeded=function(){if(this.peerConnection){this.createAndSendOffer({iceRestart:true})}else{this.sendMedia()}};BX.Call.PlainCall.Peer.prototype.reconnect=function(){if(this.isInitiator()){this._destroyPeerConnection();this.sendMedia()}else{this.getSignaling().sendNegotiationNeeded({userId:this.userId,restart:true})}};BX.Call.PlainCall.Peer.prototype.disconnect=function(){this._destroyPeerConnection()};BX.Call.PlainCall.Peer.prototype.log=function(){this.call.log.apply(this.call,arguments)};BX.Call.PlainCall.Peer.prototype.destroy=function(){this.disconnect();if(this.voiceDetection){this.voiceDetection.destroy();this.voiceDetection=null}for(var e in this.localStreams){this.localStreams[e]=null}clearTimeout(this.answerTimeout);this.answerTimeout=null;clearTimeout(this.connectionTimeout);this.connectionTimeout=null;clearTimeout(this.signalingConnectionTimeout);this.signalingConnectionTimeout=null;this.callbacks.onStateChanged=BX.DoNothing;this.callbacks.onStreamReceived=BX.DoNothing;this.callbacks.onStreamRemoved=BX.DoNothing}})();
  //# sourceMappingURL=plain_call.map.js