Source: messaging.js

/**
* This function subscribes the offender from websocket connection so that there is a connection between staffs and offenders to interact 
* with each other. Connected offender can get the reponses from other staffs and give their own responses to other staffs.
* @params {string} user - User ID of the offender
*/
var subscribe_offender = function(user){
	

	var session= "session_"+ user;

	console.log("subscribing for "+session);
	if(conn ==  null) {
		console.log("conn is null");
		return;
	}
	if(session_info.isInterpter){
		try{
			// alert('ee');
			// show_invitee_control(invitation_data);

		}catch(err){
			
		}
		
	}
	conn.subscribe(session, function(topic, data) {
		// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
		//alert('offender has updated data');		
		
		
		var data = data.data;
		// alert(data.action);
		// show_control(invitation_data);
		// var privilege = '<?php if(isset($previlege_type)){
		// 			echo  'judge' ;
		// 		}?>';
		//alert('data.action'+data.action);	
	if(privilege != 'judge'){	
		switch(data.action){
			case "staff_video_started" :
				if(privilege == 'judge'){
					successToastr("Offender's video started");
					$('#toggleOffenderVideo').prop('checked','checked')
					localStorage.setItem('LS_offender_video_start', 'true')
				}	
			break;
			case "staff_video_stopped" :
				if(privilege == 'judge'){
					infoToastr("Offender's video stopped");
					$('#toggleOffenderVideo').prop('checked', false)
					localStorage.removeItem('LS_offender_video_start')
				}	
			break;
			case "staff_case_close":
				
				jist_stop();				
				var mess = 'This case has been closed.';
				if(privilege == 'judge'){
					// staff_activity.caseClose();
					infoToastr(mess)
					location.reload(true);
				}else{
					//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
					// $('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
					infoToastr(mess)
					location.reload(true);
				}
				current();
			break;
			case "staff_call_start":
				if(data.staff_id == registration_info.user_id) return;
				connectCall();

				var numbers = data.numbers;
				var postdata ={
					'numbers' : data.numbers
				}
				console.log("numbers are "+numbers);
				$.confirm({
					title: 'Call started with offender.Are you sure want to join?',
					columnClass: 'col-md-6 col-md-offset-2',
					content: '',
					buttons: {
						cancel: {
							btnClass: 'btn btn-danger mr-3',
						},
						ok: {
							text: "Ok",
							btnClass: 'btn btn-success',
							keys: ['enter'],
							action: function () {
								$.ajax({
									type: 'POST',
									url:base_url + "staff/conference-call/joinuser",
									data: postdata,
									dataType: 'json',
									success: function(response){
										if(response.status =='success'){
											$.get(base_url + "staff/get-callers", function(data) {
												$("#list_callers").empty()
												$("#list_callers").append(data);
												var params =new Object();
												
												params.To=numbers;
												params.oss_id = response.oss_id;

												startConferences(params);
											}); 
										}
									 }
								});
							}
						}
					}
				})
			break;
			case "offender_fine_submitted":
				// if(privilege == 'judge'){
				// 	staff_activity.getFine();
				// }else{
				// 	loadFine();
				// 	successToastr('Fine Paid');
				// }
				loadFine();
				successToastr('Fine Paid');
			break;
			case "offender_fine_disagreed":
				// if(privilege == 'judge'){
				// 	staff_activity.getFine();
				// }else{
				// 	loadFine();
				// 	successToastr('Fine Paid');
				// }
				loadFine();
				successToastr('Disagree to pay fine');
			break;
			// case "new_user_in_queue":
			// 	///new user in queue
			// 	console.log('new user added to my queue');
			// 	loadQueue();
			// break;
			case "offender_probation_submitted":
				console.log("Probation Form filled by the offender.");
				if(privilege == 'judge'){
					// staff_activity.getProbation();
					showProbationForm();
				}else{
					// getLegalDocuments();
					showProbationForm();
					successToastr('Probation form Signed');
				}	
			break;
			case "offender_fair_intake_submitted":
				console.log("Probation Form filled by the offender.");
				if(privilege == 'judge'){
					// staff_activity.getProbation();
					loadFairIntake();
				}else{
					// getLegalDocuments();
					loadFairIntake();
				}	
			break;
			case "offender_e_intake_submitted":
				if(privilege == 'judge'){
					// staff_activity.getProbation();
					loadEintake();
				}else{
					// getLegalDocuments();
					loadEintake();
				}	
			break;
			case "offender_pro_intake_submitted":
				if(privilege == 'judge'){
					loadProIntake();
				}else{
					loadProIntake();
					successToastr('Profession intake form viewed');
				}	
			break;
			/// this function is used by judge
			case "new_user_in_queue":
				///new user in queue

				//alert('new user in queue inside session_sessionid');
				console.log('new user added to my queue');
				//loadQueue();
			break;
			case "offender_plea_chosen":
				///new user in queue
				// console.log('new user added to my queue');
				var msg = data.message;
				successToastr(msg);
				loadoffenderchoice(data.offender_id);
			break;
			case "offender_compliance_submitted":
				if(privilege == 'judge'){
					// staff_activity.getCompliance();
					loadCompliances();
				}else{
					loadCompliances();
					successToastr('Compliance form signed');
				}
			break;
			case "offender_newdate_submitted":
				if(privilege == 'judge'){
					// staff_activity.getNewDate();
					loadNewDate();
				}else{
					loadNewDate();
					successToastr('reset for trial form signed');
				}
			break;
			case "offender_pre_trial_submitted":
				if(privilege == 'judge'){
					// staff_activity.getNewDate();
					// loadPreTrial();
					loadPreTrialList();
					successToastr('pre trial form signed');
				}else{
					loadPreTrialList();
					successToastr('pre trial form signed');
				}
			break;
			case "accepted_to_join_a_session":
				//toastr.success('Your invitation has been accepted', '', toastrOptions)

				successToastr('Your invitation has been accepted');
			break;
			case "rejected_to_join_a_session":
			
				//toastr.success('Your invitation has been rejected', '', toastrOptions)
				successToastr('Your invitation has been rejected');
				
			break;
			case "defer_to_join_a_session":
				//toastr.success('Waiting for the response for your invitation.', '', toastrOptions);
				successToastr('Waiting for the response for your invitation.');
			break;
			case "session_started":
				//toastr.success('Offender has joined the session', '', toastrOptions)
				successToastr('Offender has joined the session');

			break;
			case "invitee_leave":
				toastr.info('Invitee has left the session.', '', toastrOptions);
				successToastr('Invitee has left the session');
			break;
			case 'staff_entered_invitee':
				toastr.info('Invitee has joined the session.', '', toastrOptions);
			break;
			case "offender_logout":
				// msg =`<div class="card new-card w-100 p-4">
				// 		<h4>Please select user in the queue</h4>
				// 	  </div>`;
				// jist_stop();
				// $('#main-section').empty();
				// $('#main-section').html(msg);
				loadQueue();pingBack();
				// loadQueue();
				//toastr.success('Offender has logged out.', '', toastrOptions)
				successToastr('Offender has logged out.');
			break;
			case "staff_fine_submitted":

				// staff_activity.getFine();
				var mess = 'A fine has been sent to offender.';
				//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
				//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");

				loadFine();
				
				//toastr.success(mess, '', toastrOptions);

				successToastr(mess);
			
			break;
			case "staff_compliance_send":
				// staff_activity.getCompliance();
				loadCompliances();
				var mess = 'A compliance form has been sent to offender.';		
				//toastr.success(mess, '', toastrOptions);
				successToastr(mess);
			break;

			case "probation_submitted":
			showProbationForm()
			// staff_activity.getProbation();
			var mess = 'A probation form has been sent to offender.';
		
			//toastr.success(mess, '', toastrOptions);
			successToastr(mess);
			break;
			case "schedule_newDate":		
			
				/**
				 * sagun commented this to stop staff's video stop
				 * as per the demand of the client
				 * 
				 * jist_stop();
				 * 
				 * */
				var mess = 'A new hearing date has been rescheduled';
				//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");

				//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");


				
				//toastr.success(mess, '', toastrOptions);
				successToastr(mess);
			break;
			case "preTrial_send":
				loadPreTrialList();
				// loadPreTrial();
				var mess = 'A preTrial form has been sent to offender.';		
				//toastr.success(mess, '', toastrOptions);

				successToastr(mess);
				break;
			case "offender_recommendation_submitted":
				if(privilege == 'judge'){
						// staff_activity.getNewDate();
					// loadRecommendation();
					loadRecommendList();
				}else{
					loadRecommendList();
					successToastr('offender has signed DUI form');
				}
				break;
			case "offender_reckless_submitted":
					if(privilege == 'judge'){
							// staff_activity.getNewDate();
						// loadRecommendation();
						loadRecklessList();
					}else{
						loadRecklessList();
						successToastr('offender has signed Reckless Driving form');
					}
					break;
			case "offender_criminal_case_submitted":
					if(privilege == 'judge'){
							// staff_activity.getNewDate();
							// loadCriminalCase();
							loadCriminalCaseList();
					}else{
						loadCriminalCaseList();
						successToastr('offender has signed request to bounce form');
					}
				break;
			case "offender_bindover_submitted":
					if(privilege == 'judge'){
							// staff_activity.getNewDate();
							// loadBindOver();
							loadBindoverList();
					}else{
						loadBindoverList();
						successToastr('offender has signed case bindover form');
					}
				break;
			case "attorney_recommendation_submitted":
				if(privilege == 'judge'){
							// staff_activity.getNewDate();
					// loadRecommendation();
					loadRecommendList();
				}else{
					loadRecommendList();
					successToastr('attorney has signed DUI form');
				}
					break;
			case "attorney_reckless_driving_submitted":
					if(privilege == 'judge'){
							
						loadRecklessList();
					}else{
						loadRecklessList();
						successToastr('attorney has signed reckless driving form');
					}
					break;
			case "attorney_criminal_case_submitted":
				 if(privilege == 'judge'){
					loadCriminalCaseList();
				}else{
					loadCriminalCaseList();
					successToastr('attorney has request to bounce form');
				}
				break;
			case "attorney_entered":
				//toastr.success('Attorney has joined the session', '', toastrOptions)
				loadParticpants();
				loadQueue();
				successToastr('Attorney has joined the session');
			break;	
			case "attorney_left":
				loadParticpants();

				toastr.info('Attorney has left the session', '', toastrOptions)
			break;
			case "witness_left":
				loadParticpants();

				toastr.info('Invitee has left the session', '', toastrOptions)
			break;
			case "witness_entered":
				//toastr.success('Attorney has joined the session', '', toastrOptions)
				loadParticpants();
				successToastr('Invitee has joined the session');
			break;	
			case "witness_left":
				loadParticpants();

				toastr.info('Invitee has left the session', '', toastrOptions)
			break;
			default:
			// alert(data.action);

			break;
		}
		/**
		 * this is the starting of the session of offender with the staffs
		 */
	}
	else {
		switch(data.action){
			case "staff_video_started" :
				// if(privilege == 'judge'){
					successToastr("Offender's video started");
					$('#toggleOffenderVideo').prop('checked','checked')
					localStorage.setItem('LS_offender_video_start', 'true')
				// }	
			break;
			case "staff_video_stopped" :
				// if(privilege == 'judge'){
					infoToastr("Offender's video stopped");
					$('#toggleOffenderVideo').prop('checked', false)
					localStorage.removeItem('LS_offender_video_start')
				// }	
			break;
			case "staff_case_close":
				
				jist_stop();				
				var mess = 'This case has been closed.';
				if(privilege == 'judge'){
					// staff_activity.caseClose();
					infoToastr(mess)
					location.reload(true);
				}else{
					//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
					// $('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
					infoToastr(mess)
					location.reload(true);
				}
				current();
			break;
			case "staff_call_start":
				if(data.staff_id == registration_info.user_id) return;
				connectCall();
				var numbers = data.numbers;
				var postdata ={
					'numbers' : data.numbers
				}
				console.log("numbers are "+numbers);
				$.confirm({
					title: 'Call started with offender.Are you sure  want to join?',
					columnClass: 'col-md-6 col-md-offset-2',
					content: '',
					buttons: {
						cancel: {
							btnClass: 'btn btn-danger mr-3',
						},
						ok: {
							text: "Ok",
							btnClass: 'btn btn-success',
							keys: ['enter'],
							action: function () {
								$.ajax({
									type: 'POST',
									url:base_url + "staff/conference-call/joinuser",
									data: postdata,
									dataType: 'json',
									success: function(response){
										if(response.status =='success'){
											$.get(base_url + "staff/get-callers", function(data) {
												$("#list_callers").empty()
												$("#list_callers").append(data);
												var params =new Object();
												
												params.To=data.numbers;
												params.oss_id = response.oss_id;

												startConferences(params);
											});  
										}
									 }
								});
							}
						}
					}
				})
			break;
			case "attorney_entered":
				//toastr.success('Attorney has joined the session', '', toastrOptions)

				successToastr('Attorney has joined the session');
			break;	
			case "attorney_left":
				toastr.info('Attorney has left the session', '', toastrOptions)
			break;
			case "offender_logout":
				// msg =`<div class="card new-card w-100 p-4">
				// 		<h4>Please select user in the queue</h4>
				// 	  </div>`;
				// jist_stop();
				// $('#main-section').empty();
				// $('#main-section').html(msg);
				loadQueue();pingBack();
				// loadQueue();
				//toastr.success('Offender has logged out.', '', toastrOptions)
				successToastr('Offender has logged out.');
			break;
			default:
			break;
		}
	}
	});
}

