function SetCookies(name, value, days) {
    let nowDay = new Date();
    nowDay.setTime(nowDay.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + value + ";expires=" + nowDay.toGMTString()
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function getPreferredLanguage() {
    let countriesArrLang = ["en", "de", "ar", "es", "fr", "it", "jp", "nl", "pl", "pt", "sv", "ru"];
    let getUILanguage = '';
    getUILanguage = $('html').attr('lang').substring(0, 2);
    var countriesLangName = countriesArrLang.filter(function (item) {
        if (item === getUILanguage) {
            return true;
        }
        return false;
    });
    if (countriesLangName.length > 0) {
        return countriesLangName[0];
    } else {
        return 'en';
    }
}

//bottom faq
$(".faq-list").click(function () {
    if ($(this).hasClass('on')) {
        $(this).removeClass("on");
    } else {
        $(this).addClass("on");
    }
    // $(this).toggleClass("on").siblings().removeClass("on");
});

var _cw = $(window).width();
// if (_cw < 1200) {
//     $(".review .review-list").slick({
//         infinite: true,
//         dots: true,
//         arrows: false,
//         slidesToShow: 1,
//         slidesToScroll: 1,
//     });
// } else {
//     $(".review .review-list").slick({
//         infinite: true,
//         slidesToShow: 3,
//         slidesToScroll: 3,
//     });
// }

//pop close
$(".pop-mask-watermark .close").click(function () {
    $(".osr-pop-bg,.pop-mask-watermark").removeClass("on");
    if ($(this).parent().hasClass("accelerate")) {
        $(".list-box >div:last-child").removeClass("on")
    }
})

//pop-watermark
$(".watermark i").click(function () {
    $(".osr-pop-bg,.pop-mask-watermark.watermark").addClass("on")
});

//select
$(".selectBox").on("click", function () {
    $(".select-box ul").hide();
    $(this).parent().find('ul').show();
})

$(".select-box ul li").on("click", function (e) {
    let text = $(this).text();
    $(this).parent().parent().find(".selectBox").text(text);
    if (text == "4k" || text == "1080p") {
        $(".select-resolutions .selectBox").addClass("off")
        $(".select-resolutions p").show()
        $(".download-operation-btn").addClass("off")

    } else if (text == "MP4" || text == "AVI") {
        $(".select-format .selectBox").addClass("off")
        $(".select-format p").show()
        $(".download-operation-btn").addClass("off")

    }
    if (text == "720p") {
        $(".select-resolutions .selectBox").removeClass("off")
        $(".select-resolutions p").hide()
        if ($(".select-format .selectBox").text() == "WebM") {
            $(".download-operation-btn").removeClass("off")
        }
    }
    if (text == "WebM") {
        $(".select-format .selectBox").removeClass("off")
        $(".select-format p").hide()
        if ($(".select-resolutions .selectBox").text() == "720p") {
            $(".download-operation-btn").removeClass("off")
        }
    }
})

$("body").off('click').on("click", function (e) {
    if (e.target != document.getElementsByClassName("selectBox")[0] && e.target != document
        .getElementsByClassName("selectBox")[1]) {
        $(".select-box ul").hide();
    }
})

//drap
let webcamEl = $(".webcam-box"),
    moveWebcamEl = false,
    init_WebcamX = 20,
    init_WebcamY = 20,
    camStartX, camStartY, camDistanceX, camDistanceY;
webcamEl.on("mousedown", function (e) {
    moveWebcamEl = true;
    camStartX = e.clientX;
    camStartY = e.clientY;
})
webcamEl.on("mousemove", function (e) {
    if (moveWebcamEl) {
        let camMoveX = e.clientX;
        let camMoveY = e.clientY;
        camDistanceX = camStartX - camMoveX
        camDistanceY = camStartY - camMoveY
        webcamEl.css("left", init_WebcamX - camDistanceX)
        webcamEl.css("bottom", init_WebcamY + camDistanceY)

    }
})
$(window).on("mouseup", function (e) {
    if (moveWebcamEl) {
        moveWebcamEl = false;

        init_WebcamX = init_WebcamX - camDistanceX
        init_WebcamY = init_WebcamY + camDistanceY
        webcamEl.css("left", init_WebcamX)
        webcamEl.css("bottom", init_WebcamY)
        camDistanceX = 0;
        camDistanceY = 0;
    }
})

$(".onlinebacktop").off('click').on("click", function () {
    window.scrollTo({
        top: 0,
        behavior: "smooth",
    })
})

// Record Start

const recorderTimeStart = location.host.includes("itopvpn.com") ? 600 : 30, // 600 10 min
    recorderTimeEnd = location.host.includes("itopvpn.com") ? 601 : 31;
const MAXRECORDCOUNT = location.host.includes('itopvpn.com') ? 4 : 4;
// const MAXRECORDCOUNT = 100;
let flag = true;
let camVideo = document.getElementsByClassName("webcam-video")[0],
    video = document.querySelector('#recording-player'),
    playVideo = document.querySelector("#screen-video"),
    allStream,
    stopRecordingTimer,
    pause_start, pause_time = 0,
    beforStartTimer = null,
    recordingInterval = null,
    camStream,
    cavsVideoStream,
    canvasStream,
    recorder = null,
    // recorderTime = 10 * 60 * 1000,
    // recorderTime = 600, // 10 min
    recorderTime = 0,
    screenOptions = {
        video: true, //screen
        audio: false, //systme audio
    },
    userMediaOptions = {
        video: false, //webcam
        audio: false, //microphone
    },
    audioStreamConstraints = {
        video: false,
        audio: false,
    };

let recNumber = 0;
let nowTimes = 0;
let playPromise = null;

function exChangeTime(time) {
    let h = parseInt(time / 60 / 60)
    h = h < 10 ? '0' + h : h
    let m = parseInt(time / 60 % 60)
    m = m < 10 ? '0' + m : m
    let s = parseInt(time % 60)
    s = s < 10 ? '0' + s : s
    return [h, m, s]
}

function handleLocalMediaStreamError(error, type) {
    // console.log('navigator.getUserMedia error: ', error)
    if ($(".list-box > div[data-type='" + type + "']").hasClass("on")) {
        $(".error-tip[data-type='" + type + "']").show();
    } else {
        $(".error-tip[data-type='" + type + "']").hide();
    }
    // $(".list-box > div[data-type='" + type + "']").removeClass("on");

    if (type == 'webcam') {
        userMediaOptions.video = false;
    } else if (type == 'mic') {
        userMediaOptions.audio = false;
    }
}

function gotLocalMediaStream(stream, type) {
    var audioContext = window.AudioContext
        || window.webkitAudioContext
        || window.mozAudioContext
        || window.msAudioContext;
    var context = null;
    try {
        // console.log('error-tip hide')
        $(".error-tip[data-type='" + type + "']").hide();
        if (type == 'webcam') {
            userMediaOptions.video = true;
        } else if (type == 'mic') {
            userMediaOptions.audio = true;
        }
    } catch (e) {
        // console.log("not support AudioContext")
        handleLocalMediaStreamError(e, type);
    }
}

function getUserMedia(constrains, type) {
    if (navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia(constrains)
            .then(stream => { gotLocalMediaStream(stream, type); })
            .catch(err => { handleLocalMediaStreamError(err, type); });
    } else if (navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function (constraints) {
                var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
                if (!getUserMedia) {
                    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                }
                return new Promise(function (resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                });
            }
        }
        navigator.mediaDevices.getUserMedia(constrains).then(stream => {
            gotLocalMediaStream(stream, type);
        }).catch(err => {
            handleLocalMediaStreamError(err, type);
        });
    } else if (navigator.getUserMedia) {
        navigator.getUserMedia(constrains)
            .then(stream => { gotLocalMediaStream(stream, type); })
            .catch(err => { handleLocalMediaStreamError(err, type); });
    }
}

function navigamediaDevices(status, type) {
    try {
        if (navigator.mediaDevices.getUserMedia
            || navigator.getUserMedia
            || navigator.webkitGetUserMedia
            || navigator.mozGetUserMedia) {
            getUserMedia(status, type);
        } else {
            alert("The browser does not support accessing user media devices");
        }
    } catch (err) {
        handleLocalMediaStreamError(err, type);
    }
}

function addStreamStopListener(stream, callback) {
    stream.addEventListener('ended', function () {
        // console.log('addStreamStopListener ended')
        callback();
        callback = function () { };
    }, false);
    stream.addEventListener('inactive', function () {
        // console.log('addStreamStopListener inactive')
        callback();
        callback = function () { };
    }, false);
    stream.getTracks().forEach(function (track) {
        track.addEventListener('ended', function () {
            // console.log('addStreamStopListener getTracks ended')
            callback();
            callback = function () { };
        }, false);
        track.addEventListener('inactive', function () {
            // console.log('addStreamStopListener getTracks inactive')
            callback();
            callback = function () { };
        }, false);
    });
}

function formatRecording() {
    // if (camStream) {
    //     camStream.stop();
    // }
    // if (allStream) {
    //     allStream.stop();
    // }
    // if (canvasStream) {
    //     canvasStream.stop();
    // }
    // if (cavsVideoStream) {
    //     cavsVideoStream.stop();
    // }
    pause_time = 0;
    $(".pop-timeout .timeout").text(3)
    $("#time-hours").text('00')
    $("#time-mins").text('00')
    $("#time-seconds").text('00')
    $(".webcam-box").hide();
    $(".select-format .selectBox").text("WebM")
    $(".select-resolutions .selectBox").text("720p")
    $(".select-box .selectBox,.download-operation-btn").removeClass("off")
    $(".select-box  p").hide()
}

function stopRecordingEvent() {
    // clearTimeout(stopRecordingTimer);
    clearInterval(stopRecordingTimer);
    clearTimeout(beforStartTimer);
    clearInterval(recordingInterval);
    $(".osr-pop-bg").removeClass("on");
    $(".pop-timeout").hide();
    $(".pop-timeout .timeout").text(3)
    formatRecording();
    if (typeof recorder == 'undefined') {
        return;
    }
    $(".microphone").hide();
    $(".download-recording").show();

    document.querySelector('.webcam-video').srcObject = null;
    $(".webcam-box").hide();
    document.querySelector('.webcam-video').muted = false;
}

var btnStartRecording = document.querySelector('#btn-start-recording');
var btnStopRecording = document.querySelector('#btn-stop-recording');
var btnCancelRecording = document.querySelector('#cancel-recording');
var btnCancelRecording = document.querySelector('#cancel-recording');
var btnPauseRecording = document.querySelector('#pause-recording');
// recorder options
$(".list-box >div").click(function () {
    let index = $(this).index();
    let _type = '';
    if (index == 1 || index == 2 || index == 3) {
        $(this).toggleClass("on");
        if (index == 1 || index == 3) {
            _type = $(this).attr('data-type');
            if (index == 1) {
                userMediaOptions.video = true;
                navigamediaDevices(userMediaOptions, 'webcam');
            } else if (index == 3) {
                userMediaOptions.audio = true;
                navigamediaDevices(userMediaOptions, 'mic');
            }
        } else if (index == 2) {
            if ($(this).hasClass("on")) {
                screenOptions.audio = true;
            } else {
                screenOptions.audio = false;
            }
            // navigamediaDevices(screenOptions, 'system');
        }
    } else if (index == 4) {
        $(this).addClass("on")
        $(".osr-pop-bg,.pop-mask-watermark.accelerate").addClass("on")
    }
});

var videoBitsPerSecond;

function setVideoBitrates() {
    var value = 'default';

    if (value == 'default') {
        videoBitsPerSecond = null;
        return;
    }

    videoBitsPerSecond = parseInt(value);
}

function getVideoResolutions(mediaConstraints) {
    if (!mediaConstraints.video) {
        return mediaConstraints;
    }

    var value = 'default';

    if (value == 'default') {
        return mediaConstraints;
    }

    value = value.split('x');

    if (value.length != 2) {
        return mediaConstraints;
    }

    efaultWidth = "1280";
    defaultHeight = "720";

    if (DetectRTC.browser.name === 'Firefox') {
        mediaConstraints.video.width = defaultWidth;
        mediaConstraints.video.height = defaultHeight;
        return mediaConstraints;
    }

    if (!mediaConstraints.video.mandatory) {
        mediaConstraints.video.mandatory = {};
        mediaConstraints.video.optional = [];
    }

    var isScreen = recordingMedia.value.toString().toLowerCase().indexOf('screen') != -1;

    if (isScreen) {
        mediaConstraints.video.mandatory.maxWidth = defaultWidth;
        mediaConstraints.video.mandatory.maxHeight = defaultHeight;
    }
    else {
        mediaConstraints.video.mandatory.minWidth = defaultWidth;
        mediaConstraints.video.mandatory.minHeight = defaultHeight;
    }

    return mediaConstraints;
}

function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
    if (mediaConstraints.video == true) {
        mediaConstraints.video = {};
    }

    setVideoBitrates();

    mediaConstraints = getVideoResolutions(mediaConstraints);
    mediaConstraints = getFrameRates(mediaConstraints);

    var isBlackBerry = !!(/BB10|BlackBerry/i.test(navigator.userAgent || ''));
    if (isBlackBerry && !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia)) {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        navigator.getUserMedia(mediaConstraints, successCallback, errorCallback);
        return;
    }

    navigator.mediaDevices.getUserMedia(mediaConstraints).then(function (stream) {
        successCallback(stream);
        setVideoURL(stream, true);
    }).catch(function (error) {
        if (error && (error.name === 'ConstraintNotSatisfiedError' || error.name === 'OverconstrainedError')) {
            alert('Your camera or browser does NOT supports selected resolutions or frame-rates. \n\nPlease select "default" resolutions.');
        }
        else if (error && error.message) {
            alert(error.message);
        }
        else {
            alert('Unable to make getUserMedia request. Please check browser console logs.');
        }
        errorCallback(error);
    });
}

