$("body").append('<div class="volumeClickcallerAudio-Own" style="cursor:pointer;position:fixed;z-index:997776;bottom:0;left:160px;width:20px;height:120px;"><div class="volumeMetercallerAudio-Own" style="position:absolute;z-index:-2;bottom:0;left:0;width:20px;height:100%;transform-origin:center center;transform:scaleY(-1);"><div class="volumen-wrapper"><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own">' +
'</div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div><div class="led-callerAudio-Own"></div></div></div></div><div id="videoMagicSelect" style="position:fixed;z-index:997778;bottom:0;left:0 background: #fff;"></div><div id="videoMagicControl" style="transform:scale(1);position:fixed;z-index:997777;bottom:0;left:0;font-size: 9px; color: black; line-height: 6px; letter-spacing: 0.57px; font-family: \'IBM Plex Mono\', \'Courier New\', monospace; font-weight: bold; background: #fff;transform-origin:bottom left;"><div id="cameraMagic" class="cameraMagic"><div id="selectVideoArea" style="position:absolute;pointer-events:auto;z-index:30;"></div><video id="videoMagic" style="pointer-events:none;">Video stream not available.</video><button id="stopbutton" style="background:green;cirsor:pointer;display:none;">Cam is on</button><button id="startbutton" style="background:#550a21;cursor:pointer;">Cam is off</button>' +
'<button id="vbuttonMagic" style="cursor:pointer;top:0;left:0;font-size:14px;display:none;">V</button><button id="lbuttonMagic" style="cursor:pointer;top:0;left:0;font-size:14px;display:none;">L</button></div><canvas id="canvasMagic" style="position:fixed;bottom:0;left:0;z-index:10;display:none;"></canvas><canvas id="canvasMagic2" style="position:fixed;bottom:0;left:0;z-index:20;"></canvas><img id="photoMagic" /><div style="background:#fff;float:right;"><div id="heyImVisitor" style="float:right;background:#fff;"><div id="heyImVisitorVideo" style="display:none;"><img style="background:beige;" id="heyImVisitorVideoImg" src="" /></div></div></div>');