/**
* This function unsubscribes the offender from websocket connection
* @params {string} user - User ID of the offender
*/
var unsubscribe_offender = function(user){
	var session= "session_"+ user;
	console.log("unsubscribing "+session);
	console.log("connection"+conn);
	try{
		// conn.unsubscribe(session, function(topic, data) {
		// 	// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
		// 	console.log('unsubscribed '+session+'successfully');
		// });

		console.log(conn.unsubscribe(session));

		

	}catch(err){
		console.log(err);
	}
	
}


/**
* This function subscribes the staff from websocket connection so that there is a connection between staffs to interact with each other.
* Connected staff can get the reponses from other staffs and give their own responses to other staffs.
* @params {string} user - User ID of the staff
*/
var subscribe_staff = function(user){
	user= "staff_"+ user;

	//alert('this is inside subscribe_staff' +user);
	//alert("subscribing staff: ");
	//+user);
	conn.subscribe(user, function(topic, data) {
		// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
		//alert(data.data.action);		
		
		//var data = JSON.parse(data);
		console.log(data);
		//alert(data.user);

		
		// alert('case not handled yet: '+data.data.action);
		switch(data.data.action){
			// case "clerk2_logged_out":
			// 	updateStaffList(); pingBack();
			// 	var mess = 'Clerk has logged out.';
			// 	toastr.success(mess, '', toastrOptions);
			// break;
			// case "judge_logged_out":
			// 	updateStaffList(); pingBack();
			// 	var mess = 'Judge has logged out.';
			// 	toastr.success(mess, '', toastrOptions);
			// break;
			// case "clerk2_logged_in":
			// 	var mess = 'Clerk has logged in.';
			// 	updateStaffList(); pingBack();append(data);
			// 	toastr.success(mess, '', toastrOptions);	
			// break;
			// case "judge_logged_in":
			// 	var mess = 'Judge has logged in.';
			// 	updateStaffList();pingBack();
			// 	toastr.success(mess, '', toastrOptions);	
			// break;

			
			case "queue_updated":
				
			break;
			case "end_session":
				
				jist_stop();
				var mess = 'This session has ended.';
				//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
				//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
				//toastr.success(mess, '', toastrOptions);
				successToastr(mess);

				current();
			break;
			case "session_started":
				var mess = 'This session has been started by '+ data.data.initiated_by;
				//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");

				//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
				//toastr.success(mess, '', toastrOptions);

				successToastr(mess);

				var user_id =  data.data.user;
				if(user_id == registration_info.user_id) {
					return
				}
				// jist_stop();
				// jist_start(data.data.offender_staff_session_id,registration_info,session_info.current_staff_id);
				$('#main-section').empty();

				unsubscribe_offender(session_info.offender_staff_session_id);

				$.get(base_url + "staff/common/current-user-being-served/"+user_id+"/0", function (data) {
					console.log("dd "+data);
					//$('#queue_'+localStorage.LS_selected_queue_id).addClass('active');
					session_info.offender_staff_session_id = data.offender_staff_session_id;
					startMyVideo();
					// $('#loading-icon').show();

					$("#info-box").html(data.offender_detail);

					localStorage.setItem('LS_selected_queue_id', user_id);
					$('.js-offender-queue').removeClass('active');
					$('#queue_'+localStorage.LS_selected_queue_id).addClass('active');
					
					/**
					 * this section will tell server which user in the queue is currently being served
					 * Sagun
					 */
					$.get(base_url + "staff/common/show-control", function (data) {		
						$('#main-section').empty();
						$('#main-section').append(data);
						/**
						 * jisti can be started only after recieving the valud of offender_staff_session_id so it shouldn't be moved from here
						 */
						subscribe_offender(session_info.offender_staff_session_id);
						// $.get(base_url + "staff/user-detail/" + user_id, function (data) {
						// 	$("#info-box").html(data);
						// });
						if (data.code == 200) {
							$(".message").html(data.message);

						} else {
							$(".message").html(data.message);
						}
						if(localStorage.LS_is_video_start === 'false' || localStorage.LS_is_video_start === '') {
							$('#toggleMyVideo').prop("checked", true)
						}

						wasOffenderVideoStarted(session_info.offender_staff_session_id)
						isOffenderQueueClick = false;
					});
			});
						
			break;
			case "offender_transferd":
				var mess = 'This offender has been transfered by the clerk.';
				//toastr.success(mess, '', toastrOptions);

				successToastr(mess);
				jist_stop();
				loadInfoBox();
				$('#main-section').html('');
			break;
			// case "offender_transferd":



			// 	var mess = 'This offender has been transfered by the clerk.';
			// 	toastr.success(mess, '', toastrOptions);
				
				
			// break;
			case "plea_send":


			break;
			// case "schedule_newDate":		

			// 	jist_stop();
			// 	var mess = 'A new hearing date has been rescheduled';
			// 	//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");

			// 	//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");


				
			// 	toastr.success(mess, '', toastrOptions);
			// break;

			// case "staff_fine_submitted":

			// 	staff_activity.getFine();
			// 	var mess = 'A fine has been sent to offender.';
			// 	//$('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
			// 	//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");


				
			// 	toastr.success(mess, '', toastrOptions);
			
			// break;
			// case "staff_compliance_send":
			// 	staff_activity.getCompliance();
			// 	var mess = 'A compliance form has been sent to offender.';
			// 	// $('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
			// 	//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
				
				
			// 	toastr.success(mess, '', toastrOptions);
				
			// break;

			// case "probation_submitted":

			// staff_activity.getProbation();
			// var mess = 'A compliance form has been sent to offender.';
			// // $('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
			// //$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
			// toastr.success(mess, '', toastrOptions);
			// break;

			case "staff_hold":
				var mess = 'This case has been put into a hold.';
				// $('#first-queue-position').html("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");
				//$('#new-clerk-tab').append("<div class='mb-4'><div class='p-3 card new-card w-100'><h4>"+mess+"</h4></div></div>");

				//toastr.success(mess, '', toastrOptions);

				successToastr(mess);
			break;
			
			default:
			
			break;
		}
		
	});
}