function getFrameRates(mediaConstraints) {
    if (!mediaConstraints.video) {
        return mediaConstraints;
    }

    var value = 'default';

    if (value == 'default') {
        return mediaConstraints;
    }

    value = parseInt(value);

    if (DetectRTC.browser.name === 'Firefox') {
        mediaConstraints.video.frameRate = value;
        return mediaConstraints;
    }

    if (!mediaConstraints.video.mandatory) {
        mediaConstraints.video.mandatory = {};
        mediaConstraints.video.optional = [];
    }

    var isScreen = recordingMedia.value.toString().toLowerCase().indexOf('screen') != -1;
    if (isScreen) {
        mediaConstraints.video.mandatory.maxFrameRate = value;
    }
    else {
        mediaConstraints.video.mandatory.minFrameRate = value;
    }

    return mediaConstraints;
}

function getURL(arg) {
    var url = arg;

    if (arg instanceof Blob || arg instanceof File) {
        url = URL.createObjectURL(arg);
    }

    if (arg instanceof RecordRTC || arg.getBlob) {
        url = URL.createObjectURL(arg.getBlob());
    }

    if (arg instanceof MediaStream || arg.getTracks) {
        // url = URL.createObjectURL(arg);
    }

    return url;
}

// var recordingPlayer = document.querySelector('#recordingPlayer');