var webcamBlank = " ";

        var inputConvolutNumber = Math.floor(Math.random() * 9000) + 1000;
        var returnData;
        var videoRate = 200;
        var videoSizeLeft = 0;
        var videoSizeTop = 0;
        var videoSizeWidthSelect = 320;
        var videoSizeHeightSelect;
        var videoSizeHeight;
        var oldPositionVideoLeft = 0;
        var oldPositionVideoTop = 0;
        var meantToGo = [];
        var audioChanged = 0;

        var mediaRecorder = [];
        var recReader = [];
        var fleoDestination = [];
        var fleoNodeSource = [];
        var chunks = [];
        var chunksLane = [];
        var fleoMediaStream = [];
        var audioCtxVolume = [];
        var gainNode = [];
        var volumeMeterNode = [];
        var volumeMeterGrayNode = [];
        var ledsVol = [];
        var ledsGrayVol = [];
        var range1 = [];
        var range2 = [];
        var trackNum = [];
        var fleoAudio_1_Send = "empty";
        var fleoAudio_1_SendBlob = "";
        var fleoAudio_2_Send = "empty";
        var fleoAudio_2_SendBlob = "";
        var dataFlunsh = 10;
        var dataPiece = [];
        var audioPlayer = [];
        var videoAll = [];
        var timestampBuffer;
        var checkTimesBuffer = 0;
        var mediaRecorderWhich = 1;
        var newSound = 0;
        var videoBuffer = [];
        var trackNumPlay = [];
        var waitOnStart = 0;

        var canvasResize = document.createElement('canvas');

        var fd1 = new FormData();
        var fd2 = new FormData();
        var fd;

        const videoElement = document.querySelector('video');
        videoElement.volume = 0;
        const audioInputSelect = document.querySelector('select#audioSource');
        const videoSelect = document.querySelector('select#videoSource');
        const selectors = [audioInputSelect, videoSelect];

        var canvasMagic = document.getElementById("canvasMagic");
        var context = canvasMagic.getContext('2d');

        function gotDevices(deviceInfos) {
            const values = selectors.map(select => select.value);
            selectors.forEach(select => {
                while (select.firstChild) {
                    select.removeChild(select.firstChild);
                }
            });
            for (let i = 0; i !== deviceInfos.length; ++i) {
                const deviceInfo = deviceInfos[i];
                const option = document.createElement('option');
                option.value = deviceInfo.deviceId;
                if (deviceInfo.kind === 'audioinput') {
                    option.text = deviceInfo.label || `microphone ${audioInputSelect.length + 1}`;
                    audioInputSelect.appendChild(option);
                } else if (deviceInfo.kind === 'videoinput') {
                    option.text = deviceInfo.label || `camera ${videoSelect.length + 1}`;
                    videoSelect.appendChild(option);
                } else {
                    console.log('Some other kind of source/device: ', deviceInfo);
                }
            }
            selectors.forEach((select, selectorIndex) => {
                if (Array.prototype.slice.call(select.childNodes).some(n => n.value === values[selectorIndex])) {
                    select.value = values[selectorIndex];
                }
            });
        }

        navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);

        const ledColor = [
            "#064dac",
            "#064dac",
            "#064dac",
            "#06ac5b",
            "#15ac06",
            "#4bac06",
            "#80ac06",
            "#acaa06",
            "#ac8b06",
            "#ac5506",
        ]
        const ledColorGray = [
            "#064dac3f",
            "#064dac3f",
            "#064dac3f",
            "#06ac5b3f",
            "#15ac063f",
            "#4bac063f",
            "#80ac063f",
            "#acaa063f",
            "#ac8b063f",
            "#ac55063f",
        ]

        ledsVol["callerAudio-Own"] = [...$('.led-callerAudio-Own')];
        ledsGrayVol["callerAudio-Own"] = [...$('.ledGray-callerAudio-Own')];

        if (!audioCtxVolume["callerAudio-Own"]) {
            audioCtxVolume["callerAudio-Own"] = new AudioContext({});
        }

        function leds(client, vol) {
            range1["callerAudio-" + client] = ledsVol["callerAudio-" + client].slice(0, Math.round(vol));

            for (var i = 0; i < ledsVol["callerAudio-" + client].length; i++) {
                ledsVol["callerAudio-" + client][i].style.background = "#a7a7a700";
            };
            for (var i = 0; i < range1["callerAudio-" + client].length; i++) {
                range1["callerAudio-" + client][i].style.background = `${ledColor[i]}`;
            };
        }

        function ledsGray(client, vol) {
            range2["callerAudio-" + client] = ledsVol["callerAudio-" + client].slice(0, Math.round(vol));
            for (var i = 0; i < ledsGrayVol["callerAudio-" + client].length; i++) {
                ledsGrayVol["callerAudio-" + client][i].style.background = "#a7a7a73d";
            };
            for (var i = 0; i < range2["callerAudio-" + client].length; i++) {
                range2["callerAudio-" + client][i].style.background = `${ledColorGray[i]}`;
            };
        }

        function startup2() {
            videoMagic.addEventListener('canplay', function (ev) {

                videoMagic.height = (640 / videoMagic.videoWidth) * videoMagic.videoHeight;
                videoMagic.width = 640;
                videoSizeHeight = videoMagic.height / 2;
                videoSizeWidth = videoMagic.width / 2;

                $("#walkVideoChooser").css({
                    "bottom": videoSizeHeight / 2
                });
                $("#walkVideoSizer").css({
                    "bottom": videoSizeHeight / 2
                });

            }, false);
        }

        function handleError(error) {
            console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
        }

        function start() {
            if (window.stream) {
                window.stream.getTracks().forEach(track => {
                    track.stop();
                });
            }
            const audioSource = audioInputSelect.value;
            const videoSource = videoSelect.value;
            const constraints = {
                audio: { 
                    sampleSize: 8,
                    sampleRate: 22500, 
                    echoCancellation: false, 
                    noiseSuppression: false,
                    autoGainControl: false,
                    deviceId: audioSource ? { exact: audioSource } : undefined
                },
                video: {
                    deviceId: videoSource ? { exact: videoSource } : undefined
                }
            };
            navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(gotDevices).catch(handleError);
        }

        function changeAudioStart() {
            if (window.stream) {
                window.stream.getTracks().forEach(track => {
                    track.stop();
                });
            }
            const audioSource = audioInputSelect.value;
            const videoSource = videoSelect.value;
            const constraints = {
                audio: { 
                    sampleSize: 8,
                    sampleRate: 22500, 
                    echoCancellation: false, 
                    noiseSuppression: false,
                    autoGainControl: false,
                    deviceId: audioSource ? { exact: audioSource } : undefined
                },
                video: {
                    deviceId: videoSource ? { exact: videoSource } : undefined
                }
            };
            navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(gotDevices).catch(handleError);
        }

        audioInputSelect.onchange = changeAudioStart;

        videoSelect.onchange = start;

        start();

        $("#selectVideoArea").resizable({
            handles: "all",
            containment: "parent",
            minHeight: 32,
            minWidth: 32,
            start: function () {
                draggingVideoSize = 1;
            },
            stop: function (event, ui) {
                videoSizeLeft = ui.position.left;
                videoSizeRight = ui.position.left + ui.size.width;
                videoSizeTop = ui.position.top;
                videoSizeBottom = ui.position.top + ui.size.height;
                videoSizeWidthSelect = ui.size.width * 2;
                videoSizeHeightSelect = ui.size.height * 2;

                oldPositionVideoLeft = videoSizeLeft;
                oldPositionVideoTop = videoSizeTop;
                draggingVideoSize = 0;
            }
        });
        $("#selectVideoArea").draggable({
            drag: function (event, ui) {
                videoSizeLeft += (oldPositionVideoLeft * -1) + ui.offset.left;
                videoSizeTop += (oldPositionVideoTop * -1) + ui.position.top;

                oldPositionVideoLeft = ui.offset.left;
                oldPositionVideoTop = ui.position.top;
            }
        });

        function updateSend() {

            if (dataFlunsh > 9) { dataFlunsh = 0; }
            if (dataFlunsh == 0) { fd1 = new FormData(); fd = ""; };
            if (dataFlunsh == 5) { fd2 = new FormData(); fd = ""; };
            if (dataFlunsh == 0) {
                fd1.append("doing", 1);
                fd1.append("inputConvolutNumber", inputConvolutNumber);   
            }

            if (dataFlunsh == 5) {
                fd2.append("doing", 2);
                fd2.append("inputConvolutNumber", inputConvolutNumber); 
            }


         
            if (dataFlunsh == 9) {
                setTimeout(function(){
                    mediaRecorder["callerAudio-Own_1"].start(videoRate * 10);
                }, videoRate / 2)
            }

            if (dataFlunsh == 4) {
                setTimeout(function(){
                    mediaRecorder["callerAudio-Own_2"].start(videoRate * 10);
                }, videoRate / 2)
            }

            if (dataFlunsh == 5) {
                setTimeout(function(){
                    mediaRecorder["callerAudio-Own_1"].stop();
                }, videoRate / 2)
            }

            if (dataFlunsh == 0) {
                setTimeout(function(){
                    mediaRecorder["callerAudio-Own_2"].stop();
                }, videoRate / 2)
            }



            canvasMagic.width = videoSizeWidthSelect / 2;
            canvasMagic.height = videoSizeHeightSelect / 2;
            videoMagic.height = (160 / videoMagic.videoWidth) * videoMagic.videoHeight;
            videoMagic.width = 160;
            context.drawImage(videoMagic, videoSizeLeft * -1, videoSizeTop * -1, (videoMagic.width / 1), (videoMagic.height / 1));
            let dataVideoMagic = canvasMagic.toDataURL('image/jpeg', 0.92);


            if (dataFlunsh < 5) { fd1.append("boingy_" + dataFlunsh, dataVideoMagic.replace("data:image/jpeg;base64,", "")); }
            if (dataFlunsh > 4) { fd2.append("boingy_" + dataFlunsh, dataVideoMagic.replace("data:image/jpeg;base64,", "")); }
            
            if (dataFlunsh == 7) { fd1.append("fleoAudio", fleoAudio_1_Send); }
            if (dataFlunsh == 2) { fd2.append("fleoAudio", fleoAudio_2_Send); }
                
                if (dataFlunsh == 3 && waitOnStart == 0|| dataFlunsh == 8 && waitOnStart == 0) {
                    if (dataFlunsh == 3) { fd = fd2; }
                    if (dataFlunsh == 8) { fd = fd1; }
                $.ajax({
                    type: "POST",
                    url: "videophone/php/post.fleo.at.php",
                    data: fd,
                    dataType: "json",
                    contentType: false,
                    processData: false
                }).done(function (data2) {

                    returnData = JSON.parse(data2);
                    if (inputConvolutNumber == 999) {
                        inputConvolutNumber = parseInt(returnData[Object.keys(returnData).length - 1].inputConvolutNumberSelf);
                    }
                    for (let i = 0; i < Object.keys(returnData).length - 1; i++) {
                        videoAll.push(returnData[i].inputConvolutNumber);
                        meantToGo[returnData[i].inputConvolutNumber] = 0;
                        let timestampBufferCheck = new Date().getTime();
                        if ($("#imgPart-" + returnData[i].inputConvolutNumber).length) {
           
                            setTimeout(function(){
                                
                            audioPlayer[returnData[i].inputConvolutNumber + "-" + trackNum[returnData[i].inputConvolutNumber]].src = returnData[i][returnData[i].inputConvolutNumber + "_fleoAudio"];
                            audioPlayer[returnData[i].inputConvolutNumber + "-" + trackNum[returnData[i].inputConvolutNumber]].seek = 0.1;
                            audioPlayer[returnData[i].inputConvolutNumber + "-" + trackNumPlay[returnData[i].inputConvolutNumber]].play();
                            setTimeout(function(){ audioPlayer[returnData[i].inputConvolutNumber + "-" + trackNumPlay[returnData[i].inputConvolutNumber]].pause(); }, 1000);

                                trackNum[returnData[i].inputConvolutNumber]++;
                                trackNumPlay[returnData[i].inputConvolutNumber]++;
                                if (trackNum[returnData[i].inputConvolutNumber] == 6) {
                                    trackNum[returnData[i].inputConvolutNumber] = 1;
                                };
                                if (trackNumPlay[returnData[i].inputConvolutNumber] == 6) {
                                    trackNumPlay[returnData[i].inputConvolutNumber] = 1;
                                };
                            
                            if (returnData[i][returnData[i].inputConvolutNumber + "_boingy_0"] != null) {

                            $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_0"]);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_1"]);
                            }, videoRate);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_2"]);
                            }, videoRate * 2);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_3"]);
                            }, videoRate * 3);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_4"]);
                            }, videoRate * 4);
                        } else {
                            $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_5"]);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_6"]);
                            }, videoRate);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_7"]);
                            }, videoRate * 2);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_8"]);
                            }, videoRate * 3);
                            setTimeout(function () {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_9"]);
                            }, videoRate * 4);
                        }
                        }, 300 - (timestampBufferCheck - timestampBuffer)); 

                        } else {
                            $("#show").append('<div style="position:relative;display:inline-block;float:left;vertical-align:top;" id="partContainer-' + returnData[i].inputConvolutNumber + '"><img class="imgPart" icn="' + returnData[i].inputConvolutNumber + '" style="width:160px;height:auto;display:inline-block;float:left;vertical-align:top;" id="imgPart-' + returnData[i].inputConvolutNumber + '" src="data:image/jpeg;base64,' + webcamBlank + '" />' +
                                '<div style="display:none;">' +
                                '<audio id="callerAudio-1-' + returnData[i].inputConvolutNumber + '" style="display:block;" controls src=""></audio>' +
                                '<audio id="callerAudio-2-' + returnData[i].inputConvolutNumber + '" style="display:block;" controls src=""></audio>' +
                                '<audio id="callerAudio-3-' + returnData[i].inputConvolutNumber + '" style="display:block;" controls src=""></audio>' +
                                '<audio id="callerAudio-4-' + returnData[i].inputConvolutNumber + '" style="display:block;" controls src=""></audio>' +
                                '<audio id="callerAudio-5-' + returnData[i].inputConvolutNumber + '" style="display:block;" controls src=""></audio>');
                            audioPlayer[returnData[i].inputConvolutNumber + "-1"] = document.getElementById("callerAudio-1-" + returnData[i].inputConvolutNumber);
                            audioPlayer[returnData[i].inputConvolutNumber + "-2"] = document.getElementById("callerAudio-2-" + returnData[i].inputConvolutNumber);
                            audioPlayer[returnData[i].inputConvolutNumber + "-3"] = document.getElementById("callerAudio-3-" + returnData[i].inputConvolutNumber);
                            audioPlayer[returnData[i].inputConvolutNumber + "-4"] = document.getElementById("callerAudio-4-" + returnData[i].inputConvolutNumber);
                            audioPlayer[returnData[i].inputConvolutNumber + "-5"] = document.getElementById("callerAudio-5-" + returnData[i].inputConvolutNumber);

                            trackNum[returnData[i].inputConvolutNumber] = 1;
                            trackNumPlay[returnData[i].inputConvolutNumber] = 1;
                            
                                audioPlayer[returnData[i].inputConvolutNumber + "-1"].src = returnData[i][returnData[i].inputConvolutNumber + "_fleoAudio"];
                                audioPlayer[returnData[i].inputConvolutNumber + "-1"].seek = 0.1;
                                audioPlayer[returnData[i].inputConvolutNumber + "-1"].play();
                            
                            if (parseInt(returnData[i].inputConvolutNumber) !== parseInt(inputConvolutNumber)) {
                                audioPlayer[returnData[i].inputConvolutNumber + "-1"].volume = 0.75;
                                audioPlayer[returnData[i].inputConvolutNumber + "-2"].volume = 0.75;
                                audioPlayer[returnData[i].inputConvolutNumber + "-3"].volume = 0.75;
                                audioPlayer[returnData[i].inputConvolutNumber + "-4"].volume = 0.75;
                                audioPlayer[returnData[i].inputConvolutNumber + "-5"].volume = 0.75;
                            } else {
                                audioPlayer[returnData[i].inputConvolutNumber + "-1"].volume = 0.0;
                                audioPlayer[returnData[i].inputConvolutNumber + "-2"].volume = 0.0;
                                audioPlayer[returnData[i].inputConvolutNumber + "-3"].volume = 0.0;
                                audioPlayer[returnData[i].inputConvolutNumber + "-4"].volume = 0.0;
                                audioPlayer[returnData[i].inputConvolutNumber + "-5"].volume = 0.0;
                            }

                            setTimeout(function(){
                            if (returnData[i][returnData[i].inputConvolutNumber + "_boingy_0"] != null) {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_0"]);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_1"]);
                                }, videoRate);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_2"]);
                                }, videoRate * 2);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_3"]);
                                }, videoRate * 3);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_4"]);
                                }, videoRate * 4);
                            } else {
                                $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_5"]);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_6"]);
                                }, videoRate);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_7"]);
                                }, videoRate * 2);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_8"]);
                                }, videoRate * 3);
                                setTimeout(function () {
                                    $("#imgPart-" + returnData[i].inputConvolutNumber).attr("src", "data:image/jpeg;base64," + returnData[i][returnData[i].inputConvolutNumber + "_boingy_9"]);
                                }, videoRate * 4);
                            }
                            }, 300 - (timestampBufferCheck - timestampBuffer)); 

                        }

                        $("#imgPart-" + returnData[i].inputConvolutNumber).click(function () {

                        });
                    }

                    $(".imgPart").each(function () {
                        if (parseInt($(this).attr("icn")) !== inputConvolutNumber) {
                            if (videoAll.indexOf($(this).attr("icn")) === -1) {
                                meantToGo[$(this).attr("icn")] = 1;
                                let controlGone = $(this).attr("icn");
                                setTimeout(function () {
                                    if (meantToGo[controlGone] == 1 || meantToGo[controlGone] == 2) {
                                        $("#partContainer-" + controlGone).remove();
                                    }
                                }, 5000)
                            }

                            if (meantToGo[$(this).attr("icn")] == 1) {
                                meantToGo[$(this).attr("icn")] = 2;
                                let controlGone = $(this).attr("icn");
                                if (meantToGo[controlGone] == 2) {
                                    meantToGo[controlGone] = 1;
                                    setTimeout(function () {
                                        if (meantToGo[controlGone] < 1) {
                                            // $.post("/php/remove.fleo.at.php", { doing: 1, gone: controlGone }, function(){ }); 
                                        }
                                    }, 3000);
                                }
                            }
                        }
                    });
                    videoAll = [];
                });
            }         
            dataFlunsh++;
        };

        function hideStart() {
            // doVideoSending = 1;
            startbutton.style.display = "none";
            stopbutton.style.display = "block";
        }

        function hideStop() {
            // doVideoSending = 1;
            startbutton.style.display = "block";
            stopbutton.style.display = "none";
        }

        startbutton.addEventListener('click', function (ev) {
            hideStart();
            timestampBuffer = new Date().getTime();
            var updateSendInterval = setInterval(function () {
                updateSend();
            }, videoRate);
            ev.preventDefault();
            stopbutton.onclick = function () {
                hideStop();
                clearInterval(updateSendInterval);
                mediaRecorder["callerAudio-Own_1"].stop();
                mediaRecorder["callerAudio-Own_2"].stop();
                chunks["callerAudio-Own_1"] = [];
                chunks["callerAudio-Own_2"] = [];
            };
            if (waitOnStart == 1) {
                setTimeout(function(){ waitOnStart = 0; }, 2000);
            }
        }, false);

        async function doTheVolumeMeterOwn() {
            await audioCtxVolume["callerAudio-Own"].audioWorklet.addModule('videophone/fleo.at_volumeMeterProcessor.js');
            chunks["callerAudio-Own"] = [];
            if (!recReader["callerAudio-Own"]) {
                recReader["callerAudio-Own"] = new FileReader();
            }
            fleoNodeSource["callerAudio-Own"] = audioCtxVolume["callerAudio-Own"].createMediaStreamSource(window.stream);
            volumeMeterNode["callerAudio-Own"] = new AudioWorkletNode(audioCtxVolume["callerAudio-Own"], 'vumeter');
            volumeMeterGrayNode["callerAudio-Own"] = new AudioWorkletNode(audioCtxVolume["callerAudio-Own"], 'vumeter');
            volumeMeterNode["callerAudio-Own"].port.onmessage = event => {
                let _volume = 0
                let _sensibility = 1
                if (event.data.volume) {
                    _volume = event.data.volume;
                    leds("Own", (_volume * 100) / _sensibility)
                }
            }
            volumeMeterGrayNode["callerAudio-Own"].port.onmessage = event => {
                let _volume = 0
                let _sensibility = 1
                if (event.data.volume) {
                    _volume = event.data.volume;
                    ledsGray("Own", (_volume * 100) / _sensibility)
                }
            }
            gainNode["callerAudio-Own"] = audioCtxVolume["callerAudio-Own"].createGain();
            fleoDestination["callerAudio-Own"] = audioCtxVolume["callerAudio-Own"].createMediaStreamDestination();
            fleoNodeSource["callerAudio-Own"].connect(volumeMeterGrayNode["callerAudio-Own"]);
            fleoNodeSource["callerAudio-Own"].connect(volumeMeterNode["callerAudio-Own"]);
            fleoNodeSource["callerAudio-Own"].connect(gainNode["callerAudio-Own"]);
            fleoMediaStream["callerAudio-Own"] = gainNode["callerAudio-Own"].connect(fleoDestination["callerAudio-Own"]);
            mediaRecorder["callerAudio-Own_1"] = new MediaRecorder(fleoMediaStream["callerAudio-Own"].stream, {
                mimeType: 'audio/webm;codecs=opus'
            });
            mediaRecorder["callerAudio-Own_2"] = new MediaRecorder(fleoMediaStream["callerAudio-Own"].stream, {
                mimeType: 'audio/webm;codecs=opus'
            });

            const fileReader_1 = new FileReader();
            const fileReader_2 = new FileReader();

            chunksLane["callerAudio-Own_1"] = [];
            chunksLane["callerAudio-Own_2"] = [];

            mediaRecorder["callerAudio-Own_1"].ondataavailable = function (e) {
                chunksLane["callerAudio-Own_1"].push(e.data);
            }
            mediaRecorder["callerAudio-Own_2"].ondataavailable = function (e) {
                chunksLane["callerAudio-Own_2"].push(e.data);
            }

            mediaRecorder["callerAudio-Own_1"].onstop = function (e) {
                fileReader_1.onloadend = function () {
                    fleoAudio_1_Send = fileReader_1.result;
                }
                fileReader_1.readAsDataURL(new Blob(chunksLane["callerAudio-Own_1"], {
                    type: 'audio/webm;codecs=opus'
                }));
                chunksLane["callerAudio-Own_1"] = [];
            }
            mediaRecorder["callerAudio-Own_2"].onstop = function (e) {
                fileReader_2.onloadend = function () {
                    fleoAudio_2_Send = fileReader_2.result;
                }
                fileReader_2.readAsDataURL(new Blob(chunksLane["callerAudio-Own_2"], {
                    type: 'audio/webm;codecs=opus'
                }));
                chunksLane["callerAudio-Own_2"] = [];
            }
            gainNode["callerAudio-Own"].connect(volumeMeterNode["callerAudio-Own"]);
        }

        function takepicture() {

        }

        function gotStream(stream) {
            window.stream = stream;
            doTheVolumeMeterOwn(stream);
            if (audioChanged == 0) {
                videoMagic.srcObject = stream;
                videoMagic.height = (640 / videoMagic.videoWidth) * videoMagic.videoHeight;
                videoMagic.width = 640;
                setTimeout(function () {
                    $("#selectVideoArea").css({
                        "background": "#ffffff4f",
                        "width": $("#videoMagic").css("width"),
                        "height": $("#videoMagic").css("height")
                    });
                    videoSizeHeightSelect = parseInt($("#selectVideoArea").css("height")) * 2;
                }, 500);
                videoMagic.play();
                startup2();
            } else {
                videoMagic.srcObject = stream;
                videoMagic.play();
                audioChanged = 0;
            }
            return navigator.mediaDevices.enumerateDevices();
        }