/**
* This function unsubscribes the staff from websocket connection
* @params {string} user - User ID of the staff
*/
var unsubscribe_staff = function(user){
	if(user ==0 )return;
	user= "staff_"+ user;
	try{
		conn.unsubscribe(user, function(topic, data) {
			// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
			console.log('unsubscribed successfully');
		});
	}catch(err){
		//console.log(err.message());
	}
}



var calAcceptinPopup;  
var ring_music;


// *
//  * @author Sagun Dhakhwa
//  * 
//  * 
//  * "internal_court_".$this->session->userdata('court_id');
//  * 

/**
* This function subscribes the staffs within the court from websocket connection so that there is a connection between staffs to interact 
* with each other. Connected staff can get the reponses from other staffs and give their own responses to other staffs.
* @params {string} court_id - ID of the court
*/
var subscribe_court = function(court_id){
	channel= "internal_court_"+ court_id;
	//console.log("subscribing staff: "+user);

	console.log('subscribing to internal court '+court_id);
	conn.subscribe(channel, function(topic, data) {
		
		//var data = JSON.parse(data);
		console.log('new console',data.data );
		//console.log(registration_info.user_id);
		
	
		var hasPrev = (typeof session_info.previlege != 'undefinded' && session_info.previlege!=null);

		console.log('has prev:'+ hasPrev);
		var isRecipent = (data.data.user_id == registration_info.user_id);

		isRecipent = true;
		console.log('isRecipient:'+isRecipent);


		var isJudge = (typeof registration_info.judges_clerk_id != 'undefinded' && registration_info.judges_clerk_id!=null);
		console.log('isJudgesClerk:'+isJudge);
		if(hasPrev||isRecipent||isJudge) {
				


		console.log(data.data.action);
		//if(data.data.user_id != registration_info.user_id && registration_info.judges_clerk_id!=null) return;
		//alert('action: '+data.data.action);
		// alert('case not handled yet: '+data.data.action);
		switch(data.data.action){
			case "staff_logged_in":
				var mess = data.data.staff+' has logged in.';
				updateStaffList();pingBack();
				//toastr.success(mess, '', toastrOptions);	

				successToastr(mess);
				

			break;
			case "staff_logged_out":
				updateStaffList(); pingBack();
				var mess = data.data.staff+' has logged out.';
				//toastr.success(mess, '', toastrOptions);

				successToastr(mess);

			break;
			
			case "new_user_in_queue":

				// alert('asdffd');
				///new user in queue
				successToastr('Reloading queue');

				
				console.log('new user added to my queue');
				loadQueue();
				// updateInviteList();
				getInvitations();
				//console.log($("#queue_"+localStorage.LS_selected_queue_id));
				

				// $.fn.exists = function () {
				// 	return this.length !== 0;
				// }

			

				//localStorage.setItem('LS_selected_queue_id', userid);
			break;
			case "attorney_entered":
			console.log('attorney entered');
				loadQueue();
				
			break;
			case "request_to_join_a_session":
				// alert('-------------------');
				//console.log(data.data.staff);
				if(data.data.invited_by == registration_info.user_id) return;
				if(data.data.user_id != registration_info.user_id) return;
				getInvitations();
				$.confirm({
					title: '<div class="pl-3">Invitation from '+data.data.staff+'</div>',	
				    columnClass: 'col-md-8 col-md-offset-2',
				    content: `
				    	<div class="container-fluid text-left">
							<form class="" name="">
								<div class="row"> 
									<div class="col-md-6 form-group">
											<h6>Case Title</h6>
											<div class="text-black-50">`+data.data.case_title+`</div>
									</div>
									<div class="col-md-6 form-group">
                                            <h6>Case No</h6>
                                            <div class="text-black-50">`+data.data.court_case_no+`</div>
                                    </div>
								</div>
						    	<div class="row">
							    	<div class="col-md-6 form-group">
							    		<h6>Offender's name</h6>
							    		<div class="text-black-50">`+data.data.offender_name+`</div>
							    	</div>
							    	<div class="col-md-6 form-group">
							    		<h6>DOB</h6>
							    		<div class="text-black-50">`+data.data.dob+`</div>
							    	</div>
							    	<div class="col-md-6 form-group">
							    		<label>Choice</label>
										<select class="select form-control" name="staff_choice" id="choice">
											<option value="accept">Accept</option>
											<option value="reject">Reject</option>
											<option value="defer">Defer</option>
										</select>
									</div>
								</div>
							</form>
						</div>

				    `,
				    buttons: {   
				        cancel: {
				            btnClass: 'btn btn-danger mr-3',
					    },
				        ok: {
				            text: "Submit",
				            btnClass: 'btn btn-success',
				            keys: ['enter'],
				            action: function(){
								var choice =$('#choice').val();
								console.log(data.data.invite_id);
								$.post(base_url + "staff/invite/respondToInvitation/"+data.data.invite_id+"/"+choice, function (data) {
								if (data.status.localeCompare("success") == 0) {
									if(data.response === "accept"){
										window.location.replace(base_url + "invitee-join-session/"+data.invite_id+'/'+data.offender_id); 

									}
									// show_invitee_control(data);	
									getInvitations();					
								}
								

								

								//subscribe_offender();
								

						}, 'json');	
				            }
				        }
				    }
				})
				
			break;
			case "accepted_to_join_a_session":
				if(data.data.invited_by == registration_info.user_id) return;
				if(data.data.user_id != registration_info.user_id) return;

				//alert('accepted');
				jist_start(data.data.oss_id, registration_info);	
				
				subscribe_offender(data.data.oss_id);
				
				//Sagun : show controls 
			break;
			case "rejected_to_join_a_session":
				// alert('this is to be removed');
				var msg =render_invite(data.data.status);
                $("#invite_staff_section").html(msg);
				
				//toastr.success('Your invitation has been rejected', '', toastrOptions)

				successToastr('Your invitation has been rejected');
				
			break;
			case "defer_to_join_a_session":
				// alert('this is to be removed');
				var msg =render_invite(data.data.status);
                $("#invite_staff_section").html(msg);
				//toastr.success('Waiting for the response for your invitation.', '', toastrOptions)
				successToastr('Waiting for the response for your invitation.');
				
			break;

			

			case "request_to_join_call":
				//animate ring button
				//play ring music
				//alert(data.data.call_id);
				// $().

				if(data.data.user_id != registration_info.user_id) return;

				//animateRing('#phone_icon_'+data.data.staff_id);
				var caller_id = data.data.caller_id
				var caller  = data.data.caller;
				$('#phone_icon_'+caller_id).hide()
				$('#phone_icon_'+caller_id).parent('.btn-dot').find('.js-phone-ringing').show()
				ring_music = document.getElementById('ring_music');
				ring_music.volume = 0.2;
				ring_music.play();
				calAcceptinPopup = $.confirm({
					title: 'Call by '+caller.fname + ' '+caller.lname,	
				    columnClass: 'col-md-8 col-md-offset-2',
				    content: `
				    	<div class="container-fluid">
				    		Do you want to accept it?
						</div>

				    `,
				    buttons: {   
				        cancel: {
				        	text: 'Reject',
							btnClass: 'btn btn-danger mr-3',
				            keys: ['enter'],
				            action: function(){					
				            	ring_music.pause();			
								var call_id = data.data.call_id;
								$.get(base_url + "staff/reject-call/"+ call_id, function (data) {
									
									$('#phone_icon_'+caller_id).show()
									$('#phone_icon_'+caller_id).parent('.btn-dot').find('.js-phone-ringing').hide()
									$('#phone_icon_'+caller_id).parents('.offender-queue').find('.js-missed-call').html('Missed Call')
									
								});
								
				            }
					    },
				        ok: {
				            text: "Accept",
				            btnClass: 'btn btn-success',
				            keys: ['enter'],
				            action: function(){						
				            	ring_music.pause();						
								var call_id = data.data.call_id;
								$.get(base_url + "staff/accept-call/"+ call_id, function (data) {
									$('#staff-info-box').html(atob(data.info_box));
									// jist_start(call_id, registration_info);
									// var template = `
									// 	<div class="card new-card w-100 p-4">
									// 		<div class="mdc-card-wrap">
									// 			<button class="mdc-card mb-0" id="endCallSession" data-call_id="`+call_id+`">End call</button>
									// 		</div>
									// 	</div>
									// `;
									// $('#main-section').empty();
									// $('#main-section').html(template)
                    				$('.js-call-court-staff').addClass('in-call')

                    				jist_stop();

									var template = `
										<div class="card new-card w-100 p-4">
											<div class="mdc-card-wrap">
												<button class="mdc-card mb-0 w-100" id="endCallSession" data-call_id="`+call_id+`">End call</button>
											</div>
										</div>
									`;
									$('#staff-main-section').empty();
									$('#staff-main-section').html(template)
                    				$('#videoCallDoModal').modal('show')
                    				staff_jist_start(call_id, registration_info);

								});
								
				            }
				        }
				    }
				})
			break;

			case "call_accepted":
				// accept the call
				if(data.data.caller_id != registration_info.user_id){
					return;
				}
				console.log(data.data.call_id);
				var call_id = data.data.call_id;
				
				$.get(base_url + "staff/get-call-participant-detail/"+data.data.callee_id, function (data) {

					
					$('#staff-info-box').html(atob(data));
					// jist_start(call_id, registration_info);

				});
				callingPopup.close();
				// var template = `
				// 	<div class="card new-card w-100 p-4">
				// 		<div class="mdc-card-wrap">
				// 			<button class="mdc-card mb-0" id="endCallSession" data-call_id="`+call_id+`">End call</button>
				// 		</div>
				// 	</div>
				// `;
				// $('#main-section').empty();
				// $('#main-section').html(template);
				
				// ring_music.pause();
				calling_music.pause();
				//getCallParticipantInfobox($id);
				//alert();
                $('.js-call-court-staff').addClass('in-call')

				jist_stop();

				var template = `
					<div class="card new-card w-100 p-4">
						<div class="mdc-card-wrap">
							<button class="mdc-card mb-0 w-100" id="endCallSession" data-call_id="`+call_id+`">End call</button>
						</div>
					</div>
				`;
				$('#staff-main-section').empty();
				$('#staff-main-section').html(template)
				$('#videoCallDoModal').modal('show')
				staff_jist_start(call_id, registration_info);

			break;
			case "call_rejected":
				callingPopup.close();
				var callee_id = data.data.callee_id
				$('#phone_icon_'+callee_id).show()
				$('#phone_icon_'+callee_id).parent('.btn-dot').find('.js-phone-ringing').hide()
				$('#phone_icon_'+callee_id).parents('.offender-queue').find('.js-missed-call').html('Call Rejected')
				calling_music.pause()
				// alert('call was rejected');
			break;

			case "call_cancelled":

				// alert('call_cancelled');
				calAcceptinPopup.close()
				var caller_id = data.data.caller_id
				$('#phone_icon_'+caller_id).show()
				$('#phone_icon_'+caller_id).parent('.btn-dot').find('.js-phone-ringing').hide()
				$('#phone_icon_'+caller_id).parents('.offender-queue').find('.js-missed-call').html('Missed Call')
				ring_music.pause();
			break;

			case "call_ended":
				$('#phone_icon_'+data.data.caller_id).show()
				$('#phone_icon_'+data.data.caller_id).parent('.btn-dot').find('.js-phone-ringing').hide();

				$('#phone_icon_'+data.data.callee_id).show()
				$('#phone_icon_'+data.data.callee_id).parent('.btn-dot').find('.js-phone-ringing').hide();
				
				if(data.data.user_id != registration_info.user_id) {
				console.log('inside call end')

					return
				}
				jist_stop();
				

				// location.reload();
                $('.js-call-court-staff').removeClass('in-call')
                $('#videoCallDoModal').modal('hide');
				$('.modal-backdrop').remove();
				
				if(localStorage.LS_selected_queue_id !== undefined) {

					// unsubscribe_offender(session_info.offender_staff_session_id);
	                $.get(base_url + "staff/common/current-user-being-served/"+ localStorage.LS_selected_queue_id, function (data) {
	                	// localStorage.setItem('LS_selected_queue_id', userid);
	                	session_info.offender_staff_session_id = data.offender_staff_session_id;
	                	startMyVideo();
	                	// $('#loading-icon').show();
	                	$("#info-box").html(data.offender_detail);
						$('#queue_'+localStorage.LS_selected_queue_id).addClass('active');
	                	
	                	$.get(base_url + "staff/common/show-control", function (data) {
	                		$('#main-section').empty();
	                		$('#main-section').html(data);
	                		
	                		// subscribe_offender(session_info.offender_staff_session_id);
	                		if (data.code == 200) {
	                			$(".message").html(data.message);

	                		} else {
	                			$(".message").html(data.message);
	                		}

	                		if(localStorage.LS_is_video_start === 'false' || localStorage.LS_is_video_start === '') {
								$('#toggleMyVideo').prop("checked", true)
							}

							// if(localStorage.LS_offender_video_start === 'true') {
							// 	$('#toggleOffenderVideo').prop('checked','checked')
							// }
							wasOffenderVideoStarted(session_info.offender_staff_session_id)
	                	});
	                });
	            }
			break;

			
			default:
			
			break;
		}
			}
		
	});
}


