var live_kit_video_client = null;
var isVideoChatActive = false;
video_chat_available = true;
var localTracks = [];
var localParticipantContainer;
var audio_only_chat = false;
var preferredMicId;
var preferredCamId;
var currentCamId;
var currentMicId;
var mic_mute_on_load = false;

var videochat_GridContainer = $('#video-chat-grid');
var video_chat_formData = new FormData();

$("body").on("click", ".main .middle > .video_chat_interface > .video_chat_container .toggle_chat_window", function(e) {
    $('.main .middle > .video_chat_interface').toggleClass('show_chat_window');
});

$("body").on("click", ".main .middle > .video_chat_interface > .video_chat_container .leave_video_call", function(e) {
    if (isVideoChatActive) {
        exit_video_chat();
    }
});

$("body").on("click", ".main .chatbox .join_video_call", function(e) {

    if ($('.call_notification').length > 0) {
        if (!$('.call_notification .call_ringtone')[0].paused) {
            $('.call_notification .call_ringtone')[0].pause();
            $('.call_notification .call_ringtone')[0].currentTime = 0;
        }
    }

    video_chat_formData = new FormData();
    video_chat_formData.append('add', 'video_chat');

    if ($(".main .chatbox").attr('group_id') !== undefined) {
        video_chat_formData.append('group_id', $(".main .chatbox").attr('group_id'));
        current_video_chat_type = 'group';
        current_video_chat_id = $(".main .chatbox").attr('group_id');
    } else if ($(".main .chatbox").attr('user_id') !== undefined) {
        video_chat_formData.append('user_id', $(".main .chatbox").attr('user_id'));
        current_video_chat_type = 'private_chat';
        current_video_chat_id = $(".main .chatbox").attr('user_id');
    } else {
        console.log('Error : Failed to fetch conversation info');
        return;
    }

    $('.main .video_chat_container>.icons>span.toggle_video_call_mic').show();

    mic_mute_on_load = false;

    if (system_variable('push_to_talk_feature') === 'enable') {

        if ($(".main .chatbox").attr('group_id') !== undefined) {
            $('.toggle_push_to_talk').removeClass('active d-none');
            $('.main .video_chat_container>.icons>span.toggle_video_call_mic').hide();
            mic_mute_on_load = true;
        } else {
            $('.toggle_push_to_talk').addClass('d-none');
            $('.main .video_chat_container>.icons>span.toggle_video_call_mic').show();
        }
    }

    if ($(this).attr('audio_only') !== undefined && $(this).attr('audio_only') === 'yes') {
        video_chat_formData.append('audio_only', true);
        $('.main .video_chat_container>.icons>span.toggle_video_call_camera').hide();
        $('.main .video_chat_container>.icons>span.toggle_screen_share').hide();
    } else {
        $('.main .video_chat_container>.icons>span.toggle_video_call_camera').show();
        $('.main .video_chat_container>.icons>span.toggle_screen_share').show();
    }

    if (user_csrf_token !== null) {
        video_chat_formData.append('csrf_token', user_csrf_token);
    }

    if (user_login_session_id !== null && user_access_code !== null && user_session_time_stamp !== null) {
        video_chat_formData.append('login_session_id', user_login_session_id);
        video_chat_formData.append('access_code', user_access_code);
        video_chat_formData.append('session_time_stamp', user_session_time_stamp);
    }

    $('.main .middle > .video_chat_interface > .video_chat_container > .video_chat_grid').html('');
    $('.video_chat_container > .video_chat_full_view').html('');
    $('.main .middle > .video_chat_interface').removeClass('d-none');
    $('.call_notification').addClass('d-none');

    if ($(this).attr('audio_only') !== undefined && $(this).attr('audio_only') === 'yes') {
        $('.main .middle > .video_chat_interface').addClass('audio_only_chat');
        audio_only_chat = true;
    } else {
        audio_only_chat = false;
        $('.main .middle > .video_chat_interface').removeClass('audio_only_chat');
    }

    if (isVideoChatActive) {
        exit_video_chat();
    } else {

        if ($('.main .chatbox').attr('user_id') !== undefined) {
            current_video_caller_id = $('.main .chatbox').attr('user_id');
        }

        initilazing_video_chat();
        create_video_chat();
    }
});

