Source: invitee_dashboard.js

/**
 * This is an object to store some of the values after invite's dashboard is loaded
 */
var session_info = {
    video_start:0,
    video_started:0,
    offender_staff_session_id: 0,
    current_staff_id : null,
    current_staff_role: null,
    current_staff_title: null,
    staff_changed : false,
    jitsi_offender_staff_sessions_id : null,
    jitsi_registration_info : null,
    jitsi_staff_id : {},   
}

var jisti_api = null;

var toastrOptions = {
    timeOut: 15000,
    closeButton: false,
    positionClass: "toast-bottom-right",
}

/**
* This function shows the success (green) popup message on the screen
* @param {string} message - Success Message
*/
var successToastr = function(message) {
    return;
    toastr.remove()
    toastr.success(message, '', toastrOptions) 
}

/**
* This function shows the information (blue) popup message on the screen
* @param {string} message - Information Message
*/
var infoToastr = function(message) {
    toastr.remove()
    toastr.info(message, '', toastrOptions)
}

/**
* This function shows the error (red) popup message on the screen
* @param {string} message - Error Message
*/
var errorToastr = function(message) {
    toastr.remove()
    toastr.error(message, '', toastrOptions)
}

$(document).ready(function(){
    initAb();
    
    // refresh the current page
    $('.js-refresh').on('click', function(){
        location.reload();
    })


    // When the user scrolls the page, execute myFunction
    // window.onscroll = function() {
    //     var windowWidth = $(window).width();
    //     if(windowWidth < 992) {
    //         roadMapSticky()   
    //     }
    // };

    // // Get the header
    // var header = document.getElementById("stickyHeader");

    // // Get the offset position of the navbar
    // var sticky = header.offsetTop;

    // // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
    // function roadMapSticky() {
    //   if (window.pageYOffset > sticky) {
    //     header.classList.add("sticky");
    //   } else {
    //     header.classList.remove("sticky");
    //   }
    // }

    /**
    * This function sets height of video and main body
    */
    var setVideoHt = function setVideoHt() {
        // var windowWidth = $(window).width();
        // var infoHt = ('.nd-session-time-staff').outerHeight()
        var windowHt = $(window).height();
        var headerHt = $('.navbar.navbar-expand-lg').height();
        var footerHt = $('.mbl-foot').outerHeight();
        var headHt = headerHt + footerHt + 38;
    
        if (windowWidth < 575) {
          if(!$('#navbarSupportedContent').hasClass('show')) {
            $('#test').css('height', windowHt - headHt);
            $('.nd-video-wrap').css('height', windowHt - headHt); // $('#mbl_link').trigger('click')
          }
        }
      }; // Add smooth scrolling to all links
    
    
      $("a#mbl_link").on('click', function (event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
          // Prevent default anchor click behavior
          event.preventDefault(); // Store hash
    
          var hash = this.hash; // Using jQuery's animate() method to add smooth page scroll
          // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    
          $('html, body').animate({
            scrollTop: $(hash).offset().top
          }, 800, function () {// Add hash (#) to URL when done scrolling (default click behavior)
            // window.location.hash = hash;
          });
        } // End if
    
      });
    
      window.onresize = function () {
        var windowWidth = $(window).width()
        if (windowWidth > 576) {
          setVideoHt();
        }
      };
    
      setVideoHt();
});

/**
 *  Current is the main function of this project,
 *  when dashboard is loaded this function is called,
 *  this function loads the roadmap, gets current queue position and renders it in offender's dashboard, loads Plea form and get registration details of the offender
 * 
 */