/**
* This function unsubscribes the court from websocket connection
* @params {string} user - ID of the court
*/
var unsubscribe_court = function(user){
	user= "staff_"+ user;
	try{
		conn.unsubscribe(user, function(topic, data) {
			// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
			console.log('unsubscribed successfully');
		});
	}catch(e){
		console.log(e.mess());
	}
	
}



// *
//  * @author Sagun Dhakhwa
//  * 
//  * 
//  * "internal_court_".$this->session->userdata('court_id');
//  * 
var subscribe_allusercourt = function(court_id){
	channel= "icourt_system_"+ court_id;
	//console.log("subscribing staff: "+user);
	conn.subscribe(channel, function(topic, data) {
		
		//var data = JSON.parse(data);
		console.log(data.data );

		console.log(data.data.action);
		switch(data.data.action){
			case "ping":
			 //var base_url = '<?= base_url(); ?>';
				pingBack();
			break;			
			
			default:
			
			break;
		}
		
	});
}




// *
//  * @author Sagun Dhakhwa
//  * 
//  * 
//  * "internal_court_".$this->session->userdata('court_id');
//  * 

/**
* This function subscribes the court from websocket connection so that there is a connection between staffs to interact 
* with each other for support/help. Connected staff can get the reponses from other staffs and give their own responses to other staffs.
* @params {string} court_id - ID of the court
*/
var subscribe_support_queue = function(court_id){
	channel= "support_queue_"+ court_id;
	//console.log("subscribing staff: "+user);
	conn.subscribe(channel, function(topic, data) {
		
		//var data = JSON.parse(data);
		console.log(data.data );

		console.log(data.data.action);
		switch(data.data.action){
			case "support_queue_changed":
				showSupportQueue();
			break;	
			case "offender_left":

				alert(data.data.name+ " has left the support session.");
				showSupportQueue();
				location.reload(true);
			break;		
			
			default:
			
			break;
		}
		
	});
}