$("body").on("click", ".main .middle > .video_chat_interface > .video_chat_container .toggle_video_call_camera", function(e) {

    if (!live_kit_video_client) {
        return;
    }

    if (!isVideoChatActive) {
        return;
    }

    localTracks.forEach(function (track) {
        if (track.kind === 'video') {

            if (track.isMuted) {
                track.unmute();
            } else {
                track.mute();
            }
        }
    });


    if ($(this).find('.cam_disabled').hasClass('d-none')) {
        live_kit_video_client.localParticipant.setCameraEnabled(false);
    } else {
        live_kit_video_client.localParticipant.setCameraEnabled(true);
    }

    if ($(this).find('.cam_disabled').hasClass('d-none')) {
        $(this).find('.cam_not_disabled').addClass('d-none');
        $(this).find('.cam_disabled').removeClass('d-none');
    } else {
        $(this).find('.cam_disabled').addClass('d-none');
        $(this).find('.cam_not_disabled').removeClass('d-none');
    }

});

$("body").on("click", ".main .middle > .video_chat_interface > .video_chat_container .toggle_video_call_mic", function(e) {

    if (!live_kit_video_client) {
        return;
    }

    if (!isVideoChatActive) {
        return;
    }

    localTracks.forEach(function (track) {
        if (track.kind === 'audio') {

            if (track.isMuted) {
                track.unmute();
            } else {
                track.mute();
            }
        }
    });

    if ($(this).find('.mic_muted').hasClass('d-none')) {
        live_kit_video_client.localParticipant.setMicrophoneEnabled(false);
    } else {
        live_kit_video_client.localParticipant.setMicrophoneEnabled(true);
    }

    if ($(this).find('.mic_muted').hasClass('d-none')) {
        $(this).find('.mic_not_muted').addClass('d-none');
        $(this).find('.mic_muted').removeClass('d-none');
    } else {
        $(this).find('.mic_muted').addClass('d-none');
        $(this).find('.mic_not_muted').removeClass('d-none');
    }

});

$("body").on("click", ".main .middle > .video_chat_interface > .video_chat_container .toggle_screen_share", function(e) {

    if (!live_kit_video_client) {
        return;
    }

    if (!isVideoChatActive) {
        return;
    }

    if ($(this).find('.share_user_screen').hasClass('d-none')) {
        stop_share_device_screen();
        $(this).find('.stop_screen_share').addClass('d-none');
        $(this).find('.share_user_screen').removeClass('d-none');
        $('.main .video_chat_container>.icons>span.toggle_video_call_camera').show();
    } else {
        share_device_screen();
        $(this).find('.share_user_screen').addClass('d-none');
        $('.main .video_chat_container>.icons>span.toggle_video_call_camera').hide();
        $(this).find('.stop_screen_share ').removeClass('d-none');
    }

});


function exit_video_chat() {

    total_vc_users = live_kit_video_client?.remoteParticipants?.size || 0;

    $('.main .middle > .video_chat_interface').addClass('d-none');

    $('.toggle_push_to_talk').removeClass('active');
    $('.toggle_push_to_talk').addClass('d-none');

    $('.toggle_video_call_mic .mic_muted').addClass('d-none');
    $('.toggle_video_call_mic .mic_not_muted').removeClass('d-none');

    $('.toggle_screen_share .stop_screen_share').addClass('d-none');
    $('.toggle_screen_share .share_user_screen').removeClass('d-none');

    $('.toggle_video_call_camera .cam_disabled').addClass('d-none');
    $('.toggle_video_call_camera .cam_not_disabled').removeClass('d-none');

    leaveChannel();
    stop_update_video_chat_status();
    current_video_chat_type = current_video_chat_id = null;
}

function leaveChannel() {

    if (!isVideoChatActive) {
        return;
    }

    if (live_kit_video_client) {
        live_kit_video_client.disconnect();
        live_kit_video_client = null;
    }
    localTracks.forEach(function (track) {
        track.stop();
    });
    localTracks = [];
    if (localParticipantContainer !== undefined && localParticipantContainer) {
        localParticipantContainer.remove();
    }

    videochat_GridContainer.innerHTML = '';
    $('.video_chat_container > .video_chat_full_view').html('');

    isVideoChatActive = false;
}