var current = function(){
    $('body').find('.modal-backdrop').remove()
        getHistory();   /// sagun added
        // findCurrentStaff();
        //getStaffSession();
        //getStaffSessionActivities();
        getRegistrationDetails();
        // getStaffSessionActivitiesUpdate();
}
/**
* to be deleted
* This function takes message as parameter and returns the html template with current time 
*/
var newInfoBox = function(message){
    var date = new Date();
    var Hrs = date.getHours();
    var Min = date.getMinutes();
    var ampm = Hrs >= 12 ? 'PM' : 'AM';
    Hrs = Hrs % 12;
    Hrs = Hrs ? Hrs : 12; // the hour '0' should be '12'
    Hrs = Hrs < 10 ? '0'+Hrs : Hrs; 
    Min = Min < 10 ? '0'+Min : Min;
    var time = Hrs + ':' + Min + ' '+ ampm;
    var template = `<div class="staff-response-box-wrap">
                        <div>
                            <div class="staff-response-box-time">
                                <i class="fa fa-clock-o fa-2x"></i>
                            </div>
                            <p class="sm-font text-center">
                                ${time}
                            </p>
                        </div>
                        <div class="card new-card w-100 ml-2">
                            <h6 class="text-capitalize">
                                ${message}
                            </h6>
                        </div>
                    </div>`;
    return template;
}
/**
* This function handles offender's session with current staff and unsubscribe session with the previous staff
*/
var findCurrentStaff = function(){
    // alert('-------');
    $.get(base_url+ "offender/current", function(data){
        if(data.status=="failed"){
            getCaseStatus();
            var mess = 'The case has been closed. You will receive a confirmation email with copies of all signed documents';
            // $('#first-queue-position').html("<div class='nd-queue-msg'><h5>"+mess+"</h5></div>");
            var date = new Date();
            var Hrs = date.getHours();
            var Min = date.getMinutes();
            var time = Hrs + ':' + Min;
            var template = `<div class="staff-response-box-wrap">
                                <div>
                                    <div class="staff-response-box-time">
                                        <i class="fa fa-clock-o fa-2x"></i>
                                    </div>
                                    <p class="sm-font text-center">
                                        ${time}
                                    </p>
                                </div>
                                <div class="card new-card w-100 ml-2">
                                    <h6>
                                        ${mess}
                                    </h6>
                                </div>
                            </div>`;
            
            // $('#offender_content').html(template);
            // $('#offender_content').html("<div class='card new-card w-auto'><h5>"+mess+"</h5></div>");
			// $('#offender_content').html('');
            // Todo redirect to status check screen;
            return;   
        }      
       
        if(session_info.current_staff_id == data.staff_id){
            session_info.staff_changed = false;
            
        }else{ /// if staff attending the offender changes then only we will unsubscribe or subscribe 
            //console.log('New session being started with a different staff '+ data.staff_slug);
            infoToastr('You are now on a queue to the '+ data.staff_slug);
            session_info.staff_changed = true;
            if(session_info.current_staff_id!=null){
                try{                    
                    unsubscribe(session_info.current_staff_id);

                    if(session_info.judges_clerk_id!= null){
                        unsubscribe(judges_clerk_id); /// need to unsubscribe
                    }
                }catch(err){
                    console.log(err);
                }       
            }    
            session_info.current_staff_id = data.staff_id;  
            session_info.judges_clerk_id = data.judges_clerk_id;

            var current_video_session = 'Session with ' +data.staff_title;
            session_info.current_staff_role = data.staff_slug;
            session_info.current_staff_title = data.staff_title;
            //alert(data.staff_slug);
           
            localStorage.setItem('LS_staff_id',data.staff_id);
            
            subscribeStaff(data.staff_id); /// need to unsubscribe

            if(data.judges_clerk_id!= null){
                subscribe(data.judges_clerk_id); /// need to unsubscribe
            }
            $('#current-video-session').html("<div class='js-video-icon-toggle'><i class='fa fa-video-camera mr-2'></i> "+data.staff_title+"</div>")

            $('#first-queue-position').html("");
            
        }
         //wait will be called
         //alert("session_info.staff_changed inside find current Staff"+session_info.staff_changed);
        wait(data.staff_slug);
    },"json");
}