var joinConference = function (params) {
	console.log("Calling " + params.To+ "...");
	$.post(base_url + "staff/conference-call/joinuser",params, function (data) {
		if (data.status.localeCompare("success") == 0) {
			// var message = atob(data.message);

			// $("#home_section").html(atob(data.message));
			// loadQueue();
			// location.reload(true);
		}

	}, 'json');
}


var connectCall = function(){
	$.getJSON(base_url + "twilio-staff/voice-token")
		.then(function (data) {

			console.log("Token: " + data.token);

			// Setup Twilio.Device
			device = new Twilio.Device(data.token, {
				// Set Opus as our preferred codec. Opus generally performs better, requiring less bandwidth and
				// providing better audio quality in restrained network conditions. Opus will be default in 2.0.
				codecPreferences: ["opus", "pcmu"],
				// Use fake DTMF tones client-side. Real tones are still sent to the other end of the call,
				// but the client-side DTMF tones are fake. This prevents the local mic capturing the DTMF tone
				// a second time and sending the tone twice. This will be default in 2.0.
				fakeLocalDTMF: true,
				// Use `enableRingingState` to enable the device to emit the `ringing`
				// state. The TwiML backend also needs to have the attribute
				// `answerOnBridge` also set to true in the `Dial` verb. This option
				// changes the behavior of the SDK to consider a call `ringing` starting
				// from the connection to the TwiML backend to when the recipient of
				// the `Dial` verb answers.
				enableRingingState: true
			});

			device.on("ready", function (device) {
				console.log("Connected");

			});

			device.on("error", function (error) {
				console.log("Twilio.Device Error: " + error.message);
			});

			device.on("connect", function (conn) {
				console.log("Successfully established call!");
			
				// bindVolumeIndicators(conn);
			});

			device.on("disconnect", function (conn) {
				console.log("Call ended.");
			
			});

			device.on("incoming", function (conn) {
				console.log("Call incomming.");
				conn.accept();
			});

			// setClientNameUI(data.identity);

			// device.audio.on("deviceChange", updateAllDevices.bind(device));

			if (device.audio.isOutputSelectionSupported) {
			}
		})
		.catch(function (err) {
			// var errorr = JSON.stringify(err);
			console.log("error "+err);
		});
}



var startConferences = function (params) {
	console.log("Calling " + params.To + "...");
	console.log("oss_id " + params.oss_id + "...");
	if (device) {
		var outgoingConnection = device.connect(params);
		outgoingConnection.on("ringing", function () {
			// log("plugout");
			// log("Ringing...");
		});
	}
}


var hangups = function (){
	console.log("Hanging up...");
	if (device) {
		// hangup();
		device.disconnectAll();
		$('#offender-queue').hide()
		$('#button-hangups').hide()
		$('#hangup-block').show()
		// $("#list_callers").empty()
		// $('.js-conference', window.parent.document).attr('src', '').empty().hide();
	}
}


// $('.js-hangup-block-yes').on('click', function() {debugger;
// 	console.log("Hanging up...");
// 	if (device) {
// 		// hangup();
// 		device.disconnectAll();
// 		$("#list_callers").empty()
// 		// $('.js-conference', window.parent.document).attr('src', '').empty().hide();
// 	}
// })