async function checkWebcamAndPermission() {
    try {
        var devices = await navigator.mediaDevices.enumerateDevices();
        var hasWebcam = devices.some(device => device.kind === 'videoinput');

        if (!hasWebcam) {
            return false;
        }

        try {
            var stream = await navigator.mediaDevices.getUserMedia({
                video: true
            });
            stream.getTracks().forEach(track => track.stop());
            return true;
        } catch (error) {
            return false;
        }
    } catch (error) {
        return false;
    }
}


async function checkMicrophonePermission() {
    try {
        var devices = await navigator.mediaDevices.enumerateDevices();
        var hasMicrophone = devices.some(device => device.kind === 'audioinput');

        if (!hasMicrophone) {
            return false;
        }

        try {
            var stream = await navigator.mediaDevices.getUserMedia({
                audio: true
            });

            stream.getTracks().forEach(track => track.stop());
            return true;
        } catch (error) {
            return false;
        }
    } catch (error) {
        return false;
    }
}



function add_livekit_participant(participant, track) {

    if (track.kind === 'video' || track.kind === 'audio') {

        var participant_identifier = participant.identity;

        if ($('.participant-container[user_identity="'+participant_identifier+'"]').length > 0) {

            if (track.kind === 'video' && $('.participant-container[user_identity="'+participant_identifier+'"] > video').length > 0) {
                $('.participant-container[user_identity="'+participant_identifier+'"]').find('video').remove();
            }
            var mediaElement = track.attach();
            $('.participant-container[user_identity="'+participant_identifier+'"]').append(mediaElement);
        } else {

            var participantContainer = $('<div></div>')
            .addClass('participant-container')
            .attr({
                "user_identity": participant_identifier,
                "user_sid": participant.sid
            });

            var mediaElement = track.attach();
            participantContainer.append(mediaElement);

            videochat_GridContainer.append(participantContainer);

            fetch_user_info(participant.identity).then(function (userData) {
                var participantUsername = userData.username;

                var group_attribute = '';

                if ($(".main .chatbox").attr('group_id') !== undefined) {
                    group_attribute = 'data-group_identifier="'+$(".main .chatbox").attr('group_id')+'"';
                }

                $('.participant-container[user_identity="'+participant_identifier+'"]').append('<span '+group_attribute+' class="participant_name get_info" user_id="'+participant.identity+'">@' + participantUsername + '</span>');

                if (audio_only_chat) {
                    $('.participant-container[user_identity="'+participant_identifier+'"]').append('<span class="participant_img"><img src="'+userData.image+'"/></span>');
                }
            }).catch(function (error) {
                console.log(error);
                $('.participant-container[user_identity="'+participant_identifier+'"]').append('<span class="participant_name">@'+participant.identity+'</span>');
            });

        }
    }
}


async function share_device_screen() {

    try {
        var screen_share_tracks = await live_kit_video_client.localParticipant.createScreenTracks({
            audio: true,
        });

        screen_share_tracks.forEach((track) => {
            live_kit_video_client.localParticipant.publishTrack(track);
        });

        if ($('.main .middle > .video_chat_interface > .video_chat_container').hasClass('full_view_container')) {
            if ($('.video_chat_container.full_view_container > .video_chat_full_view > div').length > 0) {
                $('.video_chat_container.full_view_container > .video_chat_full_view > div').appendTo('.main .middle > .video_chat_interface > .video_chat_container > .video_chat_grid');
            }

            $('.main .middle > .video_chat_interface > .video_chat_container').removeClass('full_view_container');
        }

        localParticipantContainer.find('video').remove();
        var localVideoElement = screen_share_tracks.find(track => track.kind === 'video').attach();
        localParticipantContainer.append(localVideoElement);
    } catch (error) {
        console.error('Error sharing screen share:', error);

        $('.main .video_chat_container .toggle_screen_share .stop_screen_share').addClass('d-none');
        $('.main .video_chat_container .toggle_screen_share .share_user_screen').removeClass('d-none');
        $('.main .video_chat_container>.icons>span.toggle_video_call_camera').show();
    }
}