/**
* 
* This function handles the session with currently subscribed staff, auto starts the invite staff's video if the video session was previously started when the page is reloaded, and updates the offender's queue information  
*/
var wait = function(slug){   
    alert('wait called');
    
    return ; //to be deleted
	$.get(base_url+ "offender/queue-position", function(data){   
        console.log('queue-position in wait');
        console.log(data.staff_id);
        var notify_music = document.getElementById('queue_position_music');
        // notify_music.play();
        var staff_id = data.staff_id;
        if(data.position === 1) {
            //$('#first-queue-position').html("<div class='mb-4'><div class='p-3 alert alert-info'><h4>You are now in first position in the queue.</h4></div></div>")
        }
        session_info.offender_staff_session_id = data.offender_staff_session_id;  

        //alert(data.helps_plea);
        if((data.helps_plea == true) ){
            // loadPDSuggestionForm();
            // alert('---');
        }else{
            // hidePDSuggestionForm();
        }
        
        $('.js-centered-img-wrap').hide();
        $("#first-queue-position").html(render_queue_counter(data));
        console.log(data);  

        $.get(base_url+ 'offender/get-session-id', function(data){

            alert('asdffds');
            switch(data.status){
                case "success":
                    var offender_staff_sessions_id = data.code;
                    subscribeSession(offender_staff_sessions_id);
                    localStorage.setItem('LS_offender_staff_sessions_id', offender_staff_sessions_id);

                    localStorage.setItem('LS_registration_info', JSON.stringify(registration_info));

                    jist_start( offender_staff_sessions_id,registration_info,staff_id)
                    // localStorage.setItem('LS_staff_id', data.staff_id);  
                    // alert(session_info.video_started);
                    // if(session_info.video_started){
                    //     $('.new_join_video').trigger('click');
                    // }
                    
                    // getInviteStaffSessionActivities(); 
                    break;
                case "error":
                    break;
            }
            

        },"json");
        //session_info.offender_staff_session_id = data.offender_staff_session_id;  
        
        if(data.position === 1 ){ // waiting in the queue
                       
            // $('.js-centered-img-wrap').show();
            console.log("communicating with staff: ");
            console.log (data.staff_id);
            
            $.get(base_url+ 'offender/natural/getStaffDetail/'+data.staff_id, function(re){
                console.log(re.staff_type_title);          
                //var resp = 'It is your turn to have a session with the '+re.staff_type_title;

                ///$('#first-queue-position').append("<div class='nd-queue-msg'><h5>"+resp+"</h5></div>");

                //infoToastr("session_info.staff_changed");

            },"json");
         
        }  
        
    },"json");
	

}


/**
* This function displays the queue information such as queue position and current staff type with whome offfender is waiting
* @param {string} data - Queue data such as staff's id, staff's type, and queue position
*/
var render_queue_counter = function(data){	
    alert('render_ queue_counter');
    console.log('data queue', data)
    localStorage.setItem('LS_staff_id', data.staff_id)
    // var output = '<div class="nd-first-queue" id="waiting-info"> <p class="mb-2 sm-font">You are now waiting for the '+data.staff_role+'</p><hr><p class="mb-2 sm-font">Here is your position in the waiting queue:</p><div class="queue-position-box"><h1 class="mb-0"># '+data.position+'</h1></div><h5>Estimated Waiting Time:  <span id="queue_time">'+(data.position*1)+'</span> mins</span></h5></div>';
    

    var output = '<div class="nd-first-queue" id="waiting-info"> <p class="mb-2 new-sm-font">You have an active session with '+data.staff_role+'</p><hr><p class="mb-2"></p><div class="queue-position-box"><h1 class="mb-0">A</h1></div></div>';
	return output;
}