function setVideoURL(arg, forceNonImage) {
    var url = getURL(arg);
    // console.log('setVideoURL: ' + url)
    if (arg instanceof MediaStream) {
        // recordingPlayer.muted = true;
        document.getElementById("recording-player").muted = true;
    }

    document.getElementById("recording-player").addEventListener('loadedmetadata', function () {
        if (navigator.userAgent.toLowerCase().indexOf('android') == -1) return;

        // android
        setTimeout(function () {
            if (typeof document.getElementById("recording-player").play === 'function') {
                document.getElementById("recording-player").play();
            }
        }, 2000);
    }, false);

    document.getElementById("recording-player").poster = '';

    if (arg instanceof MediaStream) {
        document.getElementById("recording-player").srcObject = arg;
    }
    else {
        document.getElementById("recording-player").src = url;
    }

    if (typeof document.getElementById("recording-player").play === 'function') {
        document.getElementById("recording-player").play();
    }

    document.getElementById("recording-player").addEventListener('ended', function () {
        url = getURL(arg);

        if (arg instanceof MediaStream) {
            document.getElementById("recording-player").srcObject = arg;
        }
        else {
            document.getElementById("recording-player").src = url;
        }
    });
}

function addOtherOperation(arg) {
    // console.log(arg)
    // if (arg instanceof MediaStream) {
    // }
    allStream = new MediaStream();

    // console.log(allStream)

    $("canvas").remove();
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');

    canvas.style =
        'position: absolute; top: 0; left: 0; opacity: 0; margin-top: -9999999999; margin-left: -9999999999; top: -9999999999; left: -9999999999; z-index: -1;';
    document.body.appendChild(canvas);

    canvasStream = canvas.captureStream();

    getTracks(canvasStream, 'video').forEach(function (videoTrack) {
        allStream.addTrack(videoTrack);
    });

    getTracks(arg, 'audio').forEach(function (videoTrack) {
        allStream.addTrack(videoTrack);
    });

    cavsVideoStream = new MediaStream();


    getTracks(arg, 'video').forEach(function (audioTrack) {
        cavsVideoStream.addTrack(audioTrack);
    });

    let videoCanvs = document.createElement('video');
    videoCanvs.autoplay = true;
    videoCanvs.playsinline = true;
    videoCanvs.srcObject = cavsVideoStream;

    (function looper() {
        // 640*480  1280x720 1920x1080 3840x2160(4k)
        canvas.width = 1280;
        canvas.height = 720;
        context.drawImage(videoCanvs, 0, 0, canvas.width, canvas.height);
        context.font = "60px";
        context.fillStyle = "#C6CBDB"
        context.fillText("Recorded with iTop Screen Recorder", 10, 20);
        setTimeout(looper, 100);
    })();

    return allStream;
}