async function stop_share_device_screen() {

    try {
        live_kit_video_client.localParticipant.setScreenShareEnabled(false);
    } catch (error) {
        console.error('Error stopping screen share:', error);
    }

    if ($('.main .middle > .video_chat_interface > .video_chat_container').hasClass('full_view_container')) {
        if ($('.video_chat_container.full_view_container > .video_chat_full_view > div').length > 0) {
            $('.video_chat_container.full_view_container > .video_chat_full_view > div').appendTo('.main .middle > .video_chat_interface > .video_chat_container > .video_chat_grid');
        }

        $('.main .middle > .video_chat_interface > .video_chat_container').removeClass('full_view_container');
    }

    var cam_permissionGranted = await checkWebcamAndPermission();

    var mic_permissionGranted = await checkMicrophonePermission();

    var local_video_tracks = await live_kit_video_client.localParticipant.createTracks({
        audio: mic_permissionGranted, video: cam_permissionGranted
    });

    local_video_tracks.forEach((track) => {
        live_kit_video_client.localParticipant.publishTrack(track);
    });

    localParticipantContainer.find('video').remove();

    if (cam_permissionGranted) {
        var localVideoElement = local_video_tracks.find(track => track.kind === 'video').attach();
        localParticipantContainer.append(localVideoElement);
    }
}

async function getPreferredCamera() {
    const devices = await navigator.mediaDevices.enumerateDevices();
    const cameras = devices.filter(device => device.kind === "videoinput");

    if (cameras.length === 0) {
        console.log("No cameras found!");
        return null;
    }

    if (currentCamId) {
        const matchedCam = cameras.find(cam => cam.deviceId === currentCamId);
        if (matchedCam) {
            console.log(`Using currentCamId: ${matchedCam.label} (ID: ${matchedCam.deviceId})`);
            return matchedCam.deviceId;
        }
    }

    let preferredCam = cameras.find(cam =>
        cam.label.toLowerCase().includes("front") ||
        cam.label.toLowerCase().includes("default")
    );

    if (!preferredCam) {
        console.log("No 'front' or 'default' camera found. Using fallback camera.");
        preferredCam = cameras[0];
    }

    console.log(`Selected Camera: ${preferredCam.label} (ID: ${preferredCam.deviceId})`);
    return preferredCam.deviceId;
}

$(document).ready(function () {
    $('.toggle_push_to_talk').on('mousedown touchstart', function () {
        if (isVideoChatActive) {
            $(this).addClass('active');

            if (live_kit_video_client && isVideoChatActive) {
                live_kit_video_client.localParticipant.setMicrophoneEnabled(true);
            }
        }
    }).on('mouseup mouseleave touchend touchcancel', function () {
        if (isVideoChatActive) {
            $(this).removeClass('active');
            if (live_kit_video_client && isVideoChatActive) {
                live_kit_video_client.localParticipant.setMicrophoneEnabled(false);
            }
        }
    });
});


async function create_video_chat() {
    try {

        var mic_permissionGranted = await checkMicrophonePermission();

        var video_cam_enabled = false;
        var audio_only_chat = false;
        var publish_local_media = true;

        var videoChatData = await fetchVideoChatData();

        if (videoChatData.alert_message) {
            alert(videoChatData.alert_message);
            exit_video_chat();
            return;
        }

        var {
            token, channel: roomName, live_kit_url, subscriber_only, audio_only
        } = videoChatData;

        if (subscriber_only) {
            hideElementsForSubscriberMode();
        }

        live_kit_video_client = new LivekitClient.Room({
            adaptiveStream: true,
            autoSubscribe: true,
        });

        audio_only_chat = Boolean(audio_only);

        if (audio_only_chat) {
            var cam_permissionGranted = false;
        } else {
            var cam_permissionGranted = await checkWebcamAndPermission();
        }



        video_cam_enabled = audio_only ? false: cam_permissionGranted;

        await live_kit_video_client.prepareConnection(live_kit_url, token);
        await live_kit_video_client.connect(live_kit_url, token);

        console.log(`Connected to Room: ${roomName}`);

        isVideoChatActive = true;

        update_wsocket_data();

        clearCallNotifications();

        live_kit_video_client.remoteParticipants.forEach(participant => {
            participant.trackPublications.forEach(publication => {
                if (publication.track) {
                    add_livekit_participant(participant, publication.track);
                }
            });
        });

        live_kit_video_client.on(LivekitClient.RoomEvent.TrackSubscribed, (track, publication, participant) => {
            add_livekit_participant(participant, track);
        });

        if (publish_local_media) {
            await setupLocalParticipant(
                live_kit_video_client,
                mic_permissionGranted,
                video_cam_enabled,
                audio_only_chat
            );
        }

        if (live_kit_video_client && isVideoChatActive) {
            if (mic_mute_on_load) {

                if (system_variable('push_to_talk_feature') === 'enable') {
                    const pt_tooltipInstance = bootstrap.Tooltip.getInstance(document.getElementById('push_to_talk_icon'));
                    if (pt_tooltipInstance) {
                        pt_tooltipInstance.show();
                    }
                }

                live_kit_video_client.localParticipant.setMicrophoneEnabled(false);
            } else {
                live_kit_video_client.localParticipant.setMicrophoneEnabled(true);
            }
        }

        live_kit_video_client.on('participantDisconnected', (disconnectedParticipant) => {
            console.log(`Participant ${disconnectedParticipant.identity} has disconnected`);
            removeDisconnectedParticipant(disconnectedParticipant.sid);
        });

        live_kit_video_client.on('activeSpeakersChanged', (speakers) => {
            $('.video_chat_grid > div').removeClass('talking');

            speakers.forEach((speaker) => {
                const participantId = speaker.sid;
                if (current_logged_user_id && current_logged_user_id == speaker.identity) {
                    $('.video_chat_grid > div.local-participant-window').addClass('talking');
                } else {
                    $(`.video_chat_grid > div[user_sid='${participantId}']`).addClass('talking');
                }
            });
        });

    } catch (error) {
        console.error('Error during video chat initialization:', error);
        exit_video_chat();
    }
}