//"1"+"0002"
/**
* This function starts the video session and hides the content of queue information
*/
var jist_start = function(offender_staff_sessions_id, registration_info, staff_id){
    stopVideoPreview();
    console.log('jisti start');
    
    console.log('registration_info',registration_info)
    if(offender_staff_sessions_id == null){
        return;
    }
    
    $('.nd-queue-msg').hide('')
    $('#loading-icon').show();
    // $('.js-centered-img-wrap').show();
    $('#video-preview').hide();
    var video_music = document.getElementById('video_start_music');
    $('#test').find('iframe').remove()
	var container = document.querySelector('#test');
	
	console.log(registration_info.jwt + "----jwt");
    var jisti_room =  "ROOM"+offender_staff_sessions_id;
    
    $('.new_stop_video').show()
    $('.new_join_video').hide()
	var options = {
		"roomName":jisti_room,
        "parentNode": container,
        "jwt": registration_info.jwt,
		userInfo: {
			canmute : false,
			canmutevideo :false,
			displayName: registration_info.user_name
		},
		"width": "100%",
        "height": "100%",
        interfaceConfigOverwrite: {
            filmStripOnly: false,
            DISABLE_DOMINANT_SPEAKER_INDICATOR: false,
        },
        configOverwrite: {
          disableRemoteMute: true,
          remoteVideoMenu: {
            disableKick: true
          },
        },
        onload: function(){
            console.log('jitsi load')
            
            session_info.video_started = true;      
            $('.new_join_video').hide()
            $('.new_stop_video').show()
            $('#loading-icon').hide();
            $('.js-centered-img-wrap').hide();
            $('#first-queue-position').hide()

    //         $.get(base_url+ 'offender/natural/getStaffDetail/'+staff_id, function(re){
    //             var mess = 'You are now having a video session with the '+re.staff_type_title;
    //             // $('#first-queue-position').html("<div class='mb-4'><div class='p-3 alert alert-info'><h4>"+mess+"</h4></div></div>");
				// infoToastr(mess)

    //             // $('.js-video-icon-toggle').addClass('active js-start-my-video cursor-pointer').attr('title', 'Start My Video')
    //             // $('#join_stop_video').show().attr('title', 'Stop My Video').html('Stop').addClass('active')
                
                
    //         },"json");
            
        },
	};
    jisti_api = new JitsiMeetExternalAPI(registration_info.jitsi_url, options);
    //jisti_api.executeCommand('toggleTileView');
    jisti_api.executeCommand('subject', ' ');
    session_info.video_start = 1;
    //$("#start").hide();
    

    /*
    jitsi_offender_staff_sessions_id = offender_staff_sessions_id  
    jitsi_registration_info = registration_info
    jitsi_staff_id = staff_id
    localStorage.setItem('LS_offender_staff_sessions_id', offender_staff_sessions_id);
    localStorage.setItem('LS_registration_info', JSON.stringify(registration_info));
    localStorage.setItem('LS_staff_id', staff_id);

    */
};

/**
* This function stops the video session and shows the content of queue information
*/
var jist_stop = function(){
    startVideoPreview();
    console.log('jitsi stop');
    
    //$("#start").html("");
    if(jisti_api!=null){
        jisti_api.executeCommand("hangup");
        // infoToastr('Closing video session ...');
        $('#test').html('')
        $('#test').html('<div class="js-centered-img-wrap">'+
            '<img src="'+video_icon_url+'" alt="iCourt loading" class="centered-video-img">'+
        '</div><div class="new_join_video" style="" title="Join Video Session">Join</div>');

        // $('.js-centered-img-wrap').show();
        session_info.video_started = false;
    }
    
    $('.js-video-icon-toggle').removeClass('active')
    $('#loading-icon').hide();
    // $('.js-centered-img-wrap').hide()
    $('.nd-queue-msg').show()
    $('#video-preview').show()
    $('#first-queue-position').show()

   
    $('.new_stop_video').hide()
    $('.new_join_video').show()
    $('.js-centered-img-wrap').show()
		
}


// *
//  * @method recieve call from other staffs when in invited mode
//  * 
//  * internal staff video call
//  * 
//  * 

/**
* This function starts the internal staff's video session
*/
var staff_jist_start = function (offender_staff_sessions_id, staff_info) {
    console.log('jisti session being started' + staff_id + "::" + registration_info.user_id);
    // infoToastr('success', 'Jisti session being started ')
    //infoToastr('initiating video')
    $('#staff_video').empty();
    $('#staff-loading-icon').show();
    var video_music = document.getElementById('staff_video_start_music');
    video_music.volume = 0.2;
    video_music.play();
    var container = document.querySelector('#staff_video');

    console.log(registration_info.jwt);

    //var domain = "jitsi1.outlines-rnd.com/";
    //var domain = "3.235.252.250:8443";
    //if(caseno ==""){alert("invalid case no"); return;}
    console.log(staff_info.user_id);
    var jisti_room = "INTERNAL STAFF ROOM" + offender_staff_sessions_id;
    console.log(jisti_room + "room");
    var options = {
        "roomName": jisti_room,
        "parentNode": container,
        "jwt": registration_info.jwt,
        userInfo: {
            canmute: false,
            canmutevideo: false,
            displayName: staff_info.user_name
        },
        interfaceConfigOverwrite: {
            filmStripOnly: false,
            DISABLE_DOMINANT_SPEAKER_INDICATOR: false,
        },
        configOverwrite: {
          disableRemoteMute: true,
          remoteVideoMenu: {
            disableKick: true
          },
        },
        onload: function(){
            session_info.jitsi_started = 1;
            $('#staff-loading-icon').hide();
        },
        "width": "100%",
        "height": "100%"
    };

    //alert(registration_info.jitsi_url);
    api = new JitsiMeetExternalAPI(registration_info.jitsi_url, options);
    
    api.executeCommand('subject', ' ');
    // api.executeCommand('toggleTileView');
    $("#start").hide();
};
/**
* This function stops the video session whenever staff ends the session with the offender
*/
jist_close = function(){
    if(jisti_api!=null){
        jisti_api.executeCommand("hangup");
        // infoToastr('Closing video session ...');
        $('#test').html('')
        $('#test').html('<div class="js-centered-img-wrap">'+
            '<img src="'+video_icon_url+'" alt="iCourt loading" class="centered-video-img">'+
        '</div>');

        // $('.js-centered-img-wrap').show();
        session_info.video_started = false;
    }
}