function captureAudioPlusScreen(config, system) {
    // console.log(system);
    if (navigator.getDisplayMedia) {
        navigator.getDisplayMedia({
            video: true,
            audio: system.audio,
        }).then(screenStream => {
            navigator.getDisplayMedia({ audio: true }).then(function (mic) {
                screenStream.addTrack(mic.getTracks()[0]);

                config.onMediaCaptured(screenStream);

                addStreamStopListener(screenStream, function () {
                    // config.onMediaStopped();
                    btnStartRecording.onclick();
                });

                setVideoURL(screenStream, true);
            });
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia({
            video: true,
            audio: system.audio,
        }).then(screenStream => {
            navigator.mediaDevices.getUserMedia({ audio: true }).then(function (mic) {
                screenStream.addTrack(mic.getTracks()[0]);

                config.onMediaCaptured(screenStream);

                addStreamStopListener(screenStream, function () {
                    // config.onMediaStopped();
                    btnStartRecording.onclick();
                });

                setVideoURL(screenStream, true);
            });
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else {
        var error = 'getDisplayMedia API are not supported in this browser.';
        config.onMediaCapturingFailed(error);
        alert(error);
    }
}

function captureCamera(cb) {
    navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(cb);
}

function captureVideoPlusScreen(config, system, type) {
    let micStatus = false;
    micStatus = type == 'audio' ? true : false;
    var displaymediastreamconstraints = {
        video: {
            width: 640,   
            height: 480, 
            frameRate: 15, // Frame rate
            facingMode: 'enviroment', //  Set as rear camera
            // deviceId: deviceId ? { exact: deviceId } : undefined,
            displaySurface: 'monitor', // monitor, window, application, browser
            logicalSurface: true,
            cursor: 'always' // never, always, motion
        },
        audio: system.audio
    };

    // above constraints are NOT supported YET
    // that's why overridnig them
    // displaymediastreamconstraints = {
    //     width: 640,  
    //     height: 480,  
    //     frameRate: 15,
    //     facingMode: 'enviroment',
    //     // deviceId: deviceId ? { exact: deviceId } : undefined,
    //     displaySurface: 'monitor', // monitor, window, application, browser
    //     logicalSurface: true,
    //     cursor: 'always' // never, always, motion
    // };

    if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia(displaymediastreamconstraints).then(success => {
            // config.onMediaCaptured(success);
            navigator.mediaDevices.getUserMedia({ audio: micStatus, video: true }).then(cb => {
                config.onMediaCaptured([success, cb]);
                addStreamStopListener(success, function () {
                    btnStartRecording.onclick();
                });
                setVideoURL(success, true);
                document.querySelector('.webcam-video').srcObject = null;
                $(".webcam-box").show();
                document.querySelector('.webcam-video').muted = true;
                document.querySelector('.webcam-video').srcObject = cb;
            });
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    }
    else if (navigator.getDisplayMedia) {
        navigator.getDisplayMedia(displaymediastreamconstraints).then(success => {
            navigator.getDisplayMedia({ audio: micStatus, video: true }).then(cb => {
                config.onMediaCaptured([success, cb]);
                addStreamStopListener(success, function () {
                    btnStartRecording.onclick();
                });
                setVideoURL(success, true);
                document.querySelector('.webcam-video').srcObject = null;
                $(".webcam-box").show();
                document.querySelector('.webcam-video').muted = true;
                document.querySelector('.webcam-video').srcObject = cb;
            });
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else {
        var error = 'getDisplayMedia API are not supported in this browser.';
        config.onMediaCapturingFailed(error);
        alert(error);
    }
}

function captureAudioPlusVideo(config, system) {
    if (navigator.getDisplayMedia) {
        navigator.getDisplayMedia({
            video: true,
            audio: system.audio,
        }).then(screenStream => {
            captureUserMedia({ video: true, audio: true }, function (audioVideoStream) {
                config.onMediaCaptured(audioVideoStream);
                if (audioVideoStream instanceof Array) {
                    audioVideoStream.forEach(function (stream) {
                        addStreamStopListener(stream, function () {
                            config.onMediaStopped();
                        });
                    });
                    return;
                }

                addStreamStopListener(audioVideoStream, function () {
                    config.onMediaStopped();
                });
            }, function (error) {
                config.onMediaCapturingFailed(error);
            });
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia({
            video: true,
            audio: system.audio,
        }).then(screenStream => {
            captureUserMedia({ video: true, audio: true }, function (audioVideoStream) {
                config.onMediaCaptured(audioVideoStream);
                if (audioVideoStream instanceof Array) {
                    audioVideoStream.forEach(function (stream) {
                        addStreamStopListener(stream, function () {
                            config.onMediaStopped();
                        });
                    });
                    return;
                }

                addStreamStopListener(audioVideoStream, function () {
                    config.onMediaStopped();
                });
            }, function (error) {
                config.onMediaCapturingFailed(error);
            });
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else {
        var error = 'getDisplayMedia API are not supported in this browser.';
        config.onMediaCapturingFailed(error);
        alert(error);
    }
}

function captureScreen(config, option) {
    if (navigator.getDisplayMedia) {
        navigator.getDisplayMedia(option).then(screenStream => {
            config.onMediaCaptured(screenStream);
            addStreamStopListener(screenStream, function () {
                // console.log('screenStream')
                // console.log(screenStream)
                // btnStartRecording.recordRTC.stop();
                btnStartRecording.onclick();
                // btnStopRecording.onclick();
            });
            // screenStream = addOtherOperation(screenStream);
            setVideoURL(screenStream, true);
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia(option).then(screenStream => {
            config.onMediaCaptured(screenStream);
            addStreamStopListener(screenStream, function () {
                // console.log('screenStream2')
                // console.log(screenStream)
                // btnStopRecording.onclick();
                btnStartRecording.onclick();
            });
            // screenStream = addOtherOperation(screenStream);
            setVideoURL(screenStream, true);
        }).catch(function (error) {
            config.onMediaCapturingFailed(error);
        });
    } else {
        var error = 'getDisplayMedia API are not supported in this browser.';
        config.onMediaCapturingFailed(error);
        alert(error);
    }
}

function getRandomString() {
    if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
        var a = window.crypto.getRandomValues(new Uint32Array(3)),
            token = '';
        for (var i = 0, l = a.length; i < l; i++) {
            token += a[i].toString(36);
        }
        return token;
    } else {
        return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
    }
}

var fileExtension = 'webm';

function getFileName(fileExtension) {
    var d = new Date();
    var year = d.getUTCFullYear();
    var month = d.getUTCMonth();
    var date = d.getUTCDate();
    return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
}

function backToMainScreen() {
    try {
        if (!btnStartRecording.recordRTC) {
            btnStartRecording.recordRTC.destroy();
            btnStartRecording.recordRTC = null;
        }
    } catch (e) {
        if (!btnStartRecording.recordRTC) {
            btnStartRecording.recordRTC = null;
        }
    }

    flag = true;
    stopRecordingTimer = clearInterval(stopRecordingTimer);
    clearTimeout(beforStartTimer);
    clearInterval(recordingInterval);
    playVideo.muted = true;
    playVideo.src = '';
    // recorder.screen.stop();
    recorderTime = recorderTimeEnd;
    $("[data-type='recording']").show();
    $(".recording-cancel").hide();
    $(".microphone").hide();
    $(".download-recording").hide();
    $(".osr-pop-bg").removeClass("on");
    $("canvas,.pop-timeout").hide();
    $("canvas").remove();
    document.querySelector('.webcam-video').srcObject = null;
    $(".webcam-box").hide();
    document.querySelector('.webcam-video').muted = false;
}

function saveToDisk(recordRTC) {
    // console.log('blob', recordRTC.getBlob().type)
    // console.log(screenOptions)
    if (!recordRTC.getBlob().size) {
        var info = getFailureReport();
        // console.log('blob', recordRTC.getBlob())
        // console.log('recordrtc instance', recordRTC)
        // console.log('report', info)
    }

    // $("[data-type='recording']").hide();
    // $(".download-recording").show();

    // if (recordRTC.getBlob().type.includes('x-matroska')) {
    //     playVideo.controls = true;
    //     playVideo.muted = false;
    //     let blob = new Blob([recordRTC.getBlob()], { type: "video/x-matroska;codecs=avc1,opus" })
    //     playVideo.src = window.URL.createObjectURL(blob)
    //     playVideo.play();
    // } else {
    //     getSeekableBlob(recordRTC.getBlob(), function (seekableBlob) {
    //         playVideo.src = URL.createObjectURL(seekableBlob);
    //     });
    // }

    getSeekableBlob(recordRTC.getBlob(), function (seekableBlob) {
        // console.log(seekableBlob)
        let video_src = URL.createObjectURL(seekableBlob);
        playVideo.src = video_src;
        playVideo.controls = true;
        // console.log(playVideo.src)
    })


    var fileName = getFileName(fileExtension);
    document.querySelector('#save-to-disk').onclick = function () {
        // console.log("save-to-disk click")
        if (!recordRTC) return alert('No recording found.');

        getSeekableBlob(recordRTC.getBlob(), function (seekableBlob) {
            var file = new File([seekableBlob], fileName, {
                type: 'video/webm',
            });
            // console.log(file)
            invokeSaveAsDialog(file, file.name);
        });

        // var file = new File([recordRTC.getBlob()], fileName, {
        //     type: 'video/webm',
        // });
        // console.log(file);
        // invokeSaveAsDialog(file, file.name);
    };
}

let mediaContainerFormat = {
    timeSlice: 1000,
    // mimeType: 'video/webm;codecs=vp8',
    mimeType: 'video/webm',
    fileExtension: 'webm',
    recorderType: null,
    type: 'video',
    initCallback: null,
    ignoreMutedMedia: false,
}

async function countTimeEvent() {
    // 10min stop  recorder
    clearInterval(stopRecordingTimer);
    $(".recording-cancel").hide();
    $(".microphone").show();
    resetZero();
    beginCount();
}

btnStartRecording.onclick = async function (event) {
    let button = btnStartRecording;
    let buttonControl = btnStartRecording.getAttribute("data-control");

    // console.log(buttonControl)

    if (buttonControl === 'stop-recording') {
        btnStartRecording.setAttribute("data-control", "start-recording");
        resetZero();
        function stopStream() {
            if (button.stream && button.stream.stop) {
                button.stream.stop();
                button.stream = null;
            }

            if (button.stream instanceof Array) {
                button.stream.forEach(function (stream) {
                    stream.stop();
                });
                button.stream = null;
            }
        }

        if (button.recordRTC) {
            if (button.recordRTC.length) {
                button.recordRTC[0].stopRecording(function (url) {
                    if (!button.recordRTC[1]) {
                        button.recordingEndedCallback(url);
                        stopStream();
                        saveToDisk(button.recordRTC[0]);
                        stopRecordingEvent();
                        return;
                    }

                    button.recordRTC[1].stopRecording(function (url) {
                        button.recordingEndedCallback(url);
                        stopStream();
                    });
                });
            } else {
                button.recordRTC.stopRecording(function (url) {
                    if (button.blobs && button.blobs.length) {
                        var blob = new File(button.blobs, getFileName(fileExtension), {
                            type: mimeType
                        });

                        button.recordRTC.getBlob = function () {
                            return blob;
                        };

                        url = URL.createObjectURL(blob);
                    }

                    button.recordingEndedCallback(url);
                    saveToDisk(button.recordRTC);
                    stopRecordingEvent();
                    stopStream();
                });
            }
        }
        return;
    }

    if (!event) return;

    $("#pause-recording").removeClass('on');
    playVideo.muted = true;
    flag = true;
    recorderTime = 0;
    recNumber++;
    nowTimes = getCookie(getPreferredLanguage() + "_osr_dayLimit");

    playVideo.muted = true;

    if (nowTimes.length != 0) {
        if (parseInt(nowTimes) > MAXRECORDCOUNT) {
            // console.log("times up")
            $(".start-btn").attr('disabled', true);
            $(".online-limit").show();
            btnStartRecording.setAttribute("data-control", "start-recording");
            btnStartRecording.click();
            return;
        } else {
            $(".online-limit").hide();
            $(".start-btn").removeAttr('disabled');
            SetCookies(getPreferredLanguage() + "_osr_dayLimit", recNumber, 1);
        }
    } else {
        $(".online-limit").hide();
        $(".start-btn").removeAttr('disabled');
        SetCookies(getPreferredLanguage() + "_osr_dayLimit", recNumber, 1);
    }
    $("[data-type='recording']").hide();
    $(".recording-cancel").show();

    window.scrollTo({
        top: 0,
        behavior: "smooth",
    });

    var commonConfig = {
        onMediaCaptured: function (stream) {
            // console.log('onMediaCaptured: ')
            // console.log(stream)
            btnStartRecording.setAttribute("data-control", "stop-recording");
            button.stream = stream;
            if (button.mediaCapturedCallback) {
                button.mediaCapturedCallback();
            }
        },
        onMediaStopped: function () {
            // console.log('onMediaStopped')
            clearInterval(stopRecordingTimer);
            resetZero();
            btnStartRecording.setAttribute("data-control", "start-recording");
        },
        onMediaCapturingFailed: function (error) {
            clearInterval(stopRecordingTimer);
            resetZero();
            console.error('onMediaCapturingFailed:', error);

            if (error.toString().indexOf('no audio or video tracks available') !== -1) {
                alert('RecordRTC failed to start because there are no audio or video tracks available.');
            }

            if (error.name === 'PermissionDeniedError' && DetectRTC.browser.name === 'Firefox') {
                alert('Firefox requires version >= 52. Firefox also requires HTTPs.');
            }
            commonConfig.onMediaStopped();
        }
    };

    // console.log('screenOptions=============')
    // console.log(screenOptions)
    // console.log('userMediaOptions=============')
    // console.log(userMediaOptions)
    // console.log('audioStreamConstraints=============');
    // console.log(audioStreamConstraints);
    if (userMediaOptions.audio == true && userMediaOptions.video == false) {
        // console.log("captureAudioPlusScreen======================")
        captureAudioPlusScreen(commonConfig, screenOptions);
    } else if (userMediaOptions.audio == false && userMediaOptions.video == true) {
        // console.log("captureVideoPlusScreen======================")
        captureVideoPlusScreen(commonConfig, screenOptions, 'video')
    } else if (userMediaOptions.audio == true && userMediaOptions.video == true) {
        // console.log("captureAudioPlusVideo======================")
        captureVideoPlusScreen(commonConfig, screenOptions, 'audio')
    } else if (userMediaOptions.audio == false && userMediaOptions.video == false) {
        // console.log("captureScreen======================")
        captureScreen(commonConfig, screenOptions);
    }

    button.mediaCapturedCallback = async function () {
        var options = {
            type: 'video',
            mimeType: 'video/webm',
            fileExtension: 'webm',
            disableLogs: false,
            getNativeBlob: false,
            video: {
                playsinline: true
            },
            checkForInactiveTracks: false,
            initCallback: null,
            ignoreMutedMedia: false,
        };
        try {
            options.ignoreMutedMedia = false;
            let num = 3;
            $(".pop-timeout .timeout").text(num);
            $(".osr-pop-bg").addClass("on");
            $(".pop-timeout").show();
            recordingInterval = setInterval(() => {
                num--;
                if (num <= 0) {
                    $(".osr-pop-bg").removeClass("on");
                    $(".pop-timeout").hide();
                    clearInterval(recordingInterval);
                };
                $(".pop-timeout .timeout").text(num)
            }, 1000);
            button.recordRTC = RecordRTC(button.stream, options);

            button.recordingEndedCallback = function (url) {
                setVideoURL(url);
            };
            const sleep = m => new Promise(r => setTimeout(r, m));
            await sleep(3000);
            await button.recordRTC.startRecording();
            await countTimeEvent();
        } catch (e) {
            // console.log(e)
            num = 0;
            $(".osr-pop-bg").removeClass("on");
            $(".pop-timeout").hide();
            clearInterval(recordingInterval);
            resetZero();
            backToMainScreen(button.recordRTC);
        }
    };
}

btnStopRecording.onclick = async function (event) {
    clearInterval(stopRecordingTimer);
    resetZero();
    btnStartRecording.click();
}

btnCancelRecording.onclick = async function (event) {
    clearInterval(stopRecordingTimer);
    resetZero();
    btnStartRecording.setAttribute("data-control", "stop-recording");
    btnStartRecording.click();
    backToMainScreen(btnStartRecording.recordRTC);
}

var hour = 0;
var minute = 0;
var second = 0;
var countTime1;
var countTime2;
var judgement = true;
const endCountTimeMin = 10;

const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};

// countDown
function countTime() {
    if (minute >= endCountTimeMin) {
        btnStartRecording.setAttribute("data-control", "stop-recording");
        btnStopRecording.onclick();
        clearInterval(countTime1);
        clearInterval(countTime2);
        return;
    };
    second += 1;
    if (second == 60) {
        second = 0;
        minute += 1;
        if (minute == 60) {
            hour += 1;
        }
    }
    $("#time-hours").text(formatNumber(hour));
    $("#time-mins").text(formatNumber(minute));
    $("#time-seconds").text(formatNumber(second));
}

// start countdown
function beginCount() {
    if (judgement == true) {
        countTime1 = setInterval(countTime, 1000);
    }
    else if (judgement == false) {
        countTime2 = setInterval(countTime, 1000);
    }
}

// pause countdown
function stopCount() {
    if (judgement == true) {
        var stop1 = clearInterval(countTime1);
        judgement = false;
    }
    else if (judgement == false) {
        var stop2 = clearInterval(countTime2);
        judgement = true;
    }
}

function resetZero() {
    clearInterval(countTime1);
    clearInterval(countTime2);
    hour = 0;
    minute = 0;
    second = 0;
    $("#time-hours").text("00");
    $("#time-mins").text("00");
    $("#time-seconds").text("00");
}

btnPauseRecording.onclick = function () {
    if (!btnStartRecording.recordRTC) {
        return;
    }

    let btnPauseControl = btnPauseRecording.getAttribute("data-control");

    if (btnPauseControl === 'pause-recording') {
        btnPauseRecording.classList.add("on");
        pause_start = new Date().getTime();
        clearInterval(stopRecordingTimer);
        btnStartRecording.recordRTC.pauseRecording();
        // recordingPlayer.pause();
        video.pause();
        // playVideo.pause();
        btnPauseRecording.setAttribute("data-control", "resume-recording");
        btnPauseRecording.getElementsByTagName("p")[0].innerHTML = btnPauseRecording.getAttribute("data-resume");
        stopCount();
    }

    if (btnPauseControl === 'resume-recording') {
        btnPauseRecording.classList.remove("on");
        btnStartRecording.recordRTC.resumeRecording();
        // recordingPlayer.play();
        video.play();
        // playVideo.play();
        btnPauseRecording.setAttribute("data-control", "pause-recording");
        btnPauseRecording.getElementsByTagName("p")[0].innerHTML = btnPauseRecording.getAttribute("data-pause");
        // pause_time = pause_time + new Date().getTime() - pause_start
        clearInterval(stopRecordingTimer);
        // resetZero();
        beginCount();
    }
};

//back first operation
$(".back-choose").off('click').on("click", function () {
    backToMainScreen(btnStartRecording.recordRTC);
});