async function fetchVideoChatData() {
    try {
        var response = await fetch(api_request_url, {
            method: 'POST',
            body: video_chat_formData,
        });

        if (!response.ok) {
            console.error(`Error: ${response.status} - ${response.statusText}`);
            throw new Error(`Failed to fetch video chat data. Status: ${response.status}`);
        }

        var data = await response.json();
        return data;

    } catch (error) {
        console.error('Error fetching video chat data:', error);
        throw error;
    }
}

function hideElementsForSubscriberMode() {
    $('.main .video_chat_container>.icons>span.toggle_video_call_camera').hide();
    $('.main .video_chat_container>.icons>span.toggle_screen_share').hide();
    $('.main .video_chat_container>.icons>span.toggle_video_call_mic').hide();
}

function clearCallNotifications() {
    if (call_notification_timeout_id) {
        clearTimeout(call_notification_timeout_id);
    }
    $('.call_notification').attr('current_call_id', 0);
}

async function getPreferredMicrophone() {
    const devices = await navigator.mediaDevices.enumerateDevices();
    const microphones = devices.filter(device => device.kind === "audioinput");

    if (microphones.length === 0) {
        console.log("No microphones found!");
        return null;
    }

    if (currentMicId) {
        const matchedMic = microphones.find(mic => mic.deviceId === currentMicId);
        if (matchedMic) {
            console.log(`Using currentMicId: ${matchedMic.label} (ID: ${matchedMic.deviceId})`);
            return matchedMic.deviceId;
        }
    }

    let preferredMic = microphones.find(mic =>
        mic.label.toLowerCase().includes("communications")
    );

    if (!preferredMic) {
        console.log("No 'Communications' microphone found. Using default microphone.");
        preferredMic = microphones[0];
    }

    console.log(`Selected Microphone: ${preferredMic.label} (ID: ${preferredMic.deviceId})`);
    return preferredMic.deviceId;
}


async function get_mic_list() {
    try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const audioDevices = devices.filter(device => device.kind === 'audioinput');

        const micSelect = document.querySelector('.video_chat_settings_box .card select.select_microphone');
        micSelect.innerHTML = '';

        if (audioDevices.length === 0) {
            console.warn("No audio input devices found.");
            return;
        }

        let currentDeviceId = null;
        if (localTracks && preferredMicId) {
            currentDeviceId = preferredMicId;
        }

        audioDevices.forEach((device, index) => {
            const option = document.createElement("option");
            option.value = device.deviceId;
            option.textContent = device.label || `Microphone ${index + 1}`;

            if (device.deviceId === currentDeviceId) {
                option.selected = true;
            }

            micSelect.appendChild(option);
        });

    } catch (error) {
        console.error("Error getting microphone list:", error);
    }
}