// to be deleted
var getStaffResonse = function(staff_id){
   //alert(atob(data.message));
    
	$.get(base_url+ "offender/staff-response/"+staff_id, function(data){
        //alert(atob(data.status));
        console.log("data.status="+data.status);
        //infoToastr('Getting response from staff')
        switch(data.status){
            case "success":
                // $("#offender_content").html(atob(data.message));
                $('.js-offender_content').html(atob(data.message))
            break;
            case "fail":
                
            break;
        }
        // $("#offender_content").html(atob(data.message));

        
        var roadMapHt = $('#my-roadmap').height()
        var roadMapAvailableHt = roadMapHt - 170
        $('.new-scrolling-table-wrap').css('max-height', roadMapAvailableHt+'px')
    },"json");
}

// var updateInviteVariable = function(){
// 	$.get(base_url+ "invitee-update-session", function(data){
       

           
//     },"json");
// }

/**
* This function redirects from invitee's dashboard to staff's dashboard
*/
var updateInvitee = function(){
	$.post(base_url+ "staff/update-invite", function(data){
        if (data.status.localeCompare("success") == 0) {
            window.location.replace(base_url + "staff/common/main"); 

        }        
    },"json");
}

/**
* This function handles the leave button in invitee dashboard. It will redirect the staff from invitee dashboard to staff's own dashboard
*/
$(document).on('click', '#invite_leave', function () {
    $.post(base_url+ "staff/invite-leave", function(data){
        if (data.status.localeCompare("success") == 0) {
            window.location.replace(base_url + "staff/common/main"); 

        }        
    },"json");

    
});






// var submitPromation = function(){

//     var _this = $(this)

//     var form = $('#offender_probation_sign')[0];

//     // Create an FormData object
//     var formData = new FormData(form);
   
   
//     $.ajax({
//         type: 'POST',
//         url:$("#offender_probation_sign").attr('action'),
//         data: formData,
//         dataType: 'json',
//         contentType: false,
//         cache: false,
//         processData:false,
//         beforeSend: function(){
            
//         },
//         success: function(response){ 

//             switch(response.status){

//                 case "success":
//                     getLegalDocuments();

//                     _this.parents('.modal').modal('hide');
//                     $('.modal-backdrop').remove();
                
//                     //$("#offender_content").html(atob(response.message));

//                     infoToastr(atob(response.message));
//                 break;
//                 case "validation_failed":
//                     _this.parents('.modal').modal('hide');
//                     $('.modal-backdrop').remove();
//                     //infoToastr('Validation error occured');
//                 break;
//                 case "error":
//                     _this.parents('.modal').modal('hide');
//                     $('.modal-backdrop').remove();
//                     //infoToastr(atob(response.message));
//                 break;


//             } 
//             $('#clerk_compliance_form').css("opacity","");
//             $('.modal').remove();
           
//         }
//     });
// }

var  changeFirstQueuePosition= function(mess){
    $('#first-queue-position').html("<div class='nd-queue-msg'><h5>"+mess+"</h5></div>");
}

var  getCaseStatus =  function(){
    // get case implementation. 
    // this functi


}

// view details from road map
$(document).on('click', '.js-get-roadmap-details', function() {
    var _this = $('.nd-toggle-view')        
    var staffTitle = $(this).data('title')
    var id = $(this).data('id')
    if(_this.find('.active').hasClass('js-view-list')) {

        document.querySelector('.'+staffTitle).scrollIntoView({ behavior: 'smooth' });
    }
    else {
        $('#staff_data').empty();

        if(id === 0) {
            $('#staff_data').append('<div class="js-registration-info"></div>');
            getRegistrationDetails();   
        }
        else {
            $('#staff_data').append('<div class="js-offender_content"></div>');
            getStaffResonse(id)
        }
    }
})

$(document).on('click', '.js-view-list', function() {

    $('.nd-toggle-view').find('.active').removeClass('active')
    $('.nd-toggle-view .nd-hearing-date-title').addClass('active')
    $('.js-view-legal-doc-block').hide()
    $('.js-list-view-block').show()
})

$(document).on('click', '.js-view-staff', function() {

    $('.nd-toggle-view').find('.active').removeClass('active')
    $('.nd-toggle-view .nd-hearing-date').addClass('active')
    $('.js-staff-view-block').show()
    $('.js-list-view-block').hide()
    getStaffResonse(session_info.current_staff_id)
})

$(document).on('click', '.js-view-legal-doc', function() {
    $('.nd-toggle-view').find('.active').removeClass('active')
    $('.nd-toggle-view .nd-hearing-date').addClass('active')
    $('.js-view-legal-doc-block').show()
    $('.js-list-view-block').hide()
    getLegalDocuments()
    // getStaffResonse(session_info.current_staff_id)
})

var getRegistrationDetails = function(){
    $.get(base_url+ "offender/getRegistrationDetails", function(data){
        console.log(data)
      $('.js-registration-info').html(atob(data.message))
        
          
    },"json");
}

// open new window for case summary
$(document).on('click', '.js-case-summary', function(e) {
    e.preventDefault();
    var caseId = $(this).data('id')
    var myWindow = window.open(base_url+"welcome/case_summary/"+caseId+"/no", "", "width='auto',height='auto',directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0");
})

// open new window for support
$(document).on('click', '.call-help-wrap', function(e) {
    e.preventDefault();
    var caseId = $(this).data('id')

    var pageURL = base_url+"offender/support" ;
    var pageTitle = "iCourtApp::Support";        
    var myWindow = newWindow.createPopupWin(pageURL, pageTitle, 800, 525);
})

// open new window for invite my lawyer
$(document).on('click', '.js-invite-lawyer', function(e) {
    e.preventDefault()
    // $('#inviteLawyerModal').modal('show');

    var pageURL = base_url+"offender/invite-lawyer" ;
    var pageTitle = "iCourtApp::Invite My Lawyer";        
    var myWindow = newWindow.createPopupWin(pageURL, pageTitle, 800, 525);
})


// form submission from new window for invite my lawyer
$(document).on('click', '#offender_invite_my_lawyer', function() {
    //function to be implemented
})

// new window for opening the payment url
var openFineUrl = function(fineUrl) {
    var pageTitle = "iCourtApp::Fine";     
    var newmyWindow = newWindow.createPopupWin(fineUrl, pageTitle, 'auto', 'auto');
}

// $(document).on('click', '.js-start-my-video', function() {

//     alert('asdfdasf');
//     jist_start(jitsi_offender_staff_sessions_id, jitsi_registration_info, jitsi_staff_id);
// })

$(document).on('click', '.new_stop_video', function() {
    jist_stop();
})


$(document).on('click', '.new_join_video', function() {
    if(localStorage.LS_offender_staff_sessions_id != ''){
        /*
        localStorage.setItem('LS_registration_info', JSON.stringify(registration_info));
        localStorage.setItem('LS_offender_staff_sessions_id', offender_staff_sessions_id);
        localStorage.setItem('LS_staff_id', invited_by);

        */
        
        jist_start(localStorage.LS_offender_staff_sessions_id, JSON.parse(localStorage.LS_registration_info), localStorage.LS_staff_id);

        $('.new_stop_video').show()
        $('.new_join_video').hide()
    }else{

        alert('Local storage is empty');
    }
})