async function get_cam_list() {
    try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const videoDevices = devices.filter(device => device.kind === 'videoinput');

        const camSelect = document.querySelector('.video_chat_settings_box .card .select_camera');
        if (!camSelect) {
            console.warn("Camera select element not found.");
            return;
        }

        camSelect.innerHTML = '';

        if (videoDevices.length === 0) {
            console.warn("No video input devices found.");
            return;
        }

        let currentDeviceId = null;
        if (localTracks && preferredCamId) {
            currentDeviceId = preferredCamId;
        }

        $('.video_chat_settings_box .card .select_camera_box').show();

        videoDevices.forEach((device, index) => {
            const option = document.createElement('option');
            option.value = device.deviceId;
            option.textContent = device.label || `Camera ${index + 1}`;

            if (device.deviceId === currentDeviceId) {
                option.selected = true;
            }

            camSelect.appendChild(option);
        });

    } catch (error) {
        console.error("Error getting camera list:", error);
    }
}

$("body").on('change', '.video_chat_settings_box .card .select_camera', async function(e) {
    const selectedCamId = $(this).val();

    try {
        const videocam_Track = localTracks.find(track => track.kind === 'video');
        videocam_Track.setDeviceId(selectedCamId);
        currentCamId = selectedCamId;
        console.log("Camera switched to:", selectedCamId);
    } catch (error) {
        console.error("Failed to switch camera:", error);
    }
});

$("body").on('change', '.video_chat_settings_box .card .select_microphone', async function(e) {
    const selectedMicId = $(this).val();

    try {
        const audiomic_Track = localTracks.find(track => track.kind === 'audio');
        audiomic_Track.setDeviceId(selectedMicId);
        currentMicId = selectedMicId;
        console.log("Mic switched to:", selectedMicId);
    } catch (error) {
        console.error("Failed to switch Mic:", error);
    }
});

async function setupLocalParticipant(client, micEnabled, videoEnabled, audioOnly) {
    try {

        if (micEnabled) {
            preferredMicId = await getPreferredMicrophone();
            await get_mic_list();
        }

        if (videoEnabled) {
            preferredCamId = await getPreferredCamera();
            await get_cam_list();
        } else {
            $('.video_chat_settings_box .card .select_camera_box').hide();
        }

        localTracks = await LivekitClient.createLocalTracks({
            audio: micEnabled ? {
                noiseSuppression: true,
                echoCancellation: true,
                autoGainControl: true,
                deviceId: preferredMicId
            }: false,
            video: videoEnabled ? {
                deviceId: preferredCamId
            }: false
        });
        localParticipantContainer = $('<div></div>').addClass('participant-container');

        if (videoEnabled) {
            var localVideoElement = localTracks.find(track => track.kind === 'video').attach();
            localParticipantContainer.append(localVideoElement);
        } else if (audioOnly) {
            localParticipantContainer.append(
                `<span class="participant_img"><img src="${$('.logged_in_user_avatar').attr('src')}" /></span>`
            );
        }

        var groupAttr = $(".main .chatbox").attr('group_id')
        ? `data-group_identifier="${$(".main .chatbox").attr('group_id')}"`: '';

        localParticipantContainer
        .addClass('identity You local-participant-window')
        .append(`<span ${groupAttr} class="participant_name get_info" user_id="${$('.logged_in_user_id').text()}">You</span>`);

        client.localParticipant.setMicrophoneEnabled(micEnabled);
        client.localParticipant.setCameraEnabled(videoEnabled);

        videochat_GridContainer.append(localParticipantContainer);
    } catch (error) {
        console.error('Error setting up local participant:', error);
        throw error;
    }
}

function removeDisconnectedParticipant(participantSid) {
    $('.participant-container').each(function () {
        if ($(this).attr('user_sid') === participantSid) {
            if ($(this).parent().hasClass('video_chat_full_view')) {
                $('.main .middle > .video_chat_interface > .video_chat_container').removeClass('full_view_container');
            }

            $(this).remove();
        }
    });

    var total_vclients = $('.main .middle > .video_chat_interface > .video_chat_container > .video_chat_grid > div').length;

    if (total_vclients === 0 && $('.main .middle > .video_chat_interface > .video_chat_container').hasClass('full_view_container')) {
        if ($('.video_chat_container.full_view_container > .video_chat_full_view > div').length > 0) {
            $('.video_chat_container.full_view_container > .video_chat_full_view > div').appendTo('.main .middle > .video_chat_interface > .video_chat_container > .video_chat_grid');
        }

        $('.main .middle > .video_chat_interface > .video_chat_container').removeClass('full_view_container');
    }
}