$(document).on('click', '#endCallSession', function(){
    var call_id = $(this).data('call_id');
    $.get(
        base_url + "staff/end-call/"+call_id,
        function (data) {
            console.log(data);
            jist_stop();
            // location.reload();
            $('#videoCallDoModal').modal('hide');
            $('.modal-backdrop').remove();
            $('.js-call-court-staff').removeClass('in-call')
            $('#phone_icon_'+call_id).parent('.btn-dot').find('.js-phone-ringing').hide();
        },
    'json');    
})

$('.js-refresh-staff-action').on('click touchstart', function() {
    $('#offender-action-message').empty()
    getInviteStaffSessionActivities();
    // alert('click')
})



var calAcceptinPopup;  
var ring_music;


/**
 * @author Sagun Dhakhwa
 * 
 * 
 * "internal_court_".$this->session->userdata('court_id');
 * */
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 "request_to_join_a_session":
                // alert('-------------------');
                //console.log(data.data.staff);
                if(data.data.invited_by == registration_info.staff_id) return;
                if(data.data.user_id != registration_info.staff_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">
                            <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.staff_id) return;
                if(data.data.user_id != registration_info.staff_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.staff_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.staff_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.staff_id) {
                    return
                }
                jist_stop();
                

                // location.reload();
                $('.js-call-court-staff').removeClass('in-call')
                $('#videoCallDoModal').modal('hide');
                $('.modal-backdrop').remove();
                
                // 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);
                        }
                    });
                });
            break;

            
            default:
            
            break;
        }
            }
        
    });
}

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());
    }
    
}

$('.js-foot-documents').on('click touchstart', function (e) {
    var _this = $(this);
  
    if (!_this.hasClass('active')) {
      if (!$(e.target).hasClass('js-refresh-staff-action')) {
        $('#offender-action-message').empty();
        $('#offender-activity-msg').empty();
        $('.activity_counter').html('');
        getInviteStaffSessionActivities();
  
        _this.parent('.mbl-foot').find('.active').removeClass('active');
  
        _this.addClass('active');
  
        $('#offender-action-message').addClass('js-mbl-doc-wrap'); // var windowHt = $(window).height();
        $('#offender-activity-msg').addClass('js-mbl-doc-wrap');
        var headerHt = $('.navbar.navbar-expand-lg').height();
        var footerHt = $('.mbl-foot').outerHeight();
        var VideoHt = $('#test').outerHeight();
        var topHt = headerHt + footerHt;
        var windowWidth = $(window).width()
        if(windowWidth < 992) {
            $('#offender-action-message.js-mbl-doc-wrap').css('top', topHt).css('min-height', VideoHt);
            $('#offender-activity-msg.js-mbl-doc-wrap').css('top', topHt).css('min-height', VideoHt); // $('#mbl_link').trigger('click') 
        }

        $('.js-dark-img').hide();
        $('.js-white-img').show();
        $('#no-form').show();
        $('#no-activity').css('top', topHt);
        $('#no-form').css('top', topHt);
      }
    }
  }); // $(document).on('click', '.js-foot-video', function() {
  
  $('.js-foot-video').on('click touchstart', function () {
    var _this = $(this);
  
    if (!_this.hasClass('active')) {
      _this.parent('.mbl-foot').find('.active').removeClass('active');
  
      _this.addClass('active');
  
        $('#offender-action-message').empty();
        $('#offender-activity-msg').empty();
      $('#offender-action-message').removeClass('js-mbl-doc-wrap');
      $('#offender-activity-msg').removeClass('js-mbl-doc-wrap');
      popUpHandler.closeIframe();
      $('.js-white-img').hide();
      $('.js-dark-img').show();
      $('#no-form').hide();
      $('#no-activity').hide();
    }
  });  

  $('.js-refresh-staff-action').on('click touchstart', function () {  
    // getStaffSessionActivities();
    $.get(base_url + "invitee-allStaffActivities", function (data) {
      console.log("data.status=" + data.status);
      switch (data.status) {
        case "success":
          $('#offender_content').html('<div class="js-staff-res-block"></div>');
          $('#offender-action-message').empty();
        $('#offender-activity-msg').empty();
        StaffAction.updateDOM(data.activities, "all");
          break;
  
        case "fail":
          break;
      }
    }, "json");
  });