(function($) {
    "use strict"; // Start of use strict
    var wizard_tour = null, wizard_tour_open = false, wizard_steps = [];
    var drag_slider = false, drag_slider_start=0, drag_slider_end=0;
    var args_callout = [];
    var interval_adjust_embed_helpers_all, count_adjust_embed_helpers_all=0;

    $(document).on('show.bs.modal', '.modal', function (event) {
        var zIndex = 2000 + (10 * $('.modal:visible').length);
        $(this).css('z-index', zIndex);
        setTimeout(function() {
            $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
        }, 0);
    });

    $(document).ajaxSend(function () {
        try {
            Pace.start();
        } catch (e) {}
    })
    $(document).ajaxStop(function () {
        try {
            Pace.stop();
        } catch (e) {}
    })

    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll("form[id^='frm']").forEach((form) => {
            const fileInput = form.querySelector("input[type='file']");
            const uploadButton = form.querySelector("input[type='submit']");
            if (!fileInput || !uploadButton) return;
            fileInput.addEventListener("change", function () {
                uploadButton.disabled = !fileInput.files.length;
            });
            form.addEventListener("reset", function () {
                uploadButton.disabled = true;
            });
            uploadButton.disabled = true;
        });
    });

    window.login = function () {
        $('#username_l').removeClass("error-highlight");
        $('#password_l').removeClass("error-highlight");
        try {
            $('#username_l').tooltipster('destroy');
        } catch (e) {}
        try {
            $('#password_l').tooltipster('destroy');
        } catch (e) {}
        var username = $('#username_l').val();
        var password = $('#password_l').val();
        var btn_label = $('#btn_login').html();
        $('#btn_login').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#btn_login').addClass("disabled");
        var complete = true;
        if($('#captcha_code').length && autologin==0) {
            if($('#captcha_code').val()!='') {
                $('#captcha_code').removeClass("error-highlight");
                var valid_captcha = window.captcha.valid($('input[id="captcha_code"]').val());
                if(!valid_captcha) {
                    $('#captcha_code').addClass("error-highlight");
                    complete = false;
                }
            } else {
                $('#captcha_code').addClass("error-highlight");
                complete = false;
            }
        }
        if(username=='') {
            $('#username_l').addClass("error-highlight");
            complete = false;
        }
        if(password=='') {
            $('#password_l').addClass("error-highlight");
            complete = false;
        }
        var remember_me = $('#remember_l').is(':checked') ? 1 : 0;
        if(complete) {
            $.ajax({
                url: "ajax/login.php",
                type: "POST",
                data: {
                    username_svt: username,
                    password_svt: password,
                    remember_svt: remember_me,
                    autologin: autologin
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    switch(rsp.status) {
                        case 'ok':
                            if(window.redirect!=='') {
                                location.href=decodeURI(window.redirect);
                            } else {
                                location.href="index.php";
                            }
                            break;
                        case '2fa':
                            $('#modal_check_login_2fa').modal('show');
                            setTimeout(function() {
                                $('#code_check_2fa').focus();
                            },300);
                            $('#btn_login').html(btn_label);
                            $('#btn_login').removeClass("disabled");
                            break;
                        case 'blocked':
                            $('#username_l').addClass("error-highlight");
                            $('#username_l').tooltipster({
                                theme: 'tooltipster-error',
                                animation: 'grow',
                                delay: 0,
                                arrow: true,
                                autoClose: false,
                                trigger: function() {},
                                content: $('<span style="color:red;">'+window.login_labels.account_locked+'</span>')
                            });
                            $('#username_l').tooltipster('show');
                            setTimeout(function() {
                                $('#username_l').tooltipster('hide', function() {
                                    $('#username_l').tooltipster('destroy');
                                });
                            },5000);
                            $('#btn_login').html(btn_label);
                            $('#btn_login').removeClass("disabled");
                            break;
                        case 'max_concurrent_sessions':
                            $('#modal_concurrent_sessions').modal('show');
                            $('#btn_login').html(btn_label);
                            $('#btn_login').removeClass("disabled");
                            break;
                        default:
                            if(rsp.status==='incorrect_username') {
                                $('#username_l').addClass("error-highlight");
                                $('#username_l').tooltipster({
                                    theme: 'tooltipster-error',
                                    animation: 'grow',
                                    delay: 0,
                                    arrow: true,
                                    autoClose: false,
                                    trigger: null,
                                    content: $('<span style="color:red;">'+window.login_labels.invalid_username+'</span>')
                                });
                                $('#username_l').tooltipster('show');
                                setTimeout(function() {
                                    $('#username_l').tooltipster('hide', function() {
                                        $('#username_l').tooltipster('destroy');
                                    });
                                },5000);
                            }
                            if(rsp.status==='incorrect_password') {
                                $('#password_l').addClass("error-highlight");
                                $('#password_l').tooltipster({
                                    theme: 'tooltipster-error',
                                    animation: 'grow',
                                    delay: 0,
                                    arrow: true,
                                    autoClose: false,
                                    trigger: null,
                                    content: $('<span style="color:red;">'+window.login_labels.invalid_password+'</span>'),
                                });
                                $('#password_l').tooltipster('show');
                                setTimeout(function() {
                                    $('#password_l').tooltipster('hide', function() {
                                        $('#password_l').tooltipster('destroy');
                                    });
                                },5000);
                            }
                            $('#btn_login').html(btn_label);
                            $('#btn_login').removeClass("disabled");
                            break;
                    }
                },
                error: function() {
                    $('#btn_login').html(btn_label);
                    $('#btn_login').removeClass("disabled");
                }
            });
        } else {
            $('#btn_login').html(btn_label);
            $('#btn_login').removeClass("disabled");
        }
    }

    window.session_register = function () {
        $('#modal_register button').addClass("disabled");
        $.ajax({
            url: "ajax/session_register.php",
            type: "POST",
            async: true,
            success: function (json) {
                location.href = 'register.php';
            }
        });
    }

    window.register_account = function () {
        var complete = true;
        var username = $('#username_r').val();
        var email = $('#email_r').val();
        var password = $('#password_r').val();
        var password2 = $('#password2_r').val();
        if(username=='') {
            complete = false;
            $('#username_r').addClass("error-highlight");
        } else {
            $('#username_r').removeClass("error-highlight");
        }
        if(email=='') {
            complete = false;
            $('#email_r').addClass("error-highlight");
        } else {
            $('#email_r').removeClass("error-highlight");
        }
        if(password=='') {
            complete = false;
            $('#password_r').addClass("error-highlight");
        } else {
            $('#password_r').removeClass("error-highlight");
        }
        if(password2=='') {
            complete = false;
            $('#password2_r').addClass("error-highlight");
        } else {
            $('#password2_r').removeClass("error-highlight");
        }
        if((password!='') && (password2!='')) {
            if(password!=password2) {
                complete = false;
                $('#password_r').addClass("error-highlight");
                $('#password2_r').addClass("error-highlight");
            } else {
                $('#password_r').removeClass("error-highlight");
                $('#password2_r').removeClass("error-highlight");
            }
        }
        if($('#captcha_code').length && auto_register!=1) {
            if($('#captcha_code').val()!='') {
                $('#captcha_code').removeClass("error-highlight");
                var valid_captcha = window.captcha.valid($('input[id="captcha_code"]').val());
                if(!valid_captcha) {
                    $('#captcha_code').addClass("error-highlight");
                    complete = false;
                }
            } else {
                $('#captcha_code').addClass("error-highlight");
                complete = false;
            }
        }
        if($('#terms_and_conditions').length && auto_register!=1) {
            if($('#terms_and_conditions').is(':checked')) {
                $('#terms_and_conditions').removeClass("error-highlight");
            } else {
                $('#terms_and_conditions').addClass("error-highlight");
                complete = false;
            }
        }
        if(complete) {
            $('#btn_register').addClass("disabled");
            $.ajax({
                url: "ajax/register.php",
                type: "POST",
                data: {
                    username_svt: username,
                    email_svt: email,
                    password_svt: password,
                    language: window.language,
                    default_language: window.default_language,
                    social_provider: social_provider,
                    social_identifier: social_identifier
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        var id_user = rsp.id_user;
                        if(parseInt(rsp.validate_email)==1) {
                            $.ajax({
                                url: "ajax/send_email.php",
                                type: "POST",
                                data: {
                                    type: 'activate',
                                    email: email,
                                    id_user: id_user,
                                    language: window.language
                                },
                                timeout: 15000,
                                async: true,
                                success: function (json) {
                                    var rsp = JSON.parse(json);
                                    if (rsp.status == "ok") {
                                        $('#modal_activate').modal("show");
                                    } else {
                                        alert(rsp.msg);
                                    }
                                },
                                error: function(){},
                            });
                        } else {
                            $.ajax({
                                url: "ajax/send_email.php",
                                type: "POST",
                                data: {
                                    type: 'notify',
                                    id_user: id_user
                                },
                                timeout: 15000,
                                async: true,
                                success: function () {
                                    location.href="index.php";
                                },
                                error: function(){
                                    location.href="index.php";
                                },
                            });
                        }
                    } else {
                        alert(rsp.msg);
                        $('#btn_register').removeClass("disabled");
                    }
                },
                error: function () {
                    alert(window.register_labels.error_msg);
                    $('#btn_register').removeClass("disabled");
                }
            });
        }
    }

    window.close_modal_activation = function () {
        $('#modal_activate').modal("hide");
        location.href="login.php";
    }

    window.send_verification_code = function() {
        var email = $('#email_f').val();
        if(email=='') {
            $('#email_f').addClass("error-highlight");
        } else {
            $('#btn_forgot_code').addClass('disabled');
            $.ajax({
                url: "ajax/send_email.php",
                type: "POST",
                data: {
                    type: 'forgot',
                    email: email,
                    language: window.language
                },
                timeout: 15000,
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        alert(window.login_labels.check_msg);
                    } else {
                        alert(rsp.msg);
                        $('#btn_forgot_code').removeClass('disabled');
                    }
                },
                error: function(){
                    alert(window.login_labels.error_msg);
                    $('#btn_forgot_code').removeClass('disabled');
                },
            });
        }
    }

    window.change_password_forgot = function() {
        var complete = true;
        var forgot_code = $('#forgot_code').val();
        var password = $('#password_f').val();
        var password2 = $('#repeat_password_f').val();

        if(forgot_code=='') {
            complete = false;
            $('#forgot_code').addClass("error-highlight");
        } else {
            $('#forgot_code').removeClass("error-highlight");
        }
        if(password=='') {
            complete = false;
            $('#password_f').addClass("error-highlight");
        } else {
            $('#password_f').removeClass("error-highlight");
        }
        if(password2=='') {
            complete = false;
            $('#repeat_password_f').addClass("error-highlight");
        } else {
            $('#repeat_password_f').removeClass("error-highlight");
        }
        if((password!='') && (password2!='')) {
            if(password!=password2) {
                complete = false;
                $('#password_f').addClass("error-highlight");
                $('#repeat_password_f').addClass("error-highlight");
            } else {
                $('#password_f').removeClass("error-highlight");
                $('#repeat_password_f').removeClass("error-highlight");
            }
        }
        if(complete) {
            $.ajax({
                url: "ajax/change_password_forgot.php",
                type: "POST",
                data: {
                    forgot_code: forgot_code,
                    password: password,
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        alert(window.login_labels.password_success);
                        location.href = 'login.php';
                    } else {
                        alert(rsp.msg);
                    }
                }
            });
        }
    }

    window.logout = function () {
        $.ajax({
            url: "ajax/logout.php",
            type: "POST",
            async: true,
            success: function (json) {
                location.href="login.php";
            }
        });
    }

    window.get_customers_stats = function() {
        $.ajax({
            url: "ajax/get_customers_stats.php",
            type: "POST",
            data: {},
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#num_customers_active').html(rsp.count_customers_active);
                $('#num_customers_total span').html(rsp.count_customers_total);
                $('#free_plans').html(rsp.free_plans);
                $('#last_registered').html(rsp.last_registered);
                $('#recurring_month').html(rsp.recurring_month);
                var html_subscriptions = '';
                jQuery.each(rsp.subscriptions, function(index, subscription) {
                    var plan = subscription.plan;
                    var active_users = subscription.active_users;
                    var perc = subscription.percentage_active_users;
                    html_subscriptions += '<div><h4 style="margin-bottom:1px;" class="small font-weight-bold">'+plan+' <span class="float-right">'+active_users+'</span></span></h4>\n' +
                        '                <div class="progress mb-2">\n' +
                        '                    <div class="progress-bar bg-primary" role="progressbar" style="width: '+perc+'%" aria-valuenow="'+perc+'" aria-valuemin="0" aria-valuemax="100"></div>\n' +
                        '                </div></div>';
                });
                $('#subscriptions_list').html(html_subscriptions);
            }
        });
    }

    window.get_services_stats = function() {
        $.ajax({
            url: "ajax/get_services_stats.php",
            type: "POST",
            data: {},
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#purchased_services').html(rsp.purchased_services);
                $('#revenue_services').html(rsp.revenue_services);
                var html_services = '';
                jQuery.each(rsp.services, function(index, service) {
                    var service_name = service.name;
                    var purchased = service.purchased;
                    var perc = service.percentage;
                    html_services += '<div><h4 style="margin-bottom:1px;" class="small font-weight-bold">'+service_name+' <span class="float-right">'+purchased+'</span></span></h4>\n' +
                        '                <div class="progress mb-2">\n' +
                        '                    <div class="progress-bar bg-primary" role="progressbar" style="width: '+perc+'%" aria-valuenow="'+perc+'" aria-valuemin="0" aria-valuemax="100"></div>\n' +
                        '                </div></div>';
                });
                $('#services_list').html(html_services);
            }
        });
    }

    window.get_dashboard_stats = function (id_vt) {
        $('#list_visitors i').show();
        $('#no_vt_msg').hide();
        $.ajax({
            url: "ajax/get_dashboard_stats.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: id_vt
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#num_rooms').html(rsp.count_rooms);
                $('#num_vt_rooms span').html(rsp.count_vt_rooms);
                $('#num_markers').html(rsp.count_markers);
                $('#num_vt_markers span').html(rsp.count_vt_markers);
                $('#num_pois').html(rsp.count_pois);
                $('#num_vt_pois span').html(rsp.count_vt_pois);
                $('#num_measures').html(rsp.count_measures);
                $('#num_vt_measures span').html(rsp.count_vt_measures);
                $('#num_slideshows').html(rsp.count_slideshows);
                $('#num_vt_slideshows span').html(rsp.count_vt_slideshows);
                $('#num_video360').html(rsp.count_video360);
                $('#num_vt_video360 span').html(rsp.count_vt_video360);
                $('#num_video_projects').html(rsp.count_video_projects);
                $('#num_vt_video_projects span').html(rsp.count_vt_video_projects);
                $('#total_visitors').html(rsp.total_visitors);
                $('#total_online_visitors').html(rsp.total_online_visitors);
                if(id_vt===null) {
                    if(rsp.count_virtual_tours==0) {
                        $('#list_visitors i').hide();
                        $('#no_vt_msg').show();
                    }
                    $('#num_virtual_tours').html(rsp.count_virtual_tours);
                    var visitors = rsp.visitors;
                    var online_visitors = rsp.online_visitors;
                    var html_visitors = "";
                    var d_count = 1;
                    var number_of_pages = Math.ceil(rsp.count_virtual_tours/window.count_vt_visitors);
                    jQuery.each(visitors, function(index, visitor) {
                        var vt_id = visitor.id;
                        var vt_name = visitor.name;
                        var count = visitor.count;
                        var perc = count / rsp.total_visitors * 100;
                        perc = Math.round(perc);
                        var page = Math.ceil(d_count / window.count_vt_visitors);
                        d_count++;
                        html_visitors += '<div class="d_pages d_page_'+page+'"><h4 style="margin-bottom:1px;" class="small font-weight-bold"><a href="index.php?p=statistics&id_vt='+vt_id+'">'+vt_name+'</a> <span class="float-right"><i class="fas fa-chart-line"></i> <b id="count_visitors_'+vt_id+'">'+count+'</b>&nbsp;&nbsp;<span id="online_visitors_'+vt_id+'"><i class="fas fa-eye"></i> <span>-</span></span></span></h4>\n' +
                            '                <div class="progress mb-2">\n' +
                            '                    <div id="perc_visitors_'+vt_id+'" class="progress-bar bg-primary" role="progressbar" style="width: '+perc+'%" aria-valuenow="'+perc+'" aria-valuemin="0" aria-valuemax="100"></div>\n' +
                            '                </div></div>';
                    });
                    if(html_visitors!='') {
                        if($('#list_visitors').html().includes('no_vt_msg')) {
                            $('#list_visitors').html(html_visitors).promise().done(function() {
                                jQuery.each(online_visitors, function(index, online_visitor) {
                                    var vt_id = online_visitor.id;
                                    var count = online_visitor.count;
                                    $('#online_visitors_'+vt_id+' span').html(count);
                                    if(count>0) {
                                        $('#online_visitors_'+vt_id).css('color','#4e73df');
                                    } else {
                                        $('#online_visitors_'+vt_id).css('color','black');
                                    }
                                });
                                $('#list_visitors').twbsPagination({
                                    totalPages: number_of_pages,
                                    visiblePages: window.count_vt_visitors,
                                    hideOnlyOnePage: true,
                                    first: '<<',
                                    prev: '<',
                                    next: '>',
                                    last: '>>',
                                    onPageClick: function (event, page) {
                                        $('.d_pages').hide();
                                        $('.d_page_'+page).show();
                                    }
                                });
                            });
                        } else {
                            jQuery.each(visitors, function(index, visitor) {
                                var vt_id = visitor.id;
                                var count = visitor.count;
                                var perc = count / rsp.total_visitors * 100;
                                perc = Math.round(perc);
                                $('#count_visitors_'+vt_id).html(count);
                                $('#perc_visitors_'+vt_id).css('width',perc+'%');
                                $('#online_visitors_'+vt_id).css('color','rgb(133, 135, 150)');
                                $('#online_visitors_'+vt_id+' span').html('-');
                            });
                            jQuery.each(online_visitors, function(index, online_visitor) {
                                var vt_id = online_visitor.id;
                                var count = online_visitor.count;
                                if(count>0) {
                                    $('#online_visitors_'+vt_id).css('color','#4e73df');
                                    $('#online_visitors_'+vt_id+' span').html(count);
                                } else {
                                    $('#online_visitors_'+vt_id).css('color','rgb(133, 135, 150)');
                                    $('#online_visitors_'+vt_id+' span').html('-');
                                }
                            });
                        }
                    }
                    $('#disk_space_used button').css('opacity',1);
                } else if(id_vt==='all') {
                    $('#num_virtual_tours').html(rsp.count_virtual_tours);
                } else {
                    $('#disk_space_used button').css('opacity',1);
                }
            }
        });
    };

    window.get_disk_space_stats = function (id_vt,id_user_s) {
        $('#disk_space_used').html('<i class="fas fa-circle-notch fa-spin"></i>');
        var id_user_t=id_user_s;
        if(id_user_t===null) id_user_t=window.id_user;
        $.ajax({
            url: "ajax/get_disk_space_stats.php",
            type: "POST",
            data: {
                id_user: id_user_t,
                id_virtualtour: id_vt
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#disk_space_used').html(rsp.disk_space_used);
            }
        });
    };

    window.get_disk_space_original = function () {
        $('#disk_space_original').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "ajax/get_disk_space_original.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#disk_space_original').html(rsp.disk_space_used);
            }
        });
    };

    window.get_disk_size_room = function () {
        $('#disk_space_original').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#disk_space_compressed').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#disk_space_multires').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#disk_space_total').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "ajax/get_disk_space_room.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour,
                id_room: window.id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#disk_space_original').html(rsp.disk_space_original);
                $('#disk_space_compressed').html(rsp.disk_space_compressed);
                $('#disk_space_multires').html(rsp.disk_space_multires);
                $('#disk_space_total').html(rsp.disk_space_total);
            },
            error: function() {
                $('#disk_space_original').html("--");
                $('#disk_space_compressed').html("--");
                $('#disk_space_multires').html("--");
                $('#disk_space_total').html("--");
            }
        });
    };

    window.get_resolution_room = function () {
        $('#resolution_original').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#resolution_compressed').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "ajax/get_resolution_room.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour,
                id_room: window.id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.resolution_original=='--') {
                    $('#resolution_original').parent().find('a').addClass('disabled');
                }
                if(rsp.resolution_compressed=='--') {
                    $('#resolution_compressed').parent().find('a').addClass('disabled');
                }
                $('#resolution_original').html(rsp.resolution_original);
                $('#resolution_compressed').html(rsp.resolution_compressed);
            },
            error: function() {
                $('#resolution_original').html("--");
                $('#resolution_compressed').html("--");
                $('#resolution_original').parent().find('a').addClass('disabled');
                $('#resolution_compressed').parent().find('a').addClass('disabled');
            }
        });
    };

    window.get_uploaded_file_size_stats = function (id_user_s) {
        $('#disk_space_used_uploaded').html('<i class="fas fa-circle-notch fa-spin"></i>');
        var id_user_t=id_user_s;
        if(id_user_t==null) id_user_t=window.id_user;
        $.ajax({
            url: "ajax/get_uploaded_file_size_stats.php",
            type: "POST",
            data: {
                id_user: id_user_t
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#disk_space_used_uploaded').html(rsp.disk_space_used);
            }
        });
    };

    window.get_virtual_tours = function (id_category,id_user_sel) {
        $.ajax({
            url: "ajax/get_virtual_tours.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_category: id_category,
                id_user_f: id_user_sel
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                parse_virtual_tour_list(rsp.vt_list,rsp.categories,id_category,rsp.users,id_user_sel,rsp.aws_s3_enabled);
                if(location.href.includes('edit_user')) {
                    if(rsp.vt_list.length==0) {
                        $('.nav-link[href="#vt_list_tab"]').addClass('disabled');
                    } else {
                        $('.nav-link[href="#vt_list_tab"]').removeClass('disabled');
                    }
                    $('#vt_num').html(rsp.vt_list.length);
                } else {
                    $('.countelem_header').html(rsp.vt_list.length);
                    $('.countelem_header').show();
                }
            }
        });
    };

    window.get_purchased_services = function (id_user_sel) {
        $.ajax({
            url: "ajax/get_purchased_services.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_user_f: id_user_sel
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('.nav-link[href="#services_tab"]').removeClass('disabled');
                $('#services_num').html(rsp.services_list.length);

            }
        });
    };

    window.get_maps = function () {
        $.ajax({
            url: "ajax/get_maps.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                var maps = rsp.maps;
                var permissions = rsp.permissions;
                $('.countelem_header').html(rsp.maps.length);
                $('.countelem_header').show();
                parse_map_list(maps,permissions);
            }
        });
    };

    window.get_rooms = function (id_virtualtour,p) {
        $.ajax({
            url: "ajax/get_rooms.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                p: p
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                window.rooms = rsp.rooms;
                var permissions = rsp.permissions;
                switch(p) {
                    case 'list':
                        $('.countelem_header').html(rsp.rooms.length);
                        $('.countelem_header').show();
                        parse_room_list(window.rooms,permissions);
                        break;
                    case 'marker':
                        parse_room_marker(window.rooms);
                        break;
                    case 'measure':
                        parse_room_measure(window.rooms);
                        break;
                    case 'poi':
                        parse_room_poi(window.rooms);
                        break;
                    case 'map':
                        get_option_rooms_target('room_default',0,window.id_room_default,null,null);
                        break;
                    case 'presentation':
                        get_presentation(id_virtualtour);
                        break;
                }
            }
        });
    };

    window.get_rooms_menu_list  = function (id_virtualtour) {
        $.ajax({
            url: "ajax/get_rooms_menu_list.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                language: window.selected_language
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                parse_rooms_menu_list(rsp);
            }
        });
    };

    window.get_presentation = function (id_virtualtour) {
        $.ajax({
            url: "ajax/get_presentation.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                array_presentation = rsp.presentation;
                parse_presentation_list();
                if(parseInt(rsp.add)==0) {
                    $('#btn_add_presentation_room').addClass('disabled');
                }
            }
        });
    };


    window.get_map = function (id_virtualtour,id_map,first_time) {
        window.map_points = [];
        if(first_time) {
            $('#msg_load_map').show();
        }
        $.ajax({
            url: "ajax/get_map.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                id_map: id_map,
                map_type: window.map_type
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                switch (window.map_type) {
                    case 'floorplan':
                        if(rsp.map!="") {
                            window.map_points = rsp.map_points;
                            window.id_map_sel = rsp.id_map;
                            if(first_time) {
                                var tmpImg = new Image();
                                tmpImg.src = rsp.map;
                                tmpImg.onload = function() {
                                    $('#msg_load_map').hide();
                                    $('#map_image').attr('src',rsp.map);
                                    $('#preview_image img').attr('src',rsp.map);
                                    $('#preview_image').show();
                                    parse_map_points(window.map_points);
                                    if(rsp.all_points) {
                                        $('#btn_add_point').prop("disabled",true);
                                        $('#btn_add_point').css('opacity',0.3);
                                    } else {
                                        $('#btn_add_point').prop("disabled",false);
                                        $('#btn_add_point').css('opacity',1);
                                    }
                                    setTimeout(function() {
                                        $('#map_compass').show();
                                    },500);
                                };
                            } else {
                                parse_map_points(window.map_points);
                                if(rsp.all_points) {
                                    $('#btn_add_point').prop("disabled",true);
                                    $('#btn_add_point').css('opacity',0.3);
                                } else {
                                    $('#btn_add_point').prop("disabled",false);
                                    $('#btn_add_point').css('opacity',1);
                                }
                            }
                        }
                        break;
                    case 'map':
                        jQuery.each(window.map_markers, function(index,marker) {
                            window.map_tour_l.removeLayer(marker);
                        });
                        window.map_points = rsp.map_points;
                        window.id_map_sel = rsp.id_map;
                        setTimeout(function() {
                            parse_map_points_l(window.map_points,first_time);
                        },100);
                        if(rsp.all_points) {
                            $('#btn_add_point').prop("disabled",true);
                            $('#btn_add_point').css('opacity',0.3);
                        } else {
                            $('#btn_add_point').prop("disabled",false);
                            $('#btn_add_point').css('opacity',1);
                        }
                        break;
                }
            }
        });
    };

    window.get_globe_map = function (id_globe,first_time) {
        window.map_points = [];
        $.ajax({
            url: "ajax/get_globe.php",
            type: "POST",
            data: {
                id_globe: id_globe
            },
            async: true,
            success: function (json) {
                jQuery.each(window.map_markers, function(index,marker) {
                    window.map_globe_l.removeLayer(marker);
                });
                var rsp = JSON.parse(json);
                window.map_points = rsp.map_points;
                parse_map_points_g(window.map_points,first_time);
                if(rsp.all_points) {
                    $('#btn_add_point').prop("disabled",true);
                    $('#btn_add_point').css('opacity',0.3);
                } else {
                    $('#btn_add_point').prop("disabled",false);
                    $('#btn_add_point').css('opacity',1);
                }
            }
        });
    };

    window.preview_vt = function(id,container_h,id_room) {
        $('.toolbar_preview_buttons').hide();
        $('.toolbar_preview_loading').removeClass('hidden');
        if($('#version').length) {
            var id_version = $('#version option:selected').attr('id');
        } else {
            var id_version = 0;
        }
        if($('#iframe_div').hasClass('mobile')) {
            var force_mobile = 1;
        } else {
            var force_mobile = 0;
        }
        $.ajax({
            url: "ajax/get_code.php",
            type: "POST",
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                var code = rsp.code;
                if(code!="") {
                    if(rsp.count_rooms>0 || rsp.external==1) {
                        if(id_room==0) {
                            if(id_version==0) {
                                var link = '../viewer/index.php?nostat=1&ignore_embedded=1&force_mobile='+force_mobile+'&code='+code;
                            } else {
                                var link = '../viewer/index.php?nostat=1&ignore_embedded=1&force_mobile='+force_mobile+'&code='+code+'&version='+id_version;
                            }
                        } else {
                            if(id_version==0) {
                                var link = '../viewer/index.php?nostat=1&ignore_embedded=1&force_mobile='+force_mobile+'&code='+code+'&room='+id_room;
                            } else {
                                var link = '../viewer/index.php?nostat=1&ignore_embedded=1&force_mobile='+force_mobile+'&code='+code+'&room='+id_room+'&version='+id_version;
                            }
                        }
                        $('#msg_no_room').hide();
                        $('#iframe_div').show();
                        $("#iframe_div").html("<iframe allow='accelerometer; camera; display-capture; fullscreen; geolocation; gyroscope; magnetometer; microphone; midi; xr-spatial-tracking;' " +
                            "width=\"100%\" height=\""+container_h+"px\" frameborder=\"0\" scrolling=\"no\" " +
                            "marginheight=\"0\" marginwidth=\"0\" " +
                            "src=\""+link+"\"" +
                            "></iframe>");
                        $('#toolbar_preview').show();
                        $('#iframe_div iframe').attr('height',container_h+'px');
                    } else {
                        $('#msg_no_room').show();
                        $('#iframe_div').hide();
                    }
                }
            }
        });
    }

    window.add_map_point = function (top,left) {
        window.adding_map_point = false;
        $('#btn_add_map_point').addClass('disabled');
        var id_room = $('#room_select option:selected').attr('id');
        if(window.map_type=='map') {
            var all_room_exif = $('#all_room_exif').is(':checked') ? 1 : 0;
            var center = window.map_tour_l.getCenter();
            var lat = center.lat;
            var lon = center.lng;
        } else {
            var all_room_exif = 0;
            var lat = null;
            var lon = null;
        }
        $.ajax({
            url: "ajax/add_map_point.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: id_room,
                id_map: window.id_map_sel,
                map_type: window.map_type,
                lat: lat,
                lon: lon,
                top: top,
                left: left,
                all_room_exif: all_room_exif
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    window.id_room_point_sel = parseInt(rsp.id_room_point_sel);
                    sessionStorage.setItem('add_point','1');
                    if(window.map_type=='map') {
                        var zoom = window.map_tour_l.getZoom();
                        sessionStorage.setItem('zoom',zoom);
                        $('#modal_add_map_point').modal('hide');
                    }
                    window.map_need_save = false;
                    save_map_settings(true);
                } else {
                    $('#btn_add_map_point').removeClass('disabled');
                }
            }
        });
    }

    window.add_map_point_g = function () {
        $('#btn_add_map_point').addClass('disabled');
        var id_vt = $('#vt_select_map option:selected').attr('id');
        var center = window.map_globe_l.getCenter();
        var lat = center.lat;
        var lon = center.lng;
        $.ajax({
            url: "ajax/add_map_point_g.php",
            type: "POST",
            data: {
                id_vt: id_vt,
                id_globe: window.id_globe,
                lat: lat,
                lon: lon
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    window.id_vt_point_sel = parseInt(rsp.id_vt_point_sel);
                    sessionStorage.setItem('add_point','1');
                    var zoom = window.map_globe_l.getZoom();
                    sessionStorage.setItem('zoom',zoom);
                    window.globe_need_save = false;
                    $('#modal_add_map_point').modal('hide');
                    save_globe(window.id_globe,true);
                } else {
                    $('#btn_add_map_point').removeClass('disabled');
                }
            }
        });
    }

    window.save_map_settings = function (reload) {
        var map_name = $('#map_name').val();
        var array_lang = {};
        array_lang['name'] = {};
        $('.input_lang[data-target-id="map_name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var point_color = $('#point_color').val();
        var point_view_color = $('#point_view_color').val();
        var point_size = $('#point_size').val();
        var point_view_size = $('#point_view_size').val();
        var width_d = $('#width_d').val();
        var width_m = $('#width_m').val();
        var north_degree = $('#north_degree').val();
        var zoom_level = $('#zoom_level option:selected').attr('id');
        var zoom_to_point = ($('#zoom_to_point').is(':checked')) ? 1 : 0;
        var map_thumb = ($('#map_thumb').is(':checked')) ? 1 : 0;
        var default_view = $('#default_view option:selected').attr('id');
        var info_link = $('#info_link').val();
        var info_type = $('#info_type option:selected').attr('id');
        var id_room_default = $('#room_default option:selected').attr('id');
        if(map_name!='') {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/save_map_settings.php",
                type: "POST",
                data: {
                    id_map: window.id_map_sel,
                    map_name: map_name,
                    point_color: point_color,
                    point_view_color: point_view_color,
                    point_size: point_size,
                    point_view_size: point_view_size,
                    north_degree: north_degree,
                    zoom_level: zoom_level,
                    zoom_to_point: zoom_to_point,
                    map_thumb: map_thumb,
                    width_d: width_d,
                    width_m: width_m,
                    default_view: default_view,
                    info_link: info_link,
                    info_type: info_type,
                    id_room_default: id_room_default,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.map_need_save = false;
                        if(reload) {
                            get_map(id_virtualtour,id_map_sel,false);
                            $('#btn_add_map_point').removeClass('disabled');
                            $('#msg_select_point').show();
                            $('.point_settings').hide();
                        }
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    } else {
                        if(reload) {
                            get_map(id_virtualtour,id_map_sel,false);
                            $('#btn_add_map_point').removeClass('disabled');
                            $('#msg_select_point').show();
                            $('.point_settings').hide();
                        }
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_map_point = function () {
        switch(map_type) {
            case 'map':
                var position = $('#point_pos_lat').val()+','+$('#point_pos_lon').val();
                break;
            case 'floorplan':
                var position = $('#point_pos').val();
                break;
        }
        $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
        $.ajax({
            url: "ajax/save_map_point.php",
            type: "POST",
            data: {
                id_room: window.id_room_sel,
                map_type: window.map_type,
                position: position
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                    },1000);
                } else {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    },1000);
                }
            },
            error: function() {
                $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                setTimeout(function () {
                    $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                    $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    $('#save_btn').removeClass("disabled");
                },1000);
            }
        });
    }

    window.save_globe_point = function () {
        var position = $('#point_pos_lat').val()+','+$('#point_pos_lon').val();
        var initial_pos = $('#initial_pos_tour').val();
        $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
        $.ajax({
            url: "ajax/save_globe_point.php",
            type: "POST",
            data: {
                id_globe: window.id_globe,
                id_vt: window.id_vt_sel,
                position: position,
                initial_pos: initial_pos
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                    },1000);
                } else {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    },1000);
                }
            },
            error: function() {
                $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                setTimeout(function () {
                    $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                    $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    $('#save_btn').removeClass("disabled");
                },1000);
            }
        });
    }

    window.change_all_room_exif = function() {
        if($('#all_room_exif').is(':checked')) {
            $("#room_select").prop("disabled", true);
            $(".selectpicker[data-id='room_select']").addClass("disabled");
            $('.preview_room_target').addClass('disabled');
        } else {
            $("#room_select").prop("disabled", false);
            $(".selectpicker[data-id='room_select']").removeClass("disabled");
            $('.preview_room_target').removeClass('disabled');
        }
        $('#room_select').selectpicker('refresh');
    }

    window.pre_add_map_point = function() {
        if(window.map_type=='map') {
            add_map_point(0,0);
        } else {
            $('#modal_add_map_point').modal('hide');
            $('#floorplan_add_point_msg').removeClass('d-none');
            $('#pointers_div').css('cursor','crosshair');
            window.adding_map_point = true;
            document.getElementById('pointers_div').addEventListener('click', function(event) {
                if(window.adding_map_point) {
                    var rect = this.getBoundingClientRect();
                    var left = event.clientX - rect.left;
                    var top = event.clientY - rect.top;
                    var point_size = parseInt($('#point_size').val());
                    top = Math.round(top / ratio_w);
                    left = Math.round(left / ratio_h);
                    top = top - (point_size/2);
                    left = left - (point_size/2);
                    $('#floorplan_add_point_msg').addClass('d-none');
                    $('#pointers_div').css('cursor','default');
                    add_map_point(top,left);
                }
            });
        }
    }

    function parse_map_points(points) {
        var html_points = '',html_map_select = '';
        jQuery.each(points, function(index, point) {
            var map_id = point.id;
            var map_top = parseInt(point.map_top);
            var map_left = parseInt(point.map_left);
            var map_name = point.name;
            var point_color = point.point_color;
            if(map_top!=null && point.id_map!=null) {
                if(point.id_map == window.id_map_sel) {
                    html_points += '<div id="pointer_'+map_id+'" style="top: '+map_top+'px; left: '+map_left+'px;" class="map_pointer_container"><div class="map_pointer_view"></div><div class="map_pointer_circle"></div></div>';
                }
            } else {
                html_map_select += '<option id="'+map_id+'">'+map_name+'</option>';
            }
        });
        try {
            $('#room_select').selectpicker('destroy');
        } catch (e) {}
        $('#room_select').empty();
        $('#room_select').html(html_map_select).promise().done(function () {
            $('#room_select').selectpicker('refresh');
            change_preview_room_image_map(null);
        });
        $('#pointers_div').empty();
        $('#pointers_div').html(html_points).promise().done(function () {
            $('.map_pointer_container').css('visibility','hidden');
            update_map_pointers_style(false);
            $(".map_pointer_container").draggable({
                containment: '#pointers_div',
                handle: '.map_pointer_circle',
                drag: function(event) {
                    var top = $(this).position().top;
                    var left = $(this).position().left;
                    var id = $(this).attr('id').replace('pointer_','');
                    set_point_map_pos(id,top,left);
                    click_map_point(id);
                },
                start: function (event, ui) {
                    $(this).addClass('dragging');
                    $(".map_pointer_container").removeClass('active');
                    $(this).addClass('active');
                    var id = $(this).attr('id').replace('pointer_','');
                    click_map_point(id);
                },
                stop: function (event, ui) {
                    $(this).removeClass('dragging');
                    var id = $(this).attr('id').replace('pointer_','');
                    click_map_point(id);
                    save_map_point();
                }
            });
            $('.map_pointer_circle').click(function (event) {
                if (!$(this).parent().hasClass('dragging')) {
                    var top = $(this).parent().position().top;
                    var left = $(this).parent().position().left;
                    $(".map_pointer_container").removeClass('active');
                    $(this).parent().addClass('active');
                    var id = $(this).parent().attr('id').replace('pointer_','');
                    set_point_map_pos(id,top,left);
                    click_map_point(id);
                }
            });
            setTimeout(function () {
                adjust_points_position();
                $('.map_pointer_container').css('visibility','visible');
                if(window.id_room_point_sel!='') {
                    $('#pointer_'+window.id_room_point_sel).trigger('click');
                }
            },250);
        });
    }

    window.update_map_pointers_style = function(map) {
        const rotation = 0;
        const fov = 90;
        let size = parseInt($('#point_size').val());
        let viewSize = parseInt($('#point_view_size').val());
        if(map) {
            size = size * 2;
            viewSize = viewSize * 2;
            $('.map_pointer_circle').css({'top':(size/2)+'px','left':(size/2)+'px'});
            $('.map_pointer_view').css({'top':(size/2)+'px','left':(size/2)+'px'});
        }
        const color = $('#point_color').val();
        const view_color = $('#point_view_color').val();
        $('.map_pointer_container').each(function() {
            const $currentMarker = $(this);
            const $dot = $currentMarker.find('.map_pointer_circle');
            const $cone = $currentMarker.find('.map_pointer_view');
            $currentMarker.css('transform', `rotate(${rotation}deg)`);
            $dot.css({
                width: `${size}px`,
                height: `${size}px`,
                backgroundColor: color,
                borderColor: color,
            });
            updateFovCone($cone, fov, viewSize, view_color);
        });
        if(!map) {
            adjust_points_position();
        }
    }

    function updateFovCone($coneElement, fovAngle, viewRadius, color) {
        $coneElement.css({
            width: `${viewRadius*2}px`,
            height: `${viewRadius*2}px`
        });
        const center = viewRadius;
        const points = [`${center}px ${center}px`];
        const steps = Math.max(10, Math.floor(fovAngle / 5));
        for (let i = 0; i <= steps; i++) {
            const angle = -fovAngle / 2 - 90 + (fovAngle * i / steps);
            const rad = angle * Math.PI / 180;
            const x = center + viewRadius * Math.cos(rad);
            const y = center + viewRadius * Math.sin(rad);
            points.push(`${x.toFixed(2)}px ${y.toFixed(2)}px`);
        }
        const polygon = `polygon(${points.join(', ')})`;
        const gradient = `radial-gradient(circle at 50% 50%, ${color}BF 0%, ${color}00 70%)`;
        $coneElement.css({
            'clip-path': polygon,
            'background': gradient
        });
    }

    function parse_map_points_l(points,first_time) {
        window.map_markers = [];
        var html_map_select = '';
        var point_size = $('#point_size').val();
        if((point_size=='') || (point_size<=0)) {
            point_size=20;
        }
        point_size = parseInt(point_size);
        point_size = point_size*2;
        var bounds = new L.LatLngBounds();
        var points_exist = false;
        var lat_new = '', lon_new = '';
        var count_point = 0;
        jQuery.each(points, function(index, point) {
            var id = parseInt(point.id);
            var name = point.name;
            var lat = point.lat;
            var lon = point.lon;
            if(lat!=null && lat!='') {
                points_exist = true;
                lat = parseFloat(lat);
                lon = parseFloat(lon);
                if(id==parseInt(window.id_room_point_sel)) {
                    lat_new=lat;
                    lon_new=lon;
                }
                var html = '<div id="pointer_'+id+'" class="map_pointer_container"><div class="map_pointer_view"></div><div style="background-image: url('+point.icon+');" class="map_pointer_circle"></div></div>';
                var icon = new L.DivIcon({
                    html: html,
                    iconSize: [point_size, point_size],
                    iconAnchor: [point_size/2, point_size/2]
                });
                var marker = L.marker([lat, lon], {
                    id: id,
                    icon: icon,
                    draggable: true,
                    autoPan: true
                });
                window.map_markers.push(marker);
                marker.on("click", function(e) {
                    var marker = e.target;
                    window.marker_sel = marker;
                    var id = marker.options.id;
                    click_map_point_l(id);
                    var position = marker.getLatLng();
                    var lat = position.lat;
                    var lon = position.lng;
                    $('#point_pos_lat').val(lat);
                    $('#point_pos_lon').val(lon);
                });
                marker.on("drag", function(e) {
                    var marker = e.target;
                    window.marker_sel = marker;
                    var id = marker.options.id;
                    click_map_point_l(id);
                    var position = marker.getLatLng();
                    var lat = position.lat;
                    var lon = position.lng;
                    $('#point_pos_lat').val(lat);
                    $('#point_pos_lon').val(lon);
                });
                marker.on("dragend", function(e) {
                    var marker = e.target;
                    var id = marker.options.id;
                    var position = marker.getLatLng();
                    var lat = position.lat;
                    var lon = position.lng;
                    $('#point_pos_lat').val(lat);
                    $('#point_pos_lon').val(lon);
                    save_map_point();
                });
                marker.addTo(window.map_tour_l);
                count_point++;
                bounds.extend(marker.getLatLng());
            } else {
                html_map_select += '<option id="'+id+'">'+name+'</option>';
            }
        });
        if(window.map_thumb==0) {
            $('.map_pointer_circle').css('background-size',0);
        }
        update_map_pointers_style(true);
        try {
            $('#room_select').selectpicker('destroy');
        } catch (e) {}
        $('#room_select').empty();
        $('#room_select').html(html_map_select).promise().done(function () {
            $('#room_select').selectpicker('refresh');
            change_preview_room_image_map(null);
        });
        if(points_exist && first_time) {
            if(window.id_room_point_sel!='') {
                var zoom = sessionStorage.getItem('zoom');
                if(zoom === null) {
                    zoom = 14;
                } else {
                    sessionStorage.removeItem('zoom');
                }
                window.map_tour_l.setView([lat_new, lon_new], zoom);
            } else {
                window.map_tour_l.fitBounds(bounds, {padding: [50,50]});
                if(count_point==1) {
                    window.map_tour_l.setZoom(14);
                }
            }
        }
        if(window.id_room_point_sel!='') {
            window.map_tour_l.eachLayer((ml)=>{
                if(ml instanceof L.Marker){
                    var id = parseInt(ml.options.id);
                    if(id == parseInt(window.id_room_point_sel)) {
                        window.marker_sel = ml;
                        click_map_point_l(id);
                        var position = ml.getLatLng();
                        var lat = position.lat;
                        var lon = position.lng;
                        $('#point_pos_lat').val(lat);
                        $('#point_pos_lon').val(lon);
                    }
                }
            });
        }
        $('#map_tour_div').hover(function () {
            if(!($('#map_tour_div').is(":focus"))) {
                $('#map_tour_div').focus();
            }
        });
    }

    window.toggle_map_thumb = function() {
        if($('#map_thumb').is(':checked')) {
            $('.map_pointer_circle').css('background-size','cover');
        } else {
            $('.map_pointer_circle').css('background-size',0);
        }
    }

    function parse_map_points_g(points,first_time) {
        var html_map_select = '';
        var bounds = new L.LatLngBounds();
        var points_exist = false;
        var lat_new = '', lon_new = '';
        var count_point = 0;
        jQuery.each(points, function(index, point) {
            var id = parseInt(point.id);
            var name = point.name;
            var lat = point.lat;
            var lon = point.lon;
            if(lat!=null && lat!='') {
                points_exist = true;
                lat = parseFloat(lat);
                lon = parseFloat(lon);
                if(id==parseInt(window.id_vt_point_sel)) {
                    lat_new=lat;
                    lon_new=lon;
                }
                var icon = new L.DivIcon({
                    html: "<div id='map_globe_icon_"+id+"' class='map_globe_icon'></div>",
                    iconSize: [10,10]
                });
                var marker = L.marker([lat, lon], {
                    id: id,
                    icon: icon,
                    draggable: true,
                    autoPan: true
                });
                window.map_markers.push(marker);
                marker.on("click", function(e) {
                    var marker = e.target;
                    window.marker_sel = marker;
                    var id = marker.options.id;
                    click_map_point_g(id);
                    var position = marker.getLatLng();
                    var lat = position.lat;
                    var lon = position.lng;
                    $('#point_pos_lat').val(lat);
                    $('#point_pos_lon').val(lon);
                });
                marker.on("drag", function(e) {
                    var marker = e.target;
                    window.marker_sel = marker;
                    var id = marker.options.id;
                    click_map_point_g(id);
                    var position = marker.getLatLng();
                    var lat = position.lat;
                    var lon = position.lng;
                    $('#point_pos_lat').val(lat);
                    $('#point_pos_lon').val(lon);
                });
                marker.on("dragend", function(e) {
                    var marker = e.target;
                    window.marker_sel = marker;
                    var id = marker.options.id;
                    var position = marker.getLatLng();
                    var lat = position.lat;
                    var lon = position.lng;
                    $('#point_pos_lat').val(lat);
                    $('#point_pos_lon').val(lon);
                    save_globe_point();
                });
                marker.addTo(window.map_globe_l);
                count_point++;
                bounds.extend(marker.getLatLng());
            } else {
                html_map_select += '<option id="'+id+'">'+name+'</option>';
            }
        });
        try {
            $('#vt_select_map').selectpicker('destroy');
        } catch (e) {}
        $('#vt_select_map').empty();
        $('#vt_select_map').html(html_map_select).promise().done(function () {
            $('#vt_select_map').selectpicker('refresh');
            change_preview_vt_image_map(null);
        });
        if(points_exist && first_time) {
            if(window.id_vt_point_sel!='') {
                var zoom = sessionStorage.getItem('zoom');
                if(zoom === null) {
                    zoom = 14;
                } else {
                    sessionStorage.removeItem('zoom');
                }
                window.map_globe_l.setView([lat_new, lon_new], zoom);
            } else {
                window.map_globe_l.fitBounds(bounds, {padding: [50,50]});
                if(count_point==1) {
                    window.map_globe_l.setZoom(14);
                }
            }
        }
        if(window.id_vt_point_sel!='') {
            window.map_globe_l.eachLayer((ml)=>{
                if(ml instanceof L.Marker){
                    var id = parseInt(ml.options.id);
                    if(id == parseInt(window.id_vt_point_sel)) {
                        window.marker_sel = ml;
                        click_map_point_g(id);
                        var position = ml.getLatLng();
                        var lat = position.lat;
                        var lon = position.lng;
                        $('#point_pos_lat').val(lat);
                        $('#point_pos_lon').val(lon);
                    }
                }
            });
        }
        $('#map_globe_div').hover(function () {
            if(!($('#map_globe_div').is(":focus"))) {
                $('#map_globe_div').focus();
            }
        });
    }

    window.adjust_point_g = function () {
        var point_size = $('#pointer_size').val();
        var point_color = $('#pointer_color').val();
        var point_border = $('#pointer_border').val();
        if(point_size!='') {
            $('.map_globe_icon').css('width',point_size+'px');
            $('.map_globe_icon').css('height',point_size+'px');
        }
        $('.map_globe_icon').css('background-color',point_color);
        $('.map_globe_icon').css('border-color',point_border);
    }

    window.change_marker_globe_position = function () {
        if(window.marker_sel!=null) {
            var lat = $('#point_pos_lat').val();
            var lon = $('#point_pos_lon').val();
            if((lat!='') && (lon!='')) {
                lat = lat.replace(',','.');
                lon = lon.replace(',','.');
                var newLatLng = new L.LatLng(lat, lon);
                window.marker_sel.setLatLng(newLatLng);
                save_globe_point();
            }
        }
    }

    window.change_marker_map_position = function () {
        if(window.marker_sel!=null) {
            var lat = $('#point_pos_lat').val();
            var lon = $('#point_pos_lon').val();
            if((lat!='') && (lon!='')) {
                lat = lat.replace(',','.');
                lon = lon.replace(',','.');
                var newLatLng = new L.LatLng(lat, lon);
                window.marker_sel.setLatLng(newLatLng);
                save_map_point();
            }
        }
    }

    function set_point_map_pos(id,top,left) {
        top = Math.round(top / ratio_w);
        left = Math.round(left / ratio_h);
        $('#point_pos').val(top+","+left);
        jQuery.each(window.map_points, function(index, point) {
            var id_point = point.id;
            if(id==id_point) {
                point.map_left = left;
                point.map_top = top;
                return;
            }
        });
    }

    function click_map_point(id) {
        if(window.id_room_sel!=id) {
            set_room_target_map(id);
            $('#btn_delete_point').attr('onclick','modal_delete_map_point('+id+');');
            $('#btn_mp_edit_room').attr('href','index.php?p=edit_room&id='+id);
            $('#btn_mp_markers').attr('href','index.php?p=markers&id_room='+id);
            $('#btn_mp_pois').attr('href','index.php?p=pois&id_room='+id);
            $('#msg_select_point').hide();
            $('.point_settings').show();
        }
        window.id_room_sel = id;
    }

    window.click_map_point_l = function(id) {
        if(window.id_room_sel!=id) {
            set_room_target_map(id);
            $('.map_pointer_container').removeClass('active');
            $('#pointer_'+id).addClass('active');
            $('#btn_delete_point').attr('onclick','modal_delete_map_point('+id+');');
            $('#btn_mp_edit_room').attr('href','index.php?p=edit_room&id='+id);
            $('#btn_mp_markers').attr('href','index.php?p=markers&id_room='+id);
            $('#btn_mp_pois').attr('href','index.php?p=pois&id_room='+id);
            $('#msg_select_point').hide();
            $('.point_settings').show();
        }
        window.id_room_sel = id;
    }

    window.click_map_point_g = function(id) {
        if(window.id_vt_sel!=id) {
            set_vt_target_map(id);
            $('.map_globe_icon').removeClass('map_tour_icon_active');
            $('#map_globe_icon_'+id).addClass('map_tour_icon_active');
            $('.map_globe_icon').parent().removeClass('map_tour_icon_top');
            $('#map_globe_icon_'+id).parent().addClass('map_tour_icon_top');
            $('#btn_delete_point').attr('onclick','modal_delete_globe_point('+id+');');
            $('#msg_select_point').hide();
            $('.point_settings').show();
        }
        window.id_vt_sel = id;
    }

    function parse_presentation_list() {
        var html = '';
        var first_row = true;
        var priority_1_old = 0;
        window.array_id_rooms = [];
        jQuery.each(array_presentation, function(index, presentation) {
            var id = presentation.id;
            var action = presentation.action;
            var room_id = presentation.id_room;
            var priority_1 = presentation.priority_1;
            if(priority_1_old==0) {
                priority_1_old = priority_1;
            }
            if(!window.array_id_rooms.includes(room_id)) {
                window.array_id_rooms.push(room_id);
            }
            var room_image = presentation.panorama_image;
            var room_name = presentation.room_name;
            var params = presentation.params;
            var panorama_type = presentation.panorama_type;
            var video_wait_end = parseInt(presentation.video_wait_end);
            var pos = presentation.pos;
            var sleep_ms = presentation.sleep;
            switch (action) {
                case'goto':
                    if(first_row) {
                        var mt = 0;
                        first_row = false;
                    } else {
                        var mt = 4;
                    }
                    var ml = 0;
                    var py = 2;
                    var b_color = 'warning';
                    var classn = 'p_room';
                    var priority_click_up = 'change_presentation_priority(1,\'up\','+id+');';
                    var priority_click_down = 'change_presentation_priority(1,\'down\','+id+');';
                    switch(panorama_type) {
                        case 'video':
                            if(video_wait_end==1) {
                                var text_append = '&nbsp;&nbsp;&nbsp;<i class="fas fa-video"></i>&nbsp;<i class="far fa-hand-paper"></i>';
                            } else {
                                var text_append = '&nbsp;&nbsp;&nbsp;<i class="fas fa-video"></i>';
                            }
                            break;
                        default:
                            var text_append = '&nbsp;&nbsp;&nbsp;<i class="fas fa-image"></i>';
                            break;
                    }
                    if(pos!='') {
                        text_append += '&nbsp;&nbsp;&nbsp;<i class="fas fa-bullseye"></i>';
                    }
                    var text = '<i class="far fa-arrow-alt-circle-up"></i> <b>'+room_name+'</b>&nbsp;&nbsp;&nbsp;<i class="far fa-pause-circle"></i> '+sleep_ms+'ms'+text_append;
                    var html_preview = '                        <div class="noselect d-inline-block ml-2 align-middle text-left"><span style="cursor: pointer" onclick="open_preview_presentation('+index+','+array_presentation[index].id_room+');return false;" class="badge badge-secondary d-inline-block"><i class="fas fa-eye"></i> '+window.backend_labels.preview_presentation+'</span></div>\n';
                    break;
                case 'lookAt':
                    var mt = 1;
                    var ml = 4;
                    var py = 1;
                    var b_color = 'primary';
                    var classn = 'p_subs p_sub_'+room_id;
                    var priority_click_up = 'change_presentation_priority(2,\'up\','+id+');';
                    var priority_click_down = 'change_presentation_priority(2,\'down\','+id+');';
                    room_image = '';
                    var text = '<i class="fas fa-bullseye"></i> '+params+'&nbsp;&nbsp;&nbsp;<i class="far fa-pause-circle"></i> '+sleep_ms+'ms';
                    var html_preview = '                        <div class="noselect d-inline-block ml-2 align-middle text-left"><span style="cursor: pointer" onclick="open_preview_presentation('+index+','+array_presentation[index].id_room+');return false;" class="badge badge-secondary d-inline-block"><i class="fas fa-eye"></i> '+window.backend_labels.preview_presentation+'</span></div>\n';
                    break;
                case 'type':
                    var mt = 1;
                    var ml = 4;
                    var py = 1;
                    var b_color = 'info';
                    var classn = 'p_subs p_sub_'+room_id;
                    var priority_click_up = 'change_presentation_priority(2,\'up\','+id+');';
                    var priority_click_down = 'change_presentation_priority(2,\'down\','+id+');';
                    room_image = '';
                    var text = '<i class="far fa-comment-dots"></i> '+params+ '&nbsp;&nbsp;&nbsp;<i class="far fa-pause-circle"></i> '+sleep_ms+'ms';
                    var html_preview = '';
                    break;
            }

            if(priority_1!=priority_1_old) {
                html += '<div onclick="open_modal_p_action('+array_presentation[index-1].id_room+');" style="cursor: pointer" class="card ml-4 mt-1 py-1 bg-info text-white">\n' +
                    '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                    '                <div class="row">\n' +
                    '                    <div class="col-md-12 text-center">\n' +
                    '                        <i class="fas fa-plus-circle"></i> <span>'+window.backend_labels.add_action+'</span>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>';
                priority_1_old = priority_1;
            }

            html += '<div class="'+classn+' noselect card mt-'+mt+' ml-'+ml+' py-'+py+' border-left-'+b_color+'">\n' +
                '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                '                <div class="row">\n' +
                '                    <div class="col-md-10 text-center text-sm-center text-md-left text-lg-left">\n';
            if(room_image!='') {
                if(window.s3_enabled==1) {
                    var room_image_url = window.s3_url+'viewer/panoramas/thumb/'+room_image;
                } else {
                    var room_image_url = '../viewer/panoramas/thumb/'+room_image;
                }
                html += '                        <div style="cursor: pointer" onclick="presentation_elem_edit('+index+');" class="d-inline-block align-middle hover_p"><img style="height: 40px;" src="'+room_image_url+'" /></div>\n';
            }
            html += '                        <div style="cursor: pointer" onclick="presentation_elem_edit('+index+');" class="noselect d-inline-block ml-2 align-middle text-left hover_p">'+text+'</div>\n' +
                html_preview +
                '                    </div>\n'+
                '                    <div class="col-md-2 align-self-center text-center text-sm-center text-md-right text-lg-right">\n';
            html += '                        <i onclick="'+priority_click_up+'" class="icon_order fas fa-caret-up"></i>&nbsp;&nbsp;<i onclick="'+priority_click_down+'" class="icon_order fas fa-caret-down"></i>';
            html += '                 </div>\n' +
                '                </div>\n' +
                '            </div>\n' +
                '        </div>';
            if((index==(array_presentation.length-1))) {
                if(window.create_content=='1') {
                    html += '<div onclick="open_modal_p_action('+room_id+');" style="cursor: pointer" class="card ml-4 mt-1 py-1 bg-info text-white">\n' +
                        '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                        '                <div class="row">\n' +
                        '                    <div class="col-md-12 text-center">\n' +
                        '                        <i class="fas fa-plus-circle"></i> <span>'+window.backend_labels.add_action+'</span>\n' +
                        '                    </div>\n' +
                        '                </div>\n' +
                        '            </div>\n' +
                        '        </div>';
                }
            }
        });

        if(window.create_content=='1') {
            html += '<div id="btn_add_presentation_room" onclick="open_modal_p_room(null)" style="cursor: pointer" class="card mt-4 py-2 bg-warning text-white">\n' +
                '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                '                <div class="row">\n' +
                '                    <div class="col-md-12 text-center">\n' +
                '                        <i class="fas fa-plus-circle"></i> <span>' + window.backend_labels.add_room + '</span>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '            </div>\n' +
                '        </div>';
        }

        $('#presentation_list').html(html).promise().done(function () {
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) {
                $('#content-wrapper')[0].scrollTo(0, parseInt(scrollpos));
                localStorage.removeItem('scrollpos');
            }
            $('.p_room:first .fa-caret-up').addClass('disabled');
            $('.p_room:last .fa-caret-down').addClass('disabled');
            jQuery.each(window.array_id_rooms, function(index, id_room) {
                $('.p_sub_'+id_room+':first .fa-caret-up').addClass('disabled');
                $('.p_sub_'+id_room+':last .fa-caret-down').addClass('disabled');
            });
        });
    }

    window.change_presentation_priority = function (priority,direction,id) {
        $.ajax({
            url: "ajax/change_presentation_priority.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id: id,
                priority: priority,
                direction: direction
            },
            async: true,
            success: function (rsp) {
                localStorage.setItem('scrollpos', parseInt(window.scrollY));
                location.reload();
            }
        });
    }

    window.change_p_action = function() {
        var p_action = $('#p_action option:selected').attr('id');
        switch (p_action) {
            case '0':
                $('#div_type').hide();
                $('#div_lookAt').hide();
                $('#btn_add_p_action').addClass('disabled');
                break;
            case 'type':
                $('#div_type').show();
                $('#div_lookAt').hide();
                $('#btn_add_p_action').removeClass('disabled');
                break;
            case 'lookAt':
                $('#div_type').hide();
                $('#div_lookAt').show();
                $('#btn_add_p_action').removeClass('disabled');
                init_p_viewer(null,null,null);
                break;
        }
    }

    function init_p_viewer(yaw,pitch,hfov) {
        $.ajax({
            url: "ajax/get_room.php",
            type: "POST",
            data: {
                id: window.id_p_room,
            },
            async: true,
            success: function (rsp) {
                var room = JSON.parse(rsp);
                if(yaw==null) yaw = room.yaw;
                if(pitch==null) pitch = room.pitch;
                if(hfov==null) hfov = window.p_hfov;
                if(parseInt(room.allow_pitch)==1) {
                    var minPitch = parseInt(room.min_pitch);
                    var maxPitch = parseInt(room.max_pitch);
                } else {
                    var minPitch = 0;
                    var maxPitch = 0;
                    pitch = 0;
                }
                if(window.s3_enabled==1) {
                    var image_url = window.s3_url+'viewer/panoramas/'+room.panorama_image+'?s3=1';
                } else {
                    var image_url = '../viewer/panoramas/'+room.panorama_image;
                }
                p_viewer = pannellum.viewer('p_lookAt', {
                    "type": "equirectangular",
                    "panorama": image_url,
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "horizonPitch": parseInt(room.h_pitch),
                    "horizonRoll": parseInt(room.h_roll),
                    "hfov": parseInt(hfov),
                    "minHfov": parseInt(window.p_min_hfov),
                    "maxHfov": parseInt(window.p_max_hfov),
                    "yaw": parseFloat(yaw),
                    "pitch": parseFloat(pitch),
                    "minPitch": minPitch,
                    "maxPitch" : maxPitch,
                    "minYaw": parseInt(room.min_yaw),
                    "maxYaw" : parseInt(room.max_yaw),
                    "haov": parseInt(room.haov),
                    "vaov": parseInt(room.vaov),
                    "compass": false,
                    "friction": 1,
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
                p_viewer.on('load', function () {
                    p_viewer_initialized = true;
                    adjust_ratio_hfov('p_lookAt',p_viewer,hfov,window.p_min_hfov,window.p_max_hfov);
                });
                p_viewer.on('animatefinished',function () {
                    var yaw = parseFloat(p_viewer.getYaw());
                    var pitch = parseFloat(p_viewer.getPitch());
                    var hfov = parseInt(p_viewer.getHfov());
                    $('#div_lookAt p').html(yaw.toFixed(2)+','+pitch.toFixed(2)+' ('+hfov+')');
                    window.p_params = pitch+','+yaw+','+hfov;
                });
            }
        });
    }

    window.open_modal_p_room = function (index) {
        if(index==null) {
            $('#p_sleep_r').val(0);
            jQuery.each(window.array_id_rooms, function(index2, id_room) {
                $("#p_room option[id='"+id_room+"']").prop("disabled", true);
            });
            $("#p_room").val($("#p_room :not([disabled]):first").val());
            $("#p_room").prop('disabled',false);
            $('#p_room').selectpicker('refresh');
            change_preview_room_image_presentation(null);
            $('#btn_add_p_room').html('<i class="fas fa-plus"></i> '+window.backend_labels.add);
            $('#btn_add_p_room').attr('onclick','add_presentation_room();');
            $('#p_wait_video_end').prop('checked',false);
            var panorama_type = $("#p_room :not([disabled]):first").attr('data-type');
            if(panorama_type=='video') {
                $('#p_wait_video_end').parent().parent().show();
            } else {
                $('#p_wait_video_end').parent().parent().hide();
            }
            $('#btn_delete_p_room').hide();
        } else {
            jQuery.each(window.array_id_rooms, function(index2, id_room) {
                if(array_presentation[index].id_room!=id_room) {
                    $("#p_room option[id='"+id_room+"']").prop("disabled", true);
                }
            });
            $('#p_sleep_r').val(array_presentation[index].sleep);
            $("#p_room").prop('disabled',false);
            $('#p_room').selectpicker('refresh');
            change_preview_room_image_presentation(null);
            $('#btn_remove_p_room').attr('onclick','delete_p_room('+array_presentation[index].id_room+')');
            if(parseInt(array_presentation[index].video_wait_end)==1) {
                $('#p_wait_video_end').prop('checked',true);
            } else {
                $('#p_wait_video_end').prop('checked',false);
            }
            var panorama_type = array_presentation[index].panorama_type;
            if(panorama_type=='video') {
                $('#p_wait_video_end').parent().parent().show();
            } else {
                $('#p_wait_video_end').parent().parent().hide();
            }
            $('#btn_delete_p_room').show();
        }
        $('#modal_presentation_room').modal('show');
    }

    window.open_modal_p_action = function (id_room) {
        window.id_p_room = id_room;
        try {
            p_viewer.destroy();
        } catch (e) {}
        $('#btn_add_p_action').html('<i class="fas fa-plus"></i> '+window.backend_labels.add);
        $('#btn_add_p_action').attr('onclick','add_presentation_action();');
        $("#p_action").prop('disabled',false);
        $('#btn_add_p_action').addClass('disabled');
        $('#div_type').hide();
        $('#div_lookAt').hide();
        $("#p_action option").prop("selected", false);
        $("#p_action").val($("#p_action option:first").val());
        $('#p_animation').val(1000);
        $('#p_sleep_l').val(0);
        $('#p_sleep_t').val(0);
        $('#p_text').val('');
        $('#btn_delete_p_action').hide();
        if($('.lang_input_switcher').length) {
            $('.lang_input_switcher').each(function() {
                var elem_o = $(this).attr('data-elem');
                var lang_o = $(this).attr('data-default-lang');
                switch_input_language(lang_o,lang_o,elem_o);
            });
        }
        $('.input_lang[data-target-id="p_text"]').val('');
        $('#modal_presentation_action').modal('show');
    }

    window.presentation_elem_edit = function (index) {
        window.index_p = index;
        window.id_p_room = array_presentation[index].id_room;
        if(array_presentation[index].action=='goto') {
            $("#p_room option").prop("selected", false);
            $("#p_room option[id='"+window.id_p_room+"']").prop("selected", true);
            $("#p_room").prop('disabled',true);
            $('#btn_add_p_room').html('<i class="fas fa-save"></i> '+window.backend_labels.save);
            $('#btn_add_p_room').attr('onclick','edit_presentation_room('+array_presentation[index].id+');');
            if(array_presentation[index].pos=='') {
                $('#override_pos_presentation').prop('checked',false);
            } else {
                $('#override_pos_presentation').prop('checked',true);
            }
            open_modal_p_room(index);
        } else {
            try {
                p_viewer.destroy();
            } catch (e) {}
            $('#btn_add_p_action').html('<i class="fas fa-save"></i> '+window.backend_labels.save);
            $('#btn_add_p_action').attr('onclick','edit_presentation_action('+array_presentation[index].id+');');
            $('#btn_add_p_action').removeClass('disabled');
            $("#p_action").prop('disabled',true);
            $("#p_action option").prop("selected", false);
            switch (array_presentation[index].action) {
                case "type":
                    if($('.lang_input_switcher').length) {
                        $('.lang_input_switcher').each(function() {
                            var elem_o = $(this).attr('data-elem');
                            var lang_o = $(this).attr('data-default-lang');
                            switch_input_language(lang_o,lang_o,elem_o);
                        });
                    }
                    $('.input_lang[data-target-id="p_text"]').val('');
                    $('#div_type').show();
                    $('#div_lookAt').hide();
                    $("#p_action option[id='type']").prop("selected", true);
                    $('#p_sleep_t').val(array_presentation[index].sleep);
                    $('#p_text').val(array_presentation[index].text);
                    jQuery.each(window.array_presentation[index].array_lang, function(index_l,item_lang) {
                        $('.input_lang[data-target-id="p_text"][data-lang="'+item_lang.language+'"]').val(item_lang.params);
                    });
                    break;
                case 'lookAt':
                    $('#div_type').hide();
                    $('#div_lookAt').show();
                    $("#p_action option[id='lookAt']").prop("selected", true);
                    $('#p_animation').val(array_presentation[index].animation);
                    $('#p_sleep_l').val(array_presentation[index].sleep);
                    init_p_viewer(array_presentation[index].yaw,array_presentation[index].pitch,array_presentation[index].hfov);
                    break;
            }
            $('#btn_remove_p_action').attr('onclick','delete_p_action('+array_presentation[index].id+')');
            $('#btn_delete_p_action').show();
            $('#modal_presentation_action').modal('show');
        }
    }

    window.add_presentation_action = function () {
        $('#modal_presentation_action button').addClass("disabled");
        var action = $('#p_action option:selected').attr('id');
        var array_lang = {};
        switch (action) {
            case "type":
                var sleep = $('#p_sleep_t').val();
                var params = $('#p_text').val();
                array_lang['params'] = {};
                $('.input_lang[data-target-id="p_text"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    array_lang['params'][lang]=value;
                });
                break;
            case 'lookAt':
                var sleep = $('#p_sleep_l').val();
                var animation = $('#p_animation').val();
                if(animation=='') animation=0;
                var params = window.p_params+','+animation;
                break;
        }
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/add_presentation_action.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: window.id_p_room,
                sleep: sleep,
                action: action,
                params: params,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_presentation_action button').removeClass("disabled");
                if(rsp.status=='ok') {
                    $('#modal_presentation_action').modal("hide");
                    localStorage.setItem('scrollpos', parseInt(window.scrollY));
                    location.reload();
                }
            }
        });
    }

    window.edit_presentation_action = function (id) {
        $('#modal_presentation_action button').addClass("disabled");
        var action = $('#p_action option:selected').attr('id');
        var array_lang = {};
        switch (action) {
            case "type":
                var sleep = $('#p_sleep_t').val();
                var params = $('#p_text').val();
                array_lang['params'] = {};
                $('.input_lang[data-target-id="p_text"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    array_lang['params'][lang]=value;
                });
                break;
            case 'lookAt':
                var sleep = $('#p_sleep_l').val();
                var animation = $('#p_animation').val();
                if(animation=='') animation=0;
                var params = window.p_params+','+animation;
                break;
        }
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_presentation_action.php",
            type: "POST",
            data: {
                id: id,
                sleep: sleep,
                params: params,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_presentation_action button').removeClass("disabled");
                if(rsp.status=='ok') {
                    $('#modal_presentation_action').modal("hide");
                    localStorage.setItem('scrollpos', parseInt(window.scrollY));
                    location.reload();
                }
            }
        });
    }

    window.save_presentation = function () {
        var auto_presentation_speed = $('#auto_presentation_speed').val();
        var presentation_type = $('#presentation_type option:selected').attr('id');
        var presentation_video = $('#presentation_video').val();
        var presentation_inactivity = $('#presentation_inactivity').val();
        var presentation_loop = ($('#presentation_loop').is(':checked')) ? 1 : 0;
        var presentation_stop_click = ($('#presentation_stop_click').is(':checked')) ? 1 : 0;
        var presentation_stop_id_room = $('#presentation_stop_id_room option:selected').attr('id');
        var presentation_view_pois = ($('#presentation_view_pois').is(':checked')) ? 1 : 0;
        var presentation_view_measures = ($('#presentation_view_measures').is(':checked')) ? 1 : 0;
        $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
        $('#save_btn').addClass("disabled");
        $.ajax({
            url: "ajax/save_presentation.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                auto_presentation_speed: auto_presentation_speed,
                presentation_type: presentation_type,
                presentation_video: presentation_video,
                presentation_inactivity: presentation_inactivity,
                presentation_loop: presentation_loop,
                presentation_stop_click: presentation_stop_click,
                presentation_stop_id_room: presentation_stop_id_room,
                presentation_view_pois: presentation_view_pois,
                presentation_view_measures: presentation_view_measures
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    window.presentation_need_save = false;
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                } else {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            },
            error: function() {
                $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                setTimeout(function () {
                    $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                    $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    $('#save_btn').removeClass("disabled");
                },1000);
            }
        });
    }

    window.add_presentation_room = function () {
        $('#modal_presentation_room button').addClass("disabled");
        var id_room = $('#p_room option:selected').attr('id');
        var sleep = $('#p_sleep_r').val();
        var video_wait_end = ($('#p_wait_video_end').is(':checked')) ? 1 : 0;
        var override_pos_presentation = ($('#override_pos_presentation').is(':checked')) ? 1 : 0;
        var yaw = parseFloat(window.viewer_pos.getYaw());
        var pitch = parseFloat(window.viewer_pos.getPitch());
        var hfov = parseInt(window.viewer_pos.getHfov());
        $.ajax({
            url: "ajax/add_presentation_room.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: id_room,
                sleep: sleep,
                video_wait_end: video_wait_end,
                override_pos_presentation: override_pos_presentation,
                yaw: yaw,
                pitch: pitch,
                hfov: hfov
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_presentation_room button').removeClass("disabled");
                if(rsp.status=='ok') {
                    $('#modal_presentation_room').modal("hide");
                    localStorage.setItem('scrollpos', parseInt(window.scrollY));
                    location.reload();
                }
            }
        });
    }

    window.edit_presentation_room = function (id) {
        $('#modal_presentation_room button').addClass("disabled");
        var sleep = $('#p_sleep_r').val();
        var video_wait_end = ($('#p_wait_video_end').is(':checked')) ? 1 : 0;
        var override_pos_presentation = ($('#override_pos_presentation').is(':checked')) ? 1 : 0;
        var yaw = parseFloat(window.viewer_pos.getYaw());
        var pitch = parseFloat(window.viewer_pos.getPitch());
        var hfov = parseInt(window.viewer_pos.getHfov());
        $.ajax({
            url: "ajax/save_presentation_room.php",
            type: "POST",
            data: {
                id: id,
                sleep: sleep,
                video_wait_end: video_wait_end,
                override_pos_presentation: override_pos_presentation,
                yaw: yaw,
                pitch: pitch,
                hfov: hfov
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_presentation_room button').removeClass("disabled");
                if(rsp.status=='ok') {
                    $('#modal_presentation_room').modal("hide");
                    localStorage.setItem('scrollpos', parseInt(window.scrollY));
                    location.reload();
                }
            }
        });
    }

    window.delete_p_action = function (id) {
        $('#modal_delete_p_action button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_presentation_action.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_delete_p_action button').removeClass("disabled");
                if(rsp.status=='ok') {
                    $('#modal_delete_p_action').modal("hide");
                    $('#modal_presentation_action').modal("hide");
                    localStorage.setItem('scrollpos', parseInt(window.scrollY));
                    location.reload();
                }
            }
        });
    }

    window.delete_p_room = function (id_room) {
        $('#modal_delete_p_room button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_presentation_room.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_delete_p_room button').removeClass("disabled");
                if(rsp.status=='ok') {
                    $('#modal_delete_p_room').modal("hide");
                    $('#modal_presentation_room').modal("hide");
                    localStorage.setItem('scrollpos', parseInt(window.scrollY));
                    location.reload();
                }
            }
        });
    }

    window.filter_vt = function () {
        var id_category = $('#filter_category option:selected').attr('id');
        var id_user = $('#filter_user option:selected').attr('id');
        if(id_category==0 && id_user==0) {
            location.href = 'index.php?p=virtual_tours';
        } else if(id_category!=0 && id_user==0) {
            location.href = 'index.php?p=virtual_tours&cat='+id_category;
        } else if(id_category==0 && id_user!=0) {
            location.href = 'index.php?p=virtual_tours&user='+id_user;
        } else {
            location.href = 'index.php?p=virtual_tours&cat='+id_category+'&user='+id_user;
        }
    }

    function parse_virtual_tour_list(virtual_tours,categories,id_category_sel,users,id_user_sel,aws_s3_enabled) {
        var html = '';
        var search_val = sessionStorage.getItem('search_vt');
        if(search_val==null) search_val='';
        if(location.href.includes('edit_user')) {
            search_val='';
        }
        var option_categories = '';
        jQuery.each(categories, function(index, category) {
            var res = category.split("|");
            var id_category = res[0];
            var name_category = res[1];
            if(id_category_sel==id_category) {
                option_categories += "<option selected id='"+id_category+"'>"+name_category+"</option>";
            } else {
                option_categories += "<option id='"+id_category+"'>"+name_category+"</option>";
            }
        });
        var option_users = '';
        jQuery.each(users, function(index, user) {
            var res = user.split("|");
            var id_user_f = res[0];
            var name_user = res[1];
            if(id_user_sel==id_user_f) {
                option_users += "<option selected id='"+id_user_f+"'>"+name_user+"</option>";
            } else {
                option_users += "<option id='"+id_user_f+"'>"+name_user+"</option>";
            }
        });
        if(window.user_role=='administrator') {
            var display_user_f = '';
            var col_sm_f = 4;
            var col_md_f = 2;
        } else {
            var display_user_f = 'd-none';
            var col_sm_f = 6;
            var col_md_f = 3;
        }
        if(virtual_tours.length>0) {
            html += '<div class="search_vt_div card mb-2 pt-3">\n' +
                '    <div class="card-body" style="padding-top: 0;padding-bottom: 0;">' +
                '<div class="row">' +
                '<div class="col-lg-6 col-md-6 col-sm-12 col-12">' +
                '   <div class="input-group mb-3">' +
                '       <span class="input-group-prepend">' +
                '           <div class="input-group-text bg-white border-right-0"><i class="fa fa-search"></i></div>' +
                '       </span>' +
                '       <input onkeyup="persist_search(\'vt\')" class="search_input form-control py-2" type="text" value="'+search_val+'" placeholder="'+window.backend_labels.search_vt+'" autocomplete="new-password" >' +
                '       <span class="input-group-append">' +
                '           <div onclick="clear_search(\'vt\');" style="cursor: pointer;" class="input-group-text bg-gray-300 border-left-0"><i class="fa fa-times"></i></div>' +
                '       </span>' +
                '   </div>' +
                '</div>' +
                '<div class="col-lg-'+col_md_f+' col-md-'+col_md_f+' col-sm-'+col_sm_f+' col-'+col_sm_f+' mb-3">' +
                '   <select onchange="filter_vt();" id="filter_category" data-live-search="true" class="form-control">' +
                '       <option id="0">'+window.backend_labels.all_categories+'</option>' +
                option_categories +
                '   </select>' +
                '</div>' +
                '<div class="col-lg-'+col_md_f+' col-md-'+col_md_f+' col-sm-'+col_sm_f+' col-'+col_sm_f+' mb-3 '+display_user_f+'">' +
                '   <select onchange="filter_vt();" id="filter_user" data-live-search="true" class="form-control">' +
                '       <option id="0">'+window.backend_labels.all_users+'</option>' +
                option_users +
                '   </select>' +
                '</div>' +
                '   <div class="col-lg-'+col_md_f+' col-md-'+col_md_f+' col-sm-'+col_sm_f+' col-'+col_sm_f+' mb-3">\n' +
                '       <input id="view_type_toggle" type="checkbox" checked data-toggle="toggle" data-width="100%" data-on="'+window.backend_labels.list+'" data-off="'+window.backend_labels.grid+'" data-onstyle="light" data-offstyle="light">\n' +
                '   </div>\n' +
                '</div>' +
                '</div>' +
                '</div>';
        } else {
            html += '<div class="card mb-2">\n' +
                '<div class="card-body">' +
                '<div class="row">' +
                '<div class="col-12">' +
                ((window.enable_wizard) ? window.backend_labels.no_tour_msg_wizard : window.backend_labels.no_tour_msg) +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';
        }
        jQuery.each(virtual_tours, function(index, virtual_tour) {
            var id = virtual_tour.id;
            var external = parseInt(virtual_tour.external);
            var block_tour = parseInt(virtual_tour.block_tour);
            var name = virtual_tour.name;
            var author = virtual_tour.author;
            var id_user = virtual_tour.id_user;
            var category = virtual_tour.category_name;
            var date_created = virtual_tour.date_created;
            var last_access = virtual_tour.last_access;
            var count_versions = parseInt(virtual_tour.count_versions);
            var count_rooms = parseInt(virtual_tour.count_rooms);
            var count_maps = parseInt(virtual_tour.count_maps);
            var count_gallery = parseInt(virtual_tour.count_gallery);
            var info_box_check = parseInt(virtual_tour.info_box_check);
            var slideshow_check = parseInt(virtual_tour.slideshow_check);
            var edit_permission = virtual_tour.edit_permission;
            var edit_ui_permission = virtual_tour.edit_ui_permission;
            var edit_3d_view = virtual_tour.edit_3d_view_permission;
            var background_image = virtual_tour.background_image;
            var panoramas_list = virtual_tour.panoramas_list;
            var dollhouse = parseInt(virtual_tour.dollhouse);
            var count_video360 = parseInt(virtual_tour.count_video360);
            var count_video_projects = parseInt(virtual_tour.count_video_projects);
            var aws_s3 = parseInt(virtual_tour.aws_s3);
            var languages = virtual_tour.languages;
            var default_language = virtual_tour.default_language;
            var languages_list = languages.join(' ');
            if(aws_s3==1) {
                var aws_s3_url = virtual_tour.aws_s3_url;
            }
            var note = virtual_tour.note;
            var array_panorams_vt = [];
            if(panoramas_list!='') {
                array_panorams_vt = panoramas_list.split(",");
            }
            if(window.user_role=='administrator') {
                author = "<span class='author_vt_list'>&nbsp;&nbsp;<a style='text-decoration:none;vertical-align:baseline' href='index.php?p=edit_user&id="+id_user+"'><i class=\"fas fa-user\"></i> "+author+"</a></span>";
            } else {
                author = "<span class='author_vt_list'>&nbsp;&nbsp;<i class=\"fas fa-user\"></i> "+author+"</span>";
            }
            var languages_html = "<img class='lang_vt_list' src='img/flags_lang/"+default_language+".png?v=2' /> ";
            var count_l = languages.length;
            if(count_l>4) languages = languages.slice(0, 4);
            $.each(languages,function(index_l, lang) {
                languages_html += "<img class='lang_vt_list' src='img/flags_lang/"+lang+".png?v=2' /> ";
            });
            if(languages_html!='') {
                languages_html = "&nbsp;&nbsp;"+languages_html;
                var other_l_count = count_l-4;
                if(other_l_count>0) languages_html += " <span style='font-size:10px;'>+"+other_l_count+"</span>";
            }
            if(external==1) {
                var disabled = 'disabled';
            } else {
                var disabled = '';
            }
            if(dollhouse==1) {
                var badge_dollhouse = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">1</span>';
            } else {
                var badge_dollhouse = '';
            }
            if(count_rooms>0) {
                var badge_room = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_rooms+'</span>';
            } else {
                var badge_room = '';
            }
            if(count_maps>0) {
                var badge_map = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_maps+'</span>';
            } else {
                var badge_map = '';
            }
            if(count_gallery>0) {
                var badge_gallery = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_gallery+'</span>';
            } else {
                var badge_gallery = '';
            }
            if(info_box_check==1) {
                var badge_info = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">1</span>';
            } else {
                var badge_info = '';
            }
            if(slideshow_check==1) {
                var badge_slideshow = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">1</span>';
            } else {
                var badge_slideshow = '';
            }
            if(count_video360>0) {
                var badge_video360 = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_video360+'</span>';
            } else {
                var badge_video360 = '';
            }
            if(count_video_projects>0) {
                var badge_video_projects = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_video_projects+'</span>';
            } else {
                var badge_video_projects = '';
            }
            if(count_versions>0) {
                var badge_versions = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_versions+'</span>';
            } else {
                var badge_versions = '';
            }
            var html_exp = '',html_status = '',html_storage='';
            /*var start_date = virtual_tour.start_date;
            var end_date = virtual_tour.end_date;
            if((start_date!='') || (end_date!='')) {
                html_exp = ' <span style="font-size:12px">('+start_date+' - '+end_date+')</span>';
            }*/
            if(external==0) {
                if(parseInt(aws_s3_enabled)==1 && window.user_role=='administrator') {
                    if(aws_s3==1) {
                        html_storage = '<span onclick="modal_move_to_local('+id+');return false;" class="badge badge-dark button_storage_vt"><i class="fas fa-cloud"></i></span>&nbsp;&nbsp;';
                    } else {
                        html_storage = '<span onclick="modal_move_to_s3('+id+');return false;" class="badge badge-light button_storage_vt"><i class="far fa-folder"></i></span>&nbsp;&nbsp;';
                    }
                }
            }
            if(parseInt(virtual_tour.status)==1) {
                html_status = '<i title="'+window.backend_labels.status_created+'" style="color: green" class="fas fa-circle i_tooltip"></i>';
            } else {
                html_status = '<i title="'+window.backend_labels.status_created+'" style="color: red" class="fas fa-circle i_tooltip"></i>';
            }
            if(parseInt(virtual_tour.external)==0) {
                if(parseInt(virtual_tour.status_gsv)>-1) {
                    switch(parseInt(virtual_tour.status_gsv)) {
                        case 1:
                            author += '&nbsp;&nbsp;<i title="'+window.backend_labels.gsv_ready+'" style="color: darkorange" class="fas fa-street-view i_tooltip"></i>';
                            break;
                        case 2:
                            if(virtual_tour.link_gsv!='') {
                                author += '&nbsp;&nbsp;<a target="_blank" href="'+virtual_tour.link_gsv+'"><i title="'+window.backend_labels.gsv_published_link+'" style="color: green" class="fas fa-street-view i_tooltip"></i></a>';
                            } else {
                                author += '&nbsp;&nbsp;<i title="'+window.backend_labels.gsv_published+'" style="color: green" class="fas fa-street-view i_tooltip"></i>';
                            }
                            break;
                    }
                }
            }
            var btn_duplicate = '';
            if(parseInt(window.can_create)==1) {
                btn_duplicate = '<a title="'+window.backend_labels.duplicate.toUpperCase()+'" href="#" onclick="modal_duplicate_virtualtour('+id+');return false;" class="btn btn-secondary btn-sm btn_duplicate '+disabled+'">\n' +
                    '<i class="fas fa-copy"></i>\n' +
                    '</a>\n';
            }
            var btn_export = '';
            if(parseInt(window.enable_export_vt)==1 || parseInt(window.enable_import_export)==1) {
                btn_export = '<a title="'+window.backend_labels.export_vt.toUpperCase()+'" href="#" onclick="modal_export_virtualtour('+id+');return false;" class="btn btn-secondary btn-sm btn_export '+disabled+'">\n' +
                    '<i class="fas fa-download"></i>\n' +
                    '</a>\n';
            }
            var btn_edit = '';
            var btn_edit_ui = '';
            var btn_edit_3d_view = '';
            var btn_rename = '';
            var input_rename = '';
            if(edit_permission) {
                btn_edit = '<a title="'+window.backend_labels.edit.toUpperCase()+'" href="index.php?p=edit_virtual_tour&id='+id+'" class="btn btn-warning btn-sm">\n' +
                    '<i class="fas fa-edit"></i>\n' +
                    '</a>\n';
                btn_rename = '<i id="btn_view_rename_'+id+'" onclick="view_rename_vt('+id+');" class="btn_view_rename fas fa-pen"></i>';
                btn_rename += '<i id="btn_save_rename_'+id+'" onclick="save_rename_vt('+id+');" class="btn_save_rename fas fa-check d-none"></i>&nbsp;&nbsp;';
                btn_rename += '<i id="btn_close_rename_'+id+'" onclick="close_rename_vt('+id+');" class="btn_close_rename fas fa-times d-none"></i>';
                input_rename = '<input id="rename_input_'+id+'" class="rename_input d-none" type="text" value="'+name+'" />';
            }
            if(edit_ui_permission) {
                btn_edit_ui = '<a title="'+window.backend_labels.editor_ui.toUpperCase()+'" href="index.php?p=edit_virtual_tour_ui&id_vt='+id+'" class="btn btn-warning btn-sm position-relative '+disabled+'">\n' +
                    '<i class="fas fa-swatchbook"></i>\n' + badge_versions +
                    '</a>\n';
            }
            if(edit_3d_view) {
                btn_edit_3d_view = '<a title="'+window.backend_labels.dollhouse.toUpperCase()+'" href="index.php?p=dollhouse&id_vt='+id+'" class="btn btn-warning btn-sm position-relative '+disabled+'">\n' +
                    '<i class="fas fa-cube"></i>\n' + badge_dollhouse +
                    '</a>\n';
            }
            var cat_html = '';
            if(category!='') {
                cat_html = '&nbsp;&nbsp;<i class="fas fa-th-list"></i> '+category;
            }
            var img2 = '', img3 = '';
            var o_position = 'center center';
            if(background_image=='') {
                if (array_panorams_vt.hasOwnProperty(0)) {
                    if(aws_s3==1) {
                        var img1_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_vt[0];
                    } else {
                        var img1_src = '../viewer/panoramas/thumb/'+array_panorams_vt[0];
                    }
                } else {
                    var img1_src = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
                }
                if (array_panorams_vt.hasOwnProperty(1)) {
                    if(aws_s3==1) {
                        var img2_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_vt[1];
                    } else {
                        var img2_src = '../viewer/panoramas/thumb/'+array_panorams_vt[1];
                    }
                    img2 = '<img class="img2_vt" loading="lazy" src="'+img2_src+'">';
                }
                if (array_panorams_vt.hasOwnProperty(2)) {
                    if(aws_s3==1) {
                        var img3_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_vt[2];
                    } else {
                        var img3_src = '../viewer/panoramas/thumb/'+array_panorams_vt[2];
                    }
                    img3 = '<img class="img3_vt" loading="lazy" src="'+img3_src+'">';
                    o_position = '-15px center';
                }
            } else {
                if(aws_s3==1) {
                    var img1_src = aws_s3_url+'viewer/content/thumb/'+background_image;
                } else {
                    var img1_src = '../viewer/content/thumb/'+background_image;
                }
                if (array_panorams_vt.hasOwnProperty(0)) {
                    if(aws_s3==1) {
                        var img2_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_vt[0];
                    } else {
                        var img2_src = '../viewer/panoramas/thumb/'+array_panorams_vt[0];
                    }
                    img2 = '<img class="img2_vt" loading="lazy" src="'+img2_src+'">';
                }
                if (array_panorams_vt.hasOwnProperty(1)) {
                    if(aws_s3==1) {
                        var img3_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_vt[1];
                    } else {
                        var img3_src = '../viewer/panoramas/thumb/'+array_panorams_vt[1];
                    }
                    img3 = '<img class="img3_vt" loading="lazy" src="'+img3_src+'">';
                    o_position = '-15px center';
                }
            }
            var note_tooltip = '';
            if(window.user_role=='administrator' && note!='') {
                note_tooltip = '&nbsp;&nbsp;<i title="'+note+'" class="far fa-sticky-note vt_note"></i>';
            }
            var btn_lock = '';
            if(window.user_role=='administrator') {
                if(block_tour==1) {
                    btn_lock = '<div title="'+window.backend_labels.unlock+'" style="cursor:pointer;" onclick="modal_unlock_virtualtour('+id+');return false;" class="btn btn_lock btn-dark btn-sm position-relative">\n' +
                        '<i class="fas fa-lock"></i>\n' +
                        '</div>';
                } else {
                    btn_lock = '<div title="'+window.backend_labels.lock+'" style="cursor:pointer;" onclick="modal_lock_virtualtour('+id+');return false;" class="btn btn_lock btn-outline-dark btn-sm position-relative">\n' +
                        '<i class="fas fa-unlock"></i>\n' +
                        '</div>';
                }
            }
            if(last_access.date!='' && last_access.date!=undefined && last_access.date!=null) {
                var style_last_access = "";
                if(parseInt(last_access.old)==1) {
                    style_last_access = 'style="color:darkorange;"';
                }
                var html_last_access = '<span class="last_access_div">&nbsp;&nbsp;<i title="'+window.backend_labels.last_visit_at+'" '+style_last_access+' class="fas fa-clock i_tooltip"></i> '+last_access.date+'</span>';
            } else {
                var html_last_access = '<span class="last_access_div">&nbsp;&nbsp;<i title="'+window.backend_labels.last_visit_at+'" class="fas fa-clock i_tooltip"></i> --</span>';
            }
            if(window.user_role=='customer' && block_tour==1) {
                html += '<div class="div_vt card mb-2 py-2">\n' +
                    '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                    '                <div class="row vt">\n' +
                    '                    <div class="vt_content col text-center text-sm-center text-md-left text-lg-left">\n' +
                    '                        <div style="width: 90px;height: 44px;overflow: hidden;border-radius: 6px;position: relative;" class="d-inline-block align-middle"><img loading="lazy" style="width:100%;height:100%;object-fit:cover;object-position:'+o_position+'" src="'+img1_src+'">'+img2+img3+'</div>' +
                    '                        <div class="vt_info d-inline-block align-middle ml-2 text-left"><b class="vt_name" id="vt_name_'+id+'">'+((name.length > 60) ? name.slice(0, 60) + "..." : name)+'</b><br><span style="font-size:12px;line-height:12px;">'+html_status+' '+date_created+html_last_access+' '+cat_html+author+note_tooltip+'</span>' + html_exp + languages_html + '</div>\n' +
                    '                    </div>\n' +
                    '                    <div class="vt_buttons col-md-auto pt-1 text-center text-sm-center text-md-right text-lg-right">\n' +
                    '                        <div title="'+window.backend_labels.lock_msg+'" class="btn btn-dark btn-sm position-relative">\n' +
                    '                            <i class="fas fa-lock"></i>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '           </div>\n' +
                    '       </div>\n';
            } else {
                html += '<div class="div_vt card mb-2 py-2">\n' +
                    '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                    '                <div class="row vt">\n' +
                    '                    <div class="vt_content col text-center text-sm-center text-md-left text-lg-left">\n' +
                    '                        <div class="vt_content_div d-flex align-items-start justify-content-center justify-content-md-start">' +
                    '                              <div style="width: 90px;height: 44px;overflow: hidden;border-radius: 6px;position: relative;margin-top: 2px;" class="align-middle"><img loading="lazy" style="width:100%;height:100%;object-fit:cover;object-position:'+o_position+'" src="'+img1_src+'">'+img2+img3+'</div>' +
                    '                              <div class="vt_info align-middle ml-2 text-left"><b class="vt_name" id="vt_name_'+id+'">'+((name.length > 60) ? name.slice(0, 60) + "..." : name)+'</b>'+input_rename+'&nbsp;&nbsp;'+btn_rename+'<br><span style="font-size:12px;line-height:12px;">'+html_storage+html_status+' '+date_created+html_last_access+' '+cat_html+author+note_tooltip+'</span>' + html_exp + languages_html + '</div>\n' +
                    '                         </div>\n' +
                    '                    </div>\n' +
                    '                    <div class="vt_buttons col-md-auto pt-1 text-center text-sm-center text-md-right text-lg-right">\n' + btn_edit + btn_edit_ui + btn_edit_3d_view +
                    '                        <a title="'+window.backend_labels.rooms.toUpperCase()+'" href="index.php?p=rooms&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-vector-square"></i>\n' + badge_room +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.maps.toUpperCase()+'" href="index.php?p=maps&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-map-marked-alt"></i>\n' + badge_map +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.gallery.toUpperCase()+'" href="index.php?p=gallery&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-images"></i>\n' + badge_gallery +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.slideshow.toUpperCase()+'" href="index.php?p=gallery&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-file-video"></i>\n' + badge_slideshow +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.info_box.toUpperCase()+'" href="index.php?p=info&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-info-circle"></i>\n' + badge_info +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.video360.toUpperCase()+'" href="index.php?p=video360&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-video"></i>\n' + badge_video360 +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.video_projects.toUpperCase()+'" href="index.php?p=video&id_vt='+id+'" class="btn btn-info btn-sm position-relative '+disabled+'">\n' +
                    '                            <i class="fas fa-film"></i>\n' + badge_video_projects +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.preview.toUpperCase()+'" href="index.php?p=preview&id_vt='+id+'" class="btn btn-dark btn-sm">\n' +
                    '                            <i class="fas fa-eye"></i>\n' +
                    '                        </a>\n' +
                    '                        <a title="'+window.backend_labels.publish.toUpperCase()+'" href="index.php?p=publish&id_vt='+id+'" class="btn btn-dark btn-sm">\n' +
                    '                            <i class="fas fa-paper-plane"></i>\n' +
                    '                        </a>\n' + btn_export + btn_duplicate +
                    '                        <a title="'+window.backend_labels.delete.toUpperCase()+'" href="#" onclick="modal_delete_virtualtour('+id+','+virtual_tour.status_gsv+');return false;" class="btn btn-danger btn-sm btn_delete_vt">\n' +
                    '                            <i class="fas fa-trash"></i>\n' +
                    '                        </a>\n' + btn_lock +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>\n';
            }
        });
        $('#virtual_tours_list').html(html).promise().done(function () {
            $('.vt_note').tooltipster({delay:0});
            $('.i_tooltip').tooltipster({delay:0,position:"bottom"});
            $('#filter_category').selectpicker();
            $('#filter_user').selectpicker();
            $('.rename_input').keydown(function (e) {
                var keyCode = e.keyCode || e.which;
                if (keyCode == 13) {
                    var id = $(this).attr('id').replace('rename_input_','');
                    save_rename_vt(id);
                }
            });
            $('#view_type_toggle').bootstrapToggle();
            $('#view_type_toggle').change(function() {
                var checked = $(this).prop('checked');
                if(!checked) {
                    localStorage.setItem('vt_view_type', 'grid');
                    $('.div_vt').addClass('div_vt_grid');
                    $('#virtual_tours_list').css('margin','0 -5px');
                    $('.search_vt_div').css('margin','0 5px');
                    $('#virtual_tours_list .vt .vt_content_div').removeClass('d-flex align-items-start justify-content-center justify-content-md-start');
                    $('#virtual_tours_list .vt .vt_content_div>div').addClass('m-auto');
                    $('#virtual_tours_list .vt .vt_content').removeClass('text-lg-left').removeClass('text-md-left');
                    $('#virtual_tours_list .vt .vt_buttons').removeClass('text-lg-right').removeClass('text-md-right');
                    $('#virtual_tours_list .vt .vt_content').removeClass('col-md-6').addClass('col-12');
                    $('#virtual_tours_list .vt .vt_buttons').removeClass('col-md-6').addClass('col-12').addClass('mt-1');
                    $('#virtual_tours_list .vt .vt_buttons').addClass('col-auto').removeClass('col-md-auto');
                    $('#virtual_tours_list .vt .vt_content .vt_info').removeClass('text-left').addClass('text-center');
                    $('#virtual_tours_list .vt .vt_content .vt_info').css('width','100%');
                } else {
                    localStorage.setItem('vt_view_type', 'list');
                    $('.div_vt').removeClass('div_vt_grid');
                    $('#virtual_tours_list').css('margin','0');
                    $('.search_vt_div').css('margin','0');
                    $('#virtual_tours_list .vt .vt_content_div').addClass('d-flex align-items-start justify-content-center justify-content-md-start');
                    $('#virtual_tours_list .vt .vt_content_div>div').removeClass('m-auto');
                    $('#virtual_tours_list .vt .vt_content').addClass('text-lg-left').addClass('text-md-left');
                    $('#virtual_tours_list .vt .vt_buttons').addClass('text-lg-right').addClass('text-md-right');
                    $('#virtual_tours_list .vt .vt_content').removeClass('col-12').addClass('col-md-6');
                    $('#virtual_tours_list .vt .vt_buttons').removeClass('col-12').addClass('col-md-6').removeClass('mt-1');
                    $('#virtual_tours_list .vt .vt_buttons').removeClass('col-auto').addClass('col-md-auto');
                    $('#virtual_tours_list .vt .vt_content .vt_info').addClass('text-left').removeClass('text-center');
                    $('#virtual_tours_list .vt .vt_content .vt_info').css('width','auto');
                }
            });
            if ("vt_view_type" in localStorage) {
                var view_type = localStorage.getItem('vt_view_type');
                switch (view_type) {
                    case 'list':
                        $('#view_type_toggle').bootstrapToggle('on');
                        break;
                    case 'grid':
                        $('#view_type_toggle').bootstrapToggle('off');
                        break;
                }
            }
            if(window.user_role=='editor') {
                $('.fa-trash').parent().hide();
                $('.fa-copy').parent().hide();
                $('.fa-paper-plane').parent().hide();
            }
            $('#virtual_tours_list').searchable({
                selector      : '.div_vt',
                childSelector : 'div',
                searchField   : '.search_input',
                searchType    : 'default',
                clearOnLoad   : false
            });
            $('#virtual_tours_list .div_vt .btn').tooltipster({
                delay: 10,
                hideOnClick: true
            });
            if(window.wizard_step==-1) {
                if(window.location.href.includes('virtual_tours')) {
                    var scrollpos = sessionStorage.getItem('scrollpos_vt');
                    if (scrollpos) {
                        document.getElementById("content-wrapper").scrollTo(0,scrollpos);
                        sessionStorage.removeItem('scrollpos_vt');
                    }
                }
            }
        });
    }

    window.view_rename_vt = function(id) {
        $('#btn_view_rename_'+id).addClass('d-none');
        $('#btn_save_rename_'+id).removeClass('d-none');
        $('#btn_close_rename_'+id).removeClass('d-none');
        $('#rename_input_'+id).removeClass('d-none');
        $('#rename_input_'+id).select();
        $('#vt_name_'+id).addClass('d-none');
    }

    window.save_rename_vt = function(id) {
        var name = $('#rename_input_'+id).val();
        if(name!='') {
            name = DOMPurify.sanitize(name);
            $('#vt_name_'+id).html(name);
            $.ajax({
                url: "ajax/rename_vt.php",
                type: "POST",
                data: {
                    id: id,
                    name: name
                },
                async: true,
                success: function (json) {
                    $('#btn_view_rename_'+id).removeClass('d-none');
                    $('#btn_save_rename_'+id).addClass('d-none');
                    $('#btn_close_rename_'+id).addClass('d-none');
                    $('#rename_input_'+id).addClass('d-none');
                    $('#vt_name_'+id).removeClass('d-none');
                }
            });
        }
    }

    window.close_rename_vt = function(id) {
        $('#btn_view_rename_'+id).removeClass('d-none');
        $('#btn_save_rename_'+id).addClass('d-none');
        $('#btn_close_rename_'+id).addClass('d-none');
        $('#rename_input_'+id).addClass('d-none');
        $('#vt_name_'+id).removeClass('d-none');
    }

    function parse_map_list(maps,permissions) {
        var html = '', html_search='';
        var search_val = sessionStorage.getItem('search_map');
        if(search_val==null) search_val='';
        if(maps.length>0) {
            html_search = '<div class="card mb-2 pt-3">\n' +
                '    <div class="card-body" style="padding-top: 0;padding-bottom: 0;">';
            html_search += '<div class="row">\n' +
                '<div class="col-lg-10 col-md-8 col-sm-8 col-6">\n' +
                '    <div class="input-group mb-3">\n' +
                '       <span class="input-group-prepend">\n' +
                '           <div class="input-group-text bg-white border-right-0"><i class="fa fa-search"></i></div>\n' +
                '       </span>\n' +
                '       <input onkeyup="persist_search(\'map\')" class="search_input form-control py-2" type="text" value="'+search_val+'" placeholder="'+window.backend_labels.search_map+'" autocomplete="new-password" >\n' +
                '       <span class="input-group-append">\n' +
                '           <div onclick="clear_search(\'map\');" style="cursor: pointer;" class="input-group-text bg-gray-300 border-left-0"><i class="fa fa-times"></i></div>\n' +
                '       </span>\n' +
                '   </div>\n' +
                '</div>\n' +
                '   <div class="col-lg-2 col-md-4 col-sm-4 col-6">\n' +
                '       <input id="view_type_toggle" type="checkbox" checked data-toggle="toggle" data-width="100%" data-on="'+window.backend_labels.list+'" data-off="'+window.backend_labels.grid+'" data-onstyle="light" data-offstyle="light">\n' +
                '   </div>\n' +
                '</div>\n';
            html_search += '</div></div>';
        }
        jQuery.each(maps, function(index, map) {
            var id = map.id;
            var name = map.name;
            var image = map.map_image;
            var map_type = map.map_type;
            var count = map.count_rooms;
            var btn_rename = '<i id="btn_view_rename_'+id+'" onclick="view_rename_map('+id+');" class="btn_view_rename fas fa-pen"></i>';
            btn_rename += '<i id="btn_save_rename_'+id+'" onclick="save_rename_map('+id+');" class="btn_save_rename fas fa-check d-none"></i>&nbsp;&nbsp;';
            btn_rename += '<i id="btn_close_rename_'+id+'" onclick="close_rename_map('+id+');" class="btn_close_rename fas fa-times d-none"></i>';
            var input_rename = '<input id="rename_input_'+id+'" class="rename_input d-none" type="text" value="'+name+'" />';
            var btn_duplicate = '';
            if(parseInt(window.can_create)==1) {
                btn_duplicate = '<a title="'+window.backend_labels.duplicate.toUpperCase()+'" href="#" onclick="modal_duplicate_map('+id+');return false;" class="btn btn-secondary btn-sm btn_duplicate">\n' +
                    '<i class="fas fa-copy"></i>\n' +
                    '</a>\n';
            }
            switch (map_type) {
                case 'floorplan':
                    html += '<div class="div_map card mb-2 py-2">\n' +
                        '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                        '                <div data-id="'+id+'" class="row maph">\n' +
                        '                    <div class="map_content col-md-8 text-center text-sm-center text-md-left text-lg-left">\n' +
                        '                        <div style="width: 90px;height: 44px;overflow: hidden;border-radius: 6px;" class="d-inline-block align-middle"><img loading="lazy" style="width: 100%;" src="'+image+'"></div>\n' +
                        '                        <div class="map_info d-inline-block align-middle ml-2 text-left">'+window.icon_show_ui_map+' <b class="map_name" id="map_name_'+id+'"><span>'+((name.length > 60) ? name.slice(0, 60) + "..." : name)+'</span></b>'+input_rename+'&nbsp;&nbsp;'+btn_rename+'<br><span style="font-size:12px">'+count+' '+window.backend_labels.rooms_assigned+'</span></div>\n' +
                        '                    </div>\n' +
                        '                    <div class="map_buttons col-md-4 pt-1 text-center text-sm-center text-md-right text-lg-right">\n' +
                        '                        <a title="'+window.backend_labels.drag_change_pos.toUpperCase()+'" style="background-color: white; border: 1px solid black; cursor: pointer" class="handle btn btn-primary btn-sm">\n' +
                        '                           <i style="color: black" class="fas fa-arrows-alt"></i>\n' +
                        '                        </a>\n' +
                        '                        <a title="'+window.backend_labels.edit.toUpperCase()+'" href="index.php?p=edit_map&id='+id+'" class="btn btn-warning btn-sm">\n' +
                        '                            <i class="fas fa-edit"></i>\n' +
                        '                        </a>\n' + btn_duplicate +
                        '                        <a title="'+window.backend_labels.delete.toUpperCase()+'" href="#" onclick="modal_delete_map('+id+');return false;" class="btn btn-danger btn-sm">\n' +
                        '                            <i class="fas fa-trash"></i>\n' +
                        '                        </a>\n' +
                        '                    </div>\n' +
                        '                </div>\n' +
                        '            </div>\n' +
                        '        </div>';
                    break;
                case 'map':
                    html += '<div class="div_map card mb-2 py-2">\n' +
                        '            <div class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                        '                <div data-id="'+id+'" class="row maph">\n' +
                        '                    <div class="map_content col-md-8 text-center text-sm-center text-md-left text-lg-left">\n' +
                        '                        <div style="width: 90px;height: 44px;overflow: hidden;border-radius: 6px;" class="d-inline-block align-middle"><img style="width: 100%;" src="img/map.jpg"></div>\n' +
                        '                        <div class="map_info d-inline-block align-middle ml-2 text-left"><b class="map_name" id="map_name_'+id+'">'+window.icon_show_ui_map_tour+' <span>'+((name.length > 60) ? name.slice(0, 60) + "..." : name)+'</span></b>'+input_rename+'&nbsp;&nbsp;'+btn_rename+'<br><span style="font-size:12px">'+count+' '+window.backend_labels.rooms_assigned+'</span></div>\n' +
                        '                    </div>\n' +
                        '                    <div class="map_buttons col-md-4 pt-1 text-center text-sm-center text-md-right text-lg-right">\n' +
                        '                        <a title="'+window.backend_labels.edit.toUpperCase()+'" href="index.php?p=edit_map&id='+id+'" class="btn btn-warning btn-sm">\n' +
                        '                            <i class="fas fa-edit"></i>\n' +
                        '                        </a>\n' +
                        '                        <a title="'+window.backend_labels.delete.toUpperCase()+'" href="#" onclick="modal_delete_map('+id+');return false;" class="btn btn-danger btn-sm">\n' +
                        '                            <i class="fas fa-trash"></i>\n' +
                        '                        </a>\n' +
                        '                    </div>\n' +
                        '                </div>\n' +
                        '            </div>\n' +
                        '        </div>';
                    break;
            }
        });
        $('#maps_list').html(html).promise().done(function () {
            $('.help_t').tooltip();
            $('#search_div').html(html_search).promise().done(function () {
                $('.rename_input').keydown(function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode == 13) {
                        var id = $(this).attr('id').replace('rename_input_','');
                        save_rename_map(id);
                    }
                });
                $('#view_type_toggle').bootstrapToggle();
                $('#view_type_toggle').change(function() {
                    var checked = $(this).prop('checked');
                    if(!checked) {
                        localStorage.setItem('map_view_type', 'grid');
                        $('.div_map').addClass('div_map_grid');
                        $('#maps_list').css('margin','0 -5px');
                        $('#maps_list .maph .map_content').removeClass('text-lg-left').removeClass('text-md-left');
                        $('#maps_list .maph .map_buttons').removeClass('text-lg-right').removeClass('text-md-right');
                        $('#maps_list .maph .map_content').removeClass('col-md-8').addClass('col-12');
                        $('#maps_list .maph .map_buttons').removeClass('col-md-4').addClass('col-12').addClass('mt-1');
                        $('#maps_list .maph .map_buttons').addClass('col-auto').removeClass('col-md-auto');
                        $('#maps_list .maph .map_content .map_info').removeClass('text-left').addClass('text-center');
                        $('#maps_list .maph .map_content .map_info').css('width','100%');
                    } else {
                        localStorage.setItem('map_view_type', 'list');
                        $('.div_map').removeClass('div_map_grid');
                        $('#maps_list').css('margin','0');
                        $('#maps_list .maph .map_content').addClass('text-lg-left').addClass('text-md-left');
                        $('#maps_list .maph .map_buttons').addClass('text-lg-right').addClass('text-md-right');
                        $('#maps_list .maph .map_content').removeClass('col-12').addClass('col-md-8');
                        $('#maps_list .maph .map_buttons').removeClass('col-12').addClass('col-md-4').removeClass('mt-1');
                        $('#maps_list .maph .map_buttons').removeClass('col-auto').addClass('col-md-auto');
                        $('#maps_list .maph .map_content .map_info').addClass('text-left').removeClass('text-center');
                        $('#maps_list .maph .map_content .map_info').css('width','auto');
                    }
                });
                if ("map_view_type" in localStorage) {
                    var view_type = localStorage.getItem('map_view_type');
                    switch (view_type) {
                        case 'list':
                            $('#view_type_toggle').bootstrapToggle('on');
                            break;
                        case 'grid':
                            $('#view_type_toggle').bootstrapToggle('off');
                            break;
                    }
                }
                if(!permissions['edit']) {
                    $('#maps_list .fa-edit').parent().hide();
                }
                if(!permissions['delete']) {
                    $('#maps_list .fa-trash').parent().hide();
                }
                if(window.user_role=='editor') {
                    $('#maps_list .fa-arrows-alt').parent().hide();
                }
                $('#maps_list').searchable({
                    selector      : '.div_map',
                    childSelector : 'div',
                    searchField   : '.search_input',
                    searchType    : 'default',
                    clearOnLoad   : false
                });
                $('#maps_list .btn').tooltipster({
                    delay: 10,
                    hideOnClick: true
                });
                var el = document.getElementById('maps_list');
                Sortable.create(el,{
                    handle: '.handle',
                    filter: ".no_drag",
                    onMove: function (e) { return e.related.className.indexOf('no_drag') === -1;  },
                    onEnd: function (evt) {
                        var array_maps_priority = [];
                        $('#maps_list .maph').each(function () {
                            var id = $(this).attr('data-id');
                            array_maps_priority.push(id);
                        });
                        change_maps_order(array_maps_priority);
                    },
                });
            });
        });
    }

    window.view_rename_map = function(id) {
        $('#btn_view_rename_'+id).addClass('d-none');
        $('#btn_save_rename_'+id).removeClass('d-none');
        $('#btn_close_rename_'+id).removeClass('d-none');
        $('#rename_input_'+id).removeClass('d-none');
        $('#rename_input_'+id).select();
        $('#map_name_'+id).addClass('d-none');
    }

    window.save_rename_map = function(id) {
        var name = $('#rename_input_'+id).val();
        if(name!='') {
            $('#map_name_'+id+' span').html(name);
            $.ajax({
                url: "ajax/rename_map.php",
                type: "POST",
                data: {
                    id: id,
                    name: name
                },
                async: true,
                success: function (json) {
                    $('#btn_view_rename_'+id).removeClass('d-none');
                    $('#btn_save_rename_'+id).addClass('d-none');
                    $('#btn_close_rename_'+id).addClass('d-none');
                    $('#rename_input_'+id).addClass('d-none');
                    $('#map_name_'+id).removeClass('d-none');
                }
            });
        }
    }

    window.close_rename_map = function(id) {
        $('#btn_view_rename_'+id).removeClass('d-none');
        $('#btn_save_rename_'+id).addClass('d-none');
        $('#btn_close_rename_'+id).addClass('d-none');
        $('#rename_input_'+id).addClass('d-none');
        $('#map_name_'+id).removeClass('d-none');
    }

    window.rs_handleOrientationChange = function(is_marker = false) {
        const isPortrait = window.innerHeight > window.innerWidth;
        rs_appContainer.toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_rs_listComponentWrapper.toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_listComponent.toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_listHeader.toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_listContainer.toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_listFooter.toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_viewSelectorGroup.toggleClass('btn-group-vertical', isPortrait).toggleClass('btn-group', !isPortrait);
        $('.rooms_slider_scroll-arrows').toggleClass('portrait', isPortrait).toggleClass('landscape', !isPortrait);
        rs_searchWrapper.toggle(!isPortrait);
        rs_scrollUpBtn.find('i').attr('class', `fa-solid ${isPortrait ? 'fa-arrow-left' : 'fa-arrow-up'}`);
        rs_scrollDownBtn.find('i').attr('class', `fa-solid ${isPortrait ? 'fa-arrow-right' : 'fa-arrow-down'}`);
        rs_renderItems(true,is_marker);
    }

    window.rs_setView = function(newView, is_marker = false) {
        rs_currentView = newView;
        localStorage.setItem('rs_currentView',rs_currentView);
        rs_viewButtons.removeClass('active');
        $(`#rooms_slider_${newView}-view-btn`).addClass('active');
        rs_renderItems(true,is_marker);
    }

    window.rs_handleItemClick = function(e,is_marker = false) {
        const target = $(e.target).closest('.rooms_slider_list-item');
        if (!target.length) return;
        const id = target.data('id');
        const image = target.data('image');
        if(is_marker) {
            if ($(e.target).closest('.rooms_slider_item-icon-wrapper, .rooms_slider_compact-plus-icon').length) {
                e.stopPropagation();
                add_marker(window.id_room_sel,window.panorama_image,id);
                return;
            }
        }
        rs_updateSelection(id, false,is_marker);
        if($('#marker_editor_div').length) {
            select_room_marker(id,image,null);
        } else if($('#poi_editor_div').length) {
            select_room_poi(id,image,null);
        } else if($('#measure_editor_div').length) {
            select_room_measure(id,image,null);
        }
    }

    window.rs_updateSelection = function(newSelectedId, shouldScroll = false,is_marker = false) {
        rs_items.forEach(item => item.selected = item.id === newSelectedId);
        $('.rooms_slider_list-item').each(function() {
            const $item = $(this);
            if (parseInt($item.data('id')) === newSelectedId) {
                $item.addClass('selected');
            } else {
                $item.removeClass('selected');
            }
        });
        if(is_marker && window.create_content==1) rs_initDraggable();
        if (shouldScroll) {
            rs_scrollToActive();
        }
    }

    window.rs_renderItems = function(shouldScroll = false, is_marker = false) {
        const searchTerm = rs_searchInput.val().toLowerCase();
        const itemsToRender = rs_items.filter(item =>
            item.name.toLowerCase().includes(searchTerm)
        );
        rs_listContainer.empty();
        const row = $('<div class="row no-gutters align-content-start h-100"></div>');
        rs_listContainer.append(row);
        const isPortrait = window.innerHeight > window.innerWidth;
        row.toggleClass('portrait', isPortrait);
        if (rs_currentView === 'compact' && isPortrait) {
            row.css({ display: 'grid', gridTemplateRows: 'repeat(2, 1fr)', gridAutoFlow: 'column', gap: '8px', padding: '8px' });
        }
        itemsToRender.forEach(item => {
            let colDiv, itemHTML;
            const wrapperStart = `<div class="h-100" style="padding: 6px;">`;
            const wrapperEnd = `</div>`;
            const badgeHTML = `<span id="count_item_${item.id}" data-count="${item.count}" class="count_item badge badge-light ml-auto">${item.count}</span>`;
            const nameOverlayHTML = `<div class="rooms_slider_item-name-overlay p-2 rounded-bottom d-flex align-items-center"><span class="text-truncate pr-1">${item.name}</span>${badgeHTML}</div>`;
            const landscapeClass = isPortrait ? '' : 'landscape';
            const portraitClass = isPortrait ? 'portrait' : '';
            switch (rs_currentView) {
                case 'list':
                    colDiv = $(`<div class="rooms_slider_list-item-col-list ${portraitClass} ${isPortrait ? '' : 'col-12'}"></div>`);
                    itemHTML = `${wrapperStart}<div class="rooms_slider_list-item rooms_slider_list-item-list ${landscapeClass} ${portraitClass} rounded ${item.selected ? 'selected' : ''} room_${item.id}" data-id="${item.id}" data-image="${item.image}"><img src="${item.thumb}" draggable="false" class="rooms_slider_item-image rounded"><div class="rooms_slider_item-icon-wrapper d-flex align-items-center justify-content-center"><i class="fa-solid fa-plus"></i></div>${nameOverlayHTML}</div>${wrapperEnd}`;
                    break;
                case 'grid':
                    colDiv = $(`<div class="rooms_slider_list-item-col-grid ${portraitClass} ${isPortrait ? '' : 'col-6'}"></div>`);
                    const gridContent = `<img src="${item.thumb}" draggable="false" class="rooms_slider_item-image rounded"><div class="rooms_slider_item-icon-wrapper d-flex align-items-center justify-content-center"><i class="fa-solid fa-plus"></i></div>${nameOverlayHTML}`;
                    itemHTML = `${wrapperStart}<div class="rooms_slider_list-item rooms_slider_list-item-grid ${landscapeClass} ${portraitClass} rounded ${item.selected ? 'selected' : ''} room_${item.id}" data-id="${item.id}">${isPortrait ? gridContent : `<div class="rooms_slider_square-content landscape">${gridContent}</div>`}</div>${wrapperEnd}`;
                    break;
                case 'compact':
                    if (isPortrait) {
                        const compactItem = $(`<div class="rooms_slider_list-item rooms_slider_list-item-compact ${portraitClass} rounded d-flex align-items-center p-2 ${item.selected ? 'selected' : ''} room_${item.id}" data-id="${item.id}" data-image="${item.image}"><img src="${item.thumb}" draggable="false" class="rooms_slider_item-image-compact"><p class="mb-0 ml-2 text-truncate pr-1" style="font-size: 12px;">${item.name}</p><div class="ml-auto d-flex align-items-center"><span id="count_item_${item.id}" data-count="${item.count}" class="count_item badge badge-light mr-2">${item.count}</span><i class="fa-solid fa-plus rooms_slider_compact-plus-icon"></i></div></div>`);
                        row.append(compactItem);
                        return;
                    } else {
                        colDiv = $('<div class="col-12"></div>');
                        itemHTML = `${wrapperStart}<div class="rooms_slider_list-item rooms_slider_list-item-compact ${landscapeClass} rounded d-flex align-items-center p-2 ${item.selected ? 'selected' : ''} room_${item.id}" data-id="${item.id}" data-image="${item.image}"><img src="${item.thumb}" draggable="false" class="rooms_slider_item-image-compact"><p class="mb-0 ml-2 text-truncate pr-1" style="font-size: 12px;">${item.name}</p><div class="ml-auto d-flex align-items-center"><span id="count_item_${item.id}" data-count="${item.count}" class="count_item badge badge-light mr-2">${item.count}</span><i class="fa-solid fa-plus rooms_slider_compact-plus-icon"></i></div></div>${wrapperEnd}`;
                    }
                    break;
            }
            if(colDiv) {
                colDiv.html(itemHTML);
                row.append(colDiv);
            }
        });
        rs_initInteractions(is_marker);
        rs_updateScrollArrows();
        if (shouldScroll) {
            setTimeout(rs_scrollToActive, 10);
        }
        if(is_marker) {
            if(window.can_create) {
                $('.rooms_slider_list-item:not(.selected) .rooms_slider_item-icon-wrapper').removeClass('disabled_c');
                $('.rooms_slider_list-item:not(.selected) .rooms_slider_compact-plus-icon').removeClass('disabled_c');
                $('.rooms_slider_list-item, .rooms_slider_list-item').css('cursor','drag');
                $('.rooms_slider_list-item:not(.selected)').draggable('enable');
            } else {
                $('.rooms_slider_list-item:not(.selected) .rooms_slider_item-icon-wrapper').addClass('disabled_c');
                $('.rooms_slider_list-item:not(.selected) .rooms_slider_compact-plus-icon').addClass('disabled_c');
                $('.rooms_slider_list-item, .rooms_slider_list-item').css('cursor','pointer');
                $('.rooms_slider_list-item:not(.selected)').draggable('disable');
            }
        }
    }

    window.rs_initDraggable = function() {
        const EDGE_THRESHOLD = 30;
        const START_DELAY = 500;
        const REPEAT_INTERVAL = 30;
        let currentEdge = null;
        let startTimeout = null;
        let repeatInterval = null;
        function onEdgeRepeat(edge) {
            switch(edge) {
                case 'top':
                    try {
                        var pitch = parseFloat(window.viewer.getPitch());
                        window.viewer.setPitch(pitch+1,false);
                    } catch (e) {}
                    break;
                case 'bottom':
                    try {
                        var pitch = parseFloat(window.viewer.getPitch());
                        window.viewer.setPitch(pitch-1,false);
                    } catch (e) {}
                    break;
                case 'left':
                    try {
                        var yaw = parseFloat(window.viewer.getYaw());
                        window.viewer.setYaw(yaw-1,false);
                    } catch (e) {}
                    break;
                case 'right':
                    try {
                        var yaw = parseFloat(window.viewer.getYaw());
                        window.viewer.setYaw(yaw+1,false);
                    } catch (e) {}
                    break;
            }
            fix_all_embeds_pos();
        }
        function startRepeatAfterDelay(edge) {
            if (currentEdge === edge) return;
            stopAllTimers();
            currentEdge = edge;
            startTimeout = setTimeout(() => {
                repeatInterval = setInterval(() => onEdgeRepeat(edge), REPEAT_INTERVAL);
            }, START_DELAY);
        }
        function stopAllTimers() {
            if (startTimeout) {
                clearTimeout(startTimeout);
                startTimeout = null;
            }
            if (repeatInterval) {
                clearInterval(repeatInterval);
                repeatInterval = null;
            }
            currentEdge = null;
        }
        $('.rooms_slider_list-item').each(function() {
            if ($(this).is('.ui-draggable')) {
                $(this).draggable('destroy');
            }
        });
        $('.rooms_slider_list-item:not(.selected)').draggable({
            delay: 200,
            distance: 20,
            cursorAt: { top: 30, left: 30 },
            helper: function(event) {
                const itemId = $(this).data('id');
                const itemData = rs_items.find(item => item.id === itemId);
                return $(`<div class="rooms_slider_custom-drag-helper"><img src="${itemData.thumb}" draggable="false" /><div class="rooms_slider_custom-drag-helper-overlay"><i class="fa-solid fa-plus"></i></div></div>`);
            },
            appendTo: 'body',
            revert: 'invalid',
            containment: '#rooms_slider_app-container',
            start: function() {
                $("body").css("cursor", "none");
                $('.center_helper').css('opacity',0);
                rs_appContainer.addClass('dragging-active');
            },
            stop: function() {
                stopAllTimers();
                $("body").css("cursor", "");
                $('.center_helper').css('opacity',0.6);
                rs_appContainer.removeClass('dragging-active');
            },
            drag: function(event, ui) {
                const parent = $("#rooms_slider_content-container");
                const containerOffset = parent.offset();
                const containerWidth = parent.outerWidth();
                const containerHeight = parent.outerHeight();
                const posX = ui.offset.left - containerOffset.left;
                const posY = ui.offset.top - containerOffset.top;
                const right = containerWidth - (posX + $(this).outerWidth());
                const bottom = containerHeight - (posY + $(this).outerHeight());
                let edge = null;
                if (posY < EDGE_THRESHOLD) edge = "top";
                else if (bottom < EDGE_THRESHOLD) edge = "bottom";
                else if (posX < EDGE_THRESHOLD && posX>-15) edge = "left";
                else if (right < EDGE_THRESHOLD) edge = "right";
                if (edge) {
                    startRepeatAfterDelay(edge);
                } else {
                    stopAllTimers();
                }
            },
        });
    }

    window.rs_initInteractions = function(is_marker = false) {
        $('.rooms_slider_list-item').on('click', function(event) {
            rs_handleItemClick(event, is_marker);
        });
        if(is_marker && window.create_content==1) rs_initDraggable();
    }

    window.rs_updateScrollArrows = function() {
        const isPortrait = window.innerHeight > window.innerWidth;
        const scrollAxis = isPortrait ? 'Width' : 'Height';
        const scrollDir = isPortrait ? 'scrollLeft' : 'scrollTop';
        const scrollDim = rs_listContainer.prop(`scroll${scrollAxis}`);
        const clientDim = rs_listContainer.prop(`client${scrollAxis}`);
        const scrollPos = rs_listContainer[scrollDir]();
        rs_scrollUpBtn.toggleClass('visible', scrollPos > 0);
        rs_scrollDownBtn.toggleClass('visible', scrollPos < scrollDim - clientDim - 1);
    }

    window.rs_scrollToActive = function() {
        if(!window.rs_scroll) {
            window.rs_scroll = true;
            return;
        }
        const selectedEl = rs_listContainer.find('.rooms_slider_list-item.selected');
        if (!selectedEl.length) return;
        const isPortrait = window.innerHeight > window.innerWidth;
        const itemToScroll = selectedEl.closest('.rooms_slider_list-item-col-list, .rooms_slider_list-item-col-grid, .rooms_slider_list-item-compact');
        if (!itemToScroll.length) return;
        if (isPortrait) {
            const containerOffsetLeft = rs_listContainer.offset().left;
            const itemOffsetLeft = itemToScroll.offset().left;
            const currentScrollLeft = rs_listContainer.scrollLeft();
            const newScrollLeft = currentScrollLeft + itemOffsetLeft - containerOffsetLeft - (rs_listContainer.width() / 2) + (itemToScroll.width() / 2);
            rs_listContainer.stop().animate({ scrollLeft: newScrollLeft }, 250);
        } else {
            const containerOffsetTop = rs_listContainer.offset().top;
            const itemOffsetTop = itemToScroll.offset().top;
            const currentScrollTop = rs_listContainer.scrollTop();
            const newScrollTop = currentScrollTop + itemOffsetTop - containerOffsetTop - (rs_listContainer.height() / 2) + (itemToScroll.height() / 2);
            rs_listContainer.stop().animate({ scrollTop: newScrollTop }, 250);
        }
    }

    window.rs_init_components = function(is_marker=false) {
        rs_scrollUpBtn.on('click', function() {
            const isPortrait = window.innerHeight > window.innerWidth;
            const scrollAmount = isPortrait ? rs_listContainer.width() * 0.8 : rs_listContainer.height() * 0.8;
            if (isPortrait) {
                rs_listContainer.animate({ scrollLeft: `-=${scrollAmount}` }, 250);
            } else {
                rs_listContainer.animate({ scrollTop: `-=${scrollAmount}` }, 250);
            }
        });
        rs_scrollDownBtn.on('click', function() {
            const isPortrait = window.innerHeight > window.innerWidth;
            const scrollAmount = isPortrait ? rs_listContainer.width() * 0.8 : rs_listContainer.height() * 0.8;
            if (isPortrait) {
                rs_listContainer.animate({ scrollLeft: `+=${scrollAmount}` }, 250);
            } else {
                rs_listContainer.animate({ scrollTop: `+=${scrollAmount}` }, 250);
            }
        });
        rs_listContainer.on('scroll', rs_updateScrollArrows);
        if(is_marker) {
            rs_contentContainer.droppable({
                accept: ".rooms_slider_list-item",
                over: function() { $(this).addClass('drop-hover'); },
                out: function() { $(this).removeClass('drop-hover'); },
                drop: function(event, ui) {
                    const droppedId = ui.draggable.data('id');
                    var coords = window.viewer.mouseEventToCoords(event);
                    var yaw = parseFloat(coords[1]);
                    var pitch = parseFloat(coords[0]);
                    window.rs_scroll = false;
                    new_marker(window.id_room_sel,window.panorama_image,droppedId,yaw,pitch);
                    $(this).removeClass('drop-hover');
                }
            });
        }
        rs_viewButtons.on('click', (e) => {
            const view = $(e.currentTarget).attr('id').replace('rooms_slider_', '').replace('-view-btn', '');
            rs_setView(view,is_marker);
        });
        rs_searchInput.on('input', function() {
            const hasText = $(this).val().length > 0;
            rs_searchClearBtn.toggle(hasText);
            rs_renderItems(false,is_marker);
        });
        rs_searchClearBtn.on('click', function() {
            rs_searchInput.val('').trigger('input');
        });
    }

    function parse_room_marker(rooms) {
        var html = '';
        if(rooms.length==0) {
            $('#msg_no_room').show();
            $('#marker_editor_div').hide();
            $('#msg_sel_room').hide();
            $('#rooms_slider_app-container').removeClass('loading');
        } else {
            $('#msg_no_room').hide();
            window.rooms_count = rooms.length;
            var index_initial_sel = 0;
            if(window.id_room_marker!=0) {
                jQuery.each(rooms, function(index, room) {
                    var id = room.id;
                    if(id==window.id_room_marker) {
                        index_initial_sel = index;
                        return;
                    }
                });
            }
            jQuery.each(rooms, function(index, room) {
                var id = parseInt(room.id);
                var name = room.name;
                var image = room.panorama_image;
                var thumb_image = room.thumb_image_url;
                var count_markers = room.count_markers;
                var selected = (index==index_initial_sel) ? true : false;
                var item = { id: id, name: name, image: image, thumb: thumb_image, selected: selected, count: count_markers };
                rs_items.push(item);
            });
            rs_renderItems(true,true);
            if(index_initial_sel!=0) {
                var id = rooms[index_initial_sel].id;
                var image = rooms[index_initial_sel].panorama_image;
                select_room_marker(id,image,null);
            } else if(rooms.length>=1) {
                var id = rooms[0].id;
                var image = rooms[0].panorama_image;
                select_room_marker(id,image,null);
            }
        }
    }

    function parse_room_poi(rooms) {
        var html = '';
        if(rooms.length==0) {
            $('#msg_no_room').show();
            $('#poi_editor_div').hide();
            $('#msg_sel_room').hide();
            $('#rooms_slider_app-container').removeClass('loading');
        } else {
            $('#msg_no_room').hide();
            window.rooms_count = rooms.length;
            var index_initial_sel = 0;
            if(window.id_room_marker!=0) {
                jQuery.each(rooms, function(index, room) {
                    var id = room.id;
                    if(id==window.id_room_marker) {
                        index_initial_sel = index;
                        return;
                    }
                });
            }
            jQuery.each(rooms, function(index, room) {
                var id = parseInt(room.id);
                var name = room.name;
                var image = room.panorama_image;
                var thumb_image = room.thumb_image_url;
                var count_pois = room.count_pois;
                var selected = (index==index_initial_sel) ? true : false;
                var item = { id: id, name: name, image: image, thumb: thumb_image, selected: selected, count: count_pois };
                rs_items.push(item);
            });
            rs_renderItems(true,false);
            if(index_initial_sel!=0) {
                var id = rooms[index_initial_sel].id;
                var image = rooms[index_initial_sel].panorama_image;
                select_room_poi(id,image,null);
            } else if(rooms.length>=1) {
                var id = rooms[0].id;
                var image = rooms[0].panorama_image;
                select_room_poi(id,image,null);
            }
        }
    }

    function parse_room_measure(rooms) {
        var html = '';
        if(rooms.length==0) {
            $('#msg_no_room').show();
            $('#measure_editor_div').hide();
            $('#msg_sel_room').hide();
            $('#rooms_slider_app-container').removeClass('loading');
        } else {
            $('#msg_no_room').hide();
            window.rooms_count = rooms.length;
            var index_initial_sel = 0;
            if(window.id_room_marker!=0) {
                jQuery.each(rooms, function(index, room) {
                    var id = room.id;
                    if(id==window.id_room_marker) {
                        index_initial_sel = index;
                        return;
                    }
                });
            }
            jQuery.each(rooms, function(index, room) {
                var id = parseInt(room.id);
                var name = room.name;
                var image = room.panorama_image;
                var thumb_image = room.thumb_image_url;
                var count_measures = room.count_measures;
                var selected = (index==index_initial_sel) ? true : false;
                var item = { id: id, name: name, image: image, thumb: thumb_image, selected: selected, count: count_measures };
                rs_items.push(item);
            });
            rs_renderItems(true,false);
            if(index_initial_sel!=0) {
                var id = rooms[index_initial_sel].id;
                var image = rooms[index_initial_sel].panorama_image;
                select_room_measure(id,image,null);
            } else if(rooms.length>=1) {
                var id = rooms[0].id;
                var image = rooms[0].panorama_image;
                select_room_measure(id,image,null);
            }
        }
    }

    window.open_preview_viewer = function () {
        $('#modal_preview .modal-body').append('<iframe style="width:100%;height:80vh;;" allowfullscreen allow="gyroscope; accelerometer; xr; microphone *" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="../viewer/index.php?code='+window.code_vt+'&room='+window.id_room_sel+'&preview=1"></iframe>');
        $('#modal_preview').modal('show');
    }

    window.open_preview_global_viewer = function () {
        var code_vt = $('#virtualtour_selector option:selected').attr('data-code');
        $('#modal_preview_global .modal-body').append('<iframe style="width:100%;height:80vh;;" allowfullscreen allow="gyroscope; accelerometer; xr; microphone *" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="../viewer/index.php?code='+code_vt+'&nostat=1&ignore_embedded=1"></iframe>');
        $('#modal_preview_global').modal('show');
    }

    window.open_preview_presentation = function (index,id_room) {
        $('#modal_preview .modal-body').append('<iframe style="width:100%;height:80vh;;" allowfullscreen allow="gyroscope; accelerometer; xr; microphone *" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="../viewer/index.php?code='+window.code_vt+'&room='+id_room+'&nostat=1&preview=1&preview_presentation='+index+'"></iframe>');
        $('#modal_preview').modal('show');
    }

    window.close_preview_viewer = function () {
        $('#modal_preview .modal-body').html('');
    }

    window.close_preview_global_viewer = function () {
        $('#modal_preview_global .modal-body').html('');
    }

    function renderRoomViews(context, id_room, image) {
        $('#visibile_in_views').empty();
        jQuery.each(window.rooms, function(index, room) {
            var id = room.id;
            if (id == id_room) {
                sessionStorage.setItem('slider_id_room_sel_' + window.id_virtualtour, id_room);
                $('#subtitle_header').html(room.name);
                var rooms_alt = room.rooms_alt;
                if (rooms_alt.length > 0) {
                    var main_img = room.panorama_image;
                    var class_active = (image == main_img) ? 'active' : '';
                    var main_view_tooltip = room.main_view_tooltip || window.backend_labels.main_view;
                    var image_url = (window.s3_enabled == 1)
                        ? window.s3_url + 'viewer/panoramas/thumb/' + main_img
                        : '../viewer/panoramas/thumb/' + main_img;

                    var html = `<img title="${main_view_tooltip}" id="room_alt_0" class="${class_active} rooms_alt tooltip_view" onclick='change_room_alt("${context}",0,"${main_img}");' src="${image_url}" />`;
                    var option_select = `<option id='0'>${main_view_tooltip}</option>`;
                    var is_active = false;
                    jQuery.each(rooms_alt, function(index_alt, room_alt) {
                        var id_alt = room_alt.id;
                        var img_alt = room_alt.panorama_image;
                        var view_tooltip = room_alt.view_tooltip || `${window.backend_labels.view} ${id_alt}`;
                        class_active = (image == img_alt) ? 'active' : '';
                        if(class_active=='active') is_active=true;
                        image_url = (window.s3_enabled == 1)
                            ? window.s3_url + 'viewer/panoramas/thumb/' + img_alt
                            : '../viewer/panoramas/thumb/' + img_alt;

                        html += `<img title="${view_tooltip}" id="room_alt_${id_alt}" class="${class_active} rooms_alt tooltip_view" onclick='change_room_alt("${context}",${id_alt},"${img_alt}");' src="${image_url}" />`;
                        option_select += `<option id='${id_alt}'>${view_tooltip}</option>`;
                    });
                    if(!is_active) $('.rooms_alt').first().addClass('active');
                    if (room.virtual_staging != 2) {
                        $('#visibile_in_views').prop('disabled', false);
                        $('#visibile_in_views').html(option_select).promise().done(function () {
                            $('#visibile_in_views').selectpicker('refresh');
                        });
                        $('.icon_visible_view').removeClass('hidden');
                    } else {
                        $('.icon_visible_view').addClass('hidden');
                    }
                    $('.rooms_view_sel').html(html).promise().done(function () {
                        $('.tooltip_view').tooltipster({
                            theme: 'tooltipster-borderless',
                            side: 'bottom',
                            animation: 'grow',
                            delay: 0,
                            arrow: false
                        });
                    });
                } else {
                    $('.rooms_view_sel').empty();
                    $('.icon_visible_view').addClass('hidden');
                }
            }
        });
    }

    window.select_room_marker = function (id_room,image,id_marker_add,yaw_m='',pitch_m='') {
        $('#rooms_slider_slider-container').addClass('disabled');
        $('#north_val').html('--');
        $('.azimuth-control').addClass('disabled');
        $('.north-control').addClass('disabled');
        if(id_room!=window.id_room_sel && !window.switched_page) {
            window.currentPitch = 0;
            window.currentYaw = 0;
            window.currentHfov = 0;
        }
        if(id_room!=window.id_room_sel) {
            window.id_room_alt_sel=0;
        }
        window.id_room_sel = id_room;
        window.image_room_sel = image;
        window.switched_page = false;
        renderRoomViews('marker', id_room, image);
        $('#btn_add_marker').attr('onclick','add_marker('+id_room+',\''+image+'\')');
        $('#btn_add_marker').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        $('#btn_switch_to_poi').attr('onclick','switch_to_poi('+id_room+')');
        $('#btn_switch_to_poi').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('#msg_sel_room').hide();
        $("#content-wrapper").animate({ scrollTop: $(document).height() }, 200);
        $('#btn_edit_room_q').attr('href','index.php?p=edit_room&id='+id_room);
        get_markers(id_room,image,id_marker_add,yaw_m,pitch_m);
    }

    window.switch_to_poi = function(id_room) {
        var yaw = parseFloat(viewer.getYaw());
        var pitch = parseFloat(viewer.getPitch());
        var hfov = parseFloat(viewer.getHfov());
        sessionStorage.setItem('currentYaw',yaw.toString());
        sessionStorage.setItem('currentPitch',pitch.toString());
        sessionStorage.setItem('currentHfov',hfov.toString());
        location.href = 'index.php?p=pois&id_room='+id_room;
    }

    window.select_room_poi = function (id_room,image,id_poi_add) {
        $('#rooms_slider_slider-container').addClass('disabled');
        if(id_room!=window.id_room_sel && !window.switched_page) {
            window.currentPitch = 0;
            window.currentYaw = 0;
            window.currentHfov = 0;
        }
        if(id_room!=window.id_room_sel) {
            window.id_room_alt_sel=0;
        }
        window.id_room_sel = id_room;
        window.image_room_sel = image;
        window.switched_page = false;
        renderRoomViews('poi', id_room, image);
        $('#btn_add_poi').attr('onclick','add_poi('+id_room+',\''+image+'\');');
        $('#btn_add_poi').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        $('#btn_switch_to_marker').attr('onclick','switch_to_marker('+id_room+')');
        $('#btn_switch_to_marker').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').hide();
        $('.icon_visible_view').hide();
        $('#msg_sel_room').hide();
        $("#content-wrapper").animate({ scrollTop: $(document).height() }, 200);
        var resolution = $('.room_'+id_room).attr('data-resolution');
        $('#room_panorama_resolution').html(resolution);
        if(window.s3_enabled==1) {
            var image_url = window.s3_url+'viewer/panoramas/'+image;
        } else {
            var image_url = '../viewer/panoramas/'+image;
        }
        $('#img_staging_room').attr('src',image_url);
        $('#btn_edit_room_q').attr('href','index.php?p=edit_room&id='+id_room);
        get_pois(id_room,image,id_poi_add);
    }

    window.change_room_alt = function (w,id,image) {
        window.id_room_alt_sel = id;
        switch(w) {
            case 'poi':
                select_room_poi(window.id_room_sel,image,null);
                break;
            case 'marker':
                select_room_marker(window.id_room_sel,image,null);
                break;
            case 'measure':
                select_room_measure(window.id_room_sel,image,null);
                break;
        }
    }

    window.toggle_visible_view = function (w) {
        if($('#check_visibile_view').is(':checked')) {
            sessionStorage.setItem('check_visibile_view', 1);
            switch(w) {
                case 'poi':
                    $('#panorama_pois .hotspot').each(function() {
                        var visible_multiview_ids = $(this).attr('visible_multiview_ids');
                        if(visible_multiview_ids=='') {
                            $(this).removeClass('hidden_p');
                        } else {
                            var array_mv = visible_multiview_ids.split(",");
                            array_mv = array_mv.map(function(element) {
                                return parseInt(element);
                            });
                            if(array_mv.includes(window.id_room_alt_sel)) {
                                $(this).removeClass('hidden_p');
                            } else {
                                $(this).addClass('hidden_p');
                            }
                        }
                    });
                    $(window).trigger('resize');
                    window.viewer.resize();
                    setTimeout(function() {
                        adjust_poi_embed_helpers_all();
                        adjust_marker_embed_helpers_all();
                    },50);
                    break;
                case 'marker':
                    $('#panorama_markers .hotspot').each(function() {
                        var visible_multiview_ids = $(this).attr('visible_multiview_ids');
                        if(visible_multiview_ids=='') {
                            $(this).removeClass('hidden_p');
                        } else {
                            var array_mv = visible_multiview_ids.split(",");
                            array_mv = array_mv.map(function(element) {
                                return parseInt(element);
                            });
                            if(array_mv.includes(window.id_room_alt_sel)) {
                                $(this).removeClass('hidden_p');
                            } else {
                                $(this).addClass('hidden_p');
                            }
                        }
                    });
                    $(window).trigger('resize');
                    window.viewer.resize();
                    setTimeout(function() {
                        adjust_poi_embed_helpers_all();
                        adjust_marker_embed_helpers_all();
                    },50);
                    break;
                case 'measure':
                    $('#panorama_measures .leader-line').each(function() {
                        var visible_multiview_ids = $(this).attr('visible_multiview_ids');
                        if(visible_multiview_ids=='') {
                            $(this).removeClass('hidden_p');
                        } else {
                            var array_mv = visible_multiview_ids.split(",");
                            array_mv = array_mv.map(function(element) {
                                return parseInt(element);
                            });
                            if(array_mv.includes(window.id_room_alt_sel)) {
                                $(this).removeClass('hidden_p');
                            } else {
                                $(this).addClass('hidden_p');
                            }
                        }
                    });
                    break;
            }
        } else {
            sessionStorage.setItem('check_visibile_view', 0);
            switch(w) {
                case 'poi':
                    $('#panorama_pois .hotspot').each(function() {
                        $(this).removeClass('hidden_p');
                    });
                    $(window).trigger('resize');
                    window.viewer.resize();
                    setTimeout(function() {
                        adjust_poi_embed_helpers_all();
                        adjust_marker_embed_helpers_all();
                    },50);
                    break;
                case 'marker':
                    $('#panorama_markers .hotspot').each(function() {
                        $(this).removeClass('hidden_p');
                    });
                    $(window).trigger('resize');
                    window.viewer.resize();
                    setTimeout(function() {
                        adjust_poi_embed_helpers_all();
                        adjust_marker_embed_helpers_all();
                    },50);
                    break;
                case 'measure':
                    $('#panorama_measures .leader-line').each(function() {
                        $(this).removeClass('hidden_p');
                    });
                    break;
            }
        }
    }

    window.select_room_measure = function (id_room,image,id_measure_add) {
        $('#rooms_slider_slider-container').addClass('disabled');
        if(id_room!=window.id_room_sel && !window.switched_page) {
            window.currentPitch = 0;
            window.currentYaw = 0;
            window.currentHfov = 0;
        }
        if(id_room!=window.id_room_sel) {
            window.id_room_alt_sel=0;
        }
        window.id_room_sel = id_room;
        window.switched_page = false;
        renderRoomViews('measure', id_room, image);
        $('#btn_add_measure').attr('onclick','add_measure('+id_room+',\''+image+'\');');
        $('#btn_add_measure').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').hide();
        $('.icon_visible_view').hide();
        $('#msg_sel_room').hide();
        $("#content-wrapper").animate({ scrollTop: $(document).height() }, 200);
        $('#btn_edit_room_q').attr('href','index.php?p=edit_room&id='+id_room);
        get_measures(id_room,image,id_measure_add);
    }

    window.switch_to_marker = function(id_room) {
        var yaw = parseFloat(viewer.getYaw());
        var pitch = parseFloat(viewer.getPitch());
        var hfov = parseFloat(viewer.getHfov());
        sessionStorage.setItem('currentYaw',yaw.toString());
        sessionStorage.setItem('currentPitch',pitch.toString());
        sessionStorage.setItem('currentHfov',hfov.toString());
        location.href = 'index.php?p=markers&id_room='+id_room;
    }

    function get_markers(id_room,image,id_marker_add,yaw_m='',pitch_m='') {
        $.ajax({
            url: "ajax/get_markers.php",
            type: "POST",
            data: {
                id_room: id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                window.markers = rsp.markers;
                parse_hs_list(window.markers,'marker');
                var array_room = rsp.room;
                window.markers_initial = JSON.parse(JSON.stringify(window.markers));
                initialize_pano_markers(id_room,image,id_marker_add,array_room,yaw_m,pitch_m);
            }
        });
    }

    window.click_backlink = function() {
        if($('#backlink_marker').is(':checked')) {
            $('#override_pos_add').prop('checked',true);
            var event = new Event('change');
            $('#override_pos_add')[0].dispatchEvent(event);
        }
    }

    window.add_marker = function (id_room,image,id_room_target=0) {
        if($('#backlink_marker').is(':checked')) {
            $('#override_pos_add').prop('checked',true);
        } else {
            $('#override_pos_add').prop('checked',false);
        }
        var event = new Event('change');
        $('#override_pos_add')[0].dispatchEvent(event);
        $('#btn_new_marker').addClass("disabled");
        $('#btn_new_marker').attr('onclick','new_marker('+id_room+',\''+image+'\',0,null,null)');
        select_marker_style('icon');
        $('#modal_add_marker').modal('show');
        get_option_rooms_target('room_target_add',id_room,id_room_target,null,null);
    }

    window.select_marker_style = function (style_sel) {
        $('#dropdown_marker_style').html($('#btn_style_'+style_sel).html());
        switch(style_sel) {
            case 'icon':
                window.embed_type_sel = '';
                break;
            case 'embed_selection':
                window.embed_type_sel = 'selection';
                break;
        }
    }

    window.select_marker_style_edit = function (style_sel) {
        $('#dropdown_marker_style_edit').html($('#btn_edit_style_'+style_sel).html());
        switch(style_sel) {
            case 'icon':
                window.embed_type_sel = '';
                break;
            case 'embed_selection':
                window.embed_type_sel = 'selection';
                break;
        }
        if(window.embed_type_current!=window.embed_type_sel) {
            $('#btn_change_marker_embed_style').removeClass('disabled');
        } else {
            $('#btn_change_marker_embed_style').addClass('disabled');
        }
    }

    window.change_marker_embed_style = function() {
        $('#btn_change_marker_embed_style').addClass('disabled');
        confirm_edit_marker(window.marker_id_edit,window.marker_index_edit,false);
        $.ajax({
            url: "ajax/change_marker_embed_style.php",
            type: "POST",
            data: {
                id: window.marker_id_edit,
                yaw: window.markers[window.marker_index_edit].yaw,
                pitch: window.markers[window.marker_index_edit].pitch,
                embed_type: window.embed_type_sel
            },
            async: true,
            success: function (json) {
                jQuery.each(window.rooms, function(index, room) {
                    var id = room.id;
                    var image = room.panorama_image;
                    if(id==window.markers[window.marker_index_edit].id_room) {
                        setTimeout(function () {
                            try {
                                var yaw = parseFloat(window.viewer.getYaw());
                                var pitch = parseFloat(window.viewer.getPitch());
                                var hfov = parseFloat(window.viewer.getHfov());
                            } catch (e) {
                                var yaw = 0;
                                var pitch = 0;
                                var hfov = 0;
                            }
                            window.currentYaw = yaw;
                            window.currentPitch = pitch;
                            window.currentHfov = hfov;
                            select_room_marker(id,image,null);
                        },250);
                    }
                });
            }
        });
    }

    window.add_poi = function (id_room,image) {
        window.new_poi_id_room = id_room;
        window.new_poi_image = image;
        select_poi_style('icon');
        $('#modal_add_poi').modal('show');
    }

    window.select_poi_style = function (style_sel) {
        $('#dropdown_poi_style').html($('#btn_style_'+style_sel).html());
        $('#btn_new_poi_none i').addClass('fa-ban').removeClass('fa-heading').removeClass('fa-circle');
        $('#btn_new_poi_none span').html(window.backend_labels.none);
        $('#btn_new_poi_staging').hide();
        switch(style_sel) {
            case 'icon':
                $('#div_poi_select_content button').removeClass('hidden');
                $('#btn_new_poi_staging').show();
                window.embed_type_sel = '';
                break;
            case 'callout':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                $('#btn_new_poi_none i').removeClass('fa-ban').addClass('fa-heading');
                $('#btn_new_poi_none span').html(window.backend_labels.html);
                window.embed_type_sel = 'callout';
                break;
            case 'grouped':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                $('#btn_new_poi_none i').removeClass('fa-ban').addClass('fa-circle');
                $('#btn_new_poi_none span').html(window.backend_labels.multiple_poi);
                window.embed_type_sel = 'grouped';
                break;
            case 'embed_image':
                $('#div_poi_select_content button').removeClass('hidden');
                window.embed_type_sel = 'image';
                break;
            case 'embed_video':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                window.embed_type_sel = 'video';
                break;
            case 'embed_video_transparent':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                window.embed_type_sel = 'video_transparent';
                break;
            case 'embed_video_chroma':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                window.embed_type_sel = 'video_chroma';
                break;
            case 'embed_object3d':
                $('#div_poi_select_content button').removeClass('hidden');
                window.embed_type_sel = 'object3d';
                break;
            case 'embed_gallery':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                window.embed_type_sel = 'gallery';
                break;
            case 'embed_link':
                $('#div_poi_select_content button').addClass('hidden');
                $('#div_poi_select_content button').first().removeClass('hidden');
                window.embed_type_sel = 'link';
                break;
            case 'embed_text':
                $('#div_poi_select_content button').removeClass('hidden');
                window.embed_type_sel = 'text';
                break;
            case 'embed_html':
                $('#div_poi_select_content button').removeClass('hidden');
                window.embed_type_sel = 'html';
                break;
            case 'embed_selection':
                $('#div_poi_select_content button').removeClass('hidden');
                window.embed_type_sel = 'selection';
                break;
        }
    }

    window.select_poi_content_edit = function (content_sel) {
        $('#dropdown_poi_content_edit').html($('#btn_edit_content_' + content_sel).html());
        switch(content_sel) {
            case 'none':
                content_sel='';
                break;
        }
        window.content_sel = content_sel;
        if(window.content_current!=window.content_sel) {
            $('#btn_change_poi_content').removeClass('disabled');
        } else {
            $('#btn_change_poi_content').addClass('disabled');
        }
    }

    window.select_poi_style_edit = function (style_sel) {
        $('#dropdown_poi_style_edit').html($('#btn_edit_style_'+style_sel).html());
        $('#dropdown_poi_content_edit').removeClass('disabled');
        switch(style_sel) {
            case 'icon':
                window.embed_type_sel = '';
                break;
            case 'callout':
                $('#dropdown_poi_content_edit').addClass('disabled');
                select_poi_content_edit('none');
                $('#btn_change_poi_content').addClass('disabled');
                window.embed_type_sel = 'callout';
                break;
            case 'embed_image':
                window.embed_type_sel = 'image';
                break;
            case 'embed_video':
                $('#dropdown_poi_content_edit').addClass('disabled');
                select_poi_content_edit('none');
                $('#btn_change_poi_content').addClass('disabled');
                window.embed_type_sel = 'video';
                break;
            case 'embed_video_transparent':
                $('#dropdown_poi_content_edit').addClass('disabled');
                select_poi_content_edit('none');
                $('#btn_change_poi_content').addClass('disabled');
                window.embed_type_sel = 'video_transparent';
                break;
            case 'embed_video_chroma':
                $('#dropdown_poi_content_edit').addClass('disabled');
                select_poi_content_edit('none');
                $('#btn_change_poi_content').addClass('disabled');
                window.embed_type_sel = 'video_chroma';
                break;
            case 'embed_object3d':
                window.embed_type_sel = 'object3d';
                break;
            case 'embed_gallery':
                $('#dropdown_poi_content_edit').addClass('disabled');
                select_poi_content_edit('none');
                $('#btn_change_poi_content').addClass('disabled');
                window.embed_type_sel = 'gallery';
                break;
            case 'embed_link':
                $('#dropdown_poi_content_edit').addClass('disabled');
                select_poi_content_edit('none');
                $('#btn_change_poi_content').addClass('disabled');
                window.embed_type_sel = 'link';
                break;
            case 'embed_text':
                window.embed_type_sel = 'text';
                break;
            case 'embed_html':
                window.embed_type_sel = 'html';
                break;
            case 'embed_selection':
                window.embed_type_sel = 'selection';
                break;
        }
        if(window.embed_type_current!=window.embed_type_sel) {
            $('#btn_change_poi_embed_style').removeClass('disabled');
        } else {
            $('#btn_change_poi_embed_style').addClass('disabled');
        }
    }

    window.change_poi_embed_style = function() {
        var retVal = confirm(window.backend_labels.change_poi_style_msg);
        if( retVal == true ) {
            $('#btn_change_poi_embed_style').addClass('disabled');
            confirm_edit_poi(window.poi_id_edit,window.poi_index_edit);
            $.ajax({
                url: "ajax/change_poi_embed_style.php",
                type: "POST",
                data: {
                    id: window.poi_id_edit,
                    yaw: window.pois[window.poi_index_edit].yaw,
                    pitch: window.pois[window.poi_index_edit].pitch,
                    embed_type: window.embed_type_sel,
                    embed_type_current: embed_type_current
                },
                async: true,
                success: function (json) {
                    jQuery.each(window.rooms, function(index, room) {
                        var id = room.id;
                        var image = room.panorama_image;
                        if(id==window.pois[window.poi_index_edit].id_room) {
                            setTimeout(function () {
                                try {
                                    var yaw = parseFloat(window.viewer.getYaw());
                                    var pitch = parseFloat(window.viewer.getPitch());
                                    var hfov = parseFloat(window.viewer.getHfov());
                                } catch (e) {
                                    var yaw = 0;
                                    var pitch = 0;
                                    var hfov = 0;
                                }
                                window.currentYaw = yaw;
                                window.currentPitch = pitch;
                                window.currentHfov = hfov;
                                select_room_poi(id,image,null);
                            },250);
                        }
                    });
                }
            });
        }
    }

    window.change_poi_content = function() {
        var retVal = confirm(window.backend_labels.change_poi_style_msg);
        if( retVal == true ) {
            $('#btn_change_poi_content').addClass('disabled');
            confirm_edit_poi(window.poi_id_edit,window.poi_index_edit);
            $.ajax({
                url: "ajax/change_poi_content.php",
                type: "POST",
                data: {
                    id: window.poi_id_edit,
                    content_type: window.content_sel
                },
                async: true,
                success: function (json) {
                    jQuery.each(window.rooms, function(index, room) {
                        var id = room.id;
                        var image = room.panorama_image;
                        if(id==window.pois[window.poi_index_edit].id_room) {
                            setTimeout(function () {
                                try {
                                    var yaw = parseFloat(window.viewer.getYaw());
                                    var pitch = parseFloat(window.viewer.getPitch());
                                    var hfov = parseFloat(window.viewer.getHfov());
                                } catch (e) {
                                    var yaw = 0;
                                    var pitch = 0;
                                    var hfov = 0;
                                }
                                window.currentYaw = yaw;
                                window.currentPitch = pitch;
                                window.currentHfov = hfov;
                                select_room_poi(id,image,null);
                            },250);
                        }
                    });
                }
            });
        }
    }

    var poi_embed_ids = [];
    window.init_poi_embed = function(force=false) {
        window.sync_poi_embed_enabled = true;
        poi_embed_ids = [];
        $('.draggable_poi_embed').remove();
        $('.poi_embed').each(function () {
            if(!$(this).hasClass('hidden_p')) {
                var id = $(this).attr('data-id');
                poi_embed_ids.push(id);
                var initialized = $(this).attr('data-initialized');
                var transform3d = $(this).attr('data-transform3d');
                if((initialized==0 || force) && transform3d==1) {
                    $(this).attr('data-initialized',1);
                    poi_embed_make_transformable('.poi_embed_'+id, id, function(element, H) {});
                }
            } else {
                $(this).attr('data-initialized',0);
            }
        });
        adjust_poi_embed_helpers_all();
    }

    var marker_embed_ids = [];
    window.init_marker_embed = function(force=false) {
        window.sync_marker_embed_enabled = true;
        marker_embed_ids = [];
        $('.draggable_marker_embed').remove();
        $('.marker_embed').each(function () {
            if(!$(this).hasClass('hidden_p')) {
                var id = $(this).attr('data-id');
                marker_embed_ids.push(id);
                var initialized = $(this).attr('data-initialized');
                var transform3d = $(this).attr('data-transform3d');
                if((initialized==0 || force) && transform3d==1) {
                    $(this).attr('data-initialized',1);
                    marker_embed_make_transformable('.marker_embed_'+id, id, function(element, H) {});
                }
            } else {
                $(this).attr('data-initialized',0);
            }
        });
        adjust_marker_embed_helpers_all();
    }

    Math.getDistance = function( x1, y1, x2, y2 ) {
        var  xs = x2 - x1, ys = y2 - y1;
        xs *= xs;
        ys *= ys;
        return Math.sqrt( xs + ys );
    };

    window.adjust_poi_embed_helpers_all = function () {
        for(var i=0; i<poi_embed_ids.length;i++) {
            var id = poi_embed_ids[i];
            var initialized = $('.poi_embed_'+id).attr('data-initialized');
            var transform3d = $('.poi_embed_'+id).attr('data-transform3d');
            var type = $('.poi_embed_'+id).attr('data-type');
            if(transform3d==0) {
                $('.poi_embed_'+id).css({'top':0,'left':0});
                switch(type) {
                    case 'image':
                        $('.poi_embed_'+id+' img').css('opacity',1);
                        break;
                    case 'video':
                    case 'video_transparent':
                        if($('.poi_embed_'+id).css('visibility')=='visible') {
                            $('#video_embed_'+id).css('opacity',1);
                            $('.poi_embed_'+id+' video').css('opacity',1);
                        }
                        break;
                    case 'video_chroma':
                        if($('.poi_embed_'+id).css('visibility')=='visible') {
                            $('#canvas_chroma_'+id).css('opacity',1);
                        }
                        break;
                    case 'object3d':
                        $('.poi_embed_'+id+' div').css('opacity',1);
                        break;
                    case 'gallery':
                        $('.poi_embed_'+id+' .poi_embed_gallery').css('opacity',1);
                        break;
                    case 'link':
                        $('.poi_embed_'+id+' div').css('opacity',1);
                        $('.poi_embed_'+id+' iframe').css('opacity',1);
                        break;
                    case 'text':
                    case 'selection':
                    case 'html':
                        $('.poi_embed_'+id+' div').css('opacity',1);
                        break;
                }
            } else if(initialized==1) {
                var id = $('.poi_embed_'+id).attr('data-id');
                const pano_container_selector = ['.div_panorama_container', '#panorama', '#panorama_video'].find(s => $(s).length) || '';
                if (!pano_container_selector) return;
                const $pano_container = $(pano_container_selector);
                const containerOffset = $pano_container.offset();
                var pos_1 = ($('#poi_embded_helper_'+id+'_1').offset());
                pos_1.top=pos_1.top-containerOffset.top+8;
                pos_1.left=pos_1.left-containerOffset.left+8;
                $('#draggable_'+id+'_1').css({'top':pos_1.top+'px','left':pos_1.left+'px'});
                var pos_2 = ($('#poi_embded_helper_'+id+'_2').offset());
                pos_2.top=pos_2.top-containerOffset.top+8;
                pos_2.left=pos_2.left-containerOffset.left+8;
                $('#draggable_'+id+'_2').css({'top':pos_2.top+'px','left':pos_2.left+'px'});
                var pos_3 = ($('#poi_embded_helper_'+id+'_3').offset());
                pos_3.top=pos_3.top-containerOffset.top+8;
                pos_3.left=pos_3.left-containerOffset.left+8;
                $('#draggable_'+id+'_3').css({'top':pos_3.top+'px','left':pos_3.left+'px'});
                var pos_4 = ($('#poi_embded_helper_'+id+'_4').offset());
                pos_4.top=pos_4.top-containerOffset.top+8;
                pos_4.left=pos_4.left-containerOffset.left+8;
                $('#draggable_'+id+'_4').css({'top':pos_4.top+'px','left':pos_4.left+'px'});
                var count_offscreen = 0;
                if($('#poi_embded_helper_'+id+'_1').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if($('#poi_embded_helper_'+id+'_2').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if($('#poi_embded_helper_'+id+'_3').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if($('#poi_embded_helper_'+id+'_4').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if(pos_1.left!=8 && pos_1.top!=8 && pos_2.left!=8 && pos_2.top!=8 && pos_3.left!=8 && pos_3.top!=8 && pos_4.left!=8 && pos_4.top!=8) {
                    $('.poi_embed_'+id).removeClass('hidden');
                    if($('.poi_embed_'+id).css('visibility')=='visible' && count_offscreen<=2) {
                        $('.poi_embed_'+id).show();
                        poi_embed_apply_transform($('.poi_embed_'+id), poi_embed_originals_pos[id], [[pos_1.left, pos_1.top],[pos_2.left, pos_2.top],[pos_3.left, pos_3.top],[pos_4.left, pos_4.top]]);
                        var current_transform = $('.poi_embed_'+id).css('transform');
                        var pos1_top = $('#poi_embded_helper_'+id+'_1').position().top;
                        var pos2_top = $('#poi_embded_helper_'+id+'_2').position().top;
                        var pos3_top = $('#poi_embded_helper_'+id+'_3').position().top;
                        var pos4_top = $('#poi_embded_helper_'+id+'_4').position().top;
                        if(current_transform!="none" && pos1_top!=0 && pos2_top!=0 && pos3_top!=0 && pos4_top!=0) {
                            switch(type) {
                                case 'image':
                                    $('.poi_embed_'+id+' img').css('opacity',1);
                                    break;
                                case 'video':
                                case 'video_transparent':
                                    $('#video_embed_'+id).css('opacity',1);
                                    $('.poi_embed_'+id+' video').css('opacity',1);
                                    break;
                                case 'video_chroma':
                                    $('#canvas_chroma_'+id).css('opacity',1);
                                    break;
                                case 'object3d':
                                    $('.poi_embed_'+id+' div').css('opacity',1);
                                    break;
                                case 'gallery':
                                    $('.poi_embed_'+id+' .poi_embed_gallery').css('opacity',1);
                                    break;
                                case 'link':
                                    $('.poi_embed_'+id+' div').css('opacity',1);
                                    $('.poi_embed_'+id+' iframe').css('opacity',1);
                                    break;
                                case 'text':
                                case 'selection':
                                case 'html':
                                    $('.poi_embed_'+id+' div').css('opacity',1);
                                    break;
                            }
                            $('.poi_embed_'+id+' .empty_embed').css('opacity',0.5);
                        } else {
                            $('.poi_embed_'+id).addClass('hidden');
                            $('.poi_embed_'+id).hide();
                        }
                    } else {
                        $('.poi_embed_'+id).hide();
                        $('.poi_embed_'+id+' .empty_embed').css('opacity',0);
                        switch(type) {
                            case 'image':
                                $('.poi_embed_'+id+' img').css('opacity',0);
                                break;
                            case 'video':
                                $('#video_embed_'+id).css('opacity',0);
                                $('.poi_embed_'+id+' video').css('opacity',0);
                                break;
                            case 'gallery':
                                $('.poi_embed_'+id+' .poi_embed_gallery').css('opacity',0);
                                break;
                            case 'link':
                                $('.poi_embed_'+id+' div').css('opacity',0);
                                $('.poi_embed_'+id+' iframe').css('opacity',0);
                                break;
                            case 'text':
                            case 'selection':
                            case 'html':
                                $('.poi_embed_'+id+' div').css('opacity',0);
                                break;
                            case 'object3d':
                                $('.poi_embed_'+id+' div').css('opacity',0);
                                break;
                        }
                    }
                } else {
                    $('.poi_embed_'+id).addClass('hidden');
                    $('.poi_embed_'+id).hide();
                }
            }
        }
    }

    window.adjust_marker_embed_helpers_all = function () {
        for(var i=0; i<marker_embed_ids.length;i++) {
            var id = marker_embed_ids[i];
            var initialized = $('.marker_embed_'+id).attr('data-initialized');
            var transform3d = $('.marker_embed_'+id).attr('data-transform3d');
            var type = $('.marker_embed_'+id).attr('data-type');
            if(transform3d==0) {
                $('.marker_embed_'+id).css({'top':0,'left':0});
                switch(type) {
                    case 'selection':
                        $('.marker_embed_'+id+' div').css('opacity',1);
                        break;
                }
            } else if(initialized==1) {
                var id = $('.marker_embed_'+id).attr('data-id');
                const pano_container_selector = ['.div_panorama_container', '#panorama', '#panorama_video'].find(s => $(s).length) || '';
                if (!pano_container_selector) return;
                const $pano_container = $(pano_container_selector);
                const containerOffset = $pano_container.offset();
                var pos_1 = ($('#marker_embded_helper_'+id+'_1').offset());
                pos_1.top=pos_1.top-containerOffset.top+8;
                pos_1.left=pos_1.left-containerOffset.left+8;
                $('#draggable_'+id+'_1').css({'top':pos_1.top+'px','left':pos_1.left+'px'});
                var pos_2 = ($('#marker_embded_helper_'+id+'_2').offset());
                pos_2.top=pos_2.top-containerOffset.top+8;
                pos_2.left=pos_2.left-containerOffset.left+8;
                $('#draggable_'+id+'_2').css({'top':pos_2.top+'px','left':pos_2.left+'px'});
                var pos_3 = ($('#marker_embded_helper_'+id+'_3').offset());
                pos_3.top=pos_3.top-containerOffset.top+8;
                pos_3.left=pos_3.left-containerOffset.left+8;
                $('#draggable_'+id+'_3').css({'top':pos_3.top+'px','left':pos_3.left+'px'});
                var pos_4 = ($('#marker_embded_helper_'+id+'_4').offset());
                pos_4.top=pos_4.top-containerOffset.top+8;
                pos_4.left=pos_4.left-containerOffset.left+8;
                $('#draggable_'+id+'_4').css({'top':pos_4.top+'px','left':pos_4.left+'px'});
                var count_offscreen = 0;
                if($('#marker_embded_helper_'+id+'_1').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if($('#marker_embded_helper_'+id+'_2').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if($('#marker_embded_helper_'+id+'_3').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if($('#marker_embded_helper_'+id+'_4').attr('data-offscreen')==1) {
                    count_offscreen++;
                }
                if(pos_1.left!=8 && pos_1.top!=8 && pos_2.left!=8 && pos_2.top!=8 && pos_3.left!=8 && pos_3.top!=8 && pos_4.left!=8 && pos_4.top!=8) {
                    $('.marker_embed_'+id).removeClass('hidden');
                    if($('.marker_embed_'+id).css('visibility')=='visible' && count_offscreen<=2) {
                        $('.marker_embed_'+id).show();
                        poi_embed_apply_transform($('.marker_embed_'+id), marker_embed_originals_pos[id], [[pos_1.left, pos_1.top],[pos_2.left, pos_2.top],[pos_3.left, pos_3.top],[pos_4.left, pos_4.top]]);
                        var current_transform = $('.marker_embed_'+id).css('transform');
                        var pos1_top = $('#marker_embded_helper_'+id+'_1').position().top;
                        var pos2_top = $('#marker_embded_helper_'+id+'_2').position().top;
                        var pos3_top = $('#marker_embded_helper_'+id+'_3').position().top;
                        var pos4_top = $('#marker_embded_helper_'+id+'_4').position().top;
                        if(current_transform!="none" && pos1_top!=0 && pos2_top!=0 && pos3_top!=0 && pos4_top!=0) {
                            $('.marker_embed_'+id+' .empty_embed').css('opacity',0.5);
                            switch(type) {
                                case 'selection':
                                    $('.marker_embed_'+id+' div').css('opacity',1);
                                    break;
                            }
                        } else {
                            $('.marker_embed_'+id).addClass('hidden');
                            $('.marker_embed_'+id).hide();
                        }
                    } else {
                        $('.marker_embed_'+id).hide();
                        $('.marker_embed_'+id+' .empty_embed').css('opacity',0);
                        switch(type) {
                            case 'selection':
                                $('.marker_embed_'+id+' div').css('opacity',0);
                                break;
                        }
                    }
                } else {
                    $('.marker_embed_'+id).addClass('hidden');
                    $('.marker_embed_'+id).hide();
                }
            }
        }
    }

    var poi_embed_galleries = [];
    window.hotspot_embed = function(hotSpotDiv, args) {
        var id = args.id;
        var type = args.embed_type;
        if(args.transform3d==1) {
            var size = args.embed_size.split(",");
            var width = size[0]+'px';
            var height = size[1]+'px';
        } else {
            var width = '100%';
            var height = '100%';
        }
        hotSpotDiv.style.zIndex = args.zIndex;
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('poi_embed');
        hotSpotDiv.classList.add('poi_embed_'+id);
        hotSpotDiv.classList.add('hotspot_'+id);
        hotSpotDiv.setAttribute('data-id',id);
        hotSpotDiv.setAttribute('data-type',type);
        hotSpotDiv.setAttribute('data-transform3d',args.transform3d);
        hotSpotDiv.setAttribute('data-initialized',0);
        hotSpotDiv.setAttribute('visible_multiview_ids',args.visible_multiview_ids);
        if(args.embed_content!='') {
            switch(type) {
                case 'image':
                    var img = document.createElement('img');
                    img.setAttribute('draggable',false);
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content').is(':visible')) {
                            embed_content = $('#poi_embed_content').val();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                                if($(this).is(':visible')) {
                                    embed_content = $(this).val();
                                }
                            });
                        }
                    }
                    if(embed_content.startsWith("http") || embed_content.startsWith("//")) {
                        img.src = embed_content;
                    } else {
                        if(window.s3_enabled==1) {
                            img.src = window.s3_url+'viewer/'+embed_content;
                        } else {
                            img.src = '../viewer/'+embed_content;
                        }
                    }
                    if(args.transform3d==0) {
                        if(args.embed_size=='') {
                            var img_tmp = new Image();
                            img_tmp.onload = function () {
                                var height = img_tmp.height;
                                var width = img_tmp.width;
                                var ratio = width / height;
                                if(width>=height) {
                                    hotSpotDiv.style = "width:300px;height:" + (300/ratio) + "px;";
                                    args.embed_size = '300,'+(300/ratio);
                                } else {
                                    hotSpotDiv.style = "width:100px;height:" + (100/ratio) + "px;";
                                    args.embed_size = '100,'+(100/ratio);
                                }
                                fix_all_embeds_pos();
                            }
                            img_tmp.src = img.src;
                        } else {
                            var size = args.embed_size.split(",");
                            var width = size[0]+'px';
                            var height = size[1]+'px';
                            hotSpotDiv.style = "width:"+width+";height:"+height;
                        }
                    }
                    img.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    hotSpotDiv.appendChild(img);
                    fix_all_embeds_pos();
                    break;
                case 'text':
                    var div = document.createElement('div');
                    div.setAttribute('draggable',false);
                    div.classList.add('poi_embed_text');
                    hotSpotDiv.classList.add('no_outline');
                    var embed_content = args.embed_content.split(' border-width')[0];
                    if(window.is_editing) {
                        if($('#poi_embed_content_html').is(':visible')) {
                            embed_content = window.poi_embed_content_html_editor.root.innerHTML;
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content_html"]').each(function() {
                                if($(this).is(':visible')) {
                                    var lang = $(this).attr('data-lang');
                                    embed_content = window.poi_embed_content_html_editor_lang[lang].root.innerHTML;
                                }
                            });
                        }
                    }
                    var style = 'border-width'+args.embed_content.split(' border-width')[1];
                    div.innerHTML = embed_content;
                    var bg_color = args.background;
                    var color = args.color;
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:"+bg_color+";border-color:"+color+";border-width:2px;"+style;
                    hotSpotDiv.appendChild(div);
                    break;
                case 'html':
                    var div = document.createElement('div');
                    div.setAttribute('draggable',false);
                    div.classList.add('poi_embed_html');
                    hotSpotDiv.classList.add('no_outline');
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content_html_sc').is(':visible')) {
                            embed_content = window.poi_embed_content_html_sc.getValue();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content_html_sc"]').each(function() {
                                if($(this).is(':visible')) {
                                    var lang = $(this).attr('data-lang');
                                    embed_content = window.poi_embed_content_html_sc_lang[lang].getValue();
                                }
                            });
                        }
                    }
                    div.innerHTML = embed_content;
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    hotSpotDiv.appendChild(div);
                    break;
                case 'selection':
                    var div = document.createElement('div');
                    div.setAttribute('draggable',false);
                    div.classList.add('poi_embed_selection');
                    hotSpotDiv.classList.add('no_outline');
                    var bg_color = args.background;
                    var color = args.color;
                    if(args.embed_params!='') {
                        div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:transparent;border-color:rgba(255,255,255,0.4);";
                    } else {
                        div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:"+bg_color+";border-color:"+color+";"+args.embed_content;
                    }
                    var canvas = document.createElement('canvas');
                    canvas.id = 'canvas_selection_'+args.id;
                    canvas.width = width.replace('px','');
                    canvas.height = height.replace('px','');
                    div.appendChild(canvas);
                    hotSpotDiv.appendChild(div);
                    if(args.embed_params!='') {
                        var canvas = document.getElementById('canvas_selection_'+id);
                        var border = args.embed_content.replace('border-width:','').replace('px;','');
                        try {
                            var points = JSON.parse(args.embed_params);
                            draw_polygon(canvas.getContext("2d"),points,border,bg_color,color);
                        } catch (e) {}
                    }
                    break;
                case 'gallery':
                    var div = document.createElement('div');
                    div.classList.add('glide');
                    div.classList.add('poi_embed_gallery');
                    div.classList.add('poi_embed_gallery_'+args.id);
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    args.embed_content = args.embed_content.substring(args.embed_content.lastIndexOf("/") + 1);
                    if(window.s3_enabled==1) {
                        var image_url = window.s3_url+'viewer/gallery/'+args.embed_content;
                    } else {
                        var image_url = '../viewer/gallery/'+args.embed_content;
                    }
                    var html = '<div class="glide__track" data-glide-el="track"><ul class="glide__slides">';
                    html += '<li style="height:'+height+'px" class="glide__slide"><img style="object-fit: contain;width: 100%;height: 100%" src="'+image_url+'" /></li>';
                    html += '</ul>' +
                        '<div class="glide__arrows" data-glide-el="controls">' +
                        '    <i class="glide__arrow glide__arrow--left fas fa-chevron-left" data-glide-dir="<"></i>' +
                        '    <i class="glide__arrow glide__arrow--right fas fa-chevron-right" data-glide-dir=">"></i>' +
                        '  </div>' +
                        '</div>';
                    div.innerHTML=html;
                    hotSpotDiv.appendChild(div);
                    poi_embed_galleries[args.id] = new Glide('.poi_embed_gallery_'+args.id,{
                        type: 'carousel',
                        startAt: 0,
                        perView: 1
                    });
                    poi_embed_galleries[args.id].mount();
                    break;
                case 'video_chroma':
                    var video = document.createElement('video');
                    video.setAttribute('draggable',false);
                    video.id = "video_embed_"+id;
                    video.classList.add('noselect');
                    video.crossOrigin = 'anonymous';
                    video.preload = 'auto';
                    video.muted = true;
                    video.volume = 0;
                    video.loop = true;
                    video.setAttribute('playsinline', '');
                    video.setAttribute('webkit-playsinline','');
                    video.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content').is(':visible')) {
                            embed_content = $('#poi_embed_content').val();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                                if($(this).is(':visible')) {
                                    embed_content = $(this).val();
                                }
                            });
                        }
                    }
                    if(window.s3_enabled==1) {
                        video.src = window.s3_url+'viewer/'+embed_content+'#t=2';
                    } else {
                        video.src = '../viewer/'+embed_content+'#t=2';
                    }
                    window.video_chroma = video;
                    var canvas = document.createElement('canvas');
                    canvas.id = "canvas_chroma_"+id;
                    canvas.setAttribute('width', width.replace('px',''));
                    canvas.setAttribute('height', height.replace('px',''));
                    canvas.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;position:absolute;top:0;left:0;";
                    hotSpotDiv.appendChild(canvas);
                    var ctx_chroma = canvas.getContext('2d');
                    window.ctx_chroma = ctx_chroma;
                    var c_chroma_tmp = document.createElement('canvas');
                    c_chroma_tmp.id = 'c_chroma_tmp_'+id;
                    c_chroma_tmp.setAttribute('width', width.replace('px',''));
                    c_chroma_tmp.setAttribute('height', height.replace('px',''));
                    var ctx_chroma_tmp = c_chroma_tmp.getContext('2d');
                    window.ctx_chroma_tmp = ctx_chroma_tmp;
                    window.width_chroma = width.replace('px','');
                    window.height_chroma = height.replace('px','');
                    video.addEventListener('loadeddata', function() {
                        var params = args.params;
                        if(window.is_editing) {
                            if(window.selected_language!='' && window.selected_language!=window.default_language) {
                                var color = $('.input_lang[data-target-id="chroma_color"][data-lang="'+window.selected_language+'"]').val();
                                var chroma_tolerance = $('.input_lang[data-target-id="chroma_tolerance"][data-lang="'+window.selected_language+'"]').val();
                            } else {
                                var color = $('#chroma_color').val();
                                var chroma_tolerance = $('#chroma_tolerance').val();
                            }
                            var chroma_color = color.toString().replace("rgb(","").replace(")","");
                            params = chroma_color+','+chroma_tolerance;
                        }
                        remove_background_video_chroma(video,ctx_chroma_tmp,ctx_chroma,width.replace('px',''),height.replace('px',''),params,true);
                        $('#btn_background_removal').removeClass('disabled');
                    });
                    video.addEventListener('play', function() {
                        var params = args.params;
                        if(window.is_editing) {
                            if (window.selected_language!='' && window.selected_language != window.default_language) {
                                var color = $('.input_lang[data-target-id="chroma_color"][data-lang="' + window.selected_language + '"]').val();
                                var chroma_tolerance = $('.input_lang[data-target-id="chroma_tolerance"][data-lang="' + window.selected_language + '"]').val();
                            } else {
                                var color = $('#chroma_color').val();
                                var chroma_tolerance = $('#chroma_tolerance').val();
                            }
                            var chroma_color = color.toString().replace("rgb(", "").replace(")", "");
                            params = chroma_color + ',' + chroma_tolerance;
                        }
                        remove_background_video_chroma(video, ctx_chroma_tmp, ctx_chroma, width.replace('px', ''), height.replace('px', ''),params,true);
                    });
                    hotSpotDiv.appendChild(video);
                    video.load();
                    break;
                case 'video_transparent':
                    var video = document.createElement('video');
                    video.setAttribute('draggable',false);
                    video.id = "video_embed_"+id;
                    video.setAttribute("preload", "auto");
                    video.setAttribute('playsinline', '');
                    video.setAttribute('webkit-playsinline','');
                    video.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content').is(':visible')) {
                            embed_content = $('#poi_embed_content').val();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                                if($(this).is(':visible')) {
                                    embed_content = $(this).val();
                                }
                            });
                        }
                    }
                    var array_videos = embed_content.split(",");
                    var mov_source = '', webm_source = '';
                    jQuery.each(array_videos, function(index_s, video_s) {
                        if(video_s.split('.').pop().toLowerCase()=='mov') {
                            mov_source = video_s;
                        }
                        if(video_s.split('.').pop().toLowerCase()=='webm') {
                            webm_source = video_s;
                        }
                    });
                    if(mov_source!='' && webm_source!='') {
                        if(supportsHEVCAlpha()) {
                            if(window.s3_enabled==1) {
                                video.src = window.s3_url+'viewer/'+mov_source+'#t=2';
                            } else {
                                video.src = '../viewer/'+mov_source+'#t=2';
                            }
                        } else {
                            if(window.s3_enabled==1) {
                                video.src = window.s3_url+'viewer/'+webm_source+'#t=2';
                            } else {
                                video.src = '../viewer/'+webm_source+'#t=2';
                            }
                        }
                    } else if(mov_source!='') {
                        if(window.s3_enabled==1) {
                            video.src = window.s3_url+'viewer/'+mov_source+'#t=2';
                        } else {
                            video.src = '../viewer/'+mov_source+'#t=2';
                        }
                    } else if(webm_source!='') {
                        if(window.s3_enabled==1) {
                            video.src = window.s3_url+'viewer/'+webm_source+'#t=2';
                        } else {
                            video.src = '../viewer/'+webm_source+'#t=2';
                        }
                    }
                    hotSpotDiv.appendChild(video);
                    break;
                case 'video':
                    var video = document.createElement('video');
                    video.setAttribute('draggable',false);
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content').is(':visible')) {
                            embed_content = $('#poi_embed_content').val();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                                if($(this).is(':visible')) {
                                    embed_content = $(this).val();
                                }
                            });
                        }
                    }
                    video.id = "video_embed_"+id;
                    video.classList.add('video-js');
                    video.classList.add('vjs-default-skin');
                    video.classList.add('vjs-big-play-centered');
                    video.classList.add('vjs-fill');
                    video.setAttribute("preload", "metadata");
                    video.setAttribute('playsinline', '');
                    video.setAttribute('webkit-playsinline','');
                    video.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    if(embed_content.includes("youtu")) {
                        if(embed_content.includes("/shorts/")) {
                            embed_content = convertYouTubeShortsToWatchUrl(embed_content);
                        }
                        video.setAttribute('data-setup','{ "techOrder":["youtube"],"sources":[{"type":"video/youtube","src":"'+embed_content+'"}],"youtube":{"iv_load_policy":3,"loop":1,"playsinline":1,"showinfo":0,"fs":0,"disablekb":1,"autoplay":0}}');
                    } else {
                        var source = document.createElement('source');
                        if(embed_content.startsWith("http") || embed_content.startsWith("//")) {
                            source.src = embed_content+'#t=2';
                        } else {
                            if(window.s3_enabled==1) {
                                source.src = window.s3_url+'viewer/'+embed_content+'#t=2';
                            } else {
                                source.src = '../viewer/'+embed_content+'#t=2';
                            }
                        }
                        source.type = 'video/mp4';
                        video.appendChild(source);
                    }
                    if(args.transform3d==0) {
                        if(args.embed_size=='') {
                            video.addEventListener( "loadedmetadata", function (e) {
                                var width = this.videoWidth, height = this.videoHeight;
                                var ratio = width / height;
                                if(width>=height) {
                                    hotSpotDiv.style = "width:300px;height:" + (300/ratio) + "px;";
                                    args.embed_size = '300,'+(300/ratio);
                                } else {
                                    hotSpotDiv.style = "width:200px;height:" + (200/ratio) + "px;";
                                    args.embed_size = '200,'+(200/ratio);
                                }
                                fix_all_embeds_pos();
                            }, false );
                        } else {
                            var size = args.embed_size.split(",");
                            var width = size[0]+'px';
                            var height = size[1]+'px';
                            hotSpotDiv.style = "width:"+width+";height:"+height;
                        }
                    }
                    hotSpotDiv.appendChild(video);
                    fix_all_embeds_pos();
                    try {
                        if (typeof video_embeds[id] !== 'undefined') {
                            video_embeds[id].dispose();
                        }
                    } catch (e) {}
                    video_embeds[id] = videojs('video_embed_'+id, {controls: false}, function() {
                        $('.poi_embed_'+id+' video').css({'width':'100%','height':'100%'});
                    });
                    break;
                case 'link':
                    var div = document.createElement('div');
                    div.classList.add('poi_embed_link');
                    div.classList.add('poi_embed_link_'+args.id);
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content').is(':visible')) {
                            embed_content = $('#poi_embed_content').val();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                                if($(this).is(':visible')) {
                                    embed_content = $(this).val();
                                }
                            });
                        }
                    }
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    var html = '<iframe frameborder="0" marginheight="0" marginwidth="0" style="border:none;" width="'+width+'px" height="'+height+'px" src="'+embed_content+'"></iframe>';
                    div.innerHTML=html;
                    hotSpotDiv.appendChild(div);
                    break;
                case 'object3d':
                    var div = document.createElement('div');
                    div.classList.add('poi_embed_object3d');
                    div.classList.add('poi_embed_object3d_'+args.id);
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                    if(args.embed_params!='') {
                        var tmp = args.embed_params.split(",");
                        if(tmp[0]!==undefined) {
                            var camera_coords = tmp[0];
                            var coords_part = camera_coords.split(" ");
                            camera_coords = coords_part[0]+" "+coords_part[1]+" 100%";
                        } else {
                            var camera_coords = "";
                        }
                        if(tmp[2]!==undefined) {
                            var exposure = tmp[2];
                        } else {
                            var exposure = 1;
                        }
                        if(tmp[3]!==undefined) {
                            var environment = tmp[3];
                        } else {
                            var environment = 'legacy';
                        }
                        if(tmp[4]!==undefined) {
                            var shadow_intensity = tmp[4];
                        } else {
                            var shadow_intensity = 1;
                        }
                        if(tmp[5]!==undefined) {
                            var shadow_softness = tmp[5];
                        } else {
                            var shadow_softness = 0.5;
                        }
                        if(tmp[6]!==undefined) {
                            var zoom_deg = (180-tmp[6])+'deg';
                        } else {
                            var zoom_deg = 'auto';
                        }
                        if(tmp[7]!==undefined) {
                            var animation = tmp[7];
                            if(animation=='none') {
                                animation = '';
                                var autoplay = '';
                            } else {
                                var autoplay = 'autoplay';
                            }
                        } else {
                            var animation = '';
                            var autoplay = '';
                        }
                    } else {
                        var camera_coords = "";
                        var exposure = 1;
                        var environment = 'legacy';
                        var shadow_intensity = 1;
                        var shadow_softness = 0.5;
                        var zoom_deg = 'auto';
                        var animation = '';
                        var autoplay = '';
                    }
                    var embed_content = args.embed_content;
                    if(window.is_editing) {
                        if($('#poi_embed_content').is(':visible')) {
                            embed_content = $('#poi_embed_content').val();
                        } else {
                            $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                                if($(this).is(':visible')) {
                                    embed_content = $(this).val();
                                }
                            });
                        }
                    }
                    if(window.s3_enabled==1) {
                        var glb_url = window.s3_url+'viewer/'+embed_content;
                    } else {
                        var glb_url = '../viewer/'+embed_content;
                    }
                    if(environment=='panorama') {
                        if(window.s3_enabled==1) {
                            environment = window.s3_url+'viewer/panoramas/lowres/'+window.panorama_image+'?s3=1';
                        } else {
                            environment = '../viewer/panoramas/lowres/'+window.panorama_image;
                        }
                    }
                    if(window.is_editing) {
                        var html = '<model-viewer '+autoplay+' animation-name="'+animation+'" min-field-of-view="'+zoom_deg+'" max-field-of-view="'+zoom_deg+'" disable-tap disable-pan disable-zoom id="object3d_'+args.id+'" src="'+glb_url+'" alt="" exposure="'+exposure+'" environment-image="'+environment+'" shadow-intensity="'+shadow_intensity+'" shadow-softness="'+shadow_softness+'" bounds="tight" camera-orbit="'+camera_coords+'" camera-controls></model-viewer>';
                    } else {
                        var html = '<model-viewer '+autoplay+' animation-name="'+animation+'" min-field-of-view="'+zoom_deg+'" max-field-of-view="'+zoom_deg+'" disable-tap disable-pan disable-zoom id="object3d_'+args.id+'" src="'+glb_url+'" alt="" exposure="'+exposure+'" environment-image="'+environment+'" shadow-intensity="'+shadow_intensity+'" shadow-softness="'+shadow_softness+'" bounds="tight" interaction-prompt="none" camera-orbit="'+camera_coords+'"></model-viewer>';
                    }
                    div.innerHTML=html;
                    hotSpotDiv.appendChild(div);
                    var modelViewer = document.querySelector("model-viewer#object3d_"+args.id);
                    modelViewer.addEventListener("camera-change", (ev) => {
                        var camera_orbit = modelViewer.getCameraOrbit().toString();
                        if(args.embed_params!='') {
                            var tmp = args.embed_params.split(",");
                            if(tmp[1]!==undefined) {
                                var interaction = tmp[1];
                            } else {
                                var interaction = 0;
                            }
                            if(tmp[2]!==undefined) {
                                var exposure = tmp[2];
                            } else {
                                var exposure = 1;
                            }
                            if(tmp[3]!==undefined) {
                                var environment = tmp[3];
                            } else {
                                var environment = 'legacy';
                            }
                            if(tmp[4]!==undefined) {
                                var shadow_intensity = tmp[4];
                            } else {
                                var shadow_intensity = 1;
                            }
                            if(tmp[5]!==undefined) {
                                var shadow_softness = tmp[5];
                            } else {
                                var shadow_softness = 0.5;
                            }
                            if(tmp[6]!==undefined) {
                                var zoom_deg = tmp[6];
                            } else {
                                var zoom_deg = 'auto';
                            }
                            if(tmp[7]!==undefined) {
                                var animation = tmp[7];
                            } else {
                                var animation = 'none';
                            }
                        } else {
                            var interaction = 0;
                            var exposure = 1;
                            var environment = 'legacy';
                            var shadow_intensity = 1;
                            var shadow_softness = 0.5;
                            var zoom_deg = 'auto';
                            var animation = 'none';
                        }
                        args.embed_params = camera_orbit+","+interaction+","+exposure+","+environment+","+shadow_intensity+","+shadow_softness+','+zoom_deg+','+animation;
                    });
                    break;
            }
        } else {
            var div = document.createElement('div');
            div.setAttribute('draggable', false);
            div.classList.add('empty_embed');
            div.style = "width:" + width + ";height:" + height + ";margin: 0 auto;vertical-align:middle;background-color:rgba(255,255,255,0.6);opacity:0;";
            hotSpotDiv.appendChild(div);
        }
    }

    function convertYouTubeShortsToWatchUrl(url) {
        try {
            const parsed = new URL(url);
            const host = parsed.hostname;
            const isYouTube = /(^|\.)youtube\.[a-z.]+$/.test(host);
            const isYoutuBe = /^youtu\.be$/.test(host);
            if (isYouTube) {
                if (parsed.pathname.startsWith("/shorts/")) {
                    const videoId = parsed.pathname.split("/")[2];
                    return `https://www.youtube.com/watch?v=${videoId}`;
                }
                if (parsed.pathname === "/watch" && parsed.searchParams.has("v")) {
                    return url;
                }
            }
            if (isYoutuBe) {
                const videoId = parsed.pathname.slice(1);
                if (videoId) {
                    return `https://www.youtube.com/watch?v=${videoId}`;
                }
            }
            return url;
        } catch (e) {
            return url;
        }
    }

    window.remove_background_video_chroma = function(video_chroma,ctx_chroma_tmp,ctx_chroma,width,height,params,force=false) {
        if (!force && (video_chroma.paused || video_chroma.ended)) { return; }
        if(!force) {
            if(window.selected_language!='') {
                if (window.selected_language != window.default_language) {
                    var color = $('.input_lang[data-target-id="chroma_color"][data-lang="' + window.selected_language + '"]').val();
                    var chroma_tolerance = $('.input_lang[data-target-id="chroma_tolerance"][data-lang="' + window.selected_language + '"]').val();
                } else {
                    var color = $('#chroma_color').val();
                    var chroma_tolerance = $('#chroma_tolerance').val();
                }
                var chroma_color = color.toString().replace("rgb(", "").replace(")", "");
                params = chroma_color + ',' + chroma_tolerance;
            } else {
                if(params==null) {
                    if(poi_index_edit==null) return;
                    params=window.pois[poi_index_edit].params;
                }
            }
        } else {
            if(params==null) {
                if(poi_index_edit==null) return;
                params=window.pois[poi_index_edit].params;
            }
        }
        ctx_chroma_tmp.drawImage(video_chroma, 0, 0, width , height );
        let frame = ctx_chroma_tmp.getImageData(0, 0, width , height );
        var params_array = params.split(",");
        var bg_r = parseInt(params_array[0]);
        var bg_g = parseInt(params_array[1]);
        var bg_b = parseInt(params_array[2]);
        var t = parseInt(params_array[3]);
        for (let i = 0; i < frame.data.length /4; i++) {
            let r = frame.data[i * 4 + 0];
            let g = frame.data[i * 4 + 1];
            let b = frame.data[i * 4 + 2];
            if (r > (bg_r-t) && r < (bg_r+t) && g > (bg_g-t) && g < (bg_g+t) && b > (bg_b-t) && b < (bg_b+t)) {
                frame.data[i * 4 + 3] = 0;
            }
        }
        ctx_chroma.putImageData(frame, 0, 0);
        if(!force) setTimeout(function () {
            remove_background_video_chroma(video_chroma,ctx_chroma_tmp,ctx_chroma,width,height,params,false);
        }, 0);
    }

    function hotspot_embed_m(hotSpotDiv, args) {
        var id = args.id;
        var type = args.embed_type;
        var size = args.embed_size.split(",");
        var width = size[0];
        var height = size[1];
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('marker_embed');
        hotSpotDiv.classList.add('marker_embed_'+id);
        hotSpotDiv.classList.add('hotspot_'+id);
        hotSpotDiv.style.zIndex = args.zIndex;
        hotSpotDiv.setAttribute('data-id',id);
        hotSpotDiv.setAttribute('data-type',type);
        hotSpotDiv.setAttribute('data-transform3d',args.transform3d);
        hotSpotDiv.setAttribute('data-initialized',0);
        hotSpotDiv.setAttribute('visible_multiview_ids',args.visible_multiview_ids);
        if(args.embed_content!='') {
            switch(type) {
                case 'selection':
                    var div = document.createElement('div');
                    div.setAttribute('draggable', false);
                    div.classList.add('marker_embed_selection');
                    hotSpotDiv.classList.add('no_outline');
                    var bg_color = args.background;
                    var color = args.color;
                    if(args.embed_params!='') {
                        div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:transparent;border-color:rgba(255,255,255,0.4);";
                    } else {
                        div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:"+bg_color+";border-color:"+color+";"+args.embed_content;
                    }
                    var canvas = document.createElement('canvas');
                    canvas.id = 'canvas_selection_'+args.id;
                    canvas.width = width.replace('px','');
                    canvas.height = height.replace('px','');
                    div.appendChild(canvas);
                    hotSpotDiv.appendChild(div);
                    if(args.embed_params!='') {
                        var canvas = document.getElementById('canvas_selection_'+id);
                        var border = args.embed_content.replace('border-width:','').replace('px;','');
                        try {
                            var points = JSON.parse(args.embed_params);
                            draw_polygon(canvas.getContext("2d"),points,border,bg_color,color);
                        } catch (e) {}
                    }
                    hotSpotDiv.appendChild(div);
                    break;
            }
        } else {
            var div = document.createElement('div');
            div.setAttribute('draggable',false);
            div.classList.add('empty_embed');
            div.style = "width:"+width+"px;height:"+height+"px;margin: 0 auto;vertical-align:middle;background-color:rgba(255,255,255,0.6);;opacity:0;";
            hotSpotDiv.appendChild(div);
        }
    }

    window.supportsHEVCAlpha = function() {
        const navigator = window.navigator;
        const ua = navigator.userAgent.toLowerCase();
        const hasMediaCapabilities = !!(navigator.mediaCapabilities && navigator.mediaCapabilities.decodingInfo);
        const isiOS = /iPad|iPhone|iPod/.test(navigator.platform) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
        const isSafariOriOSChrome = isiOS || ((ua.indexOf('safari') != -1) && (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1)));
        return isSafariOriOSChrome && hasMediaCapabilities;
    }

    function hotspot_embed_helper_m(hotSpotDiv, args) {
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('marker_embded_helper');
        hotSpotDiv.setAttribute('id','marker_embded_helper_'+args[0]+'_'+args[1]);
        var icon = document.createElement('i');
        icon.classList.add('fas');
        icon.classList.add('fa-circle');
        icon.style = 'font-size:16px;cursor:pointer;color:red;opacity:0.6;';
        hotSpotDiv.append(icon);
    }

    window.hotspot_embed_helper = function(hotSpotDiv, args) {
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('poi_embded_helper');
        hotSpotDiv.setAttribute('id','poi_embded_helper_'+args[0]+'_'+args[1]);
        var icon = document.createElement('i');
        icon.classList.add('fas');
        icon.classList.add('fa-circle');
        icon.style = 'font-size:16px;cursor:pointer;color:red;opacity:0.6;';
        hotSpotDiv.append(icon);
    }

    function hotspot_embed_move(hotSpotDiv, args) {
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('poi_embded_move');
        hotSpotDiv.setAttribute('id','poi_embded_move_'+args);
        var icon = document.createElement('i');
        icon.classList.add('fas');
        icon.classList.add('fa-arrows-alt');
        icon.style = 'font-size:16px;cursor:pointer;color:red;background-color:white;border-radius:50%;padding:5px;opacity:0.6;';
        hotSpotDiv.append(icon);
    }

    function hotspot_north_helper(hotSpotDiv, args) {
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        if(window.set_north) {
            hotSpotDiv.style.opacity = 1;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.opacity = 0;
            hotSpotDiv.style.pointerEvents = 'none';
        }
        var div = document.createElement('div');
        div.style = 'cursor:pointer;background-color:rgb(230,120,0);border-radius:50%;opacity:0.9;width:70px;height:70px;text-align:center;';
        var icon = document.createElement('i');
        icon.classList.add('north_icon_up');
        icon.classList.add('fas');
        icon.classList.add('fa-caret-up');
        icon.style = 'font-size:26px;color:white;margin-top:2px;';
        div.append(icon);
        var br = document.createElement('br');
        div.append(br);
        var icon = document.createElement('i');
        icon.classList.add('fas');
        icon.classList.add('fa-n');
        icon.style = 'font-size:30px;color:white;';
        div.append(icon);
        hotSpotDiv.append(div);
    }

    function hotspot_embed_move_m(hotSpotDiv, args) {
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('marker_embded_move');
        hotSpotDiv.setAttribute('id','marker_embded_move_'+args);
        var icon = document.createElement('i');
        icon.classList.add('fas');
        icon.classList.add('fa-arrows-alt');
        icon.style = 'font-size:16px;cursor:pointer;color:red;background-color:white;border-radius:50%;padding:5px;opacity:0.6;';
        hotSpotDiv.append(icon);
    }

    function drag_marker_move(event, args) {
        var index = args;
        var coords = window.viewer.mouseEventToCoords(event);
        var yaw = parseFloat(coords[1]);
        var pitch = parseFloat(coords[0]);
        window.markers[index].yaw = yaw;
        window.markers[index].pitch = pitch;
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                $('#confirm_move').css({'height':'34px','overflow':'hidden'});
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#confirm_move').css({'height':'auto','overflow':'unset'});
                break;
        }
        pauseEvent(event);
    }

    function drag_measure_move(event, args) {
        var index = args.index;
        var dir = args.dir;
        var coords = window.viewer.mouseEventToCoords(event);
        var yaw = parseFloat(coords[1]);
        var pitch = parseFloat(coords[0]);
        switch(dir) {
            case 'start':
                window.measures[index].yaw_start = yaw;
                window.measures[index].pitch_start = pitch;
                break;
            case 'end':
                window.measures[index].yaw_end = yaw;
                window.measures[index].pitch_end = pitch;
                break;
        }
        adjust_measurements(false);
        pauseEvent(event);
    }

    function drag_poi_move(event, args) {
        var index = args;
        var coords = window.viewer.mouseEventToCoords(event);
        var yaw = parseFloat(coords[1]);
        var pitch = parseFloat(coords[0]);
        window.pois[index].yaw = yaw;
        window.pois[index].pitch = pitch;
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                $('#confirm_move').css({'height':'34px','overflow':'hidden'});
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#confirm_move').css({'height':'auto','overflow':'unset'});
                break;
        }
        pauseEvent(event);
    }

    function pauseEvent(e){
        if(e.stopPropagation) e.stopPropagation();
        if(e.preventDefault) e.preventDefault();
        e.cancelBubble=true;
        e.returnValue=false;
        return false;
    }

    function drag_north_helper(event, args) {
        var id_room = args;
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#north_val').html('<i class="fas fa-circle-notch fa-spin"></i>');
                var coords = window.viewer.mouseEventToCoords(event);
                var yaw_north = parseInt(coords[1]);
                if(yaw_north<0) {
                    var northOffset = Math.abs(yaw_north);
                } else {
                    var northOffset =  360 - yaw_north;
                }
                if(northOffset==360) northOffset=0;
                $.ajax({
                    url: "ajax/save_room_north.php",
                    type: "POST",
                    data: {
                        id: id_room,
                        northOffset: northOffset
                    },
                    async: true,
                    success: function (json) {
                        $('.north-control').addClass('saved');
                        setTimeout(function() {
                            $('.north-control').removeClass('saved');
                            $('#north_val').html(parseInt(northOffset)+'°');
                            window.viewer.setNorthOffset(northOffset);
                            window.northOffset_sel = yaw_north;
                        },1000);
                    },
                    error: function() {
                        $('#north_val').html(parseInt(northOffset)+'°');
                    }
                });
                break;
        }
    }

    var interval_drag_helper;
    function drag_embed_helper(event, args) {
        var poi = args[0];
        var id = poi.id;
        var index = args[1];
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                $('#confirm_move').css({'height':'34px','overflow':'hidden'});
                $('.poi_embed_'+id).css({'outline':'1px dashed red','opacity':0.6});
                window.viewer.setUpdate(true);
                interval_drag_helper = setInterval(function () {
                    adjust_poi_embed_helpers_all();
                },10);
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#confirm_move').css({'height':'auto','overflow':'unset'});
                $('.poi_embed_'+id).css({'outline':'none','opacity':1.0});
                window.viewer.setUpdate(false);
                clearInterval(interval_drag_helper);
                var coords = window.viewer.mouseEventToCoords(event);
                var yaw = parseFloat(coords[1]);
                var pitch = parseFloat(coords[0]);
                var poi_embed_helpers = poi.embed_coords.split("|");
                poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
                poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
                poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
                poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
                poi_embed_helpers[index][0] = pitch;
                poi_embed_helpers[index][1] = yaw;
                var embed_coords = poi_embed_helpers[0][0]+","+poi_embed_helpers[0][1]+"|"+poi_embed_helpers[1][0]+","+poi_embed_helpers[1][1]+"|"+poi_embed_helpers[2][0]+","+poi_embed_helpers[2][1]+"|"+poi_embed_helpers[3][0]+","+poi_embed_helpers[3][1];
                poi.embed_coords = embed_coords;
                var pos_1 = ($('#poi_embded_helper_'+id+'_1').offset());
                var pos_2 = ($('#poi_embded_helper_'+id+'_2').offset());
                var pos_3 = ($('#poi_embded_helper_'+id+'_3').offset());
                var pos_4 = ($('#poi_embded_helper_'+id+'_4').offset());
                var center_left = ((parseFloat(pos_1.left) + parseFloat(pos_2.left) + parseFloat(pos_3.left) + parseFloat(pos_4.left)) / 4) + 8;
                var center_top = ((parseFloat(pos_1.top) + parseFloat(pos_2.top) + parseFloat(pos_3.top) + parseFloat(pos_4.top)) / 4) + 8;
                var event_center = [];
                event_center.clientX = center_left;
                event_center.clientY = center_top;
                var coords_center = window.viewer.mouseEventToCoords(event_center);
                poi.yaw = parseFloat(coords_center[1]);
                poi.pitch = parseFloat(coords_center[0]);
                var w = Math.getDistance(pos_1.left,pos_1.top,pos_3.left,pos_3.top);
                var h = Math.getDistance(pos_1.left,pos_1.top,pos_2.left,pos_2.top);
                poi.embed_size = w+","+h;
                jQuery.each(window.pois, function(index, poi_a) {
                    if(id==poi_a.id) {
                        window.pois[index].yaw = poi.yaw;
                        window.pois[index].pitch = poi.pitch;
                        window.pois[index].embed_coords = poi.embed_coords;
                        window.pois[index].embed_size = poi.embed_size;
                        switch(window.pois[index].embed_type) {
                            case 'gallery':
                                try {
                                    poi_embed_galleries[id].destroy();
                                } catch (e) {}
                                render_poi(id,index);
                                $('#poi_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
                                break;
                            case 'link':
                            case 'text':
                            case 'selection':
                            case 'object3d':
                                render_poi(id,index);
                                $('#poi_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
                                $('#poi_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
                                break;
                            default:
                                window.viewer.removeHotSpot("p"+id.toString()+"_move");
                                window.viewer.addHotSpot({
                                    "id": "p"+window.pois[index].id+"_move",
                                    "type": 'pointer',
                                    "object": "poi_embed_helper",
                                    "transform3d": false,
                                    "pitch": parseFloat(window.pois[index].pitch),
                                    "yaw": parseFloat(window.pois[index].yaw),
                                    "size_scale": 1,
                                    "rotateX": 0,
                                    "rotateZ": 0,
                                    "draggable": true,
                                    "cssClass": "hotspot-helper",
                                    "createTooltipFunc": hotspot_embed_move,
                                    "createTooltipArgs": window.pois[index].id,
                                    "dragHandlerFunc": drag_embed_move,
                                    "dragHandlerArgs": [window.pois[index].id,index]
                                });
                                $('#poi_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                                break;
                        }
                    }
                });
                break;
        }
    }

    var interval_drag_helper_m;
    function drag_embed_helper_m(event, args) {
        var marker = args[0];
        var id = marker.id;
        var index = args[1];
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                $('#confirm_move').css({'height':'34px','overflow':'hidden'});
                $('.marker_embed_'+id).css({'outline':'1px dashed red','opacity':0.6});
                window.viewer.setUpdate(true);
                interval_drag_helper_m = setInterval(function () {
                    adjust_marker_embed_helpers_all();
                },10);
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#confirm_move').css({'height':'auto','overflow':'unset'});
                $('.marker_embed_'+id).css({'outline':'none','opacity':1.0});
                window.viewer.setUpdate(false);
                clearInterval(interval_drag_helper_m);
                var coords = window.viewer.mouseEventToCoords(event);
                var yaw = parseFloat(coords[1]);
                var pitch = parseFloat(coords[0]);
                var marker_embed_helpers = marker.embed_coords.split("|");
                marker_embed_helpers[0] = marker_embed_helpers[0].split(",");
                marker_embed_helpers[1] = marker_embed_helpers[1].split(",");
                marker_embed_helpers[2] = marker_embed_helpers[2].split(",");
                marker_embed_helpers[3] = marker_embed_helpers[3].split(",");
                marker_embed_helpers[index][0] = pitch;
                marker_embed_helpers[index][1] = yaw;
                var embed_coords = marker_embed_helpers[0][0]+","+marker_embed_helpers[0][1]+"|"+marker_embed_helpers[1][0]+","+marker_embed_helpers[1][1]+"|"+marker_embed_helpers[2][0]+","+marker_embed_helpers[2][1]+"|"+marker_embed_helpers[3][0]+","+marker_embed_helpers[3][1];
                marker.embed_coords = embed_coords;
                var pos_1 = ($('#marker_embded_helper_'+id+'_1').offset());
                var pos_2 = ($('#marker_embded_helper_'+id+'_2').offset());
                var pos_3 = ($('#marker_embded_helper_'+id+'_3').offset());
                var pos_4 = ($('#marker_embded_helper_'+id+'_4').offset());
                var center_left = ((parseFloat(pos_1.left) + parseFloat(pos_2.left) + parseFloat(pos_3.left) + parseFloat(pos_4.left)) / 4) + 8;
                var center_top = ((parseFloat(pos_1.top) + parseFloat(pos_2.top) + parseFloat(pos_3.top) + parseFloat(pos_4.top)) / 4) + 8;
                var event_center = [];
                event_center.clientX = center_left;
                event_center.clientY = center_top;
                var coords_center = window.viewer.mouseEventToCoords(event_center);
                marker.yaw = parseFloat(coords_center[1]);
                marker.pitch = parseFloat(coords_center[0]);
                var w = Math.getDistance(pos_1.left,pos_1.top,pos_3.left,pos_3.top);
                var h = Math.getDistance(pos_1.left,pos_1.top,pos_2.left,pos_2.top);
                marker.embed_size = w+","+h;
                jQuery.each(window.markers, function(index, marker_a) {
                    if(id==marker_a.id) {
                        window.markers[index].yaw = marker.yaw;
                        window.markers[index].pitch = marker.pitch;
                        window.markers[index].embed_coords = marker.embed_coords;
                        window.markers[index].embed_size = marker.embed_size;
                        switch(window.markers[index].embed_type) {
                            case 'selection':
                                render_marker(id,index);
                                $('#marker_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                                $('#marker_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
                                $('#marker_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
                                $('#marker_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
                                $('#marker_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
                                break;
                            default:
                                window.viewer.removeHotSpot("m"+id.toString()+"_move");
                                window.viewer.addHotSpot({
                                    "id": "m"+window.markers[index].id+"_move",
                                    "type": 'pointer',
                                    "object": "marker_embed_helper",
                                    "transform3d": false,
                                    "pitch": parseFloat(window.markers[index].pitch),
                                    "yaw": parseFloat(window.markers[index].yaw),
                                    "size_scale": 1,
                                    "rotateX": 0,
                                    "rotateZ": 0,
                                    "draggable": true,
                                    "cssClass": "hotspot-helper",
                                    "createTooltipFunc": hotspot_embed_move_m,
                                    "createTooltipArgs": window.markers[index].id,
                                    "dragHandlerFunc": drag_embed_move_m,
                                    "dragHandlerArgs": [window.markers[index].id,index]
                                });
                                $('#marker_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                                break;
                        }
                    }
                });
                break;
        }
    }

    var yaw_i,pitch_i;
    function drag_embed_move(event, args) {
        var id = args[0];
        var index = args[1];
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                $('#confirm_move').css({'height':'34px','overflow':'hidden'});
                $('.poi_embed_'+id).css('outline','1px dashed red');
                var coords = window.viewer.mouseEventToCoords(event);
                yaw_i = parseFloat(coords[1]);
                pitch_i = parseFloat(coords[0]);
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#confirm_move').css({'height':'auto','overflow':'unset'});
                $('.poi_embed_'+id).css('outline','none');
                var coords = window.viewer.mouseEventToCoords(event);
                var yaw_c = parseFloat(coords[1]);
                var pitch_c = parseFloat(coords[0]);
                window.pois[index].yaw = yaw_c;
                window.pois[index].pitch = pitch_c;
                var yaw_diff = yaw_c-yaw_i;
                var pitch_diff = pitch_c-pitch_i;
                var poi_embed_helpers = window.pois[index].embed_coords.split("|");
                poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
                poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
                poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
                poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
                poi_embed_helpers[0][0] = parseFloat(poi_embed_helpers[0][0]) + pitch_diff;
                poi_embed_helpers[0][1] = parseFloat(poi_embed_helpers[0][1]) + yaw_diff;
                poi_embed_helpers[1][0] = parseFloat(poi_embed_helpers[1][0]) + pitch_diff;
                poi_embed_helpers[1][1] = parseFloat(poi_embed_helpers[1][1]) + yaw_diff;
                poi_embed_helpers[2][0] = parseFloat(poi_embed_helpers[2][0]) + pitch_diff;
                poi_embed_helpers[2][1] = parseFloat(poi_embed_helpers[2][1]) + yaw_diff;
                poi_embed_helpers[3][0] = parseFloat(poi_embed_helpers[3][0]) + pitch_diff;
                poi_embed_helpers[3][1] = parseFloat(poi_embed_helpers[3][1]) + yaw_diff;
                var embed_coords = poi_embed_helpers[0][0]+","+poi_embed_helpers[0][1]+"|"+poi_embed_helpers[1][0]+","+poi_embed_helpers[1][1]+"|"+poi_embed_helpers[2][0]+","+poi_embed_helpers[2][1]+"|"+poi_embed_helpers[3][0]+","+poi_embed_helpers[3][1];
                window.pois[index].embed_coords = embed_coords;
                render_poi(id,index);
                $('#poi_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                $('#poi_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
                $('#poi_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
                $('#poi_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
                $('#poi_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
                break;

        }
    }

    var yaw_i_m,pitch_i_m;
    function drag_embed_move_m(event, args) {
        var id = args[0];
        var index = args[1];
        switch(event.type) {
            case 'mousedown':
            case 'touchstart':
            case 'pointerdown':
                $('#confirm_move').css({'height':'34px','overflow':'hidden'});
                $('.marker_embed_'+id).css('outline','1px dashed red');
                var coords = window.viewer.mouseEventToCoords(event);
                yaw_i_m = parseFloat(coords[1]);
                pitch_i_m = parseFloat(coords[0]);
                break;
            case 'mouseup':
            case 'touchend':
            case 'pointerup':
                $('#confirm_move').css({'height':'auto','overflow':'unset'});
                $('.marker_embed_'+id).css('outline','none');
                var coords = window.viewer.mouseEventToCoords(event);
                var yaw_c = parseFloat(coords[1]);
                var pitch_c = parseFloat(coords[0]);
                window.markers[index].yaw = yaw_c;
                window.markers[index].pitch = pitch_c;
                var yaw_diff = yaw_c-yaw_i_m;
                var pitch_diff = pitch_c-pitch_i_m;
                var marker_embed_helpers = window.markers[index].embed_coords.split("|");
                marker_embed_helpers[0] = marker_embed_helpers[0].split(",");
                marker_embed_helpers[1] = marker_embed_helpers[1].split(",");
                marker_embed_helpers[2] = marker_embed_helpers[2].split(",");
                marker_embed_helpers[3] = marker_embed_helpers[3].split(",");
                marker_embed_helpers[0][0] = parseFloat(marker_embed_helpers[0][0]) + pitch_diff;
                marker_embed_helpers[0][1] = parseFloat(marker_embed_helpers[0][1]) + yaw_diff;
                marker_embed_helpers[1][0] = parseFloat(marker_embed_helpers[1][0]) + pitch_diff;
                marker_embed_helpers[1][1] = parseFloat(marker_embed_helpers[1][1]) + yaw_diff;
                marker_embed_helpers[2][0] = parseFloat(marker_embed_helpers[2][0]) + pitch_diff;
                marker_embed_helpers[2][1] = parseFloat(marker_embed_helpers[2][1]) + yaw_diff;
                marker_embed_helpers[3][0] = parseFloat(marker_embed_helpers[3][0]) + pitch_diff;
                marker_embed_helpers[3][1] = parseFloat(marker_embed_helpers[3][1]) + yaw_diff;
                var embed_coords = marker_embed_helpers[0][0]+","+marker_embed_helpers[0][1]+"|"+marker_embed_helpers[1][0]+","+marker_embed_helpers[1][1]+"|"+marker_embed_helpers[2][0]+","+marker_embed_helpers[2][1]+"|"+marker_embed_helpers[3][0]+","+marker_embed_helpers[3][1];
                window.markers[index].embed_coords = embed_coords;
                render_marker(id,index);
                $('#marker_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
                $('#marker_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
                $('#marker_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
                $('#marker_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
                $('#marker_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
                break;

        }
    }

    window.poi_embed_get_transform = function(from, to) {
        var A, H, b, h, i, k, k_i, l, lhs, m, ref, rhs;
        A = [];
        for (i = k = 0; k < 4; i = ++k) {
            A.push([from[i].x, from[i].y, 1, 0, 0, 0, -from[i].x * to[i].x, -from[i].y * to[i].x]);
            A.push([0, 0, 0, from[i].x, from[i].y, 1, -from[i].x * to[i].y, -from[i].y * to[i].y]);
        }
        b = [];
        for (i = l = 0; l < 4; i = ++l) {
            b.push(to[i].x);
            b.push(to[i].y);
        }
        h = numeric.solve(A, b);
        H = [[h[0], h[1], 0, h[2]], [h[3], h[4], 0, h[5]], [0, 0, 1, 0], [h[6], h[7], 0, 1]];
        for (i = m = 0; m < 4; i = ++m) {
            lhs = numeric.dot(H, [from[i].x, from[i].y, 0, 1]);
            k_i = lhs[3];
            rhs = numeric.dot(k_i, [to[i].x, to[i].y, 0, 1]);
        }
        return H;
    };

    window.poi_embed_apply_transform = function(element, originalPos, targetPos, callback) {
        var H, from, i, j, p, to;
        from = (function() {
            var k, len, results;
            results = [];
            for (k = 0, len = originalPos.length; k < len; k++) {
                p = originalPos[k];
                results.push({
                    x: p[0] - originalPos[0][0],
                    y: p[1] - originalPos[0][1]
                });
            }
            return results;
        })();
        to = (function() {
            var k, len, results;
            results = [];
            for (k = 0, len = targetPos.length; k < len; k++) {
                p = targetPos[k];
                results.push({
                    x: p[0] - originalPos[0][0],
                    y: p[1] - originalPos[0][1]
                });
            }
            return results;
        })();
        H = poi_embed_get_transform(from, to);
        $(element).css({
            'transform': `matrix3d(${((function() {
                var k, results;
                results = [];
                for (i = k = 0; k < 4; i = ++k) {
                    results.push((function() {
                        var l, results1;
                        results1 = [];
                        for (j = l = 0; l < 4; j = ++l) {
                            results1.push(H[j][i].toFixed(20));
                        }
                        return results1;
                    })());
                }
                return results;
            })()).join(',')})`,
            'transform-origin': '0 0'
        });
        return typeof callback === "function" ? callback(element, H) : void 0;
    };

    window.poi_embed_make_transformable = function(selector, id, callback) {
        var pano_container = '';
        var edit_room = 0;
        if($('.div_panorama_container').length) {
            pano_container = '.div_panorama_container';
        } else {
            if($('#panorama').length) {
                pano_container = '#panorama';
                edit_room = 1;
            } else {
                if($('#panorama_video').length) {
                    pano_container = '#panorama_video';
                    edit_room = 1;
                } else {
                    return;
                }
            }
        }
        return $(selector).each(function(i, element) {
            var controlPoints, originalPos, p, position;
            $(element).css('transform', '');
            controlPoints = (function() {
                var k, len, ref, results;
                ref = ['left top', 'left bottom', 'right top', 'right bottom'];
                results = [];
                for (k = 0, len = ref.length; k < len; k++) {
                    position = ref[k];
                    results.push($('<div class="draggable_poi_embed" id="draggable_'+id+'_'+(k+1)+'">').css({
                        position: 'absolute',
                        zIndex: 100000
                    }).appendTo(pano_container).position({
                        at: position,
                        of: element,
                        collision: 'none'
                    }));
                }
                return results;
            })();
            originalPos = (function() {
                var k, len, results;
                results = [];
                for (k = 0, len = controlPoints.length; k < len; k++) {
                    p = controlPoints[k];
                    results.push([p.position().left, p.position().top]);
                }
                return results;
            })();
            poi_embed_originals_pos[id] = originalPos;
            return element;
        });
    };

    window.marker_embed_make_transformable = function(selector, id, callback) {
        var pano_container = '';
        var edit_room = 0;
        if($('.div_panorama_container').length) {
            pano_container = '.div_panorama_container';
        } else {
            if($('#panorama').length) {
                pano_container = '#panorama';
                edit_room = 1;
            } else {
                if($('#panorama_video').length) {
                    pano_container = '#panorama_video';
                    edit_room = 1;
                } else {
                    return;
                }
            }
        }
        return $(selector).each(function(i, element) {
            var controlPoints, originalPos, p, position;
            $(element).css('transform', '');
            controlPoints = (function() {
                var k, len, ref, results;
                ref = ['left top', 'left bottom', 'right top', 'right bottom'];
                results = [];
                for (k = 0, len = ref.length; k < len; k++) {
                    position = ref[k];
                    results.push($('<div class="draggable_marker_embed" id="draggable_'+id+'_'+(k+1)+'">').css({
                        position: 'absolute',
                        zIndex: 100000
                    }).appendTo(pano_container).position({
                        at: position,
                        of: element,
                        collision: 'none'
                    }));
                }
                return results;
            })();
            originalPos = (function() {
                var k, len, results;
                results = [];
                for (k = 0, len = controlPoints.length; k < len; k++) {
                    p = controlPoints[k];
                    results.push([p.position().left, p.position().top]);
                }
                return results;
            })();
            marker_embed_originals_pos[id] = originalPos;
            return element;
        });
    };

    var video_p = null, app_p = null, loader_p = null;
    function initialize_pano_pois(id_room,image,id_poi_add,array_room) {
        if(window.currentYaw==0) {
            window.currentYaw = parseFloat(array_room.yaw);
        }
        if(window.currentPitch==0) {
            window.currentPitch = parseFloat(array_room.pitch);
        }
        if(window.currentHfov==0) {
            window.currentHfov = 100;
        }
        if(window.wizard_step!=-1) {
            window.currentYaw = window.currentYaw + 20;
        }
        window.panorama_image = image;
        $('#panorama_pois').show();
        var hotSpots = [];
        var index_poi_add = null;
        jQuery.each(window.pois, function(index, poi) {
            if(id_poi_add!=null) {
                if(id_poi_add==poi.id && poi.what=='poi') {
                    index_poi_add = index;
                }
            }
            if(poi.what=='poi') {
                if(poi.embed_type!='' && poi.transform3d==1) {
                    hotSpots.push({
                        "id": "p"+poi.id,
                        "type": poi.embed_type,
                        "object": "poi_embed",
                        "scale": false,
                        "transform3d": parseInt(poi.transform3d),
                        "tooltip_type": "",
                        "pitch": parseFloat(poi.pitch),
                        "yaw": parseFloat(poi.yaw),
                        "rotateX": 0,
                        "rotateZ": 0,
                        "size_scale": 1,
                        "cssClass": "hotspot-embed hotspot",
                        "createTooltipFunc": hotspot_embed,
                        "createTooltipArgs": poi,
                        "clickHandlerFunc": click_edit_poi,
                        "clickHandlerArgs": poi.id
                    });
                    if(poi.transform3d==1) {
                        var poi_embed_helpers = poi.embed_coords.split("|");
                        poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
                        poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
                        poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
                        poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
                        jQuery.each(poi_embed_helpers, function(index_h, poi_embed_helper) {
                            hotSpots.push({
                                "id": "p"+poi.id+"_"+(index_h+1),
                                "type": 'pointer',
                                "object": "poi_embed_helper",
                                "transform3d": false,
                                "pitch": parseFloat(poi_embed_helper[0]),
                                "yaw": parseFloat(poi_embed_helper[1]),
                                "size_scale": 1,
                                "rotateX": 0,
                                "rotateZ": 0,
                                "draggable": true,
                                "cssClass": "hotspot-helper",
                                "createTooltipFunc": hotspot_embed_helper,
                                "createTooltipArgs": [poi.id,(index_h+1)],
                                "dragHandlerFunc": drag_embed_helper,
                                "dragHandlerArgs": [poi,index_h]
                            });
                        });
                        hotSpots.push({
                            "id": "p"+poi.id+"_move",
                            "type": 'pointer',
                            "object": "poi_embed_helper",
                            "transform3d": false,
                            "pitch": parseFloat(poi.pitch),
                            "yaw": parseFloat(poi.yaw),
                            "size_scale": 1,
                            "rotateX": 0,
                            "rotateZ": 0,
                            "draggable": true,
                            "cssClass": "hotspot-helper",
                            "createTooltipFunc": hotspot_embed_move,
                            "createTooltipArgs": poi.id,
                            "dragHandlerFunc": drag_embed_move,
                            "dragHandlerArgs": [poi.id,index]
                        });
                    }
                } else if(poi.embed_type!='' && poi.transform3d==0) {
                    hotSpots.push({
                        "id": "p"+poi.id,
                        "type": poi.embed_type,
                        "object": "poi_embed",
                        "scale": false,
                        "transform3d": parseInt(poi.transform3d),
                        "tooltip_type": "",
                        "pitch": parseFloat(poi.pitch),
                        "yaw": parseFloat(poi.yaw),
                        "rotateX": parseInt(poi.rotateX),
                        "rotateZ": parseInt(poi.rotateZ),
                        "size_scale": parseFloat(poi.size_scale),
                        "cssClass": "hotspot-embed hotspot",
                        "createTooltipFunc": hotspot_embed,
                        "createTooltipArgs": poi,
                        "clickHandlerFunc": click_edit_poi,
                        "clickHandlerArgs": poi.id
                    });
                } else {
                    switch(poi.type) {
                        case 'callout':
                            hotSpots.push({
                                "id": "p"+poi.id,
                                "type": 'callout',
                                "transform3d": false,
                                "scale": false,
                                "pitch": parseFloat(poi.pitch),
                                "yaw": parseFloat(poi.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "cssClass": "custom-hotspot-content hotspot",
                                "createTooltipFunc": hotspot_p_callout,
                                "createTooltipArgs": poi,
                                "clickHandlerFunc": click_edit_poi,
                                "clickHandlerArgs": poi.id
                            });
                            break;
                        case 'staging':
                            hotSpots.push({
                                "id": "p"+poi.id,
                                "type": 'poi',
                                "transform3d": false,
                                "scale": false,
                                "pitch": parseFloat(poi.pitch),
                                "yaw": parseFloat(poi.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "cssClass": "custom-hotspot-content hotspot staging-hotspot",
                                "createTooltipFunc": hotspot_p_staging,
                                "createTooltipArgs": poi,
                                "clickHandlerFunc": click_edit_poi,
                                "clickHandlerArgs": poi.id
                            });
                            break;
                        default:
                            hotSpots.push({
                                "id": "p"+poi.id,
                                "type": 'poi',
                                "transform3d": false,
                                "scale": (parseInt(poi.scale)==1) ? true : false,
                                "pitch": parseFloat(poi.pitch),
                                "yaw": parseFloat(poi.yaw),
                                "rotateX": parseInt(poi.rotateX),
                                "rotateZ": parseInt(poi.rotateZ),
                                "size_scale": parseFloat(poi.size_scale),
                                "cssClass": "custom-hotspot-content hotspot",
                                "createTooltipFunc": hotspot_p,
                                "createTooltipArgs": poi,
                                "clickHandlerFunc": click_edit_poi,
                                "clickHandlerArgs": poi.id
                            });
                            break;
                    }
                }
            } else {
                if(poi.embed_type!='') {
                    hotSpots.push({
                        "id": "m"+poi.id,
                        "type": poi.embed_type,
                        "object": "marker_embed",
                        "transform3d": parseInt(poi.transform3d),
                        "scale": false,
                        "tooltip_type": "",
                        "pitch": parseFloat(poi.pitch),
                        "yaw": parseFloat(poi.yaw),
                        "rotateX": 0,
                        "rotateZ": 0,
                        "size_scale": 1,
                        "cssClass": "hotspot-embed hotspot",
                        "createTooltipFunc": hotspot_embed_m,
                        "createTooltipArgs": poi
                    });
                    var marker_embed_helpers = poi.embed_coords.split("|");
                    marker_embed_helpers[0] = marker_embed_helpers[0].split(",");
                    marker_embed_helpers[1] = marker_embed_helpers[1].split(",");
                    marker_embed_helpers[2] = marker_embed_helpers[2].split(",");
                    marker_embed_helpers[3] = marker_embed_helpers[3].split(",");
                    jQuery.each(marker_embed_helpers, function (index_h, marker_embed_helper) {
                        hotSpots.push({
                            "id": "m"+poi.id + "_" + (index_h + 1),
                            "type": 'pointer',
                            "object": "marker_embed_helper",
                            "transform3d": false,
                            "pitch": parseFloat(marker_embed_helper[0]),
                            "yaw": parseFloat(marker_embed_helper[1]),
                            "size_scale": 1,
                            "rotateX": 0,
                            "rotateZ": 0,
                            "draggable": true,
                            "cssClass": "hotspot-helper",
                            "createTooltipFunc": hotspot_embed_helper_m,
                            "createTooltipArgs": [poi.id, (index_h + 1)]
                        });
                    });
                    hotSpots.push({
                        "id": "m"+poi.id + "_move",
                        "type": 'pointer',
                        "object": "marker_embed_helper",
                        "transform3d": false,
                        "pitch": parseFloat(poi.pitch),
                        "yaw": parseFloat(poi.yaw),
                        "size_scale": 1,
                        "rotateX": 0,
                        "rotateZ": 0,
                        "draggable": true,
                        "cssClass": "hotspot-helper",
                        "createTooltipFunc": hotspot_embed_move_m,
                        "createTooltipArgs": poi.id
                    });
                } else {
                    hotSpots.push({
                        "id": "m"+poi.id,
                        "type": 'marker',
                        "transform3d": false,
                        "scale": (parseInt(poi.scale)==1) ? true : false,
                        "pitch": parseFloat(poi.pitch),
                        "yaw": parseFloat(poi.yaw),
                        "rotateX": parseInt(poi.rotateX),
                        "rotateZ": parseInt(poi.rotateZ),
                        "size_scale": parseFloat(poi.size_scale),
                        "cssClass": "custom-hotspot hotspot",
                        "createTooltipFunc": hotspot_m,
                        "createTooltipArgs": poi
                    });
                }
            }
        });
        try {
            window.video_viewer.dispose();
        } catch (e) {}
        try {
            window.viewer.destroy();
        } catch (e) {}
        $('#panorama_pois').empty();
        if(array_room.room_type == 'video') {
            var fileExt = array_room.panorama_video.split('.').pop().toLowerCase();
            switch(fileExt) {
                case 'webm':
                    var type_video = 'video/webm';
                    break;
                default:
                    var type_video = 'video/mp4';
                    break;
            }
            if(window.s3_enabled==1) {
                var video_url = window.s3_url+'viewer/videos/'+array_room.panorama_video;
                var image_url = window.s3_url+'viewer/panoramas/'+image+'?s3=1';
            } else {
                var video_url = '../viewer/videos/'+array_room.panorama_video;
                var image_url = '../viewer/panoramas/'+image;
            }
            if(window.is_mobile) {
                try {
                    loader_p.reset();
                } catch (e) {}
                try {
                    video_p.remove();
                } catch (e) {}
                $("#canvas_p").empty();
                var setup_video_p = (loader, resources) => {
                    PIXI.utils.sayHello("WebGL");
                    var index_bg = Object.keys(resources)[0];
                    app_p = new PIXI.Application({
                        antialias: false,
                        transparent: false,
                        resolution: 1,
                        width: resources[index_bg].baseTexture.width,
                        height: resources[index_bg].baseTexture.height
                    });
                    $("#canvas_p").append(app_p.view);
                    let bg = PIXI.Sprite.from(resources[index_bg]);
                    /*bg.anchor.y = 1;
                    bg.scale.y = -1;*/
                    app_p.stage.addChild(bg);
                    video_p = document.createElement('video');
                    video_p.id = 'video_viewer';
                    video_p.crossOrigin = 'anonymous';
                    video_p.preload = 'auto';
                    video_p.autoplay = true;
                    video_p.muted = true;
                    video_p.loop = true;
                    video_p.oncanplay = function () {
                        video_p.play();
                    };
                    video_p.setAttribute('playsinline', '');
                    video_p.setAttribute('webkit-playsinline', '');
                    video_p.src = video_url;
                    const sprite = PIXI.Sprite.from(video_p);
                    /*sprite.anchor.y = 1;
                    sprite.scale.y = -1;*/
                    app_p.stage.addChild(sprite);
                    let canvas = $('#canvas_p canvas')[0];
                    window.viewer = pannellum.viewer('panorama_pois', {
                        "id_room": window.id_room,
                        "type": "equirectangular",
                        "panorama": canvas,
                        "autoLoad": true,
                        "dynamic": true,
                        "dynamicUpdate": true,
                        "showFullscreenCtrl": false,
                        "showControls": false,
                        "horizonPitch": parseInt(array_room.h_pitch),
                        "horizonRoll": parseInt(array_room.h_roll),
                        "minHfov": 50,
                        "maxHfov": 120,
                        "yaw": parseFloat(window.currentYaw),
                        "pitch": parseFloat(window.currentPitch),
                        "hfov": 100,
                        "haov": parseInt(array_room.haov),
                        "vaov": parseInt(array_room.vaov),
                        "hotSpots": hotSpots,
                        "friction": 1,
                        "strings": {
                            "loadingLabel": window.backend_labels.loading + "...",
                        },
                    });
                    setTimeout(function() {
                        if(window.is_fullscreen) {
                            try {
                                $('#video_viewer').css('height','100%');
                            } catch (e) {}
                        } else {
                            var container_h = $('#content-wrapper').height() - 155;
                            if($('#tawk-container').length) {
                                container_h = container_h - 20;
                            }
                            if($('#plan_poi_msg').is(':visible')) {
                                container_h = container_h - $('#plan_poi_msg').height() - 10;
                            }
                            try {
                                $('#video_viewer').css('height',container_h+'px');
                            } catch (e) {}
                        }
                        viewer_poi_initialized(id_poi_add,index_poi_add);
                    },200);
                }
                var list_assets = ["background"];
                PIXI.Assets.add("background", image_url);
                PIXI.Assets.load(list_assets).then((textures) => {
                    setup_video_p(null,textures);
                });
            } else {
                $('#panorama_pois').append('<video controls playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="width: 100%;height: 600px;margin: 0 auto;" muted preload="none" crossorigin="anonymous"><source src="'+video_url+'" type="'+type_video+'"/></video>');
                if(window.is_fullscreen) {
                    try {
                        $('#video_viewer').css('height','100%');
                    } catch (e) {}
                } else {
                    var container_h = $('#content-wrapper').height() - 155;
                    if($('#tawk-container').length) {
                        container_h = container_h - 20;
                    }
                    if($('#plan_poi_msg').is(':visible')) {
                        container_h = container_h - $('#plan_poi_msg').height() - 10;
                    }
                    try {
                        $('#video_viewer').css('height',container_h+'px');
                    } catch (e) {}
                }
                window.video_viewer = videojs('video_viewer', {
                    loop: true,
                    autoload: true,
                    muted: true,
                    controls: true,
                    plugins: {
                        pannellum: {
                            "autoLoad": true,
                            "showFullscreenCtrl": false,
                            "showControls": false,
                            "horizonPitch": parseInt(array_room.h_pitch),
                            "horizonRoll": parseInt(array_room.h_roll),
                            "minHfov": 50,
                            "maxHfov": 120,
                            "yaw": parseFloat(window.currentYaw),
                            "pitch": parseFloat(window.currentPitch),
                            "hfov": 100,
                            "haov": parseInt(array_room.haov),
                            "vaov": parseInt(array_room.vaov),
                            "hotSpots": hotSpots,
                            "friction": 1,
                            "strings": {
                                "loadingLabel": window.backend_labels.loading+"...",
                            },
                        }
                    }
                });
                window.video_viewer.load();
                window.video_viewer.on('ready', function() {
                    window.video_viewer.play();
                    window.viewer = window.video_viewer.pnlmViewer;
                    window.viewer.on('load',function () {
                        viewer_poi_initialized(id_poi_add,index_poi_add);
                    });
                });
            }
        } else {
            if(window.id_room_alt_sel!=0) {
                var multires = 0;
            } else {
                var multires = parseInt(array_room.multires);
            }
            if(multires) {
                var multires_config = JSON.parse(array_room.multires_config);
                window.viewer = pannellum.viewer('panorama_pois', {
                    "type": "multires",
                    "multiRes": multires_config,
                    "backgroundColor": [1,1,1],
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(window.currentYaw),
                    "pitch": parseFloat(window.currentPitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "hotSpots": hotSpots
                });
                setTimeout(function () {
                    viewer_poi_initialized(id_poi_add,index_poi_add);
                },200);
            } else {
                if(window.s3_enabled==1) {
                    var image_url = window.s3_url+'viewer/panoramas/'+image+'?s3=1';
                } else {
                    var image_url = '../viewer/panoramas/'+image;
                }
                window.viewer = pannellum.viewer('panorama_pois', {
                    "type": "equirectangular",
                    "panorama": image_url,
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(window.currentYaw),
                    "pitch": parseFloat(window.currentPitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "hotSpots": hotSpots,
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
                window.viewer.on("load",function () {
                    viewer_poi_initialized(id_poi_add,index_poi_add);
                });
            }
            window.viewer.on('animatefinished',function () {
                if(window.viewer_initialized) {
                    var yaw = parseFloat(window.viewer.getYaw());
                    var pitch = parseFloat(window.viewer.getPitch());
                    var hfov = parseFloat(window.viewer.getHfov());
                    window.currentYaw = yaw;
                    window.currentPitch = pitch;
                    window.currentHfov = hfov;
                }
            });
        }
    }

    function initialize_pano_measures(id_room,image,array_room,id_measure_add) {
        if(window.currentYaw==0) {
            window.currentYaw = parseFloat(array_room.yaw);
        }
        if(window.currentPitch==0) {
            window.currentPitch = parseFloat(array_room.pitch);
        }
        if(window.currentHfov==0) {
            window.currentHfov = 100;
        }
        if(window.wizard_step!=-1) {
            window.currentYaw = window.currentYaw + 20;
        }
        window.panorama_image = image;
        $('#panorama_measures').show();
        var hotSpots = [];
        var index_measure_add = null;
        jQuery.each(window.measures, function(index, measure) {
            if(id_measure_add==measure.id) {
                index_measure_add = index;
            }
            hotSpots.push({
                "id": 'measure_'+measure.id+'_start',
                "type": 'measure',
                "view_type": 0,
                "object": "measure",
                "transform3d": false,
                "scale": false,
                "draggable": true,
                "tooltip_type": '',
                "pitch": parseFloat(measure.pitch_start),
                "yaw": parseFloat(measure.yaw_start),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "animation": '',
                "cssClass": "custom-hotspot-measure",
                "createTooltipFunc": hotspot_measure,
                "createTooltipArgs": {id:measure.id,dir:'start',index:index,yaw:parseFloat(measure.yaw_start),pitch:parseFloat(measure.pitch_start)},
                "dragHandlerFunc": drag_measure_move,
                "dragHandlerArgs": {id:measure.id,dir:'start',index:index}
            });
            hotSpots.push({
                "id": 'measure_'+measure.id+'_end',
                "type": 'measure',
                "view_type": 0,
                "object": "measure",
                "transform3d": false,
                "scale": false,
                "draggable": true,
                "tooltip_type": '',
                "pitch": parseFloat(measure.pitch_end),
                "yaw": parseFloat(measure.yaw_end),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "animation": '',
                "cssClass": "custom-hotspot-measure",
                "createTooltipFunc": hotspot_measure,
                "createTooltipArgs": {id:measure.id,dir:'end',index:index,yaw:parseFloat(measure.yaw_start),pitch:parseFloat(measure.pitch_start)},
                "dragHandlerFunc": drag_measure_move,
                "dragHandlerArgs": {id:measure.id,dir:'end',index:index}
            });
        });
        try {
            window.video_viewer.dispose();
        } catch (e) {}
        try {
            window.viewer.destroy();
        } catch (e) {}
        $('#panorama_measures').empty();
        if(array_room.room_type == 'video') {
            var fileExt = array_room.panorama_video.split('.').pop().toLowerCase();
            switch(fileExt) {
                case 'webm':
                    var type_video = 'video/webm';
                    break;
                default:
                    var type_video = 'video/mp4';
                    break;
            }
            if(window.s3_enabled==1) {
                var video_url = window.s3_url+'viewer/videos/'+array_room.panorama_video;
                var image_url = window.s3_url+'viewer/panoramas/'+image+'?s3=1';
            } else {
                var video_url = '../viewer/videos/'+array_room.panorama_video;
                var image_url = '../viewer/panoramas/'+image;
            }
            if(window.is_mobile) {
                try {
                    loader_p.reset();
                } catch (e) {}
                try {
                    video_p.remove();
                } catch (e) {}
                $("#canvas_p").empty();
                var setup_video_p = (loader, resources) => {
                    PIXI.utils.sayHello("WebGL");
                    var index_bg = Object.keys(resources)[0];
                    app_p = new PIXI.Application({
                        antialias: false,
                        transparent: false,
                        resolution: 1,
                        width: resources[index_bg].baseTexture.width,
                        height: resources[index_bg].baseTexture.height
                    });
                    $("#canvas_p").append(app_p.view);
                    let bg = PIXI.Sprite.from(resources[index_bg]);
                    /*bg.anchor.y = 1;
                    bg.scale.y = -1;*/
                    app_p.stage.addChild(bg);
                    video_p = document.createElement('video');
                    video_p.id = 'video_viewer';
                    video_p.crossOrigin = 'anonymous';
                    video_p.preload = 'auto';
                    video_p.autoplay = true;
                    video_p.muted = true;
                    video_p.loop = true;
                    video_p.oncanplay = function () {
                        video_p.play();
                    };
                    video_p.setAttribute('playsinline', '');
                    video_p.setAttribute('webkit-playsinline', '');
                    video_p.src = video_url;
                    const sprite = PIXI.Sprite.from(video_p);
                    /*sprite.anchor.y = 1;
                    sprite.scale.y = -1;*/
                    app_p.stage.addChild(sprite);
                    let canvas = $('#canvas_p canvas')[0];
                    window.viewer = pannellum.viewer('panorama_measures', {
                        "id_room": window.id_room,
                        "type": "equirectangular",
                        "panorama": canvas,
                        "autoLoad": true,
                        "dynamic": true,
                        "dynamicUpdate": true,
                        "showFullscreenCtrl": false,
                        "showControls": false,
                        "horizonPitch": parseInt(array_room.h_pitch),
                        "horizonRoll": parseInt(array_room.h_roll),
                        "minHfov": 50,
                        "maxHfov": 120,
                        "yaw": parseFloat(window.currentYaw),
                        "pitch": parseFloat(window.currentPitch),
                        "hfov": 100,
                        "haov": parseInt(array_room.haov),
                        "vaov": parseInt(array_room.vaov),
                        "hotSpots": hotSpots,
                        "friction": 1,
                        "strings": {
                            "loadingLabel": window.backend_labels.loading + "...",
                        },
                    });
                    setTimeout(function() {
                        if(window.is_fullscreen) {
                            try {
                                $('#video_viewer').css('height','100%');
                            } catch (e) {}
                        } else {
                            var container_h = $('#content-wrapper').height() - 155;
                            if($('#tawk-container').length) {
                                container_h = container_h - 20;
                            }
                            try {
                                $('#video_viewer').css('height',container_h+'px');
                            } catch (e) {}
                        }
                        viewer_measure_initialized(id_measure_add, index_measure_add);
                    },200);
                }
                var list_assets = ["background"];
                PIXI.Assets.add("background", image_url);
                PIXI.Assets.load(list_assets).then((textures) => {
                    setup_video_p(null,textures);
                });
            } else {
                $('#panorama_measures').append('<video controls playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="width: 100%;height: 600px;margin: 0 auto;" muted preload="none" crossorigin="anonymous"><source src="' + video_url + '" type="' + type_video + '"/></video>');
                if(window.is_fullscreen) {
                    try {
                        $('#video_viewer').css('height','100%');
                    } catch (e) {}
                } else {
                    var container_h = $('#content-wrapper').height() - 155;
                    if($('#tawk-container').length) {
                        container_h = container_h - 20;
                    }
                    try {
                        $('#video_viewer').css('height',container_h+'px');
                    } catch (e) {}
                }
                window.video_viewer = videojs('video_viewer', {
                    loop: true,
                    autoload: true,
                    muted: true,
                    controls: true,
                    plugins: {
                        pannellum: {
                            "autoLoad": true,
                            "showFullscreenCtrl": false,
                            "showControls": false,
                            "horizonPitch": parseInt(array_room.h_pitch),
                            "horizonRoll": parseInt(array_room.h_roll),
                            "minHfov": 50,
                            "maxHfov": 120,
                            "yaw": parseFloat(window.currentYaw),
                            "pitch": parseFloat(window.currentPitch),
                            "hfov": 100,
                            "haov": parseInt(array_room.haov),
                            "vaov": parseInt(array_room.vaov),
                            "hotSpots": hotSpots,
                            "friction": 1,
                            "strings": {
                                "loadingLabel": window.backend_labels.loading + "...",
                            },
                        }
                    }
                });
                window.video_viewer.load();
                window.video_viewer.on('ready', function () {
                    window.video_viewer.play();
                    window.viewer = window.video_viewer.pnlmViewer;
                    window.viewer.on('load', function () {
                        viewer_measure_initialized(id_measure_add, index_measure_add);
                    });
                });
            }
        } else {
            if(window.id_room_alt_sel!=0) {
                var multires = 0;
            } else {
                var multires = parseInt(array_room.multires);
            }
            if(multires) {
                var multires_config = JSON.parse(array_room.multires_config);
                window.viewer = pannellum.viewer('panorama_measures', {
                    "type": "multires",
                    "multiRes": multires_config,
                    "backgroundColor": [1,1,1],
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(window.currentYaw),
                    "pitch": parseFloat(window.currentPitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "hotSpots": hotSpots
                });
                setTimeout(function () {
                    viewer_measure_initialized(id_measure_add,index_measure_add);
                },200);
            } else {
                if(window.s3_enabled==1) {
                    var image_url = window.s3_url+'viewer/panoramas/'+image+'?s3=1';
                } else {
                    var image_url = '../viewer/panoramas/'+image;
                }
                window.viewer = pannellum.viewer('panorama_measures', {
                    "type": "equirectangular",
                    "panorama": image_url,
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(window.currentYaw),
                    "pitch": parseFloat(window.currentPitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "hotSpots": hotSpots,
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
                window.viewer.on("load",function () {
                    viewer_measure_initialized(id_measure_add,index_measure_add);
                });
            }
            window.viewer.on('animatefinished',function () {
                if(window.viewer_initialized) {
                    var yaw = parseFloat(window.viewer.getYaw());
                    var pitch = parseFloat(window.viewer.getPitch());
                    var hfov = parseFloat(window.viewer.getHfov());
                    window.currentYaw = yaw;
                    window.currentPitch = pitch;
                    window.currentHfov = hfov;
                }
            });
        }
    }

    function initialize_pano_markers(id_room,image,id_marker_add,array_room,yaw_m='',pitch_m='') {
        if(window.currentYaw==0) {
            window.currentYaw = parseFloat(array_room.yaw);
        }
        if(window.currentPitch==0) {
            window.currentPitch = parseFloat(array_room.pitch);
        }
        if(window.currentHfov==0) {
            window.currentHfov = 100;
        }
        if(yaw_m!=='') {
            window.currentYaw = parseFloat(yaw_m);
        }
        if(pitch_m!=='') {
            window.currentPitch = parseFloat(pitch_m);
        }
        window.panorama_image = image;
        $('#panorama_markers').show();
        var hotSpots = [];
        var index_marker_add = null;
        jQuery.each(window.markers, function(index_m, marker_m) {
            if(id_marker_add!=null) {
                if(id_marker_add==marker_m.id && marker_m.what=='marker') {
                    index_marker_add = index_m;
                }
            }
            if(marker_m.what=='marker') {
                if(marker_m.embed_type!='') {
                    hotSpots.push({
                        "id": "m"+marker_m.id,
                        "type": marker_m.embed_type,
                        "object": "marker_embed",
                        "transform3d": parseInt(marker_m.transform3d),
                        "scale": false,
                        "tooltip_type": "",
                        "pitch": parseFloat(marker_m.pitch),
                        "yaw": parseFloat(marker_m.yaw),
                        "rotateX": 0,
                        "rotateZ": 0,
                        "size_scale": 1,
                        "cssClass": "hotspot-embed hotspot",
                        "createTooltipFunc": hotspot_embed_m,
                        "createTooltipArgs": marker_m,
                        "clickHandlerFunc": click_edit_marker,
                        "clickHandlerArgs": marker_m.id
                    });
                    if(marker_m.transform3d==1) {
                        var marker_embed_helpers = marker_m.embed_coords.split("|");
                        marker_embed_helpers[0] = marker_embed_helpers[0].split(",");
                        marker_embed_helpers[1] = marker_embed_helpers[1].split(",");
                        marker_embed_helpers[2] = marker_embed_helpers[2].split(",");
                        marker_embed_helpers[3] = marker_embed_helpers[3].split(",");
                        jQuery.each(marker_embed_helpers, function(index_h, marker_embed_helper) {
                            hotSpots.push({
                                "id": "m"+marker_m.id+"_"+(index_h+1),
                                "type": 'pointer',
                                "object": "marker_embed_helper",
                                "transform3d": false,
                                "pitch": parseFloat(marker_embed_helper[0]),
                                "yaw": parseFloat(marker_embed_helper[1]),
                                "size_scale": 1,
                                "rotateX": 0,
                                "rotateZ": 0,
                                "draggable": true,
                                "cssClass": "hotspot-helper",
                                "createTooltipFunc": hotspot_embed_helper_m,
                                "createTooltipArgs": [marker_m.id,(index_h+1)],
                                "dragHandlerFunc": drag_embed_helper_m,
                                "dragHandlerArgs": [marker_m,index_h]
                            });
                        });
                        hotSpots.push({
                            "id": "m"+marker_m.id+"_move",
                            "type": 'pointer',
                            "object": "marker_embed_helper",
                            "transform3d": false,
                            "pitch": parseFloat(marker_m.pitch),
                            "yaw": parseFloat(marker_m.yaw),
                            "size_scale": 1,
                            "rotateX": 0,
                            "rotateZ": 0,
                            "draggable": true,
                            "cssClass": "hotspot-helper",
                            "createTooltipFunc": hotspot_embed_move_m,
                            "createTooltipArgs": marker_m.id,
                            "dragHandlerFunc": drag_embed_move_m,
                            "dragHandlerArgs": [marker_m.id,index_m]
                        });
                    }
                } else {
                    hotSpots.push({
                        "id": "m"+marker_m.id,
                        "type": 'marker',
                        "transform3d": false,
                        "scale": (parseInt(marker_m.scale)==1) ? true : false,
                        "pitch": parseFloat(marker_m.pitch),
                        "yaw": parseFloat(marker_m.yaw),
                        "rotateX": parseInt(marker_m.rotateX),
                        "rotateZ": parseInt(marker_m.rotateZ),
                        "size_scale": parseFloat(marker_m.size_scale),
                        "cssClass": "custom-hotspot hotspot",
                        "createTooltipFunc": hotspot_m,
                        "createTooltipArgs": marker_m,
                        "clickHandlerFunc": click_edit_marker,
                        "clickHandlerArgs": marker_m.id
                    });
                }
            } else {
                if(marker_m.embed_type!='') {
                    hotSpots.push({
                        "id": "p"+marker_m.id,
                        "type": marker_m.embed_type,
                        "object": "poi_embed",
                        "transform3d": parseInt(marker_m.transform3d),
                        "scale": false,
                        "tooltip_type": "",
                        "pitch": parseFloat(marker_m.pitch),
                        "yaw": parseFloat(marker_m.yaw),
                        "rotateX": 0,
                        "rotateZ": 0,
                        "size_scale": 1,
                        "cssClass": "hotspot-embed hotspot",
                        "createTooltipFunc": hotspot_embed,
                        "createTooltipArgs": marker_m,
                    });
                    if(marker_m.transform3d==1) {
                        var poi_embed_helpers = marker_m.embed_coords.split("|");
                        poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
                        poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
                        poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
                        poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
                        jQuery.each(poi_embed_helpers, function(index_h, poi_embed_helper) {
                            hotSpots.push({
                                "id": "p"+marker_m.id+"_"+(index_h+1),
                                "type": 'pointer',
                                "object": "poi_embed_helper",
                                "transform3d": false,
                                "pitch": parseFloat(poi_embed_helper[0]),
                                "yaw": parseFloat(poi_embed_helper[1]),
                                "size_scale": 1,
                                "rotateX": 0,
                                "rotateZ": 0,
                                "draggable": true,
                                "cssClass": "hotspot-helper",
                                "createTooltipFunc": hotspot_embed_helper,
                                "createTooltipArgs": [marker_m.id,(index_h+1)],
                            });
                        });
                        hotSpots.push({
                            "id": "p"+marker_m.id+"_move",
                            "type": 'pointer',
                            "object": "poi_embed_helper",
                            "transform3d": false,
                            "pitch": parseFloat(marker_m.pitch),
                            "yaw": parseFloat(marker_m.yaw),
                            "size_scale": 1,
                            "rotateX": 0,
                            "rotateZ": 0,
                            "draggable": true,
                            "cssClass": "hotspot-helper",
                            "createTooltipFunc": hotspot_embed_move,
                            "createTooltipArgs": marker_m.id
                        });
                    }
                } else {
                    switch(marker_m.type) {
                        case 'callout':
                            hotSpots.push({
                                "id": "p"+marker_m.id,
                                "type": 'callout',
                                "transform3d": false,
                                "scale": false,
                                "pitch": parseFloat(marker_m.pitch),
                                "yaw": parseFloat(marker_m.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "cssClass": "custom-hotspot-content hotspot",
                                "createTooltipFunc": hotspot_p_callout,
                                "createTooltipArgs": marker_m,
                            });
                            break;
                        case 'staging':
                            hotSpots.push({
                                "id": "p"+marker_m.id,
                                "type": 'poi',
                                "transform3d": false,
                                "scale": false,
                                "pitch": parseFloat(marker_m.pitch),
                                "yaw": parseFloat(marker_m.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "cssClass": "custom-hotspot-content hotspot staging-hotspot",
                                "createTooltipFunc": hotspot_p_staging,
                                "createTooltipArgs": marker_m,
                            });
                            break;
                        default:
                            hotSpots.push({
                                "id": "p"+marker_m.id,
                                "type": 'poi',
                                "transform3d": false,
                                "scale": (parseInt(marker_m.scale)==1) ? true : false,
                                "pitch": parseFloat(marker_m.pitch),
                                "yaw": parseFloat(marker_m.yaw),
                                "rotateX": parseInt(marker_m.rotateX),
                                "rotateZ": parseInt(marker_m.rotateZ),
                                "size_scale": parseFloat(marker_m.size_scale),
                                "cssClass": "custom-hotspot-content hotspot",
                                "createTooltipFunc": hotspot_p,
                                "createTooltipArgs": marker_m,
                            });
                            break;
                    }
                }
            }
        });
        var yaw_north = 0;
        if(array_room.northOffset<0) {
            yaw_north = Math.abs(array_room.northOffset);
        } else {
            yaw_north =  360 - array_room.northOffset;
        }
        if(yaw_north==360) yaw_north=0;
        window.northOffset_sel = yaw_north;
        $('#north_val').html(parseFloat(array_room.northOffset)+'°');
        hotSpots.push({
            "id": "north",
            "type": 'pointer',
            "object": "north_helper",
            "transform3d": false,
            "pitch": 0,
            "yaw": parseFloat(yaw_north),
            "size_scale": 1,
            "rotateX": 0,
            "rotateZ": 0,
            "draggable": true,
            "cssClass": "hotspot-helper north-helper",
            "createTooltipFunc": hotspot_north_helper,
            "createTooltipArgs": null,
            "dragHandlerFunc": drag_north_helper,
            "dragHandlerArgs": id_room
        });
        try {
            window.video_viewer.dispose();
        } catch (e) {}
        try {
            window.viewer.destroy();
        } catch (e) {}
        $('#panorama_markers').empty();
        if(array_room.room_type == 'video') {
            var fileExt = array_room.panorama_video.split('.').pop().toLowerCase();
            switch(fileExt) {
                case 'webm':
                    var type_video = 'video/webm';
                    break;
                default:
                    var type_video = 'video/mp4';
                    break;
            }
            if(window.s3_enabled==1) {
                var video_url = window.s3_url+'viewer/videos/'+array_room.panorama_video;
                var image_url = window.s3_url+'viewer/panoramas/'+image+'?s3=1';
            } else {
                var video_url = '../viewer/videos/'+array_room.panorama_video;
                var image_url = '../viewer/panoramas/'+image;
            }
            if(window.is_mobile) {
                try {
                    loader_p.reset();
                } catch (e) {}
                try {
                    video_p.remove();
                } catch (e) {}
                $("#canvas_p").empty();
                var setup_video_p = (loader, resources) => {
                    PIXI.utils.sayHello("WebGL");
                    var index_bg = Object.keys(resources)[0];
                    app_p = new PIXI.Application({
                        antialias: false,
                        transparent: false,
                        resolution: 1,
                        width: resources[index_bg].baseTexture.width,
                        height: resources[index_bg].baseTexture.height
                    });
                    $("#canvas_p").append(app_p.view);
                    let bg = PIXI.Sprite.from(resources[index_bg]);
                    /*bg.anchor.y = 1;
                    bg.scale.y = -1;*/
                    app_p.stage.addChild(bg);
                    video_p = document.createElement('video');
                    video_p.id = 'video_viewer';
                    video_p.crossOrigin = 'anonymous';
                    video_p.preload = 'auto';
                    video_p.autoplay = true;
                    video_p.muted = true;
                    video_p.loop = true;
                    video_p.oncanplay = function () {
                        video_p.play();
                    };
                    video_p.setAttribute('playsinline', '');
                    video_p.setAttribute('webkit-playsinline', '');
                    video_p.src = video_url;
                    const sprite = PIXI.Sprite.from(video_p);
                    /*sprite.anchor.y = 1;
                    sprite.scale.y = -1;*/
                    app_p.stage.addChild(sprite);
                    let canvas = $('#canvas_p canvas')[0];
                    window.viewer = pannellum.viewer('panorama_markers', {
                        "id_room": window.id_room,
                        "type": "equirectangular",
                        "panorama": canvas,
                        "autoLoad": true,
                        "dynamic": true,
                        "dynamicUpdate": true,
                        "showFullscreenCtrl": false,
                        "showControls": false,
                        "horizonPitch": parseInt(array_room.h_pitch),
                        "horizonRoll": parseInt(array_room.h_roll),
                        "minHfov": 50,
                        "maxHfov": 120,
                        "yaw": parseFloat(window.currentYaw),
                        "pitch": parseFloat(window.currentPitch),
                        "hfov": 100,
                        "haov": parseInt(array_room.haov),
                        "vaov": parseInt(array_room.vaov),
                        "hotSpots": hotSpots,
                        "friction": 1,
                        "northOffset": parseInt(array_room.northOffset),
                        "compass": true,
                        "strings": {
                            "loadingLabel": window.backend_labels.loading + "...",
                        },
                    });
                    setTimeout(function() {
                        if(window.is_fullscreen) {
                            try {
                                $('#video_viewer').css('height','100%');
                            } catch (e) {}
                        } else {
                            var container_h = $('#content-wrapper').height() - 155;
                            if($('#tawk-container').length) {
                                container_h = container_h - 20;
                            }
                            if($('#plan_marker_msg').is(':visible')) {
                                container_h = container_h - $('#plan_marker_msg').height() - 10;
                            }
                            try {
                                $('#video_viewer').css('height',container_h+'px');
                            } catch (e) {}
                        }
                        viewer_marker_initialized(id_marker_add,index_marker_add);
                    },200);
                }
                var list_assets = ["background"];
                PIXI.Assets.add("background", image_url);
                PIXI.Assets.load(list_assets).then((textures) => {
                    setup_video_p(null,textures);
                });
            } else {
                $('#panorama_markers').append('<video controls playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="width: 100%;height: 600px;margin: 0 auto;" muted preload="none" crossorigin="anonymous"><source src="' + video_url + '" type="' + type_video + '"/></video>');
                if(window.is_fullscreen) {
                    try {
                        $('#video_viewer').css('height','100%');
                    } catch (e) {}
                } else {
                    var container_h = $('#content-wrapper').height() - 155;
                    if($('#tawk-container').length) {
                        container_h = container_h - 20;
                    }
                    if($('#plan_marker_msg').is(':visible')) {
                        container_h = container_h - $('#plan_marker_msg').height() - 10;
                    }
                    try {
                        $('#video_viewer').css('height',container_h+'px');
                    } catch (e) {}
                }
                window.video_viewer = videojs('video_viewer', {
                    loop: true,
                    autoload: true,
                    muted: true,
                    controls: true,
                    plugins: {
                        pannellum: {
                            "autoLoad": true,
                            "showFullscreenCtrl": false,
                            "showControls": false,
                            "horizonPitch": parseInt(array_room.h_pitch),
                            "horizonRoll": parseInt(array_room.h_roll),
                            "minHfov": 50,
                            "maxHfov": 120,
                            "yaw": parseFloat(window.currentYaw),
                            "pitch": parseFloat(window.currentPitch),
                            "hfov": 100,
                            "haov": parseInt(array_room.haov),
                            "vaov": parseInt(array_room.vaov),
                            "hotSpots": hotSpots,
                            "friction": 1,
                            "compass": true,
                            "northOffset": parseInt(array_room.northOffset),
                            "strings": {
                                "loadingLabel": window.backend_labels.loading + "...",
                            },
                        }
                    }
                });
                window.video_viewer.load();
                window.video_viewer.on('ready', function () {
                    window.video_viewer.play();
                    window.viewer = window.video_viewer.pnlmViewer;
                    window.viewer.on('load', function () {
                        viewer_marker_initialized(id_marker_add, index_marker_add);
                    });
                });
            }
        } else {
            if(window.id_room_alt_sel!=0) {
                var multires = 0;
            } else {
                var multires = parseInt(array_room.multires);
            }
            if(multires) {
                var multires_config = JSON.parse(array_room.multires_config);
                window.viewer = pannellum.viewer('panorama_markers', {
                    "type": "multires",
                    "multiRes": multires_config,
                    "backgroundColor": [1,1,1],
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(window.currentYaw),
                    "pitch": parseFloat(window.currentPitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "compass": true,
                    "northOffset": parseInt(array_room.northOffset),
                    "hotSpots": hotSpots,
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
                setTimeout(function () {
                    viewer_marker_initialized(id_marker_add,index_marker_add);
                },200);
            } else {
                if(window.s3_enabled==1) {
                    var image_url = window.s3_url+'viewer/panoramas/'+image+'?s3=1';
                } else {
                    var image_url = '../viewer/panoramas/'+image;
                }
                window.viewer = pannellum.viewer('panorama_markers', {
                    "type": "equirectangular",
                    "panorama": image_url,
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(window.currentYaw),
                    "pitch": parseFloat(window.currentPitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "compass": true,
                    "northOffset": parseInt(array_room.northOffset),
                    "hotSpots": hotSpots,
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
                window.viewer.on("load",function () {
                    viewer_marker_initialized(id_marker_add,index_marker_add);
                });
            }
            window.viewer.on('animatefinished',function () {
                if(window.viewer_initialized) {
                    var yaw = parseFloat(window.viewer.getYaw());
                    var pitch = parseFloat(window.viewer.getPitch());
                    var hfov = parseFloat(window.viewer.getHfov());
                    window.currentYaw = yaw;
                    window.currentPitch = pitch;
                    window.currentHfov = hfov;
                }
            });
        }
    }

    function correctLinePosition($container, line, id_line) {
        if($('#rooms_slider_content-container').hasClass('show') || $('#rooms_slider_app-container').hasClass('portrait')) {
            var x=0;
        } else {
            var x=-300;
        }
        line.setOptions({
            start: LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_start'), x: x, y: 0}),
            end: LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_end'), x: x, y: 0})
        });
        line.position();
    }

    window.adjust_measurements = function(edit) {
        if(window.enable_adjust_measurements) {
            const $container = $("#panorama_measures");
            if (!$container.length) return;
            for(var i=0; i<window.measures.length; i++) {
                if(window.measures[i].index_line!=='') {
                    var id_line = window.measures[i].id;
                    var visible_start = $('#measure_'+id_line+'_start').parent().css('visibility');
                    var visible_end = $('#measure_'+id_line+'_end').parent().css('visibility');
                    if(visible_start=='hidden' || visible_end=='hidden') {
                        window.measure_lines[window.measures[i].index_line].hide('none', {duration: 0});
                    } else {
                        if(edit) {
                            window.measure_lines[window.measures[i].index_line].show('none', {duration: 0});
                        } else {
                            window.measure_lines[window.measures[i].index_line].show('fade', {duration: 100});
                        }
                        correctLinePosition($container, window.measure_lines[window.measures[i].index_line],id_line);
                    }
                }
            }
        }
        if(edit) {
            $('.leader-line').css({'opacity':0.5,'pointer-events':'none'});
            $('#line_'+window.measure_id_edit).css({'opacity':1,'pointer-events':'none'});
        }
    };

    function initialize_measures(edit) {
        $('.leader-line').remove();
        for(var i=0; i<window.measures.length; i++) {
            window.measures[i].index_line = '';
        }
        window.measure_lines = [];
        var index_line = 0;
        if($('#rooms_slider_content-container').hasClass('show') || $('#rooms_slider_app-container').hasClass('portrait')) {
            var x=0;
        } else {
            var x=-300;
        }
        for(var i=0; i<window.measures.length; i++) {
            var id_line = parseInt(window.measures[i].id);
            var params = JSON.parse(window.measures[i].params);
            var label = window.measures[i].label;
            window.measures[i].index_line = index_line;
            window.measure_lines[index_line] = new LeaderLine(
                LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_start'), x: x, y: 0}),
                LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_end'), x: x, y: 0}),
                {
                    hide: true,
                    color:params.color_line,
                    size:params.line_size,
                    path:'straight',
                    startPlug:params.start_plug,
                    endPlug:params.end_plug,
                    startPlugColor:params.start_plug_color,
                    endPlugColor:params.end_plug_color,
                    startPlugSize: params.start_plug_size,
                    endPlugSize: params.end_plug_size,
                    middleLabel: LeaderLine.pathLabel(label, {color: params.color_text, fontFamily: window.viewer_font_family, fontSize: params.size_text+'px', outlineColor: params.color_outline_text})
                }
            );
            var svg = document.querySelector('body>.leader-line:last-child');
            svg.id = 'line_'+id_line;
            svg.setAttribute('visible_multiview_ids',window.measures[i].visible_multiview_ids);
            index_line++;
        }
        $("svg.leader-line").detach().appendTo(".pnlm-ui");
        $('svg.leader-line path,svg.leader-line text,svg.leader-line use').on('click',function() {
            if(!window.is_editing) {
                var svg = findUpTag($(this)[0],'svg');
                var id_line = svg.id.replace('line_','');
                $('svg.leader-line').css({'opacity':0.5});
                $('#line_'+id_line).css({'opacity':1});
                $('.measure_points').css({'opacity':0,'pointer-events':'none'});
                click_edit_measure(id_line);
            }
        });
        adjust_measurements(edit);
    }

    function findUpTag(el, tag) {
        var r = el;
        while (r.parentNode) {
            r = r.parentNode;
            if (r.tagName === tag)
                return r;
        }
        return null;
    }

    function viewer_marker_initialized(id_marker_add,index_marker_add) {
        window.viewer.setHfov(window.currentHfov,false);
        window.viewer_initialized = true;
        $('#rooms_slider_app-container').removeClass('loading');
        $('#rooms_slider_slider-container').removeClass('disabled');
        $('#rooms_slider_slider-container').removeClass('hide');
        $('.azimuth-control').removeClass('hide');
        $('.north-control').removeClass('hide');
        $('.azimuth-control').removeClass('disabled');
        $('.north-control').removeClass('disabled');
        if($('#video_viewer').length) {
            $('.azimuth-control').css('margin-bottom','30px');
            $('.north-control').css('margin-bottom','30px');
        } else {
            $('.azimuth-control').css('margin-bottom','0');
            $('.north-control').css('margin-bottom','0');
        }
        if(window.rooms_count>1) {
            check_plan(window.id_user,'marker');
            if(window.can_create) {
                $('#plan_marker_msg').addClass('d-none');
                $('#btn_add_marker').css({'opacity':1,'pointer-events':'initial'});
            } else {
                $('#plan_marker_msg').removeClass('d-none');
                $('#btn_add_marker').css({'opacity':0.3,'pointer-events':'none'});
            }
        } else {
            $('#btn_add_marker').css({'opacity':0.3,'pointer-events':'none'});
        }
        $('#btn_add_marker').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_poi').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').show();
        $('.icon_visible_view').show();
        $('#panorama_markers').append('<i class="fas fa-dot-circle center_helper"></i>');
        var poi_embed_count = $('.poi_embed').length;
        if(poi_embed_count>0) {
            init_poi_embed();
        } else {
            window.sync_poi_embed_enabled = false;
        }
        var marker_embed_count = $('.marker_embed').length;
        if(marker_embed_count>0) {
            init_marker_embed();
        } else {
            window.sync_marker_embed_enabled = false;
        }
        setTimeout(function () {
            try {
                window.viewer.reisze();
            } catch (e) {}
            try {
                window.video_viewer.pnlmViewer.resize();
            } catch (e) {}
        },100);
        if(!$('.icon_visible_view').hasClass('hidden')) {
            toggle_visible_view('marker');
        }
        $(window).trigger('resize');
        if(id_marker_add==null && window.wizard_step!=-1) {
            $('#btn_list_hs').addClass('disabled');
            $('#btn_switch_to_poi').addClass('disabled');
            $('#btn_preview_modal').addClass('disabled');
            $('#btn_toggle_fullscreen').addClass('disabled');
            $('.rooms_view_sel').addClass('disabled');
            if(window.wizard_step!=-1) {
                $('#btn_add_marker').removeClass('disabled');
                create_wizard(window.wizard_step);
                wizard_tour_open = true;
                wizard_tour.start();
            } else {
                $('#btn_add_marker').addClass('disabled');
            }
        } else if(id_marker_add!=null && window.wizard_step!=-1) {
            Shepherd.activeTour.next();
        }
        if(id_marker_add!=null && window.wizard_step==-1) {
            $('.hotspot_'+id_marker_add).trigger('click');
            if(parseInt(window.markers[index_marker_add].scale)==1) {
                render_marker(id_marker_add,index_marker_add);
            }
            $('#action_box').css('opacity',0);
            setTimeout(function() {
                move_m(id_marker_add,index_marker_add,id_marker_add);
                $('#action_box').css('opacity',1);
            },250);
            $('.center_helper').hide();
        } else {
            $('.center_helper').show();
        }
    }

    function viewer_poi_initialized(id_poi_add,index_poi_add) {
        window.viewer.setHfov(window.currentHfov,false);
        window.viewer_initialized = true;
        $('#rooms_slider_app-container').removeClass('loading');
        $('#rooms_slider_slider-container').removeClass('disabled');
        $('#rooms_slider_slider-container').removeClass('hide');
        check_plan(window.id_user,'poi');
        if(window.can_create) {
            $('#plan_poi_msg').addClass('d-none');
            $('#btn_add_poi').css({'opacity':1,'pointer-events':'initial'});
        } else {
            $('#plan_poi_msg').removeClass('d-none');
            $('#btn_add_poi').css({'opacity':0.3,'pointer-events':'none'});
        }
        $('#btn_add_poi').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_marker').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').show();
        $('.icon_visible_view').show();
        $('.div_panorama_container').append('<i class="fas fa-dot-circle center_helper"></i>');
        var poi_embed_count = $('.poi_embed').length;
        if(poi_embed_count>0) {
            init_poi_embed();
        } else {
            window.sync_poi_embed_enabled = false;
        }
        var marker_embed_count = $('.marker_embed').length;
        if(marker_embed_count>0) {
            init_marker_embed();
        } else {
            window.sync_marker_embed_enabled = false;
        }
        setTimeout(function () {
            try {
                window.viewer.reisze();
            } catch (e) {}
            try {
                window.video_viewer.pnlmViewer.resize();
            } catch (e) {}
        },100);
        if(!$('.icon_visible_view').hasClass('hidden')) {
            toggle_visible_view('poi');
        }
        $(window).trigger('resize');
        if(id_poi_add==null && window.wizard_step!=-1) {
            $('#btn_list_hs').addClass('disabled');
            $('#btn_switch_to_marker').addClass('disabled');
            $('#btn_preview_modal').addClass('disabled');
            $('#btn_toggle_fullscreen').addClass('disabled');
            $('.rooms_view_sel').addClass('disabled');
            if(window.wizard_step!=-1) {
                $('#btn_add_poi').removeClass('disabled');
                create_wizard(window.wizard_step);
                wizard_tour_open = true;
                wizard_tour.start();
            } else {
                $('#btn_add_poi').addClass('disabled');
            }
        } else if(id_poi_add!=null && window.wizard_step!=-1) {
            edit_p(id_poi_add,index_poi_add,id_poi_add);
            $('#btn_media_library').addClass('disabled');
            $('.center_helper').hide();
        }
        if(id_poi_add!=null && window.wizard_step==-1) {
            $('.hotspot_'+id_poi_add).trigger('click');
            if (window.pois[index_poi_add]) {
                const scale = window.pois[index_poi_add].scale;
                if (scale !== undefined && scale !== null && parseInt(scale) === 1) {
                    render_poi(id_poi_add, index_poi_add);
                }
            }
            $('#action_box').css('opacity',0);
            setTimeout(function() {
                move_p(id_poi_add,index_poi_add,id_poi_add);
                $('#action_box').css('opacity',1);
            },250);
            $('.center_helper').hide();
        } else {
            $('.center_helper').show();
        }
    }

    function viewer_measure_initialized(id_measure_add,index_measure_add) {
        window.viewer.setHfov(window.currentHfov,false);
        window.viewer_initialized = true;
        $('#rooms_slider_app-container').removeClass('loading');
        $('#rooms_slider_slider-container').removeClass('disabled');
        $('#rooms_slider_slider-container').removeClass('hide');
        initialize_measures(false);
        $('#plan_marker_msg').addClass('d-none');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_add_measure').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').show();
        $('.icon_visible_view').show();
        $('#panorama_measures').append('<i class="fas fa-dot-circle center_helper"></i>');
        $('.center_helper').show();
        setTimeout(function () {
            try {
                window.viewer.reisze();
            } catch (e) {}
            try {
                window.video_viewer.pnlmViewer.resize();
            } catch (e) {}
        },100);
        if(!$('.icon_visible_view').hasClass('hidden')) {
            toggle_visible_view('measure');
        }
        $(window).trigger('resize');
        if(id_measure_add!=null) {
            move_ms(id_measure_add,index_measure_add,id_measure_add);
        }
    }

    window.click_edit_marker = function(hotSpotDiv,args) {
        $('#slider_hs_list #hs_'+args).addClass('active');
        if(!window.is_editing) {
            $('.center_helper').hide();
            $('.custom-hotspot').css('opacity',0.5);
            $('.hotspot_'+args).css('opacity',1);
            jQuery.each(window.markers, function(index_m, marker_m) {
                if(marker_m.what=='marker') {
                    if(parseInt(marker_m.id)==parseInt(args)) {
                        var yaw = parseFloat(marker_m.yaw);
                        var pitch = parseFloat(marker_m.pitch);
                        var yaw_room_target = marker_m.yaw_room_target;
                        var pitch_room_target = marker_m.pitch_room_target;
                        window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200,function () {
                            setTimeout(function () {
                                adjust_marker_embed_helpers_all();
                            },200);
                            $('.move_action').attr('onclick','move_m('+args+','+index_m+',null)');
                            $('.edit_action').attr('onclick','edit_m('+args+','+index_m+',null)');
                            $('.duplicate_action').attr('onclick','modal_duplicate_marker('+args+','+window.id_room_sel+')');
                            $('.delete_action').attr('onclick','modal_delete_marker('+args+','+window.id_room_sel+',\''+window.panorama_image+'\')');
                            $('.goto_action').attr('onclick','goto_m('+args+','+index_m+',\''+yaw_room_target+'\',\''+pitch_room_target+'\')');
                            var marker_edit_label = '';
                            switch(marker_m.embed_type) {
                                case 'selection':
                                    marker_edit_label += '<i class="far fa-square"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                default:
                                    marker_edit_label += '<i class="fas fa-info-circle"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                            }
                            $('.marker_edit_label').html(marker_edit_label+' '+marker_m.name_room_target);
                            $('#action_box').show();
                        });
                        return;
                    }
                }
            });
        }
    }

    window.click_edit_poi = function(hotSpotDiv,args) {
        $('#slider_hs_list #hs_'+args).addClass('active');
        if(window.grouped_selecting) {
            var id_grouped_sel = window.pois[poi_index_edit].content;
            if(id_grouped_sel!=='' && id_grouped_sel !==undefined) {
                id_grouped_sel = id_grouped_sel.split(",");
            } else {
                id_grouped_sel = [];
            }
            $.each(window.pois,function(index_poi,poi) {
                if(poi.id==args) {
                    var exist_id_grouped_sel = id_grouped_sel.indexOf(poi.id);
                    if($('.hotspot_'+args).hasClass('grouped_sel')) {
                        $('.hotspot_'+args).removeClass('grouped_sel');
                        if (exist_id_grouped_sel!==-1) id_grouped_sel.splice(exist_id_grouped_sel,1);
                    } else {
                        $('.hotspot_'+args).addClass('grouped_sel');
                        if (exist_id_grouped_sel===-1) id_grouped_sel.push(poi.id);
                    }
                    return;
                }
            });
            $('#grouped_count').html(id_grouped_sel.length);
            id_grouped_sel = id_grouped_sel.join(",");
            window.pois[poi_index_edit].content = id_grouped_sel;
        } else if(!window.is_editing) {
            $('.center_helper').hide();
            $('.custom-hotspot-content').css('opacity',0.5);
            $('.hotspot-embed').css('opacity',0.5);
            $('.hotspot_'+args).css('opacity',1);
            $('.edit_action').removeClass('disabled');
            jQuery.each(window.pois, function(index, poi) {
                if(poi.what=='poi') {
                    if(parseInt(poi.id)==parseInt(args)) {
                        var yaw = parseFloat(poi.yaw);
                        var pitch = parseFloat(poi.pitch);
                        window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200,function () {
                            fix_all_embeds_pos();
                            $('.move_action').attr('onclick','move_p('+args+','+index+',null)');
                            $('.edit_action').attr('onclick','edit_p('+args+','+index+',null)');
                            $('.duplicate_action').removeClass('disabled');
                            $('.duplicate_action').attr('onclick','modal_duplicate_poi('+args+','+window.id_room_sel+')');
                            $('.delete_action').attr('onclick','modal_delete_poi('+args+','+window.id_room_sel+',\''+window.panorama_image+'\')');
                            var poi_edit_label = '';
                            switch(poi.embed_type) {
                                case 'image':
                                    poi_edit_label += '<i class="fas fa-image"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'video':
                                    poi_edit_label += '<i class="fab fa-youtube"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'video_transparent':
                                case 'video_chroma':
                                    poi_edit_label += '<i class="fas fa-video"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'object3d':
                                    poi_edit_label += '<i class="fas fa-cube"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'gallery':
                                    poi_edit_label += '<i class="fas fa-images"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'link':
                                    poi_edit_label += '<i class="fas fa-external-link-alt"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'text':
                                    poi_edit_label += '<i class="fas fa-heading"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'html':
                                    poi_edit_label += '<i class="fas fa-code"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'selection':
                                    poi_edit_label += '<i class="far fa-square"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                default:
                                    poi_edit_label += '<i class="fas fa-info-circle"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                            }
                            switch(poi.type) {
                                case 'image':
                                    poi_edit_label += '<i class="fas fa-image"></i> '+window.backend_labels.image;
                                    break;
                                case 'gallery':
                                    poi_edit_label += '<i class="fas fa-images"></i> '+window.backend_labels.image_gallery;
                                    break;
                                case 'video':
                                    poi_edit_label += '<i class="fab fa-youtube"></i> '+window.backend_labels.video;
                                    break;
                                case 'audio':
                                    poi_edit_label += '<i class="fas fa-music"></i> '+window.backend_labels.audio;
                                    break;
                                case 'video360':
                                    poi_edit_label += '<i class="fas fa-video"></i> '+window.backend_labels.video360;
                                    break;
                                case 'link':
                                    poi_edit_label += '<i class="fas fa-link"></i> '+window.backend_labels.link;
                                    break;
                                case 'pdf':
                                    poi_edit_label += '<i class="fas fa-file-pdf"></i> '+window.backend_labels.pdf;
                                    break;
                                case 'pointclouds':
                                    poi_edit_label += '<i class="fas fa-dice-d20"></i> '+window.backend_labels.pointclouds;
                                    break;
                                case 'link_ext':
                                    poi_edit_label += '<i class="fas fa-external-link-alt"></i> '+window.backend_labels.link_ext;
                                    break;
                                case 'html':
                                    poi_edit_label += '<i class="fas fa-heading"></i> '+window.backend_labels.html;
                                    break;
                                case 'html_sc':
                                    poi_edit_label += '<i class="fas fa-code"></i> '+window.backend_labels.html_sc;
                                    break;
                                case 'download':
                                    poi_edit_label += '<i class="fas fa-download"></i> '+window.backend_labels.download;
                                    break;
                                case 'form':
                                    poi_edit_label += '<i class="fab fa-wpforms"></i> '+window.backend_labels.form;
                                    break;
                                case 'google_maps':
                                    poi_edit_label += '<i class="fas fa-map"></i> '+window.backend_labels.google_maps;
                                    break;
                                case 'object360':
                                    poi_edit_label += '<i class="fas fa-compact-disc"></i> '+window.backend_labels.object360;
                                    break;
                                case 'object3d':
                                    poi_edit_label += '<i class="fas fa-cube"></i> '+window.backend_labels.object3d;
                                    break;
                                case 'lottie':
                                    poi_edit_label += '<i class="fab fa-deviantart"></i> Lottie';
                                    break;
                                case 'product':
                                    poi_edit_label += '<i class="fas fa-shopping-cart"></i> '+window.backend_labels.product;
                                    break;
                                case 'switch_pano':
                                    poi_edit_label += '<i class="fas fa-sync-alt"></i> '+window.backend_labels.switch_pano;
                                    break;
                                case 'callout':
                                    poi_edit_label = '<i class="far fa-dot-circle"></i> '+window.backend_labels.callout;
                                    break;
                                case 'staging':
                                    poi_edit_label = '<i class="fas fa-arrows-spin"></i> '+window.backend_labels.staging;
                                    break;
                                case 'grouped':
                                    $('.duplicate_action').addClass('disabled');
                                    var id_grouped_sel = poi.content;
                                    if(id_grouped_sel!='' && id_grouped_sel!=null) {
                                        var count_grouped = id_grouped_sel.split(",").length;
                                    } else {
                                        var count_grouped = 0;
                                    }
                                    poi_edit_label = '<i class="fas fa-braille"></i> '+window.backend_labels.grouped+' ('+count_grouped+' '+window.backend_labels.pois+')';
                                    break;
                                default:
                                    switch(poi.embed_type) {
                                        case 'image':
                                            poi_edit_label = '<i class="fas fa-image"></i> '+window.backend_labels.embed_image;
                                            break;
                                        case 'video':
                                            poi_edit_label = '<i class="fas fa-video"></i> '+window.backend_labels.embed_video;
                                            break;
                                        case 'video_transparent':
                                            poi_edit_label = '<i class="fas fa-video"></i> '+window.backend_labels.embed_video_transparent;
                                            break;
                                        case 'video_chroma':
                                            poi_edit_label = '<i class="fas fa-video"></i> '+window.backend_labels.embed_video_chroma;
                                            break;
                                        case 'object3d':
                                            poi_edit_label = '<i class="fas fa-cube"></i> '+window.backend_labels.embed_object3d;
                                            break;
                                        case 'gallery':
                                            poi_edit_label = '<i class="fas fa-images"></i> '+window.backend_labels.embed_gallery;
                                            break;
                                        case 'link':
                                            poi_edit_label = '<i class="fas fa-images"></i> '+window.backend_labels.embed_link;
                                            break;
                                        case 'text':
                                            poi_edit_label = '<i class="fas fa-heading"></i> '+window.backend_labels.embed_text;
                                            break;
                                        case 'html':
                                            poi_edit_label = '<i class="fas fa-code"></i> '+window.backend_labels.embed_html;
                                            break;
                                        case 'selection':
                                            poi_edit_label = '<i class="far fa-square"></i> '+window.backend_labels.embed_selection;
                                            break;
                                        default:
                                            if(poi.type!='callout' && poi.type!='grouped') {
                                                poi_edit_label += '<i class="fas fa-ban"></i> '+window.backend_labels.none;
                                            }
                                            break;
                                    }
                                    break;
                            }
                            $('.poi_edit_label').html(poi_edit_label);
                            $('#action_box').show();
                        });
                        return;
                    }
                }
            });
        }
    }

    var mid_point = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2];
    window.click_edit_measure = function(id) {
        $('#slider_hs_list #hs_'+id).addClass('active');
        if(!window.is_editing) {
            $('.center_helper').hide();
            $('.edit_action').removeClass('disabled');
            jQuery.each(window.measures, function(index, measure) {
                if(parseInt(measure.id)==parseInt(id)) {
                    var yaw_start = parseFloat(measure.yaw_start);
                    var pitch_start = parseFloat(measure.pitch_start);
                    var yaw_end = parseFloat(measure.yaw_end);
                    var pitch_end = parseFloat(measure.pitch_end);
                    var tmp_coords = mid_point([yaw_start,pitch_start],[yaw_end,pitch_end]);
                    var yaw = tmp_coords[0];
                    var pitch = tmp_coords[1];
                    window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200,function () {
                        $('.move_action').attr('onclick','move_ms('+id+','+index+')');
                        $('.edit_action').attr('onclick','edit_ms('+id+','+index+')');
                        $('.delete_action').attr('onclick','modal_delete_measure('+id+','+window.id_room_sel+',\''+window.panorama_image+'\')');
                        $('.measure_edit_label').html('<i class="fas fa-arrows-alt-h"></i>&nbsp;&nbsp;'+window.backend_labels.measure_label+' '+(index+1));
                        $('#action_box').show();
                    });
                    return;
                }
            });
        }
    }

    window.check_schedule = function () {
        if($('#enable_schedule').is(':checked')) {
            $('#confirm_schedule input').prop("disabled",false);
        } else {
            $('#confirm_schedule input').prop("disabled",true);
        }
        $('#enable_schedule').prop("disabled",false);
    }

    window.show_poi_confirm = function (show) {
        if(show) {
            $('.btn_confirm').show();
        } else {
            $('.btn_confirm').hide();
        }
    }

    window.show_marker_apply_style = function (show) {
        if(show && window.markers[marker_index_edit].embed_type=='') {
            $('.btn_apply_style_all').show();
            $('#exclude_from_apply_all').parent().parent().show();
        } else {
            $('.btn_apply_style_all').hide();
            $('#exclude_from_apply_all').parent().parent().hide();
        }
    }

    window.show_marker_save_goto = function (show) {
        if(show) {
            $('.btn_confirm_go').show();
        } else {
            $('.btn_confirm_go').hide();
        }
    }

    window.show_marker_apply_move = function (show) {
        if(show && window.markers[marker_index_edit].embed_type=='') {
            $('.btn_apply_move_all').show();
        } else {
            $('.btn_apply_move_all').hide();
        }
    }

    window.show_poi_apply_style = function (show) {
        if(show && window.pois[poi_index_edit].embed_type=='' && window.pois[poi_index_edit].type!='callout' && window.pois[poi_index_edit].type!='staging' && window.pois[poi_index_edit].type!='grouped') {
            $('.btn_apply_style_all').show();
            $('#exclude_from_apply_all').parent().parent().show();
        } else {
            $('.btn_apply_style_all').hide();
            $('#exclude_from_apply_all').parent().parent().hide();
        }
        if($('.lang_input_switcher').length) {
            setTimeout(function() {
                render_poi(poi_id_edit,poi_index_edit);
            },250);
        }
    }

    window.show_poi_apply_move = function (show) {
        if(show && window.pois[poi_index_edit].embed_type=='' && window.pois[poi_index_edit].type!='callout' && window.pois[poi_index_edit].type!='staging' && window.pois[poi_index_edit].type!='grouped') {
            $('.btn_apply_move_all').show();
        } else {
            $('.btn_apply_move_all').hide();
        }
    }

    window.change_switch_panorama_default = function() {
        if($('#switch_panorama_default').is(':checked')) {
            $('#frm_sp_edit').addClass('disabled');
            $('#poi_content').parent().parent().addClass('disabled');
        } else {
            $('#frm_sp_edit').removeClass('disabled');
            $('#poi_content').parent().parent().removeClass('disabled');
        }
    }

    window.edit_p = function(id,index,id_poi_add) {
        window.poi_index_edit = index;
        window.poi_id_edit = id;
        show_poi_confirm(true);
        $('.btn_apply_style_all').hide();
        $('#exclude_from_apply_all').parent().parent().hide();
        $('#action_box').hide();
        $('#rooms_slider_slider-container').addClass('hide');
        $('#rooms_slider_content-container').addClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_poi').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        close_list_hs();
        $('#btn_switch_to_marker').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').addClass('disabled');
        $('.icon_visible_view').addClass('disabled');
        $('#confirm_edit .btn_confirm').attr('onclick','confirm_edit_poi('+id+','+index+')');
        $('#confirm_edit .btn_close').attr('onclick','exit_edit_poi('+id+','+index+')');
        if(parseInt(window.pois[index].exclude_from_apply_all)==1) {
            $('#exclude_from_apply_all').prop('checked',true);
        } else {
            $('#exclude_from_apply_all').prop('checked',false);
        }
        var yaw = parseFloat(window.pois[index].yaw);
        var pitch = parseFloat(window.pois[index].pitch)+10;
        if(window.pois[index].embed_type=='') {
            window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200);
        }
        $('#id_poi_autoopen').parent().parent().removeClass('col-md-12').addClass('col-md-3');
        $('#div_form_edit').hide();
        $('#frm_edit').hide();
        $('#frm_d_edit').hide();
        $('#frm_v_edit').hide();
        $('#frm_a_edit').hide();
        $('#frm_g_edit').hide();
        $('#frm_j_edit').hide();
        $('#frm_sp_edit').hide();
        $('#frm_pdf_edit').hide();
        $('#frm_pc_edit').hide();
        $('#poi_content').parent().parent().hide();
        $('#poi_target').parent().hide();
        $('#poi_audio_params').hide();
        $('#poi_title').parent().hide();
        $('#poi_description').parent().hide();
        $('#poi_content_html').parent().parent().hide();
        $('#poi_content_html_sc').parent().hide();
        $('#btn_poi_gallery').parent().hide();
        $('.gallery_params_div').hide();
        $('#btn_poi_object360').parent().hide();
        $('#poi_gm_map').parent().hide();
        $('#poi_gm_street').parent().hide();
        $('#poi_content_product_div').hide();
        $('#id_poi_autoopen').parent().hide();
        $('#auto_close').parent().parent().hide();
        $('#view_type').parent().hide();
        $('#view_type').prop('disabled',false);
        $('#box_pos').parent().hide();
        $('#box_max_width').parent().hide();
        $('#box_maximize').parent().hide();
        $('#box_background').parent().parent().parent().hide();
        $('#box_color').parent().parent().parent().hide();
        $('#poi_gm_map').val('');
        $('#poi_gm_street').val('');
        $('#poi_content').prop('readonly',false);
        $('#switch_panorama_default').parent().hide();
        $('.callout_settings').hide();
        $('.grouped_settings').hide();
        $('#btn_preview_poi_content i').removeClass('fa-cog').addClass('fa-eye');
        $('#pills-settings-tab').show();
        $('.btn_apply_style_all').show();
        window.content_current = window.pois[index].type;
        if(window.pois[index].type=='') {
            select_poi_content_edit('none');
        } else {
            select_poi_content_edit(window.pois[index].type);
        }
        $('#poi_content').attr('data-type',window.pois[index].type);
        try {
            if(window.pois[index].embed_content.indexOf("content/") !== -1) {
                $('#btn_link_poi_embed_content').removeClass('disabled');
            } else {
                $('#btn_link_poi_embed_content').addClass('disabled');
            }
        } catch (e) {
            $('#btn_link_poi_embed_content').addClass('disabled');
        }
        switch(window.pois[index].type) {
            case 'image':
                $('#frm_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#content_label').html(window.backend_labels.content_image);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'gallery':
                $('#btn_poi_gallery').parent().show();
                $('.gallery_params_div').show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                var poi_gallery_order = 'sort';
                var gallery_transition = 'swipe';
                var gallery_thumbs = 'bottomOverMedia';
                var gallery_autoplay = false;
                var gallery_allow_download = false;
                var gallery_slide_duration = 4;
                if(window.pois[index].params!='') {
                    try {
                        var array_params = JSON.parse(window.pois[index].params);
                        if ('order' in array_params) {
                            poi_gallery_order = array_params.order;
                        }
                        if ('gallery_transition' in array_params) {
                            gallery_transition = array_params.gallery_transition;
                        }
                        if ('gallery_thumbs' in array_params) {
                            gallery_thumbs = array_params.gallery_thumbs;
                        }
                        if ('gallery_autoplay' in array_params) {
                            gallery_autoplay = array_params.gallery_autoplay;
                        }
                        if ('gallery_allow_download' in array_params) {
                            gallery_allow_download = array_params.gallery_allow_download;
                        }
                        if ('gallery_slide_duration' in array_params) {
                            gallery_slide_duration = array_params.gallery_slide_duration;
                        }
                    } catch (e) {}
                }
                if(poi_gallery_order=='random') {
                    $('#poi_gallery_random').prop('checked',true);
                } else {
                    $('#poi_gallery_random').prop('checked',false);
                }
                $("#g_transition option[id='"+gallery_transition+"']").prop("selected", true);
                $("#g_thumbs option[id='"+gallery_thumbs+"']").prop("selected", true);
                if(parseInt(gallery_autoplay)==1) {
                    $('#g_autoplay').prop('checked',true);
                    $('#g_slide_duration').parent().removeClass('disabled');
                } else {
                    $('#g_autoplay').prop('checked',false);
                    $('#g_slide_duration').parent().addClass('disabled');
                }
                if(parseInt(gallery_allow_download)==1) {
                    $('#g_download').prop('checked',true);
                } else {
                    $('#g_download').prop('checked',false);
                }
                $('#g_slide_duration').val(gallery_slide_duration);
                break;
            case 'video':
                $('#frm_v_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#content_label').html(window.backend_labels.content_video);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'audio':
                $('#frm_a_edit').show();
                $('#poi_content').parent().parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#id_poi_autoopen').parent().parent().removeClass('col-md-3').addClass('col-md-12');
                $('#poi_audio_params').show();
                $('#content_label').html(window.backend_labels.content_audio);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_song_bg_volume').val(parseFloat(window.pois[index].song_bg_volume));
                $("#poi_song_player option").prop("selected", false);
                $("#poi_song_player option[id='"+window.pois[index].params+"']").prop("selected", true);
                change_poi_song_bg_volume();
                change_poi_song_player(false);
                $('#poi_title').val('');
                $('#poi_description').val('');
                break;
            case 'video360':
                $('#frm_v_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#content_label').html(window.backend_labels.content_video360);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'link':
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#content_label').html(window.backend_labels.content_link);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'pdf':
                $('#frm_pdf_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#content_label').html(window.backend_labels.content_pdf);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'pointclouds':
                $('#frm_pc_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                window.pois[index].view_type = 0;
                $('#view_type').prop('disabled',true);
                $('#btn_preview_poi_content i').removeClass('fa-eye').addClass('fa-cog');
                $('#content_label').html(window.backend_labels.content_pointclouds);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'link_ext':
                $('#poi_content').parent().parent().show();
                $('#poi_target').parent().show();
                $('#id_poi_autoopen').parent().parent().removeClass('col-md-3').addClass('col-md-12');
                $('#content_label').html(window.backend_labels.content_link_ext);
                $('#poi_content').val(window.pois[index].content);
                $("#poi_target option").prop("selected", false);
                $("#poi_target option[id='"+window.pois[index].target+"']").prop("selected", true);
                $('#poi_title').val('');
                $('#poi_description').val('');
                break;
            case 'html':
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#auto_close').parent().parent().show();
                $('#poi_content_html').parent().parent().show();
                $('#poi_content_html').parent().find('.ql-toolbar').remove();
                $('#poi_content_html').html(window.pois[index].content).promise().done(function () {
                    var toolbarOptions = [
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'align': [] }],['link'],
                        ['clean']
                    ];
                    window.html_editor = new Quill('#poi_content_html', {
                        modules: {
                            toolbar: toolbarOptions
                        },
                        theme: 'snow',
                        bounds: document.getElementById('confirm_edit')
                    });
                });
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'html_sc':
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#poi_content_html_sc').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                try {
                    window.poi_content_html_sc.destroy();
                } catch (e) {}
                window.poi_content_html_sc = ace.edit('poi_content_html_sc');
                window.poi_content_html_sc.session.setMode("ace/mode/html");
                window.poi_content_html_sc.setOption('enableLiveAutocompletion',true);
                window.poi_content_html_sc.setShowPrintMargin(false);
                if($('body').hasClass('dark_mode')) {
                    window.poi_content_html_sc.setTheme("ace/theme/one_dark");
                }
                if(window.rtl==1) {
                    window.poi_content_html_sc.setOption("rtl", true);
                }
                window.poi_content_html_sc.setValue(window.pois[index].content,-1);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'download':
                $('#frm_d_edit').show();
                $('#poi_content').parent().parent().show();
                $('#id_poi_autoopen').parent().parent().removeClass('col-md-3').addClass('col-md-12');
                $('#content_label').html(window.backend_labels.content_file);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val('');
                $('#poi_description').val('');
                break;
            case 'form':
                var content = window.pois[index].content;
                try {
                    content = JSON.parse(content);
                    $('#form_title').val(content[0].title);
                    $('#form_button').val(content[0].button);
                    $('#form_response').val(content[0].response);
                    $('#form_description').val(content[0].description);
                    if(content[0].background==null) content[0].background = 'rgba(255,255,255,1.0)';
                    $("#form_background").spectrum("set", content[0].background);
                    if(content[0].color==null) content[0].color = '#000000';
                    $('#form_color').spectrum("set", content[0].color);
                    if(content[0].background_button==null) content[0].background_button = '#000000';
                    $('#form_background_button').spectrum("set", content[0].background_button);
                    if(content[0].color_button==null) content[0].color_button = '#ffffff';
                    $('#form_color_button').spectrum("set", content[0].color_button);
                    if(content[0].privacy_policy==null) content[0].privacy_policy = false;
                    if(content[0]['privacy_policy']) {
                        $('#form_privacy_policy').prop('checked',true);
                    } else {
                        $('#form_privacy_policy').prop('checked',false);
                    }
                    if(content[0]['send_email']) {
                        $('#form_send_email').prop('checked',true);
                    } else {
                        $('#form_send_email').prop('checked',false);
                    }
                    $('#form_email').val(content[0].email);
                    if(content[0].webhook_url==null) content[0].webhook_url = '';
                    $('#form_webhook_url').val(content[0].webhook_url);
                    for(var i=1;i<=10;i++) {
                        if(content[i]['enabled']) {
                            $('#form_field_'+i).prop('checked',true);
                            $('#field_div_'+i).css('opacity',1);
                        } else {
                            $('#form_field_'+i).prop('checked',false);
                            $('#field_div_'+i).css('opacity',0.6);
                        }
                        if(content[i]['required']) {
                            $('#form_field_required_'+i).prop('checked',true);
                        } else {
                            $('#form_field_required_'+i).prop('checked',false);
                        }
                        $('#form_field_type_'+i+' option[id=\''+content[i]['type']+'\']').prop('selected',true);
                        $('#form_field_label_'+i).val(content[i]['label']);
                    }
                } catch (e) {
                    $("#form_background").spectrum("set", 'rgba(255,255,255,1.0)');
                    $('#form_color').spectrum("set", '#000000');
                    $('#form_background_button').spectrum("set", '#000000');
                    $('#form_color_button').spectrum("set", '#ffffff');
                }
                $('#poi_title').val('');
                $('#poi_description').val('');
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#div_form_edit').show();
                break;
            case 'google_maps':
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#poi_gm_map').parent().show();
                $('#poi_gm_street').parent().show();
                if((window.pois[index].content == null) || (window.pois[index].content.length === 0)) {
                    var gm_map = '';
                    var gm_street = '';
                } else {
                    var gm_map = window.pois[index].content.split('|')[0];
                    var gm_street = window.pois[index].content.split('|')[1];
                }
                $('#poi_gm_map').val(gm_map);
                $('#poi_gm_street').val(gm_street);
                $('#poi_content').val('');
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'object360':
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#btn_poi_object360').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'object3d':
                $('#frm_g_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $("#params_ar option").prop("selected", false);
                $("#params_interaction option").prop("selected", false);
                if(window.pois[index].params!='') {
                    var params_array = window.pois[index].params.split(",");
                    var placement = params_array[0];
                    if(params_array[1]!==undefined) {
                        var interaction = params_array[1];
                    } else {
                        var interaction = 1;
                    }
                    if(params_array[2]!==undefined) {
                        var exposure = params_array[2];
                    } else {
                        var exposure = 1;
                    }
                    if(params_array[3]!==undefined) {
                        var environment = params_array[3];
                    } else {
                        var environment = 'legacy';
                    }
                    if(params_array[5]!==undefined) {
                        var autorotate = params_array[5];
                    } else {
                        var autorotate = 'auto-rotate';
                    }
                    if(params_array[6]!==undefined) {
                        var disable_zoom = params_array[6];
                    } else {
                        var disable_zoom = 'disable-zoom';
                    }
                    if(params_array[7]!==undefined) {
                        var disable_pan = params_array[7];
                    } else {
                        var disable_pan = 'disable-pan';
                    }
                } else {
                    var placement = 0;
                    var interaction = 1;
                    var exposure = 1;
                    var environment = 'legacy';
                    var autorotate = 'auto-rotate';
                    var disable_zoom = 'disable-zoom';
                    var disable_pan = 'disable-pan';
                }
                if(autorotate=='auto-rotate') {
                    $('#params_autorotate').prop('checked',true);
                } else {
                    $('#params_autorotate').prop('checked',false);
                }
                if(disable_zoom=='disable-zoom') {
                    $('#params_zoom').prop('checked',false);
                } else {
                    $('#params_zoom').prop('checked',true);
                }
                if(disable_pan=='disable-pan') {
                    $('#params_pan').prop('checked',false);
                } else {
                    $('#params_pan').prop('checked',true);
                }
                $("#params_ar option[id='"+placement+"']").prop("selected", true);
                $("#params_interaction option[id='"+interaction+"']").prop("selected", true);
                $("#params_environment option[id='"+environment+"']").prop("selected", true);
                $('#params_exposure').val(exposure);
                $('#params_exposure_label').html(exposure);
                $('#content_label').html(window.backend_labels.content_object3d);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                var selectElement = document.getElementById("params_animation");
                var options = selectElement.getElementsByTagName("option");
                selectElement.classList.add('disabled');
                for (var i = options.length - 1; i >= 0; i--) {
                    if (options[i].id !== "none") {
                        selectElement.remove(i);
                    }
                }
                if(window.pois[index].content!='') {
                    window.modelViewer_o.src='img/test.jpg';
                    setTimeout(function() {
                        window.modelViewer_o.src=((window.s3_enabled) ? window.s3_url+'viewer/' : '../viewer/')+window.pois[index].content;
                    },500);
                }
                break;
            case 'lottie':
                $('#frm_j_edit').show();
                $('#poi_content').parent().parent().show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#content_label').html(window.backend_labels.content_lottie);
                $('#poi_content').val(window.pois[index].content);
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                break;
            case 'product':
                $('#poi_content_product_div').show();
                $('#poi_title').parent().show();
                $('#poi_description').parent().show();
                $('#id_poi_autoopen').parent().show();
                $('#auto_close').parent().parent().show();
                $('#view_type').parent().show();
                $('#box_pos').parent().show();
                $('#box_max_width').parent().show();
                $('#box_maximize').parent().show();
                $('#box_background').parent().parent().parent().show();
                $('#box_color').parent().parent().parent().show();
                $('#poi_title').val(window.pois[index].title);
                $('#poi_description').val(window.pois[index].description);
                if(window.pois[index].content!='') {
                    $("#poi_content_product option").prop("selected", false);
                    $("#poi_content_product option[id='" + window.pois[index].content + "']").prop("selected", true);
                    $('#poi_content_product').selectpicker('refresh');
                    $('#poi_content_product').selectpicker('val', window.pois[index].content);
                } else {
                    $('#poi_content_product').selectpicker('refresh');
                }
                break;
            case 'switch_pano':
                $('#content_label').html(window.backend_labels.content_panorama_image);
                $('#switch_panorama_id').val(window.pois[index].content);
                $('#poi_content').val(window.pois[index].switch_panorama_image);
                $('#poi_content').prop('readonly',true);
                $('#poi_content').parent().parent().show();
                $('#frm_sp_edit').show();
                $('#switch_panorama_default').parent().show();
                if(window.pois[index].content!='' && parseInt(window.pois[index].content)==0) {
                    $('#switch_panorama_default').prop('checked',true);
                    $('#frm_sp_edit').addClass('disabled');
                    $('#poi_content').parent().parent().addClass('disabled');
                } else {
                    $('#switch_panorama_default').prop('checked',false);
                    $('#frm_sp_edit').removeClass('disabled');
                    $('#poi_content').parent().parent().removeClass('disabled');
                }
                break;
            case 'callout':
                var json_callout = window.pois[index].params;
                var array_callout = JSON.parse(json_callout);
                $('#callout_title').val(array_callout.title);
                $('#callout_description').parent().find('.ql-toolbar').remove();
                $('#callout_description').html(array_callout.description).promise().done(function() {
                    var toolbarOptions = [
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'align': [] }],['link'],['image'],
                        ['clean']
                    ];
                    window.callout_description_editor = new Quill('#callout_description', {
                        modules: {
                            toolbar: toolbarOptions
                        },
                        theme: 'snow',
                        bounds: document.getElementById('confirm_edit')
                    });
                    window.callout_description_editor.on('text-change', function(delta, oldDelta, source) {
                        change_callout_params();
                    });
                });
                $('#callout_title_font_size').val(array_callout.title_font_size);
                $('#callout_title_margin').val(array_callout.title_margin);
                $("#callout_title_font_color").spectrum("set", array_callout.title_font_color);
                $("#callout_title_bg_color").spectrum("set", array_callout.title_bg_color);
                $('#callout_description_font_size').val(array_callout.description_font_size);
                $("#callout_description_font_color").spectrum("set", array_callout.description_font_color);
                $("#callout_dir option").prop("selected", false);
                $("#callout_dir option[id='"+array_callout.dir+"']").prop("selected", true);
                $('#callout_rotate').val(array_callout.rotate);
                $('#callout_content_width').val(array_callout.content_width);
                $('#callout_content_height').val(array_callout.content_height);
                $("#callout_main_color").spectrum("set", array_callout.main_color);
                $('#callout_line_size').val(array_callout.line_size);
                $("#callout_open option").prop("selected", false);
                $("#callout_open option[id='"+array_callout.open+"']").prop("selected", true);
                $("#callout_content_bg_color").spectrum("set", array_callout.content_bg_color);
                setTimeout(function() {
                    open_callout(poi_id_edit);
                },250);
                $('.callout_settings').show();
                break;
            case 'staging':
                var staging_items = window.pois[index].staging_items;
                populate_staging_items_table(staging_items);
                $('.btn_apply_style_all').hide();
                $('#id_poi_autoopen').parent().show();
                $('.staging_settings').show();
                break;
            case 'grouped':
                window.grouped_selecting = true;
                $('#pills-settings-tab').hide();
                $('.btn_apply_style_all').hide();
                $('.grouped_settings').show();
                var params = window.pois[index].params;
                if(params=='') {
                    var grouped_open = 0;
                    var grouped_delay = 0;
                    var hide_when_open = 0;
                } else {
                    params = params.split(",");
                    grouped_open = params[0];
                    grouped_delay = params[1];
                    if(params[2]==undefined) {
                        hide_when_open = 0;
                    } else {
                        hide_when_open = params[2];
                    }
                }
                if(grouped_open==1) {
                    $('#grouped_open').prop('checked',true);
                } else {
                    $('#grouped_open').prop('checked',false);
                }
                if(hide_when_open==1) {
                    $('#grouped_hide_when_open').prop('checked',true);
                } else {
                    $('#grouped_hide_when_open').prop('checked',false);
                }
                $('#grouped_delay').val(grouped_delay);
                var grouped_count = 0;
                var id_grouped_pois = window.pois[index].content.split(",")
                $.each(window.pois,function(index_poi,poi) {
                    if(poi.what=='poi' && poi.type!='grouped' && index_poi!=index) {
                        if(id_grouped_pois.includes(poi.id)) {
                            $('.hotspot_'+poi.id).addClass('grouped_sel');
                            grouped_count++;
                        }
                    }
                });
                $('#grouped_count').html(grouped_count);
                break;
        }
        var poi_css = $('#poi_css_class').parent().parent().detach();
        if(window.pois[index].type=='callout') {
            $('.callout_settings .row').append(poi_css);
        } else {
            $('.poi_block_div').prepend(poi_css);
        }
        if(window.id_poi_autoopen==id) {
            $('#id_poi_autoopen').prop('checked',true);
        } else {
            $('#id_poi_autoopen').prop('checked',false);
        }
        $("#view_type option").prop("selected", false);
        $("#view_type option[id='"+window.pois[index].view_type+"']").prop("selected", true);
        $("#box_pos option").prop("selected", false);
        $("#box_pos option[id='"+window.pois[index].box_pos+"']").prop("selected", true);
        if(parseInt(window.pois[index].box_maximize)==1) {
            $('#box_maximize').prop('checked',true);
        } else {
            $('#box_maximize').prop('checked',false);
        }
        $('#box_max_width').val(window.pois[index].box_max_width);
        $('#box_background').val(window.pois[index].box_background);
        $('#box_color').val(window.pois[index].box_color);
        if(window.pois[index].view_type==0) {
            $('#box_pos').prop('disabled',true);
            $('#box_max_width').prop('disabled',true);
            $('#box_maximize').prop('disabled',true);
        } else {
            $('#box_pos').prop('disabled',false);
            $('#box_max_width').prop('disabled',false);
            $('#box_maximize').prop('disabled',false);
        }
        $('#auto_close').val(window.pois[index].auto_close);
        if(parseInt(window.pois[index].learning)==1) {
            $('#learning').prop('checked',true);
        } else {
            $('#learning').prop('checked',false);
        }
        $('#learning_priority').val(window.pois[index].learning_priority);
        $('#frm_edit_e').hide();
        $('#frm_v_edit_e').hide();
        $('#frm_td_edit_e').hide();
        $('#frm_v_edit_e_s').hide();
        $('#poi_embed_content').parent().parent().hide();
        $('#poi_embed_content_html').parent().parent().hide();
        $('#poi_embed_content_html_sc').parent().hide();
        $('#poi_style').parent().parent().parent().show();
        $('#poi_color').parent().parent().parent().show();
        $('#poi_border_px').parent().parent().hide();
        $('#poi_background').parent().parent().parent().show();
        $('#poi_label').parent().parent().show();
        $('#poi_icon_type').parent().parent().show();
        $('#btn_poi_embed_gallery').parent().parent().parent().hide();
        $('#poi_embed_content_html').parent().find('.ql-toolbar').remove();
        $('#btn_background_removal').parent().parent().hide();
        $('#embed_video_autoplay').parent().parent().removeClass('col-md-3').addClass('col-md-4');
        $('#embed_video_muted').parent().parent().removeClass('col-md-3').addClass('col-md-4');
        $('#embed_video_loop').parent().parent().removeClass('col-md-3').addClass('col-md-4');
        $('#poi_color').parent().parent().removeClass('disabled');
        $('#poi_background').parent().parent().removeClass('disabled');
        $('#poi_icon_type').parent().parent().removeClass('disabled');
        $('#poi_color_label').html(window.backend_labels.color);
        if(window.pois[index].type=='callout') {
            window.embed_type_current = 'callout';
        } else if(window.pois[index].type=='grouped') {
            window.embed_type_current = 'grouped';
        } else {
            window.embed_type_current = window.pois[index].embed_type;
        }
        switch(window.pois[index].embed_type) {
            case 'image':
                select_poi_style_edit('embed_image');
                $('#frm_edit_e').show();
                $('#poi_embed_content').parent().parent().show();
                $('#embed_content_label').html(window.backend_labels.content_image_embed);
                $('#poi_embed_content').val(window.pois[index].embed_content);
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                break;
            case 'gallery':
                select_poi_style_edit('embed_gallery');
                $('#embed_gallery_autoplay').val(parseInt(window.pois[index].embed_gallery_autoplay));
                $('#btn_poi_embed_gallery').parent().parent().parent().show();
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                var poi_embed_gallery_order = 'sort';
                if(window.pois[index].embed_params!='') {
                    try {
                        var json = JSON.parse(window.pois[index].embed_params);
                        poi_embed_gallery_order = json.order;
                    } catch (e) {}
                }
                if(poi_embed_gallery_order=='random') {
                    $('#poi_embed_gallery_random').prop('checked',true);
                } else {
                    $('#poi_embed_gallery_random').prop('checked',false);
                }
                break;
            case 'video':
                select_poi_style_edit('embed_video');
                if(parseInt(window.pois[index].embed_video_autoplay)==1) {
                    $('#embed_video_autoplay').prop('checked',true);
                } else {
                    $('#embed_video_autoplay').prop('checked',false);
                }
                if(parseInt(window.pois[index].embed_video_muted)==1) {
                    $('#embed_video_muted').prop('checked',true);
                } else {
                    $('#embed_video_muted').prop('checked',false);
                }
                if(parseInt(window.pois[index].embed_video_loop)==1) {
                    $('#embed_video_loop').prop('checked',true);
                } else {
                    $('#embed_video_loop').prop('checked',false);
                }
                $('#label_mp4').show();
                $('#label_webm_mov').hide();
                window.video_ext_sel = 'mp4';
                $('.ml_btn').attr('onclick',"open_modal_media_library('videos','poi_embed_content');return false;");
                $('#frm_v_edit_e').attr('action','ajax/upload_content_video.php?e=mp4');
                $('#frm_v_edit_e').show();
                $('#frm_v_edit_e_s').show();
                $('#poi_embed_content').parent().parent().show();
                $('#embed_content_label').html(window.backend_labels.content_video_embed);
                $('#poi_embed_content').val(window.pois[index].embed_content);
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                break;
            case 'object3d':
                select_poi_style_edit('embed_object3d');
                $('#frm_td_edit_e').show();
                $('#poi_embed_content').parent().parent().show();
                $('#embed_content_label').html(window.backend_labels.content_object3d_emb);
                $('#poi_embed_content').val(window.pois[index].embed_content);
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                $("#object3d_interaction option").prop('selected',false);
                $("#object3d_environment option").prop('selected',false);
                if(window.pois[index].embed_params!='') {
                    var tmp = window.pois[index].embed_params.split(",");
                    if(tmp[1]!==undefined) {
                        var interaction = parseInt(tmp[1]);
                    } else {
                        var interaction = 0;
                    }
                    if(tmp[2]!==undefined) {
                        var exposure = parseFloat(tmp[2]);
                    } else {
                        var exposure = 1;
                    }
                    if(tmp[3]!==undefined) {
                        var environment = tmp[3];
                    } else {
                        var environment = 'legacy';
                    }
                    if(tmp[4]!==undefined) {
                        var shadow_intensity = parseFloat(tmp[4]);
                    } else {
                        var shadow_intensity = 1;
                    }
                    if(tmp[5]!==undefined) {
                        var shadow_softness = parseFloat(tmp[5]);
                    } else {
                        var shadow_softness = 0.5;
                    }
                    $("#object3d_interaction option[id='"+interaction+"']").prop('selected',true);
                    $("#object3d_environment option[id='"+environment+"']").prop('selected',true);
                    $('#object3d_exposure').val(exposure);
                    $('#object3d_exposure_label').html(exposure);
                    $('#object3d_shadow_intensity').val(shadow_intensity);
                    $('#object3d_shadow_intensity_label').html(shadow_intensity);
                    $('#object3d_shadow_softness').val(shadow_softness);
                    $('#object3d_shadow_softness_label').html(shadow_softness);
                } else {
                    $("#object3d_interaction option[id='0']").prop('selected',true);
                    $("#object3d_environment option[id='legacy']").prop('selected',true);
                    $('#object3d_exposure').val(1);
                    $('#object3d_exposure_label').html(1);
                    $('#object3d_shadow_intensity').val(1);
                    $('#object3d_shadow_intensity_label').html(1);
                    $('#object3d_shadow_softness').val(0.5);
                    $('#object3d_shadow_softness_label').html(0.5);
                }
                var selectElement = document.getElementById("object3d_animation");
                var options = selectElement.getElementsByTagName("option");
                selectElement.classList.add('disabled');
                for (var i = options.length - 1; i >= 0; i--) {
                    if (options[i].id !== "none") {
                        selectElement.remove(i);
                    }
                }
                if(window.pois[index].embed_content!='') {
                    window.modelViewer_o_e.src='img/test.jpg';
                    setTimeout(function() {
                        window.modelViewer_o_e.src=((window.s3_enabled) ? window.s3_url+'viewer/' : '../viewer/')+window.pois[index].embed_content;
                    },500);
                }
                break;
            case 'video_chroma':
                select_poi_style_edit('embed_video_chroma');
                if(parseInt(window.pois[index].embed_video_autoplay)==1) {
                    $('#embed_video_autoplay').prop('checked',true);
                } else {
                    $('#embed_video_autoplay').prop('checked',false);
                }
                if(parseInt(window.pois[index].embed_video_muted)==1) {
                    $('#embed_video_muted').prop('checked',true);
                } else {
                    $('#embed_video_muted').prop('checked',false);
                }
                if(parseInt(window.pois[index].embed_video_loop)==1) {
                    $('#embed_video_loop').prop('checked',true);
                } else {
                    $('#embed_video_loop').prop('checked',false);
                }
                $('#label_mp4').show();
                $('#label_webm_mov').hide();
                window.video_ext_sel = 'mp4';
                $('.ml_btn').attr('onclick',"open_modal_media_library('videos','poi_embed_content');return false;");
                $('#frm_v_edit_e').attr('action','ajax/upload_content_video.php?e=mp4');
                $('#frm_v_edit_e').show();
                $('#frm_v_edit_e_s').show();
                $('#poi_embed_content').parent().parent().show();
                $('#embed_content_label').html(window.backend_labels.content_video_embed_chroma);
                $('#poi_embed_content').val(window.pois[index].embed_content);
                var params = window.pois[index].params;
                if(params=='') { params = '0,255,0,0'; }
                var array_params = params.split(",");
                var bg_color = 'rgb('+array_params[0]+','+array_params[1]+','+array_params[2]+')';
                $('#chroma_color').val(bg_color);
                $("#chroma_color").spectrum("set", bg_color);
                $('#chroma_tolerance').val(array_params[3]);
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                $('#btn_background_removal').parent().parent().show();
                $('#embed_video_autoplay').parent().parent().removeClass('col-md-4').addClass('col-md-3');
                $('#embed_video_muted').parent().parent().removeClass('col-md-4').addClass('col-md-3');
                $('#embed_video_loop').parent().parent().removeClass('col-md-4').addClass('col-md-3');
                break;
            case 'video_transparent':
                select_poi_style_edit('embed_video_transparent');
                if(parseInt(window.pois[index].embed_video_autoplay)==1) {
                    $('#embed_video_autoplay').prop('checked',true);
                } else {
                    $('#embed_video_autoplay').prop('checked',false);
                }
                if(parseInt(window.pois[index].embed_video_muted)==1) {
                    $('#embed_video_muted').prop('checked',true);
                } else {
                    $('#embed_video_muted').prop('checked',false);
                }
                if(parseInt(window.pois[index].embed_video_loop)==1) {
                    $('#embed_video_loop').prop('checked',true);
                } else {
                    $('#embed_video_loop').prop('checked',false);
                }
                $('#label_mp4').hide();
                $('#label_webm_mov').show();
                window.video_ext_sel = 'webm_mov';
                $('.ml_btn').attr('onclick',"open_modal_media_library('videos_transparent','poi_embed_content');return false;");
                $('#frm_v_edit_e').attr('action','ajax/upload_content_video.php?e=webm_mov');
                $('#frm_v_edit_e').show();
                $('#frm_v_edit_e_s').show();
                $('#poi_embed_content').parent().parent().show();
                $('#embed_content_label').html(window.backend_labels.content_video_embed_transparent);
                $('#poi_embed_content').val(window.pois[index].embed_content);
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                break;
            case 'selection':
                select_poi_style_edit('embed_selection');
                $('#frm_edit_e').hide();
                $('#poi_embed_content').parent().parent().hide();
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().show();
                $('#poi_background').parent().parent().parent().show();
                $('#poi_border_px').parent().parent().show();
                $('#poi_border_px').val(window.pois[index].embed_content.replace('border-width:','').replace('px;',''));
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                $('#poi_color_label').html(window.backend_labels.border_color);
                break;
            case 'link':
                select_poi_style_edit('embed_link');
                $('#frm_edit_e').hide();
                $('#poi_embed_content').parent().parent().show();
                $('#embed_content_label').html(window.backend_labels.content_link_emb);
                $('#poi_embed_content').val(window.pois[index].embed_content);
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                break;
            case 'html':
                select_poi_style_edit('embed_html');
                $('#frm_edit_e').hide();
                $('#poi_embed_content').parent().parent().hide();
                $('#poi_embed_content_html_sc').parent().show();
                try {
                    window.poi_embed_content_html_sc.destroy();
                } catch (e) {}
                window.poi_embed_content_html_sc = ace.edit('poi_embed_content_html_sc');
                window.poi_embed_content_html_sc.session.setMode("ace/mode/html");
                window.poi_embed_content_html_sc.setOption('enableLiveAutocompletion',true);
                window.poi_embed_content_html_sc.setShowPrintMargin(false);
                if($('body').hasClass('dark_mode')) {
                    window.poi_embed_content_html_sc.setTheme("ace/theme/one_dark");
                }
                if(window.rtl==1) {
                    window.poi_embed_content_html_sc.setOption("rtl", true);
                }
                window.poi_embed_content_html_sc.setValue(window.pois[index].embed_content,-1);
                window.poi_embed_content_html_sc.getSession().on('change', function() {
                    window.pois[index].embed_content = window.poi_embed_content_html_sc.getValue();
                    render_poi(id,index);
                });
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().hide();
                $('#poi_background').parent().parent().parent().hide();
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                break;
            case 'text':
                select_poi_style_edit('embed_text');
                $('#frm_edit_e').hide();
                $('#poi_embed_content').parent().parent().hide();
                $('#poi_embed_content_html').parent().parent().show();
                $('#poi_embed_content_html').parent().find('.ql-toolbar').remove();
                $('#poi_embed_content_html').html(window.pois[index].embed_content.split(' border-width:')[0]).promise().done(function () {
                    var toolbarOptions = [
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'align': [] }],['link'],
                        ['clean']
                    ];
                    window.poi_embed_content_html_editor = new Quill('#poi_embed_content_html', {
                        modules: {
                            toolbar: toolbarOptions
                        },
                        theme: 'snow',
                        bounds: document.getElementById('confirm_edit')
                    });
                    window.poi_embed_content_html_editor.on('text-change', function(delta, oldDelta, source) {
                        window.pois[index].embed_content = window.poi_embed_content_html_editor.root.innerHTML+' border-width:'+$('#poi_border_px').val()+'px;';;
                        render_poi(id,index);
                    });
                });
                $('#poi_style').parent().parent().parent().hide();
                $('#poi_color').parent().parent().parent().show();
                $('#poi_background').parent().parent().parent().show();
                $('#poi_border_px').parent().parent().show();
                var border_width = window.pois[index].embed_content.split(' border-width:')[1].replace('px;','');
                if(border_width=='') border_width=0;
                $('#poi_border_px').val(border_width);
                $('#poi_label').parent().parent().hide();
                $('#poi_icon_type').parent().parent().hide();
                $('#poi_color_label').html(window.backend_labels.border_color);
                break;
            default:
                switch(window.pois[index].type) {
                    case 'callout':
                        $('#poi_style').parent().parent().parent().hide();
                        $('#poi_color').parent().parent().parent().hide();
                        $('#poi_background').parent().parent().parent().hide();
                        $('#poi_icon_type').parent().parent().hide();
                        $('#poi_label').parent().parent().hide();
                        select_poi_style_edit('callout');
                        break;
                    case 'staging':
                        $('#poi_background').parent().parent().hide();
                        $('#poi_animation').parent().parent().hide();
                        $('#poi_icon_type').parent().parent().hide();
                        $('#poi_label').parent().parent().hide();
                        $('#poi_sound').parent().parent().hide();
                        $('#exclude_from_apply_all').parent().parent().hide();
                        select_poi_style_edit('icon');
                        break;
                    default:
                        select_poi_style_edit('icon');
                        break;
                }
                break;
        }
        $('#poi_color').val(window.pois[index].color);
        $("#poi_color").spectrum("set", window.pois[index].color);
        $('#poi_background').val(window.pois[index].background);
        $("#poi_background").spectrum("set", window.pois[index].background);
        $('#poi_css_class').val(window.pois[index].css_class);
        $('#poi_icon_preview')[0].className = window.pois[index].icon;
        $('#poi_icon').val(window.pois[index].icon);
        $('#poi_label').val(window.pois[index].label);
        $("#poi_style option").prop("selected", false);
        switch(window.pois[index].type) {
            case 'staging':
                $('#poi_style option[id="0"]').prop('selected',true);
                $('#poi_style').prop('disabled',true);
                break;
            default:
                $('#poi_style').prop('disabled',false);
                $("#poi_style option[id='"+window.pois[index].style+"']").prop("selected", true);
                break;
        }
        $("#poi_icon_type option").prop("selected", false);
        $("#poi_icon_type option[id='"+window.pois[index].icon_type+"']").prop("selected", true);
        $("#poi_animation option").prop("selected", false);
        $("#poi_animation option[id='"+window.pois[index].animation+"']").prop("selected", true);
        $("#poi_sound option").prop("selected", false);
        $("#poi_sound option[id='"+window.pois[index].sound+"']").prop("selected", true);
        if((window.pois[index].style==0) || (window.pois[index].style==1)) {
            $("#poi_label").parent().addClass('disabled');
            $('.input_lang[data-target-id="poi_label"]').parent().addClass('disabled');
        }
        $("#tooltip_type").prop("selected", false);
        $("#tooltip_type option[id='"+window.pois[index].tooltip_type+"']").prop("selected", true);
        $("#tooltip_visibility").prop("selected", false);
        $("#tooltip_visibility option[id='"+window.pois[index].tooltip_visibility+"']").prop("selected", true);
        $("#tooltip_background").spectrum("set", window.pois[index].tooltip_background);
        $("#tooltip_color").spectrum("set", window.pois[index].tooltip_color);
        $("#box_background").spectrum("set", window.pois[index].box_background);
        $("#box_color").spectrum("set", window.pois[index].box_color);
        $('#tooltip_text_html').css('background-color',window.pois[index].tooltip_background);
        $('#tooltip_text_html').css('color',window.pois[index].tooltip_color);
        $('#tooltip_text_html').parent().find('.ql-toolbar').remove();
        $('#tooltip_text_html').html(window.pois[index].tooltip_text).promise().done(function () {
            var toolbarOptions = [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'align': [] }],
                ['clean']
            ];
            window.tooltip_text_editor = new Quill('#tooltip_text_html', {
                modules: {
                    toolbar: toolbarOptions
                },
                theme: 'snow',
                bounds: document.getElementById('confirm_edit')
            });
        });
        $('#tooltip_text_mobile_html').css('background-color',window.pois[index].tooltip_background);
        $('#tooltip_text_mobile_html').css('color',window.pois[index].tooltip_color);
        $('#tooltip_text_mobile_html').parent().find('.ql-toolbar').remove();
        $('#tooltip_text_mobile_html').html(window.pois[index].tooltip_text_mobile).promise().done(function () {
            var toolbarOptions = [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'align': [] }],
                ['clean']
            ];
            window.tooltip_text_mobile_editor = new Quill('#tooltip_text_mobile_html', {
                modules: {
                    toolbar: toolbarOptions
                },
                theme: 'snow',
                bounds: document.getElementById('confirm_edit')
            });
        });
        if($('.lang_input_switcher').length) {
            var url = new URL(location.href);
            var url_params = new URLSearchParams(url.search);
            var page_section = url_params.get('p');
            $('.lang_input_switcher').each(function() {
                var elem_o = $(this).attr('data-elem');
                var lang_o = $(this).attr('data-default-lang');
                var lang_l = sessionStorage.getItem('lang_'+window.id_virtualtour+'_'+page_section);
                if(lang_l===null) {
                    lang_l=lang_o;
                }
                switch_input_language(lang_l,lang_o,elem_o);
            });
            setTimeout(function() {
                render_poi(id,index);
            },250);
        }
        $('.input_lang[data-target-id="tooltip_text_html"]').html('');
        $('.input_lang[data-target-id="tooltip_text_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var id_l = $(this).attr('id');
            $('#'+id_l).css('background-color',window.pois[index].tooltip_background);
            $('#'+id_l).css('color',window.pois[index].tooltip_color);
            $('#'+id_l).parent().find('.ql-toolbar').remove();
            var html = '';
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    html = item_lang.tooltip_text;
                }
            });
            $('#'+id_l).html(html).promise().done(function () {
                var toolbarOptions = [
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'align': [] }],
                    ['clean']
                ];
                window.tooltip_text_editor_lang[lang] = new Quill('#'+id_l, {
                    modules: {
                        toolbar: toolbarOptions
                    },
                    theme: 'snow',
                    bounds: document.getElementById('confirm_edit')
                });
            });
        });
        $('.input_lang[data-target-id="tooltip_text_mobile_html"]').html('');
        $('.input_lang[data-target-id="tooltip_text_mobile_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var id_l = $(this).attr('id');
            $('#'+id_l).css('background-color',window.pois[index].tooltip_background);
            $('#'+id_l).css('color',window.pois[index].tooltip_color);
            $('#'+id_l).parent().find('.ql-toolbar').remove();
            var html = '';
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    html = item_lang.tooltip_text_mobile;
                }
            });
            $('#'+id_l).html(html).promise().done(function () {
                var toolbarOptions = [
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'align': [] }],
                    ['clean']
                ];
                window.tooltip_text_mobile_editor_lang[lang] = new Quill('#'+id_l, {
                    modules: {
                        toolbar: toolbarOptions
                    },
                    theme: 'snow',
                    bounds: document.getElementById('confirm_edit')
                });
            });
        });
        $('.input_lang[data-target-id="poi_label"]').each(function() {
            var lang = $(this).attr('data-lang');
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    $('.input_lang[data-target-id="poi_label"][data-lang="'+lang+'"]').val(item_lang.label);
                }
            });
        });
        $('.input_lang[data-target-id="poi_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    $('.input_lang[data-target-id="poi_title"][data-lang="'+lang+'"]').val(item_lang.title);
                }
            });
        });
        $('.input_lang[data-target-id="poi_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    $('.input_lang[data-target-id="poi_description"][data-lang="'+lang+'"]').val(item_lang.description);
                }
            });
        });
        $('.input_lang[data-target-id="poi_embed_content"]').val('');
        switch(window.pois[index].embed_type) {
            case 'image':
            case 'video':
            case 'video_transparent':
            case 'link':
            case 'object3d':
                $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    var html = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            html = item_lang.embed_content;
                        }
                    });
                    $('#'+id_l).val(html);
                });
                break;
            case 'video_chroma':
                $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    var html = '';
                    var params = '0,255,0,0';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            html = item_lang.embed_content;
                            params = item_lang.params;
                        }
                    });
                    $('#'+id_l).val(html);
                    var array_params = params.split(",");
                    var bg_color = 'rgb('+array_params[0]+','+array_params[1]+','+array_params[2]+')';
                    $('#chroma_color_'+lang).val(bg_color);
                    $("#chroma_color_"+lang).spectrum("set", bg_color);
                    $('#chroma_tolerance_'+lang).val(array_params[3]);
                });
                break;
            case 'text':
                $('.input_lang[data-target-id="poi_embed_content_html"]').html('');
                $('.input_lang[data-target-id="poi_embed_content_html"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    $('#'+id_l).parent().find('.ql-toolbar').remove();
                    var html = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            if(item_lang.embed_content!='') {
                                html = item_lang.embed_content.split(' border-width:')[0];
                            }
                        }
                    });
                    $('#'+id_l).html(html).promise().done(function () {
                        var toolbarOptions = [
                            ['bold', 'italic', 'underline', 'strike'],
                            [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            [{ 'color': [] }, { 'background': [] }],
                            [{ 'align': [] }],['link'],
                            ['clean']
                        ];
                        window.poi_embed_content_html_editor_lang[lang] = new Quill('#'+id_l, {
                            modules: {
                                toolbar: toolbarOptions
                            },
                            theme: 'snow',
                            bounds: document.getElementById('confirm_edit')
                        });
                        window.poi_embed_content_html_editor_lang[lang].on('text-change', function(delta, oldDelta, source) {
                            render_poi(id,index);
                        });
                    });
                });
                break;
            case 'html':
                $('.input_lang[data-target-id="poi_embed_content_html_sc"]').html('');
                $('.input_lang[data-target-id="poi_embed_content_html_sc"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    var html = '';
                    jQuery.each(window.pois[index].array_lang, function (index_l, item_lang) {
                        if (item_lang.language == lang) {
                            if (item_lang.embed_content != '' && item_lang.embed_content != null) {
                                html = item_lang.embed_content;
                            }
                        }
                    });
                    try {
                        window.poi_embed_content_html_sc_lang[lang].destroy();
                    } catch (e) {}
                    window.poi_embed_content_html_sc_lang[lang] = ace.edit(id_l);
                    window.poi_embed_content_html_sc_lang[lang].session.setMode("ace/mode/html");
                    window.poi_embed_content_html_sc_lang[lang].setOption('enableLiveAutocompletion',true);
                    window.poi_embed_content_html_sc_lang[lang].setShowPrintMargin(false);
                    if($('body').hasClass('dark_mode')) {
                        window.poi_embed_content_html_sc_lang[lang].setTheme("ace/theme/one_dark");
                    }
                    if(window.rtl==1) {
                        window.poi_embed_content_html_sc_lang[lang].setOption("rtl", true);
                    }
                    if(html!='') window.poi_embed_content_html_sc_lang[lang].setValue(html,-1);
                    window.poi_embed_content_html_sc_lang[lang].getSession().on('change', function() {
                        render_poi(id,index);
                    });
                });
                break;
        }
        $('.input_lang[data-target-id="poi_content"]').val('');
        switch(window.pois[index].type) {
            case 'image':
            case 'pdf':
            case 'download':
            case 'video':
            case 'video360':
            case 'lottie':
            case 'audio':
            case 'object3d':
            case 'pointclouds':
            case 'link':
            case 'link_ext':
                $('.input_lang[data-target-id="poi_content"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    var html = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            html = item_lang.content;
                        }
                    });
                    $('#'+id_l).val(html);
                });
                break;
            case 'google_maps':
                $('.input_lang[data-target-id="poi_gm_map"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var content_l = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            content_l = item_lang.content;
                        }
                    });
                    if((content_l == null) || (content_l.length === 0)) {
                        var gm_map = '';
                        var gm_street = '';
                    } else {
                        var gm_map = content_l.split('|')[0];
                        var gm_street = content_l.split('|')[1];
                    }
                    $('#poi_gm_map_'+lang).val(gm_map);
                    $('#poi_gm_street_'+lang).val(gm_street);
                });
                break;
            case 'html':
                $('.input_lang[data-target-id="poi_content_html"]').html('');
                $('.input_lang[data-target-id="poi_content_html"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    $('#'+id_l).parent().find('.ql-toolbar').remove();
                    var html = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            html = item_lang.content;
                        }
                    });
                    $('#'+id_l).html(html).promise().done(function () {
                        var toolbarOptions = [
                            ['bold', 'italic', 'underline', 'strike'],
                            [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            [{ 'color': [] }, { 'background': [] }],
                            [{ 'align': [] }],['link'],
                            ['clean']
                        ];
                        window.html_editor_lang[lang] = new Quill('#'+id_l, {
                            modules: {
                                toolbar: toolbarOptions
                            },
                            theme: 'snow',
                            bounds: document.getElementById('confirm_edit')
                        });
                    });
                });
                break;
            case 'html_sc':
                $('.input_lang[data-target-id="poi_content_html_sc"]').html('');
                $('.input_lang[data-target-id="poi_content_html_sc"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    var html = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            html = item_lang.content;
                        }
                    });
                    try {
                        window.poi_content_html_sc_lang[lang].destroy();
                    } catch (e) {}
                    window.poi_content_html_sc_lang[lang] = ace.edit(id_l);
                    window.poi_content_html_sc_lang[lang].session.setMode("ace/mode/html");
                    window.poi_content_html_sc_lang[lang].setOption('enableLiveAutocompletion',true);
                    window.poi_content_html_sc_lang[lang].setShowPrintMargin(false);
                    if($('body').hasClass('dark_mode')) {
                        window.poi_content_html_sc_lang[lang].setTheme("ace/theme/one_dark");
                    }
                    if(window.rtl==1) {
                        window.poi_content_html_sc_lang[lang].setOption("rtl", true);
                    }
                    if(html!=null) window.poi_content_html_sc_lang[lang].setValue(html,-1);
                });
                break;
            case 'form':
                $('.input_lang[data-target-id="form_title"]').val('');
                $('.input_lang[data-target-id="form_button"]').val('');
                $('.input_lang[data-target-id="form_response"]').val('');
                $('.input_lang[data-target-id="form_description"]').val('');
                $('.input_lang[data-target-id="form_title"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            var form_content = JSON.parse(item_lang.content);
                            if(form_content.length>0) {
                                $('.input_lang[data-target-id="form_title"][data-lang="'+lang+'"]').val(form_content[0]['title']);
                                $('.input_lang[data-target-id="form_button"][data-lang="'+lang+'"]').val(form_content[0]['button']);
                                $('.input_lang[data-target-id="form_response"][data-lang="'+lang+'"]').val(form_content[0]['response']);
                                $('.input_lang[data-target-id="form_description"][data-lang="'+lang+'"]').val(form_content[0]['description']);
                                for(var i=1;i<=10;i++) {
                                    $('.input_lang[data-target-id="form_field_label_'+i+'"][data-lang="'+lang+'"]').val(form_content[i]['label']);
                                }
                            }
                        }
                    });
                });
                break;
            case 'callout':
                $('.input_lang[data-target-id="callout_title"]').val('');
                $('.input_lang[data-target-id="callout_description"]').html('');
                $('.input_lang[data-target-id="callout_description"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var id_l = $(this).attr('id');
                    $('#'+id_l).parent().find('.ql-toolbar').remove();
                    var array_callout_lang = {};
                    array_callout_lang.title = '';
                    array_callout_lang.description = '';
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            if(item_lang.params!=null && item_lang.params!='') {
                                array_callout_lang = JSON.parse(item_lang.params);
                            }
                        }
                    });
                    $('.input_lang[data-target-id="callout_title"][data-lang="'+lang+'"]').val(array_callout_lang.title);
                    $('#'+id_l).html(array_callout_lang.description).promise().done(function () {
                        var toolbarOptions = [
                            ['bold', 'italic', 'underline', 'strike'],
                            [{ 'size': ['12px','14px','16px','18px','24px','28px','32px','40px','48px','56px','64px','72px'] }],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            [{ 'color': [] }, { 'background': [] }],
                            [{ 'align': [] }],['link'],['image'],
                            ['clean']
                        ];
                        window.callout_description_editor_lang[lang] = new Quill('#'+id_l, {
                            modules: {
                                toolbar: toolbarOptions
                            },
                            theme: 'snow',
                            bounds: document.getElementById('confirm_edit')
                        });
                        window.callout_description_editor_lang[lang].on('text-change', function(delta, oldDelta, source) {
                            change_callout_params();
                        });
                    });
                });
                break;
        }
        change_tooltip_type_p();
        $('#poi_library_icon').val(window.pois[index].id_icon_library);
        if(window.pois[index].style==1) {
            var image = window.pois[index].img_icon_library;
            var id_vt_library = window.pois[index].id_vt_library;
            if(window.s3_enabled==1 && id_vt_library!='') {
                var image_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
            } else {
                var image_url = '../viewer/icons/'+image;
            }
            var ext = image.split('.').pop().toLowerCase();
            if(ext=='json') {
                var html_image = '<div id="lottie_preview_'+window.poi_id_edit+'" style="height:30px;width:30px;vertical-align:middle"></div>';
                $('#poi_library_icon_preview_l').html(html_image).promise().done(function () {
                    $('#poi_library_icon_preview_l').css('display','inline-block');
                    bodymovin.loadAnimation({
                        container: document.getElementById('lottie_preview_'+window.poi_id_edit),
                        renderer: 'svg',
                        loop: true,
                        autoplay: true,
                        path: image_url,
                        rendererSettings: {
                            progressiveLoad: true,
                        }
                    });
                });
                $('#poi_library_icon_preview').hide();
            } else {
                $('#poi_library_icon_preview').attr('src',image_url);
                $('#poi_library_icon_preview').show();
                $('#poi_library_icon_preview_l').hide();
            }
        }
        var schedule = window.pois[index].schedule;
        if(schedule!='' && schedule!=null) {
            schedule = JSON.parse(schedule);
            $('#enable_schedule').prop('checked',true);
            $('#date_from').val(schedule.from_date);
            $('#date_to').val(schedule.to_date);
            $('#hour_from').val(schedule.from_hour);
            $('#hour_to').val(schedule.to_hour);
            var days = schedule.days;
            var days_array = days.split(",");
            if(days_array[0]==1) $("#days_1").prop('checked',true); else $("#days_1").prop('checked',false);
            if(days_array[1]==1) $("#days_2").prop('checked',true); else $("#days_2").prop('checked',false);
            if(days_array[2]==1) $("#days_3").prop('checked',true); else $("#days_3").prop('checked',false);
            if(days_array[3]==1) $("#days_4").prop('checked',true); else $("#days_4").prop('checked',false);
            if(days_array[4]==1) $("#days_5").prop('checked',true); else $("#days_5").prop('checked',false);
            if(days_array[5]==1) $("#days_6").prop('checked',true); else $("#days_6").prop('checked',false);
            if(days_array[6]==1) $("#days_7").prop('checked',true); else $("#days_7").prop('checked',false);
            $('#confirm_schedule input').prop("disabled",false);
        } else {
            $('#enable_schedule').prop('checked',false);
            $('#date_from').val('');
            $('#date_to').val('');
            $('#hour_from').val('');
            $('#hour_to').val('');
            $("#days_1").prop('checked',false);
            $("#days_2").prop('checked',false);
            $("#days_3").prop('checked',false);
            $("#days_4").prop('checked',false);
            $("#days_5").prop('checked',false);
            $("#days_6").prop('checked',false);
            $("#days_7").prop('checked',false);
            $('#confirm_schedule input').prop("disabled",true);
        }
        $('#enable_schedule').prop("disabled",false);
        if(window.pois[index].embed_type=='' && window.pois[index].type!='callout') {
            change_poi_style();
            $('#poi_song_player').parent().removeClass('disabled');
        } else {
            $('#poi_song_player').parent().addClass('disabled');
        }
        $('#edit-tab a[href="#pills-tooltip"]').removeClass('disabled');
        if(window.pois[index].type=='' || window.pois[index].type=='callout') {
            $('#edit-tab a[href="#pills-edit"]').addClass('disabled');
            if(window.pois[index].type=='callout') {
                $('#edit-tab a[href="#pills-tooltip"]').addClass('disabled');
            }
        } else {
            $('#edit-tab a[href="#pills-edit"]').removeClass('disabled');
        }
        if(id_poi_add!=null && window.pois[index].embed_type!='') {
            $('#edit-tab a[href="#pills-style"]').tab('show');
            show_poi_apply_style(true);
        } else {
            if(window.pois[index].type=='' || window.pois[index].type=='callout') {
                $('#edit-tab a[href="#pills-style"]').tab('show');
                show_poi_apply_style(true);
            } else {
                $('#edit-tab a[href="#pills-edit"]').tab('show');
            }
        }
        $('#confirm_edit').show();
        maximize_box_edit();
        window.is_editing = true;
    }

    function populate_staging_items_table(staging_items) {
        $('#staging_table tbody').empty();
        var i_s = 1;
        $.each(staging_items, function(index_s,staging_item) {
            var tr_s = '<tr>';
            tr_s += '<td>';
            if(window.s3_enabled==1) {
                var image_s_url = window.s3_url+'viewer/staging/'+staging_item.icon+'?s3=1';
            } else {
                var image_s_url = '../viewer/staging/'+staging_item.icon;
            }
            if(staging_item.default==1) {
                var style_default_s = 'text-decoration:underline;';
            } else {
                var style_default_s = '';
            }
            tr_s += '<img style="witdh:40px;height:30px;border-radius:50%;" src="'+image_s_url+'" />&nbsp;&nbsp;<span style="'+style_default_s+'">'+staging_item.tooltip+'</span>';
            tr_s += '</td>';
            tr_s += '<td style="text-align: right;width:110px;">\n' +
                '<button onclick="open_modal_staging(\'update\','+staging_item.id+')" class="btn btn-warning btn-sm"><i class="fas fa-edit"></i></button>\n' +
                '<button onclick="delete_poi_staging('+staging_item.id+');" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>\n' +
                '</td>';
            tr_s += '</ts>';
            $('#staging_table tbody').append(tr_s);
            i_s++;
        });
        if(i_s>=12) {
            $('#staging_table tfoot .btn').addClass('disabled');
        } else {
            $('#staging_table tfoot .btn').removeClass('disabled');
        }
    }

    window.open_modal_staging = function(mode,id) {
        window.mode_staging = mode;
        reset_modal_staging();
        switch(mode) {
            case 'new':
                if(window.pois[poi_index_edit].staging_items.length==0) {
                    $('#staging_item_default').prop('checked',true);
                    $('#staging_item_default').prop('disabled',true);
                    $('#staging_item_default_msg').show();
                } else {
                    $('#staging_item_default').prop('disabled',false);
                }
                $('#btn_save_staging_item').html('<i class="fas fa-plus"></i> '+window.backend_labels.add);
                $('#btn_save_staging_item').attr('onclick','save_staging_item(null)');
                break;
            case 'update':
                $.each(window.pois[poi_index_edit].staging_items, function(index_s,staging_item) {
                    if(staging_item.id==id) {
                        $('#staging_item_name').val(staging_item.tooltip);
                        if(parseInt(staging_item.default)==1) {
                            $('#staging_item_default').prop('checked',true);
                            $('#staging_item_default').prop('disabled',true);
                            $('#staging_item_default_msg').show();
                        } else {
                            $('#staging_item_default').prop('disabled',false);
                        }
                        if(window.s3_enabled==1) {
                            var icon = window.s3_url+'viewer/staging/'+staging_item.icon+'?s3=1';
                            var image = window.s3_url+'viewer/staging/'+staging_item.image+'?s3=1';
                        } else {
                            var icon = '../viewer/staging/'+staging_item.icon;
                            var image = '../viewer/staging/'+staging_item.image;
                        }
                        $('#image_preview_icon_staging img').attr('src',icon);
                        $('#image_preview_image_staging img').attr('src',image);
                        $('#image_preview_icon_staging').show();
                        $('#image_preview_image_staging').show();
                        $('#img_staging_room').show();
                        $('.input_lang[data-target-id="staging_item_name"]').each(function() {
                            var lang = $(this).attr('data-lang');
                            jQuery.each(staging_item.array_lang, function(index_l,item_lang) {
                                if(item_lang.language==lang) {
                                    $('.input_lang[data-target-id="staging_item_name"][data-lang="'+lang+'"]').val(item_lang.tooltip);
                                    $('.input_lang[data-target-id="staging_item_name"][data-lang="'+lang+'"]').attr('placeholder',staging_item.tooltip);
                                }
                            });
                        });
                    }
                });
                $('#btn_save_staging_item').html('<i class="fas fa-save"></i> '+window.backend_labels.save);
                $('#btn_save_staging_item').attr('onclick','save_staging_item('+id+')');
                break;
        }
        $('#modal_staging_item').modal('show');
    }

    function reset_modal_staging() {
        $('#error_vsi').hide();
        $('#error_vso').hide();
        $('#progressBar_vsi').parent().hide();
        $('#progressBar_vso').parent().hide();
        $('#image_preview_icon_staging img').attr('src','');
        $('#image_preview_image_staging img').attr('src','');
        $('#image_preview_icon_staging').hide();
        $('#image_preview_image_staging').hide();
        $('#img_staging_room').hide();
        $('#staging_item_name').val('');
        $('.input_lang[data-target-id="staging_item_name"]').val('');
        $('.input_lang[data-target-id="staging_item_name"]').attr('placeholder','');
        switch_input_language(window.default_language,window.default_language,'staging_item_name',false);
        $('#staging_item_default_msg').hide();
        $('#staging_item_default').prop('checked',false);
    }

    window.save_staging_item = function(id) {
        var tooltip = $('#staging_item_name').val();
        var default_s = ($('#staging_item_default').is(':checked')) ? 1 : 0;
        var icon = $('#image_preview_icon_staging img').attr('src');
        icon = icon ? icon.split('/').pop() : null;
        var image = $('#image_preview_image_staging img').attr('src');
        image = image ? image.split('/').pop() : null;
        var complete = true;
        if(tooltip=='') {
            $('#staging_item_name').addClass('error-highlight');
            complete = false;
        } else {
            $('#staging_item_name').removeClass('error-highlight');
        }
        var array_lang = {};
        array_lang['tooltip'] = {};
        $('.input_lang[data-target-id="staging_item_name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['tooltip'][lang]=value;
        });
        if(icon==null) {
            $('#frm_vsi .custom-file').addClass('error-highlight');
            complete = false;
        } else {
            $('#frm_vsi .custom-file').removeClass('error-highlight');
        }
        if(image==null) {
            $('#frm_vso .custom-file').addClass('error-highlight');
            complete = false;
        } else {
            $('#frm_vso .custom-file').removeClass('error-highlight');
        }
        if(complete) {
            $('#modal_staging_item .modal-footer .btn').addClass('disabled');
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/save_poi_staging.php",
                type: "POST",
                data: {
                    id: id,
                    id_poi: window.poi_id_edit,
                    tooltip: tooltip,
                    default: default_s,
                    icon: icon,
                    image: image,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        window.pois[poi_index_edit].staging_items = rsp.staging_items;
                        populate_staging_items_table(rsp.staging_items);
                        $('#modal_staging_item').modal('hide');
                    }
                    $('#modal_staging_item .modal-footer .btn').removeClass('disabled');
                },
                error: function() {
                    $('#modal_staging_item .modal-footer .btn').removeClass('disabled');
                }
            });
        }
    }

    window.delete_poi_staging = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_poi_staging.php",
                type: "POST",
                data: {
                    id: id,
                    id_poi: window.poi_id_edit
                },
                async: false,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        window.pois[poi_index_edit].staging_items = rsp.staging_items;
                        populate_staging_items_table(rsp.staging_items);
                    }
                },
                error: function() {}
            });
        } else {
            return false;
        }
    }

    window.change_exposure_m = function() {
        var exposure = $('#object3d_exposure').val();
        $('#object3d_'+window.poi_id_edit).attr('exposure',exposure);
        $('#object3d_exposure_label').html(exposure);
    }

    window.change_shadow_intensity = function() {
        var shadow_intensity = $('#object3d_shadow_intensity').val();
        $('#object3d_'+window.poi_id_edit).attr('shadow-intensity',shadow_intensity);
        $('#object3d_shadow_intensity_label').html(shadow_intensity);
    }

    window.change_shadow_softness = function() {
        var shadow_softness = $('#object3d_shadow_softness').val();
        $('#object3d_'+window.poi_id_edit).attr('shadow-softness',shadow_softness);
        $('#object3d_shadow_softness_label').html(shadow_softness);
    }

    window.change_exposure = function() {
        var exposure = $('#params_exposure').val();
        $('#params_exposure_label').html(exposure);
    }

    window.change_animation = function() {
        var animation = $('#object3d_animation option:selected').attr('id');
        var model = document.querySelector('#object3d_'+window.poi_id_edit);
        if(animation=='none') {
            model.setAttribute('autoplay','false');
            model.setAttribute('animation-name','');
            try {
                model.pause();
            } catch (e) {}
        } else {
            model.setAttribute('autoplay','true');
            model.setAttribute('animation-name',animation);
            try {
                model.play();
            } catch (e) {}
        }
    }

    window.change_object3d_zoom = function() {
        var zoom = $('#object3d_zoom').val();
        if(zoom==80) {
            render_poi(window.poi_id_edit,window.poi_index_edit);
            $('#object3d_zoom_value').html('auto');
        } else {
            var zoom_deg = 180 - zoom;
            $('#object3d_'+window.poi_id_edit).attr('min-field-of-view',zoom_deg+'deg');
            $('#object3d_'+window.poi_id_edit).attr('max-field-of-view',zoom_deg+'deg');
            $('#object3d_zoom_value').html(zoom-80);
        }
    }

    window.change_environment = function() {
        var environment = $('#object3d_environment option:selected').attr('id');
        if(environment=='panorama') {
            if(window.s3_enabled==1) {
                environment = window.s3_url+'viewer/panoramas/lowres/'+window.panorama_image+'?s3=1';
            } else {
                environment = '../viewer/panoramas/lowres/'+window.panorama_image;
            }
        }
        $('#object3d_'+window.poi_id_edit).attr('environment-image',environment);
    }

    window.open_background_removal = function() {
        $('#confirm_edit').hide();
        $('#confirm_background_removal').show();
        $('.poi_embed_'+poi_id_edit).css('pointer-events','none');
        setTimeout(function() {
            window.video_chroma.play();
        },500);
    }

    window.close_background_removal = function() {
        $('#confirm_edit').show();
        $('#confirm_background_removal').hide();
        var params = window.pois_initial[poi_index_edit].params;
        if(params=='') { params = '0,255,0,0'; }
        var array_params = params.split(",");
        var bg_color = 'rgb('+array_params[0]+','+array_params[1]+','+array_params[2]+')';
        $('#chroma_color').val(bg_color);
        $("#chroma_color").spectrum("set", bg_color);
        $('#chroma_tolerance').val(array_params[3]);
        remove_background_video_chroma(video_chroma,ctx_chroma_tmp,ctx_chroma,width_chroma,height_chroma,params,true);
        window.video_chroma.pause();
        window.video_chroma.currentTime=0;
        $('.poi_embed_'+poi_id_edit).css('pointer-events','initial');
    }

    window.play_chroma_video = function() {
        window.video_chroma.currentTime=0;
        window.video_chroma.play();
    }

    window.confirm_background_removal = function() {
        $('#confirm_edit').show();
        $('#confirm_background_removal').hide();
        $('.poi_embed_'+poi_id_edit).css('pointer-events','initial');
        window.video_chroma.pause();
        window.video_chroma.currentTime=0;
    }

    window.change_poi_border_px = function () {
        switch(window.pois[window.poi_index_edit].embed_type) {
            case 'selection':
                window.pois[window.poi_index_edit].embed_content = 'border-width:'+$('#poi_border_px').val()+'px;';
                break;
            case 'text':
                window.pois[window.poi_index_edit].embed_content = window.poi_embed_content_html_editor.root.innerHTML+' border-width:'+$('#poi_border_px').val()+'px;';
                break;
        }
        render_poi(window.poi_id_edit,window.poi_index_edit);
    }

    window.change_poi_icon_type = function () {
        window.pois[window.poi_index_edit].icon_type = $('#poi_icon_type option:selected').attr('id');
        render_poi(window.poi_id_edit,window.poi_index_edit);
    }

    window.change_marker_icon_type = function () {
        window.markers[window.marker_index_edit].icon_type = $('#marker_icon_type option:selected').attr('id');
        render_marker(window.marker_id_edit,window.marker_index_edit);
    }

    window.change_marker_border_px = function () {
        switch(window.markers[window.marker_index_edit].embed_type) {
            case 'selection':
                window.markers[window.marker_index_edit].embed_content = 'border-width:'+$('#marker_border_px').val()+'px;';
                break;
        }
        render_marker(window.marker_id_edit,window.marker_index_edit);
    }

    window.edit_poi_gallery = function() {
        $("#modal_images_gallery .modal-body").html('').promise().done(function () {
            $("#modal_images_gallery .modal-body").load('poi_gallery.php?id_poi='+window.poi_id_edit);
            $('#modal_images_gallery').modal('show');
        });
    }

    window.edit_poi_embed_gallery = function() {
        $("#modal_images_gallery .modal-body").html('').promise().done(function () {
            $("#modal_images_gallery .modal-body").load('poi_embed_gallery.php?id_poi='+window.poi_id_edit);
            $('#modal_images_gallery').modal('show');
        });
    }

    window.edit_poi_object360 = function() {
        $("#modal_images_gallery .modal-body").html('').promise().done(function () {
            $("#modal_images_gallery .modal-body").load('poi_object360.php?id_poi='+window.poi_id_edit);
            $('#modal_images_gallery').modal('show');
        });
    }

    window.change_exclude_apply_all = function(p) {
        var k = ($('#exclude_from_apply_all').is(':checked')) ? 1 : 0;
        switch(p) {
            case 'marker':
                var id = window.marker_id_edit;
                window.markers[marker_index_edit].exclude_from_apply_all=k;
                break;
            case 'poi':
                var id = window.poi_id_edit;
                window.pois[poi_index_edit].exclude_from_apply_all=k;
                break;
        }
        $.ajax({
            url: "ajax/change_exclude_apply_all.php",
            type: "POST",
            data: {
                p: p,
                id: id,
                k: k
            },
            async: false,
            success: function (rsp) {}
        });
    }

    window.edit_m = function(id,index,id_marker_add) {
        window.marker_index_edit = index;
        window.marker_id_edit = id;
        $('.btn_apply_style_all').hide();
        $('#exclude_from_apply_all').parent().parent().hide();
        $('#action_box').hide();
        $('#rooms_slider_slider-container').addClass('hide');
        $('#rooms_slider_content-container').addClass('show');
        fix_all_embeds_pos();
        $('.azimuth-control').addClass('disabled');
        $('.north-control').addClass('disabled');
        $(window).trigger('resize');
        $('#btn_add_marker').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        close_list_hs();
        $('#btn_switch_to_poi').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').addClass('disabled');
        $('.icon_visible_view').addClass('disabled');
        $('#confirm_edit .btn_confirm').addClass("disabled");
        $('#confirm_edit .btn_confirm_go').addClass("disabled");
        $('#confirm_edit .btn_confirm_go').show();
        $('#confirm_edit .btn_confirm').attr('onclick','confirm_edit_marker('+id+','+index+',false)');
        $('#confirm_edit .btn_confirm_go').attr('onclick','confirm_edit_marker('+id+','+index+',true)');
        $('#confirm_edit .btn_close').attr('onclick','exit_edit_marker('+id+','+index+')');
        if(parseInt(window.markers[index].exclude_from_apply_all)==1) {
            $('#exclude_from_apply_all').prop('checked',true);
        } else {
            $('#exclude_from_apply_all').prop('checked',false);
        }
        var yaw = parseFloat(window.markers[index].yaw);
        var pitch = parseFloat(window.markers[index].pitch)+10;
        if(window.markers[index].embed_type=='') {
            window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200);
        }
        var yaw_m = window.markers[index].yaw_room_target;
        var pitch_m = window.markers[index].pitch_room_target;
        var yaw_look_m = window.markers[index].yaw_look_room_target;
        var pitch_look_m = window.markers[index].pitch_look_room_target;
        var duration_look_m = window.markers[index].duration_look_room_target;
        if((yaw_m=='') && (pitch_m=='')) {
            $('#override_pos_edit').prop('checked',false);
        } else {
            $('#override_pos_edit').prop('checked',true);
        }
        var event = new Event('change');
        $('#override_pos_edit')[0].dispatchEvent(event);
        if((yaw_look_m=='') && (pitch_look_m=='')) {
            $('#override_look_edit').prop('checked',false);
        } else {
            $('#override_look_edit').prop('checked',true);
        }
        var event = new Event('change');
        $('#override_look_edit')[0].dispatchEvent(event);
        $('#duration_look_edit').val(duration_look_m);
        get_option_rooms_target('room_target',window.id_room_sel,window.markers[index].id_room_target,id,index);
        $('#marker_color').parent().parent().removeClass('disabled');
        $('#marker_icon_type').parent().parent().removeClass('disabled');
        $('#marker_background').parent().parent().removeClass('disabled');
        window.embed_type_current = window.markers[index].embed_type;
        switch(window.markers[index].embed_type) {
            case 'selection':
                select_marker_style_edit('embed_selection');
                $('#marker_label').parent().parent().hide();
                $('#marker_style').parent().parent().parent().hide();
                $('#marker_color').parent().parent().parent().show();
                $('#marker_background').parent().parent().parent().show();
                $('#marker_border_px').parent().parent().show();
                $('#marker_border_px').val(window.markers[index].embed_content.replace('border-width:','').replace('px;',''));
                $('#marker_icon_type').parent().parent().hide();
                $('#marker_color_label').html(window.backend_labels.border_color);
                break;
            default:
                select_marker_style_edit('icon');
                $('#marker_label').parent().parent().show();
                $('#marker_style').parent().parent().parent().show();
                $('#marker_color').parent().parent().parent().show();
                $('#marker_background').parent().parent().parent().show();
                $('#marker_border_px').parent().parent().hide();
                $('#marker_border_px').val('');
                $('#marker_icon_type').parent().parent().show();
                $('#marker_color_label').html(window.backend_labels.color);
                break;
        }
        $("#lookat").prop("selected", false);
        $("#lookat option[id='"+window.markers[index].lookat+"']").prop("selected", true);
        $('#marker_color').val(window.markers[index].color);
        $("#marker_color").spectrum("set", window.markers[index].color);
        $('#marker_background').val(window.markers[index].background);
        $("#marker_background").spectrum("set", window.markers[index].background);
        $('#marker_css_class').val(window.markers[index].css_class);
        $('#marker_icon_preview')[0].className = window.markers[index].icon;
        $('#marker_icon').val(window.markers[index].icon);
        $('#marker_label').val(window.markers[index].label);
        $("#marker_style").prop("selected", false);
        $("#marker_style option[id='"+window.markers[index].show_room+"']").prop("selected", true);
        $("#marker_icon_type option").prop("selected", false);
        $("#marker_icon_type option[id='"+window.markers[index].icon_type+"']").prop("selected", true);
        $("#marker_sound option").prop("selected", false);
        $("#marker_sound option[id='"+window.markers[index].sound+"']").prop("selected", true);
        $("#marker_animation option").prop("selected", false);
        $("#marker_animation option[id='"+window.markers[index].animation+"']").prop("selected", true);
        $("#tooltip_type").prop("selected", false);
        $("#tooltip_type option[id='"+window.markers[index].tooltip_type+"']").prop("selected", true);
        $("#tooltip_visibility").prop("selected", false);
        $("#tooltip_visibility option[id='"+window.markers[index].tooltip_visibility+"']").prop("selected", true);
        $("#tooltip_background").spectrum("set", window.markers[index].tooltip_background);
        $("#tooltip_color").spectrum("set", window.markers[index].tooltip_color);
        if((window.markers[index].show_room!=6) && (window.markers[index].show_room!=7) && (window.markers[index].show_room!=8)) {
            $("#marker_label").parent().addClass('disabled');
            $('.input_lang[data-target-id="marker_label"]').parent().addClass('disabled');
        }
        $('#tooltip_text_html').css('background-color',window.markers[index].tooltip_background);
        $('#tooltip_text_html').css('color',window.markers[index].tooltip_color);
        $('#tooltip_text_html').parent().find('.ql-toolbar').remove();
        $('#tooltip_text_html').html(window.markers[index].tooltip_text).promise().done(function () {
            var toolbarOptions = [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'align': [] }],
                ['clean']
            ];
            window.tooltip_text_editor = new Quill('#tooltip_text_html', {
                modules: {
                    toolbar: toolbarOptions
                },
                theme: 'snow',
                bounds: document.getElementById('confirm_edit')
            });
        });
        $('#tooltip_text_mobile_html').css('background-color',window.markers[index].tooltip_background);
        $('#tooltip_text_mobile_html').css('color',window.markers[index].tooltip_color);
        $('#tooltip_text_mobile_html').parent().find('.ql-toolbar').remove();
        $('#tooltip_text_mobile_html').html(window.markers[index].tooltip_text_mobile).promise().done(function () {
            var toolbarOptions = [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'align': [] }],
                ['clean']
            ];
            window.tooltip_text_mobile_editor = new Quill('#tooltip_text_mobile_html', {
                modules: {
                    toolbar: toolbarOptions
                },
                theme: 'snow',
                bounds: document.getElementById('confirm_edit')
            });
        });
        if($('.lang_input_switcher').length) {
            $('.lang_input_switcher').each(function() {
                var elem_o = $(this).attr('data-elem');
                var lang_o = $(this).attr('data-default-lang');
                switch_input_language(lang_o,lang_o,elem_o);
            });
        }
        $('.input_lang[data-target-id="tooltip_text_html"]').html('');
        $('.input_lang[data-target-id="tooltip_text_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var id_l = $(this).attr('id');
            $('#'+id_l).css('background-color',window.markers[index].tooltip_background);
            $('#'+id_l).css('color',window.markers[index].tooltip_color);
            $('#'+id_l).parent().find('.ql-toolbar').remove();
            var html = '';
            jQuery.each(window.markers[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    html = item_lang.tooltip_text;
                }
            });
            $('#'+id_l).html(html).promise().done(function () {
                var toolbarOptions = [
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'align': [] }],
                    ['clean']
                ];
                window.tooltip_text_editor_lang[lang] = new Quill('#'+id_l, {
                    modules: {
                        toolbar: toolbarOptions
                    },
                    theme: 'snow',
                    bounds: document.getElementById('confirm_edit')
                });
            });
        });
        $('.input_lang[data-target-id="tooltip_text_mobile_html"]').html('');
        $('.input_lang[data-target-id="tooltip_text_mobile_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var id_l = $(this).attr('id');
            $('#'+id_l).css('background-color',window.markers[index].tooltip_background);
            $('#'+id_l).css('color',window.markers[index].tooltip_color);
            $('#'+id_l).parent().find('.ql-toolbar').remove();
            var html = '';
            jQuery.each(window.markers[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    html = item_lang.tooltip_text_mobile;
                }
            });
            $('#'+id_l).html(html).promise().done(function () {
                var toolbarOptions = [
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'align': [] }],
                    ['clean']
                ];
                window.tooltip_text_mobile_editor_lang[lang] = new Quill('#'+id_l, {
                    modules: {
                        toolbar: toolbarOptions
                    },
                    theme: 'snow',
                    bounds: document.getElementById('confirm_edit')
                });
            });
        });
        change_tooltip_type_m();
        $('#marker_library_icon').val(window.markers[index].id_icon_library);
        if(window.markers[index].show_room==4) {
            var image = window.markers[index].img_icon_library;
            var id_vt_library = window.markers[index].id_vt_library;
            if(window.s3_enabled==1 && id_vt_library!='') {
                var image_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
            } else {
                var image_url = '../viewer/icons/'+image;
            }
            var ext = image.split('.').pop().toLowerCase();
            if(ext=='json') {
                var html_image = '<div id="lottie_preview_'+window.marker_id_edit+'" style="height:30px;width:30px;vertical-align:middle"></div>';
                $('#marker_library_icon_preview_l').html(html_image).promise().done(function () {
                    $('#marker_library_icon_preview_l').css('display','inline-block');
                    bodymovin.loadAnimation({
                        container: document.getElementById('lottie_preview_'+window.marker_id_edit),
                        renderer: 'svg',
                        loop: true,
                        autoplay: true,
                        path: image_url,
                        rendererSettings: {
                            progressiveLoad: true,
                        }
                    });
                });
                $('#marker_library_icon_preview').hide();
            } else {
                $('#marker_library_icon_preview').attr('src',image_url);
                $('#marker_library_icon_preview').show();
                $('#marker_library_icon_preview_l').hide();
            }
        }
        if(window.markers[index].embed_type=='') {
            change_marker_style();
        }
        $('#edit-tab a[href="#pills-edit"]').tab('show');
        $('#confirm_edit').show();
        window.is_editing = true;
    }

    window.edit_ms = function(id,index) {
        window.measure_index_edit = index;
        window.measure_id_edit = id;
        $('#action_box').hide();
        $('#rooms_slider_slider-container').addClass('hide');
        $('#rooms_slider_content-container').addClass('show');
        fix_all_embeds_pos();
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.count_adjust_measures = 0;
        window.interval_adjust_measures = setInterval(function () {
            if(window.count_adjust_measures>=110) {
                clearInterval(window.interval_adjust_measures);
                window.count_adjust_measures = 0;
            }
            adjust_measurements(false);
            window.count_adjust_measures++;
        },1);
        $('#btn_add_measure').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        close_list_hs();
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').addClass('disabled');
        $('.icon_visible_view').addClass('disabled');
        $('#confirm_edit .btn_confirm').removeClass("disabled");
        $('svg.leader-line path').css('pointer-events','none');
        $('svg.leader-line text').css('pointer-events','none');
        $('svg.leader-line use').css('pointer-events','none');
        $('#confirm_edit .btn_confirm').attr('onclick','confirm_edit_measure('+id+','+index+')');
        $('#confirm_edit .btn_close').attr('onclick','exit_edit_measure('+id+','+index+')');
        $(window).trigger('resize');
        var params = JSON.parse(window.measures[index].params);
        $('#measure_label').val(window.measures[index].label);
        $('#measure_line_size').val(params.line_size);
        $("#measure_line_color").spectrum("set", params.color_line);
        $("#measure_color_text").spectrum("set", params.color_text);
        $("#measure_color_outline_text").spectrum("set", params.color_outline_text);
        $('#measure_size_text').val(params.size_text);
        $('#measure_start_plug option[id='+params.start_plug+']').prop('selected', true);
        $('#measure_end_plug option[id='+params.end_plug+']').prop('selected', true);
        $("#measure_start_plug_color").spectrum("set", params.start_plug_color);
        $("#measure_end_plug_color").spectrum("set", params.end_plug_color);
        $('#measure_start_plug_size').val(params.start_plug_size);
        $('#measure_end_plug_size').val(params.end_plug_size);
        $('#measure_line_size_value').html(params.line_size);
        $('#measure_size_text_value').html(params.size_text);
        $('#measure_start_plug_size_value').html(params.start_plug_size);
        $('#measure_end_plug_size_value').html(params.end_plug_size);
        $('#confirm_edit').show();
        window.is_editing = true;
    }

    window.goto_m = function(id,index,yaw_m='',pitch_m='') {
        var id_room_target = window.markers[index].id_room_target;
        window.is_editing = false;
        $('#action_box').hide();
        jQuery.each(window.rooms, function(index, room) {
            var id = parseInt(room.id);
            if(id==parseInt(id_room_target)) {
                if(window.sameAzimuth==1) {
                    var current_north = parseInt(window.viewer.getNorthOffset());
                    var current_yaw = parseFloat(window.viewer.getYaw());
                    yaw_m = current_yaw + (current_north || 0) - (parseInt(room.northOffset) || 0);
                    pitch_m = 0;
                }
                rs_searchInput.val('').trigger('input');
                rs_updateSelection(id, true,true);
                var image = room.panorama_image;
                select_room_marker(id,image,null,yaw_m,pitch_m);
                return;
            }
        });
    }

    window.move_m = function(id,index,index_marker_add) {
        window.marker_index_edit = index;
        window.marker_id_edit = id;
        $('.center_helper').hide();
        $('#action_box').hide();
        $('#rooms_slider_slider-container').addClass('hide');
        $('#rooms_slider_content-container').addClass('show');
        fix_all_embeds_pos();
        $('.azimuth-control').addClass('disabled');
        $('.north-control').addClass('disabled');
        $('#visibile_in_views option').prop('selected',false);
        if(window.markers[index].visible_multiview_ids!='') {
            jQuery.each(window.markers[index].visible_multiview_ids.split(","), function(index_mi, mi) {
                $('#visibile_in_views option[id='+mi+']').prop('selected',true);
            });
        }
        $('#visibile_in_views').selectpicker('refresh');
        $(window).trigger('resize');
        $('#btn_add_marker').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        close_list_hs();
        $('#btn_switch_to_poi').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').addClass('disabled');
        $('.icon_visible_view').addClass('disabled');
        $('#btn_draw_polygon_m').parent().hide();
        window.is_editing = true;
        if(window.markers[index].scale==1) {
            $('#scale').prop('checked',true);
        } else {
            $('#scale').prop('checked',false);
        }
        if(window.markers[index].sticky==1) {
            $('#sticky').prop('checked',true);
        } else {
            $('#sticky').prop('checked',false);
        }
        if(window.markers[index].embed_type!='') {
            window.is_editing = true;
            $('#msg_drag_marker').hide();
            $('#msg_drag_embed').show();
            $('#marker_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
            $('#marker_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
            $('#marker_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
            $('#marker_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
            $('#marker_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
            $('#rotateX').parent().hide();
            $('#size_scale').parent().hide();
            $('#scale').parent().hide();
            $('#sticky').parent().hide();
            switch(window.markers[index].embed_type) {
                case 'selection':
                    $('#btn_draw_polygon_m').parent().show();
                    break;
            }
        } else {
            $('#msg_drag_marker').show();
            $('#msg_drag_embed').hide();
            $('#rotateX').parent().show();
            $('#size_scale').parent().show();
            $('#scale').parent().show();
            $('#sticky').parent().show();
            $('#rotateX').val(window.markers[index].rotateX);
            $('#rotateZ').val(window.markers[index].rotateZ);
            $('#size_scale').val(window.markers[index].size_scale);
            $('#perspective_values').html('('+window.markers[index].rotateX+','+window.markers[index].rotateZ+')');
            $('#size_values').html('('+window.markers[index].size_scale+')');
            $('#rotateX').attr('oninput','adjust_perspective_m('+id+','+index+')');
            $('#rotateZ').attr('oninput','adjust_perspective_m('+id+','+index+')');
            $('#size_scale').attr('oninput','adjust_size_scale_m('+id+','+index+')');
            window.viewer.removeHotSpot("m"+id.toString());
            window.viewer.addHotSpot({
                "id": "m"+window.markers[index].id,
                "type": 'marker',
                "transform3d": false,
                "pitch": parseFloat(window.markers[index].pitch),
                "yaw": parseFloat(window.markers[index].yaw),
                "draggable": true,
                "rotateX": parseInt(window.markers[index].rotateX),
                "rotateZ": parseInt(window.markers[index].rotateZ),
                "size_scale": parseFloat(window.markers[index].size_scale),
                "cssClass": "custom-hotspot",
                "createTooltipFunc": hotspot_m,
                "createTooltipArgs": window.markers[index],
                "dragHandlerFunc": drag_marker_move,
                "dragHandlerArgs": index
            });
            setTimeout(function () {
                window.viewer.resize();
                $('.hotspot_'+id).addClass('grabbable');
            },100);
        }
        $('#confirm_move .btn_confirm').attr('onclick','confirm_move_marker('+id+','+index+','+index_marker_add+')');
        $('#confirm_move .btn_close').attr('onclick','exit_move_marker('+id+','+index+')');
        $('#btn_change_zindex_left').attr('onclick','change_zindex_m_down('+id+','+index+')');
        $('#btn_change_zindex_right').attr('onclick','change_zindex_m_up('+id+','+index+')');
        $('#zIndex_value').html(window.markers[index].zIndex);
        show_marker_apply_move(true);
        $('#confirm_move').show();
    }

    window.move_ms = function(id,index,id_measure_add) {
        window.is_editing = true;
        window.measure_index_edit = index;
        window.measure_id_edit = id;
        $('.center_helper').hide();
        $('#action_box').hide();
        $('#rooms_slider_slider-container').addClass('hide');
        $('#rooms_slider_content-container').addClass('show');
        fix_all_embeds_pos();
        $('#visibile_in_views option').prop('selected',false);
        if(window.measures[index].visible_multiview_ids!='') {
            jQuery.each(window.measures[index].visible_multiview_ids.split(","), function(index_mi, mi) {
                $('#visibile_in_views option[id='+mi+']').prop('selected',true);
            });
        }
        $('#visibile_in_views').selectpicker('refresh');
        $(window).trigger('resize');
        $('#btn_add_measure').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        close_list_hs();
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').addClass('disabled');
        $('.icon_visible_view').addClass('disabled');
        $('#measure_'+id+'_start').css({'opacity':1,'pointer-events':'initial'});
        $('#measure_'+id+'_end').css({'opacity':1,'pointer-events':'initial'});
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.count_adjust_measures = 0;
        window.interval_adjust_measures = setInterval(function () {
            if(window.count_adjust_measures>=110) {
                clearInterval(window.interval_adjust_measures);
                window.count_adjust_measures = 0;
            }
            adjust_measurements(false);
            window.count_adjust_measures++;
        },1);
        $('#measure_'+id+'_start').addClass('grabbable');
        $('#measure_'+id+'_end').addClass('grabbable');
        $('svg.leader-line path').css('pointer-events','none');
        $('svg.leader-line text').css('pointer-events','none');
        $('svg.leader-line use').css('pointer-events','none');
        $('#confirm_move .btn_confirm').attr('onclick','confirm_move_measure('+id+','+index+','+id_measure_add+')');
        $('#confirm_move .btn_close').attr('onclick','exit_move_measure('+id+','+index+')');
        $('#confirm_move').show();
    }

    window.move_p = function(id,index,index_poi_add) {
        window.poi_index_edit = index;
        window.poi_id_edit = id;
        $('.center_helper').hide();
        $('#action_box').hide();
        $('#rooms_slider_slider-container').addClass('hide');
        $('#rooms_slider_content-container').addClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_poi').addClass('disabled');
        $('#btn_list_hs').addClass('disabled');
        close_list_hs();
        $('#btn_switch_to_marker').addClass('disabled');
        $('#btn_preview_modal').addClass('disabled');
        $('#btn_toggle_fullscreen').addClass('disabled');
        $('.rooms_view_sel').addClass('disabled');
        $('.icon_visible_view').addClass('disabled');
        show_poi_confirm(true);
        window.is_editing = true;
        $('#transform3d').parent().hide();
        $('#btn_draw_polygon').parent().hide();
        $('#object3d_move_params').hide();
        if(window.pois[index].transform3d==1) {
            $('#transform3d').prop('checked',true);
        } else {
            $('#transform3d').prop('checked',false);
        }
        if(window.pois[index].scale==1) {
            $('#scale').prop('checked',true);
        } else {
            $('#scale').prop('checked',false);
        }
        if(window.pois[index].sticky==1) {
            $('#sticky').prop('checked',true);
        } else {
            $('#sticky').prop('checked',false);
        }
        $('#visibile_in_views option').prop('selected',false);
        if(window.pois[index].visible_multiview_ids!='') {
            jQuery.each(window.pois[index].visible_multiview_ids.split(","), function(index_mi, mi) {
                $('#visibile_in_views option[id='+mi+']').prop('selected',true);
            });
        }
        $('#visibile_in_views').selectpicker('refresh');
        switch(window.pois[index].embed_type) {
            case 'image':
            case 'video':
                if(index_poi_add==null) {
                    $('#transform3d').parent().show();
                }
                break;
            case 'selection':
                $('#btn_draw_polygon').parent().show();
                break;
            case 'object3d':
                if(window.pois[index].embed_content!='') {
                    var tmp = window.pois[index].embed_params.split(",");
                    if(tmp[6]!==undefined) {
                        var zoom_deg = parseInt(tmp[6])-80;
                        var zoom_deg_val = parseInt(tmp[6]);
                    } else {
                        var zoom_deg = 'auto';
                        var zoom_deg_val = 80;
                    }
                    $('#object3d_zoom').val(zoom_deg_val);
                    $('#object3d_zoom_value').html(zoom_deg);
                    $('#object3d_move_params').show();
                }
                break;
        }
        if(window.pois[index].embed_type!='' && window.pois[index].transform3d==1) {
            $('#msg_drag_poi').hide();
            $('#msg_drag_embed').show();
            window.viewer.removeHotSpot("p"+id.toString());
            window.viewer.removeHotSpot("p"+id.toString()+"_1");
            window.viewer.removeHotSpot("p"+id.toString()+"_2");
            window.viewer.removeHotSpot("p"+id.toString()+"_3");
            window.viewer.removeHotSpot("p"+id.toString()+"_4");
            window.viewer.removeHotSpot("p"+id.toString()+"_move");
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "poi_embed",
                "transform3d": parseInt(window.pois[index].transform3d),
                "tooltip_type": "",
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "cssClass": "hotspot-embed",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.pois[index],
                "clickHandlerFunc": click_edit_poi,
                "clickHandlerArgs": window.pois[index].id
            });
            var poi_embed_helpers = window.pois[index].embed_coords.split("|");
            poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
            poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
            poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
            poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
            jQuery.each(poi_embed_helpers, function(index_h, poi_embed_helper) {
                window.viewer.addHotSpot({
                    "id": "p"+window.pois[index].id+"_"+(index_h+1),
                    "type": 'pointer',
                    "object": "poi_embed_helper",
                    "transform3d": false,
                    "pitch": parseFloat(poi_embed_helper[0]),
                    "yaw": parseFloat(poi_embed_helper[1]),
                    "size_scale": 1,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "draggable": true,
                    "cssClass": "hotspot-helper",
                    "createTooltipFunc": hotspot_embed_helper,
                    "createTooltipArgs": [window.pois[index].id,(index_h+1)],
                    "dragHandlerFunc": drag_embed_helper,
                    "dragHandlerArgs": [window.pois[index],index_h]
                });
            });
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id+"_move",
                "type": 'pointer',
                "object": "poi_embed_helper",
                "transform3d": false,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "size_scale": 1,
                "rotateX": 0,
                "rotateZ": 0,
                "draggable": true,
                "cssClass": "hotspot-helper",
                "createTooltipFunc": hotspot_embed_move,
                "createTooltipArgs": window.pois[index].id,
                "dragHandlerFunc": drag_embed_move,
                "dragHandlerArgs": [window.pois[index].id,index]
            });
            init_poi_embed();
            $('#poi_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
            $('#poi_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
            $('#poi_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
            $('#poi_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
            $('#poi_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
            $('#rotateX').parent().hide();
            $('#size_scale').parent().hide();
            $('#scale').parent().hide();
            $('#sticky').parent().hide();
        } else {
            $('#msg_drag_poi').show();
            $('#msg_drag_embed').hide();
            switch(window.pois[index].type) {
                case 'callout':
                    $('#rotateX').parent().hide();
                    $('#size_scale').parent().hide();
                    $('#scale').parent().hide();
                    $('#sticky').parent().hide();
                    break;
                case 'staging':
                    $('#rotateX').parent().hide();
                    $('#size_scale').parent().hide();
                    $('#scale').parent().hide();
                    $('#sticky').parent().hide();
                    break;
                default:
                    $('#rotateX').parent().show();
                    $('#size_scale').parent().show();
                    $('#scale').parent().show();
                    $('#sticky').parent().show();
                    break;
            }
            $('#rotateX').val(window.pois[index].rotateX);
            $('#rotateZ').val(window.pois[index].rotateZ);
            $('#size_scale').val(window.pois[index].size_scale);
            $('#perspective_values').html('('+window.pois[index].rotateX+','+window.pois[index].rotateZ+')');
            $('#size_values').html('('+window.pois[index].size_scale+')');
            $('#rotateX').attr('oninput','adjust_perspective_p('+id+','+index+')');
            $('#rotateZ').attr('oninput','adjust_perspective_p('+id+','+index+')');
            $('#size_scale').attr('oninput','adjust_size_scale_p('+id+','+index+')');
            if(window.pois[index].embed_type!='' && window.pois[index].transform3d==0) {
                window.viewer.removeHotSpot("p"+id.toString());
                window.viewer.addHotSpot({
                    "id": "p"+window.pois[index].id,
                    "type": window.pois[index].embed_type,
                    "object": "poi_embed",
                    "draggable": true,
                    "transform3d": parseInt(window.pois[index].transform3d),
                    "tooltip_type": "",
                    "pitch": parseFloat(window.pois[index].pitch),
                    "yaw": parseFloat(window.pois[index].yaw),
                    "rotateX": parseInt(window.pois[index].rotateX),
                    "rotateZ": parseInt(window.pois[index].rotateZ),
                    "size_scale": parseFloat(window.pois[index].size_scale),
                    "cssClass": "hotspot-embed",
                    "createTooltipFunc": hotspot_embed,
                    "createTooltipArgs": window.pois[index],
                    "dragHandlerFunc": drag_poi_move,
                    "dragHandlerArgs": index
                });
                fix_all_embeds_pos();
            } else {
                window.viewer.removeHotSpot("p"+id.toString());
                switch(window.pois[index].type) {
                    case 'callout':
                        window.viewer.addHotSpot({
                            "id": "p"+window.pois[index].id,
                            "type": 'callout',
                            "transform3d": false,
                            "draggable": true,
                            "scale": false,
                            "pitch": parseFloat(window.pois[index].pitch),
                            "yaw": parseFloat(window.pois[index].yaw),
                            "rotateX": 0,
                            "rotateZ": 0,
                            "size_scale": 1,
                            "cssClass": "custom-hotspot-content",
                            "createTooltipFunc": hotspot_p_callout,
                            "createTooltipArgs": window.pois[index],
                            "dragHandlerFunc": drag_poi_move,
                            "dragHandlerArgs": index
                        });
                        break;
                    case 'staging':
                        window.viewer.addHotSpot({
                            "id": "p"+window.pois[index].id,
                            "type": 'poi',
                            "transform3d": false,
                            "draggable": true,
                            "scale": false,
                            "pitch": parseFloat(window.pois[index].pitch),
                            "yaw": parseFloat(window.pois[index].yaw),
                            "rotateX": 0,
                            "rotateZ": 0,
                            "size_scale": 1,
                            "cssClass": "custom-hotspot-content staging-hotspot",
                            "createTooltipFunc": hotspot_p_staging,
                            "createTooltipArgs": window.pois[index],
                            "dragHandlerFunc": drag_poi_move,
                            "dragHandlerArgs": index
                        });
                        break;
                    default:
                        window.viewer.addHotSpot({
                            "id": "p"+window.pois[index].id,
                            "type": 'poi',
                            "transform3d": false,
                            "draggable": true,
                            "scale": (parseInt(window.pois[index].scale)==1) ? true : false,
                            "pitch": parseFloat(window.pois[index].pitch),
                            "yaw": parseFloat(window.pois[index].yaw),
                            "rotateX": parseInt(window.pois[index].rotateX),
                            "rotateZ": parseInt(window.pois[index].rotateZ),
                            "size_scale": parseFloat(window.pois[index].size_scale),
                            "cssClass": "custom-hotspot-content",
                            "createTooltipFunc": hotspot_p,
                            "createTooltipArgs": window.pois[index],
                            "dragHandlerFunc": drag_poi_move,
                            "dragHandlerArgs": index
                        });
                        break;
                }
            }
            setTimeout(function () {
                window.viewer.resize();
                $('.hotspot_'+id).addClass('grabbable');
            },100);
        }
        $('#btn_change_zindex_left').attr('onclick','change_zindex_p_down('+id+','+index+')');
        $('#btn_change_zindex_right').attr('onclick','change_zindex_p_up('+id+','+index+')');
        $('#zIndex_value').html(window.pois[index].zIndex);
        $('#confirm_move .btn_confirm').attr('onclick','confirm_move_poi('+id+','+index+','+index_poi_add+')');
        $('#confirm_move .btn_close').attr('onclick','exit_move_poi('+id+','+index+')');
        show_poi_apply_move(true);
        $('#confirm_move').show();
    }

    window.adjust_perspective_m = function(id,index) {
        var rotateX = $('#rotateX').val();
        var rotateZ = $('#rotateZ').val();
        var scale = $('#scale').is(':checked') ? 1:0;
        window.markers[index].rotateX = rotateX;
        window.markers[index].rotateZ = rotateZ;
        window.markers[index].scale = scale;
        window.viewer.removeHotSpot("m"+id.toString());
        window.viewer.addHotSpot({
            "id": "m"+window.markers[index].id,
            "type": 'marker',
            "transform3d": false,
            "scale": (parseInt(window.markers[index].scale)==1) ? true : false,
            "pitch": parseFloat(window.markers[index].pitch),
            "yaw": parseFloat(window.markers[index].yaw),
            "draggable": true,
            "rotateX": parseInt(window.markers[index].rotateX),
            "rotateZ": parseInt(window.markers[index].rotateZ),
            "size_scale": parseFloat(window.markers[index].size_scale),
            "cssClass": "custom-hotspot",
            "createTooltipFunc": hotspot_m,
            "createTooltipArgs": window.markers[index],
            "dragHandlerFunc": drag_marker_move,
            "dragHandlerArgs": index
        });
        $('.hotspot_'+id).addClass('grabbable');
        $('#perspective_values').html('('+window.markers[index].rotateX+','+window.markers[index].rotateZ+')');
    }

    window.change_zindex_p_down = function (id,index) {
        var zindex = parseInt($('#zIndex_value').html());
        zindex = zindex - 1;
        if(zindex<=1) zindex=1;
        $('#zIndex_value').html(zindex);
        window.pois[index].zIndex = zindex;
        $('.hotspot_'+id).css('z-index',zindex);
    }

    window.change_zindex_p_up = function (id,index) {
        var zindex = parseInt($('#zIndex_value').html());
        zindex = zindex + 1;
        $('#zIndex_value').html(zindex);
        window.pois[index].zIndex = zindex;
        $('.hotspot_'+id).css('z-index',zindex);
    }

    window.change_zindex_m_down = function (id,index) {
        var zindex = parseInt($('#zIndex_value').html());
        zindex = zindex - 1;
        if(zindex<=1) zindex=1;
        $('#zIndex_value').html(zindex);
        window.markers[index].zIndex = zindex;
        $('.hotspot_'+id).css('z-index',zindex);
    }

    window.change_zindex_m_up = function (id,index) {
        var zindex = parseInt($('#zIndex_value').html());
        zindex = zindex + 1;
        $('#zIndex_value').html(zindex);
        window.markers[index].zIndex = zindex;
        $('.hotspot_'+id).css('z-index',zindex);
    }

    window.adjust_perspective_p = function(id,index) {
        var rotateX = $('#rotateX').val();
        var rotateZ = $('#rotateZ').val();
        var scale = $('#scale').is(':checked') ? 1:0;
        window.pois[index].rotateX = rotateX;
        window.pois[index].rotateZ = rotateZ;
        window.pois[index].scale = scale;
        if(window.pois[index].embed_type!='' && window.pois[index].transform3d==0) {
            window.viewer.removeHotSpot("p"+id.toString());
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "poi_embed",
                "transform3d": parseInt(window.pois[index].transform3d),
                "tooltip_type": "",
                "draggable": true,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": parseInt(window.pois[index].rotateX),
                "rotateZ": parseInt(window.pois[index].rotateZ),
                "size_scale": parseFloat(window.pois[index].size_scale),
                "cssClass": "hotspot-embed",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.pois[index],
                "dragHandlerFunc": drag_poi_move,
                "dragHandlerArgs": index
            });
            fix_all_embeds_pos();
        } else {
            window.viewer.removeHotSpot("p"+id.toString());
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": 'poi',
                "transform3d": false,
                "draggable": true,
                "scale": (parseInt(window.pois[index].scale)==1) ? true : false,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": parseInt(window.pois[index].rotateX),
                "rotateZ": parseInt(window.pois[index].rotateZ),
                "size_scale": parseFloat(window.pois[index].size_scale),
                "cssClass": "custom-hotspot-content",
                "createTooltipFunc": hotspot_p,
                "createTooltipArgs": window.pois[index],
                "dragHandlerFunc": drag_poi_move,
                "dragHandlerArgs": index
            });
        }
        $('.hotspot_'+id).addClass('grabbable');
        $('#perspective_values').html('('+window.pois[index].rotateX+','+window.pois[index].rotateZ+')');
    }

    window.adjust_size_scale_m = function(id,index) {
        var size_scale = $('#size_scale').val();
        var scale = $('#scale').is(':checked') ? 1:0;
        window.markers[index].size_scale = size_scale;
        window.markers[index].scale = scale;
        window.viewer.removeHotSpot("m"+id.toString());
        window.viewer.addHotSpot({
            "id": "m"+window.markers[index].id,
            "type": 'marker',
            "transform3d": false,
            "scale": (parseInt(window.markers[index].scale)==1) ? true : false,
            "pitch": parseFloat(window.markers[index].pitch),
            "yaw": parseFloat(window.markers[index].yaw),
            "draggable": true,
            "rotateX": parseInt(window.markers[index].rotateX),
            "rotateZ": parseInt(window.markers[index].rotateZ),
            "size_scale": parseFloat(window.markers[index].size_scale),
            "cssClass": "custom-hotspot",
            "createTooltipFunc": hotspot_m,
            "createTooltipArgs": window.markers[index],
            "dragHandlerFunc": drag_marker_move,
            "dragHandlerArgs": index
        });
        $('.hotspot_'+id).addClass('grabbable');
        $('#size_values').html('('+window.markers[index].size_scale+')');
    }

    window.adjust_size_scale_p = function(id,index) {
        var size_scale = $('#size_scale').val();
        var scale = $('#scale').is(':checked') ? 1:0;
        window.pois[index].size_scale = size_scale;
        window.pois[index].scale = scale;
        if(window.pois[index].embed_type!='' && window.pois[index].transform3d==0) {
            window.viewer.removeHotSpot("p"+id.toString());
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "poi_embed",
                "transform3d": parseInt(window.pois[index].transform3d),
                "draggable": true,
                "tooltip_type": "",
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": parseInt(window.pois[index].rotateX),
                "rotateZ": parseInt(window.pois[index].rotateZ),
                "size_scale": parseFloat(window.pois[index].size_scale),
                "cssClass": "hotspot-embed",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.pois[index],
                "dragHandlerFunc": drag_poi_move,
                "dragHandlerArgs": index
            });
            fix_all_embeds_pos();
        } else {
            window.viewer.removeHotSpot("p"+id.toString());
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": 'poi',
                "transform3d": false,
                "draggable": true,
                "scale": (parseInt(window.pois[index].scale)==1) ? true : false,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": parseInt(window.pois[index].rotateX),
                "rotateZ": parseInt(window.pois[index].rotateZ),
                "size_scale": parseFloat(window.pois[index].size_scale),
                "cssClass": "custom-hotspot-content",
                "createTooltipFunc": hotspot_p,
                "createTooltipArgs": window.pois[index],
                "dragHandlerFunc": drag_poi_move,
                "dragHandlerArgs": index
            });
        }
        $('#size_values').html('('+window.pois[index].size_scale+')');
    }

    window.adjust_map_north = function () {
        var north_degree = $('#north_degree').val();
        $('#north_degree_val').html(north_degree);
        $('#map_compass img').css('transform','rotate('+north_degree+'deg)');
    }

    window.confirm_move_marker = function (id,index,index_marker_add) {
        if(window.markers[index].embed_type!='') {
            var yaw = window.markers[index].yaw;
            var pitch = window.markers[index].pitch;
            var rotateX = 0;
            var rotateZ = 0;
            var size_scale = 1;
            var scale = 0;
            var sticky = 0;
            var embed_coords = window.markers[index].embed_coords;
            var embed_size = window.markers[index].embed_size;
        } else {
            var yaw = window.markers[index].yaw;
            var pitch = window.markers[index].pitch;
            var rotateX = $('#rotateX').val();
            var rotateZ = $('#rotateZ').val();
            var size_scale = $('#size_scale').val();
            var scale = ($('#scale').is(':checked')) ? 1 : 0;
            var sticky = ($('#sticky').is(':checked')) ? 1 : 0;
            var embed_coords = '';
            var embed_size = '';
        }
        window.markers[index].yaw = yaw;
        window.markers[index].pitch = pitch;
        window.markers[index].rotateX = rotateX;
        window.markers[index].rotateZ = rotateZ;
        window.markers[index].size_scale = size_scale;
        window.markers[index].sticky = sticky;
        if(window.markers[index].embed_type=='') {
            render_marker(id,index);
            setTimeout(function () {
                window.viewer.resize();
            },100);
        }
        var visibile_in_views_t = $('#visibile_in_views option');
        var visible_multiview_ids = '';
        $(visibile_in_views_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    visible_multiview_ids = visible_multiview_ids+id+',';
                }
            }
        });
        if(visible_multiview_ids!='') {
            visible_multiview_ids = visible_multiview_ids.substring(0,visible_multiview_ids.length-1);
        }
        window.markers[index].visible_multiview_ids = visible_multiview_ids;
        $('.hotspot_'+id).attr('visible_multiview_ids',visible_multiview_ids);
        window.is_editing = false;
        window.markers_initial[index] = {...window.markers[index]};
        save_marker_pos(id,yaw,pitch,rotateX,rotateZ,size_scale,scale,embed_coords,embed_size,window.markers[index].embed_params,window.markers[index].zIndex,visible_multiview_ids,sticky);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $('.azimuth-control').removeClass('disabled');
        $('.north-control').removeClass('disabled');
        $(window).trigger('resize');
        $('#btn_add_marker').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_poi').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('.custom-hotspot').css({'opacity':1,'pointer-events':'initial'});
        $('.marker_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.marker_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.marker_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_move').hide();
        $('.center_helper').show();
        if(!$('.icon_visible_view').hasClass('hidden')) {
            toggle_visible_view('marker');
        }
        if(index_marker_add!=null) {
            edit_m(id,index,id);
        }
    }

    window.exit_move_marker = function (id,index) {
        window.markers[index] = {...window.markers_initial[index]};
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        render_marker(id,index);
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.is_editing = false;
        $('.azimuth-control').removeClass('disabled');
        $('.north-control').removeClass('disabled');
        $(window).trigger('resize');
        $('#btn_add_marker').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_poi').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('.custom-hotspot').css({'opacity':1,'pointer-events':'initial'});
        $('.marker_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.marker_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.marker_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_move').hide();
        $('.center_helper').show();
    }

    window.confirm_move_poi = function (id,index,index_poi_add) {
        if(window.pois[index].embed_type!='' && window.pois[index].transform3d==1) {
            var yaw = window.pois[index].yaw;
            var pitch = window.pois[index].pitch;
            var rotateX = 0;
            var rotateZ = 0;
            var size_scale = 1;
            var sticky = 0;
            var embed_coords = window.pois[index].embed_coords;
            var embed_size = window.pois[index].embed_size;
        } else if(window.pois[index].embed_type!='' && window.pois[index].transform3d==0) {
            var yaw = window.pois[index].yaw;
            var pitch = window.pois[index].pitch;
            var rotateX = $('#rotateX').val();
            var rotateZ = $('#rotateZ').val();
            var size_scale = $('#size_scale').val();
            var sticky = 0;
            var embed_coords = window.pois[index].embed_coords;
            var embed_size = window.pois[index].embed_size;
        } else {
            var yaw = window.pois[index].yaw;
            var pitch = window.pois[index].pitch;
            var rotateX = $('#rotateX').val();
            var rotateZ = $('#rotateZ').val();
            var size_scale = $('#size_scale').val();
            var sticky = ($('#sticky').is(':checked')) ? 1 : 0;
            var embed_coords = '';
            var embed_size = '';
        }
        window.pois[index].yaw = yaw;
        window.pois[index].pitch = pitch;
        window.pois[index].size_scale = size_scale;
        window.pois[index].sticky = sticky;
        window.pois[index].rotateX = rotateX;
        window.pois[index].rotateZ = rotateZ;
        if(window.pois[index].embed_type=='object3d') {
            if(window.pois[index].embed_params!='') {
                var tmp = window.pois[index].embed_params.split(",");
                var camera_coords = tmp[0];
                if(tmp[1]!==undefined) {
                    var interaction = tmp[1];
                } else {
                    var interaction = 0;
                }
                if(tmp[2]!==undefined) {
                    var exposure = tmp[2];
                } else {
                    var exposure = 1;
                }
                if(tmp[3]!==undefined) {
                    var environment = tmp[3];
                } else {
                    var environment = 'legacy';
                }
                if(tmp[4]!==undefined) {
                    var shadow_intensity = tmp[4];
                } else {
                    var shadow_intensity = 1;
                }
                if(tmp[5]!==undefined) {
                    var shadow_softness = tmp[5];
                } else {
                    var shadow_softness = 0.5;
                }
                if(tmp[7]!==undefined) {
                    var animation = tmp[7];
                } else {
                    var animation = 'none';
                }
            } else {
                var camera_coords = "";
                var interaction = 0;
                var exposure = 1;
                var environment = 'legacy';
                var shadow_intensity = 1;
                var shadow_softness = 0.5;
                var animation = 'none';
            }
            var zoom_deg = $('#object3d_zoom').val();
            if(zoom_deg==80) zoom_deg='auto';
            window.pois[index].embed_params = camera_coords+','+interaction+','+exposure+','+environment+','+shadow_intensity+','+shadow_softness+','+zoom_deg+','+animation;
        }
        var visibile_in_views_t = $('#visibile_in_views option');
        var visible_multiview_ids = '';
        $(visibile_in_views_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    visible_multiview_ids = visible_multiview_ids+id+',';
                }
            }
        });
        if(visible_multiview_ids!='') {
            visible_multiview_ids = visible_multiview_ids.substring(0,visible_multiview_ids.length-1);
        }
        window.pois[index].visible_multiview_ids = visible_multiview_ids;
        $('.hotspot_'+id).attr('visible_multiview_ids',visible_multiview_ids);
        window.is_editing = false;
        if(window.pois[index].embed_type=='' || window.pois[index].transform3d==0) {
            render_poi(id,index);
            setTimeout(function () {
                window.viewer.resize();
            },100);
        }
        if(window.pois[index].embed_type=='object3d') {
            render_poi(id,index);
        }
        window.pois_initial[index] = {...window.pois[index]};
        save_poi_pos(id,yaw,pitch,rotateX,rotateZ,size_scale,embed_coords,embed_size,window.pois[index].transform3d,window.pois[index].scale,window.pois[index].zIndex,window.pois[index].params,window.pois[index].embed_params,visible_multiview_ids,sticky);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_poi').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_marker').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('.custom-hotspot-content').css({'opacity':1,'pointer-events':'initial'});
        $('.poi_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_move').hide();
        $('.center_helper').show();
        if(index_poi_add!=null) {
            edit_p(id,index,id);
        }
        if(!$('.icon_visible_view').hasClass('hidden')) {
            toggle_visible_view('poi');
        }
    }

    window.confirm_move_measure = function (id,index,id_measure_add) {
        var visibile_in_views_t = $('#visibile_in_views option');
        var visible_multiview_ids = '';
        $(visibile_in_views_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    visible_multiview_ids = visible_multiview_ids+id+',';
                }
            }
        });
        if(visible_multiview_ids!='') {
            visible_multiview_ids = visible_multiview_ids.substring(0,visible_multiview_ids.length-1);
        }
        window.measures[index].visible_multiview_ids = visible_multiview_ids;
        $('#line_'+id).attr('visible_multiview_ids',visible_multiview_ids);
        window.is_editing = false;
        window.measures_initial[index] = {...window.measures[index]};
        save_measure(window.measures[index]);
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.count_adjust_measures = 0;
        window.interval_adjust_measures = setInterval(function () {
            if(window.count_adjust_measures>=110) {
                clearInterval(window.interval_adjust_measures);
                window.count_adjust_measures = 0;
            }
            adjust_measurements(false);
            window.count_adjust_measures++;
        },1);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_measure').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('svg.leader-line').css({'opacity':1});
        $('svg.leader-line path').css({'pointer-events':'initial'});
        $('svg.leader-line text').css('pointer-events','initial');
        $('svg.leader-line use').css('pointer-events','initial');
        $('.measure_points').css({'opacity':0,'pointer-events':'none'});
        $('#confirm_move').hide();
        $('.center_helper').show();
        if(id_measure_add!=null) {
            edit_ms(id_measure_add,index);
        }
        if(!$('.icon_visible_view').hasClass('hidden')) {
            toggle_visible_view('measure');
        }
    }

    window.confirm_edit_measure = function (id,index) {
        window.is_editing = false;
        window.measures_initial[index] = {...window.measures[index]};
        save_measure(window.measures[index]);
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.count_adjust_measures = 0;
        window.interval_adjust_measures = setInterval(function () {
            if(window.count_adjust_measures>=110) {
                clearInterval(window.interval_adjust_measures);
                window.count_adjust_measures = 0;
            }
            adjust_measurements(false);
            window.count_adjust_measures++;
        },1);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_measure').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('svg.leader-line').css({'opacity':1});
        $('svg.leader-line path').css({'pointer-events':'initial'});
        $('svg.leader-line text').css('pointer-events','initial');
        $('svg.leader-line use').css('pointer-events','initial');
        $('.measure_points').css({'opacity':0,'pointer-events':'none'});
        $('#confirm_edit').hide();
        $('.center_helper').show();
    }

    window.exit_move_poi = function (id,index) {
        window.pois[index] = {...window.pois_initial[index]};
        window.is_editing = false;
        render_poi(id,index);
        setTimeout(function () {
            window.viewer.resize();
        },100);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_poi').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_marker').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('.custom-hotspot-content').css({'opacity':1,'pointer-events':'initial'});
        $('.poi_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_move').hide();
        $('.center_helper').show();
    }

    function render_measure(id,index) {
        var measure = window.measures[index];
        window.viewer.removeHotSpot('measure_'+measure.id+'_start');
        window.viewer.removeHotSpot('measure_'+measure.id+'_end');
        window.viewer.addHotSpot({
            "id": 'measure_'+measure.id+'_start',
            "type": 'measure',
            "view_type": 0,
            "object": "measure",
            "transform3d": false,
            "scale": false,
            "draggable": true,
            "tooltip_type": '',
            "pitch": parseFloat(measure.pitch_start),
            "yaw": parseFloat(measure.yaw_start),
            "rotateX": 0,
            "rotateZ": 0,
            "size_scale": 1,
            "animation": '',
            "cssClass": "custom-hotspot-measure",
            "createTooltipFunc": hotspot_measure,
            "createTooltipArgs": {id:measure.id,dir:'start',index:index,yaw:parseFloat(measure.yaw_start),pitch:parseFloat(measure.pitch_start)},
            "dragHandlerFunc": drag_measure_move,
            "dragHandlerArgs": {id:measure.id,dir:'start',index:index}
        });
        window.viewer.addHotSpot({
            "id": 'measure_'+measure.id+'_end',
            "type": 'measure',
            "view_type": 0,
            "object": "measure",
            "transform3d": false,
            "scale": false,
            "draggable": true,
            "tooltip_type": '',
            "pitch": parseFloat(measure.pitch_end),
            "yaw": parseFloat(measure.yaw_end),
            "rotateX": 0,
            "rotateZ": 0,
            "size_scale": 1,
            "animation": '',
            "cssClass": "custom-hotspot-measure",
            "createTooltipFunc": hotspot_measure,
            "createTooltipArgs": {id:measure.id,dir:'end',index:index,yaw:parseFloat(measure.yaw_end),pitch:parseFloat(measure.pitch_end)},
            "dragHandlerFunc": drag_measure_move,
            "dragHandlerArgs": {id:measure.id,dir:'end',index:index}
        });
    }

    window.render_edit_measure = function() {
        window.enable_adjust_measurements = false;
        window.measures[window.measure_index_edit].label = $('#measure_label').val();
        var params = JSON.parse(window.measures[window.measure_index_edit].params);
        params.line_size = parseFloat($('#measure_line_size').val());
        params.color_line = $('#measure_line_color').val();
        params.color_text = $('#measure_color_text').val();
        params.color_outline_text = $('#measure_color_outline_text').val();
        params.size_text = parseInt($('#measure_size_text').val());
        params.start_plug = $('#measure_start_plug option:selected').attr('id');
        params.end_plug = $('#measure_end_plug option:selected').attr('id');
        params.start_plug_color = $('#measure_start_plug_color').val();
        params.end_plug_color = $('#measure_end_plug_color').val();
        params.start_plug_size = parseFloat($('#measure_start_plug_size').val());
        params.end_plug_size = parseFloat($('#measure_end_plug_size').val());
        $('#measure_line_size_value').html(params.line_size);
        $('#measure_size_text_value').html(params.size_text);
        $('#measure_start_plug_size_value').html(params.start_plug_size);
        $('#measure_end_plug_size_value').html(params.end_plug_size);
        window.measures[window.measure_index_edit].params = JSON.stringify(params);
        if(window.measures[window.measure_index_edit].label=='' || window.measures[window.measure_index_edit].label==null) {
            window.measure_lines[window.measure_index_edit].setOptions({
                hide: false,
                color:params.color_line,
                size:params.line_size,
                path:'straight',
                startPlug:params.start_plug,
                endPlug:params.end_plug,
                startPlugColor:params.start_plug_color,
                endPlugColor:params.end_plug_color,
                startPlugSize: params.start_plug_size,
                endPlugSize: params.end_plug_size,
                middleLabel: ''
            });
        } else {
            window.measure_lines[window.measure_index_edit].setOptions({
                hide: false,
                color:params.color_line,
                size:params.line_size,
                path:'straight',
                startPlug:params.start_plug,
                endPlug:params.end_plug,
                startPlugColor:params.start_plug_color,
                endPlugColor:params.end_plug_color,
                startPlugSize: params.start_plug_size,
                endPlugSize: params.end_plug_size,
                middleLabel: LeaderLine.pathLabel(window.measures[window.measure_index_edit].label, {color: params.color_text, ontFamily: window.viewer_font_family, fontSize: params.size_text+'px', outlineColor: params.color_outline_text})
            });
        }
        $('svg.leader-line path,svg.leader-line text,svg.leader-line use').off('click').on('click',function() {
            if(!window.is_editing) {
                var svg = findUpTag($(this)[0],'svg');
                var id_line = svg.id.replace('line_','');
                $('svg.leader-line').css({'opacity':0.5});
                $('#line_'+id_line).css({'opacity':1});
                $('.measure_points').css({'opacity':0,'pointer-events':'none'});
                click_edit_measure(id_line);
            }
        });
        window.enable_adjust_measurements = true;
        $(document).trigger('resize');
        setTimeout(function () {
            window.viewer.resize();
            adjust_measurements(true);
        },100);
    }

    window.exit_move_measure = function (id,index) {
        window.measures[index] = {...window.measures_initial[index]};
        window.is_editing = false;
        window.enable_adjust_measurements = false;
        render_measure(id,index);
        initialize_measures(false);
        window.enable_adjust_measurements = true;
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.count_adjust_measures = 0;
        window.interval_adjust_measures = setInterval(function () {
            if(window.count_adjust_measures>=110) {
                clearInterval(window.interval_adjust_measures);
                window.count_adjust_measures = 0;
            }
            adjust_measurements(false);
            window.count_adjust_measures++;
        },1);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_measure').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('svg.leader-line').css({'opacity':1});
        $('svg.leader-line path').css({'pointer-events':'initial'});
        $('svg.leader-line text').css('pointer-events','initial');
        $('svg.leader-line use').css('pointer-events','initial');
        $('.measure_points').css({'opacity':0,'pointer-events':'none'});
        $('#confirm_move').hide();
        $('.center_helper').show();
    }

    window.exit_edit_measure = function (id,index) {
        window.measures[index] = {...window.measures_initial[index]};
        window.is_editing = false;
        window.enable_adjust_measurements = false;
        render_measure(id,index);
        initialize_measures(false);
        window.enable_adjust_measurements = true;
        setTimeout(function () {
            window.viewer.resize();
        },100);
        window.count_adjust_measures = 0;
        window.interval_adjust_measures = setInterval(function () {
            if(window.count_adjust_measures>=110) {
                clearInterval(window.interval_adjust_measures);
                window.count_adjust_measures = 0;
            }
            adjust_measurements(false);
            window.count_adjust_measures++;
        },1);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_measure').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        $('svg.leader-line').css({'opacity':1});
        $('svg.leader-line path').css({'pointer-events':'initial'});
        $('svg.leader-line text').css('pointer-events','initial');
        $('svg.leader-line use').css('pointer-events','initial');
        $('.measure_points').css({'opacity':0,'pointer-events':'none'});
        $('#confirm_edit').hide();
        $('.center_helper').show();
    }

    window.confirm_edit_marker = function (id,index,goto=false) {
        if($('#override_pos_edit').is(':checked')) {
            var yaw_m = parseFloat(window.viewer_pos.getYaw());
            var pitch_m = parseFloat(window.viewer_pos.getPitch());
        } else {
            var yaw_m = '';
            var pitch_m = '';
        }
        if($('#override_look_edit').is(':checked')) {
            var yaw_look_m = parseFloat(window.viewer_look.getYaw());
            var pitch_look_m = parseFloat(window.viewer_look.getPitch());
        } else {
            var yaw_look_m = '';
            var pitch_look_m = '';
        }
        var duration_look_m = $('#duration_look_edit').val();
        var embed_content = '';
        var embed_type = window.markers[index].embed_type;
        var lookat = $('#lookat option:selected').attr('id');
        var show_room = $('#marker_style option:selected').attr('id');
        var tooltip_type = $('#tooltip_type option:selected').attr('id');
        var tooltip_visibility = $('#tooltip_visibility option:selected').attr('id');
        var tooltip_background = $('#tooltip_background').val();
        var tooltip_color = $('#tooltip_color').val();
        var tooltip_text = window.tooltip_text_editor.root.innerHTML;
        var tooltip_text_mobile = window.tooltip_text_mobile_editor.root.innerHTML;
        var color = $('#marker_color').val();
        var background = $('#marker_background').val();
        var css_class = $('#marker_css_class').val();
        var icon = $('#marker_icon').val();
        var label = $('#marker_label').val();
        var icon_type = $('#marker_icon_type option:selected').attr('id');
        var sound = $('#marker_sound option:selected').attr('id');
        if(show_room==4) {
            var id_icon_library = $('#marker_library_icon').val();
            if(id_icon_library==0) {
                alert(window.backend_labels.select_icon_msg);
                return;
            }
        } else {
            var id_icon_library = 0;
        }
        switch(window.markers[index].embed_type) {
            case 'selection':
                embed_content = 'border-width:'+$('#marker_border_px').val()+'px;';
                break;
            default:
                break;
        }
        var array_lang = {};
        array_lang['tooltip_text'] = {};
        $('.input_lang[data-target-id="tooltip_text_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.tooltip_text_editor_lang[lang].root.innerHTML;
            array_lang['tooltip_text'][lang]=value;
            var exist_l = false;
            jQuery.each(window.markers[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.tooltip_text=value;
                }
            });
            if(!exist_l) {
                window.markers[index].array_lang.push({'id_marker':id,'language':lang,'tooltip_text':value,'tooltip_text_mobile':'','label':''});
            }
        });
        array_lang['tooltip_text_mobile'] = {};
        $('.input_lang[data-target-id="tooltip_text_mobile_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.tooltip_text_mobile_editor_lang[lang].root.innerHTML;
            array_lang['tooltip_text_mobile'][lang]=value;
            var exist_l = false;
            jQuery.each(window.markers[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.tooltip_text_mobile=value;
                }
            });
            if(!exist_l) {
                window.markers[index].array_lang.push({'id_marker':id,'language':lang,'tooltip_text':'','tooltip_text_mobile':value,'label':''});
            }
        });
        array_lang['label'] = {};
        $('.input_lang[data-target-id="marker_label"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['label'][lang]=value;
            var exist_l = false;
            jQuery.each(window.markers[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.label=value;
                }
            });
            if(!exist_l) {
                window.markers[index].array_lang.push({'id_marker':id,'language':lang,'tooltip_text':'','tooltip_text_mobile':'','label':value});
            }
        });
        window.markers[index].yaw_room_target = yaw_m;
        window.markers[index].pitch_room_target = pitch_m;
        window.markers[index].yaw_look_room_target = yaw_look_m;
        window.markers[index].pitch_look_room_target = pitch_look_m;
        window.markers[index].duration_look_room_target = duration_look_m;
        window.markers[index].id_icon_library = id_icon_library;
        window.markers[index].show_room = show_room;
        window.markers[index].tooltip_type = tooltip_type;
        window.markers[index].tooltip_visibility = tooltip_visibility;
        window.markers[index].tooltip_background = tooltip_background;
        window.markers[index].tooltip_color = tooltip_color;
        window.markers[index].tooltip_text = tooltip_text;
        window.markers[index].tooltip_text_mobile = tooltip_text_mobile;
        window.markers[index].css_class = css_class;
        window.markers[index].icon_type = icon_type;
        window.markers[index].label = label;
        window.markers[index].sound = sound;
        window.markers[index].embed_content = embed_content;
        window.markers[index].lookat = lookat;
        window.markers_initial[index] = {...window.markers[index]};
        window.is_editing = false;
        var id_room_target = window.markers[index].id_room_target;
        change_exclude_apply_all('marker');
        save_marker_edit(id,id_room_target,yaw_m,pitch_m,lookat,yaw_look_m,pitch_look_m,duration_look_m);
        save_marker_style(id,show_room,color,background,icon,id_icon_library,tooltip_type,tooltip_text,tooltip_text_mobile,css_class,embed_content,window.markers[index].animation,icon_type,tooltip_visibility,tooltip_background,tooltip_color,sound,label,array_lang);
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $('.azimuth-control').removeClass('disabled');
        $('.north-control').removeClass('disabled');
        $(window).trigger('resize');
        $('#btn_add_marker').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_poi').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        var yaw = parseFloat(window.markers[index].yaw);
        var pitch = parseFloat(window.markers[index].pitch);
        window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200);
        $('.poi_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_edit').hide();
        if(window.markers[index].embed_type!='') {
            render_marker(id,index);
        }
        if(goto) {
            jQuery.each(window.markers, function(index_m, marker_m) {
                if(marker_m.what=='marker') {
                    if(parseInt(marker_m.id)==parseInt(id)) {
                        goto_m(id,index_m,yaw_m,pitch_m);
                        return;
                    }
                }
            });
        }
    }

    window.exit_edit_marker = function (id,index) {
        window.markers[index] = {...window.markers_initial[index]};
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        render_marker(id,index);
        window.is_editing = false;
        $('.azimuth-control').removeClass('disabled');
        $('.north-control').removeClass('disabled');
        $(window).trigger('resize');
        $('#btn_add_marker').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_poi').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        var yaw = parseFloat(window.markers[index].yaw);
        var pitch = parseFloat(window.markers[index].pitch);
        window.currentYaw = yaw;
        window.currentPitch = pitch;
        window.currentHfov = parseFloat(window.viewer.getHfov());
        window.viewer.lookAt(pitch,yaw,window.currentHfov,200);
        $('.poi_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_edit').hide();
    }

    window.confirm_edit_poi = function (id,index) {
        window.is_editing = false;
        window.grouped_selecting = false;
        var content = '';
        var params = '';
        var embed_content = '';
        var target = '';
        var c_title = '';
        var c_description = '';
        var song_bg_volume = 0.3;
        var type = window.pois[index].type;
        var embed_type = window.pois[index].embed_type;
        switch (type) {
            case 'image':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content').val();
                break;
            case 'video':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content').val();
                break;
            case 'video360':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content').val();
                break;
            case 'link':
            case 'pdf':
            case 'pointclouds':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content').val();
                break;
            case 'gallery':
                content = '';
                var gallery_order = $('#poi_gallery_random').is(':checked') ? 'random' : 'sort';
                var gallery_transition = $('#g_transition option:selected').attr('id');
                var gallery_thumbs = $('#g_thumbs option:selected').attr('id');
                var gallery_autoplay = $('#g_autoplay').is(':checked') ? 1 : 0;
                var gallery_allow_download = $('#g_download').is(':checked') ? 1 : 0;
                var gallery_slide_duration = $('#g_slide_duration').val();
                if(gallery_slide_duration=='' || gallery_slide_duration<=0) gallery_slide_duration=4;
                params = {'order':gallery_order,'gallery_transition':gallery_transition,'gallery_thumbs':gallery_thumbs,'gallery_autoplay':gallery_autoplay,'gallery_slide_duration':gallery_slide_duration,'gallery_allow_download':gallery_allow_download};
                params = JSON.stringify(params);
                break;
            case 'html':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = window.html_editor.root.innerHTML;
                break;
            case 'html_sc':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = window.poi_content_html_sc.getValue();
                break;
            case 'form':
                content = [{},{},{},{},{},{},{},{},{},{},{}];
                var title = $('#form_title').val();
                var button = $('#form_button').val();
                var response = $('#form_response').val();
                var description = $('#form_description').val();
                var background = $('#form_background').val();
                var color = $('#form_color').val();
                var background_button = $('#form_background_button').val();
                var color_button = $('#form_color_button').val();
                content[0]['title'] = title;
                content[0]['button'] = button;
                content[0]['response'] = response;
                content[0]['description'] = description;
                content[0]['background'] = background;
                content[0]['color'] = color;
                content[0]['background_button'] = background_button;
                content[0]['color_button'] = color_button;
                content[0]['privacy_policy'] = $('#form_privacy_policy').is(':checked');
                content[0]['send_email'] = $('#form_send_email').is(':checked');
                content[0]['email'] = $('#form_email').val();
                content[0]['webhook_url'] = $('#form_webhook_url').val();
                for(var i=1;i<=10;i++) {
                    content[i]['enabled'] = $('#form_field_'+i).is(':checked');
                    content[i]['required'] = $('#form_field_required_'+i).is(':checked');
                    content[i]['type'] = $('#form_field_type_'+i+' option:selected').attr('id');
                    content[i]['label'] = $('#form_field_label_'+i).val();
                }
                content = JSON.stringify(content);
                break;
            case 'link_ext':
                target = $('#poi_target option:selected').attr('id');
                content = $('#poi_content').val();
                break;
            case 'google_maps':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_gm_map').val()+"|"+$('#poi_gm_street').val();
                break;
            case 'object360':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = '';
                break;
            case 'object3d':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content').val();
                var placement = $('#params_ar option:selected').attr('id');
                var interaction = $('#params_interaction option:selected').attr('id');
                var exposure = $('#params_exposure').val();
                var environment = $('#params_environment option:selected').attr('id');
                var animation = $('#params_animation option:selected').attr('id');
                var autorotate = ($('#params_autorotate').is(':checked') ? 'auto-rotate' : '');
                var zoom = ($('#params_zoom').is(':checked') ? '' : 'disable-zoom');
                var pan = ($('#params_pan').is(':checked') ? '' : 'disable-pan');
                params = placement+','+interaction+','+exposure+','+environment+','+animation+','+autorotate+','+zoom+','+pan;
                break;
            case 'audio':
                song_bg_volume = $('#poi_song_bg_volume').val();
                content = $('#poi_content').val();
                params = $('#poi_song_player option:selected').attr('id');
                break;
            case 'lottie':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content').val();
                break;
            case 'product':
                c_title = $('#poi_title').val();
                c_description = $('#poi_description').val();
                content = $('#poi_content_product option:selected').attr('id');
                break;
            case 'switch_pano':
                if($('#switch_panorama_default').is(':checked')) {
                    content = 0;
                } else {
                    if($('#poi_content').val()=='') {
                        content = '';
                    } else {
                        content = $('#switch_panorama_id').val();
                    }
                }
                window.pois[index].content = content;
                break;
            case 'callout':
                params = window.pois[index].params_d;
                if(params=='' || params==null) {
                    params = window.pois[poi_index_edit].params;
                }
                break;
            case 'grouped':
                content = window.pois[index].content;
                var grouped_open = $('#grouped_open').is(':checked') ? 1 : 0;
                var grouped_hide_when_open = $('#grouped_hide_when_open').is(':checked') ? 1 : 0;
                var grouped_delay = $('#grouped_delay').val();
                if(grouped_delay=='') grouped_delay=0;
                params = grouped_open+','+grouped_delay+','+grouped_hide_when_open;
                break;
            default:
                content = $('#poi_content').val();
                break;
        }
        var view_type = parseInt($('#view_type option:selected').attr('id'));
        var box_pos = $('#box_pos option:selected').attr('id');
        var box_max_width = $('#box_max_width').val();
        var box_background = $('#box_background').val();
        var box_color = $('#box_color').val();
        var box_maximize = 0;
        if($('#box_maximize').is(':checked')) { box_maximize=1; }
        var auto_close = $('#auto_close').val();
        var learning = 0;
        if($('#learning').is(':checked')) { learning=1; }
        var learning_priority = $('#learning_priority').val();
        var color = $('#poi_color').val();
        var background = $('#poi_background').val();
        var css_class = $('#poi_css_class').val();
        var icon = $('#poi_icon').val();
        var label = $('#poi_label').val();
        var style = $('#poi_style option:selected').attr('id');
        var icon_type = $('#poi_icon_type option:selected').attr('id');
        var sound = $('#poi_sound option:selected').attr('id');
        var tooltip_type = $('#tooltip_type option:selected').attr('id');
        var tooltip_visibility = $('#tooltip_visibility option:selected').attr('id');
        var tooltip_background = $('#tooltip_background').val();
        var tooltip_color = $('#tooltip_color').val();
        var tooltip_text = window.tooltip_text_editor.root.innerHTML;
        var tooltip_text_mobile = window.tooltip_text_mobile_editor.root.innerHTML;
        if(style==1) {
            var id_icon_library = $('#poi_library_icon').val();
            if(id_icon_library==0) {
                alert(window.backend_labels.select_icon_msg);
                return;
            }
        } else {
            var id_icon_library = 0;
        }
        var embed_video_autoplay = 1;
        var embed_video_muted = 1;
        var embed_video_loop = 1;
        var embed_gallery_autoplay = 0;
        var embed_content = $('#poi_embed_content').val();
        switch(window.pois[index].embed_type) {
            case 'video':
            case 'video_transparent':
                if($('#embed_video_autoplay').is(':checked')) embed_video_autoplay=1; else embed_video_autoplay=0;
                if($('#embed_video_muted').is(':checked')) embed_video_muted=1; else embed_video_muted=0;
                if($('#embed_video_loop').is(':checked')) embed_video_loop=1; else embed_video_loop=0;
                break;
            case 'video_chroma':
                if($('#embed_video_autoplay').is(':checked')) embed_video_autoplay=1; else embed_video_autoplay=0;
                if($('#embed_video_muted').is(':checked')) embed_video_muted=1; else embed_video_muted=0;
                if($('#embed_video_loop').is(':checked')) embed_video_loop=1; else embed_video_loop=0;
                var chroma_color = $('#chroma_color').val().replace("rgb(","").replace(")","");
                var chroma_tolerance = $('#chroma_tolerance').val();
                params = chroma_color+','+chroma_tolerance;
                break;
            case 'gallery':
                embed_gallery_autoplay = $('#embed_gallery_autoplay').val();
                embed_content = get_first_poi_embed_gallery_image(id);
                window.pois[index].embed_params = {'order':($('#poi_embed_gallery_random').is(':checked') ? 'random' : 'sort')};
                window.pois[index].embed_params = JSON.stringify(window.pois[index].embed_params);
                break;
            case 'text':
                embed_content = window.poi_embed_content_html_editor.root.innerHTML+' border-width:'+$('#poi_border_px').val()+'px;';
                break;
            case 'html':
                embed_content = window.poi_embed_content_html_sc.getValue();
                break;
            case 'selection':
                embed_content = 'border-width:'+$('#poi_border_px').val()+'px;';
                break;
            case 'object3d':
                var embed_params = window.pois[index].embed_params;
                if(embed_params!='') {
                    var tmp = embed_params.split(",");
                    var camera_coords = tmp[0];
                    if(tmp[6]!==undefined) {
                        var zoom_deg = tmp[6];
                    } else {
                        var zoom_deg = 'auto';
                    }
                } else {
                    var camera_coords = "";
                    var zoom_deg = 'auto';
                }
                var exposure = $('#object3d_exposure').val();
                var interaction = $('#object3d_interaction option:selected').attr('id');
                var environment = $('#object3d_environment option:selected').attr('id');
                var shadow_intensity = $('#object3d_shadow_intensity').val();
                var shadow_softness = $('#object3d_shadow_softness').val();
                var animation = $('#object3d_animation option:selected').attr('id');
                window.pois[index].embed_params = camera_coords+','+interaction+','+exposure+','+environment+','+shadow_intensity+','+shadow_softness+','+zoom_deg+','+animation;
                break;
            default:
                break;
        }
        if($('#enable_schedule').is(':checked')) {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var hour_from = $('#hour_from').val();
            var hour_to = $('#hour_to').val();
            var days_1 = ($("#days_1").is(':checked')) ? 1 : 0;
            var days_2 = ($("#days_2").is(':checked')) ? 1 : 0;
            var days_3 = ($("#days_3").is(':checked')) ? 1 : 0;
            var days_4 = ($("#days_4").is(':checked')) ? 1 : 0;
            var days_5 = ($("#days_5").is(':checked')) ? 1 : 0;
            var days_6 = ($("#days_6").is(':checked')) ? 1 : 0;
            var days_7 = ($("#days_7").is(':checked')) ? 1 : 0;
            var schedule = {};
            schedule['from_date'] = date_from;
            schedule['to_date'] = date_to;
            schedule['from_hour'] = hour_from;
            schedule['to_hour'] = hour_to;
            schedule['days'] = days_1+","+days_2+","+days_3+","+days_4+","+days_5+","+days_6+","+days_7;
            schedule = JSON.stringify(schedule);
        } else {
            schedule = '';
        }
        if(window.pois[index].embed_type!='' && window.pois[index].transform3d==0) {
            window.pois[index].embed_size = '';
            switch(window.pois[index].embed_type) {
                case 'image':
                    var img_tmp = new Image();
                    img_tmp.onload = function () {
                        var height = img_tmp.height;
                        var width = img_tmp.width;
                        var ratio = width / height;
                        if(width>=height) {
                            window.pois[index].embed_size = '300,'+(300/ratio);
                        } else {
                            window.pois[index].embed_size = '100,'+(100/ratio);
                        }
                        save_poi_pos(id,window.pois[index].yaw,window.pois[index].pitch,window.pois[index].rotateX,window.pois[index].rotateZ,window.pois[index].size_scale,window.pois[index].embed_coords,window.pois[index].embed_size,window.pois[index].transform3d,window.pois[index].scale,window.pois[index].zIndex,window.pois[index].params,window.pois[index].embed_params,window.pois[index].visible_multiview_ids);
                        render_poi(id,index);
                        fix_all_embeds_pos();
                    }
                    if(embed_content.startsWith("http") || embed_content.startsWith("//")) {
                        img_tmp.src = embed_content;
                    } else {
                        img_tmp.src = '../viewer/'+embed_content;
                    }
                    break;
                case 'video':
                    var video = document.createElement('video');
                    video.addEventListener( "loadedmetadata", function (e) {
                        var width = this.videoWidth, height = this.videoHeight;
                        var ratio = width / height;
                        if(width>=height) {
                            window.pois[index].embed_size = '300,'+(300/ratio);
                        } else {
                            window.pois[index].embed_size = '200,'+(200/ratio);
                        }
                        save_poi_pos(id,window.pois[index].yaw,window.pois[index].pitch,window.pois[index].rotateX,window.pois[index].rotateZ,window.pois[index].size_scale,window.pois[index].embed_coords,window.pois[index].embed_size,window.pois[index].transform3d,window.pois[index].scale,window.pois[index].scale,window.pois[index].zIndex,window.pois[index].params,window.pois[index].embed_params,window.pois[index].visible_multiview_ids);
                        render_poi(id,index);
                        fix_all_embeds_pos();
                    }, false );
                    video.preload = 'metadata';
                    video.src = '../viewer/'+embed_content;
                    video.load();
                    break;
            }
        }
        var array_lang = {};
        array_lang['tooltip_text'] = {};
        $('.input_lang[data-target-id="tooltip_text_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.tooltip_text_editor_lang[lang].root.innerHTML;
            array_lang['tooltip_text'][lang]=value;
            var exist_l = false;
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.tooltip_text=value;
                }
            });
            if(!exist_l) {
                window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':value,'tooltip_text_mobile':'','title':'','description':'','content':'','params':''});
            }
        });
        array_lang['tooltip_text_mobile'] = {};
        $('.input_lang[data-target-id="tooltip_text_mobile_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.tooltip_text_mobile_editor_lang[lang].root.innerHTML;
            array_lang['tooltip_text_mobile'][lang]=value;
            var exist_l = false;
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.tooltip_text_mobile=value;
                }
            });
            if(!exist_l) {
                window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':value,'title':'','description':'','content':'','params':''});
            }
        });
        array_lang['label'] = {};
        $('.input_lang[data-target-id="poi_label"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['label'][lang]=value;
            var exist_l = false;
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.label=value;
                }
            });
            if(!exist_l) {
                window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':value,'tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':'','params':''});
            }
        });
        array_lang['title'] = {};
        $('.input_lang[data-target-id="poi_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['title'][lang]=value;
            var exist_l = false;
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.title=value;
                }
            });
            if(!exist_l) {
                window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':value,'description':'','content':'','params':''});
            }
        });
        array_lang['description'] = {};
        $('.input_lang[data-target-id="poi_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['description'][lang]=value;
            var exist_l = false;
            jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                if(item_lang.language==lang) {
                    exist_l = true;
                    item_lang.description=value;
                }
            });
            if(!exist_l) {
                window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':value,'content':'','params':''});
            }
        });
        switch(window.pois[index].embed_type) {
            case 'image':
            case 'video':
            case 'video_transparent':
            case 'link':
            case 'object3d':
                array_lang['embed_content'] = {};
                $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    array_lang['embed_content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.embed_content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':value,'label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':'','params':''});
                    }
                });
                break;
            case 'video_chroma':
                array_lang['embed_content'] = {};
                array_lang['params'] = {};
                $('.input_lang[data-target-id="poi_embed_content"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    var chroma_color = $('#chroma_color_'+lang).val().replace("rgb(","").replace(")","");
                    var chroma_tolerance = $('#chroma_tolerance_'+lang).val();
                    var params_l = chroma_color+','+chroma_tolerance;
                    array_lang['embed_content'][lang]=value;
                    array_lang['params'][lang]=params_l;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.embed_content=value;
                            item_lang.params=params_l;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':value,'label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':'','params':params_l});
                    }
                });
                break;
            case 'text':
                array_lang['embed_content'] = {};
                $('.input_lang[data-target-id="poi_embed_content_html"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = window.poi_embed_content_html_editor_lang[lang].root.innerHTML+' border-width:'+$('#poi_border_px').val()+'px;';
                    array_lang['embed_content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.embed_content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':value,'label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':'','params':''});
                    }
                });
                break;
            case 'html':
                array_lang['embed_content'] = {};
                $('.input_lang[data-target-id="poi_embed_content_html_sc"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = window.poi_embed_content_html_sc_lang[lang].getValue();
                    array_lang['embed_content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.embed_content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':value,'label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':'','params':''});
                    }
                });
                break;
        }
        switch(window.pois[index].type) {
            case 'image':
            case 'pdf':
            case 'download':
            case 'video':
            case 'video360':
            case 'lottie':
            case 'audio':
            case 'object3d':
            case 'pointclouds':
            case 'link':
            case 'link_ext':
                array_lang['content'] = {};
                $('.input_lang[data-target-id="poi_content"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    array_lang['content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':value,'params':''});
                    }
                });
                break;
            case 'google_maps':
                array_lang['content'] = {};
                $('.input_lang[data-target-id="poi_gm_map"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $('#poi_gm_map_'+lang).val()+"|"+$('#poi_gm_street_'+lang).val();;
                    array_lang['content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':value,'params':''});
                    }
                });
                break;
            case 'html':
                array_lang['content'] = {};
                $('.input_lang[data-target-id="poi_content_html"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = window.html_editor_lang[lang].root.innerHTML;
                    array_lang['content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':value,'params':''});
                    }
                });
                break;
            case 'html_sc':
                array_lang['content'] = {};
                $('.input_lang[data-target-id="poi_content_html_sc"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = window.poi_content_html_sc_lang[lang].getValue();
                    if (!value.startsWith("<div")) {
                        value = "<div>" + value + "</div>";
                    }
                    array_lang['content'][lang]=value;
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.content=value;
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':value,'params':''});
                    }
                });
                break;
            case 'form':
                array_lang['content'] = {};
                $('.input_lang[data-target-id="form_title"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var content_lang = [{},{},{},{},{},{},{},{},{},{},{}];
                    if($('.input_lang[data-target-id="form_title"][data-lang="'+lang+'"]').val()!='') {
                        content_lang[0]['title'] = $('.input_lang[data-target-id="form_title"][data-lang="'+lang+'"]').val();
                    } else {
                        content_lang[0]['title'] = $('#form_title').val();
                    }
                    if($('.input_lang[data-target-id="form_button"][data-lang="'+lang+'"]').val()!='') {
                        content_lang[0]['button'] = $('.input_lang[data-target-id="form_button"][data-lang="'+lang+'"]').val();
                    } else {
                        content_lang[0]['button'] = $('#form_button').val();
                    }
                    if($('.input_lang[data-target-id="form_response"][data-lang="'+lang+'"]').val()!='') {
                        content_lang[0]['response'] = $('.input_lang[data-target-id="form_response"][data-lang="'+lang+'"]').val();
                    } else {
                        content_lang[0]['response'] = $('#form_response').val();
                    }
                    if($('.input_lang[data-target-id="form_description"][data-lang="'+lang+'"]').val()!='') {
                        content_lang[0]['description'] = $('.input_lang[data-target-id="form_description"][data-lang="'+lang+'"]').val();
                    } else {
                        content_lang[0]['description'] = $('#form_description').val();
                    }
                    content_lang[0]['privacy_policy'] = $('#form_privacy_policy').is(':checked');
                    content_lang[0]['send_email'] = $('#form_send_email').is(':checked');
                    content_lang[0]['email'] = $('#form_email').val();
                    content_lang[0]['webhook_url'] = $('#form_webhook_url').val();
                    content_lang[0]['background'] = $('#form_background').val();
                    content_lang[0]['color'] = $('#form_color').val();
                    content_lang[0]['background_button'] = $('#form_background_button').val();
                    content_lang[0]['color_button'] = $('#form_color_button').val();
                    for(var i=1;i<=10;i++) {
                        content_lang[i]['enabled'] = $('#form_field_'+i).is(':checked');
                        content_lang[i]['required'] = $('#form_field_required_'+i).is(':checked');
                        content_lang[i]['type'] = $('#form_field_type_'+i+' option:selected').attr('id');
                        if($('.input_lang[data-target-id="form_field_label_'+i+'"][data-lang="'+lang+'"]').val()!='') {
                            content_lang[i]['label'] = $('.input_lang[data-target-id="form_field_label_'+i+'"][data-lang="'+lang+'"]').val();
                        } else {
                            content_lang[i]['label'] = $('#form_field_label_'+i).val();
                        }
                    }
                    array_lang['content'][lang]=JSON.stringify(content_lang);
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.content=JSON.stringify(content_lang);
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':JSON.stringify(content_lang),'params':''});
                    }
                });
                break;
            case 'callout':
                var tmp_param = window.pois[index].params_d;
                if(tmp_param=='' || tmp_param==null) {
                    tmp_param = window.pois[index].params;
                }
                tmp_param = JSON.parse(tmp_param);
                array_lang['params'] = {};
                $('.input_lang[data-target-id="callout_title"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    if($(this).val()!='') {
                        tmp_param.title = $(this).val();
                    } else {
                        tmp_param.title = $('#callout_title').val();
                    }
                    if(window.callout_description_editor_lang[lang].root.innerHTML!='' && window.callout_description_editor_lang[lang].root.innerHTML!='<p><br></p>') {
                        tmp_param.description = window.callout_description_editor_lang[lang].root.innerHTML;
                    } else {
                        tmp_param.description = window.callout_description_editor.root.innerHTML;
                    }
                    array_lang['params'][lang]=JSON.stringify(tmp_param);
                    var exist_l = false;
                    jQuery.each(window.pois[index].array_lang, function(index_l,item_lang) {
                        if(item_lang.language==lang) {
                            exist_l = true;
                            item_lang.params=JSON.stringify(tmp_param);
                        }
                    });
                    if(!exist_l) {
                        window.pois[index].array_lang.push({'id_poi':id,'language':lang,'embed_content':'','label':'','tooltip_text':'','tooltip_text_mobile':'','title':'','description':'','content':'','params':JSON.stringify(tmp_param)});
                    }
                });
                break;
        }
        window.pois[index].target = target;
        window.pois[index].content = content;
        window.pois[index].params = params;
        window.pois[index].title = c_title;
        window.pois[index].description = c_description;
        window.pois[index].view_type = view_type;
        window.pois[index].box_pos = box_pos;
        window.pois[index].box_max_width = box_max_width;
        window.pois[index].box_maximize = box_maximize;
        window.pois[index].box_background = box_background;
        window.pois[index].box_color = box_color;
        window.pois[index].auto_close = auto_close;
        window.pois[index].id_icon_library = id_icon_library;
        window.pois[index].style = style;
        window.pois[index].icon_type = icon_type;
        window.pois[index].sound = sound;
        window.pois[index].background = background;
        window.pois[index].color = color;
        window.pois[index].label = label;
        window.pois[index].css_class = css_class;
        window.pois[index].tooltip_type = tooltip_type;
        window.pois[index].tooltip_visibility = tooltip_visibility;
        window.pois[index].tooltip_background = tooltip_background;
        window.pois[index].tooltip_color = tooltip_color;
        window.pois[index].tooltip_text = tooltip_text;
        window.pois[index].tooltip_text_mobile = tooltip_text_mobile;
        window.pois[index].embed_content = embed_content;
        window.pois[index].embed_video_autoplay = embed_video_autoplay;
        window.pois[index].embed_video_loop = embed_video_loop;
        window.pois[index].embed_gallery_autoplay = embed_gallery_autoplay;
        window.pois[index].embed_video_muted = embed_video_muted;
        window.pois[index].schedule = schedule;
        window.pois[index].song_bg_volume = song_bg_volume;
        window.pois[index].learning = learning;
        window.pois[index].learning_priority = learning_priority;
        window.pois_initial[index] = {...window.pois[index]};
        if($('#id_poi_autoopen').is(':checked')) {
            window.id_poi_autoopen = id;
        } else {
            if(window.id_poi_autoopen==id) {
                window.id_poi_autoopen = '';
            }
        }
        change_exclude_apply_all('poi');
        save_poi_edit(id,type,content,c_title,c_description,target,view_type,box_pos,box_max_width,box_maximize,song_bg_volume,params,auto_close,box_background,box_color,learning,learning_priority);
        save_poi_style(id,color,background,icon,style,id_icon_library,label,tooltip_type,tooltip_text,tooltip_text_mobile,css_class,embed_content,embed_video_autoplay,embed_video_loop,embed_video_muted,embed_gallery_autoplay,window.pois[index].embed_type,window.pois[index].animation,icon_type,window.pois[index].embed_params,tooltip_visibility,tooltip_background,tooltip_color,sound,array_lang);
        save_poi_schedule(id,schedule);
        $('.hotspot').removeClass('grouped_sel');
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_poi').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_marker').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        var yaw = parseFloat(window.pois[index].yaw);
        var pitch = parseFloat(window.pois[index].pitch);
        window.viewer.lookAt(pitch,yaw,window.viewer.getHfov(),200);
        $('.custom-hotspot-content').css('opacity',1);
        $('.poi_embded_helper').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embded_move').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embed').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_edit').hide();
        if(window.pois[index].embed_type!='') {
            render_poi(id,index);
        }
        if(window.pois[index].type=='callout') {
            close_callout(id);
        }
        parse_hs_list(window.pois,'poi');
    }

    window.exit_edit_poi = function (id,index) {
        window.pois[index] = {...window.pois_initial[index]};
        window.is_editing = false;
        window.grouped_selecting = false;
        render_poi(id,index);
        $('.hotspot').removeClass('grouped_sel');
        $('#rooms_slider_slider-container').removeClass('hide');
        $('#rooms_slider_content-container').removeClass('show');
        fix_all_embeds_pos();
        $(window).trigger('resize');
        $('#btn_add_poi').removeClass('disabled');
        $('#btn_list_hs').removeClass('disabled');
        $('#btn_switch_to_marker').removeClass('disabled');
        $('#btn_preview_modal').removeClass('disabled');
        $('#btn_toggle_fullscreen').removeClass('disabled');
        $('.rooms_view_sel').removeClass('disabled');
        $('.icon_visible_view').removeClass('disabled');
        var yaw = parseFloat(window.pois[index].yaw);
        var pitch = parseFloat(window.pois[index].pitch);
        window.currentYaw = yaw;
        window.currentPitch = pitch;
        window.currentHfov = parseFloat(window.viewer.getHfov());
        window.viewer.lookAt(pitch,yaw,window.currentHfov,200);
        $('.custom-hotspot-content').css('opacity',1);
        $('.hotspot-embed').css('opacity',1);
        $('#confirm_edit').hide();
        if(window.pois[index].type=='callout') {
            close_callout(id);
        }
    }

    function get_first_poi_embed_gallery_image(id) {
        var image = '';
        $.ajax({
            url: "ajax/get_first_poi_embed_gallery_image.php",
            type: "POST",
            data: {
                id_poi: id
            },
            async: false,
            success: function (rsp) {
                image = rsp;
            }
        });
        if(image!='') image='../viewer/gallery/'+image;
        return image;
    }

    function hotspot_measure(hotSpotDiv, args) {
        var div = document.createElement('div');
        div.id = 'measure_'+args.id+'_'+args.dir;
        div.classList.add('measure_points');
        div.classList.add('noselect');
        div.innerHTML = '';
        div.style.opacity = 0;
        div.style.width = '30px';
        div.style.height = '30px';
        div.style.border = '1px solid red';
        div.style.borderRadius = '50%';
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.style.pointerEvents = 'none';
        div.setAttribute('yaw',args.yaw);
        div.setAttribute('pitch',args.pitch);
        hotSpotDiv.appendChild(div);
    }

    function hotspot_p_callout(hotSpotDiv, args) {
        hotSpotDiv.classList.add('hotspot_'+args.id);
        hotSpotDiv.setAttribute('visible_multiview_ids',args.visible_multiview_ids);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.style.zIndex = args.zIndex;
        var json_callout = args.params;
        try {
            args_callout[args.id] = JSON.parse(json_callout);
        } catch (e) {
            return;
        }
        var tmp = args_callout[args.id].title_bg_color;
        tmp = tmp.replace('rgba(','').replace(')','');
        tmp = tmp.split(',');
        if(tmp[3]==0) {
            var title_margin = args_callout[args.id].title_margin+'px 0px';
        } else {
            var title_margin = args_callout[args.id].title_margin+'px';
        }
        switch(args_callout[args.id].dir) {
            case 'left':
                args_callout[args.id].rotate = args_callout[args.id].rotate + 180;
                var callout_html = '<div id="callout_'+args.id+'" class="callout" style="position: absolute; z-index: 2002; overflow: visible; background-color: '+args_callout[args.id].main_color+'; border: 0px solid rgb(0, 0, 0); border-radius: 10px; opacity: 1; cursor: pointer; pointer-events: initial; width: 10px; height: 10px; transform-origin: 50% 50%; transform: translateZ(0px) translate(0px, 0px) translate(-5px, -5px) rotate(315deg) translate(0px) scale(1, 1) translate(0px);">\n' +
                    '        <div id="callout_pointer_'+args.id+'" class="callout_pointer" style="position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; background-image: none; border: 2px solid '+args_callout[args.id].main_color+'; border-radius: 20px; width: 24px; height: 24px; transform: translateZ(1000000000000px) translate(-9px, -9px) translate(0px, 0px) rotate(0deg) translate(0px, 0px);"></div>\n' +
                    '        <div id="callout_line_'+args.id+'" class="callout_line" style="position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; background-image: none; background-color: '+args_callout[args.id].main_color+'; border: 0px solid rgb(0, 0, 0); border-radius: 0px; width: 2px; height: 0px; transform: translateZ(1000000000000px) translate(4px, 5px) translate(0px, 0px) rotate(0deg) translate(0px, 0px);">\n' +
                    '            <div id="callout_content_'+args.id+'" class="callout_content" style="position: absolute; z-index: 3001; overflow: hidden; opacity: 1; cursor: default; pointer-events: none; background-color: '+args_callout[args.id].content_bg_color+'; background-image: none; border-style: solid; border-color: '+args_callout[args.id].main_color+'; border-width: 0px 2px 0px 0px; border-radius: 0px; width: 0px; height: 0px; transform: translateZ(1000000000000px) translate(0px, 0px) translate(0px, 0px) rotate(-300deg) translate(0px, 0px);">\n' +
                    '                <div id="callout_title_'+args.id+'" class="callout_title" style="margin-top: 5px;font-size: '+args_callout[args.id].title_font_size+'px;position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; color: rgb(0, 0, 0); width: 300px; height: 49px; transform: translateZ(1000000000000px) translate(-104px, 0px) translate(47px, -24.5px) rotate(0deg) translate(-47px, 24.5px); background-image: none;">\n' +
                    '                    <div style="position: absolute; top: 0px; right: 0px; transform-origin: 0px 0px; transform: scale(1); width: 100%; height: 100%; line-height: normal; color: rgb(0, 0, 0); pointer-events: none; visibility: visible;">\n' +
                    '                        <div class="callout_title_bg" style="float:right;white-space: nowrap; background-color: '+args_callout[args.id].title_bg_color+';line-height: '+args_callout[args.id].title_font_size+'px;">\n' +
                    '                            <div class="callout_title_text" style="margin: '+title_margin+';color:'+args_callout[args.id].title_font_color+';text-align:right">'+args_callout[args.id].title+'<span style="width:0;height:0;"></span></div>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '                <div id="callout_description_'+args.id+'" class="callout_description" style="font-size: '+args_callout[args.id].description_font_size+'px;position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; color: rgb(0, 0, 0); width: 300px; height: 28px; transform: translateZ(1000000000000px) translate(-310px, -28px) translate(150px, 14px) rotate(0deg) translate(-150px, -14px); background-image: none;">\n' +
                    '                    <div style="position: absolute; top: 0px; left: 0px; transform-origin: 0px 0px; transform: scale(1); width: 100%; height: 100%; line-height: normal; color: rgb(0, 0, 0); pointer-events: none; visibility: visible;">\n' +
                    '                        <div style="position:absolute;width:100%;overflow:hidden;">\n' +
                    '                            <div class="callout_description_text" style="margin:10px 0px 0px 0px;color:'+args_callout[args.id].description_font_color+';text-align:right">'+args_callout[args.id].description+'<span style="width:0;height:0;"></span></div>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>\n' +
                    '    </div>';
                break;
            case 'right':
                var callout_html = '<div id="callout_'+args.id+'" class="callout" style="position: absolute; z-index: 3001; overflow: visible; background-color: '+args_callout[args.id].main_color+'; border: 0px solid rgb(0, 0, 0); border-radius: 10px; opacity: 1; cursor: pointer; pointer-events: initial; width: 10px; height: 10px; transform-origin: 50% 50%; transform: translateZ(0px) translate(0px, 0px) translate(-5px, -5px) rotate(45deg) translate(0px) scale(1, 1) translate(0px);">\n' +
                    '        <div id="callout_pointer_'+args.id+'" class="callout_pointer" style="position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; background-image: none; border: 2px solid '+args_callout[args.id].main_color+'; border-radius: 20px; width: 24px; height: 24px; transform: translateZ(1000000000000px) translate(-9px, -9px) translate(0px, 0px) rotate(0deg) translate(0px, 0px);"></div>\n' +
                    '        <div id="callout_line_'+args.id+'" class="callout_line" style="position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; background-image: none; background-color: '+args_callout[args.id].main_color+'; border: 0px solid rgb(0, 0, 0); border-radius: 0px; width: 2px; height: 0px; transform: translateZ(1000000000000px) translate(4px, 5px) translate(0px, 0px) rotate(0deg) translate(0px, 0px);">\n' +
                    '            <div id="callout_content_'+args.id+'" class="callout_content" style="position: absolute; z-index: 3001; overflow: hidden; opacity: 1; cursor: default; pointer-events: none; background-color: '+args_callout[args.id].content_bg_color+'; background-image: none; border-style: solid; border-color: '+args_callout[args.id].main_color+'; border-width: 0px 0px 0px 2px; border-radius: 0px; width: 0px; height: 0px; transform: translateZ(1000000000000px) translate(0px, 0px) translate(0px, 0px) rotate(-45deg) translate(0px, 0px);">\n' +
                    '                <div id="callout_title_'+args.id+'" class="callout_title" style="margin-top: 5px;font-size: '+args_callout[args.id].title_font_size+'px;position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; color: rgb(0, 0, 0); width: 158px; height: 49px; transform: translateZ(1000000000000px) translate(10px, 0px) translate(-79px, -24.5px) rotate(0deg) translate(79px, 24.5px); background-image: none;">\n' +
                    '                    <div style="position: absolute; top: 0px; left: 0px; transform-origin: 0px 0px; transform: scale(1); width: 100%; height: 100%; line-height: normal; color: rgb(0, 0, 0); pointer-events: none; visibility: visible;">\n' +
                    '                        <div class="callout_title_bg" style="position: absolute; white-space: nowrap; background-color: '+args_callout[args.id].title_bg_color+';line-height: '+args_callout[args.id].title_font_size+'px;">\n' +
                    '                            <div class="callout_title_text" style="margin: '+title_margin+';color:'+args_callout[args.id].title_font_color+';">'+args_callout[args.id].title+'<span style="width:0;height:0;"></span></div>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '                <div id="callout_description_'+args.id+'" class="callout_description" style="font-size: '+args_callout[args.id].description_font_size+'px;position: absolute; z-index: 3001; overflow: visible; opacity: 1; cursor: default; pointer-events: none; color: rgb(0, 0, 0); width: 300px; height: 103px; transform: translateZ(1000000000000px) translate(10px, -103px) translate(-150px, 51.5px) rotate(0deg) translate(150px, -51.5px); background-image: none;">\n' +
                    '                    <div style="position: absolute; top: 0px; left: 0px; transform-origin: 0px 0px; transform: scale(1); width: 100%; height: 100%; line-height: normal; color: rgb(0, 0, 0); pointer-events: none; visibility: visible;">\n' +
                    '                        <div style="position:absolute;width:100%;overflow:hidden;">\n' +
                    '                            <div class="callout_description_text" style="margin:10px 10px 0px 0px;color:'+args_callout[args.id].description_font_color+';">'+args_callout[args.id].description+'<span style="width:0;height:0;"></span></div>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>\n' +
                    '    </div>';
                break;
        }
        hotSpotDiv.innerHTML = callout_html;
    }

    function hotspot_p_staging(hotSpotDiv, args) {
        hotSpotDiv.classList.add('hotspot_'+args.id);
        hotSpotDiv.setAttribute('visible_multiview_ids',args.visible_multiview_ids);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.style.zIndex = args.zIndex;
        var i = document.createElement('i');
        i.style = "color:"+args.color;
        i.className = 'icon_s '+args.icon;
        hotSpotDiv.appendChild(i);
    }

    function open_callout(id) {
        var callout = document.getElementById('callout_'+id);
        var callout_pointer = document.getElementById('callout_pointer_'+id);
        var callout_line = document.getElementById('callout_line_'+id);
        var callout_content = document.getElementById('callout_content_'+id);
        var callout_title = document.getElementById('callout_title_'+id);
        var callout_description = document.getElementById('callout_description_'+id);
        callout.classList.add('callout_open');
        callout_pointer.classList.remove('callout_blink');
        var description_y = callout_title.getElementsByClassName("callout_title_bg")[0].offsetHeight;
        switch(args_callout[id].dir) {
            case 'left':
                callout_line.style.height = args_callout[id].line_size+'px';
                callout_line.style.transform = 'translateZ(1000000000000px) translate(4px, -'+(args_callout[id].line_size-5)+'px) translate(0px, '+(args_callout[id].line_size/2)+'px) rotate('+(args_callout[id].rotate-315)+'deg) translate(0px, -'+(args_callout[id].line_size/2)+'px)';
                callout_content.style.width = args_callout[id].content_width+'px';
                callout_content.style.height = args_callout[id].content_height+'px';
                callout_content.style.transform = 'translateZ(1000000000000px) translate(-'+args_callout[id].content_width+'px, -'+(args_callout[id].content_height/2)+'px) translate('+(args_callout[id].content_width/2)+'px, 0px) rotate(-'+args_callout[id].rotate+'deg) translate(-'+(args_callout[id].content_width/2)+'px, 0px)';
                callout_title.style.width = (args_callout[id].content_width-10)+'px';
                callout_title.style.transform = 'translateZ(1000000000000px) translate(0px, 0px) translate(150px, -24.5px) rotate(0deg) translate(-150px, 24.5px)';
                callout_description.style.width = (args_callout[id].content_width-10)+'px';
                callout_description.style.transform = 'translateZ(1000000000000px) translate(0px, '+description_y+'px) translate(150px, 0px) rotate(0deg) translate(-150px, 0px)';
                break;
            case 'right':
                callout_line.style.height = args_callout[id].line_size+'px';
                callout_line.style.transform = 'translateZ(1000000000000px) translate(4px, -'+(args_callout[id].line_size-5)+'px) translate(0px, '+(args_callout[id].line_size/2)+'px) rotate('+(args_callout[id].rotate-45)+'deg) translate(0px, -'+(args_callout[id].line_size/2)+'px)';
                callout_content.style.width = args_callout[id].content_width+'px';
                callout_content.style.height = args_callout[id].content_height+'px';
                callout_content.style.transform = 'translateZ(1000000000000px) translate(0px, -'+(args_callout[id].content_height/2)+'px) translate(-'+(args_callout[id].content_width/2)+'px, 0px) rotate(-'+args_callout[id].rotate+'deg) translate('+(args_callout[id].content_width/2)+'px, 0px)';
                callout_description.style.width = (args_callout[id].content_width-10)+'px';
                callout_description.style.transform = 'translateZ(1000000000000px) translate(10px, '+description_y+'px) translate(-150px, 0px) rotate(0deg) translate(150px, 0px)';
                break;
        }
    }

    function close_callout(id) {
        var callout = document.getElementById('callout_'+id);
        callout.classList.remove('callout_open');
        var callout_pointer = document.getElementById('callout_pointer_'+id);
        callout_pointer.classList.add('callout_blink');
        var callout_line = document.getElementById('callout_line_'+id);
        callout_line.style.height = '0px';
        callout_line.style.transform = 'translateZ(1000000000000px) translate(4px, 5px) translate(0px, 0px) rotate(0deg) translate(0px, 0px)';
        var callout_content = document.getElementById('callout_content_'+id);
        callout_content.style.width = '0px';
        callout_content.style.height = '0px';
        callout_content.style.transform = 'translateZ(1000000000000px) translate(0px, 0px) translate(0px, 0px) rotate(-45deg) translate(0px, 0px)';
        var callout_description = document.getElementById('callout_description_'+id);
        callout_description.style.transform = 'translateZ(1000000000000px) translate(10px, -103px) translate(-150px, 51.5px) rotate(0deg) translate(150px, -51.5px)';
    }

    window.change_callout_params = function() {
        var title_default = $('#callout_title').val();
        var description_default = window.callout_description_editor.root.innerHTML;
        if(window.selected_language=='' || window.selected_language==window.default_language) {
            var title = $('#callout_title').val();
            var description = window.callout_description_editor.root.innerHTML;
        } else {
            var title = $('.input_lang[data-target-id="callout_title"][data-lang="'+window.selected_language+'"]').val();
            var description = window.callout_description_editor_lang[window.selected_language].root.innerHTML;
        }
        var dir = $('#callout_dir option:selected').attr('id');
        var title_font_size = $('#callout_title_font_size').val();
        var title_margin = $('#callout_title_margin').val();
        var description_font_size = $('#callout_description_font_size').val();
        var main_color = $('#callout_main_color').val();
        var content_bg_color = $('#callout_content_bg_color').val();
        var title_font_color = $('#callout_title_font_color').val();
        var title_bg_color = $('#callout_title_bg_color').val();
        var description_font_color = $('#callout_description_font_color').val();
        var content_height = $('#callout_content_height').val();
        var content_width = $('#callout_content_width').val();
        var line_size = $('#callout_line_size').val();
        var rotate = $('#callout_rotate').val();
        var open = $('#callout_open option:selected').attr('id');
        var json = window.pois[poi_index_edit].params;
        var array = JSON.parse(json);
        array.title = title;
        array.description = description;
        array.dir = dir;
        array.title_font_size = title_font_size;
        array.title_margin = title_margin;
        array.description_font_size = description_font_size;
        array.main_color = main_color;
        array.content_bg_color = content_bg_color;
        array.title_font_color = title_font_color;
        array.title_bg_color = title_bg_color;
        array.description_font_color = description_font_color;
        array.content_height = parseInt(content_height);
        array.content_width = parseInt(content_width);
        array.line_size = parseInt(line_size);
        array.rotate = parseInt(rotate);
        array.open = open;
        window.pois[poi_index_edit].params = JSON.stringify(array);
        var array_d = JSON.parse(json);
        array_d.title = title_default;
        array_d.description = description_default;
        array_d.dir = dir;
        array_d.title_font_size = title_font_size;
        array_d.title_margin = title_margin;
        array_d.description_font_size = description_font_size;
        array_d.main_color = main_color;
        array_d.content_bg_color = content_bg_color;
        array_d.title_font_color = title_font_color;
        array_d.title_bg_color = title_bg_color;
        array_d.description_font_color = description_font_color;
        array_d.content_height = parseInt(content_height);
        array_d.content_width = parseInt(content_width);
        array_d.line_size = parseInt(line_size);
        array_d.rotate = parseInt(rotate);
        array_d.open = open;
        window.pois[poi_index_edit].params_d = JSON.stringify(array_d);
        render_poi(poi_id_edit,poi_index_edit);
        open_callout(poi_id_edit);
    }

    function hotspot_p(hotSpotDiv, args) {
        hotSpotDiv.classList.add('hotspot_'+args.id);
        hotSpotDiv.setAttribute('visible_multiview_ids',args.visible_multiview_ids);
        hotSpotDiv.classList.add('noselect');
        if(args.what=='marker') {
            hotSpotDiv.style.opacity = 0.3;
        }
        hotSpotDiv.style.zIndex = args.zIndex;
        var div_wrapper = document.createElement('div');
        div_wrapper.classList.add('div_poi_wrapper');
        if(args.animation!='none') {
            div_wrapper.classList.add('animate__animated');
            div_wrapper.classList.add('animate__slow');
            div_wrapper.classList.add('animate__'+args.animation);
            div_wrapper.classList.add('animate__infinite');
        }
        var lottie = false;
        if(args.what=='poi' && args.type=='audio') {
            if($('#poi_song_player').is(':visible')) {
                var player = $('#poi_song_player option:selected').attr('id');
            } else {
                var player = args.params;
            }
            if(player=='minimal') {
                if(parseInt(args.style)==1 || parseInt(args.style)==4) {
                    args.style = 0;
                }
                args.icon = "fas fa-play";
            }
        }
        var style_t = parseInt(args.style);
        if(style_t==1) {
            var icon_type = 'round';
        } else {
            var icon_type = args.icon_type;
        }
        switch(icon_type) {
            case 'square':
                div_wrapper.style.borderRadius = '3px';
                break;
            case 'round_outline':
                div_wrapper.style.borderWidth = '2px';
                div_wrapper.style.borderStyle = 'solid';
                div_wrapper.style.borderColor = args.color;
                break;
            case 'square_outline':
                div_wrapper.style.borderRadius = '3px';
                div_wrapper.style.borderWidth = '2px';
                div_wrapper.style.borderStyle = 'solid';
                div_wrapper.style.borderColor = args.color;
                break;
        }
        var label = args.label;
        if(window.is_editing) {
            if($('#poi_label').is(':visible')) {
                label = $('#poi_label').val();
            } else {
                $('.input_lang[data-target-id="poi_label"]').each(function() {
                    if($(this).is(':visible')) {
                        label = $(this).val();
                    }
                });
            }
        }
        switch (style_t) {
            case 0:
                var i = document.createElement('i');
                i.className = args.icon;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                break;
            case 1:
                var ext = args.img_icon_library.split('.').pop().toLowerCase();
                if(ext=='json') {
                    lottie = true;
                    hotSpotDiv.classList.add('lottie_icon');
                    var div = document.createElement('div');
                    div.innerHTML = '<div id="lottie_p_'+args.id+'" style="height:100px;width:100px;vertical-align:middle"></div>';
                    hotSpotDiv.appendChild(div);
                    var id_vt_library = args.id_vt_library;
                    if(window.s3_enabled==1 && id_vt_library!='') {
                        var image_url = window.s3_url+'viewer/icons/'+args.img_icon_library+'?s3=1';
                    } else {
                        var image_url = '../viewer/icons/'+args.img_icon_library;
                    }
                    bodymovin.loadAnimation({
                        container: document.getElementById('lottie_p_'+args.id),
                        renderer: 'svg',
                        loop: true,
                        autoplay: true,
                        path: image_url,
                        rendererSettings: {
                            progressiveLoad: true,
                        }
                    });
                } else {
                    var img = document.createElement('img');
                    if(isSVG(args.img_icon_library)) {
                        var id_vt_library = args.id_vt_library;
                        if(window.s3_enabled==1 && id_vt_library!='') {
                            var image_url = window.s3_url+'viewer/icons/'+args.img_icon_library+'?s3=1';
                        } else {
                            var image_url = '../viewer/icons/'+args.img_icon_library;
                        }
                        img.src = image_url;
                    } else {
                        img.src = args.base64_icon_library;
                    }
                    img.style = "width:100px";
                    img.draggable = false;
                    div_wrapper.appendChild(img);
                }
                break;
            case 2:
                var i = document.createElement('i');
                i.className = args.icon;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                var span = document.createElement('span');
                span.innerHTML = '&nbsp;'+label;
                span.style = "vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                }
                div_wrapper.appendChild(span);
                break;
            case 3:
                var span = document.createElement('span');
                span.innerHTML = label+'&nbsp;';
                span.style = "vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                }
                div_wrapper.appendChild(span);
                var i = document.createElement('i');
                i.className = args.icon;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                break;
            case 4:
                var span = document.createElement('span');
                span.innerHTML = label;
                span.style = "font-size:32px;vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(span);
                break;
        }
        if(lottie==false) hotSpotDiv.appendChild(div_wrapper);
    }

    function hotspot_m(hotSpotDiv, args) {
        hotSpotDiv.classList.add('custom-tooltip');
        hotSpotDiv.classList.add('hotspot_'+args.id);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.setAttribute('visible_multiview_ids',args.visible_multiview_ids);
        var div_wrapper = document.createElement('div');
        div_wrapper.classList.add('div_marker_wrapper');
        if(args.animation!='none') {
            div_wrapper.classList.add('animate__animated');
            div_wrapper.classList.add('animate__slow');
            div_wrapper.classList.add('animate__'+args.animation);
            div_wrapper.classList.add('animate__infinite');
        }
        hotSpotDiv.style.zIndex = args.zIndex;
        var show_room_t = parseInt(args.show_room);
        if(show_room_t==4 || show_room_t==5) {
            var icon_type = 'round';
        } else {
            var icon_type = args.icon_type;
        }
        switch(icon_type) {
            case 'square':
                div_wrapper.style.borderRadius = '3px';
                break;
            case 'round_outline':
                div_wrapper.style.borderWidth = '2px';
                div_wrapper.style.borderStyle = 'solid';
                div_wrapper.style.borderColor = args.color;
                break;
            case 'square_outline':
                div_wrapper.style.borderRadius = '3px';
                div_wrapper.style.borderWidth = '2px';
                div_wrapper.style.borderStyle = 'solid';
                div_wrapper.style.borderColor = args.color;
                break;
        }
        var lottie = false;
        var label = args.label;
        if(window.is_editing) {
            if($('#marker_label').is(':visible')) {
                label = $('#marker_label').val();
            } else {
                $('.input_lang[data-target-id="marker_label"]').each(function() {
                    if($(this).is(':visible')) {
                        label = $(this).val();
                    }
                });
            }
        }
        switch (show_room_t) {
            case 0:
                var i = document.createElement('i');
                i.className = args.icon+" marker_img_"+args.id_room_target;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                break;
            case 1:
                var i = document.createElement('i');
                i.className = args.icon+" marker_img_"+args.id_room_target;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                var span = document.createElement('span');
                span.innerHTML = '&nbsp;'+args.name_room_target.toUpperCase();
                span.style = "vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                }
                div_wrapper.appendChild(span);
                break;
            case 2:
                var span = document.createElement('span');
                span.innerHTML = args.name_room_target.toUpperCase()+'&nbsp;';
                span.style = "vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                }
                div_wrapper.appendChild(span);
                var i = document.createElement('i');
                i.className = args.icon+" marker_img_"+args.name_room_target;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                break;
            case 3:
                var span = document.createElement('span');
                span.innerHTML = args.name_room_target.toUpperCase();
                span.style = "font-size:32px;vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(span);
                break;
            case 4:
                var ext = args.img_icon_library.split('.').pop().toLowerCase();
                if(ext=='json') {
                    lottie = true;
                    hotSpotDiv.classList.add('lottie_icon');
                    var div = document.createElement('div');
                    div.innerHTML = '<div id="lottie_m_'+args.id+'" style="height:100px;width:100px;vertical-align:middle"></div>';
                    hotSpotDiv.appendChild(div);
                    var id_vt_library = args.id_vt_library;
                    if(window.s3_enabled==1 && id_vt_library!='') {
                        var image_url = window.s3_url+'viewer/icons/'+args.img_icon_library+'?s3=1';
                    } else {
                        var image_url = '../viewer/icons/'+args.img_icon_library;
                    }
                    bodymovin.loadAnimation({
                        container: document.getElementById('lottie_m_'+args.id),
                        renderer: 'svg',
                        loop: true,
                        autoplay: true,
                        path: image_url,
                        rendererSettings: {
                            progressiveLoad: true,
                        }
                    });
                } else {
                    var img = document.createElement('img');
                    if(isSVG(args.img_icon_library)) {
                        var id_vt_library = args.id_vt_library;
                        if(window.s3_enabled==1 && id_vt_library!='') {
                            var image_url = window.s3_url+'viewer/icons/'+args.img_icon_library+'?s3=1';
                        } else {
                            var image_url = '../viewer/icons/'+args.img_icon_library;
                        }
                        img.src = image_url;
                    } else {
                        img.src = args.base64_icon_library;
                    }
                    img.style = "width:100px";
                    img.draggable = false;
                    div_wrapper.appendChild(img);
                }
                break;
            case 5:
                var image = args.base64_marker_preview;
                var div = document.createElement('div');
                div.classList.add('marker_preview');
                div.style = 'width:96px;height:96px;border-radius:50%;background-image: url('+image+');background-size: cover;background-position: center;';
                div_wrapper.appendChild(div);
                break;
            case 6:
                var i = document.createElement('i');
                i.className = args.icon+" marker_img_"+args.id_room_target;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                var span = document.createElement('span');
                span.innerHTML = '&nbsp;'+label;
                span.style = "vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                }
                div_wrapper.appendChild(span);
                break;
            case 7:
                var span = document.createElement('span');
                span.innerHTML = label+'&nbsp;';
                span.style = "vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                }
                div_wrapper.appendChild(span);
                var i = document.createElement('i');
                i.className = args.icon+" marker_img_"+args.name_room_target;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(icon_type=='stroke') {
                    i.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(i);
                break;
            case 8:
                var span = document.createElement('span');
                span.innerHTML = label;
                span.style = "font-size:32px;vertical-align:middle;color:"+args.color;
                if(icon_type=='stroke') {
                    span.style.textShadow = '-1px -1px 0 '+args.background+', 1px -1px 0 '+args.background+', -1px 1px 0 '+args.background+', 1px 1px 0 '+args.background;
                } else {
                    div_wrapper.style.background = args.background;
                }
                div_wrapper.appendChild(span);
                break;
        }
        if(lottie==false) hotSpotDiv.appendChild(div_wrapper);
    }

    function get_pois(id_room,image,id_poi_add) {
        $.ajax({
            url: "ajax/get_pois.php",
            type: "POST",
            data: {
                id_room: id_room,
                edit_room: 0
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                window.pois = rsp.pois;
                parse_hs_list(window.pois,'poi');
                var array_room = rsp.room;
                if(array_room.room_type=='image') {
                    $('#btn_edit_content_staging').removeClass('disabled');
                    $('#btn_new_poi_staging').removeClass('disabled');
                } else {
                    $('#btn_edit_content_staging').addClass('disabled');
                    $('#btn_new_poi_staging').addClass('disabled');
                }
                window.id_poi_autoopen = array_room.id_poi_autoopen;
                window.pois_initial = JSON.parse(JSON.stringify(window.pois));
                initialize_pano_pois(id_room,image,id_poi_add,array_room);
            }
        });
    }

    window.get_pois_edit_rooms = function(id_room) {
        $.ajax({
            url: "ajax/get_pois.php",
            type: "POST",
            data: {
                id_room: id_room,
                edit_room: 1
            },
            async: false,
            success: function (json) {
                var rsp = JSON.parse(json);
                window.pois = rsp.pois;
            }
        });
    }

    function get_measures(id_room,image,id_measure_add) {
        $.ajax({
            url: "ajax/get_measures.php",
            type: "POST",
            data: {
                id_room: id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                window.measures = rsp.measures;
                parse_hs_list(window.measures,'measure');
                var array_room = rsp.room;
                window.measures_initial = JSON.parse(JSON.stringify(window.measures));
                initialize_pano_measures(id_room,image,array_room,id_measure_add);
            }
        });
    }

    function handleGroupedObjects(objects,objects_sorted,id_object_added,hs,currentSortLevel) {
        if (!id_object_added.includes(parseInt(hs.id))) {
            hs.sort_level = currentSortLevel;
            id_object_added.push(parseInt(hs.id));
            objects_sorted.push(hs);
            var id_grouped_pois = hs.content;
            if (id_grouped_pois != '') {
                id_grouped_pois = id_grouped_pois.split(",");
                $.each(id_grouped_pois, function (index_igp, hs_igp) {
                    $.each(objects, function (index2, hs2) {
                        if (hs2.id == hs_igp) {
                            if (hs2.type == 'grouped') {
                                handleGroupedObjects(objects,objects_sorted,id_object_added,hs2,currentSortLevel+1);
                            } else {
                                hs2.sort_level = currentSortLevel+1;
                                if (!id_object_added.includes(parseInt(hs2.id))) {
                                    id_object_added.push(parseInt(hs2.id));
                                    objects_sorted.push(hs2);
                                }
                            }
                            return false;
                        }
                    });
                });
            }
        }
    }

    function parse_hs_list(objects,type) {
        var html = '';
        var count = 0;
        if(type=='poi') {
            var objects_sorted = [];
            var id_object_added = [];
            $.each(objects,function(index,hs) {
                if (hs.type == 'grouped') {
                    handleGroupedObjects(objects,objects_sorted,id_object_added,hs,0);
                }
            });
            $.each(objects,function(index,hs) {
                if(hs.type!='grouped') {
                    if(!id_object_added.includes(parseInt(hs.id))) {
                        hs.sort_level = 0;
                        id_object_added.push(parseInt(hs.id));
                        objects_sorted.push(hs);
                    }
                }
            });
        } else {
            var objects_sorted = objects;
        }
        $.each(objects_sorted,function(index,hs) {
            var hs_label = '';
            if(type=='measure') {
                count++;
                hs_label += '<i class="fas fa-arrows-alt-h"></i>&nbsp;&nbsp;'+window.backend_labels.measure_label;
                var hs_title = hs_label;
                html += '<button id="hs_'+hs.id+'" onclick="click_hs('+hs.id+',\''+type+'\');" type="button" class="list-group-item list-group-item-action"><span class="badge badge-light badge-pill">'+(index+1)+'</span>&nbsp;&nbsp;<span class="hs_title">'+hs_title+'</span></button>';
            } else {
                if(hs.what==type) {
                    count++;
                    switch(type) {
                        case 'marker':
                            switch(hs.embed_type) {
                                case 'selection':
                                    hs_label += '<i class="far fa-square"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                default:
                                    hs_label += '<i class="fas fa-info-circle"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                            }
                            var hs_title = hs_label+' '+hs.name_room_target;
                            break;
                        case 'poi':
                            switch(hs.embed_type) {
                                case 'image':
                                    hs_label += '<i class="fas fa-image"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'video':
                                    hs_label += '<i class="fab fa-youtube"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'video_transparent':
                                case 'video_chroma':
                                    hs_label += '<i class="fas fa-video"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'object3d':
                                    hs_label += '<i class="fas fa-cube"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'gallery':
                                    hs_label += '<i class="fas fa-images"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'link':
                                    hs_label += '<i class="fas fa-external-link-alt"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'text':
                                    hs_label += '<i class="fas fa-heading"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'html':
                                    hs_label += '<i class="fas fa-code"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                case 'selection':
                                    hs_label += '<i class="far fa-square"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                                default:
                                    hs_label += '<i class="fas fa-info-circle"></i> <i class="fas fa-caret-right"></i> ';
                                    break;
                            }
                            switch(hs.type) {
                                case 'image':
                                    hs_label += '<i class="fas fa-image"></i> '+window.backend_labels.image;
                                    break;
                                case 'gallery':
                                    hs_label += '<i class="fas fa-images"></i> '+window.backend_labels.image_gallery;
                                    break;
                                case 'video':
                                    hs_label += '<i class="fab fa-youtube"></i> '+window.backend_labels.video;
                                    break;
                                case 'audio':
                                    hs_label += '<i class="fas fa-music"></i> '+window.backend_labels.audio;
                                    break;
                                case 'video360':
                                    hs_label += '<i class="fas fa-video"></i> '+window.backend_labels.video360;
                                    break;
                                case 'link':
                                    hs_label += '<i class="fas fa-link"></i> '+window.backend_labels.link;
                                    break;
                                case 'pdf':
                                    hs_label += '<i class="fas fa-file-pdf"></i> '+window.backend_labels.pdf;
                                    break;
                                case 'pointclouds':
                                    hs_label += '<i class="fas fa-dice-d20"></i> '+window.backend_labels.pointclouds;
                                    break;
                                case 'link_ext':
                                    hs_label += '<i class="fas fa-external-link-alt"></i> '+window.backend_labels.link_ext;
                                    break;
                                case 'html':
                                    hs_label += '<i class="fas fa-heading"></i> '+window.backend_labels.html;
                                    break;
                                case 'html_sc':
                                    hs_label += '<i class="fas fa-code"></i> '+window.backend_labels.html_sc;
                                    break;
                                case 'download':
                                    hs_label += '<i class="fas fa-download"></i> '+window.backend_labels.download;
                                    break;
                                case 'form':
                                    hs_label += '<i class="fab fa-wpforms"></i> '+window.backend_labels.form;
                                    break;
                                case 'google_maps':
                                    hs_label += '<i class="fas fa-map"></i> '+window.backend_labels.google_maps;
                                    break;
                                case 'object360':
                                    hs_label += '<i class="fas fa-compact-disc"></i> '+window.backend_labels.object360;
                                    break;
                                case 'object3d':
                                    hs_label += '<i class="fas fa-cube"></i> '+window.backend_labels.object3d;
                                    break;
                                case 'lottie':
                                    hs_label += '<i class="fab fa-deviantart"></i> Lottie';
                                    break;
                                case 'product':
                                    hs_label += '<i class="fas fa-shopping-cart"></i> '+window.backend_labels.product;
                                    break;
                                case 'switch_pano':
                                    hs_label += '<i class="fas fa-sync-alt"></i> '+window.backend_labels.switch_pano;
                                    break;
                                case 'callout':
                                    var title = '';
                                    if(hs.params!='' && hs.params!=null && hs.params!=undefined) {
                                        var params = JSON.parse(hs.params);
                                        if(params.title!='' && params.title!=null && params.title!=undefined) {
                                            title = ' - '+params.title;
                                        }
                                    }
                                    hs_label = '<i class="far fa-dot-circle"></i> '+window.backend_labels.callout+title;
                                    break;
                                case 'staging':
                                    hs_label = '<i class="fas fa-arrows-spin"></i> '+window.backend_labels.staging;
                                    break;
                                case 'grouped':
                                    var id_grouped_sel = hs.content;
                                    if(id_grouped_sel!='' && id_grouped_sel!=null) {
                                        var count_grouped = id_grouped_sel.split(",").length;
                                    } else {
                                        var count_grouped = 0;
                                    }
                                    hs_label = '<i class="fas fa-braille"></i> '+window.backend_labels.grouped+' ('+count_grouped+' '+window.backend_labels.pois+')';
                                    break;
                                default:
                                    switch(hs.embed_type) {
                                        case 'image':
                                            hs_label = '<i class="fas fa-image"></i> '+window.backend_labels.embed_image;
                                            break;
                                        case 'video':
                                            hs_label = '<i class="fas fa-video"></i> '+window.backend_labels.embed_video;
                                            break;
                                        case 'video_transparent':
                                            hs_label = '<i class="fas fa-video"></i> '+window.backend_labels.embed_video_transparent;
                                            break;
                                        case 'video_chroma':
                                            hs_label = '<i class="fas fa-video"></i> '+window.backend_labels.embed_video_chroma;
                                            break;
                                        case 'object3d':
                                            hs_label = '<i class="fas fa-cube"></i> '+window.backend_labels.embed_object3d;
                                            break;
                                        case 'gallery':
                                            hs_label = '<i class="fas fa-images"></i> '+window.backend_labels.embed_gallery;
                                            break;
                                        case 'link':
                                            hs_label = '<i class="fas fa-images"></i> '+window.backend_labels.embed_link;
                                            break;
                                        case 'text':
                                            hs_label = '<i class="fas fa-heading"></i> '+window.backend_labels.embed_text;
                                            break;
                                        case 'html':
                                            hs_label = '<i class="fas fa-code"></i> '+window.backend_labels.embed_html;
                                            break;
                                        case 'selection':
                                            hs_label = '<i class="far fa-square"></i> '+window.backend_labels.embed_selection;
                                            break;
                                        default:
                                            if(hs.type != 'callout' && hs.type != 'grouped') {
                                                hs_label += '<i class="fas fa-ban"></i> '+window.backend_labels.none;
                                            }
                                            break;
                                    }
                                    break;
                            }
                            var hs_title = hs_label;
                            break;
                    }
                    html += '<button id="hs_'+hs.id+'" onclick="click_hs('+hs.id+',\''+type+'\');" type="button" class="list-group-item list-group-item-action">'+((type=='poi') ? "<i style='font-size:10px;vertical-align:middle;' class='fas fa-minus'></i>".repeat(hs.sort_level) : '')+'<span class="badge badge-light badge-pill">'+(index+1)+'</span>&nbsp;&nbsp;<span class="hs_title">'+hs_title+'</span></button>';
                }
            }
        });
        if(count==0) {
            $('#btn_list_hs').addClass('disabled_d');
        } else {
            $('#btn_list_hs').removeClass('disabled_d');
        }
        $('.hs_badge_count').html(count);
        $('#slider_hs_list .list-group').html(html);
    }

    window.click_hs = function(id,type) {
        $('#action_box').hide();
        $('#slider_hs_list .list-group button').removeClass('active');
        switch(type) {
            case 'marker':
                click_edit_marker('',id);
                break;
            case 'poi':
                click_edit_poi('',id);
                break;
            case 'measure':
                click_edit_measure(id);
                break;
        }
    }

    window.change_marker_room_target = function (id,index,id_select) {
        $('#confirm_edit .btn_confirm').addClass("disabled");
        $('#confirm_edit .btn_confirm_go').addClass("disabled");
        $('#btn_new_marker').addClass("disabled");
        switch(id_select) {
            case 'room_target_add':
                $('#override_pos_add').prop('checked',false);
                var event = new Event('change');
                $('#override_pos_add')[0].dispatchEvent(event);
                $('#override_look_add').prop('checked',false);
                var event = new Event('change');
                $('#override_look_add')[0].dispatchEvent(event);
                if(window.markers_default_backlink==1) {
                    $('#backlink_marker').prop('checked',true);
                } else {
                    $('#backlink_marker').prop('checked',false);
                }
                break;
            case 'room_target':
                $('#override_pos_edit').prop('checked',false);
                var event = new Event('change');
                $('#override_pos_edit')[0].dispatchEvent(event);
                $('#override_look_edit').prop('checked',false);
                var event = new Event('change');
                $('#override_look_edit')[0].dispatchEvent(event);
                break;
        }
        var name_room_target = $('#'+id_select).val();
        var id_room_target = $('#'+id_select+' option:selected').attr('id');
        if(id_select=='room_target') {
            window.markers[index].name_room_target = name_room_target;
            window.markers[index].id_room_target = id_room_target;
            render_marker(id,index);
            if(id_room_target == id_room_target_sel) {
                var yaw_m = window.markers[index].yaw_room_target;
                var pitch_m = window.markers[index].pitch_room_target;
                var yaw_look_m = window.markers[index].yaw_look_room_target;
                var pitch_look_m = window.markers[index].pitch_look_room_target;
                if((yaw_m=='') && (pitch_m=='')) {
                    $('#override_pos_edit').prop('checked',false);
                } else {
                    $('#override_pos_edit').prop('checked',true);
                }
                var event = new Event('change');
                $('#override_pos_edit')[0].dispatchEvent(event);
                if((yaw_look_m=='') && (pitch_look_m=='')) {
                    $('#override_look_edit').prop('checked',false);
                } else {
                    $('#override_look_edit').prop('checked',true);
                }
                var event = new Event('change');
                $('#override_look_edit')[0].dispatchEvent(event);
            } else {
                $('#override_pos_edit').prop('checked',false);
                var event = new Event('change');
                $('#override_pos_edit')[0].dispatchEvent(event);
                $('#override_look_edit').prop('checked',false);
                var event = new Event('change');
                $('#override_look_edit')[0].dispatchEvent(event);
            }
        }
        change_preview_room_image(id_room_target,id_select,index);
    }

    function change_preview_room_image(id_room_target,id_select,index_marker) {
        id_room_target = parseInt(id_room_target);
        jQuery.each(window.rooms, function(index, room) {
            var id_room = parseInt(room.id);
            if(id_room==id_room_target) {
                var room_image = room.panorama_image;
                if(window.s3_enabled==1) {
                    $('.preview_room_target').attr('src',window.s3_url+'viewer/panoramas/thumb/'+room_image);
                } else {
                    $('.preview_room_target').attr('src','../viewer/panoramas/thumb/'+room_image);
                }
                $('.preview_room_target').show();
                if(index_marker!=null && id_room_target==id_room_target_sel) {
                    var yaw_m = window.markers[index_marker].yaw_room_target;
                    var pitch_m = window.markers[index_marker].pitch_room_target;
                    var yaw_look_m = window.markers[index_marker].yaw_look_room_target;
                    var pitch_look_m = window.markers[index_marker].pitch_look_room_target;
                    if((yaw_m=='') && (pitch_m=='')) {
                        var yaw = parseFloat(room.yaw);
                        var pitch = parseFloat(room.pitch);
                    } else {
                        var yaw = parseFloat(window.markers[index_marker].yaw_room_target);
                        var pitch = parseFloat(window.markers[index_marker].pitch_room_target);
                    }
                    if((yaw_look_m=='') && (pitch_look_m=='')) {
                        var yaw_look_m = parseFloat(room.yaw);
                        var pitch_look_m = parseFloat(room.pitch);
                    } else {
                        var yaw_look_m = parseFloat(window.markers[index_marker].yaw_look_room_target);
                        var pitch_look_m = parseFloat(window.markers[index_marker].pitch_look_room_target);
                    }
                } else {
                    var yaw = parseFloat(room.yaw);
                    var pitch = parseFloat(room.pitch);
                    var yaw_look_m = yaw;
                    var pitch_look_m = pitch;
                }
                var h_pitch = room.h_pitch;
                var h_roll = room.h_roll;
                if(parseInt(room.allow_pitch)==1) {
                    var min_pitch = room.min_pitch;
                    var max_pitch = room.max_pitch;
                } else {
                    var min_pitch = 0;
                    var max_pitch = 0;
                    pitch = 0;
                }
                var min_yaw = room.min_yaw;
                var max_yaw = room.max_yaw;
                var haov = room.haov;
                var vaov = room.vaov;
                if(window.s3_enabled==1) {
                    var panorama_image = window.s3_url+'viewer/panoramas/lowres/'+room_image+'?s3=1';
                } else {
                    var panorama_image = '../viewer/panoramas/lowres/'+room_image;
                }
                if(window.sameAzimuth!==undefined) {
                    if(window.sameAzimuth==1) {
                        var current_north = parseInt(window.viewer.getNorthOffset());
                        var current_yaw = parseFloat(window.viewer.getYaw());
                        yaw = current_yaw + (current_north || 0) - (parseInt(room.northOffset) || 0);
                        pitch = 0;
                        if(index_marker!=null && id_room_target==id_room_target_sel) {
                            if((window.markers[index_marker].yaw_look_room_target=='') && (window.markers[index_marker].pitch_look_room_target=='')) {
                                yaw_look_m = yaw;
                                pitch_look_m = pitch;
                            }
                        } else {
                            yaw_look_m = yaw;
                            pitch_look_m = pitch;
                        }
                    }
                }
                if(id_select=='room_target_add') {
                    load_viewer_pos('panorama_pos_add',id_room,panorama_image,yaw,pitch,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,100);
                    load_viewer_look('panorama_look_add',id_room,panorama_image,yaw_look_m,pitch_look_m,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,100);
                } else {
                    load_viewer_pos('panorama_pos_edit',id_room,panorama_image,yaw,pitch,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,100);
                    load_viewer_look('panorama_look_edit',id_room,panorama_image,yaw_look_m,pitch_look_m,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,100);
                }
                return;
            }
        });
    }

    window.change_preview_room_image_map = function (id_room_sel) {
        if(id_room_sel==null) {
            id_room_sel = $('#room_select option:selected').attr('id');
        }
        jQuery.each(window.map_points, function(index, map_point) {
            var id_room = map_point.id;
            if(id_room==id_room_sel) {
                var room_image = map_point.room_image;
                $('.preview_room_target').attr('src',room_image);
                $('.preview_room_target').show();
                return;
            }
        });
    }

    window.change_preview_vt_image_map = function (id_vt_sel) {
        if(id_vt_sel==null) {
            id_vt_sel = $('#vt_select_map option:selected').attr('id');
        }
        jQuery.each(window.map_points, function(index, map_point) {
            var id_vt = map_point.id;
            if(id_vt==id_vt_sel) {
                var vt_image = map_point.background_image;
                if(vt_image!='') {
                    $('.preview_vt_target').attr('src',vt_image);
                    $('.preview_vt_target').show();
                } else {
                    $('.preview_vt_target').hide();
                }
                return;
            }
        });
    }

    window.change_preview_room_image_presentation = function (id_room_sel) {
        var id_room_sel = $('#p_room option:selected').attr('id');
        var panorama_type = $('#p_room option:selected').attr('data-type');
        if(panorama_type=='video') {
            $('#p_wait_video_end').parent().parent().show();
        } else {
            $('#p_wait_video_end').parent().parent().hide();
        }
        jQuery.each(window.rooms, function(index, room) {
            var id_room = room.id;
            if(id_room==id_room_sel) {
                $('#btn_add_p_room').addClass('disabled');
                var room_image = room.panorama_image;
                if(window.s3_enabled==1) {
                    $('.preview_room_target').attr('src',window.s3_url+'viewer/panoramas/thumb/'+room_image);
                } else {
                    $('.preview_room_target').attr('src','../viewer/panoramas/thumb/'+room_image);
                }
                $('.preview_room_target').show();
                var index_p_sel = -1;
                jQuery.each(array_presentation,function(index_p,array_p) {
                    if(array_p.action=='goto' && array_p.id_room==id_room_sel) {
                        index_p_sel=index_p;
                    }
                });
                if(index_p_sel!=-1) {
                    if(array_presentation[index_p_sel].pos=='') {
                        $('#override_pos_presentation').prop('checked',false);
                        var yaw = parseFloat(room.yaw);
                        var pitch = parseFloat(room.pitch);
                        var hfov = 100;
                    } else {
                        $('#override_pos_presentation').prop('checked',true);
                        var tmp = array_presentation[index_p_sel].pos.split(",");
                        var yaw = parseFloat(tmp[0]);
                        var pitch = parseFloat(tmp[1]);
                        var hfov = parseInt(tmp[2]);
                    }
                } else {
                    $('#override_pos_presentation').prop('checked',false);
                    var yaw = parseFloat(room.yaw);
                    var pitch = parseFloat(room.pitch);
                    var hfov = 100;
                }
                var h_pitch = room.h_pitch;
                var h_roll = room.h_roll;
                if(parseInt(room.allow_pitch)==1) {
                    var min_pitch = room.min_pitch;
                    var max_pitch = room.max_pitch;
                } else {
                    var min_pitch = 0;
                    var max_pitch = 0;
                    pitch = 0;
                }
                var min_yaw = room.min_yaw;
                var max_yaw = room.max_yaw;
                var haov = room.haov;
                var vaov = room.vaov;
                if(window.s3_enabled==1) {
                    var panorama_image = window.s3_url+'viewer/panoramas/lowres/'+room_image+'?s3=1';
                } else {
                    var panorama_image = '../viewer/panoramas/lowres/'+room_image;
                }
                load_viewer_pos('panorama_pos_presentation',id_room,panorama_image,yaw,pitch,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,hfov,null);
                return;
            }
        });
    }

    window.change_marker_style_v = function() {
        var style = $('#markers_style option:selected').attr('id');
        switch(style) {
            case 'custom_icon':
                $('#m_icon').addClass('d-none').addClass('disabled');
                $('#m_custom_icon').removeClass('d-none').removeClass('disabled');
                $('#markers_color').addClass('disabled');
                $('#markers_background').addClass('disabled');
                $('#markers_icon_type').addClass('disabled');
                break;
            case 'only_room':
            case 'only_label':
                $('#m_icon').removeClass('d-none').addClass('disabled');
                $('#m_custom_icon').addClass('d-none').addClass('disabled');
                $('#markers_color').removeClass('disabled');
                $('#markers_background').removeClass('disabled');
                $('#markers_icon_type').removeClass('disabled');
                break;
            case 'preview_room':
                $('#m_icon').removeClass('d-none').addClass('disabled');
                $('#m_custom_icon').addClass('d-none').addClass('disabled');
                $('#markers_color').addClass('disabled');
                $('#markers_background').addClass('disabled');
                $('#markers_icon_type').addClass('disabled');
                break;
            default:
                $('#m_icon').removeClass('d-none').removeClass('disabled');
                $('#m_custom_icon').addClass('d-none').addClass('disabled');
                $('#markers_color').removeClass('disabled');
                $('#markers_background').removeClass('disabled');
                $('#markers_icon_type').removeClass('disabled');
                break;
        }
        var icon_type = $('#markers_icon_type option:selected').attr('id');
        $('.div_marker_wrapper_bg i').css('-webkit-text-stroke','');
        $('.div_marker_wrapper_bg i').css('text-shadow','');
        $('.div_marker_wrapper_bg span').css('-webkit-text-stroke','');
        $('.div_marker_wrapper_bg span').css('text-shadow','');
        switch(icon_type) {
            case 'round':
                var markers_background = $('#markers_background').val();
                $('.div_marker_wrapper_bg').css('background-color',markers_background);
                $('.div_marker_wrapper_bg').css('border-radius','48px');
                $('.div_marker_wrapper_bg').css('border','none');
                break;
            case 'square':
                var markers_background = $('#markers_background').val();
                $('.div_marker_wrapper_bg').css('background-color',markers_background);
                $('.div_marker_wrapper_bg').css('border-radius','3px');
                $('.div_marker_wrapper_bg').css('border','none');
                break;
            case 'round_outline':
                var markers_color = $('#markers_color').val();
                var markers_background = $('#markers_background').val();
                $('.div_marker_wrapper_bg').css('background-color',markers_background);
                $('.div_marker_wrapper_bg').css('border-radius','48px');
                $('.div_marker_wrapper_bg').css('border','2px solid '+markers_color);
                break;
            case 'square_outline':
                var markers_color = $('#markers_color').val();
                var markers_background = $('#markers_background').val();
                $('.div_marker_wrapper_bg').css('background-color',markers_background);
                $('.div_marker_wrapper_bg').css('border-radius','3px');
                $('.div_marker_wrapper_bg').css('border','2px solid '+markers_color);
                break;
            case 'stroke':
                var markers_color = $('#markers_color').val();
                var markers_background = $('#markers_background').val();
                $('.div_marker_wrapper_bg').css('background-color','transparent');
                $('.div_marker_wrapper_bg').css('border','none');
                $('.div_marker_wrapper_bg i').css('-webkit-text-stroke','1px '+markers_background);
                $('.div_marker_wrapper_bg i').css('text-shadow','-1px -1px 0 '+markers_background+', 1px -1px 0 '+markers_background+', -1px 1px 0 '+markers_background+', 1px 1px 0 '+markers_background);
                $('.div_marker_wrapper_bg span').css('-webkit-text-stroke','1px '+markers_background);
                $('.div_marker_wrapper_bg span').css('text-shadow','-1px -1px 0 '+markers_background+', 1px -1px 0 '+markers_background+', -1px 1px 0 '+markers_background+', 1px 1px 0 '+markers_background);
                break;
        }
        $('.marker_final_preview').addClass('d-none');
        $('#marker_'+style).removeClass('d-none');
    }

    window.change_poi_style_v = function() {
        var style = $('#pois_style option:selected').attr('id');
        switch(style) {
            case 'custom_icon':
                $('#p_icon').addClass('d-none').addClass('disabled');
                $('#p_custom_icon').removeClass('d-none').removeClass('disabled');
                $('#pois_color').addClass('disabled');
                $('#pois_background').addClass('disabled');
                $('#pois_icon_type').addClass('disabled');
                break;
            case 'only_label':
                $('#p_icon').removeClass('d-none').addClass('disabled');;
                $('#p_custom_icon').addClass('d-none').addClass('disabled');
                $('#pois_color').removeClass('disabled');
                $('#pois_background').removeClass('disabled');
                $('#pois_icon_type').removeClass('disabled');
                break;
            default:
                $('#p_icon').removeClass('d-none').removeClass('disabled');
                $('#p_custom_icon').addClass('d-none').addClass('disabled');
                $('#pois_color').removeClass('disabled');
                $('#pois_background').removeClass('disabled');
                $('#pois_icon_type').removeClass('disabled');
                break;
        }
        var icon_type = $('#pois_icon_type option:selected').attr('id');
        $('.div_poi_wrapper_bg i').css('-webkit-text-stroke','');
        $('.div_poi_wrapper_bg i').css('text-shadow','');
        $('.div_poi_wrapper_bg span').css('-webkit-text-stroke','');
        $('.div_poi_wrapper_bg span').css('text-shadow','');
        switch(icon_type) {
            case 'round':
                var pois_background = $('#pois_background').val();
                $('.div_poi_wrapper_bg').css('background-color',pois_background);
                $('.div_poi_wrapper_bg').css('border-radius','48px');
                $('.div_poi_wrapper_bg').css('border','none');
                break;
            case 'square':
                var pois_background = $('#pois_background').val();
                $('.div_poi_wrapper_bg').css('background-color',pois_background);
                $('.div_poi_wrapper_bg').css('border-radius','3px');
                $('.div_poi_wrapper_bg').css('border','none');
                break;
            case 'round_outline':
                var pois_color = $('#pois_color').val();
                var pois_background = $('#pois_background').val();
                $('.div_poi_wrapper_bg').css('background-color',pois_background);
                $('.div_poi_wrapper_bg').css('border-radius','48px');
                $('.div_poi_wrapper_bg').css('border','2px solid '+pois_color);
                break;
            case 'square_outline':
                var pois_color = $('#pois_color').val();
                var pois_background = $('#pois_background').val();
                $('.div_poi_wrapper_bg').css('background-color',pois_background);
                $('.div_poi_wrapper_bg').css('border-radius','3px');
                $('.div_poi_wrapper_bg').css('border','2px solid '+pois_color);
                break;
            case 'stroke':
                var pois_color = $('#pois_color').val();
                var pois_background = $('#pois_background').val();
                $('.div_poi_wrapper_bg').css('background-color','transparent');
                $('.div_poi_wrapper_bg').css('border','none');
                $('.div_poi_wrapper_bg i').css('-webkit-text-stroke','1px '+pois_background);
                $('.div_poi_wrapper_bg i').css('text-shadow','-1px -1px 0 '+pois_background+', 1px -1px 0 '+pois_background+', -1px 1px 0 '+pois_background+', 1px 1px 0 '+pois_background);
                $('.div_poi_wrapper_bg span').css('-webkit-text-stroke','1px '+pois_background);
                $('.div_poi_wrapper_bg span').css('text-shadow','-1px -1px 0 '+pois_background+', 1px -1px 0 '+pois_background+', -1px 1px 0 '+pois_background+', 1px 1px 0 '+pois_background);
                break;
        }
        $('.poi_final_preview').addClass('d-none');
        $('#poi_'+style).removeClass('d-none');
    }

    window.change_marker_style = function() {
        var show_room = parseInt($('#marker_style option:selected').attr('id'));
        window.markers[window.marker_index_edit].show_room = show_room;
        switch(show_room) {
            case 3:
            case 8:
                $('#marker_library_icon').parent().parent().addClass('disabled').hide();
                $('#marker_icon').parent().parent().addClass('disabled').show();
                $('#marker_color').parent().parent().removeClass('disabled');
                $('#marker_icon_type').parent().parent().removeClass('disabled');
                $('#marker_background').parent().parent().removeClass('disabled');
                render_marker(window.marker_id_edit,window.marker_index_edit);
                break;
            case 4:
                $('#marker_icon').parent().parent().addClass('disabled').hide();
                $('#marker_color').parent().parent().addClass('disabled');
                $('#marker_background').parent().parent().addClass('disabled');
                $('#marker_icon_type').parent().parent().addClass('disabled');
                $('#marker_library_icon').parent().parent().removeClass('disabled').show();
                var id_icon_library = parseInt($('#marker_library_icon').val());
                if(id_icon_library!=0) {
                    render_marker(window.marker_id_edit,window.marker_index_edit);
                } else {
                    $('#marker_library_icon_preview').hide();
                    $('#marker_library_icon_preview_l').hide();
                }
                break;
            case 5:
                $('#marker_library_icon').parent().parent().addClass('disabled').hide();
                $('#marker_icon').parent().parent().addClass('disabled').show();
                $('#marker_color').parent().parent().addClass('disabled');
                $('#marker_icon_type').parent().parent().addClass('disabled');
                $('#marker_background').parent().parent().addClass('disabled');
                render_marker(window.marker_id_edit,window.marker_index_edit);
                break;
            default:
                $('#marker_library_icon').parent().parent().addClass('disabled').hide();
                $('#marker_icon').parent().parent().removeClass('disabled').show();
                $('#marker_color').parent().parent().removeClass('disabled');
                $('#marker_icon_type').parent().parent().removeClass('disabled');
                $('#marker_background').parent().parent().removeClass('disabled');
                render_marker(window.marker_id_edit,window.marker_index_edit);
                break;
        }
        if((show_room==6) || (show_room==7) || (show_room==8)) {
            $('#marker_label').parent().removeClass('disabled');
            $('.input_lang[data-target-id="marker_label"]').parent().removeClass('disabled');
        } else {
            $('#marker_label').parent().addClass('disabled');
            $('.input_lang[data-target-id="marker_label"]').parent().addClass('disabled');
        }
    }

    window.change_poi_style = function() {
        var style = parseInt($('#poi_style option:selected').attr('id'));
        switch(style) {
            case 1:
                $('#poi_icon').parent().parent().addClass('disabled').hide();
                $('#poi_color').parent().parent().addClass('disabled');
                $('#poi_background').parent().parent().addClass('disabled');
                $('#poi_icon_type').parent().parent().addClass('disabled');
                $('#poi_library_icon').parent().parent().removeClass('disabled').show();
                var id_icon_library = parseInt($('#poi_library_icon').val());
                if(id_icon_library!=0) {
                    render_poi(window.poi_id_edit,window.poi_index_edit);
                } else {
                    $('#poi_library_icon_preview').hide();
                    $('#poi_library_icon_preview_l').hide();
                }
                break;
            case 4:
                $('#poi_library_icon').parent().parent().addClass('disabled').hide();
                $('#poi_icon').parent().parent().addClass('disabled').show();
                $('#poi_color').parent().parent().removeClass('disabled');
                $('#poi_background').parent().parent().removeClass('disabled');
                $('#poi_icon_type').parent().parent().removeClass('disabled');
                window.pois[window.poi_index_edit].style = style;
                render_poi(window.poi_id_edit,window.poi_index_edit);
                break;
            default:
                $('#poi_library_icon').parent().parent().addClass('disabled').hide();
                $('#poi_icon').parent().parent().removeClass('disabled').show();
                $('#poi_color').parent().parent().removeClass('disabled');
                $('#poi_background').parent().parent().removeClass('disabled');
                $('#poi_icon_type').parent().parent().removeClass('disabled');
                window.pois[window.poi_index_edit].style = style;
                render_poi(window.poi_id_edit,window.poi_index_edit);
                break;
        }
        if((style==0) || (style==1)) {
            $('#poi_label').parent().addClass('disabled');
            $('.input_lang[data-target-id="poi_label"]').parent().addClass('disabled');
        } else {
            $('#poi_label').parent().removeClass('disabled');
            $('.input_lang[data-target-id="poi_label"]').parent().removeClass('disabled');
        }
    }

    window.change_poi_animation = function () {
        var animation = $('#poi_animation option:selected').attr('id');
        window.pois[window.poi_index_edit].animation = animation;
        render_poi(window.poi_id_edit,window.poi_index_edit);
    }

    window.change_marker_animation = function () {
        var animation = $('#marker_animation option:selected').attr('id');
        window.markers[window.marker_index_edit].animation = animation;
        render_marker(window.marker_id_edit,window.marker_index_edit);
    }

    window.change_poi_animation_vt = function () {
        var animation = $('#pois_animation option:selected').attr('id');
        $('#modal_default_pois_style .pnlm-hotspot-base').removeClass(function(index, className) {
            return (className.match(/\banimate__\S+/g) || []).join(' ');
        });
        $('#modal_default_pois_style .pnlm-hotspot-base').addClass('animate__animated');
        $('#modal_default_pois_style .pnlm-hotspot-base').addClass('animate__slow');
        $('#modal_default_pois_style .pnlm-hotspot-base').addClass('animate__infinite');
        $('#modal_default_pois_style .pnlm-hotspot-base').addClass('animate__'+animation);
    }

    window.change_marker_animation_vt = function () {
        var animation = $('#markers_animation option:selected').attr('id');
        $('#modal_default_markers_style .pnlm-hotspot-base').removeClass(function(index, className) {
            return (className.match(/\banimate__\S+/g) || []).join(' ');
        });
        $('#modal_default_markers_style .pnlm-hotspot-base').addClass('animate__animated');
        $('#modal_default_markers_style .pnlm-hotspot-base').addClass('animate__slow');
        $('#modal_default_markers_style .pnlm-hotspot-base').addClass('animate__infinite');
        $('#modal_default_markers_style .pnlm-hotspot-base').addClass('animate__'+animation);
    }

    window.change_tooltip_type_m = function () {
        var tooltip_type = $('#tooltip_type option:selected').attr('id');
        switch(tooltip_type) {
            case 'text':
                $('#tooltip_text_html').parent().parent().removeClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().removeClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().removeClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().removeClass('disabled');
                $('#tooltip_visibility').parent().removeClass('disabled');
                $('#tooltip_background').parent().parent().removeClass('disabled');
                $('#tooltip_color').parent().parent().removeClass('disabled');
                break;
            case 'room_name':
                $('#tooltip_text_html').parent().parent().addClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().addClass('disabled');
                $('#tooltip_visibility').parent().removeClass('disabled');
                $('#tooltip_background').parent().parent().removeClass('disabled');
                $('#tooltip_color').parent().parent().removeClass('disabled');
                break;
            case 'preview':
                $('#tooltip_text_html').parent().parent().addClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().addClass('disabled');
                $('#tooltip_visibility').parent().removeClass('disabled');
                $('#tooltip_background').parent().parent().addClass('disabled');
                $('#tooltip_color').parent().parent().addClass('disabled');
                break;
            case 'preview_square':
                $('#tooltip_text_html').parent().parent().addClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().addClass('disabled');
                $('#tooltip_visibility').parent().removeClass('disabled');
                $('#tooltip_background').parent().parent().addClass('disabled');
                $('#tooltip_color').parent().parent().addClass('disabled');
                break;
            case 'preview_rect':
                $('#tooltip_text_html').parent().parent().addClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().addClass('disabled');
                $('#tooltip_visibility').parent().removeClass('disabled');
                $('#tooltip_background').parent().parent().addClass('disabled');
                $('#tooltip_color').parent().parent().addClass('disabled');
                break;
            case 'none':
                $('#tooltip_text_html').parent().parent().addClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().addClass('disabled');
                $('#tooltip_visibility').parent().addClass('disabled');
                $('#tooltip_background').parent().parent().addClass('disabled');
                $('#tooltip_color').parent().parent().addClass('disabled');
                break;
        }
    }

    window.change_tooltip_type_m_vt = function () {
        var tooltip_type = $('#markers_tooltip_type option:selected').attr('id');
        switch(tooltip_type) {
            case 'text':
                $('#markers_tooltip_visibility').parent().removeClass('disabled');
                $('#markers_tooltip_background').parent().parent().removeClass('disabled');
                $('#markers_tooltip_color').parent().parent().removeClass('disabled');
                break;
            case 'room_name':
                $('#markers_tooltip_visibility').parent().removeClass('disabled');
                $('#markers_tooltip_background').parent().parent().removeClass('disabled');
                $('#markers_tooltip_color').parent().parent().removeClass('disabled');
                break;
            case 'preview':
                $('#markers_tooltip_visibility').parent().removeClass('disabled');
                $('#markers_tooltip_background').parent().parent().addClass('disabled');
                $('#markers_tooltip_color').parent().parent().addClass('disabled');
                break;
            case 'preview_square':
                $('#markers_tooltip_visibility').parent().removeClass('disabled');
                $('#markers_tooltip_background').parent().parent().addClass('disabled');
                $('#markers_tooltip_color').parent().parent().addClass('disabled');
                break;
            case 'preview_rect':
                $('#markers_tooltip_visibility').parent().removeClass('disabled');
                $('#markers_tooltip_background').parent().parent().addClass('disabled');
                $('#markers_tooltip_color').parent().parent().addClass('disabled');
                break;
            case 'none':
                $('#markers_tooltip_visibility').parent().addClass('disabled');
                $('#markers_tooltip_background').parent().parent().addClass('disabled');
                $('#markers_tooltip_color').parent().parent().addClass('disabled');
                break;
        }
    }

    window.change_tooltip_type_p = function () {
        var tooltip_type = $('#tooltip_type option:selected').attr('id');
        switch(tooltip_type) {
            case 'text':
                $('#tooltip_text_html').parent().parent().removeClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().removeClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().removeClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().removeClass('disabled');
                $('#tooltip_visibility').parent().removeClass('disabled');
                $('#tooltip_background').parent().parent().removeClass('disabled');
                $('#tooltip_color').parent().parent().removeClass('disabled');
                break;
            case 'none':
                $('#tooltip_text_html').parent().parent().addClass('disabled');
                $('#tooltip_text_mobile_html').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_html"]').parent().parent().addClass('disabled');
                $('.input_lang[data-target-id="tooltip_text_mobile_html"]').parent().parent().addClass('disabled');
                $('#tooltip_visibility').parent().addClass('disabled');
                $('#tooltip_background').parent().parent().addClass('disabled');
                $('#tooltip_color').parent().parent().addClass('disabled');
                break;
        }
    }

    window.change_tooltip_type_p_vt = function () {
        var tooltip_type = $('#pois_tooltip_type option:selected').attr('id');
        switch(tooltip_type) {
            case 'text':
                $('#pois_tooltip_visibility').parent().removeClass('disabled');
                $('#pois_tooltip_background').parent().parent().removeClass('disabled');
                $('#pois_tooltip_color').parent().parent().removeClass('disabled');
                break;
            case 'none':
                $('#pois_tooltip_visibility').parent().addClass('disabled');
                $('#pois_tooltip_background').parent().parent().addClass('disabled');
                $('#pois_tooltip_color').parent().parent().addClass('disabled');
                break;
        }
    }

    window.select_icon_library = function(p,id,image,base64,id_vt) {
        if(window.s3_enabled==1 && id_vt!='') {
            var image_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
        } else {
            var image_url = '../viewer/icons/'+image;
        }
        switch(p){
            case 'marker':
                window.markers[window.marker_index_edit].show_room = 4;
                window.markers[window.marker_index_edit].img_icon_library = image;
                window.markers[window.marker_index_edit].base64_icon_library = base64;
                $('#marker_library_icon').val(id);
                var ext = image.split('.').pop().toLowerCase();
                if(ext=='json') {
                    var html_image = '<div id="lottie_preview_'+window.marker_id_edit+'" style="height:30px;width:30px;vertical-align:middle"></div>';
                    $('#marker_library_icon_preview_l').html(html_image).promise().done(function () {
                        $('#marker_library_icon_preview_l').css('display','inline-block');
                        bodymovin.loadAnimation({
                            container: document.getElementById('lottie_preview_'+window.marker_id_edit),
                            renderer: 'svg',
                            loop: true,
                            autoplay: true,
                            path: image_url,
                            rendererSettings: {
                                progressiveLoad: true,
                            }
                        });
                    });
                    $('#marker_library_icon_preview').hide();
                } else {
                    $('#marker_library_icon_preview').attr('src',image_url);
                    $('#marker_library_icon_preview').show();
                    $('#marker_library_icon_preview_l').hide();
                }
                render_marker(window.marker_id_edit,window.marker_index_edit);
                break;
            case 'poi':
                window.pois[window.poi_index_edit].style = 1;
                window.pois[window.poi_index_edit].img_icon_library = image;
                window.pois[window.poi_index_edit].base64_icon_library = base64;
                $('#poi_library_icon').val(id);
                var ext = image.split('.').pop().toLowerCase();
                if(ext=='json') {
                    var html_image = '<div id="lottie_preview_'+window.poi_id_edit+'" style="height:30px;width:30px;vertical-align:middle"></div>';
                    $('#poi_library_icon_preview_l').html(html_image).promise().done(function () {
                        $('#poi_library_icon_preview_l').css('display','inline-block');
                        bodymovin.loadAnimation({
                            container: document.getElementById('lottie_preview_'+window.poi_id_edit),
                            renderer: 'svg',
                            loop: true,
                            autoplay: true,
                            path: image_url,
                            rendererSettings: {
                                progressiveLoad: true,
                            }
                        });
                    });
                    $('#poi_library_icon_preview').hide();
                } else {
                    $('#poi_library_icon_preview').attr('src',image_url);
                    $('#poi_library_icon_preview').show();
                    $('#poi_library_icon_preview_l').hide();
                }
                render_poi(window.poi_id_edit,window.poi_index_edit);
                break;
            case 'icons':
                $('#'+window.element_icon_sel+'_library_icon').val(id);
                $('#'+window.element_icon_sel+'_library_icon_preview').attr('src',image_url);
                $('.'+window.element_icon_sel+'_control img').remove();
                $('div.'+window.element_icon_sel+'_control').prepend('<img src="'+image_url+'" />')
                $('p.'+window.element_icon_sel+'_control').prepend('<img style="width:12px;height:12px;vertical-align:middle;margin-bottom:1px;" src="'+image_url+'" />')
                $('.'+window.element_icon_sel+'_control i').css('display','none');
                $('#GetIconPicker_'+window.element_icon_sel).parent().addClass('disabled');
                $('#btn_remove_library_icon_'+window.element_icon_sel).removeClass('disabled');
                $('#'+window.element_icon_sel+'_library_icon_preview').show();
                $('#modal_library_icons').modal('hide');
                break;
        }
        $('#modal_library_icons').modal('hide');
    }

    window.select_icon_library_v = function(p,id,image,id_vt) {
        if(window.s3_enabled==1 && id_vt!='') {
            var image_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
        } else {
            var image_url = '../viewer/icons/'+image;
        }
        switch(p){
            case 'marker':
                $('#marker_library_icon').val(id);
                var ext = image.split('.').pop().toLowerCase();
                if(ext=='json') {
                    var html_image = '<div id="lottie_preview_m_'+id+'" style="height:30px;width:30px;vertical-align:middle"></div>';
                    $('#marker_library_icon_preview_l').html(html_image).promise().done(function () {
                        $('#marker_library_icon_preview_l').css('display','inline-block');
                        bodymovin.loadAnimation({
                            container: document.getElementById('lottie_preview_m_'+id),
                            renderer: 'svg',
                            loop: true,
                            autoplay: true,
                            path: image_url,
                            rendererSettings: {
                                progressiveLoad: true,
                            }
                        });
                    });
                    var html_image = '<div id="lottie_preview_m" style="height:50px;width:50px;vertical-align:middle"></div>';
                    $('#marker_lottie_pewview').html(html_image).promise().done(function () {
                        $('#marker_lottie_pewview').css('display','inline-block');
                        bodymovin.loadAnimation({
                            container: document.getElementById('lottie_preview_m'),
                            renderer: 'svg',
                            loop: true,
                            autoplay: true,
                            path: image_url,
                            rendererSettings: {
                                progressiveLoad: true,
                            }
                        });
                    });
                    $('#marker_lottie_pewview').removeClass('d-none');
                    $('#marker_custom_icon img').addClass('d-none');
                    $('#marker_library_icon_preview').hide();
                } else {
                    $('#marker_library_icon_preview').attr('src',image_url);
                    $('#marker_custom_icon img').attr('src',image_url);
                    $('#marker_lottie_pewview').addClass('d-none');
                    $('#marker_custom_icon img').removeClass('d-none');
                    $('#marker_library_icon_preview').show();
                    $('#marker_library_icon_preview_l').hide();
                }
                $('#modal_library_icons_markers').modal('hide');
                break;
            case 'poi':
                $('#poi_library_icon').val(id);
                var ext = image.split('.').pop().toLowerCase();
                if(ext=='json') {
                    var html_image = '<div id="lottie_preview_p_'+id+'" style="height:30px;width:30px;vertical-align:middle"></div>';
                    $('#poi_library_icon_preview_l').html(html_image).promise().done(function () {
                        $('#poi_library_icon_preview_l').css('display','inline-block');
                        bodymovin.loadAnimation({
                            container: document.getElementById('lottie_preview_p_'+id),
                            renderer: 'svg',
                            loop: true,
                            autoplay: true,
                            path: image_url,
                            rendererSettings: {
                                progressiveLoad: true,
                            }
                        });
                        var html_image = '<div id="lottie_preview_p" style="height:50px;width:50px;vertical-align:middle"></div>';
                        $('#poi_lottie_pewview').html(html_image).promise().done(function () {
                            $('#poi_lottie_pewview').css('display','inline-block');
                            bodymovin.loadAnimation({
                                container: document.getElementById('lottie_preview_p'),
                                renderer: 'svg',
                                loop: true,
                                autoplay: true,
                                path: image_url,
                                rendererSettings: {
                                    progressiveLoad: true,
                                }
                            });
                        });
                    });
                    $('#poi_lottie_pewview').removeClass('d-none');
                    $('#poi_custom_icon img').addClass('d-none');
                    $('#poi_library_icon_preview').hide();
                } else {
                    $('#poi_library_icon_preview').attr('src',image_url);
                    $('#poi_custom_icon img').attr('src',image_url);
                    $('#poi_lottie_pewview').addClass('d-none');
                    $('#poi_custom_icon img').removeClass('d-none');
                    $('#poi_library_icon_preview').show();
                    $('#poi_library_icon_preview_l').hide();
                }
                $('#modal_library_icons_pois').modal('hide');
                break;
        }
    }

    window.remove_library_icon = function(element) {
        $('#'+element+'_library_icon').val(0);
        $('#'+element+'_library_icon_preview').attr('src','');
        $('.'+element+'_control img').remove();
        $('.'+element+'_control i').css('display','inline-block');
        $('#GetIconPicker_'+element).parent().removeClass('disabled');
        $('#btn_remove_library_icon_'+element).addClass('disabled');
        $('#'+element+'_library_icon_preview').hide();
    }

    window.render_marker_p = function(id,index) {
        if(window.pois[index].embed_type!='') {
            window.viewer.removeHotSpot("m"+id.toString());
            window.viewer.removeHotSpot("m"+id.toString()+"_1");
            window.viewer.removeHotSpot("m"+id.toString()+"_2");
            window.viewer.removeHotSpot("m"+id.toString()+"_3");
            window.viewer.removeHotSpot("m"+id.toString()+"_4");
            window.viewer.removeHotSpot("m"+id.toString()+"_move");
            window.viewer.addHotSpot({
                "id": "m"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "marker_embed",
                "transform3d": parseInt(window.pois[index].transform3d),
                "scale": false,
                "tooltip_type": "",
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "cssClass": "hotspot-embed hotspot",
                "createTooltipFunc": hotspot_embed_m,
                "createTooltipArgs": window.pois[index],
                "clickHandlerFunc": click_edit_marker,
                "clickHandlerArgs": window.pois[index].id
            });
            var marker_embed_helpers = window.pois[index].embed_coords.split("|");
            marker_embed_helpers[0] = marker_embed_helpers[0].split(",");
            marker_embed_helpers[1] = marker_embed_helpers[1].split(",");
            marker_embed_helpers[2] = marker_embed_helpers[2].split(",");
            marker_embed_helpers[3] = marker_embed_helpers[3].split(",");
            jQuery.each(marker_embed_helpers, function(index_h, marker_embed_helper) {
                window.viewer.addHotSpot({
                    "id": "m"+window.pois[index].id+"_"+(index_h+1),
                    "type": 'pointer',
                    "object": "marker_embed_helper",
                    "transform3d": false,
                    "pitch": parseFloat(marker_embed_helper[0]),
                    "yaw": parseFloat(marker_embed_helper[1]),
                    "size_scale": 1,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "draggable": true,
                    "cssClass": "hotspot-helper",
                    "createTooltipFunc": hotspot_embed_helper_m,
                    "createTooltipArgs": [window.pois[index].id,(index_h+1)],
                    "dragHandlerFunc": drag_embed_helper_m,
                    "dragHandlerArgs": [window.pois[index],index_h]
                });
            });
            window.viewer.addHotSpot({
                "id": "m"+window.pois[index].id+"_move",
                "type": 'pointer',
                "object": "marker_embed_helper",
                "transform3d": false,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "size_scale": 1,
                "rotateX": 0,
                "rotateZ": 0,
                "draggable": true,
                "cssClass": "hotspot-helper",
                "createTooltipFunc": hotspot_embed_move_m,
                "createTooltipArgs": window.pois[index].id,
                "dragHandlerFunc": drag_embed_move_m,
                "dragHandlerArgs": [window.pois[index].id,index]
            });
            init_marker_embed();
        }
    }

    window.render_marker = function(id,index) {
        if(window.markers[index].embed_type!='') {
            window.viewer.removeHotSpot("m"+id.toString());
            window.viewer.removeHotSpot("m"+id.toString()+"_1");
            window.viewer.removeHotSpot("m"+id.toString()+"_2");
            window.viewer.removeHotSpot("m"+id.toString()+"_3");
            window.viewer.removeHotSpot("m"+id.toString()+"_4");
            window.viewer.removeHotSpot("m"+id.toString()+"_move");
            window.viewer.addHotSpot({
                "id": "m"+window.markers[index].id,
                "type": window.markers[index].embed_type,
                "object": "marker_embed",
                "transform3d": parseInt(window.markers[index].transform3d),
                "scale": false,
                "tooltip_type": "",
                "pitch": parseFloat(window.markers[index].pitch),
                "yaw": parseFloat(window.markers[index].yaw),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "cssClass": "hotspot-embed hotspot",
                "createTooltipFunc": hotspot_embed_m,
                "createTooltipArgs": window.markers[index],
                "clickHandlerFunc": click_edit_marker,
                "clickHandlerArgs": window.markers[index].id
            });
            var marker_embed_helpers = window.markers[index].embed_coords.split("|");
            marker_embed_helpers[0] = marker_embed_helpers[0].split(",");
            marker_embed_helpers[1] = marker_embed_helpers[1].split(",");
            marker_embed_helpers[2] = marker_embed_helpers[2].split(",");
            marker_embed_helpers[3] = marker_embed_helpers[3].split(",");
            jQuery.each(marker_embed_helpers, function(index_h, marker_embed_helper) {
                window.viewer.addHotSpot({
                    "id": "m"+window.markers[index].id+"_"+(index_h+1),
                    "type": 'pointer',
                    "object": "marker_embed_helper",
                    "transform3d": false,
                    "pitch": parseFloat(marker_embed_helper[0]),
                    "yaw": parseFloat(marker_embed_helper[1]),
                    "size_scale": 1,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "draggable": true,
                    "cssClass": "hotspot-helper",
                    "createTooltipFunc": hotspot_embed_helper_m,
                    "createTooltipArgs": [window.markers[index].id,(index_h+1)],
                    "dragHandlerFunc": drag_embed_helper_m,
                    "dragHandlerArgs": [window.markers[index],index_h]
                });
            });
            window.viewer.addHotSpot({
                "id": "m"+window.markers[index].id+"_move",
                "type": 'pointer',
                "object": "marker_embed_helper",
                "transform3d": false,
                "pitch": parseFloat(window.markers[index].pitch),
                "yaw": parseFloat(window.markers[index].yaw),
                "size_scale": 1,
                "rotateX": 0,
                "rotateZ": 0,
                "draggable": true,
                "cssClass": "hotspot-helper",
                "createTooltipFunc": hotspot_embed_move_m,
                "createTooltipArgs": window.markers[index].id,
                "dragHandlerFunc": drag_embed_move_m,
                "dragHandlerArgs": [window.markers[index].id,index]
            });
            init_marker_embed();
        } else {
            window.viewer.removeHotSpot("m"+id.toString());
            window.viewer.addHotSpot({
                "id": "m"+window.markers[index].id,
                "type": 'marker',
                "transform3d": false,
                "draggable": false,
                "scale": (parseInt(window.markers[index].scale)==1) ? true : false,
                "pitch": parseFloat(window.markers[index].pitch),
                "yaw": parseFloat(window.markers[index].yaw),
                "rotateX": parseInt(window.markers[index].rotateX),
                "rotateZ": parseInt(window.markers[index].rotateZ),
                "size_scale": parseFloat(window.markers[index].size_scale),
                "cssClass": "custom-hotspot hotspot",
                "createTooltipFunc": hotspot_m,
                "createTooltipArgs": window.markers[index],
                "clickHandlerFunc": click_edit_marker,
                "clickHandlerArgs": parseInt(window.markers[index].id)
            });
        }
    }

    window.render_poi_embed_m = function(id,index) {
        window.viewer.removeHotSpot("p"+id.toString());
        window.viewer.removeHotSpot("p"+id.toString()+"_1");
        window.viewer.removeHotSpot("p"+id.toString()+"_2");
        window.viewer.removeHotSpot("p"+id.toString()+"_3");
        window.viewer.removeHotSpot("p"+id.toString()+"_4");
        window.viewer.removeHotSpot("p"+id.toString()+"_move");
        if(window.markers[index].embed_type!='' && window.markers[index].transform3d==1) {
            window.viewer.addHotSpot({
                "id": "p"+window.markers[index].id,
                "type": window.markers[index].embed_type,
                "object": "poi_embed",
                "transform3d": parseInt(window.markers[index].transform3d),
                "scale": false,
                "tooltip_type": "",
                "pitch": parseFloat(window.markers[index].pitch),
                "yaw": parseFloat(window.markers[index].yaw),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "cssClass": "hotspot-embed hotspot",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.markers[index],
                "clickHandlerFunc": click_edit_poi,
                "clickHandlerArgs": window.markers[index].id
            });
            var poi_embed_helpers = window.markers[index].embed_coords.split("|");
            poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
            poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
            poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
            poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
            jQuery.each(poi_embed_helpers, function(index_h, poi_embed_helper) {
                window.viewer.addHotSpot({
                    "id": "p"+window.markers[index].id+"_"+(index_h+1),
                    "type": 'pointer',
                    "object": "poi_embed_helper",
                    "transform3d": false,
                    "pitch": parseFloat(poi_embed_helper[0]),
                    "yaw": parseFloat(poi_embed_helper[1]),
                    "size_scale": 1,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "draggable": true,
                    "cssClass": "hotspot-helper",
                    "createTooltipFunc": hotspot_embed_helper,
                    "createTooltipArgs": [window.markers[index].id,(index_h+1)],
                    "dragHandlerFunc": drag_embed_helper,
                    "dragHandlerArgs": [window.markers[index],index_h]
                });
            });
            window.viewer.addHotSpot({
                "id": "p"+window.markers[index].id+"_move",
                "type": 'pointer',
                "object": "poi_embed_helper",
                "transform3d": false,
                "pitch": parseFloat(window.markers[index].pitch),
                "yaw": parseFloat(window.markers[index].yaw),
                "size_scale": 1,
                "rotateX": 0,
                "rotateZ": 0,
                "draggable": true,
                "cssClass": "hotspot-helper",
                "createTooltipFunc": hotspot_embed_move,
                "createTooltipArgs": window.markers[index].id,
                "dragHandlerFunc": drag_embed_move,
                "dragHandlerArgs": [window.markers[index].id,index]
            });
            init_poi_embed();
        }
    }

    window.render_poi = function(id,index) {
        window.viewer.removeHotSpot("p"+id.toString());
        window.viewer.removeHotSpot("p"+id.toString()+"_1");
        window.viewer.removeHotSpot("p"+id.toString()+"_2");
        window.viewer.removeHotSpot("p"+id.toString()+"_3");
        window.viewer.removeHotSpot("p"+id.toString()+"_4");
        window.viewer.removeHotSpot("p"+id.toString()+"_move");
        if(window.pois[index].embed_type!='' && window.pois[index].transform3d==1) {
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "poi_embed",
                "transform3d": parseInt(window.pois[index].transform3d),
                "scale": false,
                "tooltip_type": "",
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "cssClass": "hotspot-embed hotspot",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.pois[index],
                "clickHandlerFunc": click_edit_poi,
                "clickHandlerArgs": window.pois[index].id
            });
            var poi_embed_helpers = window.pois[index].embed_coords.split("|");
            poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
            poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
            poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
            poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
            jQuery.each(poi_embed_helpers, function(index_h, poi_embed_helper) {
                window.viewer.addHotSpot({
                    "id": "p"+window.pois[index].id+"_"+(index_h+1),
                    "type": 'pointer',
                    "object": "poi_embed_helper",
                    "transform3d": false,
                    "pitch": parseFloat(poi_embed_helper[0]),
                    "yaw": parseFloat(poi_embed_helper[1]),
                    "size_scale": 1,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "draggable": true,
                    "cssClass": "hotspot-helper",
                    "createTooltipFunc": hotspot_embed_helper,
                    "createTooltipArgs": [window.pois[index].id,(index_h+1)],
                    "dragHandlerFunc": drag_embed_helper,
                    "dragHandlerArgs": [window.pois[index],index_h]
                });
            });
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id+"_move",
                "type": 'pointer',
                "object": "poi_embed_helper",
                "transform3d": false,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "size_scale": 1,
                "rotateX": 0,
                "rotateZ": 0,
                "draggable": true,
                "cssClass": "hotspot-helper",
                "createTooltipFunc": hotspot_embed_move,
                "createTooltipArgs": window.pois[index].id,
                "dragHandlerFunc": drag_embed_move,
                "dragHandlerArgs": [window.pois[index].id,index]
            });
            init_poi_embed();
        } else {
            if(window.pois[index].embed_type!='' && window.pois[index].transform3d==0) {
                window.viewer.addHotSpot({
                    "id": "p"+window.pois[index].id,
                    "type": window.pois[index].embed_type,
                    "object": "poi_embed",
                    "transform3d": parseInt(window.pois[index].transform3d),
                    "scale": false,
                    "pitch": parseFloat(window.pois[index].pitch),
                    "yaw": parseFloat(window.pois[index].yaw),
                    "rotateX": parseInt(window.pois[index].rotateX),
                    "rotateZ": parseInt(window.pois[index].rotateZ),
                    "size_scale": parseFloat(window.pois[index].size_scale),
                    "cssClass": "hotspot-embed hotspot",
                    "createTooltipFunc": hotspot_embed,
                    "createTooltipArgs": window.pois[index],
                    "clickHandlerFunc": click_edit_poi,
                    "clickHandlerArgs": window.pois[index].id
                });
                fix_all_embeds_pos();
            } else {
                switch(window.pois[index].type) {
                    case 'callout':
                        window.viewer.addHotSpot({
                            "id": "p"+window.pois[index].id,
                            "type": 'callout',
                            "transform3d": false,
                            "scale": false,
                            "pitch": parseFloat(window.pois[index].pitch),
                            "yaw": parseFloat(window.pois[index].yaw),
                            "rotateX": 0,
                            "rotateZ": 0,
                            "size_scale": 1,
                            "cssClass": "custom-hotspot-content hotspot",
                            "createTooltipFunc": hotspot_p_callout,
                            "createTooltipArgs": window.pois[index],
                            "clickHandlerFunc": click_edit_poi,
                            "clickHandlerArgs": window.pois[index].id
                        });
                        break;
                    case 'staging':
                        window.viewer.addHotSpot({
                            "id": "p"+window.pois[index].id,
                            "type": 'poi',
                            "transform3d": false,
                            "scale": false,
                            "pitch": parseFloat(window.pois[index].pitch),
                            "yaw": parseFloat(window.pois[index].yaw),
                            "rotateX": 0,
                            "rotateZ": 0,
                            "size_scale": 1,
                            "cssClass": "custom-hotspot-content hotspot staging-hotspot",
                            "createTooltipFunc": hotspot_p_staging,
                            "createTooltipArgs": window.pois[index],
                            "clickHandlerFunc": click_edit_poi,
                            "clickHandlerArgs": window.pois[index].id
                        });
                        break;
                    default:
                        window.viewer.addHotSpot({
                            "id": "p"+window.pois[index].id,
                            "type": 'poi',
                            "transform3d": false,
                            "scale": (parseInt(window.pois[index].scale)==1) ? true : false,
                            "pitch": parseFloat(window.pois[index].pitch),
                            "yaw": parseFloat(window.pois[index].yaw),
                            "rotateX": parseInt(window.pois[index].rotateX),
                            "rotateZ": parseInt(window.pois[index].rotateZ),
                            "size_scale": parseFloat(window.pois[index].size_scale),
                            "cssClass": "custom-hotspot-content hotspot",
                            "createTooltipFunc": hotspot_p,
                            "createTooltipArgs": window.pois[index],
                            "clickHandlerFunc": click_edit_poi,
                            "clickHandlerArgs": window.pois[index].id
                        });
                        break;
                }
            }
        }
    }

    window.render_poi_move = function(id,index) {
        window.viewer.removeHotSpot("p"+id.toString());
        window.viewer.removeHotSpot("p"+id.toString()+"_1");
        window.viewer.removeHotSpot("p"+id.toString()+"_2");
        window.viewer.removeHotSpot("p"+id.toString()+"_3");
        window.viewer.removeHotSpot("p"+id.toString()+"_4");
        window.viewer.removeHotSpot("p"+id.toString()+"_move");
        if(window.pois[index].transform3d==1) {
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "poi_embed",
                "transform3d": parseInt(window.pois[index].transform3d),
                "tooltip_type": "",
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": 0,
                "rotateZ": 0,
                "size_scale": 1,
                "cssClass": "hotspot-embed hotspot",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.pois[index]
            });
            var poi_embed_helpers = window.pois[index].embed_coords.split("|");
            poi_embed_helpers[0] = poi_embed_helpers[0].split(",");
            poi_embed_helpers[1] = poi_embed_helpers[1].split(",");
            poi_embed_helpers[2] = poi_embed_helpers[2].split(",");
            poi_embed_helpers[3] = poi_embed_helpers[3].split(",");
            jQuery.each(poi_embed_helpers, function(index_h, poi_embed_helper) {
                window.viewer.addHotSpot({
                    "id": "p"+window.pois[index].id+"_"+(index_h+1),
                    "type": 'pointer',
                    "object": "poi_embed_helper",
                    "transform3d": false,
                    "pitch": parseFloat(poi_embed_helper[0]),
                    "yaw": parseFloat(poi_embed_helper[1]),
                    "size_scale": 1,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "draggable": true,
                    "cssClass": "hotspot-helper",
                    "createTooltipFunc": hotspot_embed_helper,
                    "createTooltipArgs": [window.pois[index].id,(index_h+1)],
                    "dragHandlerFunc": drag_embed_helper,
                    "dragHandlerArgs": [window.pois[index],index_h]
                });
            });
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id+"_move",
                "type": 'pointer',
                "object": "poi_embed_helper",
                "transform3d": false,
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "size_scale": 1,
                "rotateX": 0,
                "rotateZ": 0,
                "draggable": true,
                "cssClass": "hotspot-helper",
                "createTooltipFunc": hotspot_embed_move,
                "createTooltipArgs": window.pois[index].id,
                "dragHandlerFunc": drag_embed_move,
                "dragHandlerArgs": [window.pois[index].id,index]
            });
        } else {
            window.viewer.addHotSpot({
                "id": "p"+window.pois[index].id,
                "type": window.pois[index].embed_type,
                "object": "poi_embed",
                "draggable": true,
                "transform3d": parseInt(window.pois[index].transform3d),
                "pitch": parseFloat(window.pois[index].pitch),
                "yaw": parseFloat(window.pois[index].yaw),
                "rotateX": parseInt(window.pois[index].rotateX),
                "rotateZ": parseInt(window.pois[index].rotateZ),
                "size_scale": parseFloat(window.pois[index].size_scale),
                "cssClass": "hotspot-embed hotspot",
                "createTooltipFunc": hotspot_embed,
                "createTooltipArgs": window.pois[index],
                "dragHandlerFunc": drag_poi_move,
                "dragHandlerArgs": index
            });
        }
        init_poi_embed();
    }

    window.get_option_rooms_target = function(id_select,id,id_room_target,id_marker,index_marker) {
        id_room_target_sel = id_room_target;
        var html_option_rooms_target = "";
        var first_id_room = null;
        if(id_select=='room_default') {
            html_option_rooms_target += '<option id="0">'+window.backend_labels.none+'</option>';
        }
        jQuery.each(window.rooms, function(index, room) {
            var id_room = room.id;
            var name = room.name;
            if(id!=id_room) {
                if(first_id_room==null) {
                    first_id_room = id_room;
                }
                if(id_room==id_room_target) {
                    html_option_rooms_target += '<option selected id="'+id_room+'" val="'+id_room+'">'+name+'</option>';
                } else {
                    html_option_rooms_target += '<option id="'+id_room+'" val="'+id_room+'">'+name+'</option>';
                }
                return;
            }
        });
        $('#'+id_select).empty();
        $('#'+id_select).html(html_option_rooms_target).promise().done(function () {
            switch(id_select) {
                case 'room_default':
                    break;
                case 'room_target_add':
                    $('#'+id_select).attr('onchange','change_marker_room_target('+id_marker+','+index_marker+',\''+id_select+'\')');
                    if(id_room_target==0) {
                        change_preview_room_image(first_id_room,id_select,index_marker);
                    } else {
                        change_preview_room_image(id_room_target,id_select,index_marker);
                    }
                    break;
                default:
                    $('#'+id_select).attr('onchange','change_marker_room_target('+id_marker+','+index_marker+',\''+id_select+'\')');
                    change_preview_room_image(id_room_target,id_select,index_marker);
                    break;
            }
            $('#'+id_select).selectpicker('refresh');
            var val = $('#'+id_select).selectpicker('val');
            $('#'+id_select).selectpicker('val', val);
        });
    }

    window.get_option_rooms_duplicate = function(id_select,id) {
        var html_option_rooms_target = "";
        jQuery.each(window.rooms, function(index, room) {
            var id_room = room.id;
            var name = room.name;
            var panorama_image = room.panorama_image;
            if(id_room==id) {
                html_option_rooms_target += '<option data-image="'+panorama_image+'" selected id="'+id_room+'" value="'+id_room+'">'+name+'</option>';
            } else {
                html_option_rooms_target += '<option data-image="'+panorama_image+'" id="'+id_room+'" value="'+id_room+'">' + name + '</option>';
            }
        });
        $('#'+id_select).empty();
        $('#'+id_select).html(html_option_rooms_target).promise().done(function () {
            $('#'+id_select).selectpicker('refresh');
            var val = $('#'+id_select).selectpicker('val');
            $('#'+id_select).selectpicker('val', val);
        });
    }

    window.set_room_target_map = function(id) {
        jQuery.each(window.map_points, function(index, point) {
            var id_room = point.id;
            var name = point.name;
            if(id_room==id) {
                $('#room_target').val(name);
                $('#preview_room_image_map').attr('src',point.room_image);
                return;
            }
        });
    }

    window.set_vt_target_map = function(id) {
        jQuery.each(window.map_points, function(index, point) {
            var id_room = point.id;
            var name = point.name;
            if(id_room==id) {
                var initial_pos = point.initial_pos;
                if(initial_pos=='') {
                    $('#btn_remove_initial_pos_tour').addClass('disabled');
                } else {
                    $('#btn_remove_initial_pos_tour').removeClass('disabled');
                }
                $('#room_target').val(name);
                if(point.background_image!='') {
                    $('#preview_vt_image_map').attr('src',point.background_image);
                    $('#preview_vt_image_map').show();
                } else {
                    $('#preview_vt_image_map').hide();
                }
            }
        });
    }

    window.adjust_points_size = function () {
        var point_size = $('#point_size').val();
        $('#point_size_val').html(point_size);
        if((point_size=='') || (point_size<=0)) {
            point_size=20;
        }
        point_size = parseInt(point_size);
        window.point_size = point_size;
        var point_view_size = $('#point_view_size').val();
        $('#point_view_size_val').html(point_view_size);
        if((point_view_size=='') || (point_view_size<=0)) {
            point_size=80;
        }
        point_view_size = parseInt(point_view_size);
        window.point_view_size = point_view_size;
        switch (window.map_type) {
            case 'floorplan':
                update_map_pointers_style(false);
                break;
            case 'map':
                point_size = point_size*2;
                window.map_tour_l.eachLayer((ml)=>{
                    if(ml instanceof L.Marker){
                        var icon = ml.options.icon;
                        icon.options.iconSize = [point_size, point_size];
                        icon.options.iconAnchor = [point_size/2, point_size/2];
                        ml.setIcon(icon);
                    }
                });
                if($('#map_thumb').is(':checked')) {
                    $('.map_pointer_circle').css('background-size','cover');
                } else {
                    $('.map_pointer_circle').css('background-size',0);
                }
                update_map_pointers_style(true);
                if(window.marker_sel!=null) {
                    var id = window.marker_sel.options.id;
                    $('.map_pointer_container').removeClass('active');
                    $('#pointer_'+id).addClass('active');
                }
                break;
        }
    }

    window.adjust_points_position = function () {
        var image_w = $('#map_image').width();
        var image_h = $('#map_image').height();
        $('#pointers_div').css('width',image_w+'px');
        $('#pointers_div').css('height',image_h+'px');
        var ratio = image_w / image_h;
        var ratio_w = image_w / 300;
        var ratio_h = image_h / ((image_w / ratio_w) / ratio);
        window.ratio_w = ratio_w;
        window.ratio_h = ratio_h;
        jQuery.each(window.map_points, function(index, point) {
            var id_point = point.id;
            var map_left = parseInt(point.map_left);
            var map_top = parseInt(point.map_top);
            var pos_left = map_left * ratio_w;
            var pos_top = map_top * ratio_h;
            $('#pointer_'+id_point).css('transform','scale('+ratio_w+')');
            $('#pointer_'+id_point).css('top',pos_top+'px');
            $('#pointer_'+id_point).css('left',pos_left+'px');
        });
    }

    window.adjust_marker_position = function () {
        var image_w = $('#panorama_image').width();
        var image_h = $('#panorama_image').height();
        $('#markers_div').css('width',image_w+'px');
        $('#markers_div').css('height',image_h+'px');
        var half_x = image_w / 2;
        var half_y = image_h / 2;
        var ratio_x = half_x / 180;
        var ratio_y = half_y / 90;
        if(image_w>=1100) {
            var scale = 0.7;
        } else if((image_w<1100) & (image_w>=500)) {
            var scale = 0.5;
        } else {
            var scale = 0.3;
        }
        jQuery.each(window.markers, function(index, marker) {
            var id_marker = marker.id;
            var yaw = marker.yaw;
            var pitch = marker.pitch * -1;
            var marker_w = $('#marker_'+id_marker).width();
            var marker_h = $('#marker_'+id_marker).height();
            var pos_left = ((yaw*ratio_x)+half_x)-(marker_w/1.77);
            var pos_top = ((pitch*ratio_y)+half_y)-(marker_h/1.77);
            $('#marker_'+id_marker).css('transform','translate('+pos_left+'px,'+pos_top+'px) scale('+scale+')');
        });
    }

    window.adjust_poi_position = function () {
        var image_w = $('#panorama_image').width();
        var image_h = $('#panorama_image').height();
        $('#markers_div').css('width',image_w+'px');
        $('#markers_div').css('height',image_h+'px');
        var half_x = image_w / 2;
        var half_y = image_h / 2;
        var ratio_x = half_x / 180;
        var ratio_y = half_y / 90;
        if(image_w>=1100) {
            var scale = 1;
        } else if((image_w<1100) & (image_w>=500)) {
            var scale = 0.6;
        } else {
            var scale = 0.3;
        }
        jQuery.each(window.pois, function(index, poi) {
            var id_poi = poi.id;
            var yaw = poi.yaw;
            var pitch = poi.pitch * -1;
            var poi_w = $('#poi_'+id_poi).width();
            var poi_h = $('#poi_'+id_poi).height();
            var pos_left = ((yaw*ratio_x)+half_x)-(poi_w/1.3);
            var pos_top = ((pitch*ratio_y)+half_y)-(poi_h/1.3);
            $('#poi_'+id_poi).css('transform','translate('+pos_left+'px,'+pos_top+'px) scale('+scale+')');
        });
    }

    window.persist_search = function (type) {
        sessionStorage.setItem('search_'+type,$('.search_input').val());
    }

    window.clear_search = function (type) {
        sessionStorage.setItem('search_'+type,'');
        $('.search_input').val('');
        $('.search_input').trigger('change');
    }

    window.filter_0_markers = function () {
        $('.search_input').val('0 '+window.backend_labels.markers);
        sessionStorage.setItem('search_room',$('.search_input').val());
        $('.search_input').trigger('change');
    }

    window.preview_panorama_room = function(id_room) {
        $('#modal_preview_room').modal('show');
        $('#preview_room_div').html('<i class="fas fa-spin fa-circle-notch"></i>');
        $.ajax({
            url: "ajax/get_room.php",
            type: "POST",
            data: {
                id: id_room,
            },
            async: true,
            success: function (rsp) {
                var room = JSON.parse(rsp);
                initialize_preview_panorama_room(room);
            },
            error: function() {
                $('#modal_preview_room').modal('hide');
            }
        });
    }

    function initialize_preview_panorama_room(array_room) {
        $('#preview_room_div').empty();
        try {
            window.video_viewer.dispose();
        } catch (e) {}
        try {
            window.viewer.destroy();
        } catch (e) {}
        if(array_room.room_type == 'video') {
            var fileExt = array_room.panorama_video.split('.').pop().toLowerCase();
            switch(fileExt) {
                case 'webm':
                    var type_video = 'video/webm';
                    break;
                default:
                    var type_video = 'video/mp4';
                    break;
            }
            if(window.s3_enabled==1) {
                var video_url = window.s3_url+'viewer/videos/'+array_room.panorama_video;
                var image_url = window.s3_url+'viewer/panoramas/'+array_room.panorama_image+'?s3=1';
            } else {
                var video_url = '../viewer/videos/'+array_room.panorama_video;
                var image_url = '../viewer/panoramas/'+array_room.panorama_image;
            }
            if(window.is_mobile) {
                try {
                    loader_p.reset();
                } catch (e) {}
                try {
                    video_p.remove();
                } catch (e) {}
                $("#canvas_p").empty();
                var setup_video_p = (loader, resources) => {
                    PIXI.utils.sayHello("WebGL");
                    var index_bg = Object.keys(resources)[0];
                    app_p = new PIXI.Application({
                        antialias: false,
                        transparent: false,
                        resolution: 1,
                        width: resources[index_bg].baseTexture.width,
                        height: resources[index_bg].baseTexture.height
                    });
                    $("#canvas_p").append(app_p.view);
                    let bg = PIXI.Sprite.from(resources[index_bg]);
                    /*bg.anchor.y = 1;
                    bg.scale.y = -1;*/
                    app_p.stage.addChild(bg);
                    video_p = document.createElement('video');
                    video_p.id = 'video_viewer';
                    video_p.crossOrigin = 'anonymous';
                    video_p.preload = 'auto';
                    video_p.autoplay = true;
                    video_p.muted = true;
                    video_p.loop = true;
                    video_p.oncanplay = function () {
                        video_p.play();
                    };
                    video_p.setAttribute('playsinline', '');
                    video_p.setAttribute('webkit-playsinline', '');
                    video_p.src = video_url;
                    const sprite = PIXI.Sprite.from(video_p);
                    /*sprite.anchor.y = 1;
                    sprite.scale.y = -1;*/
                    app_p.stage.addChild(sprite);
                    let canvas = $('#canvas_p canvas')[0];
                    window.viewer = pannellum.viewer('preview_room_div', {
                        "type": "equirectangular",
                        "panorama": canvas,
                        "autoLoad": true,
                        "dynamic": true,
                        "dynamicUpdate": true,
                        "showFullscreenCtrl": false,
                        "showControls": false,
                        "compass": false,
                        "horizonPitch": parseInt(array_room.h_pitch),
                        "horizonRoll": parseInt(array_room.h_roll),
                        "minHfov": 50,
                        "maxHfov": 120,
                        "yaw": parseFloat(array_room.yaw),
                        "pitch": parseFloat(array_room.pitch),
                        "hfov": 100,
                        "haov": parseInt(array_room.haov),
                        "vaov": parseInt(array_room.vaov),
                        "hotSpots": [],
                        "friction": 1,
                        "strings": {
                            "loadingLabel": window.backend_labels.loading + "...",
                        },
                    });
                }
                var list_assets = ["background"];
                PIXI.Assets.add("background", image_url);
                PIXI.Assets.load(list_assets).then((textures) => {
                    setup_video_p(null,textures);
                });
            } else {
                $('#preview_room_div').html('<video controls playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="width: 100%;height: 600px;margin: 0 auto;" muted preload="none" crossorigin="anonymous"><source src="' + video_url + '" type="' + type_video + '"/></video>');
                window.video_viewer = videojs('video_viewer', {
                    loop: true,
                    autoload: true,
                    muted: true,
                    controls: true,
                    plugins: {
                        pannellum: {
                            "autoLoad": true,
                            "showFullscreenCtrl": false,
                            "showControls": false,
                            "horizonPitch": parseInt(array_room.h_pitch),
                            "horizonRoll": parseInt(array_room.h_roll),
                            "minHfov": 50,
                            "maxHfov": 120,
                            "yaw": parseFloat(array_room.yaw),
                            "pitch": parseFloat(array_room.pitch),
                            "hfov": 100,
                            "haov": parseInt(array_room.haov),
                            "vaov": parseInt(array_room.vaov),
                            "hotSpots": [],
                            "friction": 1,
                            "compass": false,
                            "northOffset": parseInt(array_room.northOffset),
                            "strings": {
                                "loadingLabel": window.backend_labels.loading + "...",
                            },
                        }
                    }
                });
                window.video_viewer.load();
                window.video_viewer.on('ready', function () {
                    window.video_viewer.play();
                    window.viewer = window.video_viewer.pnlmViewer;
                });
            }
        } else {
            var multires = parseInt(array_room.multires);
            if(multires) {
                var multires_config = JSON.parse(array_room.multires_config);
                window.viewer = pannellum.viewer('preview_room_div', {
                    "type": "multires",
                    "multiRes": multires_config,
                    "backgroundColor": [1,1,1],
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(array_room.yaw),
                    "pitch": parseFloat(array_room.pitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "compass": false,
                    "northOffset": parseInt(array_room.northOffset),
                    "hotSpots": [],
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
            } else {
                if(window.s3_enabled==1) {
                    var image_url = window.s3_url+'viewer/panoramas/'+array_room.panorama_image+'?s3=1';
                } else {
                    var image_url = '../viewer/panoramas/'+array_room.panorama_image;
                }
                window.viewer = pannellum.viewer('preview_room_div', {
                    "type": "equirectangular",
                    "panorama": image_url,
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "multiResMinHfov": true,
                    "horizonPitch": parseInt(array_room.h_pitch),
                    "horizonRoll": parseInt(array_room.h_roll),
                    "minHfov": 50,
                    "maxHfov": 120,
                    "yaw": parseFloat(array_room.yaw),
                    "pitch": parseFloat(array_room.pitch),
                    "hfov": 100,
                    "haov": parseInt(array_room.haov),
                    "vaov": parseInt(array_room.vaov),
                    "friction": 1,
                    "compass": false,
                    "northOffset": parseInt(array_room.northOffset),
                    "hotSpots": [],
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                });
            }
        }
    }

    function parse_room_list(rooms,permissions) {
        var html = '', html_search = '';
        var search_val = sessionStorage.getItem('search_room');
        if(search_val==null) search_val='';
        if(rooms.length>0 && window.ar_simulator==0) {
            html_search = '<div class="card mb-2 pt-3">\n' +
                '    <div class="card-body" style="padding-top: 0;padding-bottom: 0;">';
            html_search += '<div class="row">\n' +
                '   <div class="col-lg-6 col-md-6 col-sm-12 col-12">\n' +
                '       <div class="input-group mb-3">\n' +
                '       <span class="input-group-prepend">\n' +
                '           <div class="input-group-text bg-white border-right-0"><i class="fa fa-search"></i></div>\n' +
                '       </span>\n' +
                '       <input onkeyup="persist_search(\'room\')" class="search_input form-control py-2" type="text" value="'+search_val+'" placeholder="'+window.backend_labels.search_room+'" autocomplete="new-password" >\n' +
                '       <span class="input-group-append">\n' +
                '           <div onclick="clear_search(\'room\');" style="cursor: pointer;" class="input-group-text bg-gray-300 border-left-0"><i class="fa fa-times"></i></div>\n' +
                '       </span>\n' +
                '   </div>\n' +
                '  </div>\n' +
                '   <div class="col-lg-4 col-md-4 col-sm-8 col-8">\n' +
                '      <button data-toggle="modal" data-target="#modal_list_alt" class="btn btn-block btn-outline-secondary mb-3"><i class="fas fa-layer-group"></i>&nbsp;&nbsp;'+window.backend_labels.rooms_list+'</button>\n' +
                '  </div>\n' +
                '   <div class="col-lg-2 col-md-2 col-sm-4 col-4">\n' +
                '       <input id="view_type_toggle" type="checkbox" checked data-toggle="toggle" data-width="100%" data-on="'+window.backend_labels.list+'" data-off="'+window.backend_labels.grid+'" data-onstyle="light" data-offstyle="light">\n' +
                '   </div>\n' +
                '</div>';
            html_search += '</div></div>';
        }
        jQuery.each(rooms, function(index, room) {
            var id = room.id;
            var name = room.name;
            var category = room.category;
            var image = room.panorama_image;
            var thumb_image = room.thumb_image_url;
            var count_markers = room.count_markers;
            var count_pois = room.count_pois;
            var count_measures = room.count_measures;
            var visible = parseInt(room.visible);
            var panoramas_list = room.panoramas_list;
            var aws_s3 = parseInt(room.aws_s3);
            if(aws_s3==1) {
                var aws_s3_url = room.aws_s3_url;
            }
            var array_panorams_r = [];
            if(panoramas_list!='') {
                array_panorams_r = panoramas_list.split(",");
            }
            var gsv_add = "";
            if(parseInt(room.status_gsv)>-1) {
                switch(parseInt(room.status_gsv)) {
                    case 1:
                        gsv_add = '&nbsp;&nbsp;<i title="'+window.backend_labels.gsv_ready+'" style="color: darkorange" class="fas fa-street-view i_tooltip"></i>';
                        break;
                    case 2:
                        if(room.link_gsv!='') {
                            gsv_add = '&nbsp;&nbsp;<a target="_blank" href="'+room.link_gsv+'"><i title="'+window.backend_labels.gsv_published_link+'" style="color: green" class="fas fa-street-view i_tooltip"></i></a>';
                        } else {
                            gsv_add = '&nbsp;&nbsp;<i title="'+window.backend_labels.gsv_published+'" style="color: green" class="fas fa-street-view i_tooltip"></i>';
                        }
                        break;
                }
            }
            if(category!='') {
                var category_add = '&nbsp;&nbsp;&nbsp;<i class="fas fa-layer-group"></i> '+category;
            } else {
                var category_add = "";
            }
            if(count_markers>0) {
                var badge_markers = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_markers+'</span>';
            } else {
                var badge_markers = '';
            }
            if(count_pois>0) {
                var badge_pois = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_pois+'</span>';
            } else {
                var badge_pois = '';
            }
            if(count_measures>0) {
                var badge_measures = '<span style="top:-8px;right:-5px" class="badge badge-pill badge-secondary position-absolute">'+count_measures+'</span>';
            } else {
                var badge_measures = '';
            }
            var type = room.type;
            switch (type) {
                case 'image':
                    if(parseInt(room.multires)) {
                        type = '<i id="type_'+id+'" style="font-size: 14px" class="fas fa-images"></i>';
                    } else {
                        type = '<i id="type_'+id+'" style="font-size: 14px" class="fas fa-image"></i>';
                    }
                    if(parseInt(room.multires_status)==1) {
                        type = '<i id="type_'+id+'" style="font-size: 14px" class="fas fa-spin fa-cog"></i>';
                    }
                    break;
                case 'video':
                    type = '<i id="type_'+id+'" style="font-size: 14px" class="fas fa-video"></i>';
                    break;
                case 'hls':
                    type = '<i id="type_'+id+'" style="font-size: 14px" class="fas fa-film"></i>';
                    break;
                case 'lottie':
                    type = '<i id="type_'+id+'" style="font-size: 14px" class="fab fa-deviantart"></i>';
                    break;
            }
            var btn_duplicate = '';
            if(parseInt(window.can_create)==1 && permissions['create'] && window.ar_simulator==0) {
                btn_duplicate = '<a title="'+window.backend_labels.duplicate.toUpperCase()+'" href="#" onclick="modal_duplicate_room('+id+');return false;" class="btn btn-secondary btn-sm btn_duplicate">\n' +
                    '<i class="fas fa-copy"></i>\n' +
                    '</a>\n';
            }
            var btn_markers = '';
            var btn_measures = '';
            var btn_drag = '';
            if(window.ar_simulator==0) {
                btn_markers = '<a title="'+window.backend_labels.markers.toUpperCase()+'" href="index.php?p=markers&id_room='+id+'" class="btn btn-info btn-sm position-relative">\n' +
                    '<i class="fas fa-caret-square-up"></i>\n' + badge_markers +
                    '</a>\n';
                btn_measures = '<a title="'+window.backend_labels.measures.toUpperCase()+'" href="index.php?p=measurements&id_room='+id+'" class="btn btn-info btn-sm position-relative">\n' +
                    '<i class="fas fa-ruler-combined"></i>\n' + badge_measures +
                    '</a>\n';
                btn_drag = '<a title="'+window.backend_labels.drag_change_pos.toUpperCase()+'" style="background-color: white; border: 1px solid black; cursor: pointer" class="handle btn btn-primary btn-sm">\n' +
                    '<i style="color: black" class="fas fa-arrows-alt"></i>\n' +
                    '</a>\n';
            }
            var btn_home = '<a title="'+window.backend_labels.initial_room.toUpperCase()+'" onclick="open_modal_initial_room('+id+');" data-id="'+id+'" style="background-color: white; border: 1px solid black; cursor: pointer" class="room_home btn btn-primary btn-sm">\n' +
                '<i style="color: black" class="fas fa-home"></i>\n' +
                '</a>\n';
            var btn_rename = '<i id="btn_view_rename_'+id+'" onclick="view_rename_room('+id+');" class="btn_view_rename fas fa-pen"></i>';
            btn_rename += '<i id="btn_save_rename_'+id+'" onclick="save_rename_room('+id+');" class="btn_save_rename fas fa-check d-none"></i>&nbsp;&nbsp;';
            btn_rename += '<i id="btn_close_rename_'+id+'" onclick="close_rename_room('+id+');" class="btn_close_rename fas fa-times d-none"></i>';
            var input_rename = '<input id="rename_input_'+id+'" class="rename_input d-none" type="text" value="'+name+'" />';
            var class_visible = '';
            if(visible==0) {
                class_visible = 'room_hidden';
            }
            var img2 = '', img3 = '';
            var o_position = 'center center';
            if (array_panorams_r.hasOwnProperty(0)) {
                if(aws_s3==1) {
                    var img2_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_r[0];
                } else {
                    var img2_src = '../viewer/panoramas/thumb/'+array_panorams_r[0];
                }
                img2 = '<img class="img2_vt" loading="lazy" src="'+img2_src+'">';
            }
            if (array_panorams_r.hasOwnProperty(1)) {
                if(aws_s3==1) {
                    var img3_src = aws_s3_url+'viewer/panoramas/thumb/'+array_panorams_r[1];
                } else {
                    var img3_src = '../viewer/panoramas/thumb/'+array_panorams_r[1];
                }
                img3 = '<img class="img3_vt" loading="lazy" src="'+img3_src+'">';
                o_position = '-15px center';
            }
            if(aws_s3==1) {
                var img_preview = aws_s3_url+'viewer/panoramas/lowres/'+image;
            } else {
                var img_preview = '../viewer/panoramas/lowres/'+image;
            }
            html += '<div class="div_room '+class_visible+' card mb-2 py-2">\n' +
                '            <div id="room_list" class="card-body" style="padding-top: 0;padding-bottom: 0;">\n' +
                '                <div data-id="'+id+'" class="row room">\n' +
                '                    <div class="room_content col text-center text-sm-center text-md-left text-lg-left">\n' +
                '                        <div onclick="preview_panorama_room('+room.id+')" style="width: 90px;height: 44px;overflow: hidden;border-radius: 6px;position: relative" class="d-inline-block align-middle room_image_div"><div class="preview_room_overlay"><i class="fas fa-eye"></i></div><img loading="lazy" style="width:100%;height:100%;object-fit:cover;object-position:'+o_position+'" src="'+thumb_image+'">'+img2+img3+'</div>\n' +
                '                        <div class="room_info d-inline-block ml-2 align-middle text-left">'+type+' <b class="room_name" id="room_name_'+id+'">'+((name.length > 60) ? name.slice(0, 60) + "..." : name)+'</b>'+input_rename+'&nbsp;&nbsp;'+btn_rename+'<br><a class="marker_label_list" data-count="'+count_markers+'" href="index.php?p=markers&id_room='+id+'"><i style="font-size:12px"><i class="fas fa-caret-square-up"></i> '+count_markers+' '+window.backend_labels.markers+'</a>&nbsp;&nbsp;&nbsp;<a class="poi_label_list" data-count="'+count_pois+'" href="index.php?p=pois&id_room='+id+'"><i class="fas fa-bullseye"></i> '+count_pois+' '+window.backend_labels.pois+'</a>'+category_add+gsv_add+'</i></div>\n' +
                '                    </div>\n' +
                '                    <div class="room_buttons col-md-auto pt-1 text-center text-sm-center text-md-right text-lg-right">\n' + btn_home + btn_drag +
                '                        <a title="'+window.backend_labels.edit.toUpperCase()+'" href="index.php?p=edit_room&id='+id+'" class="btn btn-warning btn-sm">\n' +
                '                            <i class="fas fa-edit"></i>\n' +
                '                        </a>\n' + btn_markers +
                '                        <a title="'+window.backend_labels.pois.toUpperCase()+'" href="index.php?p=pois&id_room='+id+'" class="btn btn-info btn-sm position-relative">\n' +
                '                            <i class="fas fa-bullseye"></i>\n' + badge_pois +
                '                        </a>\n' + btn_measures +
                '                        <a title="'+window.backend_labels.open_direct_link.toUpperCase()+'" target="_blank" href="../viewer/index.php?code='+window.code_vt+'&room='+id+'" class="btn  btn-dark btn-sm">\n' +
                '                            <i class="fas fa-external-link"></i>\n' +
                '                        </a>\n' + btn_duplicate +
                '                        <a title="'+window.backend_labels.delete.toUpperCase()+'" href="#" onclick="modal_delete_room('+id+','+room.status_gsv+');return false;" class="btn btn-danger btn-sm">\n' +
                '                            <i class="fas fa-trash"></i>\n' +
                '                        </a>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '            </div>\n' +
                '        </div>';
        });
        $('#rooms_list').html(html).promise().done(function () {
            $('.i_tooltip').tooltipster({delay:0,position:"bottom"});
            $('#search_div').html(html_search).promise().done(function () {
                $('.rename_input').keydown(function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode == 13) {
                        var id = $(this).attr('id').replace('rename_input_','');
                        save_rename_room(id);
                    }
                });
                $('#view_type_toggle').bootstrapToggle();
                $('#view_type_toggle').change(function() {
                    var checked = $(this).prop('checked');
                    if(!checked) {
                        localStorage.setItem('room_view_type', 'grid');
                        $('.div_room').addClass('div_room_grid');
                        $('#rooms_list').css('margin','0 -5px');
                        $('#room_list .room .room_content').removeClass('text-lg-left').removeClass('text-md-left');
                        $('#room_list .room .room_buttons').removeClass('text-lg-right').removeClass('text-md-right');
                        $('#room_list .room .room_content').addClass('col-12');
                        $('#room_list .room .room_buttons').addClass('col-12').addClass('mt-1');
                        $('#room_list .room .room_buttons').addClass('col-auto').removeClass('col-md-auto');
                        $('#room_list .room .room_content .room_info').removeClass('text-left').addClass('text-center');
                        $('#room_list .room .room_content .room_info').css('width','100%');
                    } else {
                        localStorage.setItem('room_view_type', 'list');
                        $('.div_room').removeClass('div_room_grid');
                        $('#rooms_list').css('margin','0');
                        $('#room_list .room .room_content').addClass('text-lg-left').addClass('text-md-left');
                        $('#room_list .room .room_buttons').addClass('text-lg-right').addClass('text-md-right');
                        $('#room_list .room .room_content').removeClass('col-12');
                        $('#room_list .room .room_buttons').removeClass('col-12').removeClass('mt-1');
                        $('#room_list .room .room_buttons').removeClass('col-auto').addClass('col-md-auto');
                        $('#room_list .room .room_content .room_info').addClass('text-left').removeClass('text-center');
                        $('#room_list .room .room_content .room_info').css('width','auto');
                    }
                });
                if ("room_view_type" in localStorage) {
                    var view_type = localStorage.getItem('room_view_type');
                    switch (view_type) {
                        case 'list':
                            $('#view_type_toggle').bootstrapToggle('on');
                            break;
                        case 'grid':
                            $('#view_type_toggle').bootstrapToggle('off');
                            break;
                    }
                }
                if(!permissions['edit']) {
                    $('#rooms_list .fa-edit').parent().hide();
                }
                if(!permissions['delete']) {
                    $('#rooms_list .fa-trash').parent().hide();
                }
                if(window.user_role=='editor') {
                    $('#rooms_list .fa-arrows-alt').parent().hide();
                }
                $('#rooms_list').searchable({
                    selector      : '.div_room',
                    childSelector : 'div',
                    searchField   : '.search_input',
                    searchType    : 'default',
                    clearOnLoad   : false
                });
                $('#rooms_list .btn').tooltipster({
                    delay: 10,
                    hideOnClick: true
                });
                adjust_room_home_icons();
                var el = document.getElementById('rooms_list');
                Sortable.create(el,{
                    handle: '.handle',
                    filter: ".no_drag",
                    onMove: function (e) { return e.related.className.indexOf('no_drag') === -1;  },
                    onEnd: function (evt) {
                        var array_rooms_priority = [];
                        $('#rooms_list .room').each(function () {
                            var id = $(this).attr('data-id');
                            array_rooms_priority.push(id);
                        });
                        change_rooms_order(array_rooms_priority);
                        adjust_room_home_icons();
                    },
                });
                var scrollpos = sessionStorage.getItem('scrollpos_room');
                if (scrollpos) {
                    document.getElementById("content-wrapper").scrollTo(0,scrollpos);
                    sessionStorage.removeItem('scrollpos_room');
                }
            });
        });
    }

    window.open_modal_initial_room = function(id) {
        if(id!=window.id_room_initial && window.id_room_initial>0) {
            var name_room = $('#room_name_'+id).html();
            $('#name_room_initial').html(name_room);
            $('#modal_select_room_initial').modal('show');
            $('#btn_select_room_initial').attr('onclick','save_initial_room('+id+');');
        } else {
            $('#modal_initial_room').modal('show');
        }
    }

    window.save_initial_room = function(id_initial_room_sel=0) {
        var id_initial_room_o = 0;
        if(id_initial_room_sel==0) {
            $('#modal_initial_room button').addClass('disabled');
            id_initial_room_o = parseInt($('#mode_initial_room option:selected').attr('id'));
            if(id_initial_room_o==0) {
                if(window.id_initial_room>0) {
                    id_initial_room_o = window.id_initial_room;
                } else {
                    id_initial_room_o = parseInt($('#rooms_list .room').first().attr('data-id'));
                }
            }
        } else {
            $('#modal_select_room_initial button').addClass('disabled');
            id_initial_room_o = id_initial_room_sel;
        }
        $.ajax({
            url: "ajax/save_initial_room.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_initial_room: id_initial_room_o,
            },
            async: true,
            success: function (json) {
                if(id_initial_room_sel==0) {
                    $('#modal_initial_room button').removeClass('disabled');
                    $('#modal_initial_room').modal('hide');
                } else {
                    $('#modal_select_room_initial button').removeClass('disabled');
                    $('#modal_select_room_initial').modal('hide');
                }
                window.id_room_initial = id_initial_room_o;
                adjust_room_home_icons();
            },
            error: function() {
                if(id_initial_room_sel==0) {
                    $('#modal_initial_room button').removeClass('disabled');
                } else {
                    $('#modal_select_room_initial button').removeClass('disabled');
                }
            }
        });
    }

    function adjust_room_home_icons() {
        if(window.id_room_initial==undefined) return;
        switch(window.id_room_initial) {
            case -2:
                $('.room_home').removeClass('inactive');
                $('.room_home').removeClass('active');
                $('.room_home').hide();
                $('.room_home').first().css('display','inline-block');
                $('.room_home').first().find('i').removeClass('fa-shuffle').addClass('fa-home');
                break;
            case -1:
                $('.room_home').removeClass('inactive');
                $('.room_home').removeClass('active');
                $('.room_home').hide();
                $('.room_home').first().css('display','inline-block');
                $('.room_home').first().find('i').removeClass('fa-home').addClass('fa-shuffle');
                break;
            default:
                $('.room_home').addClass('inactive');
                $('.room_home').removeClass('active');
                $('.room_home i').addClass('fa-home').removeClass('fa-shuffle');
                $('.room_home[data-id="'+window.id_room_initial+'"]').addClass('active');
                break;
        }
    }

    window.view_rename_room = function(id) {
        $('#btn_view_rename_'+id).addClass('d-none');
        $('#btn_save_rename_'+id).removeClass('d-none');
        $('#btn_close_rename_'+id).removeClass('d-none');
        $('#rename_input_'+id).removeClass('d-none');
        $('#rename_input_'+id).select();
        $('#room_name_'+id).addClass('d-none');
        $('#type_'+id).addClass('d-none');
    }

    window.save_rename_room = function(id) {
        var name = $('#rename_input_'+id).val();
        if(name!='') {
            $('#room_name_'+id).html(name);
            $.ajax({
                url: "ajax/rename_room.php",
                type: "POST",
                data: {
                    id: id,
                    name: name
                },
                async: true,
                success: function (json) {
                    $('#btn_view_rename_'+id).removeClass('d-none');
                    $('#btn_save_rename_'+id).addClass('d-none');
                    $('#btn_close_rename_'+id).addClass('d-none');
                    $('#rename_input_'+id).addClass('d-none');
                    $('#room_name_'+id).removeClass('d-none');
                    $('#type_'+id).removeClass('d-none');
                }
            });
        }
    }

    window.close_rename_room = function(id) {
        $('#btn_view_rename_'+id).removeClass('d-none');
        $('#btn_save_rename_'+id).addClass('d-none');
        $('#btn_close_rename_'+id).addClass('d-none');
        $('#rename_input_'+id).addClass('d-none');
        $('#room_name_'+id).removeClass('d-none');
        $('#type_'+id).removeClass('d-none');
    }

    function parse_rooms_menu_list(menu_list) {
        function render_menu_items(items) {
            let html = '<ol class="dd-list">';
            items.forEach(item => {
                if(item!==null && item!==undefined) {
                    let id = item.id;
                    let name = item.name.length > 35 ? item.name.substring(0, 35) + '...' : item.name;
                    let type = item.type;
                    let hide = parseInt(item.hide);
                    if (type === 'room') {
                        html += `
                    <li class="dd-item dd-nochildren" data-hide="${hide}" data-type="room" data-id="${id}">
                        <div class="dd-handle dd3-handle"></div>
                        <div class="dd3-content">
                            <span style="opacity: ${hide == 0 ? '1.0' : '0.5'}">
                                <i class="fas fa-fw fa-vector-square"></i> ${name}
                            </span>
                            <i onclick="${hide == 0 ? `hide_menu_item('${id}')` : `show_menu_item('${id}')`}"
                               style="float: right; cursor: pointer"
                               class="fas ${hide == 0 ? 'fa-eye' : 'fa-eye-slash'}"></i>
                        </div>
                    </li>`;
                    } else if (type === 'category') {
                        html += `
                    <li class="dd-item" data-cat="${name}" data-type="category" data-id="${id}">
                        <div class="dd-handle dd3-handle"></div>
                        <div class="dd3-content">
                            <i class="fas fa-stream" style="vertical-align: super;"></i>
                            <div class="category_editable"
                                 style="width: 70%; padding-left: 5px; display: inline-block; background-color: white; border: 1px solid lightgray;"
                                 contenteditable="true">${name}</div>
                            <i onclick="remove_menu_item('${id}')"
                               style="float: right; cursor: pointer"
                               class="fas fa-trash"></i>
                        </div>`;

                        if (item.childrens && item.childrens.length > 0) {
                            html += render_menu_items(item.childrens);
                        }
                        html += '</li>';
                    }
                }
            });
            html += '</ol>';
            return html;
        }
        let html = '<div class="col-md-12"><div class="dd">';
        html += render_menu_items(menu_list);
        html += '</div></div>';
        try {
            $('.dd').nestable('destroy');
        } catch (e) {}
        $('.list_div').html(html).promise().done(function () {
            $('.dd3-content div.category_editable').on('input', function () {
                var cat = $(this).html();
                $(this).closest('.dd-item').attr('data-cat', cat).data('cat', cat);
                save_list_alt();
            });
            $('.dd').nestable({
                scroll: false,
                maxDepth: 6,
                callback: function (l, e) {
                    check_category_deletable();
                    save_list_alt();
                }
            });
            check_category_deletable();
            if (window.default_language != window.selected_language && window.selected_language != '' && window.rooms_list_show_lang == 1) {
                $('.dd3-content .fa-trash').hide();
                $('.dd3-content .fa-eye').hide();
                $('.dd3-content .fa-eye-slash').hide();
                $('.add_cat_div').hide();
            } else {
                $('.add_cat_div').show();
            }
        });
    }

    function check_category_deletable() {
        $(".dd-item[data-type='category']").each(function () {
            if($(this).find('ol').hasClass('dd-list')) {
                $(this).find('i.fa-trash').addClass('disabled');
            } else {
                $(this).find('i.fa-trash').removeClass('disabled');
            }
        });
    }

    function save_list_alt() {
        var list_alt = $('.dd').nestable('serialize');
        list_alt = JSON.stringify(list_alt);
        $.ajax({
            url: "ajax/save_list_alt.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                list_alt: list_alt,
                language: window.selected_language
            },
            async: true,
            success: function (json) {}
        });
    }

    window.add_menu_list_cat = function () {
        var last_id_cat = $(".dd-item[data-type='category']").length;
        if(last_id_cat==0) {
            last_id_cat = 1;
        } else {
            last_id_cat++;
        }
        var add_cat = $('#add_cat').val();
        if(add_cat != '') {
            $(".dd > ol").append("<li class='dd-item' data-cat=\""+add_cat+"\" data-type='category' data-id='c"+last_id_cat+"'><div class='dd-handle dd3-handle'></div><div class='dd3-content'><i class=\"fas fa-stream\" style='vertical-align: super;'></i> <div class=\"category_editable\" style=\"width: 70%;padding-left: 5px;display: inline-block;background-color: white;border: 1px solid lightgray;\" contenteditable=\"true\">"+add_cat+"</div> <i onclick=\"remove_menu_item('c"+last_id_cat+"')\" style=\"float: right;cursor: pointer\" class=\"fas fa-trash\"></i></div></li>");
            $('.dd3-content div').off('input');
            $('.dd3-content div').on('input',function () {
                var cat = $(this).html();
                $(this).parent().parent().attr('data-cat',cat);
                $(this).parent().parent().data('cat',cat);
                save_list_alt();
            });
        }
        $('#add_cat').val('');
    }

    window.remove_menu_item = function(id) {
        $('.dd').nestable('remove', id);
        save_list_alt();
    }

    window.hide_menu_item = function(id) {
        $(".dd-item[data-id='"+id+"']").find('i.fa-eye').first().removeClass('fa-eye').addClass('fa-eye-slash');
        $(".dd-item[data-id='"+id+"']").find('span').first().css('opacity',0.5);
        $(".dd-item[data-id='"+id+"']").attr('data-hide','1');
        $(".dd-item[data-id='"+id+"']").data('hide','1');
        $(".dd-item[data-id='"+id+"']").find('i.fa-eye-slash').first().attr('onclick','show_menu_item(\''+id+'\')');
        save_list_alt();
    }

    window.show_menu_item = function(id) {
        $(".dd-item[data-id='"+id+"']").find('i.fa-eye-slash').first().removeClass('fa-eye-slash').addClass('fa-eye');
        $(".dd-item[data-id='"+id+"']").find('span').first().css('opacity',1.0);
        $(".dd-item[data-id='"+id+"']").attr('data-hide','0');
        $(".dd-item[data-id='"+id+"']").data('hide','0');
        $(".dd-item[data-id='"+id+"']").find('i.fa-eye').first().attr('onclick','hide_menu_item(\''+id+'\')');
        save_list_alt();
    }

    /*function ai_get_styles() {
        $.ajax({
            url: "../services/ai_get_styles.php",
            type: "POST",
            data: {},
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#ai_styles').empty();
                jQuery.each(rsp,function(index,style) {
                    $('#ai_styles').append('<option data-image="'+style['image_jpg']+'" data-max-char="'+style['max-char']+'" id="'+style.id+'">'+style.name+'</option>');
                });
                set_ai_prompt_max_length();
                $('#ai_styles').prop('disabled',false);
                window.ai_styles_loaded = true;
            }
        });
    }*/

    function ai_get_styles() {
        $.ajax({
            url: "../services/ai_get_styles.php",
            type: "POST",
            data: {},
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#ai_styles').empty();
                Object.keys(rsp).forEach(function(key) {
                    var item = rsp[key];
                    if (item.type === 'family') {
                        var optgroup = $('<optgroup label="' + item.name + '">');
                        item.items.forEach(function(style) {
                            optgroup.append('<option data-image="' + style.image_jpg + '" data-max-char="' + style['max-char'] + '" id="' + style.id + '">' + style.name + '</option>');
                        });
                        $('#ai_styles').append(optgroup);
                    } else if (item.type === 'style') {
                        $('#ai_styles').append('<option data-image="' + item.image_jpg + '" data-max-char="' + item['max-char'] + '" id="' + item.id + '">' + item.name + '</option>');
                    }
                });
                set_ai_prompt_max_length();
                $('#ai_styles').prop('disabled', false);
                window.ai_styles_loaded = true;
            }
        });
    }

    function update_ai_log(id_ai_log,response) {
        $.ajax({
            url: "ajax/ai_update_log.php",
            type: "POST",
            data: {
                id_ai_log: id_ai_log,
                response: response
            },
            async: true,
            success: function (json) {
                $('#btn_view_ai_history').removeClass('disabled_d');
            }
        });
    }

    window.view_ai_history = function() {
        $('#ai_history_content').hide();
        $('#ai_history_content').empty();
        $('#ai_history_loading').show();
        $('#modal_ai_history').modal('show');
        $.ajax({
            url: "../services/ai_get_history.php",
            type: "POST",
            async: true,
            success: function (json) {
                var list_history = JSON.parse(json);
                var html = '';
                if(list_history.length>0) {
                    html += '<div id="ai_list_history" class="row">';
                    for(var i=0;i<list_history.length;i++) {
                        html += '<div class="col-md-4 mb-3">';
                        html += '<div class="ai_list_panorama">';
                        html += '<i onclick="delete_ai_history_panorama('+list_history[i].id+');" class="fa-solid fa-trash btn_remove_ai_history_panorama"></i>';
                        html += '<img loading="lazy" onclick="use_ai_history_panorama(\''+list_history[i].thumb_url+'\',\''+list_history[i].file_url+'\');" src="'+list_history[i].thumb_url+'" />';
                        html += '<span class="ai_history_prompt"><b>'+list_history[i].style+'</b> - '+list_history[i].prompt+'</span>';
                        html += '</div>';
                        html += '</div>';
                    }
                    html += '</div>';
                }
                $('#ai_history_content').html(html).promise().done(function() {
                    $('#ai_history_loading').hide();
                    $('#ai_history_content').show();
                });
            },
            error: function () {
                $('#modal_ai_history').modal('hide');
            }
        });
    }

    window.view_panorama_uploaded = function() {
        $('#uploaded_panoramas_content').hide();
        $('uploaded_panoramas_content').empty();
        $('#uploaded_panoramas_loading').show();
        $('#modal_uploaded_panoramas').modal('show');
        $.ajax({
            url: "ajax/get_uploaded_panoramas.php",
            type: "POST",
            async: true,
            success: function (json) {
                var uploaded_panoramas = JSON.parse(json);
                var html = '';
                if(uploaded_panoramas.length>0) {
                    html += '<div id="uploaded_panoramas" class="row">';
                    for(var i=0;i<uploaded_panoramas.length;i++) {
                        html += '<div class="col-md-3 mb-3">';
                        html += '<div class="uploaded_panorama">';
                        if(window.user_role=='administrator' && window.count_users>0) {
                            html += '<div id="public_v_'+uploaded_panoramas[i].id_room+'" onclick="toggle_panorama_public('+uploaded_panoramas[i].id_room+')" class="public_panorama_uploaded '+((uploaded_panoramas[i].public==1) ? 'active_public_v' : '')+'">';
                            html += '<i class="fa-solid fa-users-viewfinder"></i>';
                            html += '</div>';
                        }
                        html += '<img loading="lazy" onclick="use_uploaded_panorama(\''+uploaded_panoramas[i].thumb_url+'\',\''+uploaded_panoramas[i].file_url+'\','+i+');" src="'+uploaded_panoramas[i].thumb_url+'" />';
                        html += '<span class="uploaded_panorama_name"><b>'+uploaded_panoramas[i].tour_name+'</b> - <span id="name_use_panorama_'+i+'">'+uploaded_panoramas[i].room_name+'</span></span>';
                        html += '</div>';
                        html += '</div>';
                    }
                    html += '</div>';
                }
                $('#uploaded_panoramas_content').html(html).promise().done(function() {
                    $('#uploaded_panoramas_loading').hide();
                    $('#uploaded_panoramas_content').show();
                });
            },
            error: function () {
                $('#modal_uploaded_panoramas').modal('hide');
            }
        });
    }

    window.toggle_panorama_public = function(id_room) {
        $('#public_v_'+id_room).addClass('disabled');
        $('#public_v_'+id_room+' i').removeClass('fa-users-viewfinder').addClass('fa-circle-notch').addClass('fa-spin');
        $.ajax({
            url: "ajax/toggle_panorama_public.php",
            type: "POST",
            data: {
                id_room: id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#public_v_'+id_room+' i').addClass('fa-users-viewfinder').removeClass('fa-circle-notch').removeClass('fa-spin');
                $('#public_v_'+id_room).removeClass('disabled');
                if(rsp.status=='ok') {
                    switch(rsp.action) {
                        case '+':
                            $('#public_v_'+id_room).addClass('active_public_v');
                            break;
                        case '-':
                            $('#public_v_'+id_room).removeClass('active_public_v');
                            break;
                    }
                }
            },
            error: function () {
                $('#public_v_'+id_room+' i').addClass('fa-users-viewfinder').removeClass('fa-circle-notch').removeClass('fa-spin');
                $('#public_v_'+id_room).removeClass('disabled');
            }
        });
    }

    window.delete_ai_history_panorama = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $('#modal_ai_history button').addClass("disabled");
            $('.ai_list_panorama').css('pointer-event','none');
            $.ajax({
                url: "ajax/delete_ai_history_panorama.php",
                type: "POST",
                data: {
                    id_ai_log: id,
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        var ai_generated_panoramas = parseInt($('#ai_generated_panoramas').html());
                        $('#ai_generated_panoramas').html(ai_generated_panoramas-1);
                        if((ai_generated_panoramas-1)==0) {
                            $('#btn_view_ai_history').addClass('disabled_d');
                            $('#modal_ai_history').modal('hide');
                            $('#modal_ai_history button').removeClass("disabled");
                            $('.ai_list_panorama').css('pointer-event','initial');
                        } else {
                            $('#modal_ai_history button').removeClass("disabled");
                            $('.ai_list_panorama').css('pointer-event','initial');
                            view_ai_history();
                        }
                    } else {
                        $('#modal_ai_history button').removeClass("disabled");
                        $('.ai_list_panorama').css('pointer-event','initial');
                    }
                },
                error: function() {
                    $('#modal_ai_history button').removeClass("disabled");
                    $('.ai_list_panorama').css('pointer-event','initial');
                }
            });
        }
    }

    window.use_ai_history_panorama = function(ai_thumb_url,ai_file_url) {
        $('#preview_panorama_ai').hide();
        $('#btn_close_panorama_ai').hide();
        $('#btn_full_panorama_ai').hide();
        $('#ai_image').val(ai_file_url);
        $('#preview_image_ai img').attr('src',ai_thumb_url);
        $('#preview_image_ai').show();
        $('#preview_image_ai img').show();
        $('#btn_preview_panorama_ai').show();
        load_viewer_preview_room('preview_panorama_ai',ai_file_url);
        $('#modal_ai_history').modal('hide');
        $('#btn_create_room').prop('disabled',false);
    }

    window.use_uploaded_panorama = function(ai_thumb_url,ai_file_url,i) {
        var name = $('#name_use_panorama_'+i).html();
        $('#name').val(name);
        $('#preview_panorama_image').hide();
        $('#btn_close_panorama_image').hide();
        $('#btn_full_panorama_image').hide();
        $('#panorama_image').val(ai_file_url);
        $('#preview_image img').attr('src',ai_thumb_url);
        $('#preview_image').show();
        $('#preview_image img').show();
        $('#btn_preview_panorama_image').show();
        load_viewer_preview_room('preview_panorama_image',ai_file_url);
        $('#modal_uploaded_panoramas').modal('hide');
        $('#btn_create_room').prop('disabled',false);
        window.use_existing_panorama = true;
    }

    window.generate_ai_room = function() {
        $('#btn_generate_ai_room').addClass('disabled');
        $('#btn_view_ai_history').addClass('disabled');
        var html_btn = $('#btn_generate_ai_room').html();
        $('#btn_generate_ai_room').html("<i class='fas fa-circle-notch fa-spin'></i>&nbsp;&nbsp;<span id='ai_status'>sending</span>");
        $('#preview_image_ai img').attr('src','');
        $('#preview_image_ai').hide();
        $('#preview_panorama_ai').hide();
        $('#btn_close_panorama_ai').hide();
        $('#btn_full_panorama_ai').hide();
        $('#ai_image').val('');
        $('#btn_create_room').prop('disabled',true);
        var ai_prompt = $('#ai_prompt').val();
        var ai_style = $('#ai_styles option:selected').attr('id');
        var pusher = new Pusher('a6a7b7662238ce4494d5', {
            cluster: 'mt1',
        });
        pusher.connection.bind( 'error', function( err ) {
            $('#btn_generate_ai_room').removeClass('disabled');
            $('#btn_view_ai_history').removeClass('disabled');
            $('#btn_generate_ai_room').html(html_btn);
        });
        pusher.connection.bind('connected', function() {
            $.ajax({
                url: "../services/ai_generate.php",
                type: "POST",
                data: {
                    prompt: ai_prompt,
                    style: ai_style
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        window.ai_generated = window.ai_generated + 1;
                        var id_ai_log = rsp.id_ai_log;
                        $('#num_ai_generated').html(window.ai_generated);
                        var ai_perc = calculatePercentage(parseInt(window.ai_generated),parseInt(window.ai_to_generate));
                        $('#progress_ai_generations .progress-bar').css('width',ai_perc+'%');
                        $('#progress_ai_generations .progress-bar').attr('aria-valuenow',ai_perc);
                        var pusher_channel = rsp.pusher_channel;
                        var pusher_event = rsp.pusher_event;
                        const channel = pusher.subscribe(pusher_channel);
                        channel.bind(pusher_event, function (data) {
                            var status = data.status;
                            $('#ai_status').html(status);
                            switch(status) {
                                case 'complete':
                                    update_ai_log(id_ai_log,JSON.stringify(data));
                                    var ai_thumb_url = data.thumb_url;
                                    var ai_file_url = data.file_url;
                                    $('#ai_image').val(ai_file_url);
                                    $('#preview_image_ai img').attr('src',ai_thumb_url);
                                    $('#preview_image_ai').show();
                                    $('#preview_image_ai img').show();
                                    $('#btn_preview_panorama_ai').show();
                                    load_viewer_preview_room('preview_panorama_ai',ai_file_url);
                                    channel.unbind();
                                    pusher.unsubscribe(pusher_channel);
                                    pusher.disconnect();
                                    $('#btn_generate_ai_room').removeClass('disabled');
                                    $('#btn_view_ai_history').removeClass('disabled');
                                    $('#btn_generate_ai_room').html(html_btn);
                                    var ai_generated_panoramas = parseInt($('#ai_generated_panoramas').html());
                                    $('#ai_generated_panoramas').html(ai_generated_panoramas+1);
                                    if(parseInt(window.ai_generated)>=parseInt(window.ai_to_generate)) {
                                        $('#btn_generate_ai_room').remove();
                                    }
                                    $('#btn_create_room').prop('disabled',false);
                                    break;
                                case 'abort':
                                case 'error':
                                    $('#btn_generate_ai_room').removeClass('disabled');
                                    $('#btn_view_ai_history').removeClass('disabled');
                                    $('#btn_generate_ai_room').html(html_btn);
                                    if(parseInt(window.ai_generated)>=parseInt(window.ai_to_generate)) {
                                        $('#btn_generate_ai_room').remove();
                                    }
                                    break;
                            }
                        });
                    } else {
                        $('#btn_generate_ai_room').removeClass('disabled');
                        $('#btn_view_ai_history').removeClass('disabled');
                        $('#btn_generate_ai_room').html(html_btn);
                    }
                }, error: function() {
                    $('#btn_generate_ai_room').removeClass('disabled');
                    $('#btn_view_ai_history').removeClass('disabled');
                    $('#btn_generate_ai_room').html(html_btn);
                }
            });
        });
    }

    window.set_ai_prompt_max_length = function() {
        var text_max = parseInt($('#ai_styles option:selected').attr('data-max-char'));
        var image = $('#ai_styles option:selected').attr('data-image');
        $('#ai_prompt').attr('maxlength',text_max);
        var text_length = $('#ai_prompt').val().length;
        $('#ai_count_message').html(text_length+' / ' + text_max );
        if(image!='null') {
            $('#ai_preview_style_image').html('<img src="'+image+'" />');
        } else {
            $('#ai_preview_style_image').html('');
        }
        $('#ai_prompt').keyup(function() {
            var text_length = $('#ai_prompt').val().length;
            if(text_length>0) {
                $('#btn_generate_ai_room').removeClass('disabled');
            } else {
                $('#btn_generate_ai_room').addClass('disabled');
            }
            $('#ai_count_message').html(text_length + ' / ' + text_max);
        });
    }

    function calculatePercentage(first, second) {
        return (first / second) * 100;
    }

    window.change_room_type = function() {
        var type = $('#type_pano option:selected').attr('id');
        switch (type) {
            case 'image':
                $('#ai_room_div').hide();
                $('#hls_div').hide();
                $('#lottie_div').hide();
                $('#label_panorama_type').html(window.backend_labels.panorama_image);
                $('#room_upload_div #msg_accept_files').html('<i>'+window.backend_labels.panorama_image_msg+'</i>');
                $('#frm').attr('action', 'ajax/upload_room_image.php');
                $('#frm').show();
                $('#div_uploaded_panoramas_image').show();
                break;
            case 'ai_room':
                $('#hls_div').hide();
                $('#lottie_div').hide();
                $('#frm').hide();
                $('#ai_room_div').show();
                if(!window.ai_styles_loaded) {
                    ai_get_styles();
                } else {
                    $('#ai_styles').prop('disabled',false);
                }
                $('#div_uploaded_panoramas_image').hide();
                break;
            case 'video':
                $('#ai_room_div').hide();
                $('#hls_div').hide();
                $('#lottie_div').hide();
                $('#label_panorama_type').html(window.backend_labels.panorama_video);
                $('#room_upload_div #msg_accept_files').html('<i>'+window.backend_labels.panorama_video_msg+'</i>');
                $('#frm').attr('action', 'ajax/upload_room_video.php');
                $('#frm').show();
                $('#div_uploaded_panoramas_image').hide();
                break;
            case 'hls':
                $('#ai_room_div').hide();
                $('#hls_div').show();
                $('#lottie_div').hide();
                $('#label_panorama_type').html(window.backend_labels.panorama_hls);
                $('#room_upload_div #msg_accept_files').html('<i>'+window.backend_labels.panorama_hls_msg+'</i>');
                $('#frm').attr('action', 'ajax/upload_room_image.php');
                $('#frm').show();
                $('#div_uploaded_panoramas_image').hide();
                break;
            case 'lottie':
                $('#ai_room_div').hide();
                $('#hls_div').hide();
                $('#lottie_div').show();
                $('#label_panorama_type').html(window.backend_labels.panorama_lottie);
                $('#room_upload_div #msg_accept_files').html('<i>'+window.backend_labels.panorama_lottie_msg+'</i>');
                $('#frm').attr('action', 'ajax/upload_room_image.php');
                $('#frm').show();
                $('#div_uploaded_panoramas_image').hide();
                break;
        }
        window.use_existing_panorama = false;
        $('#frm')[0].reset();
        $('#frm_l')[0].reset();
        $('#preview_lottie').html('');
        $('#preview_image img').attr('src','');
        $('#preview_image').hide();
        $('#preview_image_ai img').attr('src','');
        $('#preview_image_ai').hide();
        $('#btn_preview_panorama_ai').hide();
        $('#btn_preview_panorama_image').hide();
        $('#btn_close_panorama_ai').hide();
        $('#btn_close_panorama_image').hide();
        $('#btn_full_panorama_image').hide();
        $('#btn_full_panorama_ai').hide();
        $('#btn_create_room').prop("disabled",true);
    }

    window.add_showcase = function () {
        var complete = true;
        var name = $('#name').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#modal_new_showcase button').addClass("disabled");
            $.ajax({
                url: "ajax/add_showcase.php",
                type: "POST",
                data: {
                    name: name
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_showcase button').removeClass("disabled");
                        location.href='index.php?p=edit_showcase&id='+rsp.id;
                    } else {
                        alert(rsp.msg);
                        $('#modal_new_showcase button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.add_globe = function () {
        var complete = true;
        var name = $('#name').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#modal_new_globe button').addClass("disabled");
            $.ajax({
                url: "ajax/add_globe.php",
                type: "POST",
                data: {
                    name: name
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_globe button').removeClass("disabled");
                        location.href='index.php?p=edit_globe&id='+rsp.id;
                    } else {
                        alert(rsp.msg);
                        $('#modal_new_globe button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.add_product = function () {
        var complete = true;
        var name = $('#name').val();
        var price = $('#price').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#modal_new_product button').addClass("disabled");
            $.ajax({
                url: "ajax/add_product.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    name: name,
                    price: price
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_product button').removeClass("disabled");
                        location.href='index.php?p=edit_product&id='+rsp.id;
                    } else {
                        alert(rsp.msg);
                        $('#modal_new_product button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.add_video = function () {
        var complete = true;
        var name = $('#name').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#modal_new_video button').addClass("disabled");
            $.ajax({
                url: "ajax/add_video.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    name: name,
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_video button').removeClass("disabled");
                        location.href='index.php?p=edit_video&id='+rsp.id;
                    } else {
                        alert(rsp.msg);
                        $('#modal_new_video button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.add_advertisement = function () {
        var complete = true;
        var name = $('#name').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#modal_new_advertisement button').addClass("disabled");
            $.ajax({
                url: "ajax/add_announce.php",
                type: "POST",
                data: {
                    name: name
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_advertisement button').removeClass("disabled");
                        location.href='index.php?p=edit_advertisement&id='+rsp.id;
                    } else {
                        alert(rsp.msg);
                        $('#modal_new_advertisement button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.add_user = function () {
        var complete = true;
        var username = $('#username').val();
        var email = $('#email').val();
        var language = $('#language option:selected').attr('id');
        var role = $('#role option:selected').attr('id');
        var plan = $('#plan option:selected').attr('id');
        var password = $('#password').val();
        var password2 = $('#repeat_password').val();
        if(username=='') {
            complete = false;
            $('#username').addClass("error-highlight");
        } else {
            $('#username').removeClass("error-highlight");
        }
        if(email=='') {
            complete = false;
            $('#email').addClass("error-highlight");
        } else {
            $('#email').removeClass("error-highlight");
        }
        if(password=='') {
            complete = false;
            $('#password').addClass("error-highlight");
        } else {
            $('#password').removeClass("error-highlight");
        }
        if(password2=='') {
            complete = false;
            $('#repeat_password').addClass("error-highlight");
        } else {
            $('#repeat_password').removeClass("error-highlight");
        }
        if((password!='') && (password2!='')) {
            if(password!=password2) {
                complete = false;
                $('#password').addClass("error-highlight");
                $('#repeat_password').addClass("error-highlight");
            } else {
                $('#password').removeClass("error-highlight");
                $('#repeat_password').removeClass("error-highlight");
            }
        }
        if(complete) {
            $('#modal_new_user button').addClass("disabled");
            $.ajax({
                url: "ajax/add_user.php",
                type: "POST",
                data: {
                    username_svt: username,
                    email_svt: email,
                    password_svt: password,
                    role_svt: role,
                    plan_svt: plan,
                    language: language
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $.ajax({
                            url: "ajax/send_email.php",
                            type: "POST",
                            data: {
                                type: 'user_add',
                                email: email,
                                id_user: rsp.id_user,
                                password_svt: password,
                                language: language
                            },
                            timeout: 15000,
                            async: true,
                            success: function () {
                                $('#modal_new_user button').removeClass("disabled");
                                $('#modal_new_user').modal("hide");
                                location.reload();
                            },
                            error: function(){
                                $('#modal_new_user button').removeClass("disabled");
                                $('#modal_new_user').modal("hide");
                                location.reload();
                            },
                        });
                    } else {
                        alert(rsp.msg);
                        $('#modal_new_user button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.change_password = function () {
        var complete = true;
        var password = $('#password').val();
        var password2 = $('#repeat_password').val();
        if(password=='') {
            complete = false;
            $('#password').addClass("error-highlight");
        } else {
            $('#password').removeClass("error-highlight");
        }
        if(password2=='') {
            complete = false;
            $('#repeat_password').addClass("error-highlight");
        } else {
            $('#repeat_password').removeClass("error-highlight");
        }
        if((password!='') && (password2!='')) {
            if(password!=password2) {
                complete = false;
                $('#password').addClass("error-highlight");
                $('#repeat_password').addClass("error-highlight");
            } else {
                $('#password').removeClass("error-highlight");
                $('#repeat_password').removeClass("error-highlight");
            }
        }
        var csrf_token = $('#csrf_token').val();
        if(complete) {
            $('#modal_change_password button').addClass("disabled");
            $.ajax({
                url: "ajax/change_password.php",
                type: "POST",
                data: {
                    id_svt: window.id_user_edit,
                    password_svt: password,
                    csrf_token: csrf_token
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        window.user_need_save = false;
                        $('#modal_change_password button').removeClass("disabled");
                        $('#modal_change_password').modal("hide");
                        $('#password').val('');
                        $('#repeat_password').val('');
                    } else {
                        $('#modal_change_password button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.delete_plan = function () {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $('#modal_edit_plan button').addClass("disabled");
            $.ajax({
                url: "ajax/delete_plan.php",
                type: "POST",
                data: {
                    id: window.id_plan_sel
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_edit_plan button').removeClass("disabled");
                        $('#modal_edit_plan').modal("hide");
                        window.plan_need_save = false;
                        window.plans_table.ajax.reload();
                    } else {
                        alert(rsp.msg);
                        $('#modal_edit_plan button').removeClass("disabled");
                    }
                }
            });
        } else {
            return false;
        }
    };

    window.delete_service = function () {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $('#modal_edit_service button').addClass("disabled");
            $.ajax({
                url: "ajax/delete_service.php",
                type: "POST",
                data: {
                    id: window.id_service_sel
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_edit_service button').removeClass("disabled");
                        $('#modal_edit_service').modal("hide");
                        window.service_need_save = false;
                        window.services_table.ajax.reload();
                    } else {
                        alert(rsp.msg);
                        $('#modal_edit_service button').removeClass("disabled");
                    }
                }
            });
        } else {
            return false;
        }
    };

    window.open_modal_plan_edit = function(id) {
        $.ajax({
            url: "ajax/get_plan.php",
            type: "POST",
            data: {
                id: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#name_edit').val(rsp.name);
                $('#position_edit').val(rsp.position);
                $('#n_virtual_tours_edit').val(rsp.n_virtual_tours);
                $('#n_virtual_tours_month_edit').val(rsp.n_virtual_tours_month);
                $('#n_rooms_edit').val(rsp.n_rooms);
                $('#n_rooms_tour_edit').val(rsp.n_rooms_tour);
                $('#n_markers_edit').val(rsp.n_markers);
                $('#n_pois_edit').val(rsp.n_pois);
                $('#n_gallery_images_edit').val(rsp.n_gallery_images);
                $('#n_ai_generate_month_edit').val(rsp.n_ai_generate_month);
                $('#n_autoenhance_generate_month_edit').val(rsp.n_autoenhance_generate_month);
                $('#n_gsv_publish_month_edit').val(rsp.n_gsv_publish_month);
                $('#n_custom_domain_edit').val(rsp.n_custom_domain);
                $('#days_edit').val(rsp.days);
                $('#price_edit').val(rsp.price);
                change_price('_edit');
                $('#price2_edit').val(rsp.price2);
                $("#frequency_edit option[id='"+rsp.frequency+"']").prop("selected", true);
                $("#ai_generate_mode_edit option[id='"+rsp.ai_generate_mode+"']").prop("selected", true);
                $("#autoenhance_generate_mode_edit option[id='"+rsp.autoenhance_generate_mode+"']").prop("selected", true);
                $("#gsv_publish_mode_edit option[id='"+rsp.gsv_publish_mode+"']").prop("selected", true);
                $('#interval_count_edit').val(rsp.interval_count);
                change_frequency('_edit');
                change_ai_generate_mode('_edit');
                change_autoenhance_generate_mode('_edit');
                change_gsv_publish_mode('_edit');
                $('#max_file_size_upload_edit').val(rsp.max_file_size_upload);
                $('#max_storage_space_edit').val(rsp.max_storage_space);
                $("#currency_edit option").prop("selected", false);
                $("#currency_edit option[id='"+rsp.currency+"']").prop("selected", true);
                $("#expire_tours_edit option[id='"+rsp.expire_tours+"']").prop("selected", true);
                $('#features_edit #create_landing_edit').prop('selected',(rsp.create_landing==1)?true:false);
                $('#features_edit #create_showcase_edit').prop('selected',(rsp.create_showcase==1)?true:false);
                $('#features_edit #create_globes_edit').prop('selected',(rsp.create_globes==1)?true:false);
                $('#features_edit #create_gallery_edit').prop('selected',(rsp.create_gallery==1)?true:false);
                $('#features_edit #enable_download_slideshow_edit').prop('selected',(rsp.enable_download_slideshow==1)?true:false);
                $('#features_edit #create_presentation_edit').prop('selected',(rsp.create_presentation==1)?true:false);
                $('#features_edit #create_video360_edit').prop('selected',(rsp.create_video360==1)?true:false);
                $('#features_edit #create_video_projects_edit').prop('selected',(rsp.create_video_projects==1)?true:false);
                $('#features_edit #enable_live_session_edit').prop('selected',(rsp.enable_live_session==1)?true:false);
                $('#features_edit #enable_meeting_edit').prop('selected',(rsp.enable_meeting==1)?true:false);
                $('#features_edit #enable_info_box_edit').prop('selected',(rsp.enable_info_box==1)?true:false);
                $('#features_edit #enable_context_info_edit').prop('selected',(rsp.enable_context_info==1)?true:false);
                $('#features_edit #enable_maps_edit').prop('selected',(rsp.enable_maps==1)?true:false);
                $('#features_edit #enable_icons_library_edit').prop('selected',(rsp.enable_icons_library==1)?true:false);
                $('#features_edit #enable_media_library_edit').prop('selected',(rsp.enable_media_library==1)?true:false);
                $('#features_edit #enable_music_library_edit').prop('selected',(rsp.enable_music_library==1)?true:false);
                $('#features_edit #enable_sound_library_edit').prop('selected',(rsp.enable_sound_library==1)?true:false);
                $('#features_edit #enable_voice_commands_edit').prop('selected',(rsp.enable_voice_commands==1)?true:false);
                $('#features_edit #enable_chat_edit').prop('selected',(rsp.enable_chat==1)?true:false);
                $('#features_edit #enable_auto_rotate_edit').prop('selected',(rsp.enable_auto_rotate==1)?true:false);
                $('#features_edit #enable_flyin_edit').prop('selected',(rsp.enable_flyin==1)?true:false);
                $('#features_edit #enable_multires_edit').prop('selected',(rsp.enable_multires==1)?true:false);
                $('#features_edit #enable_password_tours_edit').prop('selected',(rsp.enable_password_tour==1)?true:false);
                $('#features_edit #enable_expiring_dates_edit').prop('selected',(rsp.enable_expiring_dates==1)?true:false);
                $('#features_edit #enable_export_vt_edit').prop('selected',(rsp.enable_export_vt==1)?true:false);
                $('#features_edit #enable_import_export_edit').prop('selected',(rsp.enable_import_export==1)?true:false);
                $('#features_edit #enable_statistics_edit').prop('selected',(rsp.enable_statistics==1)?true:false);
                $('#features_edit #enable_multilanguage_edit').prop('selected',(rsp.enable_multilanguage==1)?true:false);
                $('#features_edit #enable_auto_translation_edit').prop('selected',(rsp.enable_auto_translation==1)?true:false);
                $('#features_edit #enable_forms_edit').prop('selected',(rsp.enable_forms==1)?true:false);
                $('#features_edit #enable_logo_edit').prop('selected',(rsp.enable_logo==1)?true:false);
                $('#features_edit #enable_poweredby_edit').prop('selected',(rsp.enable_poweredby==1)?true:false);
                $('#features_edit #enable_nadir_logo_edit').prop('selected',(rsp.enable_nadir_logo==1)?true:false);
                $('#features_edit #enable_song_edit').prop('selected',(rsp.enable_song==1)?true:false);
                $('#features_edit #enable_comments_edit').prop('selected',(rsp.enable_comments==1)?true:false);
                $('#features_edit #enable_annotations_edit').prop('selected',(rsp.enable_annotations==1)?true:false);
                $('#features_edit #enable_avatar_video_edit').prop('selected',(rsp.enable_avatar_video==1)?true:false);
                $('#features_edit #enable_panorama_video_edit').prop('selected',(rsp.enable_panorama_video==1)?true:false);
                $('#features_edit #enable_ai_room_edit').prop('selected',(rsp.enable_ai_room==1)?true:false);
                $('#features_edit #enable_autoenhance_room_edit').prop('selected',(rsp.enable_autoenhance_room==1)?true:false);
                $('#features_edit #enable_rooms_multiple_edit').prop('selected',(rsp.enable_rooms_multiple==1)?true:false);
                $('#features_edit #enable_rooms_protect_edit').prop('selected',(rsp.enable_rooms_protect==1)?true:false);
                $('#features_edit #enable_share_edit').prop('selected',(rsp.enable_share==1)?true:false);
                $('#features_edit #enable_snapshot_edit').prop('selected',(rsp.enable_snapshot==1)?true:false);
                $('#features_edit #enable_device_orientation_edit').prop('selected',(rsp.enable_device_orientation==1)?true:false);
                $('#features_edit #enable_webvr_edit').prop('selected',(rsp.enable_webvr==1)?true:false);
                $('#features_edit #enable_shop_edit').prop('selected',(rsp.enable_shop==1)?true:false);
                $('#features_edit #enable_learning_edit').prop('selected',(rsp.enable_learning==1)?true:false);
                $('#features_edit #enable_dollhouse_edit').prop('selected',(rsp.enable_dollhouse==1)?true:false);
                $('#features_edit #enable_editor_ui_edit').prop('selected',(rsp.enable_editor_ui==1)?true:false);
                $('#features_edit #enable_custom_html_edit').prop('selected',(rsp.enable_custom_html==1)?true:false);
                $('#features_edit #enable_metatag_edit').prop('selected',(rsp.enable_metatag==1)?true:false);
                $('#features_edit #enable_loading_iv_edit').prop('selected',(rsp.enable_loading_iv==1)?true:false);
                $('#features_edit #enable_intro_slider_edit').prop('selected',(rsp.enable_intro_slider==1)?true:false);
                $('#features_edit #enable_measurements_edit').prop('selected',(rsp.enable_measurements==1)?true:false);
                $('#features_edit #enable_gsv_publish').prop('selected',(rsp.enable_gsv_publish==1)?true:false);
                $('#features_edit #enable_custom_domain').prop('selected',(rsp.enable_custom_domain==1)?true:false);
                $('#features_edit').selectpicker('refresh');
                var count_usage = rsp.count_usage;
                if(count_usage>0) {
                    $('#btn_delete_plan').addClass("disabled");
                } else {
                    $('#btn_delete_plan').removeClass("disabled");
                }
                if(rsp.visible==1) {
                    $('#visible_edit').prop('checked',true);
                } else {
                    $('#visible_edit').prop('checked',false);
                }
                $('#external_url_edit').val(rsp.external_url);
                $('#custom_features_edit').val(rsp.custom_features);
                var customize_menu = rsp.customize_menu;
                $('#customize_menu_edit option').prop('selected',true);
                $('#customize_menu_edit option[data-divider="true"]').prop('selected',false);
                if(customize_menu!='') {
                    var menu_items = JSON.parse(customize_menu);
                    jQuery.each(menu_items,function (menu_item,enabled) {
                        $('#customize_menu_edit #'+menu_item).prop('selected',enabled);
                    });
                }
                $('#customize_menu_edit').selectpicker('refresh');
                $("#button_type_edit option[id='"+rsp.button_type+"']").prop("selected", true);
                switch(rsp.button_type) {
                    case 'custom':
                        $('#button_text_edit').prop('disabled',false);
                        $('#GetIconPicker_edit').prop('disabled',false);
                        $('#button_icon_preview_edit').show();
                        break;
                    default:
                        $('#button_text_edit').prop('disabled',true);
                        $('#GetIconPicker_edit').prop('disabled',true);
                        $('#button_icon_preview_edit').hide();
                        break;
                }
                $("#button_text_edit").val(rsp.button_text);
                $("#button_icon_edit").val(rsp.button_icon);
                $("#button_icon_preview_edit").addClass(rsp.button_icon);
                $('#sample_override_edit').prop('checked',(parseInt(rsp.override_sample)==1)?true:false);
                $('#template_override_edit').prop('checked',(parseInt(rsp.override_template)==1)?true:false);
                $('#enable_sample_edit').prop('checked',(parseInt(rsp.enable_sample)==1)?true:false);
                if(parseInt(rsp.override_sample)==0) {
                    $('#sample_settings_edit').addClass('disabled');
                } else {
                    $('#sample_settings_edit').removeClass('disabled');
                }
                if(parseInt(rsp.override_template)==0) {
                    $('#template_settings_edit').addClass('disabled');
                } else {
                    $('#template_settings_edit').removeClass('disabled');
                }
                $("#id_vt_template_edit option").prop("selected", false);
                $("#id_vt_template_edit option[id='"+rsp.id_vt_template+"']").prop("selected", true);
                $('#id_vt_template_edit').selectpicker('refresh');
                var id_vt_sample = rsp.id_vt_sample;
                $('#id_vt_sample_edit option').prop('selected',false);
                if(id_vt_sample!=null && id_vt_sample!='') {
                    var id_vt_samples = id_vt_sample.split(",");
                    jQuery.each(id_vt_samples,function (index_sample,id_sample) {
                        $('#id_vt_sample_edit #'+id_sample).prop('selected',true);
                    });
                }
                $('#id_vt_sample_edit').selectpicker('refresh');
                $('#price_label_edit').val(rsp.price_label);
                $('#description_edit').val(rsp.description);
                $('#show_features_edit').prop('checked',(parseInt(rsp.show_features)==1)?true:false);
                $('.input_lang[data-target-id="name_edit"]').val('');
                $('.input_lang[data-target-id="description_edit"]').val('');
                $('.input_lang[data-target-id="price_label_edit"]').val('');
                $('.input_lang[data-target-id="custom_features_edit"]').val('');
                $('.input_lang[data-target-id="button_text_edit"]').val('');
                $('.input_lang[data-target-id="name_edit"]').attr('placeholder',rsp.name);
                $('.input_lang[data-target-id="description_edit"]').attr('placeholder',rsp.description);
                $('.input_lang[data-target-id="price_label_edit"]').attr('placeholder',rsp.price_label);
                $('.input_lang[data-target-id="custom_features_edit"]').attr('placeholder',rsp.custom_features);
                $('.input_lang[data-target-id="button_text_edit"]').attr('placeholder',rsp.button_text);
                jQuery.each(rsp.array_lang, function(index_l,item_lang) {
                    $('.input_lang[data-target-id="name_edit"][data-lang="'+item_lang.language+'"]').val(item_lang.name);
                    $('.input_lang[data-target-id="description_edit"][data-lang="'+item_lang.language+'"]').val(item_lang.description);
                    $('.input_lang[data-target-id="price_label_edit"][data-lang="'+item_lang.language+'"]').val(item_lang.price_label);
                    $('.input_lang[data-target-id="custom_features_edit"][data-lang="'+item_lang.language+'"]').val(item_lang.custom_features);
                    $('.input_lang[data-target-id="button_text_edit"][data-lang="'+item_lang.language+'"]').val(item_lang.button_text);
                });
                $('#modal_edit_plan').modal("show");
            }
        });
    };

    window.open_modal_service_edit = function(id) {
        $.ajax({
            url: "ajax/get_service.php",
            type: "POST",
            data: {
                id: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#name_edit').val(rsp.name);
                $('#position_edit').val(rsp.position);
                window.description_edit_editor.root.innerHTML=rsp.description;
                $("#type_edit option").prop("selected", false);
                $("#type_edit option[id='"+rsp.type+"']").prop("selected", true);
                $('#price_edit').val(rsp.price);
                $('#credits_edit').val(rsp.credits);
                change_service_type('_edit');
                $("#currency_edit option").prop("selected", false);
                $("#currency_edit option[id='"+rsp.currency+"']").prop("selected", true);
                $('#block_tour_edit').prop('checked',(parseInt(rsp.block_tour)==1)?true:false);
                $('#visible_edit').prop('checked',(parseInt(rsp.visible)==1)?true:false);
                var array_input_lang = rsp.array_input_lang;
                setTimeout(function() {
                    $('.input_lang[data-target-id="name_edit"]').each(function() {
                        var lang = $(this).attr('data-lang');
                        if (array_input_lang && array_input_lang[lang] && array_input_lang[lang].name !== undefined) {
                            $(this).val(array_input_lang[lang].name);
                        } else {
                            $(this).val('');
                        }
                        $(this).attr('placeholder',rsp.name);
                    });
                    $('.input_lang[data-target-id="description_edit"]').each(function() {
                        var lang = $(this).attr('data-lang');
                        if (array_input_lang && array_input_lang[lang] && array_input_lang[lang].description !== undefined) {
                            window.description_edit_editor_lang[lang].root.innerHTML = array_input_lang[lang].description;
                        } else {
                            window.description_edit_editor_lang[lang].root.innerHTML = '';
                        }
                        window.description_edit_editor_lang[lang].root.dataset.placeholder = truncateString(window.description_edit_editor.getText(),100);
                    });
                },100);
                $('#modal_edit_service').modal("show");
            }
        });
    };

    window.add_plan = function () {
        var complete = true;
        var name = $('#name').val();
        var position = $('#position').val();
        var n_virtual_tours = $('#n_virtual_tours').val();
        var n_virtual_tours_month = $('#n_virtual_tours_month').val();
        var n_rooms = $('#n_rooms').val();
        var n_rooms_tour = $('#n_rooms_tour').val();
        var n_markers = $('#n_markers').val();
        var n_pois = $('#n_pois').val();
        var n_gallery_images = $('#n_gallery_images').val();
        var n_ai_generate_month = $('#n_ai_generate_month').val();
        var n_autoenhance_generate_month = $('#n_autoenhance_generate_month').val();
        var max_file_size_upload = $('#max_file_size_upload').val();
        var max_storace_space = $('#max_storage_space').val();
        var create_landing = ($('#features option[id="create_landing"]').is(':selected')) ? 1 : 0;
        var create_showcase = ($('#features option[id="create_showcase"]').is(':selected')) ? 1 : 0;
        var create_globes = ($('#features option[id="create_globes"]').is(':selected')) ? 1 : 0;
        var create_gallery = ($('#features option[id="create_gallery"]').is(':selected')) ? 1 : 0;
        var enable_download_slideshow = ($('#features option[id="enable_download_slideshow"]').is(':selected')) ? 1 : 0;
        var create_presentation = ($('#features option[id="create_presentation"]').is(':selected')) ? 1 : 0;
        var create_video360 = ($('#features option[id="create_video360"]').is(':selected')) ? 1 : 0;
        var create_video_projects = ($('#features option[id="create_video_projects"]').is(':selected')) ? 1 : 0;
        var enable_live_session = ($('#features option[id="enable_live_session"]').is(':selected')) ? 1 : 0;
        var enable_meeting = ($('#features option[id="enable_meeting"]').is(':selected')) ? 1 : 0;
        var enable_chat = ($('#features option[id="enable_chat"]').is(':selected')) ? 1 : 0;
        var enable_voice_commands = ($('#features option[id="enable_voice_commands"]').is(':selected')) ? 1 : 0;
        var enable_share = ($('#features option[id="enable_share"]').is(':selected')) ? 1 : 0;
        var enable_snapshot = ($('#features option[id="enable_snapshot"]').is(':selected')) ? 1 : 0;
        var enable_device_orientation = ($('#features option[id="enable_device_orientation"]').is(':selected')) ? 1 : 0;
        var enable_webvr = ($('#features option[id="enable_webvr"]').is(':selected')) ? 1 : 0;
        var enable_logo = ($('#features option[id="enable_logo"]').is(':selected')) ? 1 : 0;
        var enable_poweredby = ($('#features option[id="enable_poweredby"]').is(':selected')) ? 1 : 0;
        var enable_nadir_logo = ($('#features option[id="enable_nadir_logo"]').is(':selected')) ? 1 : 0;
        var enable_song = ($('#features option[id="enable_song"]').is(':selected')) ? 1 : 0;
        var enable_comments = ($('#features option[id="enable_comments"]').is(':selected')) ? 1 : 0;
        var enable_forms = ($('#features option[id="enable_forms"]').is(':selected')) ? 1 : 0;
        var enable_annotations = ($('#features option[id="enable_annotations"]').is(':selected')) ? 1 : 0;
        var enable_avatar_video = ($('#features option[id="enable_avatar_video"]').is(':selected')) ? 1 : 0;
        var enable_panorama_video = ($('#features option[id="enable_panorama_video"]').is(':selected')) ? 1 : 0;
        var enable_ai_room = ($('#features option[id="enable_ai_room"]').is(':selected')) ? 1 : 0;
        var enable_autoenhance_room = ($('#features option[id="enable_autoenhance_room"]').is(':selected')) ? 1 : 0;
        var enable_rooms_multiple = ($('#features option[id="enable_rooms_multiple"]').is(':selected')) ? 1 : 0;
        var enable_rooms_protect = ($('#features option[id="enable_rooms_protect"]').is(':selected')) ? 1 : 0;
        var enable_info_box = ($('#features option[id="enable_info_box"]').is(':selected')) ? 1 : 0;
        var enable_context_info = ($('#features option[id="enable_context_info"]').is(':selected')) ? 1 : 0;
        var enable_maps = ($('#features option[id="enable_maps"]').is(':selected')) ? 1 : 0;
        var enable_icons_library = ($('#features option[id="enable_icons_library"]').is(':selected')) ? 1 : 0;
        var enable_media_library = ($('#features option[id="enable_media_library"]').is(':selected')) ? 1 : 0;
        var enable_music_library = ($('#features option[id="enable_music_library"]').is(':selected')) ? 1 : 0;
        var enable_sound_library = ($('#features option[id="enable_sound_library"]').is(':selected')) ? 1 : 0;
        var enable_password_tour = ($('#features option[id="enable_password_tours"]').is(':selected')) ? 1 : 0;
        var enable_expiring_dates = ($('#features option[id="enable_expiring_dates"]').is(':selected')) ? 1 : 0;
        var enable_export_vt = ($('#features option[id="enable_export_vt"]').is(':selected')) ? 1 : 0;
        var enable_import_export = ($('#features option[id="enable_import_export"]').is(':selected')) ? 1 : 0;
        var enable_statistics = ($('#features option[id="enable_statistics"]').is(':selected')) ? 1 : 0;
        var enable_multilanguage = ($('#features option[id="enable_multilanguage"]').is(':selected')) ? 1 : 0;
        var enable_auto_translation = ($('#features option[id="enable_auto_translation"]').is(':selected')) ? 1 : 0;
        var enable_auto_rotate = ($('#features option[id="enable_auto_rotate"]').is(':selected')) ? 1 : 0;
        var enable_flyin = ($('#features option[id="enable_flyin"]').is(':selected')) ? 1 : 0;
        var enable_multires = ($('#features option[id="enable_multires"]').is(':selected')) ? 1 : 0;
        var enable_shop = ($('#features option[id="enable_shop"]').is(':selected')) ? 1 : 0;
        var enable_learning = ($('#features option[id="enable_learning"]').is(':selected')) ? 1 : 0;
        var enable_dollhouse = ($('#features option[id="enable_dollhouse"]').is(':selected')) ? 1 : 0;
        var enable_editor_ui = ($('#features option[id="enable_editor_ui"]').is(':selected')) ? 1 : 0;
        var enable_custom_html = ($('#features option[id="enable_custom_html"]').is(':selected')) ? 1 : 0;
        var enable_metatag = ($('#features option[id="enable_metatag"]').is(':selected')) ? 1 : 0;
        var enable_loading_iv = ($('#features option[id="enable_loading_iv"]').is(':selected')) ? 1 : 0;
        var enable_intro_slider = ($('#features option[id="enable_intro_slider"]').is(':selected')) ? 1 : 0;
        var enable_measurements = ($('#features option[id="enable_measurements"]').is(':selected')) ? 1 : 0;
        var days = $('#days').val();
        var price = $('#price').val();
        var price2 = $('#price2').val();
        var frequency = $('#frequency option:selected').attr('id');
        var ai_generate_mode = $('#ai_generate_mode option:selected').attr('id');
        var autoenhance_generate_mode = $('#autoenhance_generate_mode option:selected').attr('id');
        var interval_count = $('#interval_count').val();
        var currency = $('#currency option:selected').attr('id');
        var visible = ($('#visible').is(':checked')) ? 1 : 0;
        var external_url = $('#external_url').val();
        var expire_tours = $('#expire_tours option:selected').attr('id');
        var custom_features = $('#custom_features').val();
        var customize_menu_edit_t = $('#customize_menu option');
        var customize_menu = {};
        $(customize_menu_edit_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    customize_menu[id]=1;
                } else {
                    customize_menu[id]=0;
                }
            }
        });
        var customize_menu_json = JSON.stringify(customize_menu);
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var button_type = $('#button_type option:selected').attr('id');
        var button_text = $('#button_text').val();
        var button_icon = $('#button_icon').val();
        var override_template = $('#template_override_add').is(':checked') ? 1 : 0;
        var override_sample = $('#sample_override_add').is(':checked') ? 1 : 0;
        var enable_sample = $('#enable_sample_add').is(':checked') ? 1 : 0;
        var id_vt_template = $('#id_vt_template_add option:selected').attr('id');
        var id_vt_sample_t = $('#id_vt_sample_add option');
        var id_vt_sample = '';
        $(id_vt_sample_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    id_vt_sample += id+",";
                }
            }
        });
        let lastIndex = id_vt_sample.lastIndexOf(",");
        if (lastIndex !== -1) {
            id_vt_sample = id_vt_sample.slice(0, lastIndex) + id_vt_sample.slice(lastIndex + 1);
        }
        if(window.gsv_installed) {
            var enable_gsv_publish = ($('#features option[id="enable_gsv_publish"]').is(':selected')) ? 1 : 0;
            var gsv_publish_mode = $('#gsv_publish_mode option:selected').attr('id');
            var n_gsv_publish_month = $('#n_gsv_publish_month').val();
        } else {
            var enable_gsv_publish = 0;
            var gsv_publish_mode = 'month';
            var n_gsv_publish_month = -1;
        }
        if(custom_domain_enabled) {
            var enable_custom_domain =  ($('#features option[id="enable_custom_domain"]').is(':selected')) ? 1 : 0;
            var n_custom_domain = $('#n_custom_domain').val();
        } else {
            var enable_custom_domain = 0;
            var n_custom_domain = 0;
        }
        var price_label = $('#price_label').val();
        var description = $('#description').val();
        var show_features = $('#show_features').is(':checked') ? 1 : 0;
        var array_lang = {};
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['description'][lang]=value;
        });
        array_lang['price_label'] = {};
        $('.input_lang[data-target-id="price_label"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['price_label'][lang]=value;
        });
        array_lang['custom_features'] = {};
        $('.input_lang[data-target-id="custom_features"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom_features'][lang]=value;
        });
        array_lang['button_text'] = {};
        $('.input_lang[data-target-id="button_text"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['button_text'][lang]=value;
        });
        var array_lang_json = JSON.stringify(array_lang);
        if(complete) {
            $('#modal_new_plan button').addClass("disabled");
            $.ajax({
                url: "ajax/add_plan.php",
                type: "POST",
                data: {
                    name: name,
                    position: position,
                    n_virtual_tours: n_virtual_tours,
                    n_virtual_tours_month: n_virtual_tours_month,
                    n_rooms: n_rooms,
                    n_rooms_tour: n_rooms_tour,
                    n_markers: n_markers,
                    n_pois: n_pois,
                    n_gallery_images: n_gallery_images,
                    n_ai_generate_month: n_ai_generate_month,
                    n_autoenhance_generate_month: n_autoenhance_generate_month,
                    days: days,
                    price: price,
                    price2: price2,
                    currency: currency,
                    custom_features: custom_features,
                    create_landing: create_landing,
                    create_showcase: create_showcase,
                    create_globes: create_globes,
                    create_gallery: create_gallery,
                    enable_download_slideshow: enable_download_slideshow,
                    create_presentation: create_presentation,
                    create_video360: create_video360,
                    create_video_projects: create_video_projects,
                    enable_live_session: enable_live_session,
                    enable_meeting: enable_meeting,
                    max_file_size_upload: max_file_size_upload,
                    max_storace_space: max_storace_space,
                    enable_chat: enable_chat,
                    enable_voice_commands: enable_voice_commands,
                    enable_share: enable_share,
                    enable_snapshot: enable_snapshot,
                    enable_device_orientation: enable_device_orientation,
                    enable_webvr: enable_webvr,
                    enable_logo: enable_logo,
                    enable_poweredby: enable_poweredby,
                    enable_nadir_logo: enable_nadir_logo,
                    enable_song: enable_song,
                    enable_comments: enable_comments,
                    enable_forms: enable_forms,
                    enable_annotations: enable_annotations,
                    enable_avatar_video: enable_avatar_video,
                    enable_panorama_video: enable_panorama_video,
                    enable_ai_room: enable_ai_room,
                    enable_autoenhance_room: enable_autoenhance_room,
                    enable_rooms_multiple: enable_rooms_multiple,
                    enable_rooms_protect: enable_rooms_protect,
                    enable_info_box: enable_info_box,
                    enable_context_info: enable_context_info,
                    enable_maps: enable_maps,
                    enable_icons_library: enable_icons_library,
                    enable_media_library: enable_media_library,
                    enable_music_library: enable_music_library,
                    enable_sound_library: enable_sound_library,
                    enable_password_tour: enable_password_tour,
                    enable_expiring_dates: enable_expiring_dates,
                    enable_export_vt: enable_export_vt,
                    enable_import_export: enable_import_export,
                    enable_statistics: enable_statistics,
                    enable_multilanguage: enable_multilanguage,
                    enable_auto_translation: enable_auto_translation,
                    enable_auto_rotate: enable_auto_rotate,
                    enable_flyin: enable_flyin,
                    enable_multires: enable_multires,
                    enable_shop: enable_shop,
                    enable_learning: enable_learning,
                    enable_dollhouse: enable_dollhouse,
                    enable_editor_ui: enable_editor_ui,
                    enable_custom_html: enable_custom_html,
                    enable_metatag: enable_metatag,
                    enable_loading_iv: enable_loading_iv,
                    enable_intro_slider: enable_intro_slider,
                    enable_measurements: enable_measurements,
                    visible: visible,
                    external_url: external_url,
                    frequency: frequency,
                    interval_count: interval_count,
                    customize_menu: customize_menu_json,
                    expire_tours: expire_tours,
                    button_type: button_type,
                    button_text: button_text,
                    button_icon: button_icon,
                    override_template: override_template,
                    override_sample: override_sample,
                    id_vt_template: id_vt_template,
                    enable_sample: enable_sample,
                    id_vt_sample: id_vt_sample,
                    ai_generate_mode: ai_generate_mode,
                    autoenhance_generate_mode: autoenhance_generate_mode,
                    enable_gsv_publish: enable_gsv_publish,
                    gsv_publish_mode: gsv_publish_mode,
                    n_gsv_publish_month: n_gsv_publish_month,
                    enable_custom_domain: enable_custom_domain,
                    n_custom_domain: n_custom_domain,
                    price_label: price_label,
                    description: description,
                    show_features: show_features,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_plan button').removeClass("disabled");
                        $('#modal_new_plan').modal("hide");
                        window.plan_need_save = false;
                        window.plans_table.ajax.reload();
                        if(window.stripe_enabled) {
                            stripe_initialize(rsp.id,0);
                        }
                        if(window.paypal_enabled) {
                            paypal_initialize(rsp.id,0);
                        }
                        if(max_storace_space!=-1) {
                            $.ajax({
                                url: "../services/calculate_storage_space.php",
                                type: "POST",
                                async: true,
                                success: function (json) {}
                            });
                        }
                    } else {
                        $('#modal_new_plan button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.add_service = function () {
        var complete = true;
        var array_lang = {};
        var name = $('#name').val();
        var position = $('#position').val();
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var description = window.description_editor.root.innerHTML;
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.description_editor_lang[lang].root.innerHTML;
            array_lang['description'][lang]=value;
        });
        var price = $('#price').val();
        var credits = $('#credits').val();
        var currency = $('#currency option:selected').attr('id');
        var type = $('#type option:selected').attr('id');
        var block_tour = ($('#block_tour').is(':checked')) ? 1 : 0;
        var visible = ($('#visible').is(':checked')) ? 1 : 0;
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var array_lang_json = JSON.stringify(array_lang);
        if(complete) {
            $('#modal_new_service button').addClass("disabled");
            $.ajax({
                url: "ajax/add_service.php",
                type: "POST",
                data: {
                    name: name,
                    position: position,
                    description: description,
                    price: price,
                    credits: credits,
                    currency: currency,
                    type: type,
                    block_tour: block_tour,
                    visible: visible,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_service button').removeClass("disabled");
                        $('#modal_new_service').modal("hide");
                        window.service_need_save = false;
                        location.reload();
                    } else {
                        $('#modal_new_service button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.save_plan = function () {
        var complete = true;
        var name = $('#name_edit').val();
        var position = $('#position_edit').val();
        var n_virtual_tours = $('#n_virtual_tours_edit').val();
        var n_virtual_tours_month = $('#n_virtual_tours_month_edit').val();
        var n_rooms = $('#n_rooms_edit').val();
        var n_rooms_tour = $('#n_rooms_tour_edit').val();
        var n_markers = $('#n_markers_edit').val();
        var n_pois = $('#n_pois_edit').val();
        var n_gallery_images = $('#n_gallery_images_edit').val();
        var n_ai_generate_month = $('#n_ai_generate_month_edit').val();
        var n_autoenhance_generate_month = $('#n_autoenhance_generate_month_edit').val();
        var days = $('#days_edit').val();
        var max_file_size_upload = $('#max_file_size_upload_edit').val();
        var max_storace_space = $('#max_storage_space_edit').val();
        var create_landing = ($('#features_edit option[id="create_landing_edit"]').is(':selected')) ? 1 : 0;
        var create_showcase = ($('#features_edit option[id="create_showcase_edit"]').is(':selected')) ? 1 : 0;
        var create_globes = ($('#features_edit option[id="create_globes_edit"]').is(':selected')) ? 1 : 0;
        var create_gallery = ($('#features_edit option[id="create_gallery_edit"]').is(':selected')) ? 1 : 0;
        var enable_download_slideshow = ($('#features_edit option[id="enable_download_slideshow_edit"]').is(':selected')) ? 1 : 0;
        var create_presentation = ($('#features_edit option[id="create_presentation_edit"]').is(':selected')) ? 1 : 0;
        var create_video360 = ($('#features_edit option[id="create_video360_edit"]').is(':selected')) ? 1 : 0;
        var create_video_projects = ($('#features_edit option[id="create_video_projects_edit"]').is(':selected')) ? 1 : 0;
        var enable_live_session = ($('#features_edit option[id="enable_live_session_edit"]').is(':selected')) ? 1 : 0;
        var enable_meeting = ($('#features_edit option[id="enable_meeting_edit"]').is(':selected')) ? 1 : 0;
        var enable_chat = ($('#features_edit option[id="enable_chat_edit"]').is(':selected')) ? 1 : 0;
        var enable_voice_commands = ($('#features_edit option[id="enable_voice_commands_edit"]').is(':selected')) ? 1 : 0;
        var enable_share = ($('#features_edit option[id="enable_share_edit"]').is(':selected')) ? 1 : 0;
        var enable_snapshot = ($('#features_edit option[id="enable_snapshot_edit"]').is(':selected')) ? 1 : 0;
        var enable_device_orientation = ($('#features_edit option[id="enable_device_orientation_edit"]').is(':selected')) ? 1 : 0;
        var enable_webvr = ($('#features_edit option[id="enable_webvr_edit"]').is(':selected')) ? 1 : 0;
        var enable_logo = ($('#features_edit option[id="enable_logo_edit"]').is(':selected')) ? 1 : 0;
        var enable_poweredby = ($('#features_edit option[id="enable_poweredby_edit"]').is(':selected')) ? 1 : 0;
        var enable_nadir_logo = ($('#features_edit option[id="enable_nadir_logo_edit"]').is(':selected')) ? 1 : 0;
        var enable_song = ($('#features_edit option[id="enable_song_edit"]').is(':selected')) ? 1 : 0;
        var enable_comments = ($('#features_edit option[id="enable_comments_edit"]').is(':selected')) ? 1 : 0;
        var enable_forms = ($('#features_edit option[id="enable_forms_edit"]').is(':selected')) ? 1 : 0;
        var enable_annotations = ($('#features_edit option[id="enable_annotations_edit"]').is(':selected')) ? 1 : 0;
        var enable_avatar_video = ($('#features_edit option[id="enable_avatar_video_edit"]').is(':selected')) ? 1 : 0;
        var enable_panorama_video = ($('#features_edit option[id="enable_panorama_video_edit"]').is(':selected')) ? 1 : 0;
        var enable_ai_room = ($('#features_edit option[id="enable_ai_room_edit"]').is(':selected')) ? 1 : 0;
        var enable_autoenhance_room = ($('#features_edit option[id="enable_autoenhance_room_edit"]').is(':selected')) ? 1 : 0;
        var enable_rooms_multiple = ($('#features_edit option[id="enable_rooms_multiple_edit"]').is(':selected')) ? 1 : 0;
        var enable_rooms_protect = ($('#features_edit option[id="enable_rooms_protect_edit"]').is(':selected')) ? 1 : 0;
        var enable_info_box = ($('#features_edit option[id="enable_info_box_edit"]').is(':selected')) ? 1 : 0;
        var enable_context_info = ($('#features_edit option[id="enable_context_info_edit"]').is(':selected')) ? 1 : 0;
        var enable_maps = ($('#features_edit option[id="enable_maps_edit"]').is(':selected')) ? 1 : 0;
        var enable_icons_library = ($('#features_edit option[id="enable_icons_library_edit"]').is(':selected')) ? 1 : 0;
        var enable_media_library = ($('#features_edit option[id="enable_media_library_edit"]').is(':selected')) ? 1 : 0;
        var enable_music_library = ($('#features_edit option[id="enable_music_library_edit"]').is(':selected')) ? 1 : 0;
        var enable_sound_library = ($('#features_edit option[id="enable_sound_library_edit"]').is(':selected')) ? 1 : 0;
        var enable_password_tour = ($('#features_edit option[id="enable_password_tours_edit"]').is(':selected')) ? 1 : 0;
        var enable_expiring_dates = ($('#features_edit option[id="enable_expiring_dates_edit"]').is(':selected')) ? 1 : 0;
        var enable_export_vt = ($('#features_edit option[id="enable_export_vt_edit"]').is(':selected')) ? 1 : 0;
        var enable_import_export = ($('#features_edit option[id="enable_import_export_edit"]').is(':selected')) ? 1 : 0;
        var enable_statistics = ($('#features_edit option[id="enable_statistics_edit"]').is(':selected')) ? 1 : 0;
        var enable_multilanguage = ($('#features_edit option[id="enable_multilanguage_edit"]').is(':selected')) ? 1 : 0;
        var enable_auto_translation = ($('#features_edit option[id="enable_auto_translation_edit"]').is(':selected')) ? 1 : 0;
        var enable_auto_rotate = ($('#features_edit option[id="enable_auto_rotate_edit"]').is(':selected')) ? 1 : 0;
        var enable_flyin = ($('#features_edit option[id="enable_flyin_edit"]').is(':selected')) ? 1 : 0;
        var enable_multires = ($('#features_edit option[id="enable_multires_edit"]').is(':selected')) ? 1 : 0;
        var enable_shop = ($('#features_edit option[id="enable_shop_edit"]').is(':selected')) ? 1 : 0;
        var enable_learning = ($('#features_edit option[id="enable_learning_edit"]').is(':selected')) ? 1 : 0;
        var enable_dollhouse = ($('#features_edit option[id="enable_dollhouse_edit"]').is(':selected')) ? 1 : 0;
        var enable_editor_ui = ($('#features_edit option[id="enable_editor_ui_edit"]').is(':selected')) ? 1 : 0;
        var enable_custom_html = ($('#features_edit option[id="enable_custom_html_edit"]').is(':selected')) ? 1 : 0;
        var enable_metatag = ($('#features_edit option[id="enable_metatag_edit"]').is(':selected')) ? 1 : 0;
        var enable_loading_iv = ($('#features_edit option[id="enable_loading_iv_edit"]').is(':selected')) ? 1 : 0;
        var enable_intro_slider = ($('#features_edit option[id="enable_intro_slider_edit"]').is(':selected')) ? 1 : 0;
        var enable_measurements = ($('#features_edit option[id="enable_measurements_edit"]').is(':selected')) ? 1 : 0;
        var price = $('#price_edit').val();
        var price2 = $('#price2_edit').val();
        var frequency = $('#frequency_edit option:selected').attr('id');
        var ai_generate_mode = $('#ai_generate_mode_edit option:selected').attr('id');
        var autoenhance_generate_mode = $('#autoenhance_generate_mode_edit option:selected').attr('id');
        var interval_count = $('#interval_count_edit').val();
        var currency = $('#currency_edit option:selected').attr('id');
        var visible = ($('#visible_edit').is(':checked')) ? 1 : 0;
        var external_url = $('#external_url_edit').val();
        var expire_tours = $('#expire_tours_edit option:selected').attr('id');
        var custom_features = $('#custom_features_edit').val();
        var customize_menu_edit_t = $('#customize_menu_edit option');
        var customize_menu = {};
        $(customize_menu_edit_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    customize_menu[id]=1;
                } else {
                    customize_menu[id]=0;
                }
            }
        });
        var customize_menu_json = JSON.stringify(customize_menu);
        if(name=='') {
            complete = false;
            $('#name_edit').addClass("error-highlight");
        } else {
            $('#name_edit').removeClass("error-highlight");
        }
        var button_type = $('#button_type_edit option:selected').attr('id');
        var button_text = $('#button_text_edit').val();
        var button_icon = $('#button_icon_edit').val();
        var override_template = $('#template_override_edit').is(':checked') ? 1 : 0;
        var override_sample = $('#sample_override_edit').is(':checked') ? 1 : 0;
        var enable_sample = $('#enable_sample_edit').is(':checked') ? 1 : 0;
        var id_vt_template = $('#id_vt_template_edit option:selected').attr('id');
        var id_vt_sample_t = $('#id_vt_sample_edit option');
        var id_vt_sample = '';
        $(id_vt_sample_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    id_vt_sample += id+",";
                }
            }
        });
        let lastIndex = id_vt_sample.lastIndexOf(",");
        if (lastIndex !== -1) {
            id_vt_sample = id_vt_sample.slice(0, lastIndex) + id_vt_sample.slice(lastIndex + 1);
        }
        if(window.gsv_installed) {
            var enable_gsv_publish = ($('#features_edit option[id="enable_gsv_publish"]').is(':selected')) ? 1 : 0;
            var gsv_publish_mode = $('#gsv_publish_mode_edit option:selected').attr('id');
            var n_gsv_publish_month = $('#n_gsv_publish_month_edit').val();
        } else {
            var enable_gsv_publish = 0;
            var gsv_publish_mode = 'month';
            var n_gsv_publish_month = -1;
        }
        if(custom_domain_enabled) {
            var enable_custom_domain =  ($('#features_edit option[id="enable_custom_domain"]').is(':selected')) ? 1 : 0;
            var n_custom_domain = $('#n_custom_domain_edit').val();
        } else {
            var enable_custom_domain = 0;
            var n_custom_domain = -1;
        }
        var price_label = $('#price_label_edit').val();
        var description = $('#description_edit').val();
        var show_features = $('#show_features_edit').is(':checked') ? 1 : 0;
        var array_lang = {};
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['description'][lang]=value;
        });
        array_lang['price_label'] = {};
        $('.input_lang[data-target-id="price_label_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['price_label'][lang]=value;
        });
        array_lang['custom_features'] = {};
        $('.input_lang[data-target-id="custom_features_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom_features'][lang]=value;
        });
        array_lang['button_text'] = {};
        $('.input_lang[data-target-id="button_text_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['button_text'][lang]=value;
        });
        var array_lang_json = JSON.stringify(array_lang);
        if(complete) {
            $('#modal_edit_plan button').addClass("disabled");
            $.ajax({
                url: "ajax/save_plan.php",
                type: "POST",
                data: {
                    id: window.id_plan_sel,
                    name: name,
                    position: position,
                    n_virtual_tours: n_virtual_tours,
                    n_virtual_tours_month: n_virtual_tours_month,
                    n_rooms: n_rooms,
                    n_rooms_tour: n_rooms_tour,
                    n_markers: n_markers,
                    n_pois: n_pois,
                    n_gallery_images: n_gallery_images,
                    n_ai_generate_month: n_ai_generate_month,
                    n_autoenhance_generate_month: n_autoenhance_generate_month,
                    days: days,
                    price: price,
                    price2: price2,
                    currency: currency,
                    custom_features: custom_features,
                    create_landing: create_landing,
                    create_showcase: create_showcase,
                    create_globes: create_globes,
                    create_gallery: create_gallery,
                    enable_download_slideshow: enable_download_slideshow,
                    create_presentation: create_presentation,
                    create_video360: create_video360,
                    create_video_projects: create_video_projects,
                    enable_live_session: enable_live_session,
                    enable_meeting: enable_meeting,
                    max_file_size_upload: max_file_size_upload,
                    max_storace_space: max_storace_space,
                    enable_chat: enable_chat,
                    enable_voice_commands: enable_voice_commands,
                    enable_share: enable_share,
                    enable_snapshot: enable_snapshot,
                    enable_device_orientation: enable_device_orientation,
                    enable_webvr: enable_webvr,
                    enable_logo: enable_logo,
                    enable_poweredby: enable_poweredby,
                    enable_nadir_logo: enable_nadir_logo,
                    enable_song: enable_song,
                    enable_comments: enable_comments,
                    enable_forms: enable_forms,
                    enable_annotations: enable_annotations,
                    enable_avatar_video: enable_avatar_video,
                    enable_panorama_video: enable_panorama_video,
                    enable_ai_room: enable_ai_room,
                    enable_autoenhance_room: enable_autoenhance_room,
                    enable_rooms_multiple: enable_rooms_multiple,
                    enable_rooms_protect: enable_rooms_protect,
                    enable_info_box: enable_info_box,
                    enable_context_info: enable_context_info,
                    enable_maps: enable_maps,
                    enable_icons_library: enable_icons_library,
                    enable_media_library: enable_media_library,
                    enable_music_library: enable_music_library,
                    enable_sound_library: enable_sound_library,
                    enable_password_tour: enable_password_tour,
                    enable_expiring_dates: enable_expiring_dates,
                    enable_export_vt: enable_export_vt,
                    enable_import_export: enable_import_export,
                    enable_statistics: enable_statistics,
                    enable_multilanguage: enable_multilanguage,
                    enable_auto_translation: enable_auto_translation,
                    enable_auto_rotate: enable_auto_rotate,
                    enable_flyin: enable_flyin,
                    enable_multires: enable_multires,
                    enable_shop: enable_shop,
                    enable_learning: enable_learning,
                    enable_dollhouse: enable_dollhouse,
                    enable_editor_ui: enable_editor_ui,
                    enable_custom_html: enable_custom_html,
                    enable_metatag: enable_metatag,
                    enable_loading_iv: enable_loading_iv,
                    enable_intro_slider: enable_intro_slider,
                    enable_measurements: enable_measurements,
                    visible: visible,
                    external_url: external_url,
                    frequency: frequency,
                    interval_count: interval_count,
                    customize_menu: customize_menu_json,
                    expire_tours: expire_tours,
                    button_type: button_type,
                    button_text: button_text,
                    button_icon: button_icon,
                    override_template: override_template,
                    override_sample: override_sample,
                    id_vt_template: id_vt_template,
                    enable_sample: enable_sample,
                    id_vt_sample: id_vt_sample,
                    ai_generate_mode: ai_generate_mode,
                    autoenhance_generate_mode: autoenhance_generate_mode,
                    enable_gsv_publish: enable_gsv_publish,
                    gsv_publish_mode: gsv_publish_mode,
                    n_gsv_publish_month: n_gsv_publish_month,
                    enable_custom_domain: enable_custom_domain,
                    n_custom_domain: n_custom_domain,
                    price_label: price_label,
                    description: description,
                    show_features: show_features,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_edit_plan button').removeClass("disabled");
                        $('#modal_edit_plan').modal("hide");
                        window.plan_need_save = false;
                        window.plans_table.ajax.reload();
                        if(window.stripe_enabled) {
                            stripe_initialize(window.id_plan_sel,0);
                        }
                        if(window.paypal_enabled) {
                            paypal_initialize(window.id_plan_sel,0);
                        }
                        if(max_storace_space!=-1) {
                            $.ajax({
                                url: "../services/calculate_storage_space.php",
                                type: "POST",
                                async: true,
                                success: function (json) {}
                            });
                        }
                    } else {
                        $('#modal_edit_plan button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.save_service = function () {
        var complete = true;
        var array_lang = {};
        var name = $('#name_edit').val();
        var position = $('#position_edit').val();
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var description = window.description_edit_editor.root.innerHTML;
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description_edit"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.description_edit_editor_lang[lang].root.innerHTML;
            array_lang['description'][lang]=value;
        });
        var price = $('#price_edit').val();
        var credits = $('#credits_edit').val();
        var currency = $('#currency_edit option:selected').attr('id');
        var type = $('#type_edit option:selected').attr('id');
        var block_tour = ($('#block_tour_edit').is(':checked')) ? 1 : 0;
        var visible = ($('#visible_edit').is(':checked')) ? 1 : 0;
        if(name=='') {
            complete = false;
            $('#name_edit').addClass("error-highlight");
        } else {
            $('#name_edit').removeClass("error-highlight");
        }
        var array_lang_json = JSON.stringify(array_lang);
        if(complete) {
            $('#modal_edit_service button').addClass("disabled");
            $.ajax({
                url: "ajax/save_service.php",
                type: "POST",
                data: {
                    id: window.id_service_sel,
                    name: name,
                    position: position,
                    description: description,
                    price: price,
                    credits: credits,
                    currency: currency,
                    type: type,
                    block_tour: block_tour,
                    visible: visible,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_edit_service button').removeClass("disabled");
                        $('#modal_edit_service').modal("hide");
                        window.service_need_save = false;
                        window.services_table.ajax.reload();
                    } else {
                        $('#modal_edit_service button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.stripe_initialize = function (id_plan,save) {
        $('#modal_stripe_init').modal("show");
        var postData = new FormData();
        postData.append('id_plan', id_plan);
        postData.append('save', save);
        if(save==1) {
            var stripe_public_key = $('#stripe_public_key').val();
            var stripe_secret_key = $('#stripe_secret_key').val();
            var stripe_automatic_tax_rate = $('#stripe_automatic_tax_rate option:selected').attr('id');
            postData.append('stripe_secret_key', stripe_secret_key);
            postData.append('stripe_public_key', stripe_public_key);
            postData.append('stripe_automatic_tax_rate', stripe_automatic_tax_rate);
        }
        fetch('../payments/stripe_init.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(rsp) {
            $('#modal_stripe_init').modal("hide");
            if(rsp.status=="ok") {
                $('#stripe_enabled').prop("disabled",false);
                $('#stripe_enabled').prop("checked",true);
                $('#paypal_enabled').prop("disabled",true);
                $('#paypal_enabled').prop("checked",false);
                $('#btn_check_stripe').removeClass("btn-primary");
                $('#btn_check_stripe').addClass("btn-success");
                setTimeout(function () {
                    $('#btn_check_stripe').addClass("btn-primary");
                    $('#btn_check_stripe').removeClass("btn-success");
                },1000);
            } else {
                alert(rsp.msg);
                $('#stripe_enabled').prop("disabled",true);
                $('#stripe_enabled').prop("checked",false);
                $('#btn_check_stripe').removeClass("btn-primary");
                $('#btn_check_stripe').addClass("btn-danger");
                setTimeout(function () {
                    $('#btn_check_stripe').addClass("btn-primary");
                    $('#btn_check_stripe').removeClass("btn-danger");
                },1000);
            }
        }).catch(function(error) {
            $('#modal_stripe_init').modal("hide");
            $('#btn_check_stripe').addClass("btn-danger");
            $('#btn_check_stripe').removeClass("btn-primary");
            setTimeout(function () {
                $('#btn_check_stripe').addClass("btn-primary");
                $('#btn_check_stripe').removeClass("btn-danger");
            },1000);
        });
    }

    window.paypal_initialize = function (id_plan,save) {
        $('#modal_stripe_init').modal("show");
        var postData = new FormData();
        postData.append('id_plan', id_plan);
        postData.append('save', save);
        if(save==1) {
            var paypal_live = ($('#paypal_live').is(':checked')) ? 1 : 0;
            var paypal_client_id = $('#paypal_client_id').val();
            var paypal_client_secret = $('#paypal_client_secret').val();
            postData.append('paypal_live', paypal_live);
            postData.append('paypal_client_id', paypal_client_id);
            postData.append('paypal_client_secret', paypal_client_secret);
        }
        fetch('../payments/paypal_init.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(rsp) {
            $('#modal_stripe_init').modal("hide");
            if(rsp.status=="ok") {
                $('#paypal_enabled').prop("disabled",false);
                $('#paypal_enabled').prop("checked",true);
                $('#stripe_enabled').prop("disabled",true);
                $('#stripe_enabled').prop("checked",false);
                $('#btn_check_paypal').removeClass("btn-primary");
                $('#btn_check_paypal').addClass("btn-success");
                setTimeout(function () {
                    $('#btn_check_paypal').addClass("btn-primary");
                    $('#btn_check_paypal').removeClass("btn-success");
                },1000);
            } else {
                alert(rsp.msg);
                $('#paypal_enabled').prop("disabled",true);
                $('#paypal_enabled').prop("checked",false);
                $('#btn_check_paypal').removeClass("btn-primary");
                $('#btn_check_paypal').addClass("btn-danger");
                setTimeout(function () {
                    $('#btn_check_paypal').addClass("btn-primary");
                    $('#btn_check_paypal').removeClass("btn-danger");
                },1000);
            }
        }).catch(function(error) {
            $('#modal_stripe_init').modal("hide");
            $('#btn_check_paypal').removeClass("btn-primary");
            $('#btn_check_paypal').addClass("btn-danger");
            setTimeout(function () {
                $('#btn_check_paypal').addClass("btn-primary");
                $('#btn_check_paypal').removeClass("btn-danger");
            },1000);
        });
    }

    window.aws_s3_initialize = function () {
        $('#modal_aws_s3_init').modal("show");
        var postData = new FormData();
        var aws_s3_type = $('#aws_s3_type option:selected').attr('id');
        var aws_s3_vt_auto = $('#aws_s3_vt_auto').val();
        var aws_s3_bucket = $('#aws_s3_bucket').val();
        switch(aws_s3_type) {
            case 'digitalocean':
                var aws_s3_region = $('#aws_s3_region_digitalocean option:selected').attr('id');
                break;
            case 'backblaze':
                var aws_s3_region = $('#aws_s3_region_backblaze option:selected').attr('id');
                break;
            default:
                var aws_s3_region = $('#aws_s3_region option:selected').attr('id');
                break;
        }
        var aws_s3_key = $('#aws_s3_key').val();
        var aws_s3_secret = $('#aws_s3_secret').val();
        var aws_s3_accountid = $('#aws_s3_accountid').val();
        var aws_s3_custom_domain = $('#aws_s3_custom_domain').val();
        postData.append('aws_s3_type', aws_s3_type);
        postData.append('aws_s3_vt_auto', aws_s3_vt_auto);
        postData.append('aws_s3_bucket', aws_s3_bucket);
        postData.append('aws_s3_region', aws_s3_region);
        postData.append('aws_s3_key', aws_s3_key);
        postData.append('aws_s3_secret', aws_s3_secret);
        postData.append('aws_s3_accountid', aws_s3_accountid);
        postData.append('aws_s3_custom_domain', aws_s3_custom_domain);
        fetch('../services/aws_s3_init.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(rsp) {
            $('#modal_aws_s3_init').modal("hide");
            if(rsp.status=="ok") {
                $('#aws_s3_enabled').prop("disabled",false);
                $('#aws_s3_enabled').prop("checked",true);
                $('#btn_check_aws').removeClass("btn-primary");
                $('#btn_check_aws').addClass("btn-success");
                setTimeout(function () {
                    $('#btn_check_aws').removeClass("btn-success");
                    $('#btn_check_aws').addClass("btn-primary");
                },1000);
            } else {
                alert(rsp.msg);
                $('#aws_s3_enabled').prop("disabled",true);
                $('#aws_s3_enabled').prop("checked",false);
                $('#btn_check_aws').removeClass("btn-primary");
                $('#btn_check_aws').addClass("btn-danger");
                setTimeout(function () {
                    $('#btn_check_aws').removeClass("btn-danger");
                    $('#btn_check_aws').addClass("btn-primary");
                },1000);
            }
        }).catch(function(error) {
            $('#modal_aws_s3_init').modal("hide");
            $('#btn_check_aws').removeClass("btn-primary");
            $('#btn_check_aws').addClass("btn-danger");
            setTimeout(function () {
                $('#btn_check_aws').removeClass("btn-danger");
                $('#btn_check_aws').addClass("btn-primary");
            },1000);
        });
    }

    window.save_virtualtour = function(reload) {
        var complete = true;
        var array_lang = {};
        var array_versions = {};
        var name = $('#name').val();
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var author = $('#author').val();
        var id_user = $('#user option:selected').attr('id');
        var id_categories = [];
        $("#category option:selected").each(function () {
            id_categories.push(parseInt($(this).attr('id')));
        });
        var hfov = parseInt($('#hfov').val());
        var min_hfov = parseInt($('#min_hfov').val());
        var max_hfov = parseInt($('#max_hfov').val());
        var hfov_mobile_ratio = parseFloat($('#hfov_mobile_ratio').val());
        var pan_speed = parseFloat($('#pan_speed').val());
        var pan_speed_mobile = parseFloat($('#pan_speed_mobile').val());
        var friction = parseFloat($('#friction').val());
        var friction_mobile = parseFloat($('#friction_mobile').val());
        var zoom_friction = parseFloat($('#zoom_friction').val());
        var zoom_friction_mobile = parseFloat($('#zoom_friction_mobile').val());
        var mouse_follow_feedback = parseFloat($('#mouse_follow_feedback').val());
        var zoom_to_pointer = ($('#zoom_to_pointer').is(':checked')) ? 1 : 0;
        var mouse_zoom = $('#mouse_zoom option:selected').attr('id');
        var quality_viewer = parseFloat($('#quality_viewer').val());
        var flyin = $('#flyin option:selected').attr('id');
        var flyin_duration = parseInt($('#flyin_duration').val());
        var auto_start = $('#auto_start option:selected').attr('id');
        var hide_loading = ($('#hide_loading').is(':checked')) ? 0 : 1;
        var show_background = ($('#show_background').is(':checked')) ? 1 : 0;
        var background_video_delay = $('#background_video_delay').val();
        var background_video_delay_mobile = $('#background_video_delay_m').val();
        var background_video_skip = ($('#background_video_skip').is(':checked')) ? 1 : 0;
        var background_video_skip_mobile = ($('#background_video_skip_mobile').is(':checked')) ? 1 : 0;
        var sameAzimuth = ($('#sameAzimuth').is(':checked')) ? 1 : 0;
        var description = $('#description').val();
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['description'][lang]=value;
        });
        var external_url = $('#external_url').val();
        var ga_tracking_id = $('#ga_tracking_id').val();
        var compress_jpg = $('#compress_jpg').val();
        var max_width_compress = $('#max_width_compress').val();
        var link_logo = $('#link_logo').val();
        var enable_multires = ($('#enable_multires').is(':checked')) ? 1 : 0;
        var preload_panoramas = ($('#preload_panoramas').is(':checked')) ? 1 : 0;
        var mobile_panoramas = ($('#mobile_panoramas').is(':checked')) ? 1 : 0;
        var keep_original_panorama = ($('#keep_original_panorama').is(':checked')) ? 1 : 0;
        var transition_time = $('#transition_time').val();
        var transition_fadeout = $('#transition_fadeout').val();
        var transition_zoom = $('#transition_zoom').val();
        var transition_loading = ($('#transition_loading').is(':checked')) ? 1 : 0;
        var transition_effect = $('#transition_effect option:selected').attr('id');
        var transition_hfov = $('#transition_hfov').val();
        var transition_hfov_time = $('#transition_hfov_time').val();
        var markers_default_lookat = $('#markers_default_lookat option:selected').attr('id');
        var markers_default_backlink = ($('#markers_default_backlink').is(':checked')) ? 1 : 0;
        var click_anywhere = ($('#click_anywhere').is(':checked')) ? 1 : 0;
        var hide_markers = ($('#hide_markers').is(':checked')) ? 1 : 0;
        if(click_anywhere==0) hide_markers=0;
        var hover_markers = ($('#hover_markers').is(':checked')) ? 1 : 0;
        if(hide_markers==0) hover_markers=0;
        var keyboard_mode = $('#keyboard_mode option:selected').attr('id');
        var note = $('#note').val();
        var shop_type = $('#shop_type option:selected').attr('id');
        var woocommerce_store_url = $('#woocommerce_store_url').val();
        var woocommerce_store_cart = $('#woocommerce_store_cart').val();
        var woocommerce_store_checkout = $('#woocommerce_store_checkout').val();
        var woocommerce_show_stock_quantity = ($('#woocommerce_show_stock_quantity').is(':checked')) ? 1 : 0;
        var woocommerce_modal = ($('#woocommerce_modal').is(':checked')) ? 1 : 0;
        var woocommerce_customer_key = $('#woocommerce_customer_key').val();
        var woocommerce_customer_secret = $('#woocommerce_customer_secret').val();
        var snipcart_api_key = $('#snipcart_api_key').val();
        var snipcart_currency = $('#snipcart_currency option:selected').attr('id');
        var ar_camera_align = ($('#ar_camera_align').is(':checked')) ? 1 : 0;
        var custom_html = window.custom_vt_html.getValue();
        var context_info = window.context_info_editor.root.innerHTML;
        var intro_desktop_hide = $('#intro_desktop_hide').val();
        var intro_mobile_hide = $('#intro_mobile_hide').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(window.external==1) {
            if(external_url=='') {
                complete = false;
                $('#external_url').addClass("error-highlight");
            } else {
                $('#external_url').removeClass("error-highlight");
            }
        }
        var initial_feedback = $('#initial_feedback').val();
        var loading_background_color = $('#loading_background_color').val();
        var loading_text_color = $('#loading_text_color').val();
        var language = $('#language option:selected').attr('id');
        var languages_enabled_t = $('#languages_enabled option');
        var languages_enabled = {};
        var count_lang_enabled = 1;
        $(languages_enabled_t).each(function(index, elem){
            var id = $(this).attr('id').replace('ls_','');
            if($(this).is(':selected')) {
                languages_enabled[id]=1;
                if(id!=window.default_language) {
                    count_lang_enabled++;
                }
            } else {
                languages_enabled[id]=0;
            }
        });
        var languages_enabled_json = JSON.stringify(languages_enabled);
        var poweredby_type = $('#poweredby_type option:selected').attr('id');
        var poweredby_text = $('#poweredby_text').val();
        switch(poweredby_type) {
            case 'image':
                var poweredby_link = $('#poweredby_link_image').val();
                break;
            case 'text':
                var poweredby_link = $('#poweredby_link_text').val();
                break;
        }
        var song_bg_volume = $('#song_bg_volume').val();
        var cookie_consent = ($('#cookie_consent').is(':checked')) ? 1 : 0;
        var add_room_sort = $('#add_room_sort option:selected').attr('id');
        var intro_slider_delay = $('#intro_slider_delay').val();
        var avatar_video = $('#avatar_video_content').val();
        var avatar_video_autoplay = $('#avatar_video_autoplay').is(':checked') ? 1 : 0;
        var avatar_video_pause = $('#avatar_video_pause').is(':checked') ? 1 : 0;
        var avatar_video_hide_end = $('#avatar_video_hide_end').is(':checked') ? 1 : 0;
        array_lang['avatar_video'] = {};
        $('.input_lang[data-target-id="avatar_video_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['avatar_video'][lang]=value;
        });
        array_lang['intro_desktop'] = {};
        $.each(window.introd_file_langs,function(lang,value) {
            array_lang['intro_desktop'][lang]=value;
        });
        array_lang['intro_mobile'] = {};
        $.each(window.introm_file_langs,function(lang,value) {
            array_lang['intro_mobile'][lang]=value;
        });
        $('.loading_settings_v').each(function() {
            var id_version = $(this).attr('data-id-version');
            array_versions[id_version] = {};
            array_versions[id_version]['auto_start']=$('#auto_start_v'+id_version+' option:selected').attr('id');
            array_versions[id_version]['hide_loading']=($('#hide_loading_v'+id_version).is(':checked')) ? 0 : 1;
            array_versions[id_version]['show_background']=($('#show_background_v'+id_version).is(':checked')) ? 1 : 0;
            array_versions[id_version]['flyin']=$('#flyin_v'+id_version+' option:selected').attr('id');
            array_versions[id_version]['flyin_duration']=$('#flyin_duration_v'+id_version).val();
            array_versions[id_version]['loading_background_color']=$('#loading_background_color_v'+id_version).val();
            array_versions[id_version]['loading_text_color']=$('#loading_text_color_v'+id_version).val();
        });
        var leave_poi_open = $('#leave_poi_open').is(':checked') ? 1 : 0;
        var close_poi_click_outside = $('#close_poi_click_outside').is(':checked') ? 1 : 0;
        var pwa_enable = $('#pwa_enable').is(':checked') ? 1 : 0;
        var vr_icons_size = {};
        $('.vr_icon_size_select').each(function() {
            var icon_type = $(this).attr('data-type');
            vr_icons_size[icon_type] = $(this).find('option:selected').attr('id');
        });
        var nadir_round = $('#nadir_round').is(':checked') ? 1 : 0;
        var learning_mode = $('#learning_mode').is(':checked') ? 1 : 0;
        var learning_unlock_marker = $('#learning_unlock_marker').is(':checked') ? 1 : 0;
        var learning_poi_progressive = $('#learning_poi_progressive').is(':checked') ? 1 : 0;
        var learning_show_modal = $('#learning_show_modal').is(':checked') ? 1 : 0;
        var learning_modal_icon = $('#learning_modal_icon').val();
        var learning_modal_title = $('#learning_modal_title').val();
        var learning_modal_subtitle = $('#learning_modal_subtitle').val();
        var learning_modal_description = window.learning_modal_description_editor.root.innerHTML;
        var learning_show_email = $('#learning_show_email').is(':checked') ? 1 : 0;
        var learning_mandatory_email = $('#learning_mandatory_email').is(':checked') ? 1 : 0;
        var learning_restore_session = $('#learning_restore_session').is(':checked') ? 1 : 0;
        var learning_modal_color = $('#learning_modal_color').val();
        var learning_modal_background = $('#learning_modal_background').val();
        var learning_modal_color_text = $('#learning_modal_color_text').val();
        var learning_modal_button_background = $('#learning_modal_button_background').val();
        var learning_modal_button_color = $('#learning_modal_button_color').val();
        var learning_summary_style = $('#learning_summary_style option:selected').attr('id');
        var learning_summary_title = $('#learning_summary_title').val();
        var learning_summary_background = $('#learning_summary_background').val();
        var learning_summary_color = $('#learning_summary_color').val();
        var learning_summary_partial_title = $('#learning_summary_partial_title').val();
        var learning_summary_partial_color = $('#learning_summary_partial_color').val();
        var learning_summary_global_title = $('#learning_summary_global_title').val();
        var learning_summary_global_color = $('#learning_summary_global_color').val();
        var learning_check_icon = $('#learning_check_icon').val();
        var learning_check_background = $('#learning_check_background').val();
        var learning_check_color = $('#learning_check_color').val();
        var learning_modal_button = $('#learning_modal_button').val();
        var learning_placeholder_email = $('#learning_placeholder_email').val();
        array_lang['learning_modal_title'] = {};
        $('.input_lang[data-target-id="learning_modal_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_modal_title'][lang]=value;
        });
        array_lang['learning_modal_subtitle'] = {};
        $('.input_lang[data-target-id="learning_modal_subtitle"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_modal_subtitle'][lang]=value;
        });
        array_lang['learning_modal_description'] = {};
        $('.input_lang[data-target-id="learning_modal_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.learning_modal_description_editor_lang[lang].root.innerHTML;
            array_lang['learning_modal_description'][lang]=value;
        });
        array_lang['learning_modal_button'] = {};
        $('.input_lang[data-target-id="learning_modal_button"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_modal_button'][lang]=value;
        });
        array_lang['learning_summary_title'] = {};
        $('.input_lang[data-target-id="learning_summary_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_summary_title'][lang]=value;
        });
        array_lang['learning_summary_partial_title'] = {};
        $('.input_lang[data-target-id="learning_summary_partial_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_summary_partial_title'][lang]=value;
        });
        array_lang['learning_summary_global_title'] = {};
        $('.input_lang[data-target-id="learning_summary_global_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_summary_global_title'][lang]=value;
        });
        array_lang['learning_placeholder_email'] = {};
        $('.input_lang[data-target-id="learning_placeholder_email"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['learning_placeholder_email'][lang]=value;
        });
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            var array_lang_json = JSON.stringify(array_lang);
            var array_versions_json = JSON.stringify(array_versions);
            var vr_icons_size_json = JSON.stringify(vr_icons_size);
            $.ajax({
                url: "ajax/save_virtual_tour.php",
                type: "POST",
                data: {
                    id_virtualtour: id_virtualtour,
                    name: name,
                    id_user: id_user,
                    author: author,
                    hfov: hfov,
                    min_hfov: min_hfov,
                    max_hfov: max_hfov,
                    hfov_mobile_ratio: hfov_mobile_ratio,
                    pan_speed: pan_speed,
                    pan_speed_mobile: pan_speed_mobile,
                    friction: friction,
                    friction_mobile: friction_mobile,
                    zoom_friction: zoom_friction,
                    zoom_friction_mobile: zoom_friction_mobile,
                    mouse_follow_feedback: mouse_follow_feedback,
                    zoom_to_pointer: zoom_to_pointer,
                    mouse_zoom: mouse_zoom,
                    quality_viewer: quality_viewer,
                    song: window.song,
                    flyin: flyin,
                    flyin_duration: flyin_duration,
                    background_image: window.background_image,
                    background_video: window.background_video,
                    background_image_mobile: window.background_image_mobile,
                    background_video_mobile: window.background_video_mobile,
                    background_video_delay: background_video_delay,
                    background_video_delay_mobile: background_video_delay_mobile,
                    background_video_skip: background_video_skip,
                    background_video_skip_mobile: background_video_skip_mobile,
                    logo: window.logo,
                    link_logo: link_logo,
                    nadir_logo: window.nadir_logo,
                    intro_mobile: window.intro_mobile,
                    intro_desktop: window.intro_desktop,
                    intro_desktop_hide: intro_desktop_hide,
                    intro_mobile_hide: intro_mobile_hide,
                    auto_start: auto_start,
                    hide_loading: hide_loading,
                    show_background: show_background,
                    sameAzimuth: sameAzimuth,
                    description: description,
                    external_url: external_url,
                    ga_tracking_id: ga_tracking_id,
                    compress_jpg: compress_jpg,
                    max_width_compress: max_width_compress,
                    enable_multires: enable_multires,
                    preload_panoramas: preload_panoramas,
                    mobile_panoramas: mobile_panoramas,
                    keep_original_panorama: keep_original_panorama,
                    transition_time: transition_time,
                    transition_fadeout: transition_fadeout,
                    transition_zoom: transition_zoom,
                    transition_loading: transition_loading,
                    transition_effect: transition_effect,
                    transition_hfov: transition_hfov,
                    transition_hfov_time: transition_hfov_time,
                    click_anywhere: click_anywhere,
                    hide_markers: hide_markers,
                    hover_markers: hover_markers,
                    note: note,
                    language: language,
                    languages_enabled: languages_enabled_json,
                    id_categories: id_categories,
                    keyboard_mode: keyboard_mode,
                    shop_type: shop_type,
                    woocommerce_store_url: woocommerce_store_url,
                    woocommerce_store_cart: woocommerce_store_cart,
                    woocommerce_store_checkout: woocommerce_store_checkout,
                    woocommerce_show_stock_quantity: woocommerce_show_stock_quantity,
                    woocommerce_modal: woocommerce_modal,
                    woocommerce_customer_key: woocommerce_customer_key,
                    woocommerce_customer_secret: woocommerce_customer_secret,
                    snipcart_api_key: snipcart_api_key,
                    snipcart_currency: snipcart_currency,
                    markers_default_lookat: markers_default_lookat,
                    markers_default_backlink: markers_default_backlink,
                    custom_html: custom_html,
                    context_info: context_info,
                    ar_camera_align: ar_camera_align,
                    initial_feedback: initial_feedback,
                    loading_background_color: loading_background_color,
                    loading_text_color: loading_text_color,
                    array_lang: array_lang_json,
                    poweredby_type: poweredby_type,
                    poweredby_image: window.poweredby_image,
                    poweredby_text: poweredby_text,
                    poweredby_link: poweredby_link,
                    song_bg_volume: song_bg_volume,
                    cookie_consent: cookie_consent,
                    avatar_video: avatar_video,
                    add_room_sort: add_room_sort,
                    avatar_video_autoplay: avatar_video_autoplay,
                    avatar_video_pause: avatar_video_pause,
                    avatar_video_hide_end: avatar_video_hide_end,
                    intro_slider_delay: intro_slider_delay,
                    array_versions: array_versions_json,
                    leave_poi_open: leave_poi_open,
                    close_poi_click_outside: close_poi_click_outside,
                    pwa_enable: pwa_enable,
                    vr_icons_size: vr_icons_size_json,
                    nadir_round: nadir_round,
                    learning_mode: learning_mode,
                    learning_unlock_marker: learning_unlock_marker,
                    learning_poi_progressive: learning_poi_progressive,
                    learning_show_modal: learning_show_modal,
                    learning_modal_icon: learning_modal_icon,
                    learning_modal_title: learning_modal_title,
                    learning_modal_subtitle: learning_modal_subtitle,
                    learning_modal_description: learning_modal_description,
                    learning_show_email: learning_show_email,
                    learning_mandatory_email: learning_mandatory_email,
                    learning_restore_session: learning_restore_session,
                    learning_modal_color: learning_modal_color,
                    learning_modal_background: learning_modal_background,
                    learning_modal_color_text: learning_modal_color_text,
                    learning_modal_button_background: learning_modal_button_background,
                    learning_modal_button_color: learning_modal_button_color,
                    learning_summary_style: learning_summary_style,
                    learning_summary_title: learning_summary_title,
                    learning_summary_background: learning_summary_background,
                    learning_summary_color: learning_summary_color,
                    learning_summary_partial_title: learning_summary_partial_title,
                    learning_summary_partial_color: learning_summary_partial_color,
                    learning_summary_global_title: learning_summary_global_title,
                    learning_summary_global_color: learning_summary_global_color,
                    learning_check_icon: learning_check_icon,
                    learning_check_background: learning_check_background,
                    learning_check_color: learning_check_color,
                    learning_modal_button: learning_modal_button,
                    learning_placeholder_email: learning_placeholder_email
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        if(rsp.favicon!=1) {
                            generate_favicons(rsp.favicon);
                        }
                        window.vt_need_save = false;
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        if(reload) location.reload();
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    } else {
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_form = function() {
        var content = [{},{},{},{},{},{},{},{},{},{},{}];
        content[0]['title'] = $('#form_title').val();
        content[0]['button'] = $('#form_button').val();
        content[0]['response'] = $('#form_response').val();
        content[0]['description'] = $('#form_description').val();
        content[0]['privacy_policy'] = $('#form_privacy_policy').is(':checked');
        content[0]['send_email'] = $('#form_send_email').is(':checked');
        content[0]['email'] = $('#form_email').val();
        content[0]['webhook_url'] = $('#form_webhook_url').val();
        content[0]['background'] = $('#form_background_m').val();
        content[0]['color'] = $('#form_color_m').val();
        content[0]['background_button'] = $('#form_background_button').val();
        content[0]['color_button'] = $('#form_color_button').val();
        for(var i=1;i<=10;i++) {
            content[i]['enabled'] = $('#form_field_'+i).is(':checked');
            content[i]['required'] = $('#form_field_required_'+i).is(':checked');
            content[i]['type'] = $('#form_field_type_'+i+' option:selected').attr('id');
            content[i]['label'] = $('#form_field_label_'+i).val();
        }
        var form_content = JSON.stringify(content);
        var array_lang = {};
        array_lang['form_content'] = {};
        $('.input_lang[data-target-id="form_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var content_lang = [{},{},{},{},{},{},{},{},{},{},{}];
            if($('.input_lang[data-target-id="form_title"][data-lang="'+lang+'"]').val()!='') {
                content_lang[0]['title'] = $('.input_lang[data-target-id="form_title"][data-lang="'+lang+'"]').val();
            } else {
                content_lang[0]['title'] = $('#form_title').val();
            }
            if($('.input_lang[data-target-id="form_button"][data-lang="'+lang+'"]').val()!='') {
                content_lang[0]['button'] = $('.input_lang[data-target-id="form_button"][data-lang="'+lang+'"]').val();
            } else {
                content_lang[0]['button'] = $('#form_button').val();
            }
            if($('.input_lang[data-target-id="form_response"][data-lang="'+lang+'"]').val()!='') {
                content_lang[0]['response'] = $('.input_lang[data-target-id="form_response"][data-lang="'+lang+'"]').val();
            } else {
                content_lang[0]['response'] = $('#form_response').val();
            }
            if($('.input_lang[data-target-id="form_description"][data-lang="'+lang+'"]').val()!='') {
                content_lang[0]['description'] = $('.input_lang[data-target-id="form_description"][data-lang="'+lang+'"]').val();
            } else {
                content_lang[0]['description'] = $('#form_description').val();
            }
            content_lang[0]['privacy_policy'] = $('#form_privacy_policy').is(':checked');
            content_lang[0]['send_email'] = $('#form_send_email').is(':checked');
            content_lang[0]['email'] = $('#form_email').val();
            content_lang[0]['webhook_url'] = $('#form_webhook_url').val();
            content_lang[0]['background'] = $('#form_background_m').val();
            content_lang[0]['color'] = $('#form_color_m').val();
            content_lang[0]['background_button'] = $('#form_background_button').val();
            content_lang[0]['color_button'] = $('#form_color_button').val();
            for(var i=1;i<=10;i++) {
                content_lang[i]['enabled'] = $('#form_field_'+i).is(':checked');
                content_lang[i]['required'] = $('#form_field_required_'+i).is(':checked');
                content_lang[i]['type'] = $('#form_field_type_'+i+' option:selected').attr('id');
                if($('.input_lang[data-target-id="form_field_label_'+i+'"][data-lang="'+lang+'"]').val()!='') {
                    content_lang[i]['label'] = $('.input_lang[data-target-id="form_field_label_'+i+'"][data-lang="'+lang+'"]').val();
                } else {
                    content_lang[i]['label'] = $('#form_field_label_'+i).val();
                }
            }
            array_lang['form_content'][lang]=JSON.stringify(content_lang);
        });
        $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
        $('#save_btn').addClass("disabled");
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_form.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                form_content: form_content,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    window.form_need_save = false;
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                } else {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            },
            error: function() {
                $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                setTimeout(function () {
                    $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                    $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    $('#save_btn').removeClass("disabled");
                },1000);
            }
        });
    }

    window.save_features = function () {
        var array_features = [];
        $('.feature_content').each(function() {
            var feature = $(this).attr('data-feature');
            var content = window.feature_content_editor[feature].root.innerHTML;
            var name = $('#'+feature+'_name').val();
            array_features.push({'feature':feature,'name':name,'content':content});
        })
        $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
        $('#save_btn').addClass("disabled");
        var array_features_lang = [];
        $('.feature_content_lang').each(function() {
            var feature = $(this).attr('data-feature');
            var lang = $(this).attr('data-lang');
            var content = window.feature_content_editor_lang[feature][lang].root.innerHTML;
            var name = $('#'+feature+'_name_'+lang).val();
            array_features_lang.push({'lang':lang,'feature':feature,'name':name,'content':content});
        })
        var array_features_json = JSON.stringify(array_features);
        var array_features_lang_json = JSON.stringify(array_features_lang);
        $.ajax({
            url: "ajax/save_features.php",
            type: "POST",
            data: {
                array_features: array_features_json,
                array_features_lang: array_features_lang_json
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    window.features_need_save = false;
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                        $('#save_btn').removeClass("disabled");
                    }, 1000);
                } else {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    }, 1000);
                }
            },
            error: function() {
                $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                setTimeout(function () {
                    $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                    $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                    $('#save_btn').removeClass("disabled");
                }, 1000);
            }
        });
    }

    window.save_settings = function (validate_mail,reload=false) {
        var complete = true;
        var purchase_code = $('#purchase_code').val();
        var purchase_code_gsv = $('#purchase_code_gsv').val();
        var name = $('#name').val();
        var theme_color = $('#theme_color').val();
        var sidebar = $('#sidebar option:selected').attr('id');
        var font_provider = $('#font_provider option:selected').attr('id');
        var sidebar_color_1 = $('#sidebar_color_1').val();
        var sidebar_color_2 = $('#sidebar_color_2').val();
        var theme_color_dark = $('#theme_color_dark').val();
        var dark_mode = parseInt($('#dark_mode option:selected').attr('id'));
        var sidebar_color_1_dark = $('#sidebar_color_1_dark').val();
        var sidebar_color_2_dark = $('#sidebar_color_2_dark').val();
        if(font_provider=='systems') {
            var font_backend = $('#font_backend_system option:selected').attr('id');
        } else {
            var font_backend = $('#font_backend').val();
        }
        var welcome_msg = window.welcome_msg_editor.root.innerHTML;
        var welcome_title = $('#welcome_title').val();
        var welcome_icon = $('#welcome_icon').val();
        var welcome_enable = ($('#welcome_enable').is(':checked')) ? 1 : 0;
        var terms_and_conditions = window.terms_and_conditions_editor.root.innerHTML;
        var privacy_policy = window.privacy_policy_editor.root.innerHTML;
        var cookie_policy = window.cookie_policy_editor.root.innerHTML;
        var cookie_consent = ($('#cookie_consent').is(':checked')) ? 1 : 0;
        var style_login = parseInt($('#style_login option:selected').attr('id'));
        var style_register = parseInt($('#style_register option:selected').attr('id'));
        var language = $('#language option:selected').attr('id');
        var language_domain = $('#language_domain option:selected').attr('id');
        var languages_enabled_t = $('#languages_enabled option');
        var languages_enabled = {};
        $(languages_enabled_t).each(function(index, elem){
            var id = $(this).attr('id').replace('ls_','');
            if($(this).is(':selected')) {
                languages_enabled[id]=1;
            } else {
                languages_enabled[id]=0;
            }
        });
        var languages_enabled_json = JSON.stringify(languages_enabled);
        var languages_viewer_enabled_t = $('#languages_viewer_enabled option');
        var languages_viewer_enabled = {};
        $(languages_viewer_enabled_t).each(function(index, elem){
            var id = $(this).attr('id').replace('lv_','');
            if($(this).is(':selected')) {
                languages_viewer_enabled[id]=1;
            } else {
                languages_viewer_enabled[id]=0;
            }
        });
        var languages_viewer_enabled_json = JSON.stringify(languages_viewer_enabled);
        var furl_blacklist = $('#furl_blacklist').val();
        var contact_mail = $('#contact_mail').val();
        var help_url = $('#help_url').val();
        var website_url = $('#website_url').val();
        var website_name = $('#website_name').val();
        var enable_external_vt = ($('#enable_external_vt').is(':checked')) ? 1 : 0;
        var enable_ar_vt = ($('#enable_ar_vt').is(':checked')) ? 1 : 0;
        var enable_ai_room = ($('#enable_ai_room').is(':checked')) ? 1 : 0;
        var ai_key = $('#ai_key').val();
        var enable_autoenhance_room = ($('#enable_autoenhance_room').is(':checked')) ? 1 : 0;
        var autoenhance_key = $('#autoenhance_key').val();
        var enable_deepl = ($('#enable_deepl').is(':checked')) ? 1 : 0;
        var deepl_api_key = $('#deepl_api_key').val();
        var enable_wizard = ($('#enable_wizard').is(':checked')) ? 1 : 0;
        var popup_add_room_vt = ($('#popup_add_room_vt').is(':checked')) ? 1 : 0;
        var enable_sample = ($('#enable_sample').is(':checked')) ? 1 : 0;
        var id_vt_template = $('#id_vt_template option:selected').attr('id');
        var smtp_server = $('#smtp_server').val();
        var smtp_port = $('#smtp_port').val();
        var smtp_auth = ($('#smtp_auth').is(':checked')) ? 1 : 0;
        var smtp_secure = $('#smtp_secure option:selected').attr('id');
        var smtp_username = $('#smtp_username').val();
        var smtp_password = $('#smtp_password').val();
        var smtp_from_email = $('#smtp_from_email').val();
        var smtp_from_name = $('#smtp_from_name').val();
        var captcha_login = ($('#captcha_login').is(':checked')) ? 1 : 0;
        var captcha_register = ($('#captcha_register').is(':checked')) ? 1 : 0;
        var twofa_enable = ($('#2fa_enable').is(':checked')) ? 1 : 0;
        var css_array = {};
        $(".editors_css").each(function() {
            var id = $(this).attr('id');
            css_array[id]=window.editors_css[id].getValue();
        });
        var js_array = {};
        $(".editors_js").each(function() {
            var id = $(this).attr('id');
            js_array[id.replace("_js","")]=window.editors_js[id].getValue();
        });
        var head_array = {};
        $(".editors_head").each(function() {
            var id = $(this).attr('id');
            head_array[id.replace("_head","")]=window.editors_head[id].getValue();
        });
        var head_php_array = {};
        $(".editors_head_php").each(function() {
            var id = $(this).attr('id');
            head_php_array[id.replace("_head_php","")]=window.editors_head_php[id].getValue();
        });
        var css_array_json = JSON.stringify(css_array);
        var js_array_json = JSON.stringify(js_array);
        var head_array_json = JSON.stringify(head_array);
        var head_php_array_json = JSON.stringify(head_php_array);
        var custom_html = window.custom_b_html.getValue();
        var social_google_enable = ($('#social_google_enable').is(':checked')) ? 1 : 0;
        var social_facebook_enable = ($('#social_facebook_enable').is(':checked')) ? 1 : 0;
        var social_twitter_enable = ($('#social_twitter_enable').is(':checked')) ? 1 : 0;
        var social_wechat_enable = ($('#social_wechat_enable').is(':checked')) ? 1 : 0;
        var social_qq_enable = ($('#social_qq_enable').is(':checked')) ? 1 : 0;
        var social_google_id = $('#social_google_id').val();
        var social_google_secret = $('#social_google_secret').val();
        var social_facebook_id = $('#social_facebook_id').val();
        var social_facebook_secret = $('#social_facebook_secret').val();
        var social_twitter_id = $('#social_twitter_id').val();
        var social_twitter_secret = $('#social_twitter_secret').val();
        var social_wechat_id = $('#social_wechat_id').val();
        var social_wechat_secret = $('#social_wechat_secret').val();
        var social_qq_id = $('#social_qq_id').val();
        var social_qq_secret = $('#social_qq_secret').val();
        var enable_registration = ($('#enable_registration').is(':checked')) ? 1 : 0;
        var change_plan = ($('#change_plan').is(':checked')) ? 1 : 0;
        var buy_services = ($('#buy_services').is(':checked')) ? 1 : 0;
        var validate_email = ($('#validate_email').is(':checked')) ? 1 : 0;
        var default_id_plan = $('#default_plan option:selected').attr('id');
        var stripe_enabled = ($('#stripe_enabled').is(':checked')) ? 1 : 0;
        var stripe_automatic_tax_rate = $('#stripe_automatic_tax_rate option:selected').attr('id');
        var stripe_secret_key = $('#stripe_secret_key').val();
        var stripe_public_key = $('#stripe_public_key').val();
        var paypal_enabled = ($('#paypal_enabled').is(':checked')) ? 1 : 0;
        var paypal_live = ($('#paypal_live').is(':checked')) ? 1 : 0;
        var paypal_client_id = $('#paypal_client_id').val();
        var paypal_client_secret = $('#paypal_client_secret').val();
        var aws_s3_enabled = ($('#aws_s3_enabled').is(':checked')) ? 1 : 0;
        var aws_s3_type = $('#aws_s3_type option:selected').attr('id');
        var aws_s3_vt_auto = ($('#aws_s3_vt_auto').is(':checked')) ? 1 : 0;
        var aws_s3_bucket = $('#aws_s3_bucket').val();
        switch(aws_s3_type) {
            case 'digitalocean':
                var aws_s3_region = $('#aws_s3_region_digitalocean option:selected').attr('id');
                break;
            case 'backblaze':
                var aws_s3_region = $('#aws_s3_region_backblaze option:selected').attr('id');
                break;
            default:
                var aws_s3_region = $('#aws_s3_region option:selected').attr('id');
                break;
        }
        var aws_s3_key = $('#aws_s3_key').val();
        var aws_s3_secret = $('#aws_s3_secret').val();
        var aws_s3_accountid = $('#aws_s3_accountid').val();
        var aws_s3_custom_domain = $('#aws_s3_custom_domain').val();
        var mail_activate_subject = $('#mail_activate_subject').val();
        var mail_activate_body = window.mail_activate_body_editor.root.innerHTML;
        var mail_user_add_subject = $('#mail_user_add_subject').val();
        var mail_user_add_body = window.mail_user_add_body_editor.root.innerHTML;
        var mail_forgot_subject = $('#mail_forgot_subject').val();
        var mail_forgot_body = window.mail_forgot_body_editor.root.innerHTML;
        var mail_plan_expiring_subject = $('#mail_plan_expiring_subject').val();
        var mail_plan_expiring_body = window.mail_plan_expiring_body_editor.root.innerHTML;
        var mail_plan_expired_subject = $('#mail_plan_expired_subject').val();
        var mail_plan_expired_body = window.mail_plan_expired_body_editor.root.innerHTML;
        var mail_plan_changed_subject = $('#mail_plan_changed_subject').val();
        var mail_plan_changed_body = window.mail_plan_changed_body_editor.root.innerHTML;
        var mail_plan_canceled_subject = $('#mail_plan_canceled_subject').val();
        var mail_plan_canceled_body = window.mail_plan_canceled_body_editor.root.innerHTML;
        var mail_service_purchased_subject = $('#mail_service_purchased_subject').val();
        var mail_service_purchased_body = window.mail_service_purchased_body_editor.root.innerHTML;
        var language_vc = $('#language_vc').val();
        var initial_msg = $('#initial_msg').val();
        var listening_msg = $('#listening_msg').val();
        var error_msg = $('#error_msg').val();
        var help_cmd = $('#help_cmd').val();
        var help_msg_1 = $('#help_msg_1').val();
        var help_msg_2 = $('#help_msg_2').val();
        var next_cmd = $('#next_cmd').val();
        var next_msg = $('#next_msg').val();
        var prev_cmd = $('#prev_cmd').val();
        var prev_msg = $('#prev_msg').val();
        var left_cmd = $('#left_cmd').val();
        var left_msg = $('#left_msg').val();
        var right_cmd = $('#right_cmd').val();
        var right_msg = $('#right_msg').val();
        var up_cmd = $('#up_cmd').val();
        var up_msg = $('#up_msg').val();
        var down_cmd = $('#down_cmd').val();
        var down_msg = $('#down_msg').val();
        $('#voice_commands_tab input').each(function () {
            if($(this).val()=='') {
                complete = false;
                $(this).addClass("error-highlight");
            } else {
                $(this).removeClass("error-highlight");
            }
        });
        var first_name_enable = ($('#first_name_enable').is(':checked')) ? 1 : 0;
        var last_name_enable = ($('#last_name_enable').is(':checked')) ? 1 : 0;
        var company_enable = ($('#company_enable').is(':checked')) ? 1 : 0;
        var tax_id_enable = ($('#tax_id_enable').is(':checked')) ? 1 : 0;
        var street_enable = ($('#street_enable').is(':checked')) ? 1 : 0;
        var city_enable = ($('#city_enable').is(':checked')) ? 1 : 0;
        var province_enable = ($('#province_enable').is(':checked')) ? 1 : 0;
        var postal_code_enable = ($('#postal_code_enable').is(':checked')) ? 1 : 0;
        var country_enable = ($('#country_enable').is(':checked')) ? 1 : 0;
        var tel_enable = ($('#tel_enable').is(':checked')) ? 1 : 0;
        var first_name_mandatory = ($('#first_name_mandatory').is(':checked')) ? 1 : 0;
        var last_name_mandatory = ($('#last_name_mandatory').is(':checked')) ? 1 : 0;
        var company_mandatory = ($('#company_mandatory').is(':checked')) ? 1 : 0;
        var tax_id_mandatory = ($('#tax_id_mandatory').is(':checked')) ? 1 : 0;
        var street_mandatory = ($('#street_mandatory').is(':checked')) ? 1 : 0;
        var city_mandatory = ($('#city_mandatory').is(':checked')) ? 1 : 0;
        var province_mandatory = ($('#province_mandatory').is(':checked')) ? 1 : 0;
        var postal_code_mandatory = ($('#postal_code_mandatory').is(':checked')) ? 1 : 0;
        var country_mandatory = ($('#country_mandatory').is(':checked')) ? 1 : 0;
        var tel_mandatory = ($('#tel_mandatory').is(':checked')) ? 1 : 0;
        var peerjs_host = $('#peerjs_host').val();
        var peerjs_port = $('#peerjs_port').val();
        var peerjs_path = $('#peerjs_path').val();
        var turn_host = $('#turn_host').val();
        var turn_port = $('#turn_port').val();
        var turn_username = $('#turn_username').val();
        var turn_password = $('#turn_password').val();
        var jitsi_domain = $('#jitsi_domain').val();
        var leaflet_street_basemap = $('#leaflet_street_basemap').val();
        var leaflet_satellite_basemap = $('#leaflet_satellite_basemap').val();
        var leaflet_street_subdomain = $('#leaflet_street_subdomain').val();
        var leaflet_street_maxzoom = $('#leaflet_street_maxzoom').val();
        var leaflet_satellite_subdomain = $('#leaflet_satellite_subdomain').val();
        var leaflet_satellite_maxzoom = $('#leaflet_satellite_maxzoom').val();
        var footer_link_1 = $('#footer_link_1').val();
        var footer_link_2 = $('#footer_link_2').val();
        var footer_link_3 = $('#footer_link_3').val();
        var footer_value_1 = window.footer_value_1.root.innerHTML;
        var footer_value_2 = window.footer_value_2.root.innerHTML;
        var footer_value_3 = window.footer_value_3.root.innerHTML;
        var multires = $('#multires option:selected').attr('id');
        var multires_cloud_url = $('#multires_cloud_url').val();
        var video360 = $('#video360 option:selected').attr('id');
        var video360_cloud_url = $('#video360_cloud_url').val();
        var slideshow = $('#slideshow option:selected').attr('id');
        var slideshow_cloud_url = $('#slideshow_cloud_url').val();
        var video_project = $('#video_project option:selected').attr('id');
        var video_project_url = $('#video_project_url').val();
        var enable_screencast = ($('#enable_screencast').is(':checked')) ? 1 : 0;
        var url_screencast = $('#url_screencast').val();
        var notify_email = $('#notify_email').val();
        var days_expire_notification = $('#days_expire_notification').val();
        var notify_registrations = ($('#notify_registrations').is(':checked')) ? 1 : 0;
        var notify_useradd = ($('#notify_useradd').is(':checked')) ? 1 : 0;
        var notify_plan_expires = ($('#notify_plan_expires').is(':checked')) ? 1 : 0;
        var notify_plan_expiring = ($('#notify_plan_expiring').is(':checked')) ? 1 : 0;
        var notify_plan_changes = ($('#notify_plan_changes').is(':checked')) ? 1 : 0;
        var notify_plan_cancels = ($('#notify_plan_cancels').is(':checked')) ? 1 : 0;
        var notify_service_purchase = ($('#notify_service_purchase').is(':checked')) ? 1 : 0;
        var notify_vt_create = ($('#notify_vt_create').is(':checked')) ? 1 : 0;
        var notify_custom_domain_request = ($('#notify_custom_domain_request').is(':checked')) ? 1 : 0;
        var vr_button = $('#vr_button option:selected').attr('id');
        var disqus_allow_tour = ($('#disqus_allow_tour').is(':checked')) ? 1 : 0;
        var share_providers_t = $('#share_providers option');
        var share_providers = '';
        $(share_providers_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                id = id.replace('provider_','');
                if($(this).is(':selected')) {
                    share_providers = share_providers+id+',';
                }
            }
        });
        if(share_providers!='') {
            share_providers = share_providers.substring(0,share_providers.length-1);
        }
        var disqus_shortname = $('#disqus_shortname').val();
        var disqus_public_key = $('#disqus_public_key').val();
        var globe_ion_token = $('#globe_ion_token').val();
        var globe_arcgis_token = $('#globe_arcgis_token').val();
        var globe_googlemaps_key = $('#globe_googlemaps_key').val();
        var maintenance_backend = ($('#maintenance_backend').is(':checked')) ? 1 : 0;
        var maintenance_viewer = ($('#maintenance_viewer').is(':checked')) ? 1 : 0;
        var maintenance_ip = $('#maintenance_ip').val();
        var ga_tracking_id = $('#ga_tracking_id').val();
        var max_concurrent_sessions = $('#max_concurrent_sessions').val();
        if($('#google_maps_api_key').length) {
            var google_maps_api_key = $('#google_maps_api_key').val();
            var google_oauth2_client_id = $('#google_oauth2_client_id').val();
            var google_oauth2_client_secret = $('#google_oauth2_client_secret').val();
        } else {
            var google_maps_api_key = null;
            var google_oauth2_client_id = null;
            var google_oauth2_client_secret = null;
        }
        var enable_custom_domain = ($('#enable_custom_domain').is(':checked')) ? 1 : 0;
        var custom_domain_ip_address = $('#custom_domain_ip_address').val();
        var server_domain_name = $('#server_domain_name').val();
        var restrict_domain_viewer = ($('#restrict_domain_viewer').is(':checked')) ? 1 : 0;
        var restrict_domain_backend = ($('#restrict_domain_backend').is(':checked')) ? 1 : 0;
        var tawkto_chat_link = $('#tawkto_chat_link').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(!mail_activate_body.includes('%LINK%')) {
            complete = false;
            $('#mail_activate_body').addClass("error-highlight");
        } else {
            $('#mail_activate_body').removeClass("error-highlight");
        }
        $('.input_lang[data-target-id="mail_activate_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_activate_body_editor_lang[lang].root.innerHTML;
            if(value!='' && value!='<p><br></p>') {
                if(!value.includes('%LINK%')) {
                    complete = false;
                    $('#mail_activate_body_'+lang).addClass("error-highlight");
                } else {
                    $('#mail_activate_body_'+lang).removeClass("error-highlight");
                }
            }
        });
        if((!mail_forgot_body.includes('%LINK%')) || (!mail_forgot_body.includes('%VERIFICATION_CODE%'))) {
            complete = false;
            $('#mail_forgot_body').addClass("error-highlight");
        } else {
            $('#mail_forgot_body').removeClass("error-highlight");
        }
        $('.input_lang[data-target-id="mail_forgot_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_forgot_body_editor_lang[lang].root.innerHTML;
            if(value!='' && value!='<p><br></p>') {
                if((!value.includes('%LINK%')) || (!value.includes('%VERIFICATION_CODE%'))) {
                    complete = false;
                    $('#mail_forgot_body_'+lang).addClass("error-highlight");
                } else {
                    $('#mail_forgot_body_'+lang).removeClass("error-highlight");
                }
            }
        });
        var timezone = $('#timezone').val();
        var menuItems = [];
        for (var i = 1; i <= 5; i++) {
            var menuItem = {
                index: i,
                name: $('#menu' + i + '_name').val(),
                icon: $('#menu' + i + '_icon').val(),
                type: $('#menu' + i + '_type option:selected').attr('id'),
                link: $('#menu' + i + '_link').val()
            };
            menuItems.push(menuItem);
        }
        var extra_menu_items = JSON.stringify(menuItems);
        var api_key = $('#api_key').val();
        var id_vt_sample_t = $('#id_vt_sample option');
        var id_vt_sample = '';
        $(id_vt_sample_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    id_vt_sample = id_vt_sample+id+',';
                }
            }
        });
        if(id_vt_sample!='') {
            id_vt_sample = id_vt_sample.substring(0,id_vt_sample.length-1);
        } else {
            id_vt_sample = '0';
        }
        var tour_list_mode = $('#tour_list_mode option:selected').attr('id');
        var tour_inactive_days = $('#tour_inactive_days').val();
        var pwa_enable = ($('#pwa_enable').is(':checked')) ? 1 : 0;
        var meta_title = $('#meta_title').val();
        var meta_description = $('#meta_description').val();
        var array_lang = {};
        array_lang['welcome_msg'] = {};
        $('.input_lang[data-target-id="welcome_msg"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.welcome_msg_editor_lang[lang].root.innerHTML;
            array_lang['welcome_msg'][lang]=value;
        });
        array_lang['welcome_title'] = {};
        $('.input_lang[data-target-id="welcome_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['welcome_title'][lang]=value;
        });
        array_lang['footer_link_1'] = {};
        $('.input_lang[data-target-id="footer_link_1"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['footer_link_1'][lang]=value;
        });
        array_lang['footer_link_2'] = {};
        $('.input_lang[data-target-id="footer_link_2"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['footer_link_2'][lang]=value;
        });
        array_lang['footer_link_3'] = {};
        $('.input_lang[data-target-id="footer_link_3"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['footer_link_3'][lang]=value;
        });
        array_lang['footer_value_1'] = {};
        $('.input_lang[data-target-id="footer_value_1"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.footer_value_1_lang[lang].root.innerHTML;
            array_lang['footer_value_1'][lang]=value;
        });
        array_lang['footer_value_2'] = {};
        $('.input_lang[data-target-id="footer_value_2"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.footer_value_2_lang[lang].root.innerHTML;
            array_lang['footer_value_2'][lang]=value;
        });
        array_lang['footer_value_3'] = {};
        $('.input_lang[data-target-id="footer_value_3"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.footer_value_3_lang[lang].root.innerHTML;
            array_lang['footer_value_3'][lang]=value;
        });
        array_lang['mail_activate_subject'] = {};
        $('.input_lang[data-target-id="mail_activate_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_activate_subject'][lang]=value;
        });
        array_lang['mail_user_add_subject'] = {};
        $('.input_lang[data-target-id="mail_user_add_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_user_add_subject'][lang] = value;
        });
        array_lang['mail_forgot_subject'] = {};
        $('.input_lang[data-target-id="mail_forgot_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_forgot_subject'][lang] = value;
        });
        array_lang['mail_plan_expiring_subject'] = {};
        $('.input_lang[data-target-id="mail_plan_expiring_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_plan_expiring_subject'][lang] = value;
        });
        array_lang['mail_plan_expired_subject'] = {};
        $('.input_lang[data-target-id="mail_plan_expired_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_plan_expired_subject'][lang] = value;
        });
        array_lang['mail_plan_changed_subject'] = {};
        $('.input_lang[data-target-id="mail_plan_changed_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_plan_changed_subject'][lang] = value;
        });
        array_lang['mail_plan_canceled_subject'] = {};
        $('.input_lang[data-target-id="mail_plan_canceled_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_plan_canceled_subject'][lang] = value;
        });
        array_lang['mail_service_purchased_subject'] = {};
        $('.input_lang[data-target-id="mail_service_purchased_subject"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['mail_service_purchased_subject'][lang] = value;
        });
        array_lang['mail_activate_body'] = {};
        $('.input_lang[data-target-id="mail_activate_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_activate_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_activate_body'][lang]=value;
        });
        array_lang['mail_user_add_body'] = {};
        $('.input_lang[data-target-id="mail_user_add_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_user_add_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_user_add_body'][lang] = value;
        });
        array_lang['mail_forgot_body'] = {};
        $('.input_lang[data-target-id="mail_forgot_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_forgot_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_forgot_body'][lang] = value;
        });
        array_lang['mail_plan_expiring_body'] = {};
        $('.input_lang[data-target-id="mail_plan_expiring_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_plan_expiring_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_plan_expiring_body'][lang] = value;
        });
        array_lang['mail_plan_expired_body'] = {};
        $('.input_lang[data-target-id="mail_plan_expired_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_plan_expired_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_plan_expired_body'][lang] = value;
        });
        array_lang['mail_plan_changed_body'] = {};
        $('.input_lang[data-target-id="mail_plan_changed_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_plan_changed_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_plan_changed_body'][lang] = value;
        });
        array_lang['mail_plan_canceled_body'] = {};
        $('.input_lang[data-target-id="mail_plan_canceled_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_plan_canceled_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_plan_canceled_body'][lang] = value;
        });
        array_lang['mail_service_purchased_body'] = {};
        $('.input_lang[data-target-id="mail_service_purchased_body"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.mail_service_purchased_body_editor_lang[lang].root.innerHTML;
            array_lang['mail_service_purchased_body'][lang] = value;
        });
        array_lang['extra_menu_items'] = {};
        $('.input_lang[data-target-id="menu1_name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var menuItems = [];
            for (var i = 1; i <= 5; i++) {
                var menuItem = {
                    index: i,
                    name: $('#menu' + i + '_name_'+lang).val(),
                    icon: $('#menu' + i + '_icon').val(),
                    type: $('#menu' + i + '_type option:selected').attr('id'),
                    link: $('#menu' + i + '_link').val()
                };
                menuItems.push(menuItem);
            }
            var value = JSON.stringify(menuItems);
            array_lang['extra_menu_items'][lang]=value;
        });
        if(complete) {
            if(reload) $('#modal_change_languages').modal('hide');
            if(validate_mail) {
                $('#btn_validate_mail').addClass("disabled");
            }
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/save_settings.php",
                type: "POST",
                data: {
                    purchase_code: purchase_code,
                    purchase_code_gsv: purchase_code_gsv,
                    name: name,
                    theme_color: theme_color,
                    theme_color_dark: theme_color_dark,
                    dark_mode: dark_mode,
                    sidebar: sidebar,
                    sidebar_color_1: sidebar_color_1,
                    sidebar_color_2: sidebar_color_2,
                    sidebar_color_1_dark: sidebar_color_1_dark,
                    sidebar_color_2_dark: sidebar_color_2_dark,
                    font_backend: font_backend,
                    welcome_msg: welcome_msg,
                    welcome_title: welcome_title,
                    welcome_enable: welcome_enable,
                    welcome_icon: welcome_icon,
                    terms_and_conditions: terms_and_conditions,
                    privacy_policy: privacy_policy,
                    logo: window.b_logo_image,
                    small_logo: window.b_logo_s_image,
                    background: window.b_background_image,
                    background_reg: window.b_background_reg_image,
                    style_login: style_login,
                    style_register: style_register,
                    smtp_server: smtp_server,
                    smtp_port: smtp_port,
                    smtp_secure: smtp_secure,
                    smtp_auth: smtp_auth,
                    smtp_username: smtp_username,
                    smtp_password: smtp_password,
                    smtp_from_email: smtp_from_email,
                    smtp_from_name: smtp_from_name,
                    furl_blacklist: furl_blacklist,
                    language: language,
                    language_domain: language_domain,
                    languages_enabled: languages_enabled_json,
                    languages_viewer_enabled: languages_viewer_enabled_json,
                    css_array: css_array_json,
                    js_array: js_array_json,
                    head_array: head_array_json,
                    head_php_array: head_php_array_json,
                    contact_mail: contact_mail,
                    help_url: help_url,
                    website_url: website_url,
                    website_name: website_name,
                    enable_external_vt: enable_external_vt,
                    enable_ar_vt: enable_ar_vt,
                    enable_ai_room: enable_ai_room,
                    ai_key: ai_key,
                    enable_autoenhance_room: enable_autoenhance_room,
                    autoenhance_key: autoenhance_key,
                    enable_wizard: enable_wizard,
                    popup_add_room_vt: popup_add_room_vt,
                    enable_sample: enable_sample,
                    id_vt_sample: id_vt_sample,
                    id_vt_template: id_vt_template,
                    social_google_enable: social_google_enable,
                    social_facebook_enable: social_facebook_enable,
                    social_twitter_enable: social_twitter_enable,
                    social_wechat_enable: social_wechat_enable,
                    social_qq_enable: social_qq_enable,
                    social_google_id: social_google_id,
                    social_google_secret: social_google_secret,
                    social_facebook_id: social_facebook_id,
                    social_facebook_secret: social_facebook_secret,
                    social_twitter_id: social_twitter_id,
                    social_twitter_secret: social_twitter_secret,
                    social_wechat_id: social_wechat_id,
                    social_wechat_secret: social_wechat_secret,
                    social_qq_id: social_qq_id,
                    social_qq_secret: social_qq_secret,
                    enable_registration: enable_registration,
                    default_id_plan: default_id_plan,
                    change_plan: change_plan,
                    buy_services: buy_services,
                    validate_email: validate_email,
                    stripe_enabled: stripe_enabled,
                    stripe_automatic_tax_rate: stripe_automatic_tax_rate,
                    stripe_secret_key: stripe_secret_key,
                    stripe_public_key: stripe_public_key,
                    paypal_enabled: paypal_enabled,
                    paypal_live: paypal_live,
                    paypal_client_id: paypal_client_id,
                    paypal_client_secret: paypal_client_secret,
                    mail_activate_subject: mail_activate_subject,
                    mail_activate_body: mail_activate_body,
                    mail_user_add_subject: mail_user_add_subject,
                    mail_user_add_body: mail_user_add_body,
                    mail_forgot_subject: mail_forgot_subject,
                    mail_forgot_body: mail_forgot_body,
                    mail_plan_expiring_subject: mail_plan_expiring_subject,
                    mail_plan_expiring_body: mail_plan_expiring_body,
                    mail_plan_expired_subject: mail_plan_expired_subject,
                    mail_plan_expired_body: mail_plan_expired_body,
                    mail_plan_changed_subject: mail_plan_changed_subject,
                    mail_plan_changed_body: mail_plan_changed_body,
                    mail_plan_canceled_subject: mail_plan_canceled_subject,
                    mail_plan_canceled_body: mail_plan_canceled_body,
                    mail_service_purchased_subject: mail_service_purchased_subject,
                    mail_service_purchased_body: mail_service_purchased_body,
                    voice_commands: {
                        language: language_vc,
                        initial_msg: initial_msg,
                        listening_msg: listening_msg,
                        error_msg: error_msg,
                        help_cmd: help_cmd,
                        help_msg_1: help_msg_1,
                        help_msg_2: help_msg_2,
                        next_cmd: next_cmd,
                        next_msg: next_msg,
                        prev_cmd: prev_cmd,
                        prev_msg: prev_msg,
                        left_cmd: left_cmd,
                        left_msg: left_msg,
                        right_cmd: right_cmd,
                        right_msg: right_msg,
                        up_cmd: up_cmd,
                        up_msg: up_msg,
                        down_cmd: down_cmd,
                        down_msg: down_msg
                    },
                    first_name_enable: first_name_enable,
                    last_name_enable: last_name_enable,
                    company_enable: company_enable,
                    tax_id_enable: tax_id_enable,
                    street_enable: street_enable,
                    city_enable: city_enable,
                    province_enable: province_enable,
                    postal_code_enable: postal_code_enable,
                    country_enable: country_enable,
                    tel_enable: tel_enable,
                    first_name_mandatory: first_name_mandatory,
                    last_name_mandatory: last_name_mandatory,
                    company_mandatory: company_mandatory,
                    tax_id_mandatory: tax_id_mandatory,
                    street_mandatory: street_mandatory,
                    city_mandatory: city_mandatory,
                    province_mandatory: province_mandatory,
                    postal_code_mandatory: postal_code_mandatory,
                    country_mandatory: country_mandatory,
                    tel_mandatory: tel_mandatory,
                    peerjs_host: peerjs_host,
                    peerjs_port: peerjs_port,
                    peerjs_path: peerjs_path,
                    turn_host: turn_host,
                    turn_port: turn_port,
                    turn_username: turn_username,
                    turn_password: turn_password,
                    jitsi_domain: jitsi_domain,
                    url_street: leaflet_street_basemap,
                    url_sat: leaflet_satellite_basemap,
                    sub_street: leaflet_street_subdomain,
                    sub_sat: leaflet_satellite_subdomain,
                    zoom_street: leaflet_street_maxzoom,
                    zoom_sat: leaflet_satellite_maxzoom,
                    footer_link_1: footer_link_1,
                    footer_link_2: footer_link_2,
                    footer_link_3: footer_link_3,
                    footer_value_1: footer_value_1,
                    footer_value_2: footer_value_2,
                    footer_value_3: footer_value_3,
                    multires: multires,
                    multires_cloud_url: multires_cloud_url,
                    video360: video360,
                    video360_cloud_url: video360_cloud_url,
                    slideshow: slideshow,
                    slideshow_cloud_url: slideshow_cloud_url,
                    video_project: video_project,
                    video_project_url: video_project_url,
                    enable_screencast: enable_screencast,
                    url_screencast: url_screencast,
                    notify_email: notify_email,
                    notify_registrations: notify_registrations,
                    notify_useradd: notify_useradd,
                    notify_plan_expires: notify_plan_expires,
                    notify_plan_expiring: notify_plan_expiring,
                    notify_plan_changes: notify_plan_changes,
                    notify_plan_cancels: notify_plan_cancels,
                    notify_service_purchase: notify_service_purchase,
                    notify_vt_create: notify_vt_create,
                    notify_custom_domain_request: notify_custom_domain_request,
                    captcha_login: captcha_login,
                    captcha_register: captcha_register,
                    twofa_enable: twofa_enable,
                    vr_button: vr_button,
                    share_providers: share_providers,
                    disqus_shortname: disqus_shortname,
                    disqus_public_key: disqus_public_key,
                    disqus_allow_tour: disqus_allow_tour,
                    font_provider: font_provider,
                    days_expire_notification: days_expire_notification,
                    aws_s3_enabled: aws_s3_enabled,
                    aws_s3_type: aws_s3_type,
                    aws_s3_vt_auto: aws_s3_vt_auto,
                    aws_s3_bucket: aws_s3_bucket,
                    aws_s3_region: aws_s3_region,
                    aws_s3_key: aws_s3_key,
                    aws_s3_secret: aws_s3_secret,
                    aws_s3_accountid: aws_s3_accountid,
                    aws_s3_custom_domain: aws_s3_custom_domain,
                    globe_ion_token: globe_ion_token,
                    globe_arcgis_token: globe_arcgis_token,
                    globe_googlemaps_key: globe_googlemaps_key,
                    maintenance_backend: maintenance_backend,
                    maintenance_viewer: maintenance_viewer,
                    maintenance_ip: maintenance_ip,
                    enable_deepl: enable_deepl,
                    deepl_api_key: deepl_api_key,
                    timezone: timezone,
                    ga_tracking_id: ga_tracking_id,
                    cookie_policy: cookie_policy,
                    cookie_consent: cookie_consent,
                    extra_menu_items: extra_menu_items,
                    api_key: api_key,
                    tour_list_mode: tour_list_mode,
                    tour_inactive_days: tour_inactive_days,
                    max_concurrent_sessions: max_concurrent_sessions,
                    custom_html: custom_html,
                    google_maps_api_key: google_maps_api_key,
                    google_oauth2_client_id: google_oauth2_client_id,
                    google_oauth2_client_secret: google_oauth2_client_secret,
                    array_lang: array_lang_json,
                    enable_custom_domain: enable_custom_domain,
                    custom_domain_ip_address: custom_domain_ip_address,
                    server_domain_name: server_domain_name,
                    restrict_domain_viewer: restrict_domain_viewer,
                    restrict_domain_backend: restrict_domain_backend,
                    tawkto_chat_link: tawkto_chat_link,
                    pwa_enable: pwa_enable,
                    meta_title: meta_title,
                    meta_description: meta_description,
                    meta_image: window.image_meta
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        if(rsp.favicon!=1) {
                            generate_favicons(rsp.favicon);
                        }
                        edit_all_categories();
                        window.settings_need_save = false;
                        if(reload) {
                            let currentUrl = window.location.href;
                            if (!currentUrl.includes("&localization=1")) {
                                currentUrl += "&localization=1";
                            }
                            window.location.href = currentUrl;
                        }
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        }, 1000);
                        if(validate_mail) {
                            $.ajax({
                                url: "ajax/send_email.php",
                                type: "POST",
                                data: {
                                    type: 'validate',
                                    email: smtp_from_email
                                },
                                timeout: 15000,
                                async: true,
                                success: function (json) {
                                    var rsp = JSON.parse(json);
                                    if (rsp.status == "ok") {
                                        $('#validate_mail').html('<i style="color: green" class="fas fa-circle"></i> '+window.backend_labels.valid);
                                        $('#validate_email').parent().removeClass('disabled');
                                    } else {
                                        alert(rsp.msg);
                                        $('#validate_mail').html('<i style="color: red" class="fas fa-circle"></i> '+window.backend_labels.invalid);
                                        $('#validate_email').parent().addClass('disabled');
                                    }
                                    $('#btn_validate_mail').removeClass("disabled");
                                },
                                error: function(){
                                    alert('Timeout');
                                    $('#validate_mail').html('<i style="color: red" class="fas fa-circle"></i> '+window.backend_labels.invalid);
                                    $('#btn_validate_mail').removeClass("disabled");
                                },
                            });
                        } else {
                            if(window.current_language!=language) {
                                location.reload();
                            }
                        }
                    } else {
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        }, 1000);
                        if(validate_mail) {
                            $('#btn_validate_mail').removeClass("disabled");
                        }
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    }, 1000);
                    if(validate_mail) {
                        $('#btn_validate_mail').removeClass("disabled");
                    }
                }
            });
        }
    }

    window.open_modal_enable_2fa = function() {
        $('#code_2fa').val('');
        $('#qr_code_2fa').html('<i class=\'fas fa-spin fa-circle-notch\' aria-hidden=\'true\'></i>');
        $('#modal_enable_2fa').modal("show");
        $.ajax({
            url: "ajax/init_2fa.php",
            type: "POST",
            data: {},
            timeout: 15000,
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                var secretkey = rsp.secretkey;
                var qrcode_img = rsp.qrcode;
                $('#code_2fa').val(secretkey);
                $('#qr_code_2fa').html('<img src="data:image/png;base64,'+qrcode_img+'"/>');
            }
        });
    }

    window.continue_enable_2fa = function () {
        $('#modal_enable_2fa').modal("hide");
        $('#modal_check_enable_2fa').modal("show");
    }

    window.enable_2fa = function () {
        var btn_html = $('#btn_enable_2fa').html();
        $('#btn_enable_2fa').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#modal_check_enable_2fa button').addClass('disabled');
        $('#code_check_2fa').removeClass('error-highlight');
        var code = $('#code_check_2fa').val();
        if(code=='') {
            $('#btn_enable_2fa').html(btn_html);
            $('#modal_check_enable_2fa button').removeClass('disabled');
            $('#code_check_2fa').addClass('error-highlight');
        } else {
            $.ajax({
                url: "ajax/enable_2fa.php",
                type: "POST",
                data: {
                    code: code,
                },
                timeout: 15000,
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        $('#btn_modal_enable_2fa').addClass('d-none');
                        $('#btn_modal_disable_2fa').removeClass('d-none');
                        $('#circle_2fa').css('color','green');
                        $('#modal_check_enable_2fa').modal("hide");
                    } else {
                        $('#code_check_2fa').addClass('error-highlight');
                    }
                    $('#btn_enable_2fa').html(btn_html);
                    $('#modal_check_enable_2fa button').removeClass('disabled');
                },
                error: function () {
                    $('#btn_enable_2fa').html(btn_html);
                    $('#modal_check_enable_2fa button').removeClass('disabled');
                    $('#code_check_2fa').addClass('error-highlight');
                }
            });
        }
    }

    window.check_login_2fa = function () {
        var btn_html = $('#btn_login_2fa').html();
        $('#btn_login_2fa').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#modal_check_login_2fa button').addClass('disabled');
        $('#code_check_2fa').removeClass('error-highlight');
        var code = $('#code_check_2fa').val();
        if(code=='') {
            $('#btn_login_2fa').html(btn_html);
            $('#modal_check_login_2fa button').removeClass('disabled');
            $('#code_check_2fa').addClass('error-highlight');
        } else {
            $.ajax({
                url: "ajax/check_login_2fa.php",
                type: "POST",
                data: {
                    code: code,
                },
                timeout: 15000,
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        $('#btn_login').addClass("disabled");
                        $('#modal_check_login_2fa').modal("hide");
                        location.href='index.php';
                    } else {
                        $('#code_check_2fa').addClass('error-highlight');
                    }
                    $('#btn_login_2fa').html(btn_html);
                    $('#modal_check_login_2fa button').removeClass('disabled');
                },
                error: function () {
                    $('#btn_login_2fa').html(btn_html);
                    $('#modal_check_login_2fa button').removeClass('disabled');
                    $('#code_check_2fa').addClass('error-highlight');
                }
            });
        }
    }

    window.disable_2fa = function () {
        var btn_html = $('#btn_disable_2fa').html();
        $('#btn_disable_2fa').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $('#modal_disable_2fa button').addClass('disabled');
        $('#code_disable_2fa').removeClass('error-highlight');
        var code = $('#code_disable_2fa').val();
        if(code=='') {
            $('#btn_disable_2fa').html(btn_html);
            $('#modal_disable_2fa button').removeClass('disabled');
            $('#code_disable_2fa').addClass('error-highlight');
        } else {
            $.ajax({
                url: "ajax/disable_2fa.php",
                type: "POST",
                data: {
                    code: code,
                },
                timeout: 15000,
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        $('#btn_modal_enable_2fa').removeClass('d-none');
                        $('#btn_modal_disable_2fa').addClass('d-none');
                        $('#circle_2fa').css('color','red');
                        $('#modal_disable_2fa').modal("hide");
                    } else {
                        $('#code_disable_2fa').addClass('error-highlight');
                    }
                    $('#btn_disable_2fa').html(btn_html);
                    $('#modal_disable_2fa button').removeClass('disabled');
                },
                error: function () {
                    $('#btn_disable_2fa').html(btn_html);
                    $('#modal_disable_2fa button').removeClass('disabled');
                    $('#code_disable_2fa').addClass('error-highlight');
                }
            });
        }
    }

    window.add_virtualtour_sample = function () {
        $('#modal_sample_tour').modal("show");
    }

    window.close_virtualtour_sample = function () {
        $('#modal_sample_tour').modal("hide");
    }

    window.close_virtualtour_import = function () {
        $('#modal_import_tour').modal("hide");
    }

    window.add_virtualtour = function (create_and_edit) {
        window.create_and_edit = create_and_edit;
        var complete = true;
        var name = $('#name').val();
        var author = $('#author').val();
        var vt_type = $('#vt_type option:selected').attr('id');
        var language = $('#language option:selected').attr('id');
        var sample_data = $('#sample_data').is(':checked');
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            if(sample_data) {
                add_virtualtour_sample();
                return;
            }
            if(create_and_edit) {
                var btn_html = $('#btn_create_edit_tour').html();
                $('#btn_create_edit_tour').html('<i class="fas fa-circle-notch fa-spin"></i>');
            } else {
                var btn_html = $('#btn_create_tour').html();
                $('#btn_create_tour').html('<i class="fas fa-circle-notch fa-spin"></i>');
            }
            $('#modal_new_virtualtour button').addClass("disabled");
            $.ajax({
                url: "ajax/add_virtual_tour.php",
                type: "POST",
                data: {
                    name: name,
                    author: author,
                    language: language,
                    vt_type: vt_type
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $.ajax({
                            url: "ajax/send_email.php",
                            type: "POST",
                            data: {
                                type: 'vt_create',
                                id_user: window.id_user,
                                id_vt: rsp.id
                            },
                            timeout: 15000,
                            async: true,
                            success: function () {}
                        });
                        if(window.create_and_edit) {
                            if (rsp.id != "") {
                                location.href="index.php?p=edit_virtual_tour&id="+rsp.id;
                            } else {
                                if(create_and_edit) {
                                    $('#btn_create_edit_tour').html(btn_html);
                                } else {
                                    $('#btn_create_tour').html(btn_html);
                                }
                                $('#modal_new_virtualtour button').removeClass("disabled");
                            }
                        } else {
                            if(window.wizard_step!=-1) {
                                location.href = 'index.php?p=virtual_tours&wstep=5';
                            } else {
                                const doNotShowPopup = localStorage.getItem("doNotShowPopup");
                                switch(parseInt(vt_type)) {
                                    case 0:
                                        if(window.popup_add_room_vt) {
                                            if($('#btn_purchase_service').length) $('#btn_purchase_service').attr('href','index.php?p=buy_service&id_vt='+rsp.id);
                                            if(doNotShowPopup !== "true") {
                                                $('#modal_add_room_vt').modal('show');
                                            } else {
                                                location.reload();
                                            }
                                        } else {
                                            location.reload();
                                        }
                                        break;
                                    case 1:
                                        $('#btn_add_external_link').attr('onclick','save_external_link('+rsp.id+')');
                                        $('#modal_external_link').modal('show');
                                        $('#external_link').focus();
                                        break;
                                    case 2:
                                        if(window.popup_add_room_vt) {
                                            if($('#btn_purchase_service').length) $('#btn_purchase_service').attr('href','index.php?p=buy_service&id_vt='+rsp.id);
                                            $('#modal_add_room_vt .modal-footer a:nth-child(2)').addClass('disabled');
                                            if(doNotShowPopup !== "true") {
                                                $('#modal_add_room_vt').modal('show');
                                            } else {
                                                location.reload();
                                            }
                                        } else {
                                            location.reload();
                                        }
                                        break;
                                }
                            }
                        }
                    } else {
                        if(create_and_edit) {
                            $('#btn_create_edit_tour').html(btn_html);
                        } else {
                            $('#btn_create_tour').html(btn_html);
                        }
                        $('#modal_new_virtualtour button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.save_external_link = function(id_vt) {
        var external_link = $('#external_link').val();
        if(external_link!='') {
            $('#modal_external_link button').addClass('disabled');
            $.ajax({
                url: "ajax/save_external_link.php",
                type: "POST",
                data: {
                    id_virtualtour: id_vt,
                    external_link: external_link
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        location.reload();
                    } else {
                        $('#modal_external_link button').removeClass('disabled');
                    }
                },
                error: function() {
                    $('#modal_external_link button').removeClass('disabled');
                }
            });
        } else {
            $('#external_link').focus();
        }
    }

    window.close_modal_add_room_vt = function() {
        $('#modal_add_room_vt').modal('hide');
        location.reload();
    }

    window.close_modal_external_link = function() {
        $('#modal_external_link').modal('hide');
        location.reload();
    }

    window.change_map_type = function () {
        var map_type = $('#map_type option:selected').attr('id');
        switch(map_type) {
            case 'map':
                $('#frm').addClass('disabled');
                $('#btn_create_map').prop('disabled',false);
                break;
            case 'floorplan':
                $('#frm').removeClass('disabled');
                $('#btn_create_map').prop('disabled',true);
                break;
        }
    }

    window.add_map = function () {
        var complete = true;
        var name = $('#name').val();
        var map_image = $('#preview_image img').attr('src');
        var map_type = $('#map_type option:selected').attr('id');
        var cropData = null;
        if(map_type=='floorplan') {
            cropData = window.cropper_image.getData();
            const imageData = window.cropper_image.getImageData();
            const needsCrop =
                cropData.x > 0 ||
                cropData.y > 0 ||
                Math.abs(cropData.width - imageData.naturalWidth) > 1 ||
                Math.abs(cropData.height - imageData.naturalHeight) > 1;
            if(!needsCrop) {
                cropData = null;
            }
        }
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#modal_new_map button').addClass("disabled");
            $.ajax({
                url: "ajax/add_map.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    name: name,
                    map_image: map_image,
                    map_type: map_type,
                    cropData: cropData
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_new_map button').removeClass("disabled");
                        $('#modal_new_map').modal("hide");
                        var id_map = rsp.id;
                        location.href = "index.php?p=edit_map&id="+id_map;
                    } else {
                        $('#modal_new_map button').removeClass("disabled");
                    }
                }
            });
        }
    };

    window.edit_map_image = function() {
        $('#modal_edit_map button').addClass("disabled");
        var map_image = $('#preview_image img').attr('src');
        var cropData = window.cropper_image.getData();
        const imageData = window.cropper_image.getImageData();
        const needsCrop =
            cropData.x > 0 ||
            cropData.y > 0 ||
            Math.abs(cropData.width - imageData.naturalWidth) > 1 ||
            Math.abs(cropData.height - imageData.naturalHeight) > 1;
        if(!needsCrop) {
            cropData = null;
        }
        $.ajax({
            url: "ajax/change_map_image.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_map: window.id_map_sel,
                map_image: map_image,
                cropData: cropData
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_edit_map').modal("hide");
                    location.reload();
                } else {
                    $('#modal_edit_map button').removeClass("disabled");
                }
            }
        });
    }

    window.add_room = function () {
        var complete = true;
        var name = $('#name').val();
        var panorama_image = $('#preview_image img').attr('src');
        var type_pano = $('#type_pano option:selected').attr('id');
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var panorama_url = $('#panorama_url').val();
        switch(type_pano) {
            case 'hls':
                if(panorama_url=='') {
                    complete = false;
                    $('#panorama_url').addClass("error-highlight");
                } else {
                    $('#panorama_url').removeClass("error-highlight");
                }
                break;
            case 'video':
                panorama_image = panorama_image.replace(/^data:image\/(jpeg|jpg);base64,/, "");
                break;
            case 'ai_room':
                panorama_image = $('#ai_image').val();
                break;
        }
        if(complete) {
            $('#modal_new_room .btn').addClass("disabled");
            var btn_html =  $('#btn_create_room').html();
            $('#btn_create_room').html('<i class="fas fa-circle-notch fa-spin"></i>');
            $.ajax({
                url: "ajax/add_room.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    name: name,
                    type_pano: type_pano,
                    panorama_image: panorama_image,
                    panorama_video: window.panorama_video,
                    panorama_url: panorama_url,
                    panorama_json: window.panorama_json,
                    use_existing_panorama: (window.use_existing_panorama) ? 1 : 0
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        var id_room = rsp.id;
                        var panorama_image_gt = rsp.panorama_image_gt;
                        generate_thumb_panorama(id_room,panorama_image_gt);
                    } else {
                        $('#btn_create_room').html(btn_html);
                        $('#modal_new_room button').removeClass("disabled");
                    }
                },
                error: function() {
                    $('#btn_create_room').html(btn_html);
                    $('#modal_new_room button').removeClass("disabled");
                }
            });
        }
    };

    window.add_bulk_room = function (id_virtualtour,panorama_image,name) {
        $.ajax({
            url: "ajax/add_room.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                name: name,
                panorama_image: panorama_image
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    var panorama_image_gt = rsp.panorama_image_gt;
                    generate_thumb_panorama('bulk',panorama_image_gt);
                }
            }
        });
    };

    function generate_thumb_panorama(id_room,panorama_image_gt) {
        if(panorama_image_gt!='') {
            $.ajax({
                url: "../services/generate_thumb.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    panorama_image_gt: panorama_image_gt
                },
                async: true,
                success: function (json) {
                    generate_mobile_panorama(id_room,panorama_image_gt);
                },
                error: function() {
                    generate_mobile_panorama(id_room,panorama_image_gt);
                }
            });
        } else {
            generate_mobile_panorama(id_room,panorama_image_gt);
        }
    }

    function generate_mobile_panorama(id_room,panorama_image_gt) {
        if(panorama_image_gt!='') {
            $.ajax({
                url: "../services/generate_pano_mobile.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    panorama_image_gt: panorama_image_gt
                },
                async: true,
                success: function (json) {
                    redirect_add_room(id_room);
                },
                error: function() {
                    redirect_add_room(id_room);
                }
            });
        } else {
            redirect_add_room(id_room);
        }
    }
    function redirect_add_room(id_room) {
        if(id_room=='bulk') {
            window.rooms_created++;
            $('#rooms_created').html(window.rooms_created);
        } else {
            $('#modal_new_room .btn').removeClass("disabled");
            $('#modal_new_room').modal("hide");
            if(window.wizard_step!=-1) {
                if(window.wizard_step==12) {
                    location.href = "index.php?p=edit_room&id="+id_room+"&wstep=16";
                } else {
                    location.href = "index.php?p=edit_room&id="+id_room+"&wstep=10";
                }
            } else {
                location.href = "index.php?p=edit_room&id="+id_room;
            }
        }
    }

    window.add_bulk_map = function (id_virtualtour,map_image,name) {
        $.ajax({
            url: "ajax/add_map.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                name: name,
                map_image: map_image,
                map_type: 'floorplan'
            },
            async: true,
            success: function (json) {
                window.maps_created++;
                $('#maps_created').html(window.maps_created);
            }
        });
    };

    window.save_user = function(id_user_edit) {
        var complete = true;
        var username = $('#username').val();
        var email = $('#email').val();
        var role = $('#role option:selected').attr('id');
        var plan = $('#plan option:selected').attr('id');
        var language = $('#language option:selected').attr('id');
        var active = ($('#active').is(':checked')) ? 1 : 0;
        var expire_plan_date_manual_date = $('#expire_plan_date_manual_date').val();
        var expire_plan_date_manual_time = $('#expire_plan_date_manual_time').val();
        if($('#ai_credits').prop('readonly') === true) {
            var ai_credits = 0;
        } else {
            var ai_credits = $('#ai_credits').val();
        }
        if($('#autoenhance_credits').prop('readonly') === true) {
            var autoenhance_credits = 0;
        } else {
            var autoenhance_credits = $('#autoenhance_credits').val();
        }
        if($('#gsv_publish_credits').prop('readonly') === true) {
            var gsv_publish_credits = 0;
        } else {
            var gsv_publish_credits = $('#gsv_publish_credits').val();
        }
        var services_credits = $('#services_credits').val();
        var username = $('#username').val();
        var email = $('#email').val();
        var avatar = $('#avatar_edit').attr('src');
        var language = $('#language option:selected').attr('id');
        var first_name = $('#first_name').val();
        var last_name = $('#last_name').val();
        var company = $('#company').val();
        var tax_id = $('#tax_id').val();
        var street = $('#street').val();
        var city = $('#city').val();
        var province = $('#province').val();
        var postal_code = $('#postal_code').val();
        var country = $('#country option:selected').val();
        var tel = $('#tel').val();
        if(username=='') {
            complete = false;
            $('#username').addClass("error-highlight");
        } else {
            $('#username').removeClass("error-highlight");
        }
        if(email=='') {
            complete = false;
            $('#email').addClass("error-highlight");
        } else {
            $('#email').removeClass("error-highlight");
        }
        var note = $('#note').val();
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            $.ajax({
                url: "ajax/save_user.php",
                type: "POST",
                data: {
                    id_svt: id_user_edit,
                    username_svt: username,
                    email_svt: email,
                    role_svt: role,
                    plan_svt: plan,
                    ai_credits: ai_credits,
                    autoenhance_credits: autoenhance_credits,
                    services_credits: services_credits,
                    gsv_publish_credits: gsv_publish_credits,
                    language_svt: language,
                    active_svt: active,
                    expire_plan_date_manual_date_svt: expire_plan_date_manual_date,
                    expire_plan_date_manual_time_svt: expire_plan_date_manual_time,
                    first_name: first_name,
                    last_name: last_name,
                    company: company,
                    tax_id: tax_id,
                    street: street,
                    city: city,
                    province: province,
                    postal_code: postal_code,
                    country: country,
                    tel: tel,
                    note: note
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.user_need_save = false;
                        if(rsp.reload==1) {
                            location.reload();
                        } else {
                            $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                            setTimeout(function () {
                                $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                                $('#save_btn').removeClass("disabled");
                            },1000);
                        }
                    } else {
                        alert(rsp.msg);
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_globe = function(id_globe,reload) {
        $('#friendly_url').removeClass("error-highlight");
        var complete = true;
        var name = $('#name').val();
        var pointer_size = $('#pointer_size').val();
        var pointer_color = $('#pointer_color').val();
        var pointer_border = $('#pointer_border').val();
        var min_altitude = $('#min_altitude').val();
        var zoom_duration = $('#zoom_duration').val();
        var default_view = $('#default_view option:selected').attr('id');
        var type = $('#type option:selected').attr('id');
        var custom_css = window.editor_css.getValue();
        var open_target = $('#open_target option:selected').attr('id');
        var ga_tracking_id = $('#ga_tracking_id').val();
        var cookie_consent = ($('#cookie_consent').is(':checked')) ? 1 : 0;
        var pwa_enable = $('#pwa_enable').is(':checked') ? 1 : 0;
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            $.ajax({
                url: "ajax/save_globe.php",
                type: "POST",
                data: {
                    id: id_globe,
                    name: name,
                    pointer_size: pointer_size,
                    pointer_color: pointer_color,
                    pointer_border: pointer_border,
                    logo: window.s_logo_image,
                    custom_css: custom_css,
                    min_altitude: min_altitude,
                    zoom_duration: zoom_duration,
                    default_view: default_view,
                    type: type,
                    open_target: open_target,
                    initial_pos: window.initial_pos,
                    ga_tracking_id: ga_tracking_id,
                    cookie_consent: cookie_consent,
                    pwa_enable: pwa_enable
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        if(rsp.favicon!=1) {
                            generate_favicons(rsp.favicon);
                        }
                        window.globe_need_save = false;
                        if(reload==true) {
                            get_globe_map(id_globe,false);
                            $('#btn_add_map_point').removeClass('disabled');
                            $('#msg_select_point').show();
                            $('.point_settings').hide();
                        } else if(reload=='cd') {
                            location.reload();
                        }
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    } else {
                        if(rsp.status=='error_furl') {
                            $('#friendly_url').addClass("error-highlight");
                        }
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_showcase = function(id_showcase,reload) {
        $('#friendly_url').removeClass("error-highlight");
        var complete = true;
        var array_lang = {};
        var name = $('#name').val();
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var bg_color = $('#bg_color').val();
        var header_html = window.editor_html_h.getValue();
        array_lang['header_html'] = {};
        $('.input_lang[data-target-id="header_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.editor_html_h_langs[lang].getValue();
            array_lang['header_html'][lang]=value;
        });
        var footer_html = window.editor_html_f.getValue();
        array_lang['footer_html'] = {};
        $('.input_lang[data-target-id="footer_html"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.editor_html_f_langs[lang].getValue();
            array_lang['footer_html'][lang]=value;
        });
        var custom_css = window.editor_css.getValue();
        var ga_tracking_id = $('#ga_tracking_id').val();
        var cookie_consent = ($('#cookie_consent').is(':checked')) ? 1 : 0;
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var list_s_vt = [];
        var list_s_type = [];
        var list_s_priority = [];
        $('.list_s_vt input[type=checkbox]').each(function () {
            var id = this.id;
            if(this.checked) {
                list_s_vt.push(id);
                list_s_type.push($('#t_'+id+' option:selected').attr('id'));
                list_s_priority.push($('#p_'+id).val());
            }
        });
        var sort_settings_t = $('#sort_settings option');
        var sort_settings = {};
        $(sort_settings_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                if($(this).is(':selected')) {
                    sort_settings[id]=1;
                } else {
                    sort_settings[id]=0;
                }
            }
        });
        var sort_default = $('#sort_default option:selected').attr('id');
        sort_settings['default'] = sort_default;
        var sort_settings_json = JSON.stringify(sort_settings);
        var open_target = $('#open_target option:selected').attr('id');
        var language = $('#language option:selected').attr('id');
        var languages_enabled_t = $('#languages_enabled option');
        var languages_enabled = {};
        $(languages_enabled_t).each(function(index, elem){
            var id = $(this).attr('id').replace('ls_','');
            if($(this).is(':selected')) {
                languages_enabled[id]=1;
            } else {
                languages_enabled[id]=0;
            }
        });
        var languages_enabled_json = JSON.stringify(languages_enabled);
        var pwa_enable = $('#pwa_enable').is(':checked') ? 1 : 0;
        if(complete) {
            if(reload) $('#modal_change_languages').modal('hide');
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/save_showcase.php",
                type: "POST",
                data: {
                    id: id_showcase,
                    name: name,
                    bg_color: bg_color,
                    logo: window.s_logo_image,
                    banner: window.s_banner_image,
                    list_s_vt: list_s_vt,
                    list_s_type: list_s_type,
                    list_s_priority: list_s_priority,
                    header_html: header_html,
                    footer_html: footer_html,
                    custom_css: custom_css,
                    sort_settings: sort_settings_json,
                    open_target: open_target,
                    ga_tracking_id: ga_tracking_id,
                    cookie_consent: cookie_consent,
                    language: language,
                    languages_enabled: languages_enabled_json,
                    array_lang: array_lang_json,
                    pwa_enable: pwa_enable
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        if(rsp.favicon!=1) {
                            generate_favicons(rsp.favicon);
                        }
                        window.showcase_need_save = false;
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        if(reload) location.reload();
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    } else {
                        if(rsp.status=='error_furl') {
                            $('#friendly_url').addClass("error-highlight");
                        }
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_advertisement = function(id_advertisement) {
        var complete = true;
        var name = $('#name').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var link = $('#link').val();
        var countdown = $('#countdown').val();
        var type = $('#type option:selected').attr('id');
        var iframe_link = $('#iframe_link').val();
        var auto_assign = ($('#auto_assign').is(':checked')) ? 1 : 0;
        var list_p_vt = [];
        $('.list_p_vt input[type=checkbox]').each(function () {
            if(this.checked) {
                list_p_vt.push(this.id);
            }
        });
        var list_s_vt = [];
        $('.list_s_vt input[type=checkbox]').each(function () {
            if(this.checked) {
                list_s_vt.push(this.id);
            }
        });
        var custom_html = window.custom_ads_html.getValue();
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            $.ajax({
                url: "ajax/save_announce.php",
                type: "POST",
                data: {
                    id: id_advertisement,
                    name: name,
                    link: link,
                    countdown: countdown,
                    auto_assign: auto_assign,
                    type: type,
                    image: window.image_advertisement,
                    video: window.video_advertisement,
                    iframe_link: iframe_link,
                    custom_html: custom_html,
                    list_p_vt: list_p_vt,
                    list_s_vt: list_s_vt
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.advertisement_need_save = false;
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    } else {
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_product = function(id_product) {
        var complete = true;
        var array_lang = {};
        var name = $('#name').val();
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var price = $('#price').val();
        var description = window.description_editor.root.innerHTML;
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.description_editor_lang[lang].root.innerHTML;
            array_lang['description'][lang]=value;
        });
        var link = $('#link').val();
        var purchase_type = $('#type option:selected').attr('id').replace('t_','');
        var button_icon = $('#button_icon').val();
        var button_text = $('#button_text').val();
        array_lang['button_text'] = {};
        $('.input_lang[data-target-id="button_text"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['button_text'][lang]=value;
        });
        var button_background = $('#button_background').val();
        var button_color = $('#button_color').val();
        var custom_currency = $('#custom_currency').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var array_lang_json = JSON.stringify(array_lang);
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            $.ajax({
                url: "ajax/save_product.php",
                type: "POST",
                data: {
                    id: id_product,
                    name: name,
                    price: price,
                    description: description,
                    link: link,
                    purchase_type: purchase_type,
                    button_icon: button_icon,
                    button_text: button_text,
                    button_background: button_background,
                    button_color: button_color,
                    custom_currency: custom_currency,
                    array_lang: array_lang_json
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.product_need_save = false;
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    } else {
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.modal_delete_showcase = function(id) {
        $('#btn_delete_showcase').attr('onclick','delete_showcase(\''+id+'\');');
        $('#modal_delete_showcase').modal("show");
    }

    window.modal_delete_globe = function(id) {
        $('#btn_delete_globe').attr('onclick','delete_globe(\''+id+'\');');
        $('#modal_delete_globe').modal("show");
    }

    window.delete_showcase = function (id) {
        $('#modal_delete_showcase button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_showcase.php",
            type: "POST",
            data: {
                id_showcase: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_showcase button').removeClass("disabled");
                    $('#modal_delete_showcase').modal("hide");
                    location.href = 'index.php?p=showcases';
                } else {
                    $('#modal_delete_showcase button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_globe = function (id) {
        $('#modal_delete_globe button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_globe.php",
            type: "POST",
            data: {
                id_globe: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_globe button').removeClass("disabled");
                    $('#modal_delete_globe').modal("hide");
                    location.href = 'index.php?p=globes';
                } else {
                    $('#modal_delete_globe button').removeClass("disabled");
                }
            }
        });
    };

    window.modal_delete_advertisement = function(id) {
        $('#btn_delete_advertisement').attr('onclick','delete_advertisement(\''+id+'\');');
        $('#modal_delete_advertisement').modal("show");
    }

    window.delete_advertisement = function (id) {
        $('#modal_delete_advertisement button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_announce.php",
            type: "POST",
            data: {
                id_advertisement: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_advertisement button').removeClass("disabled");
                    $('#modal_delete_advertisement').modal("hide");
                    location.href = 'index.php?p=advertisements';
                } else {
                    $('#modal_delete_advertisement button').removeClass("disabled");
                }
            }
        });
    };

    window.modal_delete_product = function(id) {
        $('#btn_delete_product').attr('onclick','delete_product(\''+id+'\');');
        $('#modal_delete_product').modal("show");
    }

    window.delete_product = function (id) {
        $('#modal_delete_product button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_product.php",
            type: "POST",
            data: {
                id_product: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_product button').removeClass("disabled");
                    $('#modal_delete_product').modal("hide");
                    location.href = 'index.php?p=products';
                } else {
                    $('#modal_delete_product button').removeClass("disabled");
                }
            }
        });
    };

    window.modal_delete_video_project = function(id) {
        $('#btn_delete_video_project').attr('onclick','delete_video_project(\''+id+'\');');
        $('#modal_delete_video_project').modal("show");
    }

    window.delete_video_project = function (id) {
        $('#modal_delete_video_project button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_video_project.php",
            type: "POST",
            data: {
                id_video: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_video_project button').removeClass("disabled");
                    $('#modal_delete_video_project').modal("hide");
                    location.href = 'index.php?p=video';
                } else {
                    $('#modal_delete_video_project button').removeClass("disabled");
                }
            }
        });
    };

    window.modal_delete_user = function(id) {
        $('#btn_delete_user').attr('onclick','delete_user(\''+id+'\');');
        $('#modal_delete_user').modal("show");
    }

    window.delete_user = function (id) {
        var id_user_assign = $('#user_assign option:selected').attr('id');
        $('#modal_delete_user button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_user.php",
            type: "POST",
            data: {
                id_user: id,
                id_user_assign: id_user_assign
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_user button').removeClass("disabled");
                    $('#modal_delete_user').modal("hide");
                    location.href = 'index.php?p=users';
                } else {
                    $('#modal_delete_user button').removeClass("disabled");
                }
            }
        });
    };

    window.save_profile = function(complete_profile) {
        var complete = true;
        var username = $('#username').val();
        var email = $('#email').val();
        var avatar = $('#avatar_edit').attr('src');
        var language = $('#language option:selected').attr('id');
        var first_name = $('#first_name').val();
        var last_name = $('#last_name').val();
        var company = $('#company').val();
        var tax_id = $('#tax_id').val();
        var street = $('#street').val();
        var city = $('#city').val();
        var province = $('#province').val();
        var postal_code = $('#postal_code').val();
        var country = $('#country option:selected').val();
        var tel = $('#tel').val();
        if(username=='') {
            complete = false;
            $('#username').addClass("error-highlight");
        } else {
            $('#username').removeClass("error-highlight");
        }
        if(email=='') {
            complete = false;
            $('#email').addClass("error-highlight");
        } else {
            $('#email').removeClass("error-highlight");
        }
        if($('#first_name').attr('data-mandatory')=='true' && first_name=='') {
            complete = false;
            $('#first_name').addClass("error-highlight");
        } else {
            $('#first_name').removeClass("error-highlight");
        }
        if($('#last_name').attr('data-mandatory')=='true' && last_name=='') {
            complete = false;
            $('#last_name').addClass("error-highlight");
        } else {
            $('#last_name').removeClass("error-highlight");
        }
        if($('#company').attr('data-mandatory')=='true' && company=='') {
            complete = false;
            $('#company').addClass("error-highlight");
        } else {
            $('#company').removeClass("error-highlight");
        }
        if($('#tax_id').attr('data-mandatory')=='true' && tax_id=='') {
            complete = false;
            $('#tax_id').addClass("error-highlight");
        } else {
            $('#tax_id').removeClass("error-highlight");
        }
        if($('#street').attr('data-mandatory')=='true' && street=='') {
            complete = false;
            $('#street').addClass("error-highlight");
        } else {
            $('#street').removeClass("error-highlight");
        }
        if($('#city').attr('data-mandatory')=='true' && city=='') {
            complete = false;
            $('#city').addClass("error-highlight");
        } else {
            $('#city').removeClass("error-highlight");
        }
        if($('#province').attr('data-mandatory')=='true' && province=='') {
            complete = false;
            $('#province').addClass("error-highlight");
        } else {
            $('#province').removeClass("error-highlight");
        }
        if($('#postal_code').attr('data-mandatory')=='true' && postal_code=='') {
            complete = false;
            $('#postal_code').addClass("error-highlight");
        } else {
            $('#postal_code').removeClass("error-highlight");
        }
        if($('#country').attr('data-mandatory')=='true' && country=='') {
            complete = false;
            $('button[data-id="country"]').addClass("error-highlight");
        } else {
            $('button[data-id="country"]').removeClass("error-highlight");
        }
        if($('#tel').attr('data-mandatory')=='true' && tel=='') {
            complete = false;
            $('#tel').addClass("error-highlight");
        } else {
            $('#tel').removeClass("error-highlight");
        }
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            $('#btn_save_continue_profile').addClass('disabled');
            $.ajax({
                url: "ajax/save_profile.php",
                type: "POST",
                data: {
                    username_svt: username,
                    email_svt: email,
                    language_svt: language,
                    avatar_svt: avatar,
                    first_name: first_name,
                    last_name: last_name,
                    company: company,
                    tax_id: tax_id,
                    street: street,
                    city: city,
                    province: province,
                    postal_code: postal_code,
                    country: country,
                    tel: tel
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.user_need_save = false;
                        if(complete_profile) {
                            location.href = 'index.php';
                        } else {
                            $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                            setTimeout(function () {
                                $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                                $('#save_btn').removeClass("disabled");
                                if(rsp.reload_page==1) {
                                    location.href = 'index.php?p=edit_profile';
                                }
                            },200);
                        }
                    } else {
                        if(!complete_profile) {
                            alert(rsp.msg);
                            $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                            $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                            setTimeout(function () {
                                $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                                $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                                $('#save_btn').removeClass("disabled");
                            }, 1000);
                        } else {
                            $('#btn_save_continue_profile').removeClass('disabled');
                        }
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_room = function(goto,apply_preset_to_vt) {
        var complete = true;
        var array_lang = {};
        var name = $('#name').val();
        array_lang['name'] = {};
        $('.input_lang[data-target-id="name"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        var yaw_pitch = $('#yaw_pitch').val();
        var northOffset = $('#northOffset').val();
        var panorama_image = $('#panorama_image').attr('src');
        var allow_pitch = ($('#allow_pitch').is(':checked')) ? 1 : 0;
        var allow_hfov = ($('#allow_hfov').is(':checked')) ? 1 : 0;
        var visible = ($('#visible').is(':checked')) ? 1 : 0;
        var visible_list = ($('#visible_list').is(':checked')) ? 1 : 0;
        var show_nadir = ($('#show_nadir').is(':checked')) ? 1 : 0;
        var annotation_title = $('#annotation_title').val();
        array_lang['annotation_title'] = {};
        $('.input_lang[data-target-id="annotation_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['annotation_title'][lang]=value;
        });
        var annotation_description = $('#annotation_description').val();
        array_lang['annotation_description'] = {};
        $('.input_lang[data-target-id="annotation_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['annotation_description'][lang]=value;
        });
        var min_pitch = $('#min_pitch').val();
        var max_pitch = $('#max_pitch').val();
        var min_yaw = $('#min_yaw').val();
        var max_yaw = $('#max_yaw').val();
        var haov = $('#haov').val();
        var vaov = $('#vaov').val();
        var hfov = $('#hfov').val();
        var h_pitch = $('#h_pitch').val();
        var h_roll = $('#h_roll').val();
        var protect_type = $('#protect_type option:selected').attr('id');
        if(protect_type=='leads') {
            if(check_lead_params()==false) {
                alert(window.backend_labels.lead_params_error);
                return;
            }
        }
        var passcode_title = $('#passcode_title').val();
        array_lang['passcode_title'] = {};
        $('.input_lang[data-target-id="passcode_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['passcode_title'][lang]=value;
        });
        var passcode_description = $('#passcode_description').val();
        array_lang['passcode_description'] = {};
        $('.input_lang[data-target-id="passcode_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['passcode_description'][lang]=value;
        });
        var passcode = $('#passcode_code').val();
        var protect_mc_form = $('#protect_mc_form').val();
        var protect_lead_params = {};
        protect_lead_params['protect_name_enabled'] = ($('#protect_name_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_name_mandatory'] = ($('#protect_name_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_company_enabled'] = ($('#protect_company_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_company_mandatory'] = ($('#protect_company_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_email_enabled'] = ($('#protect_email_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_email_mandatory'] = ($('#protect_email_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_phone_enabled'] = ($('#protect_phone_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_phone_mandatory'] = ($('#protect_phone_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params = JSON.stringify(protect_lead_params);
        var transition_override = ($('#transition_override').is(':checked')) ? 1 : 0;
        var transition_time = $('#transition_time').val();
        var transition_fadeout = $('#transition_fadeout').val();
        var transition_zoom = $('#transition_zoom').val();
        var transition_effect = $('#transition_effect option:selected').attr('id');
        var transition_hfov = $('#transition_hfov').val();
        var transition_hfov_time = $('#transition_hfov_time').val();
        var autorotate_override = ($('#autorotate_override').is(':checked')) ? 1 : 0;
        var autorotate_speed = $('#autorotate_speed').val();
        var autorotate_inactivity = $('#autorotate_inactivity').val();
        var brightness = $('#brightness').val();
        var contrast = $('#contrast').val();
        var saturate = $('#saturate').val();
        var grayscale = $('#grayscale').val();
        var effect = $('#effect option:selected').attr('id');
        var main_view_tooltip = $('#main_view_tooltip').val();
        array_lang['main_view_tooltip'] = {};
        $('.input_lang[data-target-id="main_view_tooltip"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['main_view_tooltip'][lang]=value;
        });
        var protect_send_email = ($('#protect_send_email').is(':checked')) ? 1 : 0;
        var protect_email = $('#protect_email').val();
        var protect_lead_webhook_url = $('#protect_lead_webhook_url').val();
        var protect_remember = ($('#protect_remember').is(':checked')) ? 1 : 0;
        if(window.room_type=='video' || window.room_type=='hls') {
            var audio_track_enable = ($('#audio_track_enable').is(':checked')) ? 1 : 0;
            var song_loop = 0;
            var song_once = 0;
        } else {
            var audio_track_enable = 0;
            var song_loop = ($('#song_loop').is(':checked')) ? 1 : 0;
            var song_once = ($('#song_once').is(':checked')) ? 1 : 0;
        }
        if(window.room_type=='hls') {
            var panorama_url = $('#panorama_url').val();
        } else {
            var panorama_url = '';
        }
        var song_bg_volume = $('#song_bg_volume').val();
        var song_volume = $('#song_volume').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        var logo_height = $('#logo_height').val();
        if(window.room_type=='video') {
            var video_end_goto = $('#video_end_goto option:selected').attr('id');
        } else {
            var video_end_goto = 0;
        }
        var lp_duration = $('#lp_duration').val();
        var lp_fade = $('#lp_fade').val();
        var avatar_video_play_once = $('#avatar_video_play_once').is(':checked') ? 1 : 0;
        var avatar_video_autoplay = $('#avatar_video_autoplay').is(':checked') ? 1 : 0;
        var avatar_video_pause = $('#avatar_video_pause').is(':checked') ? 1 : 0;
        var avatar_video_hide_end = $('#avatar_video_hide_end').is(':checked') ? 1 : 0;
        var avatar_video = $('#avatar_video_content').val();
        array_lang['avatar_video'] = {};
        $('.input_lang[data-target-id="avatar_video_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['avatar_video'][lang]=value;
        });
        if($('#room_list_category').length) {
            var room_list_category = $('#room_list_category option:selected').attr('id');
        } else {
            var room_list_category = '';
        }
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            if(goto=='blur') {
                $('#btn_edit_blur').addClass("disabled");
            }
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/save_room.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    id_room: id_room,
                    name: name,
                    logo: window.logo,
                    logo_height: logo_height,
                    yaw_pitch: yaw_pitch,
                    northOffset: northOffset,
                    change_image: change_image,
                    change_image_st: change_image_st,
                    change_video: change_video,
                    change_json: change_json,
                    panorama_image_name: window.panorama_image_name,
                    panorama_image: (change_image==1 || change_video==1) ? panorama_image : '',
                    stereo_image: (change_image_st==1) ? stereo_image : '',
                    remove_image_st: window.remove_image_st,
                    panorama_video: panorama_video.replace('../viewer/videos/',''),
                    panorama_json: panorama_json.replace('../viewer/panoramas/',''),
                    panorama_url: panorama_url,
                    allow_pitch: allow_pitch,
                    allow_hfov: allow_hfov,
                    visible: visible,
                    visible_list: visible_list,
                    min_pitch: min_pitch,
                    max_pitch: max_pitch,
                    min_yaw: min_yaw,
                    max_yaw: max_yaw,
                    h_pitch: h_pitch,
                    h_roll: h_roll,
                    haov: haov,
                    vaov: vaov,
                    hfov: hfov,
                    audio_track_enable: audio_track_enable,
                    song_loop: song_loop,
                    song_once: song_once,
                    song: window.song,
                    song_bg_volume: song_bg_volume,
                    song_volume: song_volume,
                    annotation_title: annotation_title,
                    annotation_description: annotation_description,
                    protect_type: protect_type,
                    passcode_title: passcode_title,
                    passcode_description: passcode_description,
                    passcode: passcode,
                    protect_mc_form: protect_mc_form,
                    transition_time: transition_time,
                    transition_fadeout: transition_fadeout,
                    transition_zoom: transition_zoom,
                    transition_override: transition_override,
                    transition_effect: transition_effect,
                    transition_hfov: transition_hfov,
                    transition_hfov_time: transition_hfov_time,
                    autorotate_override: autorotate_override,
                    autorotate_speed: autorotate_speed,
                    autorotate_inactivity: autorotate_inactivity,
                    brightness: brightness,
                    contrast: contrast,
                    saturate: saturate,
                    grayscale: grayscale,
                    effect: effect,
                    thumb_image: window.thumb_image,
                    virtual_staging: window.virtual_staging,
                    main_view_tooltip: main_view_tooltip,
                    background_color: window.background_color,
                    apply_preset_to_vt: apply_preset_to_vt,
                    protect_send_email: protect_send_email,
                    protect_email: protect_email,
                    protect_lead_webhook_url: protect_lead_webhook_url,
                    protect_remember: protect_remember,
                    protect_lead_params: protect_lead_params,
                    video_end_goto: video_end_goto,
                    lp_duration: lp_duration,
                    lp_fade: lp_fade,
                    show_nadir: show_nadir,
                    array_lang: array_lang_json,
                    avatar_video: avatar_video,
                    avatar_video_play_once: avatar_video_play_once,
                    avatar_video_autoplay: avatar_video_autoplay,
                    avatar_video_pause: avatar_video_pause,
                    avatar_video_hide_end: avatar_video_hide_end,
                    room_list_category: room_list_category
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.room_need_save = false;
                        switch(goto) {
                            case 'blur':
                                window.change_image = 0;
                                window.change_video = 0;
                                location.href = 'index.php?p=edit_blur&id='+id_room;
                                break;
                            case 'enhance':
                                location.href = 'index.php?p=edit_room&id='+id_room;
                                break;
                            default:
                                if(window.change_image || window.change_video) {
                                    if(panorama_image!='') {
                                        if(panorama_image.includes('tmp_panoramas/')) {
                                            if(window.s3_enabled==1) {
                                                var new_pano_image = window.s3_url+"viewer/panoramas/"+panorama_image.replace('tmp_panoramas/',"");
                                            } else {
                                                var new_pano_image = "../viewer/panoramas/"+panorama_image.replace('tmp_panoramas/',"");
                                            }
                                            $('#panorama_image').attr('src',new_pano_image);
                                            $('#panorama_image').attr('data-src',new_pano_image);
                                        }
                                    }
                                }
                                window.change_image = 0;
                                window.change_video = 0;
                                if(apply_preset_to_vt) {
                                    $('#modal_apply_preset_tour button').removeClass('disabled');
                                    $('#modal_apply_preset_tour').modal('hide');
                                }
                                $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                                setTimeout(function () {
                                    $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                                    $('#save_btn').removeClass("disabled");
                                },1000);
                                break;
                        }
                    } else {
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.save_marker_pos = function(id_marker,yaw,pitch,rotateX,rotateZ,size_scale,scale,embed_coords,embed_size,embed_params,zIndex,visible_multiview_ids,sticky) {
        $.ajax({
            url: "ajax/save_marker_pos.php",
            type: "POST",
            data: {
                id: id_marker,
                yaw: yaw,
                pitch: pitch,
                rotateX: rotateX,
                rotateZ: rotateZ,
                size_scale: size_scale,
                scale: scale,
                embed_coords: embed_coords,
                embed_size: embed_size,
                embed_params: embed_params,
                zIndex: zIndex,
                visible_multiview_ids: visible_multiview_ids,
                sticky: sticky
            },
            async: true
        });
    }

    window.save_marker_style = function(id_marker,show_room,color,background,icon,id_icon_library,tooltip_type,tooltip_text,tooltip_text_mobile,css_class,embed_content,animation,icon_type,tooltip_visibility,tooltip_background,tooltip_color,sound,label,array_lang) {
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_marker_style.php",
            type: "POST",
            data: {
                id: id_marker,
                show_room: show_room,
                color: color,
                background: background,
                icon: icon,
                id_icon_library: id_icon_library,
                tooltip_type: tooltip_type,
                tooltip_visibility: tooltip_visibility,
                tooltip_background: tooltip_background,
                tooltip_color: tooltip_color,
                tooltip_text: tooltip_text,
                tooltip_text_mobile: tooltip_text_mobile,
                css_class: css_class,
                embed_content: embed_content,
                animation: animation,
                icon_type: icon_type,
                sound: sound,
                label: label,
                array_lang: array_lang_json
            },
            async: false
        });
    }

    window.save_measure = function(measure) {
        $.ajax({
            url: "ajax/save_measure.php",
            type: "POST",
            data: {
                measure: measure
            },
            async: true
        });
    }

    window.save_poi_pos = function(id_poi,yaw,pitch,rotateX,rotateZ,size_scale,embed_coords,embed_size,transform3d,scale,zindex,params,embed_params,visible_multiview_ids,sticky) {
        $.ajax({
            url: "ajax/save_poi_pos.php",
            type: "POST",
            data: {
                id: id_poi,
                yaw: yaw,
                pitch: pitch,
                rotateX: rotateX,
                rotateZ: rotateZ,
                size_scale: size_scale,
                embed_coords: embed_coords,
                embed_size: embed_size,
                transform3d: transform3d,
                scale: scale,
                zindex: zindex,
                params: params,
                embed_params: embed_params,
                visible_multiview_ids: visible_multiview_ids,
                sticky: sticky
            },
            async: true
        });
    }

    window.save_poi_style = function(id_poi,color,background,icon,style,id_icon_library,label,tooltip_type,tooltip_text,tooltip_text_mobile,css_class,embed_content,embed_video_autoplay,embed_video_loop,embed_video_muted,embed_gallery_autoplay,embed_type,animation,icon_type,embed_params,tooltip_visibility,tooltip_background,tooltip_color,sound,array_lang) {
        if(embed_type=='gallery') embed_content='';
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_poi_style.php",
            type: "POST",
            data: {
                id: id_poi,
                color: color,
                background: background,
                icon: icon,
                label: label,
                style: style,
                id_icon_library: id_icon_library,
                tooltip_type: tooltip_type,
                tooltip_visibility: tooltip_visibility,
                tooltip_background: tooltip_background,
                tooltip_color: tooltip_color,
                tooltip_text: tooltip_text,
                tooltip_text_mobile: tooltip_text_mobile,
                css_class: css_class,
                embed_content: embed_content,
                embed_video_autoplay: embed_video_autoplay,
                embed_video_loop: embed_video_loop,
                embed_video_muted: embed_video_muted,
                embed_gallery_autoplay: embed_gallery_autoplay,
                animation: animation,
                icon_type: icon_type,
                embed_params: embed_params,
                sound: sound,
                array_lang: array_lang_json
            },
            async: false
        });
    }

    window.save_poi_schedule = function(id_poi,schedule) {
        $.ajax({
            url: "ajax/save_poi_schedule.php",
            type: "POST",
            data: {
                id: id_poi,
                schedule: schedule
            },
            async: true
        });
    }

    window.save_poi_edit = function(id_poi,type,content,title,description,target,view_type,box_pos,box_max_width,box_maximize,song_bg_volume,params,auto_close,box_background,box_color,learning,learning_priority) {
        $.ajax({
            url: "ajax/save_poi_edit.php",
            type: "POST",
            data: {
                id: id_poi,
                type: type,
                content: content,
                title: title,
                description: description,
                target: target,
                id_room: window.id_room_sel,
                id_poi_autoopen: window.id_poi_autoopen,
                view_type: view_type,
                box_pos: box_pos,
                box_max_width: box_max_width,
                box_maximize: box_maximize,
                box_background: box_background,
                box_color: box_color,
                song_bg_volume: song_bg_volume,
                params: params,
                auto_close: auto_close,
                learning: learning,
                learning_priority: learning_priority
            },
            async: false
        });
    }

    window.save_marker_edit = function(id_marker,id_room_target,yaw,pitch,lookat,yaw_look_m,pitch_look_m,duration_look_m) {
        $.ajax({
            url: "ajax/save_marker_edit.php",
            type: "POST",
            data: {
                id: id_marker,
                id_room_target: id_room_target,
                yaw: yaw,
                pitch: pitch,
                lookat: lookat,
                yaw_look_m: yaw_look_m,
                pitch_look_m: pitch_look_m,
                duration_look_m: duration_look_m
            },
            async: false
        });
    }

    window.new_marker = function(id_room,image,id_room_target=0,yaw_drag=null,pitch_drag=null) {
        if(window.demo==1) return;
        if(id_room_target==0) {
            id_room_target = $('#room_target_add option:selected').attr('id');
        }
        $('#modal_add_marker button').prop("disabled",true);
        if(yaw_drag!=null && pitch_drag!=null) {
            var yaw = yaw_drag;
            var pitch = pitch_drag;
            try {
                var hfov = parseFloat(window.viewer.getHfov());
            } catch (e) {
                var hfov = 0;
            }
        } else {
            try {
                var yaw = parseFloat(window.viewer.getYaw());
                var pitch = parseFloat(window.viewer.getPitch());
                var hfov = parseFloat(window.viewer.getHfov());
            } catch (e) {
                var yaw = 0;
                var pitch = 0;
                var hfov = 0;
            }
        }
        var lookat = $('#lookat_add option:selected').attr('id');
        if($('#modal_add_marker').is(':visible')) {
            var backlink = $('#backlink_marker').is(':checked');
            if(backlink) backlink=1; else backlink=0;
            if(backlink==1) {
                var yaw_m = parseFloat(window.viewer_pos.getYaw());
                var pitch_m = parseFloat(window.viewer_pos.getPitch());
            }
            if($('#override_pos_add').is(':checked')) {
                var yaw_m = parseFloat(window.viewer_pos.getYaw());
                var pitch_m = parseFloat(window.viewer_pos.getPitch());
            } else {
                var yaw_m = '';
                var pitch_m = '';
            }
            if($('#override_look_add').is(':checked')) {
                var yaw_look_m = parseFloat(window.viewer_look.getYaw());
                var pitch_look_m = parseFloat(window.viewer_look.getPitch());
            } else {
                var yaw_look_m = '';
                var pitch_look_m = '';
            }
            var duration_look_m = $('#duration_look_add').val();
        } else {
            var backlink = 0;
            var yaw_m = '';
            var pitch_m = '';
            var duration_look_m = 2000;
        }
        if(yaw_drag!=null && pitch_drag!=null) {
            window.currentYaw = parseFloat(window.viewer.getYaw());
            window.currentPitch = parseFloat(window.viewer.getPitch());
            window.currentHfov = hfov;
        } else {
            window.currentYaw = yaw;
            window.currentPitch = pitch;
            window.currentHfov = hfov;
        }
        $.ajax({
            url: "ajax/add_marker.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: id_room,
                id_room_target: id_room_target,
                yaw: yaw,
                pitch: pitch,
                yaw_m: yaw_m,
                pitch_m: pitch_m,
                embed_type: window.embed_type_sel,
                lookat: lookat,
                backlink: backlink,
                yaw_look_m: yaw_look_m,
                pitch_look_m: pitch_look_m,
                duration_look_m: duration_look_m
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#modal_add_marker').modal("hide");
                    $('#modal_add_marker button').prop("disabled", false);
                    var count_item = parseInt($('#count_item_'+id_room).html());
                    const item = rs_items.find(item => item.id === parseInt(id_room));
                    count_item = count_item + 1;
                    $('#count_item_'+id_room).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    if(backlink) {
                        count_item = count_item + 1;
                        $('#count_item_'+id_room_target).html(count_item);
                        if (item) {
                            item.count = count_item;
                        }
                    }
                    if(yaw_drag!=null && pitch_drag!=null) {
                        select_room_marker(id_room,image,null);
                    } else {
                        select_room_marker(id_room,image,rsp.id);
                    }
                } else {
                    $('#modal_add_marker button').prop("disabled", false);
                }
            }
        });
    }

    window.new_poi = function(type) {
        var id_room = window.new_poi_id_room;
        var image = window.new_poi_image;
        $('#modal_add_poi button').prop("disabled",true);
        try {
            var yaw = parseFloat(window.viewer.getYaw());
            var pitch = parseFloat(window.viewer.getPitch());
            var hfov = parseFloat(window.viewer.getHfov());
        } catch (e) {
            var yaw = 0;
            var pitch = 0;
            var hfov = 0;
        }
        window.currentYaw = yaw;
        window.currentPitch = pitch;
        window.currentHfov = hfov;
        switch(window.embed_type_sel) {
            case 'callout':
                window.embed_type_sel='';
                type='callout';
                break;
            case 'grouped':
                window.embed_type_sel='';
                type='grouped';
                break;
        }
        $.ajax({
            url: "ajax/add_poi.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: id_room,
                yaw: yaw,
                pitch: pitch,
                type: type,
                embed_type: window.embed_type_sel
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#modal_add_poi').modal("hide");
                    $('#modal_add_poi button').prop("disabled", false);
                    var count_item = parseInt($('#count_item_'+id_room).html());
                    const item = rs_items.find(item => item.id === parseInt(id_room));
                    count_item = count_item + 1;
                    $('#count_item_'+id_room).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    select_room_poi(id_room,image,rsp.id);
                } else {
                    $('#modal_add_poi button').prop("disabled", false);
                }
            }
        });
    }

    window.add_measure = function(id_room,image) {
        $('#btn_add_measure').prop('disabled',true);
        try {
            var yaw = parseFloat(window.viewer.getYaw());
            var pitch = parseFloat(window.viewer.getPitch());
            var hfov = parseFloat(window.viewer.getHfov());
        } catch (e) {
            var yaw = 0;
            var pitch = 0;
            var hfov = 0;
        }
        window.currentYaw = yaw;
        window.currentPitch = pitch;
        window.currentHfov = hfov;
        $.ajax({
            url: "ajax/add_measure.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_room: id_room,
                yaw: yaw,
                pitch: pitch
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    var count_item = parseInt($('#count_item_'+id_room).html());
                    const item = rs_items.find(item => item.id === parseInt(id_room));
                    count_item = count_item + 1;
                    $('#count_item_'+id_room).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    select_room_measure(id_room,image,rsp.id);
                }
                $('#btn_add_measure').prop('disabled',false);
            }
        });
    }

    window.move_to_local = function(id_vt) {
        var html_btn = $('#btn_move_to_local').html();
        $('#btn_move_to_local').html("<i class='fas fa-circle-notch fa-spin'></i>");
        $('#modal_move_to_local button').addClass('disabled');
        $.ajax({
            url: "../services/move_vt_to_local.php",
            type: "POST",
            data: {
                id_virtualtour: id_vt
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#btn_move_to_local').html("<i class='fas fa-check'></i>");
                    location.reload();
                } else {
                    $('#modal_move_to_local button').removeClass('disabled');
                    $('#btn_move_to_local').html(html_btn);
                    alert(rsp.msg);
                }
            },
            error: function() {
                $('#modal_move_to_local button').removeClass('disabled');
                $('#btn_move_to_local').html(html_btn);
            }
        });
    }

    window.move_to_s3 = function(id_vt) {
        var html_btn = $('#btn_move_to_s3').html();
        $('#btn_move_to_s3').html("<i class='fas fa-circle-notch fa-spin'></i>");
        $('#modal_move_to_s3 button').addClass('disabled');
        $.ajax({
            url: "../services/move_vt_to_s3.php",
            type: "POST",
            data: {
                id_virtualtour: id_vt
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#btn_move_to_s3').html("<i class='fas fa-check'></i>");
                    location.reload();
                } else {
                    $('#modal_move_to_s3 button').removeClass('disabled');
                    $('#btn_move_to_s3').html(html_btn);
                    alert(rsp.msg);
                }
            },
            error: function() {
                $('#modal_move_to_s3 button').removeClass('disabled');
                $('#btn_move_to_s3').html(html_btn);
            }
        });
    }

    window.modal_delete_map = function(id) {
        var name_map = $('#map_name_'+id+' span').html();
        $('#name_map_delete').html(name_map);
        $('#btn_delete_map').attr('onclick','delete_map('+id+');');
        $('#modal_delete_map').modal("show");
    }

    window.modal_delete_virtualtour = function(id,gsv_published) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_delete').html(name_vt);
        $('#btn_delete_virtualtour').attr('onclick','delete_virtualtour('+id+');');
        if(parseInt(gsv_published)==2) {
            $('#modal_delete_virtualtour .gsv_delete_warning').show();
        } else {
            $('#modal_delete_virtualtour .gsv_delete_warning').hide();
        }
        $('#modal_delete_virtualtour').modal("show");
    }

    window.modal_lock_virtualtour = function(id) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_lock').html(name_vt);
        $('#btn_lock_virtualtour').attr('onclick','lock_virtualtour('+id+');');
        $('#modal_lock_virtualtour').modal("show");
    }

    window.modal_unlock_virtualtour = function(id) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_unlock').html(name_vt);
        $('#btn_unlock_virtualtour').attr('onclick','unlock_virtualtour('+id+');');
        $('#modal_unlock_virtualtour').modal("show");
    }

    window.modal_move_to_s3 = function(id) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_move_to_s3').html(name_vt);
        $('#btn_move_to_s3').attr('onclick','move_to_s3('+id+');');
        $('#modal_move_to_s3').modal("show");
    }

    window.modal_move_to_local = function(id) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_move_to_local').html(name_vt);
        $('#btn_move_to_local').attr('onclick','move_to_local('+id+');');
        $('#modal_move_to_local').modal("show");
    }

    window.modal_duplicate_virtualtour = function(id) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_duplicate').html(name_vt);
        $('#btn_duplicate_virtualtour').attr('onclick','duplicate_virtualtour('+id+');');
        $('#modal_duplicate_virtualtour').modal("show");
    }

    window.modal_duplicate_map = function(id) {
        var name_map = $('#map_name_'+id).html();
        $('#name_map_duplicate').html(name_map);
        $('#btn_duplicate_map').attr('onclick','duplicate_map('+id+');');
        $('#modal_duplicate_map').modal("show");
    }

    window.modal_export_virtualtour = function(id) {
        var name_vt = $('#vt_name_'+id).html();
        $('#name_vt_download').html(name_vt);
        $('#btn_export_virtualtour').attr('onclick','export_virtualtour('+id+');');
        $('#btn_export_virtualtour_vr').attr('onclick','export_virtualtour_vr('+id+');');
        $('#btn_export_virtualtour_b').attr('onclick','export_virtualtour_b('+id+');');
        $('#modal_export_virtualtour').modal("show");
    }

    window.modal_duplicate_room = function(id) {
        $('#btn_duplicate_room').attr('onclick','duplicate_room('+id+');');
        $('#modal_duplicate_room').modal("show");
    }

    window.modal_delete_room = function(id,gsv_published) {
        var name_room = $('#room_name_'+id).html();
        $('#name_room_delete').html(name_room);
        $('#btn_delete_room').attr('onclick','delete_room('+id+',false);');
        if(parseInt(gsv_published)==2) {
            $('#modal_delete_room .gsv_delete_warning').show();
        } else {
            $('#modal_delete_room .gsv_delete_warning').hide();
        }
        $('#modal_delete_room').modal("show");
    }

    window.modal_delete_marker = function(id,id_room,image) {
        $('#btn_delete_marker').attr('onclick','delete_marker('+id+','+id_room+',\''+image+'\')');
        $('#modal_delete_marker').modal("show");
    }

    window.modal_delete_poi = function(id,id_room,image) {
        $('#btn_delete_poi').attr('onclick','delete_poi('+id+','+id_room+',\''+image+'\')');
        $('#modal_delete_poi').modal("show");
    }

    window.modal_delete_measure = function(id,id_room,image) {
        $('#btn_delete_measure').attr('onclick','delete_measure('+id+','+id_room+',\''+image+'\')');
        $('#modal_delete_measure').modal("show");
    }

    window.modal_duplicate_poi = function(id,id_room) {
        get_option_rooms_duplicate('room_target',id_room);
        $('#btn_duplicate_poi').attr('onclick','duplicate_poi('+id+')');
        $('#modal_edit_poi').modal('hide');
        $('#modal_duplicate_poi').modal("show");
    }

    window.modal_duplicate_marker = function(id,id_room) {
        $('#btn_duplicate_marker').attr('onclick','duplicate_marker('+id+')');
        $('#modal_edit_marker').modal('hide');
        $('#modal_duplicate_marker').modal("show");
    }

    window.modal_delete_map_point = function(id) {
        $('#btn_delete_map_point').attr('onclick','delete_map_point('+id+');');
        $('#modal_delete_map_point').modal("show");
    }

    window.modal_delete_globe_point = function(id) {
        $('#btn_delete_globe_point').attr('onclick','delete_globe_point('+id+');');
        $('#modal_delete_globe_point').modal("show");
    }

    window.delete_virtualtour = function (id) {
        $('#modal_delete_virtualtour button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_virtual_tour.php",
            type: "POST",
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_virtualtour button').removeClass("disabled");
                    $('#modal_delete_virtualtour').modal("hide");
                    location.reload();
                } else {
                    $('#modal_delete_virtualtour button').removeClass("disabled");
                }
            },
            error: function() {
                $('#modal_delete_virtualtour button').removeClass("disabled");
            }
        });
    };

    window.lock_virtualtour = function (id) {
        $('#modal_lock_virtualtour button').addClass("disabled");
        var block_tour_msg = $('#block_tour_msg').val();
        $.ajax({
            url: "ajax/lock_virtual_tour.php",
            type: "POST",
            data: {
                id_virtualtour: id,
                block_tour_msg: block_tour_msg,
                lock: 1
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_lock_virtualtour button').removeClass("disabled");
                    $('#modal_lock_virtualtour').modal("hide");
                    location.reload();
                } else {
                    $('#modal_lock_virtualtour button').removeClass("disabled");
                }
            },
            error: function() {
                $('#modal_lock_virtualtour button').removeClass("disabled");
            }
        });
    };

    window.unlock_virtualtour = function (id) {
        $('#modal_unlock_virtualtour button').addClass("disabled");
        $.ajax({
            url: "ajax/lock_virtual_tour.php",
            type: "POST",
            data: {
                id_virtualtour: id,
                lock: 0
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_unlock_virtualtour button').removeClass("disabled");
                    $('#modal_unlock_virtualtour').modal("hide");
                    location.reload();
                } else {
                    $('#modal_unlock_virtualtour button').removeClass("disabled");
                }
            },
            error: function() {
                $('#modal_unlock_virtualtour button').removeClass("disabled");
            }
        });
    };

    window.import_tour = function (file_name,settings) {
        if(!settings) {
            $('#modal_import_tour .modal-footer .btn').addClass('disabled');
            var btn_html =  $('#btn_import_tour').html();
            $('#btn_import_tour').html('<i class="fas fa-circle-notch fa-spin"></i>');
        } else {
            $('#modal_import_tour').modal("show");
        }
        $.ajax({
            url: "../services/import_backend_vt.php",
            type: "POST",
            timeout: 300000,
            async: true,
            data: {
                file_name: file_name
            },
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    $('#modal_import_tour').modal('hide');
                    if(settings) {
                        get_import_files();
                    } else {
                        location.reload();
                    }
                } else {
                    if(!settings) {
                        $('#btn_import_tour').html(btn_html);
                        $('#modal_import_tour .modal-footer .btn').removeClass('disabled');
                    } else {
                        $('#modal_import_tour').modal("hide");
                    }
                    alert(rsp.msg);
                }
            },
            error: function () {
                if(!settings) {
                    $('#btn_import_tour').html(btn_html);
                    $('#modal_import_tour .modal-footer .btn').removeClass('disabled');
                } else {
                    $('#modal_import_tour').modal("hide");
                }
            }
        });
    }

    window.create_sample_tour = function () {
        $('#modal_sample_tour button').addClass("disabled");
        $('#btn_create_sample_tour').html('<i class="fas fa-circle-notch fa-spin"></i>');
        var name = $('#name').val();
        var author = $('#author').val();
        var id_vt_sample = $('#id_vt_sample option:selected').attr('id');
        $.ajax({
            url: "../services/create_sample_tour.php",
            type: "POST",
            timeout: 300000,
            async: true,
            data: {
                name: name,
                author: author,
                id_vt_sample: id_vt_sample
            },
            success: function (json) {
                var rsp = JSON.parse(json);
                $('#modal_sample_tour button').removeClass("disabled");
                $('#modal_sample_tour').modal("hide");
                $.ajax({
                    url: "ajax/send_email.php",
                    type: "POST",
                    data: {
                        type: 'vt_create',
                        id_user: id_user,
                        id_vt: rsp.id
                    },
                    timeout: 15000,
                    async: true,
                    success: function () {}
                });
                if(window.create_and_edit) {
                    if (rsp.id != "") {
                        location.href="index.php?p=edit_virtual_tour&id="+rsp.id;
                    } else {
                        location.reload();
                    }
                } else {
                    location.reload();
                }
            }
        });
    }

    window.change_vt_type = function () {
        var vt_type = $('#vt_type option:selected').attr("id");
        switch(vt_type) {
            case '0':
                $('#sample_data').removeClass("disabled");
                break;
            case '1':
            case '2':
                $('#sample_data').addClass("disabled");
                break;
        }
    }

    window.duplicate_virtualtour = function (id) {
        $('#modal_duplicate_virtualtour button').addClass("disabled");
        var html_btn = $('#btn_duplicate_virtualtour').html();
        $('#btn_duplicate_virtualtour').html('<i class="fas fa-circle-notch fa-spin"></i>');
        var duplicate_info_box = $('#duplicate_info_box').is(':checked')?1:0;
        var duplicate_maps = $('#duplicate_maps').is(':checked')?1:0;
        var duplicate_gallery = $('#duplicate_gallery').is(':checked')?1:0;
        var duplicate_presentation = $('#duplicate_presentation').is(':checked')?1:0;
        var duplicate_rooms = $('#duplicate_rooms').is(':checked')?1:0;
        var duplicate_markers = $('#duplicate_markers').is(':checked')?1:0;
        var duplicate_pois = $('#duplicate_pois').is(':checked')?1:0;
        var duplicate_products = $('#duplicate_products').is(':checked')?1:0;
        $.ajax({
            url: "ajax/duplicate_virtual_tour.php",
            type: "POST",
            timeout: 300000,
            data: {
                id_user: window.id_user,
                id_virtualtour: id,
                duplicate_info_box: duplicate_info_box,
                duplicate_maps: duplicate_maps,
                duplicate_gallery: duplicate_gallery,
                duplicate_presentation: duplicate_presentation,
                duplicate_rooms: duplicate_rooms,
                duplicate_markers: duplicate_markers,
                duplicate_pois: duplicate_pois,
                duplicate_products: duplicate_products
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $.ajax({
                        url: "ajax/send_email.php",
                        type: "POST",
                        data: {
                            type: 'vt_create',
                            id_user: window.id_user,
                            id_vt: rsp.id
                        },
                        timeout: 15000,
                        async: true,
                        success: function () {}
                    });
                    $('#modal_duplicate_virtualtour button').removeClass("disabled");
                    $('#modal_duplicate_virtualtour').modal("hide");
                    location.reload();
                } else {
                    $('#btn_duplicate_virtualtour').html(html_btn);
                    $('#modal_duplicate_virtualtour button').removeClass("disabled");
                }
            }
        });
    };

    window.duplicate_map = function (id) {
        $('#modal_duplicate_map button').addClass("disabled");
        var html_btn = $('#btn_duplicate_map').html();
        $('#btn_duplicate_map').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "ajax/duplicate_map.php",
            type: "POST",
            timeout: 300000,
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour,
                id_map: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_duplicate_map button').removeClass("disabled");
                    $('#modal_duplicate_map').modal("hide");
                    location.reload();
                } else {
                    $('#btn_duplicate_map').html(html_btn);
                    $('#modal_duplicate_map button').removeClass("disabled");
                }
            }
        });
    };

    window.export_virtualtour = function (id) {
        $('#modal_export_virtualtour button').addClass("disabled");
        var html_btn = $('#btn_export_virtualtour').html();
        $('#btn_export_virtualtour').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "../services/export_vt.php",
            type: "POST",
            timeout: 300000,
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                $('#btn_export_virtualtour').html(html_btn);
                $('#modal_export_virtualtour button').removeClass("disabled");
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_export_virtualtour').modal("hide");
                    var zip = rsp.zip;
                    var url="../services/export_tmp/"+zip;
                    window.open(url, '_self');
                } else {
                    alert(rsp.msg);
                }
            },
            error: function () {
                $('#btn_export_virtualtour').html(html_btn);
                $('#modal_export_virtualtour button').removeClass("disabled");
            }
        });
    };

    window.export_virtualtour_vr = function (id) {
        $('#modal_export_virtualtour button').addClass("disabled");
        var html_btn = $('#btn_export_virtualtour_vr').html();
        $('#btn_export_virtualtour_vr').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "../services/export_vt_vr.php",
            type: "POST",
            timeout: 300000,
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                $('#btn_export_virtualtour_vr').html(html_btn);
                $('#modal_export_virtualtour button').removeClass("disabled");
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_export_virtualtour').modal("hide");
                    var zip = rsp.zip;
                    var url="../services/export_tmp/"+zip;
                    window.open(url, '_self');
                } else {
                    alert(rsp.msg);
                }
            },
            error: function () {
                $('#btn_export_virtualtour_vr').html(html_btn);
                $('#modal_export_virtualtour button').removeClass("disabled");
            }
        });
    };

    window.export_virtualtour_b = function (id) {
        $('#modal_export_virtualtour button').addClass("disabled");
        var html_btn = $('#btn_export_virtualtour_b').html();
        $('#btn_export_virtualtour_b').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            url: "../services/export_backend_vt.php",
            type: "POST",
            timeout: 300000,
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                $('#btn_export_virtualtour_b').html(html_btn);
                $('#modal_export_virtualtour button').removeClass("disabled");
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_export_virtualtour').modal("hide");
                    var zip = rsp.zip;
                    var url="../services/export_tmp/"+zip;
                    window.open(url, '_self');
                } else {
                    alert(rsp.msg);
                }
            },
            error: function () {
                $('#btn_export_virtualtour_b').html(html_btn);
                $('#modal_export_virtualtour button').removeClass("disabled");
            }
        });
    };

    window.duplicate_room = function (id) {
        $('#modal_duplicate_room button').addClass("disabled");
        var html_btn = $('#btn_duplicate_room').html();
        $('#btn_duplicate_room').html('<i class="fas fa-circle-notch fa-spin"></i>');
        var duplicate_pois = $('#duplicate_pois').is(':checked')?1:0;
        var duplicate_markers = $('#duplicate_markers').is(':checked')?1:0;
        var duplicate_target_vt = $('#duplicate_target_vt option:selected').attr('id');
        $.ajax({
            url: "ajax/duplicate_room.php",
            type: "POST",
            timeout: 300000,
            data: {
                id_room: id,
                duplicate_pois: duplicate_pois,
                duplicate_markers: duplicate_markers,
                duplicate_target_vt: duplicate_target_vt
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_duplicate_room button').removeClass("disabled");
                    $('#modal_duplicate_room').modal("hide");
                    location.reload();
                } else {
                    $('#btn_duplicate_room').html(html_btn);
                    $('#modal_duplicate_room button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_room = function (id,inside) {
        $('#modal_delete_room button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_room.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_room: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_room button').removeClass("disabled");
                    $('#modal_delete_room').modal("hide");
                    if(inside) {
                        location.href = 'index.php?p=rooms';
                    } else {
                        location.reload();
                    }
                } else {
                    $('#modal_delete_room button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_marker = function (id,id_room,image) {
        $('#modal_delete_marker button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_marker.php",
            type: "POST",
            data: {
                id_marker: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_marker button').removeClass("disabled");
                    $('#modal_delete_marker').modal("hide");
                    var count_item = parseInt($('#count_item_'+id_room).html());
                    const item = rs_items.find(item => item.id === parseInt(id_room));
                    count_item = count_item - 1;
                    $('#count_item_'+id_room).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    try {
                        var yaw = parseFloat(window.viewer.getYaw());
                        var pitch = parseFloat(window.viewer.getPitch());
                        var hfov = parseFloat(window.viewer.getHfov());
                    } catch (e) {
                        var yaw = 0;
                        var pitch = 0;
                        var hfov = 0;
                    }
                    window.currentYaw = yaw;
                    window.currentPitch = pitch;
                    window.currentHfov = hfov;
                    select_room_marker(id_room,image,null);
                } else {
                    $('#modal_delete_marker button').removeClass("disabled");
                }
            }
        });
    };

    window.change_poi_room_target = function() {
        var array_id_sel = $('#room_target').val();
        if(array_id_sel.length==0) {
            $('#btn_duplicate_poi').addClass('disabled');
        } else {
            $('#btn_duplicate_poi').removeClass('disabled');
            if(array_id_sel.length>1) {
                $('#duplicate_goto').prop('disabled',true);
            } else {
                $('#duplicate_goto').prop('disabled',false);
            }
        }
    }

    window.duplicate_poi = function (id) {
        $('#modal_duplicate_poi button').addClass("disabled");
        var id_room_targets = $('#room_target').val();
        $.ajax({
            url: "ajax/duplicate_poi.php",
            type: "POST",
            data: {
                id_poi: id,
                id_room_sel: window.id_room_sel,
                id_room_target: id_room_targets
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_duplicate_poi button').removeClass("disabled");
                    $('#modal_duplicate_poi').modal("hide");
                    $.each(id_room_targets,function(index_t,id_room_target) {
                        var count_item = parseInt($('#count_item_'+window.id_room_sel).html());
                        const item = rs_items.find(item => item.id === parseInt(window.id_room_sel));
                        count_item = count_item + 1;
                        $('#count_item_'+window.id_room_sel).html(count_item);
                        if (item) {
                            item.count = count_item;
                        }
                    });
                    if($('#duplicate_goto').is(':checked') && id_room_targets.length==1) {
                        try {
                            var yaw = parseFloat(window.viewer.getYaw());
                            var pitch = parseFloat(window.viewer.getPitch());
                            var hfov = parseFloat(window.viewer.getHfov());
                        } catch (e) {
                            var yaw = 0;
                            var pitch = 0;
                            var hfov = 0;
                        }
                        window.currentYaw = yaw;
                        window.currentPitch = pitch;
                        window.currentHfov = hfov;
                        var image = $('#room_target option:selected').attr('data-image');
                        select_room_poi(id_room_targets[0],image,rsp.id);
                    } else {
                        select_room_poi(window.id_room_sel,window.image_room_sel,rsp.id);
                    }
                } else {
                    $('#modal_duplicate_poi button').removeClass("disabled");
                }
            }
        });
    }

    window.duplicate_marker = function (id) {
        $('#modal_duplicate_marker button').addClass("disabled");
        $.ajax({
            url: "ajax/duplicate_marker.php",
            type: "POST",
            data: {
                id_marker: id,
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    var count_item = parseInt($('#count_item_'+window.id_room_sel).html());
                    const item = rs_items.find(item => item.id === parseInt(window.id_room_sel));
                    count_item = count_item + 1;
                    $('#count_item_'+window.id_room_sel).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    $('#modal_duplicate_marker button').removeClass("disabled");
                    $('#modal_duplicate_marker').modal("hide");
                    select_room_marker(window.id_room_sel, window.image_room_sel, rsp.id);
                }
            }
        });
    }

    window.delete_poi = function (id,id_room,image) {
        $('#modal_delete_poi button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_poi.php",
            type: "POST",
            data: {
                id_poi: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_poi button').removeClass("disabled");
                    $('#modal_delete_poi').modal("hide");
                    var count_item = parseInt($('#count_item_'+id_room).html());
                    const item = rs_items.find(item => item.id === parseInt(id_room));
                    count_item = count_item - 1;
                    $('#count_item_'+id_room).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    try {
                        var yaw = parseFloat(window.viewer.getYaw());
                        var pitch = parseFloat(window.viewer.getPitch());
                        var hfov = parseFloat(window.viewer.getHfov());
                    } catch (e) {
                        var yaw = 0;
                        var pitch = 0;
                        var hfov = 0;
                    }
                    window.currentYaw = yaw;
                    window.currentPitch = pitch;
                    window.currentHfov = hfov;
                    select_room_poi(id_room,image,null);
                } else {
                    $('#modal_delete_poi button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_measure = function (id,id_room,image) {
        $('#modal_delete_measure button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_measure.php",
            type: "POST",
            data: {
                id_measure: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_measure button').removeClass("disabled");
                    $('#modal_delete_measure').modal("hide");
                    var count_item = parseInt($('#count_item_'+id_room).html());
                    const item = rs_items.find(item => item.id === parseInt(id_room));
                    count_item = count_item - 1;
                    $('#count_item_'+id_room).html(count_item);
                    if (item) {
                        item.count = count_item;
                    }
                    try {
                        var yaw = parseFloat(window.viewer.getYaw());
                        var pitch = parseFloat(window.viewer.getPitch());
                        var hfov = parseFloat(window.viewer.getHfov());
                    } catch (e) {
                        var yaw = 0;
                        var pitch = 0;
                        var hfov = 0;
                    }
                    window.currentYaw = yaw;
                    window.currentPitch = pitch;
                    window.currentHfov = hfov;
                    select_room_measure(id_room,image,null);
                } else {
                    $('#modal_delete_measure button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_map_point = function (id) {
        $('#modal_delete_map_point button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_map_point.php",
            type: "POST",
            data: {
                id_room: id,
                map_type: window.map_type
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_map_point button').removeClass("disabled");
                    $('#modal_delete_map_point').modal("hide");
                    sessionStorage.setItem('add_point','1');
                    window.id_room_point_sel = '';
                    window.id_room_sel = '';
                    save_map_settings(true);
                } else {
                    $('#modal_delete_map_point button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_globe_point = function (id) {
        $('#modal_delete_globe_point button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_globe_point.php",
            type: "POST",
            data: {
                id_vt: id,
                id_globe: id_globe
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_globe_point button').removeClass("disabled");
                    $('#modal_delete_globe_point').modal("hide");
                    sessionStorage.setItem('add_point','1');
                    window.id_vt_point_sel = '';
                    window.id_vt_sel = '';
                    save_globe(window.id_globe,true);
                } else {
                    $('#modal_delete_globe_point button').removeClass("disabled");
                }
            }
        });
    };

    window.delete_map = function (id_map) {
        $('#modal_delete_map button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_map.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                id_map: id_map
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_map button').removeClass("disabled");
                    $('#modal_delete_map').modal("hide");
                    location.reload();
                } else {
                    $('#modal_delete_map button').removeClass("disabled");
                }
            }
        });
    };

    window.change_exist_logo = function() {
        var logo = $('#exist_logo option:selected').attr('id');
        if(logo==0) {
            window.logo = '';
            window.vt_need_save = true;
            $('#div_delete_logo').hide();
            $('#div_image_logo').hide();
            $('#div_upload_logo').show();
            $('#div_exist_logo').show();
            $('#div_image_logo img').attr('src','');
        } else {
            window.logo = logo;
            window.vt_need_save = true;
            $('#div_delete_logo').hide();
            $('#div_image_logo').show();
            $('#div_upload_logo').hide();
            $('#div_exist_logo').show();
            if(window.s3_enabled==1) {
                $('#div_image_logo img').attr('src',window.s3_url+'viewer/content/'+logo);
            } else {
                $('#div_image_logo img').attr('src','../viewer/content/'+logo);
            }
        }
    }

    window.change_poweredby_type = function() {
        var poweredby_type = $('#poweredby_type option:selected').attr('id');
        switch(poweredby_type) {
            case 'image':
                $('#poweredby_type_text').hide();
                $('#poweredby_type_image').show();
                break;
            case 'text':
                $('#poweredby_type_text').show();
                $('#poweredby_type_image').hide();
                break;
        }
    }

    window.change_exist_poweredby = function() {
        var poweredby = $('#exist_poweredby option:selected').attr('id');
        if(poweredby==0) {
            window.poweredby_image = '';
            window.vt_need_save = true;
            $('#div_delete_poweredby').hide();
            $('#div_image_poweredby').hide();
            $('#div_upload_poweredby').show();
            $('#div_exist_poweredby').show();
            $('#div_image_poweredby img').attr('src','');
        } else {
            window.poweredby_image = poweredby;
            window.vt_need_save = true;
            $('#div_delete_poweredby').hide();
            $('#div_image_poweredby').show();
            $('#div_upload_poweredby').hide();
            $('#div_exist_poweredby').show();
            if(window.s3_enabled==1) {
                $('#div_image_poweredby img').attr('src',window.s3_url+'viewer/content/'+poweredby);
            } else {
                $('#div_image_poweredby img').attr('src','../viewer/content/'+poweredby);
            }
        }
    }

    window.change_exist_media = function(lang) {
        if($('#div_delete_media').is(':visible')) {
            return;
        }
        if(lang=='') {
            var media_file = $('#exist_media option:selected').attr('id');
            if(media_file==0) {
                window.media_file = '';
                window.vt_need_save = true;
                $('#div_delete_media').hide();
                $('#div_image_media').hide();
                $('#div_upload_media').show();
                $('#div_exist_media').show();
                $('#div_image_media img').attr('src','');
            } else {
                window.media_file = media_file;
                window.vt_need_save = true;
                $('#div_delete_media').hide();
                $('#div_image_media').show();
                $('#div_upload_media').hide();
                $('#div_exist_media').show();
                if(window.s3_enabled==1) {
                    $('#div_image_media img').attr('src',window.s3_url+'viewer/content/'+media_file);
                } else {
                    $('#div_image_media img').attr('src','../viewer/content/'+media_file);
                }
            }
        } else {
            var media_file = $('#exist_media_'+lang+' option:selected').attr('id');
            if(media_file==0) {
                window.media_file_langs[lang] = '';
                window.vt_need_save = true;
                $('#div_delete_media').hide();
                $('#div_image_media_'+lang).hide();
                $('#div_upload_media').show();
                $('#div_exist_media_'+lang).show();
                $('#div_image_media_'+lang+' img').attr('src','');
            } else {
                window.media_file_langs[lang] = media_file;
                window.vt_need_save = true;
                $('#div_delete_media').hide();
                $('#div_image_media_'+lang).show();
                $('#div_upload_media').hide();
                $('#div_exist_media_'+lang).show();
                if(window.s3_enabled==1) {
                    $('#div_image_media_'+lang+' img').attr('src',window.s3_url+'viewer/content/'+media_file);
                } else {
                    $('#div_image_media_'+lang+' img').attr('src','../viewer/content/'+media_file);
                }
            }
        }
    }

    window.change_exist_introd = function(lang) {
        if($('#div_delete_introd').is(':visible')) {
            return;
        }
        if(lang=='') {
            var introd_file = $('#exist_introd option:selected').attr('id');
            if(introd_file==0) {
                window.intro_desktop = '';
                window.vt_need_save = true;
                $('#div_delete_introd').hide();
                $('#div_image_introd').hide();
                $('#div_upload_introd').show();
                $('#div_exist_introd').show();
                $('#div_image_introd img').attr('src','');
            } else {
                window.intro_desktop = introd_file;
                window.vt_need_save = true;
                $('#div_delete_introd').hide();
                $('#div_image_introd').show();
                $('#div_upload_introd').hide();
                $('#div_exist_introd').show();
                if(window.s3_enabled==1) {
                    $('#div_image_introd img').attr('src',window.s3_url+'viewer/content/'+introd_file);
                } else {
                    $('#div_image_introd img').attr('src','../viewer/content/'+introd_file);
                }
            }
        } else {
            var introd_file = $('#exist_introd_'+lang+' option:selected').attr('id');
            if(introd_file==0) {
                window.introd_file_langs[lang] = '';
                window.vt_need_save = true;
                $('#div_delete_introd').hide();
                $('#div_image_introd_'+lang).hide();
                $('#div_upload_introd').show();
                $('#div_exist_introd_'+lang).show();
                $('#div_image_introd_'+lang+' img').attr('src','');
            } else {
                window.introd_file_langs[lang] = introd_file;
                window.vt_need_save = true;
                $('#div_delete_introd').hide();
                $('#div_image_introd_'+lang).show();
                $('#div_upload_introd').hide();
                $('#div_exist_introd_'+lang).show();
                if(window.s3_enabled==1) {
                    $('#div_image_introd_'+lang+' img').attr('src',window.s3_url+'viewer/content/'+introd_file);
                } else {
                    $('#div_image_introd_'+lang+' img').attr('src','../viewer/content/'+introd_file);
                }
            }
        }
    }

    window.change_exist_introm = function(lang) {
        if($('#div_delete_introm').is(':visible')) {
            return;
        }
        if(lang=='') {
            var introm_file = $('#exist_introm option:selected').attr('id');
            if(introm_file==0) {
                window.intro_mobile = '';
                window.vt_need_save = true;
                $('#div_delete_introm').hide();
                $('#div_image_introm').hide();
                $('#div_upload_introm').show();
                $('#div_exist_introm').show();
                $('#div_image_introm img').attr('src','');
            } else {
                window.intro_mobile = introm_file;
                window.vt_need_save = true;
                $('#div_delete_introm').hide();
                $('#div_image_introm').show();
                $('#div_upload_introm').hide();
                $('#div_exist_introm').show();
                if(window.s3_enabled==1) {
                    $('#div_image_introm img').attr('src',window.s3_url+'viewer/content/'+introm_file);
                } else {
                    $('#div_image_introm img').attr('src','../viewer/content/'+introm_file);
                }
            }
        } else {
            var introm_file = $('#exist_introm_'+lang+' option:selected').attr('id');
            if(introm_file==0) {
                window.introm_file_langs[lang] = '';
                window.vt_need_save = true;
                $('#div_delete_introm').hide();
                $('#div_image_introm_'+lang).hide();
                $('#div_upload_introm').show();
                $('#div_exist_introm_'+lang).show();
                $('#div_image_introm_'+lang+' img').attr('src','');
            } else {
                window.introm_file_langs[lang] = introm_file;
                window.vt_need_save = true;
                $('#div_delete_introm').hide();
                $('#div_image_introm_'+lang).show();
                $('#div_upload_introm').hide();
                $('#div_exist_introm_'+lang).show();
                if(window.s3_enabled==1) {
                    $('#div_image_introm_'+lang+' img').attr('src',window.s3_url+'viewer/content/'+introm_file);
                } else {
                    $('#div_image_introm_'+lang+' img').attr('src','../viewer/content/'+introm_file);
                }
            }
        }
    }

    window.change_exist_bg = function() {
        var logo = $('#exist_bg option:selected').attr('id');
        if(logo==0) {
            window.background_image = '';
            window.vt_need_save = true;
            $('#div_delete_bg').hide();
            $('#div_image_bg').hide();
            $('#div_upload_bg').show();
            $('#div_exist_bg').show();
            $('#div_image_bg img').attr('src','');
        } else {
            window.background_image = logo;
            window.vt_need_save = true;
            $('#div_delete_bg').hide();
            $('#div_image_bg').show();
            $('#div_upload_bg').hide();
            $('#div_exist_bg').show();
            if(window.s3_enabled==1) {
                $('#div_image_bg img').attr('src',window.s3_url+'viewer/content/'+logo);
            } else {
                $('#div_image_bg img').attr('src','../viewer/content/'+logo);
            }
        }
    }

    window.change_exist_bg_m = function() {
        var logo = $('#exist_bg_m option:selected').attr('id');
        if(logo==0) {
            window.background_image_mobile = '';
            window.vt_need_save = true;
            $('#div_delete_bg_m').hide();
            $('#div_image_bg_m').hide();
            $('#div_upload_bg_m').show();
            $('#div_exist_bg_m').show();
            $('#div_image_bg_m img').attr('src','');
        } else {
            window.background_image_mobile = logo;
            window.vt_need_save = true;
            $('#div_delete_bg_m').hide();
            $('#div_image_bg_m').show();
            $('#div_upload_bg_m').hide();
            $('#div_exist_bg_m').show();
            if(window.s3_enabled==1) {
                $('#div_image_bg_m img').attr('src',window.s3_url+'viewer/content/'+logo);
            } else {
                $('#div_image_bg_m img').attr('src','../viewer/content/'+logo);
            }
        }
    }

    window.change_exist_video_bg = function() {
        var video = $('#exist_video_bg option:selected').attr('id');
        if(video==0) {
            window.background_video = '';
            window.vt_need_save = true;
            $('#div_delete_video_bg').hide();
            $('#div_video_bg').hide();
            $('#div_video_params').hide();
            $('#div_upload_video_bg').show();
            $('#div_exist_video_bg').show();
            $('#div_video_bg video source').attr('src','');
            $('#div_video_bg video').get(0).load();
            $('#background_video_delay').prop('disabled',true);
        } else {
            window.background_video = video;
            window.vt_need_save = true;
            $('#div_delete_video_bg').hide();
            $('#div_video_bg').show();
            $('#div_video_params').show();
            $('#div_upload_video_bg').hide();
            $('#div_exist_video_bg').show();
            if(window.s3_enabled==1) {
                $('#div_video_bg video source').attr('src',window.s3_url+'viewer/content/'+video+'#t=2');
            } else {
                $('#div_video_bg video source').attr('src','../viewer/content/'+video+'#t=2');
            }
            $('#div_video_bg video').get(0).load();
            $('#background_video_delay').prop('disabled',false);
        }
    }

    window.change_exist_video_bg_m = function() {
        var video = $('#exist_video_bg_m option:selected').attr('id');
        if(video==0) {
            window.background_video_mobile = '';
            window.vt_need_save = true;
            $('#div_delete_video_bg_m').hide();
            $('#div_video_bg_m').hide();
            $('#div_video_m_params').hide();
            $('#div_upload_video_bg_m').show();
            $('#div_exist_video_bg_m').show();
            $('#div_video_bg_m video source').attr('src','');
            $('#div_video_bg_m video').get(0).load();
            $('#background_video_delay_m').prop('disabled',true);
        } else {
            window.background_video_mobile = video;
            window.vt_need_save = true;
            $('#div_delete_video_bg_m').hide();
            $('#div_video_bg_m').show();
            $('#div_video_m_params').show();
            $('#div_upload_video_bg_m').hide();
            $('#div_exist_video_bg_m').show();
            if(window.s3_enabled==1) {
                $('#div_video_bg_m video source').attr('src',window.s3_url+'viewer/content/'+video+'#t=2');
            } else {
                $('#div_video_bg_m video source').attr('src','../viewer/content/'+video+'#t=2');
            }
            $('#div_video_bg_m video').get(0).load();
            $('#background_video_delay_m').prop('disabled',false);
        }
    }

    window.change_exist_nadir_logo = function() {
        var logo = $('#exist_nadir_logo option:selected').attr('id');
        if(logo==0) {
            window.nadir_logo = '';
            window.vt_need_save = true;
            $('#div_delete_nadir_logo').hide();
            $('#div_image_nadir_logo').hide();
            $('#div_upload_nadir_logo').show();
            $('#div_exist_nadir_logo').show();
            $('#div_size_nadir_logo').hide();
            $('#div_image_nadir_logo img').attr('src','');
        } else {
            window.nadir_logo = logo;
            window.vt_need_save = true;
            $('#div_delete_nadir_logo').hide();
            $('#div_image_nadir_logo').show();
            $('#div_upload_nadir_logo').hide();
            $('#div_exist_nadir_logo').show();
            $('#div_size_nadir_logo').show();
            if(window.s3_enabled==1) {
                $('#div_image_nadir_logo img').attr('src',window.s3_url+'viewer/content/'+logo);
            } else {
                $('#div_image_nadir_logo img').attr('src','../viewer/content/'+logo);
            }
        }
    }

    window.change_exist_song = function() {
        var song = $('#exist_song option:selected').attr('id');
        if(song==0) {
            window.song = '';
            window.vt_need_save = true;
            $('#div_delete_song').hide();
            $('#div_player_song').hide();
            $('#div_upload_song').show();
            $('#div_exist_song').show();
            $('#div_player_song audio').attr('src','');
        } else {
            window.song = song;
            window.vt_need_save = true;
            $('#div_delete_song').hide();
            $('#div_player_song').show();
            $('#div_upload_song').hide();
            $('#div_exist_song').show();
            if(window.s3_enabled==1) {
                $('#div_player_song audio').attr('src',window.s3_url+'viewer/content/'+song);
            } else {
                $('#div_player_song audio').attr('src','../viewer/content/'+song);
            }
        }
    }

    window.change_slideshow_audio = function() {
        $('#btn_sync_audio').addClass('disabled');
        var song = $('#s_audio option:selected').attr('id');
        if(song==0) {
            $('#div_player_s_audio').hide();
            $('#div_player_s_audio audio').attr('src','');
            window.audio_duration = 0;
        } else {
            $('#div_player_s_audio').show();
            if(window.s3_enabled==1) {
                var audio_url = window.s3_url+'viewer/content/'+song;
            } else {
                var audio_url = '../viewer/content/'+song;
            }
            $('#div_player_s_audio audio').attr('src',audio_url);
            getAudioDuration(audio_url, function(length) {
                window.audio_duration = length.toFixed(0);
                $('#btn_sync_audio').removeClass('disabled');
            });
        }
    }

    function getAudioDuration(src, cb) {
        var audio = document.createElement('audio');
        audio.addEventListener("loadedmetadata", function(){
            cb(audio.duration);
        });
        audio.src = src;
        audio.crossOrigin = false;
    }

    window.delete_song = function() {
        window.song = '';
        window.vt_need_save = true;
        $('#div_delete_song').hide();
        $('#div_player_song').hide();
        $('#div_upload_song').show();
        $('#div_exist_song').show();
        $('#div_player_song audio').attr('src','');
    }

    window.delete_room_song = function() {
        window.song = '';
        window.room_need_save = true;
        $('#div_delete_song').hide();
        $('#div_player_song').hide();
        $('#div_upload_song').show();
        $('#div_exist_song').show();
        $('#div_player_song audio').attr('src','');
    }

    window.delete_logo = function () {
        window.logo = '';
        window.vt_need_save = true;
        $('#div_delete_logo').hide();
        $('#div_image_logo').hide();
        $('#div_upload_logo').show();
        $('#div_exist_logo').show();
        $('#div_image_logo img').attr('src','');
    }

    window.delete_introd = function () {
        if($('#div_image_introd').css('display')=='block') {
            window.intro_desktop = '';
            $('#div_delete_introd').hide();
            $('#div_image_introd').hide();
            $('#div_upload_introd').show();
            $('#div_exist_introd').show();
            $('#div_image_introd img').attr('src','');
            $('#exist_introd option[id=0]').prop('selected',true);
            $('#exist_introd').selectator('refresh');
        } else {
            $('.input_lang[data-target-id="div_image_introd"]').each(function() {
                if($(this).css('display')=='block') {
                    var lang = $(this).attr('data-lang');
                    window.introd_file_langs[lang] = '';
                    $('#div_delete_introd').hide();
                    $('#div_image_introd_'+lang).hide();
                    $('#div_upload_introd').show();
                    $('#div_exist_introd_'+lang).show();
                    $('#div_image_introd_'+lang+' img').attr('src','');
                    $('#exist_introd_'+lang+' option[id=0]').prop('selected',true);
                    $('#exist_introd').selectator('refresh');
                }
            });
        }
    }

    window.delete_introm = function () {
        if($('#div_image_introm').css('display')=='block') {
            window.intro_mobile = '';
            $('#div_delete_introm').hide();
            $('#div_image_introm').hide();
            $('#div_upload_introm').show();
            $('#div_exist_introm').show();
            $('#div_image_introm img').attr('src','');
            $('#exist_introm option[id=0]').prop('selected',true);
            $('#exist_introm').selectator('refresh');
        } else {
            $('.input_lang[data-target-id="div_image_introm"]').each(function() {
                if($(this).css('display')=='block') {
                    var lang = $(this).attr('data-lang');
                    window.introm_file_langs[lang] = '';
                    $('#div_delete_introm').hide();
                    $('#div_image_introm_'+lang).hide();
                    $('#div_upload_introm').show();
                    $('#div_exist_introm_'+lang).show();
                    $('#div_image_introm_'+lang+' img').attr('src','');
                    $('#exist_introm_'+lang+' option[id=0]').prop('selected',true);
                    $('#exist_introm').selectator('refresh');
                }
            });
        }
    }

    window.delete_media = function () {
        window.vt_need_save = true;
        if($('#div_image_media').css('display')=='block') {
            window.media_file = '';
            $('#div_delete_media').hide();
            $('#div_image_media').hide();
            $('#div_upload_media').show();
            $('#div_exist_media').show();
            $('#div_image_media img').attr('src','');
            $('#div_image_media video').find('source:first').attr('src','');
            $('#exist_media option[id=0]').prop('selected',true);
            $('#exist_media').selectator('refresh');
        } else {
            $('.input_lang[data-target-id="div_image_media"]').each(function() {
                if($(this).css('display')=='block') {
                    var lang = $(this).attr('data-lang');
                    window.media_file_langs[lang] = '';
                    $('#div_delete_media').hide();
                    $('#div_image_media_'+lang).hide();
                    $('#div_upload_media').show();
                    $('#div_exist_media_'+lang).show();
                    $('#div_image_media_'+lang+' img').attr('src','');
                    $('#div_image_media_'+lang+' video').find('source:first').attr('src','');
                    $('#exist_media_'+lang+' option[id=0]').prop('selected',true);
                    $('#exist_media').selectator('refresh');
                }
            });
        }
    }

    window.delete_poweredby = function () {
        window.poweredby_image = '';
        window.vt_need_save = true;
        $('#div_delete_poweredby').hide();
        $('#div_image_poweredby').hide();
        $('#div_upload_poweredby').show();
        $('#div_exist_poweredby').show();
        $('#div_image_poweredby img').attr('src','');
    }

    window.delete_avatar_video = function () {
        window.vt_need_save = true;
        if($('#div_avatar_video_extensions').css('display')=='flex') {
            $('#avatar_video_content').val("");
            $('#div_delete_avatar_video').hide();
            $('#div_avatar_video_preview').hide();
            $('#div_upload_avatar_video').show();
            $('#mov_uploaded').css('color','orange');
            $('#webm_uploaded').css('color','orange');
            $('#div_avatar_video_preview video').attr('src','');
        } else {
            $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                if($(this).css('display')=='flex') {
                    var lang = $(this).attr('data-lang');
                    $('#avatar_video_content_'+lang).val("");
                    $('#div_delete_avatar_video_'+lang).hide();
                    $('#div_avatar_video_preview_'+lang).hide();
                    $('#div_upload_avatar_video_'+lang).show();
                    $('#mov_uploaded_'+lang).css('color','orange');
                    $('#webm_uploaded_'+lang).css('color','orange');
                    $('#div_avatar_video_preview_'+lang+' video').attr('src','');
                }
            });
        }
    }

    window.delete_bg = function () {
        window.background_image = '';
        window.vt_need_save = true;
        $('#div_delete_bg').hide();
        $('#div_image_bg').hide();
        $('#div_upload_bg').show();
        $('#div_exist_bg').show();
        $('#div_image_bg img').attr('src','');
    }

    window.delete_bg_m = function () {
        window.background_image_mobile = '';
        window.vt_need_save = true;
        $('#div_delete_bg_m').hide();
        $('#div_image_bg_m').hide();
        $('#div_upload_bg_m').show();
        $('#div_exist_bg_m').show();
        $('#div_image_bg_m img').attr('src','');
    }

    window.delete_video_bg = function () {
        window.background_video = '';
        window.vt_need_save = true;
        $('#div_delete_video_bg').hide();
        $('#div_video_bg').hide();
        $('#div_video_params').hide();
        $('#div_upload_video_bg').show();
        $('#div_exist_video_bg').show();
        $('#div_video_bg video source').attr('src','');
        $('#div_video_bg video').get(0).load();
        $('#background_video_delay').prop('disabled',true);
    }

    window.delete_video_bg_m = function () {
        window.background_video_mobile = '';
        window.vt_need_save = true;
        $('#div_delete_video_bg_m').hide();
        $('#div_video_bg_m').hide();
        $('#div_video_m_params').hide();
        $('#div_upload_video_bg_m').show();
        $('#div_exist_video_bg_m').show();
        $('#div_video_bg_m video source').attr('src','');
        $('#div_video_bg_m video').get(0).load();
        $('#background_video_delay_m').prop('disabled',true);
    }

    window.delete_b_bg = function () {
        window.b_background_image = '';
        window.settings_need_save = true;
        $('#div_delete_bg').hide();
        $('#div_image_bg').hide();
        $('#div_upload_bg').show();
        $('#div_image_bg img').attr('src','');
    }

    window.delete_b_bg_reg = function () {
        window.b_background_reg_image = '';
        window.settings_need_save = true;
        $('#div_delete_bg_reg').hide();
        $('#div_image_bg_reg').hide();
        $('#div_upload_bg_reg').show();
        $('#div_image_bg_reg img').attr('src','');
    }

    window.delete_s_banner = function () {
        window.s_banner_image = '';
        window.showcase_need_save = true;
        $('#div_delete_banner').hide();
        $('#div_image_banner').hide();
        $('#div_upload_banner').show();
        $('#div_image_banner img').attr('src','');
    }

    window.delete_b_logo = function () {
        window.b_logo_image = '';
        window.settings_need_save = true;
        $('#div_delete_logo').hide();
        $('#div_image_logo').hide();
        $('#div_upload_logo').show();
        $('#div_image_logo img').attr('src','');
    }

    window.delete_watermark_logo = function () {
        window.watermark_logo = '';
        window.video_need_save = true;
        $('#div_delete_logo').hide();
        if(window.vt_logo=='') {
            $('#div_image_logo').hide();
            $('#div_image_logo img').attr('src','');
        } else {
            if(window.s3_enabled==1) {
                $('#div_image_logo img').attr('src',window.s3_url+'viewer/content/'+window.vt_logo);
            } else {
                $('#div_image_logo img').attr('src','../viewer/content/'+window.vt_logo);
            }
        }
        $('#div_upload_logo').show();
    }

    window.delete_slide_logo = function () {
        $('#div_delete_slide_logo').hide();
        if(window.vt_logo=='') {
            $('#div_image_slide_logo').hide();
            $('#div_image_slide_logo img').attr('src','');
        } else {
            if(window.s3_enabled==1) {
                $('#div_image_slide_logo img').attr('src',window.s3_url+'viewer/content/'+window.vt_logo);
            } else {
                $('#div_image_slide_logo img').attr('src','../viewer/content/'+window.vt_logo);
            }
        }
        $('#div_upload_slide_logo').show();
    }

    window.delete_slide_image = function () {
        $('#div_delete_slide_image').hide();
        $('#div_image_slide_image').hide();
        $('#div_image_slide_image img').attr('src','');
        $('#div_upload_slide_image').show();
    }

    window.delete_slide_video = function () {
        $('#div_delete_slide_video').hide();
        $('#div_image_slide_video').hide();
        $('#div_image_slide_video video').attr('src','');
        $('#div_upload_slide_video').show();
    }

    window.delete_room_logo = function () {
        window.logo = '';
        window.room_need_save = true;
        $('#div_delete_logo').hide();
        $('#div_image_logo').hide();
        $('#div_upload_logo').show();
        $('#div_image_logo img').attr('src','');
    }

    window.delete_b_logo_s = function () {
        window.b_logo_s_image = '';
        window.settings_need_save = true;
        $('#div_delete_logo_s').hide();
        $('#div_image_logo_s').hide();
        $('#div_upload_logo_s').show();
        $('#div_image_logo_s img').attr('src','');
    }

    window.delete_s_logo = function () {
        window.s_logo_image = '';
        window.showcase_need_save = true;
        $('#div_delete_logo').hide();
        $('#div_image_logo').hide();
        $('#div_upload_logo').show();
        $('#div_image_logo img').attr('src','');
    }

    window.delete_g_logo = function () {
        window.s_logo_image = '';
        window.globe_need_save = true;
        $('#div_delete_logo').hide();
        $('#div_image_logo').hide();
        $('#div_upload_logo').show();
        $('#div_image_logo img').attr('src','');
    }

    window.delete_ad_logo = function () {
        window.image_advertisement = '';
        window.advertisement_need_save = true;
        $('#div_delete_logo').hide();
        $('#div_image_logo').hide();
        $('#div_upload_logo').show();
        $('#div_image_logo img').attr('src','');
    }

    window.delete_ad_video = function () {
        window.video_advertisement = '';
        window.advertisement_need_save = true;
        $('#div_delete_video').hide();
        $('#div_video').hide();
        $('#div_upload_video').show();
        $('#div_video video').attr('src','');
    }

    window.delete_nadir_logo = function () {
        window.nadir_logo = '';
        window.vt_need_save = true;
        $('#div_delete_nadir_logo').hide();
        $('#div_image_nadir_logo').hide();
        $('#div_size_nadir_logo').hide();
        $('#div_upload_nadir_logo').show();
        $('#div_exist_nadir_logo').show();
        $('#div_image_nadir_logo img').attr('src','');
    }

    window.get_rooms_alt_images = function (id_room) {
        $.ajax({
            url: "ajax/get_rooms_alt_images.php",
            type: "POST",
            data: {
                id_room: id_room
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_rooms_alt_images(rsp);
                    $('#virtual_staging').removeClass('disabled');
                    $('#main_view_tooltip').removeClass('disabled');
                    $('.input_lang[data-target-id="main_view_tooltip"]').removeClass('disabled');
                } else {
                    var html = '<div data-id="'+window.id_room+'" style="position: relative;" class="image_room_alt float-left mb-2 ml-1 mr-1"><div class="remove_image_room_alt"><i onclick="edit_main_view_tooltip();" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-edit"></i></div><img draggable="false" style="height:90px;border-radius:5px;" src="'+window.panorama_image.replace('/panoramas/','/panoramas/thumb/')+'" /></div>';
                    $('#list_rooms_alt').html(html);
                    $('#virtual_staging').addClass('disabled');
                    $('#main_view_tooltip').addClass('disabled');
                    $('.input_lang[data-target-id="main_view_tooltip"]').addClass('disabled');
                }
            }
        });
    }

    window.get_gallery_images = function(id_virtualtour) {
        $.ajax({
            url: "ajax/get_gallery_images.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_gallery_images(rsp);
                } else {
                    $('#btn_generate_slideshow').addClass('disabled');
                    $('#list_images').html("<p>"+window.backend_labels.no_image_msg+"</p>");
                }
            }
        });
    }

    window.get_intro_slider_images = function(id_virtualtour) {
        $('.image_gallery_slider').removeClass('disabled');
        $.ajax({
            url: "ajax/get_intro_slider_images.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_intro_slider_images(rsp);
                } else {
                    $('#list_images').html("<p>"+window.backend_labels.no_image_msg+"</p>");
                }
            }
        });
    }

    window.change_font_size_slide_logo = function() {
        var font_size = $('#slide_logo_font_size').val();
        if(font_size!='') {
            $('#slide_logo_text').css('font-size',font_size/1.5+'px');
        }
    }

    window.change_font_size_slide_text = function() {
        var font_size = $('#slide_text_font_size').val();
        if(font_size!='') {
            $('#slide_text_text').css('font-size',font_size/1.5+'px');
        }
    }

    window.play_panorama_preview = function() {
        $('#play_slide_panorama_btn').hide();
        $('#panorama_slide_start_btn').hide();
        $('#panorama_slide_end_btn').hide();
        var initial_yaw = $('#panorama_slide_start_btn').attr('data-yaw');
        var initial_pitch = $('#panorama_slide_start_btn').attr('data-pitch');
        var initial_hfov = $('#panorama_slide_start_btn').attr('data-hfov');
        var end_yaw = $('#panorama_slide_end_btn').attr('data-yaw');
        var end_pitch = $('#panorama_slide_end_btn').attr('data-pitch');
        var end_hfov = $('#panorama_slide_end_btn').attr('data-hfov');
        var duration = $('#slide_panorama_duration').val();
        window.viewer_pos.setYaw(parseInt(initial_yaw),false);
        window.viewer_pos.setPitch(parseInt(initial_pitch),false);
        window.viewer_pos.setHfov(parseInt(initial_hfov),false);
        window.viewer_pos.lookAt(parseInt(end_pitch),parseInt(end_yaw),parseInt(end_hfov),duration*1000,function() {
            setTimeout(function() {
                window.viewer_pos.setYaw(parseInt(initial_yaw),false);
                window.viewer_pos.setPitch(parseInt(initial_pitch),false);
                window.viewer_pos.setHfov(parseInt(initial_hfov),false);
                $('#play_slide_panorama_btn').show();
                $('#panorama_slide_start_btn').show();
                $('#panorama_slide_end_btn').show();
            },500);
        });
    }

    window.save_panorama_pos = function(type) {
        var yaw = parseInt(window.viewer_pos.getYaw());
        var pitch = parseInt(window.viewer_pos.getPitch());
        var hfov = parseInt(window.viewer_pos.getHfov());
        switch(type) {
            case 'start':
                $('#panorama_slide_start_btn').attr('data-yaw',yaw);
                $('#panorama_slide_start_btn').attr('data-pitch',pitch);
                $('#panorama_slide_start_btn').attr('data-hfov',hfov);
                break;
            case 'end':
                $('#panorama_slide_end_btn').attr('data-yaw',yaw);
                $('#panorama_slide_end_btn').attr('data-pitch',pitch);
                $('#panorama_slide_end_btn').attr('data-hfov',hfov);
                break;
        }
        reset_panorama_pos();
    }

    function reset_panorama_pos() {
        $('#panorama_pos_slide').css('pointer-events','none');
        $('#play_slide_panorama_btn').removeClass('disabled');
        $('#panorama_slide_start_btn').removeClass('disabled');
        $('#panorama_slide_end_btn').removeClass('disabled');
        $('#panorama_slide_start_btn').html(window.backend_labels.start);
        $('#panorama_slide_end_btn').html(window.backend_labels.end);
        $('#panorama_slide_start_btn').removeClass('btn-success').addClass('btn-white');
        $('#panorama_slide_start_btn').css('border','1px solid black');
        $('#panorama_slide_start_btn').attr('onclick','set_start_panorama_pos()');
        $('#panorama_slide_end_btn').removeClass('btn-success').addClass('btn-white');
        $('#panorama_slide_end_btn').css('border','1px solid black');
        $('#panorama_slide_end_btn').attr('onclick','set_end_panorama_pos()');
        $('#drag_set_msg').hide();
    }

    window.set_start_panorama_pos = function() {
        $('#panorama_pos_slide').css('pointer-events','initial');
        $('#play_slide_panorama_btn').addClass('disabled');
        $('#panorama_slide_start_btn').removeClass('btn-white').addClass('btn-success');
        $('#panorama_slide_start_btn').css('border','1px solid white');
        $('#panorama_slide_start_btn').attr('onclick','save_panorama_pos(\'start\')');
        $('#panorama_slide_start_btn').html(window.backend_labels.set);
        $('#panorama_slide_end_btn').addClass('disabled');
        $('#drag_set_msg').show();
        var initial_yaw = $('#panorama_slide_start_btn').attr('data-yaw');
        var initial_pitch = $('#panorama_slide_start_btn').attr('data-pitch');
        var initial_hfov = $('#panorama_slide_start_btn').attr('data-hfov');
        if(initial_yaw!='') {
            window.viewer_pos.setYaw(parseInt(initial_yaw),false);
            window.viewer_pos.setPitch(parseInt(initial_pitch),false);
            window.viewer_pos.setHfov(parseInt(initial_hfov),false);
        }
    }

    window.set_end_panorama_pos = function() {
        $('#panorama_pos_slide').css('pointer-events','initial');
        $('#play_slide_panorama_btn').addClass('disabled');
        $('#panorama_slide_start_btn').addClass('disabled');
        $('#panorama_slide_end_btn').removeClass('btn-white').addClass('btn-success');
        $('#panorama_slide_end_btn').css('border','1px solid white');
        $('#panorama_slide_end_btn').attr('onclick','save_panorama_pos(\'end\')');
        $('#panorama_slide_end_btn').html(window.backend_labels.set);
        $('#drag_set_msg').show();
        var end_yaw = $('#panorama_slide_end_btn').attr('data-yaw');
        var end_pitch = $('#panorama_slide_end_btn').attr('data-pitch');
        var end_hfov = $('#panorama_slide_end_btn').attr('data-hfov');
        if(end_yaw!='') {
            window.viewer_pos.setYaw(parseInt(end_yaw),false);
            window.viewer_pos.setPitch(parseInt(end_pitch),false);
            window.viewer_pos.setHfov(parseInt(end_hfov),false);
        }
    }

    window.change_room_panorama_pos = function() {
        var id_room = $('#room_panorama option:selected').attr('id');
        var panorama_image = $('#room_panorama option:selected').attr('data-panorama');
        if(window.id_video_slide_sel!=null) {
            var index = window.array_slides.findIndex(element => parseInt(element.id) === parseInt(window.id_video_slide_sel));
            if (parseInt(window.array_slides[index].id_room) == id_room) {
                var params = JSON.parse(window.array_slides[index].params);
                var initial_yaw = parseInt(params.initial_yaw);
                var initial_pitch = parseInt(params.initial_pitch);
                var initial_hfov = parseInt(params.initial_hfov);
                var end_yaw = parseInt(params.end_yaw);
                var end_pitch = parseInt(params.end_pitch);
                var end_hfov = parseInt(params.end_hfov);
            } else {
                var initial_yaw = 0;
                var initial_pitch = 0;
                var initial_hfov = 100;
                var end_yaw = 0;
                var end_pitch = 0;
                var end_hfov = 100;
            }
        } else {
            var initial_yaw = 0;
            var initial_pitch = 0;
            var initial_hfov = 100;
            var end_yaw = 0;
            var end_pitch = 0;
            var end_hfov = 100;
        }
        $('#panorama_slide_start_btn').attr('data-yaw',initial_yaw);
        $('#panorama_slide_start_btn').attr('data-pitch',initial_pitch);
        $('#panorama_slide_start_btn').attr('data-hfov',initial_hfov);
        $('#panorama_slide_end_btn').attr('data-yaw',end_yaw);
        $('#panorama_slide_end_btn').attr('data-pitch',end_pitch);
        $('#panorama_slide_end_btn').attr('data-hfov',end_hfov);
        if(window.s3_enabled==1) {
            var panorama_url = window.s3_url+'viewer/panoramas/'+panorama_image+'?s3=1';
        } else {
            var panorama_url = '../viewer/panoramas/'+panorama_image;
        }
        load_viewer_pos('panorama_pos_slide',id_room,panorama_url,initial_yaw,initial_pitch,0,0,-90,90,360,180,-180,180,initial_hfov,null);
        reset_panorama_pos();
    }

    window.new_slide = function(type) {
        $('#modal_new_slide').modal('hide');
        edit_video_slide(type,null);
    }

    window.edit_video_slide = function(type,id) {
        window.id_video_slide_sel = id;
        if(id!=null) {
            var index = window.array_slides.findIndex(element => parseInt(element.id) === parseInt(id));
            var slide = window.array_slides[index];
        }
        switch(type) {
            case 'panorama':
                if(id!=null) {
                    var duration = slide.duration;
                    var id_room = slide.id_room;
                    var params = JSON.parse(slide.params);
                    var anim_type = params.anim_type;
                    var initial_yaw = parseInt(params.initial_yaw);
                    var initial_pitch = parseInt(params.initial_pitch);
                    var initial_hfov = parseInt(params.initial_hfov);
                    var end_yaw = parseInt(params.end_yaw);
                    var end_pitch = parseInt(params.end_pitch);
                    var end_hfov = parseInt(params.end_hfov);
                    var panorama_image = slide.panorama_image;
                } else {
                    var duration = 3;
                    var anim_type = 'manual';
                    var id_room = $('#room_panorama option:first').attr('id');
                    var initial_yaw = 0;
                    var initial_pitch = 0;
                    var initial_hfov = 100;
                    var end_yaw = 0;
                    var end_pitch = 0;
                    var end_hfov = 100;
                    var panorama_image = $('#room_panorama option:first').attr('data-panorama');
                }
                $('#slide_panorama_duration').val(duration);
                $('#slide_panorama_anim_type option').prop('selected',false);
                $('#slide_panorama_anim_type option[id="'+anim_type+'"]').prop('selected',true);
                change_anim_type();
                try {
                    $('#room_panorama').selectpicker('destroy');
                } catch (e) {}
                $('#room_panorama option').prop('selected',false);
                $('#room_panorama option[id="'+id_room+'"]').prop('selected',true);
                $('#room_panorama').selectpicker({
                    liveSearch: true,
                });
                $('#panorama_slide_start_btn').attr('data-yaw',initial_yaw);
                $('#panorama_slide_start_btn').attr('data-pitch',initial_pitch);
                $('#panorama_slide_start_btn').attr('data-hfov',initial_hfov);
                $('#panorama_slide_end_btn').attr('data-yaw',end_yaw);
                $('#panorama_slide_end_btn').attr('data-pitch',end_pitch);
                $('#panorama_slide_end_btn').attr('data-hfov',end_hfov);
                if(window.s3_enabled==1) {
                    var panorama_url = window.s3_url+'viewer/panoramas/'+panorama_image+'?s3=1';
                } else {
                    var panorama_url = '../viewer/panoramas/'+panorama_image;
                }
                load_viewer_pos('panorama_pos_slide',id_room,panorama_url,initial_yaw,initial_pitch,0,0,-90,90,360,180,-180,180,initial_hfov,null);
                reset_panorama_pos();
                break;
            case 'image':
                if(id!=null) {
                    var duration = slide.duration;
                    var file = slide.file;
                } else {
                    var duration = 3;
                    var file = '';
                }
                $('#slide_image_duration').val(duration);
                if(file!='') {
                    if(window.s3_enabled==1) {
                        $('#div_image_slide_image img').attr('src',window.s3_url+'video/assets/'+window.id_virtualtour+'/'+file);
                    } else {
                        $('#div_image_slide_image img').attr('src','../video/assets/'+window.id_virtualtour+'/'+file);
                    }
                    $('#div_image_slide_image').show();
                    $('#div_upload_slide_image').hide();
                    $('#div_delete_slide_image').show();
                } else {
                    $('#div_image_slide_image img').attr('src','');
                    $('#div_image_slide_image').hide();
                    $('#div_upload_slide_image').show();
                    $('#div_delete_slide_image').hide();
                }
                break;
            case 'video':
                if(id!=null) {
                    var file = slide.file;
                } else {
                    var file = '';
                }
                if(file!='') {
                    if(window.s3_enabled==1) {
                        $('#div_image_slide_video video').attr('src',window.s3_url+'video/assets/'+window.id_virtualtour+'/'+file);
                    } else {
                        $('#div_image_slide_video video').attr('src','../video/assets/'+window.id_virtualtour+'/'+file);
                    }
                    $('#div_image_slide_video').show();
                    $('#div_upload_slide_video').hide();
                    $('#div_delete_slide_video').show();
                } else {
                    $('#div_image_slide_video video').attr('src','');
                    $('#div_image_slide_video').hide();
                    $('#div_upload_slide_video').show();
                    $('#div_delete_slide_video').hide();
                }
                break;
            case 'logo':
                if(id!=null) {
                    var duration = slide.duration;
                    var params = slide.params;
                    var file = slide.file;
                } else {
                    var duration = 3;
                    var params = '{"bg_color":"#000000","font_color":"#ffffff","font_size":"24","bottom_padding":"0","text":""}';
                    var file = '';
                }
                var params = JSON.parse(params);
                $('#slide_logo_duration').val(duration);
                $('#slide_logo_background_color').val(params.bg_color);
                $('#slide_logo_bottom_padding').val(params.bottom_padding);
                $('#slide_logo_font_size').val(params.font_size);
                $('#slide_logo_font_color').val(params.font_color);
                $('#slide_logo_text').val(params.text);
                $('#slide_logo_text').css('background-color',params.bg_color);
                $('#slide_logo_text').css('color',params.font_color);
                $('#slide_logo_text').css('font-size',params.font_size/1.5+'px');
                $('#div_image_slide_logo').css('background-color',params.bg_color);
                $("#slide_logo_background_color").spectrum("set", params.bg_color);
                $("#slide_logo_font_color").spectrum("set", params.font_color);
                if(file!='') {
                    if(window.s3_enabled==1) {
                        $('#div_image_slide_logo img').attr('src',window.s3_url+'video/assets/'+window.id_virtualtour+'/'+file);
                    } else {
                        $('#div_image_slide_logo img').attr('src','../video/assets/'+window.id_virtualtour+'/'+file);
                    }
                    $('#div_image_slide_logo').show();
                    $('#div_upload_slide_logo').hide();
                    $('#div_delete_slide_logo').show();
                } else {
                    if(window.vt_logo!='') {
                        if(window.s3_enabled==1) {
                            $('#div_image_slide_logo img').attr('src',window.s3_url+'viewer/content/'+window.vt_logo);
                        } else {
                            $('#div_image_slide_logo img').attr('src','../viewer/content/'+window.vt_logo);
                        }
                        $('#div_image_slide_logo').show();
                        $('#div_upload_slide_logo').show();
                        $('#div_delete_slide_logo').hide();
                    } else {
                        $('#div_image_slide_logo img').attr('src','');
                        $('#div_image_slide_logo').hide();
                        $('#div_upload_slide_logo').show();
                        $('#div_delete_slide_logo').hide();
                    }
                }
                break;
            case 'text':
                if(id!=null) {
                    var duration = slide.duration;
                    var params = slide.params;
                } else {
                    var duration = 3;
                    var params = '{"bg_color":"#000000","font_color":"#ffffff","font_size":"24","text":""}';
                }
                var params = JSON.parse(params);
                $('#slide_text_duration').val(duration);
                $('#slide_text_background_color').val(params.bg_color);
                $('#slide_text_font_size').val(params.font_size);
                $('#slide_text_font_color').val(params.font_color);
                $('#slide_text_text').val(params.text);
                $('#slide_text_text').css('background-color',params.bg_color);
                $('#slide_text_text').css('color',params.font_color);
                $('#slide_text_text').css('font-size',params.font_size/1.5+'px');
                $("#slide_text_background_color").spectrum("set", params.bg_color);
                $("#slide_text_font_color").spectrum("set", params.font_color);
                break;
        }
        $('#btn_save_slide_'+type).attr('onclick','save_video_slide(\''+type+'\','+id+')');
        $('#modal_slide_'+type).modal("show");
    }

    window.delete_video_slide = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_video_slide.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_video_slides(id_virtualtour,id_video);
                }
            });
        } else {
            return false;
        }
    }

    window.duplicate_video_slide = function(id) {
        var retVal = confirm(window.backend_labels.duplicate_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/duplicate_video_slide.php",
                type: "POST",
                data: {
                    id_video: window.id_video,
                    id: id
                },
                async: false,
                success: function (json) {
                    get_video_slides(id_virtualtour,id_video);
                }
            });
        } else {
            return false;
        }
    }

    window.save_video_slide = function(type,id) {
        $('#modal_slide_'+type+' button').addClass('disabled');
        switch(type) {
            case 'panorama':
                var id_room = $('#room option:selected').attr('id');
                var duration = $('#slide_panorama_duration').val();
                var anim_tyoe = $('#slide_panorama_anim_type option:selected').attr('id');
                var initial_yaw = $('#panorama_slide_start_btn').attr('data-yaw');
                var initial_pitch = $('#panorama_slide_start_btn').attr('data-pitch');
                var initial_hfov = $('#panorama_slide_start_btn').attr('data-hfov');
                var end_yaw = $('#panorama_slide_end_btn').attr('data-yaw');
                var end_pitch = $('#panorama_slide_end_btn').attr('data-pitch');
                var end_hfov = $('#panorama_slide_end_btn').attr('data-hfov');
                var params = {'initial_yaw':initial_yaw,'initial_pitch':initial_pitch,'initial_hfov':initial_hfov,'end_yaw':end_yaw,'end_pitch':end_pitch,'end_hfov':end_hfov,'anim_type':anim_tyoe};
                params = JSON.stringify(params);
                break;
            case 'image':
                var id_room = '';
                var duration = $('#slide_image_duration').val();
                var image = $('#div_image_slide_image img').attr('src');
                var file = '';
                if(image!='') {
                    file = image;
                } else {
                    $('#txtFile_si').parent().addClass("error-highlight");
                    $('#modal_slide_'+type+' button').removeClass('disabled');
                    return;
                }
                params = '';
                break;
            case 'video':
                var id_room = '';
                var duration = '';
                var video = $('#div_image_slide_video video').attr('src');
                var file = '';
                if(video!='') {
                    file = video;
                } else {
                    $('#txtFile_sv').parent().addClass("error-highlight");
                    $('#modal_slide_'+type+' button').removeClass('disabled');
                    return;
                }
                params = '';
                break;
            case 'logo':
                var id_room = '';
                var duration = $('#slide_logo_duration').val();
                var logo = $('#div_image_slide_logo img').attr('src');
                var file = '';
                if(logo!='') {
                    if(logo.includes('video/assets')) {
                        file = logo;
                    } else {
                        if(window.vt_logo=='') {
                            $('#txtFile_sl').parent().addClass("error-highlight");
                            $('#modal_slide_'+type+' button').removeClass('disabled');
                            return;
                        }
                    }
                } else {
                    $('#txtFile_sl').parent().addClass("error-highlight");
                    $('#modal_slide_'+type+' button').removeClass('disabled');
                    return;
                }
                var bg_color = $("#slide_logo_background_color").val();
                var bottom_padding = $("#slide_logo_bottom_padding").val();
                var font_size = $("#slide_logo_font_size").val();
                var font_color = $("#slide_logo_font_color").val();
                var text = $('#slide_logo_text').val();
                var params = {'bg_color':bg_color,'font_color':font_color,'font_size':font_size,'bottom_padding':bottom_padding,'text':text};
                params = JSON.stringify(params);
                break;
            case 'text':
                var id_room = '';
                var duration = $('#slide_text_duration').val();
                var file = '';
                var bg_color = $("#slide_text_background_color").val();
                var font_size = $("#slide_text_font_size").val();
                var font_color = $("#slide_text_font_color").val();
                var text = $('#slide_text_text').val();
                var params = {'bg_color':bg_color,'font_color':font_color,'font_size':font_size,'text':text};
                params = JSON.stringify(params);
                break;
        }
        $.ajax({
            url: "ajax/save_video_slide.php",
            type: "POST",
            data: {
                id: id,
                id_video: id_video,
                id_room: id_room,
                type: type,
                file: file,
                duration: duration,
                params: params
            },
            async: true,
            success: function (json) {
                get_video_slides(id_virtualtour,id_video);
                $('#modal_slide_'+type).modal("hide");
                $('#modal_slide_'+type+' button').removeClass('disabled');
            },
            error: function() {
                $('#modal_slide_'+type+' button').removeClass('disabled');
            }
        });
    }

    window.calculate_timeline_duration = function() {
        var total_duration = 0;
        var total_duration_f = 0;
        var num_slides = 0;
        var fade = parseFloat($('#fade').val());
        jQuery.each(window.array_slides,function(index,slide) {
            if(parseInt(slide.enabled)==1) {
                $('.video_slide[data-id="'+slide.id+'"]').attr('data-timeline-start',total_duration_f.toFixed(2));
                total_duration = total_duration + parseFloat(slide.duration);
                total_duration_f = total_duration_f + parseFloat(slide.duration) - (fade/2);
                $('.video_slide[data-id="'+slide.id+'"]').attr('data-timeline-end',total_duration_f.toFixed(2));
                num_slides++;
            }
        })
        if(total_duration!=0) {
            total_duration = total_duration -(fade*((num_slides-1)/2));
            $('#total_duration').html(convertSeconds(total_duration));
        }
    }

    window.get_active_slide_timeline = function(sec) {
        $('.video_slide').removeClass('active_slide_record');
        $('.video_slide').each(function() {
            var start = parseFloat($(this).attr('data-timeline-start'));
            var end = parseFloat($(this).attr('data-timeline-end'));
            if(sec>=start && sec<end) {
                $(this).addClass('active_slide_record');
            }
        });
    }

    function convertSeconds(seconds) {
        var h = Math.floor(seconds / 3600);
        var m = Math.floor(seconds % 3600 / 60);
        var s = Math.floor(seconds % 3600 % 60);
        return (h > 0 ? h + ":" + (m < 10 ? "0" : "") : "00:") + (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
    }

    window.get_video_slides = function(id_virtualtour,id_video) {
        $('#list_video_slides').empty();
        $.ajax({
            url: "ajax/get_video_slides.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                id_video: id_video
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                var html = rsp.html;
                var count = rsp.count;
                window.array_slides = rsp.array_slides;
                $('#list_video_slides').html(html).promise().done(function() {
                    if(count>0) {
                        var el = document.getElementById('list_video_slides');
                        Sortable.create(el,{
                            filter: ".sort-disabled",
                            onMove: function (e) { return e.related.className.indexOf('sort-disabled') === -1;  },
                            onEnd: function (evt) {
                                var array_slides_priority = [];
                                $('#list_video_slides .video_slide').each(function () {
                                    var id = $(this).attr('data-id');
                                    array_slides_priority.push(id);
                                });
                                change_video_slides_order(array_slides_priority);
                            },
                        });
                    }
                    var num_video_slides = 0;
                    $('.video_slide.sort-item').each(function() {
                        if($(this).css('opacity')==1) {
                            num_video_slides++;
                        }
                    });
                    if(num_video_slides>=1) {
                        $('#btn_generate_video').removeClass('disabled');
                    } else {
                        $('#btn_generate_video').addClass('disabled');
                    }
                    calculate_timeline_duration();
                });
            }
        });
    }

    window.get_product_images = function(id_product) {
        $.ajax({
            url: "ajax/get_product_images.php",
            type: "POST",
            data: {
                id_product: id_product
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_product_images(rsp);
                } else {
                    $('#list_images').html("<p>"+window.backend_labels.no_image_msg+"</p>");
                }
            }
        });
    }

    window.get_media_library_files = function(id_virtualtour) {
        $.ajax({
            url: "ajax/get_media_library_files.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                type: 'all'
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_media_library_files(rsp);
                } else {
                    $('#list_files').html("<p>"+window.backend_labels.no_files_msg+"</p>");
                }
            }
        });
    }

    window.get_music_library_files = function(id_virtualtour) {
        $.ajax({
            url: "ajax/get_music_library_files.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_music_library_files(rsp);
                } else {
                    $('#list_files').html("<p>"+window.backend_labels.no_files_msg+"</p>");
                }
            }
        });
    }

    window.get_sound_library_files = function(id_virtualtour) {
        $.ajax({
            url: "ajax/get_sound_library_files.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_sound_library_files(rsp);
                } else {
                    $('#list_files').html("<p>"+window.backend_labels.no_files_msg+"</p>");
                }
            }
        });
    }

    window.get_poi_gallery_images = function(id_poi) {
        $.ajax({
            url: "ajax/get_poi_gallery_images.php",
            type: "POST",
            data: {
                id_poi: id_poi
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_poi_gallery_images(rsp);
                } else {
                    $('#list_images').html("<p>"+window.backend_labels.no_image_msg+"</p>");
                }
            }
        });
    }

    window.get_poi_embed_gallery_images = function(id_poi) {
        $.ajax({
            url: "ajax/get_poi_embed_gallery_images.php",
            type: "POST",
            data: {
                id_poi: id_poi
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_poi_embed_gallery_images(rsp);
                } else {
                    $('#list_images').html("<p>"+window.backend_labels.no_image_msg+"</p>");
                }
            }
        });
    }

    window.get_poi_object360_images = function(id_poi) {
        $.ajax({
            url: "ajax/get_poi_object360_images.php",
            type: "POST",
            data: {
                id_poi: id_poi
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_poi_object360_images(rsp);
                } else {
                    $('#list_images').html("<p>"+window.backend_labels.no_image_msg+"</p>");
                }
            }
        });
    }

    window.get_icon_images = function(id_virtualtour) {
        $.ajax({
            url: "ajax/get_icon_images.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.length>0) {
                    parse_icon_images(rsp);
                } else {
                    $('#list_images').html("<p>"+window.backend_labels.no_icon_msg+"</p>");
                }
            }
        });
    }

    window.get_icon_images_m = function(id_virtualtour,m) {
        $.ajax({
            url: "ajax/get_icon_images_m.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                m: m
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                switch(m) {
                    case 'icons':
                        $('#list_images').html(rsp.html).promise().done(function() {});
                        break;
                    case 'marker':
                    case 'marker_h':
                        $('#list_images_im').html(rsp.html).promise().done(function() {
                            switch (m) {
                                case 'marker':
                                    $('.lottie_icon_marker_list').each(function () {
                                        var id = $(this).attr('data-id');
                                        var image = $(this).attr('data-image');
                                        var id_vt = $(this).attr('data-id_vt');
                                        if(window.s3_enabled==1 && id_vt!='') {
                                            var json_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
                                        } else {
                                            var json_url = '../viewer/icons/'+image;
                                        }
                                        bodymovin.loadAnimation({
                                            container: document.getElementById('lottie_icon_marker_'+id),
                                            renderer: 'svg',
                                            loop: true,
                                            autoplay: true,
                                            path: json_url,
                                            rendererSettings: {
                                                progressiveLoad: true,
                                            }
                                        });
                                    });
                                    break;
                                case 'marker_h':
                                    $('.lottie_icon_list').each(function () {
                                        var id = $(this).attr('data-id');
                                        var image = $(this).attr('data-image');
                                        var id_vt = $(this).attr('data-id_vt');
                                        if(window.s3_enabled==1 && id_vt!='') {
                                            var json_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
                                        } else {
                                            var json_url = '../viewer/icons/'+image;
                                        }
                                        bodymovin.loadAnimation({
                                            container: document.getElementById('lottie_icon_'+id),
                                            renderer: 'svg',
                                            loop: true,
                                            autoplay: true,
                                            path: json_url,
                                            rendererSettings: {
                                                progressiveLoad: true,
                                            }
                                        });
                                    });
                                    break;
                            }
                        });
                        break;
                    case 'poi':
                    case 'poi_h':
                        $('#list_images_ip').html(rsp.html).promise().done(function() {
                            switch (m) {
                                case 'poi':
                                    $('.lottie_icon_poi_list').each(function () {
                                        var id = $(this).attr('data-id');
                                        var image = $(this).attr('data-image');
                                        var id_vt = $(this).attr('data-id_vt');
                                        if(window.s3_enabled==1 && id_vt!='') {
                                            var json_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
                                        } else {
                                            var json_url = '../viewer/icons/'+image;
                                        }
                                        bodymovin.loadAnimation({
                                            container: document.getElementById('lottie_icon_poi_'+id),
                                            renderer: 'svg',
                                            loop: true,
                                            autoplay: true,
                                            path: json_url,
                                            rendererSettings: {
                                                progressiveLoad: true,
                                            }
                                        });
                                    });
                                    break;
                                case 'poi_h':
                                    $('.lottie_icon_list').each(function () {
                                        var id = $(this).attr('data-id');
                                        var image = $(this).attr('data-image');
                                        var id_vt = $(this).attr('data-id_vt');
                                        if(window.s3_enabled==1 && id_vt!='') {
                                            var json_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
                                        } else {
                                            var json_url = '../viewer/icons/'+image;
                                        }
                                        bodymovin.loadAnimation({
                                            container: document.getElementById('lottie_icon_'+id),
                                            renderer: 'svg',
                                            loop: true,
                                            autoplay: true,
                                            path: json_url,
                                            rendererSettings: {
                                                progressiveLoad: true,
                                            }
                                        });
                                    });
                                    break;
                            }
                        });
                        break;
                }
            }
        });
    }

    window.preview_poi_content = function (id) {
        if(window.is_fullscreen) {
            var parent_elem = document.getElementById('poi_editor_div');
        } else {
            var parent_elem = 'body';
        }
        var content = '';
        if($('#'+id).is(':visible')) {
            content = $('#'+id).val();
        } else {
            $('.input_lang[data-target-id="poi_content"]').each(function() {
                if($(this).is(':visible')) {
                    content = $(this).val();
                }
            });
        }
        if(content!='') {
            var ext = content.split('.').pop().toLowerCase();
            var type = $('#'+id).attr('data-type');
            switch(type) {
                case 'pointclouds':
                    if(window.s3_enabled==1) {
                        var url_file = window.s3_url+'viewer/'+content;
                    } else {
                        var url_file = content;
                    }
                    var iframe = '<iframe class="potree_iframe" style="width:100%;height:100%;" allow="accelerometer; camera; display-capture; fullscreen; geolocation; gyroscope; magnetometer; microphone; midi; xr-spatial-tracking;" width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="../viewer/vendor/potree/viewer/index.html?id_poi='+window.poi_id_edit+'&file='+url_file+'&edit=1"></iframe>';
                    var html = '<div style="overflow:hidden;padding:0;width:calc(100% - 0px);height:calc(100% - 0px);">'+iframe+'</div>';
                    $.fancybox.open({
                        src  : html,
                        type : 'html',
                        touch: false,
                        smallBtn: false,
                        clickOutside: false,
                        afterShow: function(instance, current) {
                            $('.fancybox-toolbar').addClass('always-visible');
                        },
                        beforeClose: function(instance, current) {
                            $('.fancybox-toolbar').removeClass('always-visible');
                        }
                    });
                    break;
                default:
                    switch (ext) {
                        case 'mp3':
                            if(content.startsWith('http')) {
                                var url = content;
                            } else {
                                if(window.s3_enabled==1) {
                                    var url = window.s3_url+'viewer/'+content;
                                } else {
                                    var url = '../viewer/'+content;
                                }
                            }
                            content = '<div><audio controls preload="auto" playsinline webkit-playsinline><source src="'+url+'" type="audio/mpeg"></audio></div>';
                            $.fancybox.open({
                                src: content,
                                type: 'html',
                                parentEl: parent_elem
                            });
                            break;
                        case 'glb':
                        case 'gltf':
                        case 'usdz':
                            var array_files = content.split(",");
                            var glb_file = '';
                            jQuery.each(array_files, function(index_s, file_s) {
                                if(file_s.split('.').pop().toLowerCase()=='glb') {
                                    glb_file = file_s;
                                }
                                if(file_s.split('.').pop().toLowerCase()=='gltf') {
                                    glb_file = file_s;
                                }
                            });
                            if(content.startsWith('http')) {
                                var url = content;
                            } else {
                                if(window.s3_enabled==1) {
                                    var url = window.s3_url+'viewer/'+glb_file;
                                } else {
                                    var url = '../viewer/'+glb_file;
                                }
                            }
                            if($('#params_exposure').length) {
                                var exposure = $('#params_exposure').val();
                            } else {
                                var exposure = 1;
                            }
                            if($('#params_environment').length) {
                                var environment = $('#params_environment option:selected').attr('id');
                            } else {
                                var environment = 'legacy';
                            }
                            if($('#params_animation').length) {
                                var animation = $('#params_animation option:selected').attr('id');
                                if(animation=='none') {
                                    var animation = '';
                                    var autoplay = '';
                                } else {
                                    var autoplay = 'autoplay';
                                }
                            } else {
                                var animation = '';
                                var autoplay = '';
                            }
                            if($('#params_autorotate').length) {
                                var autorotate = ($('#params_autorotate').is(':checked') ? 'auto-rotate' : '');
                            } else {
                                var autorotate = 'auto-rotate';
                            }
                            if($('#params_zoom').length) {
                                var disable_zoom = ($('#params_zoom').is(':checked') ? '' : 'disable-zoom');
                            } else {
                                var disable_zoom = 'disable-zoom';
                            }
                            if($('#params_pan').length) {
                                var disable_pan = ($('#params_pan').is(':checked') ? '' : 'disable-pan');
                            } else {
                                var disable_pan = 'disable-pan';
                            }
                            var html = '<div class="poi_object3d_content"><model-viewer disable-tap '+autorotate+' '+disable_pan+' '+disable_zoom+' '+autoplay+' animation-name="'+animation+'" src="'+url+'" alt="" environment-image="'+environment+'" exposure="'+exposure+'" camera-controls></model-viewer></div>';
                            $.fancybox.open({
                                src  : html,
                                type : 'html',
                                touch: false,
                                smallBtn: false,
                                clickOutside: false,
                                parentEl: parent_elem,
                                afterShow : function() {}
                            });
                            break;
                        case 'json':
                            if(content.startsWith('http')) {
                                var url = content;
                            } else {
                                if(window.s3_enabled==1) {
                                    var url = window.s3_url+'viewer/'+content+'?s3=1';
                                } else {
                                    var url = '../viewer/'+content;
                                }
                            }
                            var html = '<div class="poi_lottie_content"></div>';
                            $.fancybox.open({
                                src  : html,
                                type : 'html',
                                touch: false,
                                smallBtn: false,
                                clickOutside: false,
                                parentEl: parent_elem,
                                afterShow : function() {
                                    bodymovin.loadAnimation({
                                        container: document.getElementsByClassName('poi_lottie_content')[0],
                                        renderer: 'svg',
                                        loop: true,
                                        autoplay: true,
                                        path: url,
                                        rendererSettings: {
                                            progressiveLoad: true,
                                        }
                                    });
                                }
                            });
                            break;
                        case 'pdf':
                            if(content.startsWith('http')) {
                                $.fancybox.open({
                                    src: '../viewer/vendor/pdf_viewer/index.php?file='+content,
                                    type: 'iframe',
                                    parentEl: parent_elem
                                });
                            } else {
                                if(window.s3_enabled==1) {
                                    var file = window.s3_url+'viewer/'+content;
                                } else {
                                    var file = window.base_url+'viewer/'+content;
                                }
                                $.fancybox.open({
                                    src: '../viewer/vendor/pdf_viewer/index.php?file='+file,
                                    parentEl: parent_elem
                                });
                            }
                            break;
                        default:
                            if(content.startsWith('http')) {
                                $.fancybox.open({
                                    src: content,
                                    type: 'iframe',
                                    parentEl: parent_elem
                                });
                            } else {
                                if(window.s3_enabled==1) {
                                    content = window.s3_url+'viewer/'+content;
                                } else {
                                    content = '../viewer/'+content;
                                }
                                $.fancybox.open({
                                    src: content,
                                    parentEl: parent_elem
                                });
                            }
                            break;
                    }
                    break;
            }
        }
    }

    window.link_poi_content = function (id) {
        var content = '';
        if($('#'+id).is(':visible')) {
            content = $('#'+id).val();
        } else {
            $('.input_lang[data-target-id="poi_content"]').each(function() {
                if($(this).is(':visible')) {
                    content = $(this).val();
                }
            });
        }
        if(content!='') {
            if(content.indexOf("content/") !== -1 || content.indexOf("media/") !== -1) {
                var ext = content.split('.').pop().toLowerCase();
                var type = $('#'+id).attr('data-type');
                switch(type) {
                    default:
                        switch (ext) {
                            case 'mp3':
                                if(content.startsWith('http')) {
                                    var url = content;
                                } else {
                                    if(window.s3_enabled==1) {
                                        var url = window.s3_url+'viewer/'+content;
                                    } else {
                                        var url = '../viewer/'+content;
                                    }
                                    window.open(url);
                                }
                                break;
                            case 'pdf':
                                if(content.startsWith('http')) {
                                    $.fancybox.open({
                                        src: '../viewer/vendor/pdf_viewer/index.php?file='+content,
                                        type: 'iframe',
                                        parentEl: parent_elem
                                    });
                                } else {
                                    if(window.s3_enabled==1) {
                                        var file = window.s3_url+'viewer/'+content;
                                    } else {
                                        var file = window.base_url+'viewer/'+content;
                                    }
                                    window.open(file);
                                }
                                break;
                            default:
                                if(window.s3_enabled==1) {
                                    content = window.s3_url+'viewer/'+content;
                                } else {
                                    content = '../viewer/'+content;
                                }
                                window.open(content);
                                break;
                        }
                        break;
                }
            }
        }
    }

    window.switch_gallery_mode = function(mode) {
        switch(mode) {
            case 'images':
                $('#btn_gallerymode_images').removeClass('btn-outline-primary').addClass('btn-primary');
                $('#btn_gallerymode_slideshow').addClass('btn-outline-primary').removeClass('btn-primary');
                $('#gallery_div').removeClass('d-none');
                break;
            case 'slideshow':
                $('#btn_gallerymode_images').addClass('btn-outline-primary').removeClass('btn-primary');
                $('#btn_gallerymode_slideshow').removeClass('btn-outline-primary').addClass('btn-primary');
                $('#gallery_div').addClass('d-none');
                break;
        }
        $.ajax({
            url: "ajax/switch_gallery_mode.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                mode: mode
            },
            async: false,
            success: function (json) {}
        });
    }

    window.save_gallery = function() {
        $('#save_gallery_btn').addClass('disabled');
        var resolution = parseInt($('#s_resolution option:selected').attr('id'));
        var aspect_ratio = $('#s_aspect_ratio option:selected').attr('id');
        switch(aspect_ratio) {
            case '16_9':
                var width = resolution*16/9;
                var height = resolution;
                break;
            case '9_16':
                var width = resolution*9/16;
                var height = resolution;
                break;
            case '1_1':
                var width = resolution;
                var height = resolution;
                break;
        }
        var slide_duration = $('#s_slide_duration').val();
        var fade_duration = $('#s_fade_duration').val();
        var zoom_rate = $('#s_zoom_rate').val();
        var audio = $('#s_audio option:selected').attr('id');
        if(audio=='0') audio='';
        var watermark = $('#s_watermark option:selected').attr('id');
        var watermark_opacity = $('#s_watermark_opacity').val();
        var gallery_transition = $('#g_transition option:selected').attr('id');
        var gallery_thumbs = $('#g_thumbs option:selected').attr('id');
        var gallery_autoplay = $('#g_autoplay').is(':checked')?1:0;
        var gallery_allow_download = $('#g_download').is(':checked')?1:0;
        var gallery_slide_duration = $('#g_slide_duration').val();
        $.ajax({
            url: 'ajax/save_gallery.php',
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                width: width,
                height: height,
                slide_duration: slide_duration,
                fade_duration: fade_duration,
                zoom_rate: zoom_rate,
                audio: audio,
                watermark: watermark,
                watermark_opacity: watermark_opacity,
                gallery_transition: gallery_transition,
                gallery_thumbs: gallery_thumbs,
                gallery_autoplay: gallery_autoplay,
                gallery_allow_download: gallery_allow_download,
                gallery_slide_duration: gallery_slide_duration
            },
            async: true,
            success: function (json) {
                $('#save_gallery_btn').removeClass('disabled');
            }
        });
    }

    window.generate_slideshow = function() {
        $('#btn_generate_slideshow').addClass('disabled');
        $('#modal_generate_slideshow').modal('show');
        setTimeout(function () {
            $('#btn_continue_w').removeClass('d-none');
        },10000);
        var resolution = parseInt($('#s_resolution option:selected').attr('id'));
        var aspect_ratio = $('#s_aspect_ratio option:selected').attr('id');
        switch(aspect_ratio) {
            case '16_9':
                var width = resolution*16/9;
                var height = resolution;
                break;
            case '9_16':
                var width = resolution*9/16;
                var height = resolution;
                break;
            case '1_1':
                var width = resolution;
                var height = resolution;
                break;
        }
        var slide_duration = $('#s_slide_duration').val();
        var fade_duration = $('#s_fade_duration').val();
        var zoom_rate = $('#s_zoom_rate').val();
        var audio = $('#s_audio option:selected').attr('id');
        if(audio=='0') audio='';
        var watermark = $('#s_watermark option:selected').attr('id');
        var watermark_opacity = $('#s_watermark_opacity').val();
        var gallery_transition = $('#g_transition option:selected').attr('id');
        var gallery_thumbs = $('#g_thumbs option:selected').attr('id');
        var gallery_autoplay = $('#g_autoplay').is(':checked')?1:0;
        var gallery_slide_duration = $('#g_slide_duration').val();
        switch(window.slideshow_type) {
            case 'local':
                var url_ajax = "../services/generate_slideshow.php";
                break;
            case 'cloud':
                var url_ajax = "../services/generate_slideshow_cloud.php";
                break;
        }
        $.ajax({
            url: url_ajax,
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                width: width,
                height: height,
                slide_duration: slide_duration,
                fade_duration: fade_duration,
                zoom_rate: zoom_rate,
                audio: audio,
                watermark: watermark,
                watermark_opacity: watermark_opacity,
                gallery_transition: gallery_transition,
                gallery_thumbs: gallery_thumbs,
                gallery_autoplay: gallery_autoplay,
                gallery_slide_duration: gallery_slide_duration
            },
            async: true,
            success: function (json) {
                try {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        $('#modal_generate_slideshow').modal('hide');
                        location.reload();
                    } else {
                        $('#btn_generate_slideshow').removeClass('disabled');
                        $('#modal_generate_slideshow').modal('hide');
                        alert(rsp.msg);
                    }
                } catch (e) {
                    $('#btn_generate_slideshow').removeClass('disabled');
                    $('#modal_generate_slideshow').modal('hide');
                    alert(window.backend_labels.generic_error_msg);
                }
            },
            error: function () {
                $('#btn_generate_slideshow').removeClass('disabled');
                $('#modal_generate_slideshow').modal('hide');
                alert(window.backend_labels.generic_error_msg);
            }
        });
    }

    window.download_file = function(uri) {
        var link = document.createElement("a");
        link.setAttribute('download', '');
        link.target = '_blank';
        link.href = uri;
        document.body.appendChild(link);
        link.click();
        link.remove();
    }

    window.rotate_image = function(image,id,angle) {
        $.ajax({
            url: "ajax/rotate_image_gallery.php",
            type: "POST",
            data: {
                id_gallery: id,
                filename: image,
                rotate: angle
            },
            async: false,
            success: function (json) {
                get_gallery_images(window.id_virtualtour);
            }
        });
    }

    window.toggle_gallery_image_visibility = function(id) {
        var visible = $('#gallery_image_visible_'+id).is(':checked');
        if(visible) {
            visible=1;
            $('#gallery_image_'+id).css('opacity',1);
        } else {
            visible=0;
            $('#gallery_image_'+id).css('opacity',0.6);
        }
        jQuery.each(window.gallery_images, function(index, image) {
            var id_ig = image.id;
            if(id_ig==id) {
                window.gallery_images[index].visible=visible;
            }
        });
        var num_gallery_images = 0;
        jQuery.each(window.gallery_images, function(index, image) {
            if(image.visible==1) {
                num_gallery_images++;
            }
        });
        if(num_gallery_images>=2) {
            $('#btn_generate_slideshow').removeClass('disabled');
        } else {
            $('#btn_generate_slideshow').addClass('disabled');
        }
        $.ajax({
            url: "ajax/set_gallery_image_visibility.php",
            type: "POST",
            data: {
                id_gallery: id,
                visible: visible
            },
            async: true,
            success: function () {}
        });
    }

    window.toggle_video_slide_visibility = function(id) {
        var visible = $('#visible_video_slide_'+id).is(':checked');
        if(visible) {
            visible=1;
            $('.video_slide[data-id="'+id+'"]').css('opacity',1);
        } else {
            visible=0;
            $('.video_slide[data-id="'+id+'"]').css('opacity',0.5);
        }
        var num_video_slides = 0;
        $('.video_slide.sort-item').each(function() {
            if($(this).css('opacity')==1) {
                num_video_slides++;
            }
        });
        if(num_video_slides>=1) {
            $('#btn_generate_video').removeClass('disabled');
        } else {
            $('#btn_generate_video').addClass('disabled');
        }
        jQuery.each(window.array_slides, function(index, slide) {
            if(parseInt(slide.id)==id) {
                window.array_slides[index].enabled = visible;
            }
        });
        calculate_timeline_duration();
        $.ajax({
            url: "ajax/set_video_slide_visibility.php",
            type: "POST",
            data: {
                id_slide: id,
                visible: visible
            },
            async: true,
            success: function () {}
        });
    }

    function parse_rooms_alt_images(rooms_alt_images) {
        var html = '';
        window.rooms_alt_images = rooms_alt_images;
        html += '<div data-id="'+window.id_room+'" style="position: relative;" class="image_room_alt no_drag float-left mb-2 ml-1 mr-1"><div class="remove_image_room_alt"><i onclick="edit_main_view_tooltip();" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-edit"></i></div><img draggable="false" style="height:90px;border-radius:5px;" src="'+window.panorama_image.replace('/panoramas/','/panoramas/thumb/')+'" /></div>';
        if(rooms_alt_images.length>=2) {
            var cursor = 'move';
        } else {
            var cursor = 'default';
        }
        if(window.virtual_staging==2) {
            var disabled = 'disabled';
        } else {
            var disabled = '';
        }
        jQuery.each(rooms_alt_images, function(index, image) {
            var id = image.id;
            var image = image.panorama_image;
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/panoramas/thumb/'+image;
            } else {
                var image_url = '../viewer/panoramas/thumb/'+image;
            }
            html += '<div data-id="'+id+'" style="position: relative;cursor: '+cursor+';" class="image_room_alt float-left mb-2 ml-1 mr-1"><div class="remove_image_room_alt"><i onclick="edit_view_tooltip('+index+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-edit '+disabled+'"></i>&nbsp;&nbsp;&nbsp;<i onclick="remove_image_room_alt('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><img draggable="false" style="height:90px;border-radius:5px;" src="'+image_url+'" /></div>';
        });
        $('#list_rooms_alt').html(html).promise().done(function() {
            if(rooms_alt_images.length>=2) {
                var el = document.getElementById('list_rooms_alt');
                Sortable.create(el,{
                    filter: ".no_drag",
                    onMove: function (e) { return e.related.className.indexOf('no_drag') === -1;  },
                    onEnd: function (evt) {
                        var array_images_priority = [];
                        $('#list_rooms_alt .image_room_alt').each(function () {
                            var id = $(this).attr('data-id');
                            array_images_priority.push(id);
                        });
                        change_rooms_alt_order(array_images_priority);
                    },
                });
            }
        });
    }

    function parse_gallery_images(images_array) {
        var html = '';
        window.gallery_images = images_array;
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var visible = image.visible;
            var image = image.image;
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/gallery/thumb/'+image+'?s3=1';
                var image_o_url = window.s3_url+'viewer/gallery/'+image+'?s3=1';
            } else {
                var image_url = '../viewer/gallery/thumb/'+image;
                var image_o_url = '../viewer/gallery/'+image;
            }
            if(visible==1) {
                var opacity=1;
                var checked = "checked";
            } else {
                var opacity=0.6;
                var checked = "";
            }
            html += '<div data-id="'+id+'" style="position:relative;cursor:move;min-width:120px;" class="image_gallery float-left mb-2 ml-1 mr-1"><div class="remove_image_gallery"><i onclick="edit_image_gallery('+index+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-heading"></i>&nbsp;&nbsp;&nbsp;<i onclick="remove_image_gallery('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><div class="rotate_image_gallery"><i onclick="rotate_image(\''+image+'\','+id+',-90);" class="fas fa-undo rotate_left"></i><i onclick="rotate_image(\''+image+'\','+id+',90);" style="transform:scaleX(-1);" class="fas fa-undo rotate_right"></i></div><div class="preview_content_btn"><a target="_blank" href="'+image_o_url+'"><i class="fas fa-external-link"></i></a></div><div class="visible_image_gallery"><input id="gallery_image_visible_'+id+'" onclick="toggle_gallery_image_visibility('+id+');" '+checked+' type="checkbox" /></div><img id="gallery_image_'+id+'" draggable="false" style="object-fit:cover;width:120px;height:120px;opacity:'+opacity+'" src="'+image_url+'" /></div>';
        });
        $('#list_images').html(html).promise().done(function () {
            var el = document.getElementById('list_images');
            Sortable.create(el,{
                onEnd: function (evt) {
                    var array_images_priority = [];
                    $('#list_images .image_gallery').each(function () {
                        var id = $(this).attr('data-id');
                        array_images_priority.push(id);
                    });
                    change_image_gallery_order(array_images_priority);
                },
            });
        });
        var num_gallery_images = 0;
        jQuery.each(window.gallery_images, function(index, image) {
            if(image.visible==1) {
                num_gallery_images++;
            }
        });
        if(num_gallery_images>=2) {
            $('#btn_generate_slideshow').removeClass('disabled');
        } else {
            $('#btn_generate_slideshow').addClass('disabled');
        }
    }

    function parse_intro_slider_images(images_array) {
        var html = '';
        window.intro_slider_images = images_array;
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var image = image.image;
            $('.image_gallery_slider[data-image="'+image+'"]').addClass('disabled');
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/gallery/thumb/'+image+'?s3=1';
            } else {
                var image_url = '../viewer/gallery/thumb/'+image;
            }
            html += '<div data-id="'+id+'" style="position:relative;cursor:move;min-width:120px;" class="image_intro_slider float-left mb-2 ml-1 mr-1"><div class="remove_image_gallery"><i onclick="remove_image_intro_slider('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><img id="gallery_image_'+id+'" draggable="false" style="object-fit:cover;width:120px;height:120px;opacity:1" src="'+image_url+'" /></div>';
        });
        $('#list_images').html(html).promise().done(function () {
            var el = document.getElementById('list_images');
            Sortable.create(el,{
                onEnd: function (evt) {
                    var array_images_priority = [];
                    $('#list_images .image_intro_slider').each(function () {
                        var id = $(this).attr('data-id');
                        array_images_priority.push(id);
                    });
                    change_image_intro_slider_order(array_images_priority);
                },
            });
        });
    }

    function parse_product_images(images_array) {
        var html = '';
        window.product_images = images_array;
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var image = image.image;
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/products/thumb/'+image;
            } else {
                var image_url = '../viewer/products/thumb/'+image;
            }
            html += '<div data-id="'+id+'" style="position: relative;cursor: move" class="image_product float-left mb-2 ml-1 mr-1"><div class="remove_image_product"><i onclick="remove_image_product('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><img draggable="false" style="height: 70px;" src="'+image_url+'" /></div>';
        });
        $('#list_images').html(html).promise().done(function () {
            var el = document.getElementById('list_images');
            Sortable.create(el,{
                onEnd: function (evt) {
                    var array_images_priority = [];
                    $('#list_images .image_product').each(function () {
                        var id = $(this).attr('data-id');
                        array_images_priority.push(id);
                    });
                    change_image_product_order(array_images_priority);
                },
            });
        });
    }

    function parse_media_library_files(files_array) {
        var html = '';
        window.media_library_files = files_array;
        jQuery.each(files_array, function(index, file_t) {
            var id = parseInt(file_t.id);
            var file = file_t.file;
            var from = file_t.from;
            var count = file_t.count;
            var id_vt = file_t.id_virtualtour;
            switch(from) {
                case 'media_library':
                    if(window.s3_enabled==1 && id_vt!='') {
                        var src = window.s3_url+'viewer/media/'+file;
                        var src_t = window.s3_url+'viewer/media/thumb/'+file;
                    } else {
                        var src = '../viewer/media/'+file;
                        var src_t = '../viewer/media/thumb/'+file;
                    }
                    break;
                case 'content':
                    if(window.s3_enabled==1 && id_vt!='') {
                        var src = window.s3_url+'viewer/content/'+file;
                        var src_t = window.s3_url+'viewer/content/thumb/'+file;
                    } else {
                        var src = '../viewer/content/'+file;
                        var src_t = '../viewer/content/thumb/'+file;
                    }
                    break;
            }
            if(file.includes('.mp4') || file.includes('.mov') || file.includes('.webm')) {
                var icon = '<span class="icon_type"><i class="fa fa-video"></i> '+count+'</span>';
                var html_file = '<video draggable="false" preload="auto" height="100px" src="'+src+'#t=2" playsinline webkit-playsinline autoplay loop muted style="height: 100px;"></video>';
            } else {
                var icon = '<span class="icon_type"><i class="fa fa-image"></i> '+count+'</span>';
                var html_file = '<img draggable="false" style="height: 100px;" src="'+src_t+'" onerror="this.src=\''+src+'\';this.onerror=\'\';" />';
            }
            if(id==0 || count>0 || window.id_virtualtour!=id_vt) {
                html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_media_library mb-2 ml-1 mr-1"><div class="preview_content_btn"><a target="_blank" href="'+src+'"><i class="fas fa-external-link"></i></a></div>'+icon+''+html_file+'</div>';
            } else {
                html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_media_library mb-2 ml-1 mr-1">'+icon+'<div class="remove_file_media_library"><i onclick="remove_media_library_file('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><div class="preview_content_btn"><a target="_blank" href="'+src+'"><i class="fas fa-external-link"></i></a></div>'+html_file+'</div>';
            }
        });
        $('#list_files').html(html).promise().done(function () {
            $("#list_files img").each(function(){
                var image = $(this);
                if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){
                    $(image).parent().hide();
                }
            });
        });
    }

    function parse_music_library_files(files_array) {
        var html = '';
        window.music_library_files = files_array;
        jQuery.each(files_array, function(index, file_t) {
            var id = parseInt(file_t.id);
            var file = file_t.file;
            var count = file_t.count;
            var id_vt = file_t.id_virtualtour;
            if(window.s3_enabled==1 && id_vt!='') {
                var src = window.s3_url+'viewer/content/'+file;
            } else {
                var src = '../viewer/content/'+file;
            }
            var file_name = file.split('.').slice(0, -1).join('.');
            var icon = '<span class="icon_type noselect"><i class="fa fa-music"></i> '+count+'</span>';
            var name = '<span class="name_file noselect">'+file_name+'</span>';
            var html_file = '<audio draggable="false" controls preload="auto" playsinline webkit-playsinline><source src="'+src+'" type="audio/mpeg"></audio>';
            if(id==0 || count>0 || window.id_virtualtour!=id_vt) {
                html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_music_library col-md-4 mb-2">'+icon+''+name+''+html_file+'</div>';
            } else {
                html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_music_library col-md-4 mb-2">'+icon+''+name+'<i onclick="remove_music_library_file('+id+');" style="font-size: 12px;cursor: pointer" class="remove_file_music_library fas fa-trash-alt"></i>'+html_file+'</div>';
            }
        });
        $('#list_files').html(html);
    }

    function parse_sound_library_files(files_array) {
        var html = '';
        window.sound_library_files = files_array;
        jQuery.each(files_array, function(index, file_t) {
            var id = parseInt(file_t.id);
            var file = file_t.file;
            var count = file_t.count;
            var id_vt = file_t.id_virtualtour;
            if(window.s3_enabled==1 && id_vt!='') {
                var src = window.s3_url+'viewer/content/'+file;
            } else {
                var src = '../viewer/content/'+file;
            }
            var file_name = file.split('.').slice(0, -1).join('.');
            var icon = '<span class="icon_type noselect"><i class="fa fa-music"></i> '+count+'</span>';
            var name = '<span class="name_file noselect">'+file_name+'</span>';
            var html_file = '<audio draggable="false" controls preload="auto" playsinline webkit-playsinline><source src="'+src+'" type="audio/mpeg"></audio>';
            if(id==0 || count>0 || window.id_virtualtour!=id_vt) {
                html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_music_library col-md-4 mb-2">'+icon+''+name+''+html_file+'</div>';
            } else {
                html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_music_library col-md-4 mb-2">'+icon+''+name+'<i onclick="remove_sound_library_file('+id+');" style="font-size: 12px;cursor: pointer" class="remove_file_music_library fas fa-trash-alt"></i>'+html_file+'</div>';
            }
        });
        $('#list_files').html(html);
    }

    function parse_poi_gallery_images(images_array) {
        var html = '';
        window.gallery_images = images_array;
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var image = image.image;
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/gallery/thumb/'+image+'?s3=1';
                var image_o_url = window.s3_url+'viewer/gallery/'+image+'?s3=1';
            } else {
                var image_url = '../viewer/gallery/thumb/'+image;
                var image_o_url = '../viewer/gallery/'+image;
            }
            html += '<div data-id="'+id+'" style="position: relative;cursor: move" class="image_gallery float-left mb-2 ml-1 mr-1"><div class="remove_image_gallery"><i onclick="edit_image_poi_gallery('+index+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-heading"></i>&nbsp;&nbsp;&nbsp;<i onclick="remove_image_poi_gallery('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><div class="preview_content_btn"><a target="_blank" href="'+image_o_url+'"><i class="fas fa-external-link"></i></a></div><img draggable="false" style="height: 90px;" src="'+image_url+'" /></div>';
        });
        $('#list_images').html(html).promise().done(function () {
            var el = document.getElementById('list_images');
            Sortable.create(el,{
                onEnd: function (evt) {
                    var array_images_priority = [];
                    $('#list_images .image_gallery').each(function () {
                        var id = $(this).attr('data-id');
                        array_images_priority.push(id);
                    });
                    change_poi_image_gallery_order(array_images_priority);
                },
            });
        });
    }

    function parse_poi_embed_gallery_images(images_array) {
        var html = '';
        window.gallery_images = images_array;
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var image = image.image;
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/gallery/thumb/'+image+'?s3=1';
            } else {
                var image_url = '../viewer/gallery/thumb/'+image;
            }
            html += '<div data-id="'+id+'" style="position: relative;cursor: move" class="image_gallery float-left mb-2 ml-1 mr-1"><div class="remove_image_embed_gallery"><i onclick="remove_image_poi_embed_gallery('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><img draggable="false" style="height: 90px;" src="'+image_url+'" /></div>';
        });
        $('#list_images').html(html).promise().done(function () {
            var el = document.getElementById('list_images');
            Sortable.create(el,{
                onEnd: function (evt) {
                    var array_images_priority = [];
                    $('#list_images .image_gallery').each(function () {
                        var id = $(this).attr('data-id');
                        array_images_priority.push(id);
                    });
                    change_poi_image_embed_gallery_order(array_images_priority);
                },
            });
        });
    }

    function parse_poi_object360_images(images_array) {
        var html = '';
        window.object360_images = images_array;
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var image = image.image;
            var millieconds = new Date().getMilliseconds();
            if(window.s3_enabled==1) {
                var image_url = window.s3_url+'viewer/objects360/'+image;
            } else {
                var image_url = '../viewer/objects360/'+image;
            }
            html += '<div data-id="'+id+'" style="position: relative;cursor: move" class="image_object360 float-left mb-2 ml-1 mr-1"><div class="remove_image_object360"><i onclick="remove_image_poi_object360('+id+');" style="font-size: 22px;color: white;cursor: pointer" class="fas fa-trash-alt"></i></div><img draggable="false" style="height: 70px;" src="'+image_url+'?v='+millieconds+'" /></div>';
        });
        $('#list_images').html(html).promise().done(function () {
            var array_images_priority = [];
            $('#list_images .image_object360').each(function () {
                var id = $(this).attr('data-id');
                array_images_priority.push(id);
            });
            change_poi_image_object360_order(array_images_priority);
            var el = document.getElementById('list_images');
            Sortable.create(el,{
                onEnd: function (evt) {
                    var array_images_priority = [];
                    $('#list_images .image_object360').each(function () {
                        var id = $(this).attr('data-id');
                        array_images_priority.push(id);
                    });
                    change_poi_image_object360_order(array_images_priority);
                },
            });
        });
    }

    function parse_icon_images(images_array) {
        var html = '';
        jQuery.each(images_array, function(index, image) {
            var id = image.id;
            var id_vt = image.id_virtualtour;
            var image = image.image;
            var ext = image.split('.').pop().toLowerCase();
            if(ext=='json') {
                var html_image = '<div class="lottie_icon_list" data-id="'+id+'" data-id_vt="'+id_vt+'" data-image="'+image+'" id="lottie_icon_'+id+'" style="height:100px;width:100px;vertical-align:middle"></div>';
            } else {
                if(window.s3_enabled==1 && id_vt!='') {
                    var image_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
                } else {
                    var image_url = '../viewer/icons/'+image;
                }
                var html_image = '<img draggable="false" style="height: 100px;" src="'+image_url+'" />';
            }
            if(window.id_virtualtour!=id_vt) {
                html += '<div data-id="'+id+'" style="position: relative" class="image_icon float-left mb-2 ml-1 mr-1"><div class="preview_content_btn"><a target="_blank" href="'+image_url+'"><i class="fas fa-external-link"></i></a></div>'+html_image+'</div>';
            } else {
                html += '<div data-id="'+id+'" style="position: relative" class="image_icon float-left mb-2 ml-1 mr-1"><div class="remove_image_icon"><i onclick="remove_image_icon('+id+');" style="font-size: 24px;color: white;cursor: pointer;" class="fas fa-trash-alt"></i></div><div class="preview_content_btn"><a target="_blank" href="'+image_url+'"><i class="fas fa-external-link"></i></a></div>'+html_image+'</div>';
            }
        });
        $('#list_images').html(html).promise().done(function () {
            $('.lottie_icon_list').each(function () {
                var id = $(this).attr('data-id');
                var image = $(this).attr('data-image');
                var id_vt = $(this).attr('data-id_vt');
                if(window.s3_enabled==1 && id_vt!='') {
                    var json_url = window.s3_url+'viewer/icons/'+image+'?s3=1';
                } else {
                    var json_url = '../viewer/icons/'+image;
                }
                bodymovin.loadAnimation({
                    container: document.getElementById('lottie_icon_'+id),
                    renderer: 'svg',
                    loop: true,
                    autoplay: true,
                    path: json_url,
                    rendererSettings: {
                        progressiveLoad: true,
                    }
                });
            });
        });
    }

    window.open_modal_media_library = function (type,target) {
        $('#modal_media_library .modal-body').empty();
        $('#modal_media_library').modal('show');
        $.ajax({
            url: "ajax/get_media_library_files.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                type: type
            },
            async: true,
            success: function (json) {
                var html = '';
                var files_array = JSON.parse(json);
                if(files_array.length==0) {
                    html = "<p>"+window.backend_labels.no_files_msg+"</p>";
                } else {
                    jQuery.each(files_array, function(index, file_t) {
                        var file = file_t.file;
                        var from = file_t.from;
                        var id_vt = file_t.id_vt;
                        switch(from) {
                            case 'media_library':
                                if(window.s3_enabled==1 && id_vt!='') {
                                    var src = window.s3_url+'viewer/media/'+file;
                                    var src_t = window.s3_url+'viewer/media/thumb/'+file;
                                } else {
                                    var src = '../viewer/media/'+file;
                                    var src_t = '../viewer/media/thumb/'+file;
                                }
                                break;
                            case 'content':
                                if(window.s3_enabled==1 && id_vt!='') {
                                    var src = window.s3_url+'viewer/content/'+file;
                                    var src_t = window.s3_url+'viewer/content/thumb/'+file;
                                } else {
                                    var src = '../viewer/content/'+file;
                                    var src_t = '../viewer/content/thumb/'+file;
                                }
                                break;
                        }
                        if(file.includes('.mp4') || file.includes('.mov') || file.includes('.webm')) {
                            var html_file = '<video preload="auto" src="'+src+'#t=2" playsinline webkit-playsinline muted style="height: 100px;"></video>';
                        } else {
                            var html_file = '<img style="height: 100px;" src="'+src_t+'" onerror="this.src=\''+src+'\';this.onerror=\'\';" />';
                        }
                        html += '<div onclick="select_media_library_file(\''+file+'\',\''+type+'\',\''+from+'\',\''+target+'\',\''+id_vt+'\');" style="display:inline-block;position:relative;vertical-align:top;cursor:pointer;" class="file_media_library mb-2 ml-1 mr-1">'+html_file+'</div>';
                    });
                }
                $('#modal_media_library .modal-body').html(html);
            }
        });
    }

    window.open_modal_music_library = function (target) {
        $('#modal_music_library .modal-body').empty();
        $('#modal_music_library').modal('show');
        $.ajax({
            url: "ajax/get_music_library_files.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour
            },
            async: true,
            success: function (json) {
                var html = '';
                var files_array = JSON.parse(json);
                if(files_array.length==0) {
                    html = "<p>"+window.backend_labels.no_files_msg+"</p>";
                } else {
                    jQuery.each(files_array, function(index, file_t) {
                        var file = file_t.file;
                        var id_vt = file_t.id_vt;
                        if(window.s3_enabled==1 && id_vt!='') {
                            var src = window.s3_url+'viewer/content/'+file;
                        } else {
                            var src = '../viewer/content/'+file;
                        }
                        var file_name = file.split('.').slice(0, -1).join('.');
                        var name = '<span class="name_file noselect">'+file_name+'</span>';
                        var html_file = '<audio controls preload="auto" playsinline webkit-playsinline><source src="'+src+'" type="audio/mpeg"></audio>';
                        html += '<div style="display:inline-block;position:relative;vertical-align:top;" class="file_music_library col-md-4 mb-2">'+name+'<i onclick="select_music_library_file(\''+file+'\',\''+target+'\');" style="font-size: 12px;cursor: pointer" class="remove_file_music_library fas fa-check-circle"></i>'+html_file+'</div>';
                    });
                }
                $('#modal_music_library .modal-body').html(html);
            }
        });
    }

    window.select_music_library_file = function(file,target) {
        var src = 'content/'+file;
        $('#'+target).val(src);
        $('#modal_music_library').modal('hide');
    }

    window.select_media_library_file = function(file,type,from,target,id_vt) {
        switch(from) {
            case 'media_library':
                var src = 'media/'+file;
                var src_h = 'media/'+file;
                if(window.s3_enabled==1 && id_vt!='') {
                    src_h = window.s3_url+'viewer/media/'+file;
                }
                break;
            case 'content':
                var src = 'content/'+file;
                var src_h = 'content/'+file;
                if(window.s3_enabled==1 && id_vt!='') {
                    src_h = window.s3_url+'viewer/content/'+file;
                }
                break;
        }
        switch(type) {
            case 'all':
                switch(target) {
                    case 'html':
                        if($('#poi_content_html_sc').is(':visible')) {
                            window.poi_content_html_sc.session.insert(window.poi_content_html_sc.getCursorPosition(), src_h);
                        } else {
                            $('.input_lang[data-target-id="poi_content_html_sc"]').each(function() {
                                if($(this).is(':visible')) {
                                    var lang = $(this).attr('data-lang');
                                    window.poi_content_html_sc_lang[lang].session.insert(window.poi_content_html_sc_lang[lang].getCursorPosition(), src_h);
                                }
                            });
                        }
                        break;
                    case 'html_vt':
                        window.custom_vt_html.session.insert(window.custom_vt_html.getCursorPosition(), src_h);
                        break;
                }
                break;
            case 'videos_transparent':
                var exists_videos = $('#'+target).val();
                var array_videos = exists_videos.split(",");
                var mov_video = '', webm_video = '';
                jQuery.each(array_videos, function(index_s, video_s) {
                    if(video_s.split('.').pop().toLowerCase()=='mov') {
                        mov_video = video_s;
                    }
                    if(video_s.split('.').pop().toLowerCase()=='webm') {
                        webm_video = video_s;
                    }
                });
                if(src.split('.').pop().toLowerCase()=='mov') {
                    mov_video = src;
                }
                if(src.split('.').pop().toLowerCase()=='webm') {
                    webm_video = src;
                }
                if(webm_video!='' && mov_video!='') {
                    var poi_embed_content = webm_video+','+mov_video;
                } else if(webm_video!='' && mov_video=='') {
                    var poi_embed_content = webm_video;
                } else if(webm_video=='' && mov_video!='') {
                    var poi_embed_content = mov_video;
                }
                if($('#'+target).is(':visible')) {
                    $('#'+target).val(poi_embed_content);
                } else {
                    $('.input_lang[data-target-id="'+target+'"]').each(function() {
                        if($(this).is(':visible')) {
                            var lang = $(this).attr('data-lang');
                            $(this).val(poi_embed_content);
                        }
                    });
                }
                break;
            default:
                if($('#'+target).is(':visible')) {
                    $('#'+target).val(src);
                } else {
                    $('.input_lang[data-target-id="'+target+'"]').each(function() {
                        if($(this).is(':visible')) {
                            var lang = $(this).attr('data-lang');
                            $(this).val(src);
                        }
                    });
                }
                break;
        }
        $('#modal_media_library').modal('hide');
        if(window.pois[poi_index_edit].embed_type!='') {
            switch(window.pois[poi_index_edit].embed_type) {
                case 'image':
                case 'video':
                case 'video_chroma':
                    window.pois[poi_index_edit].embed_content = src;
                    break;
                case 'videos_transparent':
                    window.pois[poi_index_edit].embed_content = poi_embed_content;
                    break;
            }
            render_poi(poi_id_edit,poi_index_edit);
        }
    }

    window.close_modal = function (id) {
        $('#'+id).modal('hide');
    }

    function change_rooms_order(array_rooms_priority) {
        var array_rooms_priority = JSON.stringify(array_rooms_priority);
        $.ajax({
            url: "ajax/change_rooms_order.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                array_rooms_priority: array_rooms_priority
            },
            async: false,
            success: function (json) {

            }
        });
    }

    function change_maps_order(array_maps_priority) {
        var array_maps_priority = JSON.stringify(array_maps_priority);
        $.ajax({
            url: "ajax/change_maps_order.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                array_maps_priority: array_maps_priority
            },
            async: false,
            success: function (json) {

            }
        });
    }

    function change_image_gallery_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_image_gallery_order.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    function change_image_intro_slider_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_image_intro_slider_order.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    window.change_video_slides_order = function(array_slides_priority) {
        var array_slides_priority = JSON.stringify(array_slides_priority);
        $.ajax({
            url: "ajax/change_video_slides_order.php",
            type: "POST",
            data: {
                id_video: window.id_video,
                array_slides_priority: array_slides_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    function change_rooms_alt_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_rooms_alt_order.php",
            type: "POST",
            data: {
                id_room: window.id_room,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    function change_image_product_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_image_product_order.php",
            type: "POST",
            data: {
                id_product: id_product,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    function change_poi_image_gallery_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_poi_image_gallery_order.php",
            type: "POST",
            data: {
                id_poi: window.id_poi,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    function change_poi_image_embed_gallery_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_poi_image_embed_gallery_order.php",
            type: "POST",
            data: {
                id_poi: window.id_poi,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    function change_poi_image_object360_order(array_images_priority) {
        var array_images_priority = JSON.stringify(array_images_priority);
        $.ajax({
            url: "ajax/change_poi_image_object360_order.php",
            type: "POST",
            data: {
                id_poi: window.id_poi,
                array_images_priority: array_images_priority
            },
            async: false,
            success: function (json) {}
        });
    }

    window.add_image_to_gallery = function(id_virtualtour,image) {
        $.ajax({
            url: "ajax/add_image_to_gallery.php",
            type: "POST",
            data: {
                image: image
            },
            async: true,
            success: function (json) {
                get_gallery_images(id_virtualtour);
            }
        });
    }

    window.add_image_to_intro_slider = function(id_virtualtour,image) {
        $.ajax({
            url: "ajax/add_image_to_intro_slider.php",
            type: "POST",
            data: {
                image: image
            },
            async: true,
            success: function (json) {
                get_intro_slider_images(id_virtualtour);
            }
        });
    }

    window.add_images_to_intro_slider = function(id_virtualtour) {
        $('#btn_add_image_to_slider').addClass('disabled');
        var images = [];
        $('.image_gallery_slider.selected').each(function() {
            var image = $(this).attr('data-image');
            images.push(image);
        });
        $.ajax({
            url: "ajax/add_images_to_intro_slider.php",
            type: "POST",
            data: {
                images: images
            },
            async: true,
            success: function (json) {
                $('#modal_gallery_images').modal('hide');
                $('#btn_add_image_to_slider').removeClass('disabled');
                $('.image_gallery_slider').removeClass('selected');
                get_intro_slider_images(id_virtualtour);
            }
        });
    }

    window.add_image_to_product = function(id_product,image) {
        $.ajax({
            url: "ajax/add_image_to_product.php",
            type: "POST",
            data: {
                id_product: id_product,
                image: image
            },
            async: true,
            success: function (json) {
                get_product_images(id_product);
            }
        });
    }

    window.add_file_to_media_library = function(id_virtualtour,file) {
        $.ajax({
            url: "ajax/add_file_to_media_library.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                file: file
            },
            async: true,
            success: function (json) {
                get_media_library_files(id_virtualtour);
            }
        });
    }

    window.add_file_to_music_library = function(id_virtualtour,file) {
        $.ajax({
            url: "ajax/add_file_to_music_library.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                file: file
            },
            async: true,
            success: function (json) {
                get_music_library_files(id_virtualtour);
            }
        });
    }

    window.add_file_to_sound_library = function(id_virtualtour,file) {
        $.ajax({
            url: "ajax/add_file_to_sound_library.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                file: file
            },
            async: true,
            success: function (json) {
                get_sound_library_files(id_virtualtour);
            }
        });
    }

    window.add_image_to_poi_gallery = function(id_poi,image) {
        $.ajax({
            url: "ajax/add_image_to_poi_gallery.php",
            type: "POST",
            data: {
                id_poi: id_poi,
                image: image
            },
            async: true,
            success: function (json) {
                get_poi_gallery_images(id_poi);
            }
        });
    }

    window.add_image_to_poi_embed_gallery = function(id_poi,image) {
        $.ajax({
            url: "ajax/add_image_to_poi_embed_gallery.php",
            type: "POST",
            data: {
                id_poi: id_poi,
                image: image
            },
            async: true,
            success: function (json) {
                get_poi_embed_gallery_images(id_poi);
            }
        });
    }

    window.add_image_to_poi_object360 = function(id_poi,image) {
        $.ajax({
            url: "ajax/add_image_to_poi_object360.php",
            type: "POST",
            data: {
                id_poi: id_poi,
                image: image
            },
            async: true,
            success: function (json) {
                get_poi_object360_images(id_poi);
            }
        });
    }

    window.add_image_to_icon = function(id_virtualtour,image) {
        $.ajax({
            url: "ajax/add_image_to_icon.php",
            type: "POST",
            data: {
                image: image
            },
            async: true,
            success: function (json) {
                get_icon_images(id_virtualtour);
            }
        });
    }

    window.add_image_to_icon_m = function(id_virtualtour,image,m) {
        $.ajax({
            url: "ajax/add_image_to_icon.php",
            type: "POST",
            data: {
                image: image
            },
            async: true,
            success: function (json) {
                get_icon_images_m(id_virtualtour,m);
            }
        });
    }

    window.edit_view_tooltip = function (index) {
        if($('.lang_input_switcher').length) {
            $('.lang_input_switcher').each(function() {
                var elem_o = $(this).attr('data-elem');
                var lang_o = $(this).attr('data-default-lang');
                switch_input_language(lang_o,lang_o,elem_o);
            });
        }
        var view_tooltip = window.rooms_alt_images[index].view_tooltip;
        $('.input_lang[data-target-id="view_tooltip"]').val('');
        jQuery.each(window.rooms_alt_images[index].array_lang, function(index_l,item_lang) {
            $('.input_lang[data-target-id="view_tooltip"][data-lang="'+item_lang.language+'"]').val(item_lang.view_tooltip);
        });
        var auto_open = parseInt(window.rooms_alt_images[index].auto_open);
        var from_hour = window.rooms_alt_images[index].from_hour;
        var to_hour = window.rooms_alt_images[index].to_hour;
        var auto_open = parseInt(window.rooms_alt_images[index].auto_open);
        if(auto_open==1) {
            $('#auto_open').prop('checked',true);
        } else {
            $('#auto_open').prop('checked',false);
        }
        $('#view_tooltip').val(view_tooltip);
        $('#from_hour').val(from_hour);
        $('#to_hour').val(to_hour);
        $('#modal_view_tooltip #btn_save_view_tooltip').attr('onclick','save_view_tooltip('+index+')');
        $('#modal_view_tooltip').modal("show");
    }

    window.edit_main_view_tooltip = function() {
        $('#modal_view_tooltip_main').modal('show');
    }

    window.edit_image_gallery = function (index) {
        if($('.lang_input_switcher').length) {
            $('.lang_input_switcher').each(function() {
                var elem_o = $(this).attr('data-elem');
                var lang_o = $(this).attr('data-default-lang');
                switch_input_language(lang_o,lang_o,elem_o);
            });
        }
        var title = window.gallery_images[index].title;
        $('#title').val(title);
        $('.input_lang[data-target-id="title"]').val('');
        jQuery.each(window.gallery_images[index].array_lang, function(index_l,item_lang) {
            $('.input_lang[data-target-id="title"][data-lang="'+item_lang.language+'"]').val(item_lang.title);
        });
        var description = window.gallery_images[index].description;
        $('#description').val(description);
        $('.input_lang[data-target-id="description"]').val('');
        jQuery.each(window.gallery_images[index].array_lang, function(index_l,item_lang) {
            $('.input_lang[data-target-id="description"][data-lang="'+item_lang.language+'"]').val(item_lang.description);
        });
        $('#modal_caption #btn_save_caption').attr('onclick','save_gallery_caption('+index+')');
        $('#modal_caption').modal("show");
    }

    window.edit_image_poi_gallery = function (index) {
        if($('.lang_input_switcher').length) {
            $('.lang_input_switcher').each(function() {
                var elem_o = $(this).attr('data-elem');
                var lang_o = $(this).attr('data-default-lang');
                switch_input_language(lang_o,lang_o,elem_o);
            });
        }
        var title = window.gallery_images[index].title;
        $('#title').val(title);
        $('.input_lang[data-target-id="title"]').val('');
        jQuery.each(window.gallery_images[index].array_lang, function(index_l,item_lang) {
            $('.input_lang[data-target-id="title"][data-lang="'+item_lang.language+'"]').val(item_lang.title);
        });
        var description = window.gallery_images[index].description;
        $('#description').val(description);
        $('.input_lang[data-target-id="description"]').val('');
        jQuery.each(window.gallery_images[index].array_lang, function(index_l,item_lang) {
            $('.input_lang[data-target-id="description"][data-lang="'+item_lang.language+'"]').val(item_lang.description);
        });
        $('#modal_caption #btn_save_caption').attr('onclick','save_poi_gallery_caption('+index+')');
        $('#modal_caption').modal("show");
    }

    window.save_view_tooltip = function(index) {
        $('#modal_view_tooltip #btn_save_view_tooltip').addClass('disabled');
        var view_tooltip = $('#view_tooltip').val();
        var array_lang = {};
        array_lang['view_tooltip'] = {};
        $('.input_lang[data-target-id="view_tooltip"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['view_tooltip'][lang]=value;
        });
        var auto_open = ($('#auto_open').is(':checked')) ? 1 : 0;
        var from_hour = $('#from_hour').val();
        var to_hour = $('#to_hour').val();
        var id = window.rooms_alt_images[index].id;
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_view_tooltip.php",
            type: "POST",
            data: {
                id: id,
                id_room: window.id_room,
                view_tooltip: view_tooltip,
                auto_open: auto_open,
                from_hour: from_hour,
                to_hour: to_hour,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {
                window.rooms_alt_images[index].view_tooltip = view_tooltip;
                window.rooms_alt_images[index].array_lang=[];
                $('.input_lang[data-target-id="view_tooltip"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    var tmp = {};
                    tmp.id_room_alt=id.toString();
                    tmp.language=lang;
                    tmp.view_tooltip=value;
                    window.rooms_alt_images[index].array_lang.push(tmp);
                });
                window.rooms_alt_images[index].auto_open = auto_open;
                jQuery.each(window.rooms_alt_images, function(index_r, image_r) {
                    if(index!=index_r) {
                        window.rooms_alt_images[index_r].auto_open = 0;
                    }
                });
                $('#modal_view_tooltip #btn_save_view_tooltip').removeClass('disabled');
                $('#modal_view_tooltip').modal("hide");
            }
        });
    }

    window.save_gallery_caption = function(index) {
        $('#modal_caption #btn_save_caption').addClass('disabled');
        var title = $('#title').val();
        var description = $('#description').val();
        var array_lang = {};
        array_lang['title'] = {};
        $('.input_lang[data-target-id="title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['title'][lang]=value;
        });
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['description'][lang]=value;
        });
        var id = window.gallery_images[index].id;
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_gallery_caption.php",
            type: "POST",
            data: {
                id: id,
                title: title,
                description: description,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {
                window.gallery_images[index].title = title;
                window.gallery_images[index].description = description;
                window.gallery_images[index].array_lang=[];
                $('.input_lang[data-target-id="title"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    var tmp = {};
                    tmp.id_gallery=id.toString();
                    tmp.language=lang;
                    tmp.title=value;
                    tmp.description=$('.input_lang[data-target-id="description"][data-lang="'+lang+'"]').val();
                    window.gallery_images[index].array_lang.push(tmp);
                });
                $('#modal_caption #btn_save_caption').removeClass('disabled');
                $('#modal_caption').modal("hide");
            }
        });
    }

    window.save_poi_gallery_caption = function(index) {
        $('#modal_caption #btn_save_caption').addClass('disabled');
        var title = $('#title').val();
        var description = $('#description').val();
        var array_lang = {};
        array_lang['title'] = {};
        $('.input_lang[data-target-id="title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['title'][lang]=value;
        });
        array_lang['description'] = {};
        $('.input_lang[data-target-id="description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['description'][lang]=value;
        });
        var id = window.gallery_images[index].id;
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/save_poi_gallery_caption.php",
            type: "POST",
            data: {
                id: id,
                title: title,
                description: description,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {
                window.gallery_images[index].title = title;
                window.gallery_images[index].description = description;
                window.gallery_images[index].array_lang=[];
                $('.input_lang[data-target-id="title"]').each(function() {
                    var lang = $(this).attr('data-lang');
                    var value = $(this).val();
                    var tmp = {};
                    tmp.id_gallery=id.toString();
                    tmp.language=lang;
                    tmp.title=value;
                    tmp.description=$('.input_lang[data-target-id="description"][data-lang="'+lang+'"]').val();
                    window.gallery_images[index].array_lang.push(tmp);
                });
                $('#modal_caption #btn_save_caption').removeClass('disabled');
                $('#modal_caption').modal("hide");
            }
        });
    }

    window.remove_image_room_alt = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_room_alt.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_rooms_alt_images(window.id_room);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_gallery = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_gallery.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    if(window.count_gallery_images_create==-1) {
                        get_gallery_images(window.id_virtualtour);
                    } else {
                        location.href='index.php?p=gallery';
                    }
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_intro_slider = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_intro_slider.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_intro_slider_images(window.id_virtualtour);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_product = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_product.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_product_images(window.id_product);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_media_library_file = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_file_to_media_library.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_media_library_files(window.id_virtualtour);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_music_library_file = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_file_to_music_library.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_music_library_files(window.id_virtualtour);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_sound_library_file = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_file_to_sound_library.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_sound_library_files(window.id_virtualtour);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_poi_gallery = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_poi_gallery.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_poi_gallery_images(window.id_poi);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_poi_embed_gallery = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_poi_embed_gallery.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_poi_embed_gallery_images(window.id_poi);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_poi_object360 = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_poi_object360.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_poi_object360_images(window.id_poi);
                }
            });
        } else {
            return false;
        }
    }

    window.remove_image_icon = function(id) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_image_to_icon.php",
                type: "POST",
                data: {
                    id: id
                },
                async: false,
                success: function (json) {
                    get_icon_images(window.id_virtualtour);
                }
            });
        } else {
            return false;
        }
    }

    window.check_plan = function(id_user,object) {
        $.ajax({
            url: "ajax/check_plan.php",
            type: "POST",
            data: {
                id_user: id_user,
                object: object
            },
            async: false,
            success: function (json) {
                var rsp = JSON.parse(json);
                window.can_create = rsp.can_create;
            }
        });
    }

    window.set_expiring_dates = function() {
        $('#btn_expires').addClass('disabled');
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        var start_url = $('#start_url').val();
        var end_url = $('#end_url').val();
        $.ajax({
            url: "ajax/set_expiring_dates.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                start_date: start_date,
                end_date: end_date,
                start_url: start_url,
                end_url: end_url
            },
            async: true,
            success: function (json) {
                $('#btn_expires').removeClass('disabled');
            }
        });
    }

    window.set_status_vt = function(status) {
        $.ajax({
            url: "ajax/set_status_vt.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                status: status
            },
            async: false,
            success: function (json) {}
        });
    }

    window.set_show_in_first_page = function(show_in_first_page,w) {
        switch(w) {
            case 'vt':
            case 'landing':
                var id = window.id_virtualtour;
                break;
            case 'globe':
                var id = window.id_globe;
                break;
            case 'showcase':
                var id = window.id_showcase;
                break;
        }
        $.ajax({
            url: "ajax/set_show_in_first_page.php",
            type: "POST",
            data: {
                id: id,
                w: w,
                show_in_first_page: show_in_first_page
            },
            async: false,
            success: function (json) {}
        });
    }

    window.check_lead_params = function() {
        var protect_name_enabled = ($('#protect_name_enabled').is(':checked')) ? 1 : 0;
        var protect_company_enabled = ($('#protect_company_enabled').is(':checked')) ? 1 : 0;
        var protect_email_enabled = ($('#protect_email_enabled').is(':checked')) ? 1 : 0;
        var protect_phone_enabled = ($('#protect_phone_enabled').is(':checked')) ? 1 : 0;
        if(protect_name_enabled==0) $('#protect_name_mandatory').prop('checked',false);
        if(protect_company_enabled==0) $('#protect_company_mandatory').prop('checked',false);
        if(protect_email_enabled==0) $('#protect_email_mandatory').prop('checked',false);
        if(protect_phone_enabled==0) $('#protect_phone_mandatory').prop('checked',false);
        var protect_name_mandatory = ($('#protect_name_mandatory').is(':checked')) ? 1 : 0;
        var protect_company_mandatory = ($('#protect_company_mandatory').is(':checked')) ? 1 : 0;
        var protect_email_mandatory = ($('#protect_email_mandatory').is(':checked')) ? 1 : 0;
        var protect_phone_mandatory = ($('#protect_phone_mandatory').is(':checked')) ? 1 : 0;
        if(protect_name_enabled==0 && protect_company_enabled==0 && protect_email_enabled==0 && protect_phone_enabled==0) {
            return false;
        }
        if(protect_name_mandatory==0 && protect_company_mandatory==0 && protect_email_mandatory==0 && protect_phone_mandatory==0) {
            return false;
        }
    }

    window.set_password_vt = function() {
        var array_lang = {};
        var password = $('#vt_password').val();
        var password_title = $('#vt_password_title').val();
        var password_description = $('#vt_password_description').val();
        array_lang['password_title'] = {};
        $('.input_lang[data-target-id="vt_password_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['password_title'][lang]=value;
        });
        array_lang['password_description'] = {};
        $('.input_lang[data-target-id="vt_password_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['password_description'][lang]=value;
        });
        var protect_mc_form = $('#protect_mc_form').val();
        var protect_type = $('#protect_type option:selected').attr('id');
        var protect_send_email = ($('#protect_send_email').is(':checked')) ? 1 : 0;
        var protect_email = $('#protect_email').val();
        var protect_lead_webhook_url = $('#protect_lead_webhook_url').val();
        var protect_remember = ($('#protect_remember').is(':checked')) ? 1 : 0;
        if(protect_type=='lead') {
            if(check_lead_params()==false) {
                alert(window.backend_labels.lead_params_error);
                return;
            }
        }
        var protect_lead_params = {};
        protect_lead_params['protect_name_enabled'] = ($('#protect_name_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_name_mandatory'] = ($('#protect_name_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_company_enabled'] = ($('#protect_company_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_company_mandatory'] = ($('#protect_company_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_email_enabled'] = ($('#protect_email_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_email_mandatory'] = ($('#protect_email_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_phone_enabled'] = ($('#protect_phone_enabled').is(':checked')) ? 1 : 0;
        protect_lead_params['protect_phone_mandatory'] = ($('#protect_phone_mandatory').is(':checked')) ? 1 : 0;
        protect_lead_params = JSON.stringify(protect_lead_params);
        $('#btn_protect').addClass('disabled');
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: "ajax/set_password_vt.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                password: password,
                password_title: password_title,
                password_description: password_description,
                protect_type: protect_type,
                protect_send_email: protect_send_email,
                protect_email: protect_email,
                protect_lead_webhook_url: protect_lead_webhook_url,
                protect_remember: protect_remember,
                protect_mc_form: protect_mc_form,
                protect_lead_params: protect_lead_params,
                array_lang: array_lang_json
            },
            async: true,
            success: function () {
                $('#btn_protect').removeClass('disabled');
            }
        });
    }

    window.check_license = function() {
        $('#btn_check_license').addClass("disabled");
        var purchase_code = $('#purchase_code').val();
        $.ajax({
            url: 'https://simpledemo.it/check_license_svt.php',
            type: "POST",
            data: {
                server_name: window.server_name,
                server_ip: window.server_ip,
                purchase_code: purchase_code
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                switch (rsp.status) {
                    case 'ok':
                        $('#license_status').html("<i style='color: green;' class=\"fas fa-circle\"></i> "+rsp.msg);
                        $('#license_status_saas').html("<i class=\"fas fa-circle\"></i> Unchecked");
                        var license = rsp.license;
                        var license2 = rsp.license2;
                        if(rsp.msg.indexOf('Extended') >= 0){
                            $('#registration_li').removeClass('d-none');
                            $('#payments_li').removeClass('d-none');
                            $('#license_status_saas').html("<i style='color: green;' class=\"fas fa-circle\"></i> Active");
                        }
                        if(rsp.msg.indexOf('Regular') >= 0){
                            $('#registration_li').addClass('d-none');
                            $('#payments_li').addClass('d-none');
                            $('#license_status_saas').html("<i style='color: red;' class=\"fas fa-circle\"></i> Inactive");
                        }
                        if(rsp.msg.indexOf('Invalid') >= 0){
                            $('#purchase_code').val('');
                            $('#registration_li').addClass('d-none');
                            $('#payments_li').addClass('d-none');
                            purchase_code = '';
                            license = '';
                            license2 = '';
                        }
                        if(rsp.msg.indexOf('already registered') >= 0){
                            $('#purchase_code').val('');
                            $('#registration_li').addClass('d-none');
                            $('#payments_li').addClass('d-none');
                            purchase_code = '';
                            license = '';
                            license2 = '';
                        }
                        break;
                    case 'error':
                        $('#license_status').html("<i style='color: red;' class=\"fas fa-circle\"></i> "+rsp.msg);
                        var license = '';
                        var license2 = '';
                        break;
                }
                $('#btn_check_license').removeClass("disabled");
                $.ajax({
                    url: "ajax/save_lic.php",
                    type: "POST",
                    data: {
                        purchase_code: purchase_code,
                        license: license,
                        license2: license2
                    },
                    async: true,
                    success: function () {
                        if(window.input_license==1 && license!='') {
                            window.settings_need_save=false;
                            location.href='index.php';
                        }
                    }
                });
            },
            error: function() {
                $('#btn_check_license').removeClass("disabled");
            }
        });
    }

    window.check_license_gsv = function() {
        $('#btn_check_license_gsv').addClass("disabled");
        var purchase_code = $('#purchase_code_gsv').val();
        $.ajax({
            url: 'https://simpledemo.it/check_license_svt_gsv.php',
            type: "POST",
            data: {
                server_name: window.server_name,
                server_ip: window.server_ip,
                purchase_code: purchase_code
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                switch (rsp.status) {
                    case 'ok':
                        $('#license_status_gsv').html("<i style='color: green;' class=\"fas fa-circle\"></i> "+rsp.msg);
                        var license = rsp.license;
                        var license2 = rsp.license2;
                        if(rsp.msg.indexOf('Active') >= 0){
                            $('#gsv_li').removeClass('d-none');
                        }
                        if(rsp.msg.indexOf('Invalid') >= 0){
                            $('#purchase_code_gsv').val('');
                            $('#gsv_li').addClass('d-none');
                            purchase_code = '';
                            license = '';
                            license2 = '';
                        }
                        if(rsp.msg.indexOf('already registered') >= 0){
                            $('#purchase_code_gsv').val('');
                            $('#gsv_li').addClass('d-none');
                            purchase_code = '';
                            license = '';
                            license2 = '';
                        }
                        break;
                    case 'error':
                        $('#license_status_gsv').html("<i style='color: red;' class=\"fas fa-circle\"></i> "+rsp.msg);
                        var license = '';
                        var license2 = '';
                        break;
                }
                $('#btn_check_license_gsv').removeClass("disabled");
                $.ajax({
                    url: "ajax/save_lic_gsv.php",
                    type: "POST",
                    data: {
                        purchase_code: purchase_code,
                        license: license,
                        license2: license2
                    },
                    async: true,
                    success: function () {}
                });
            },
            error: function() {
                $('#btn_check_license_gsv').removeClass("disabled");
            }
        });
    }

    window.set_session_vt = function(id) {
        $.ajax({
            url: "ajax/set_session_vt.php",
            type: "POST",
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    var url = window.location.href;
                    url = removeParam('id_vt',url);
                    url = removeParam('id_room',url);
                    url = removeParam('version',url);
                    location.href = url;
                }
            }
        });
    }

    window.show_info_edit_room = function(tab) {
        switch(tab) {
            case 'view':
                $('#initial_position_div').show();
                $('#north_div').hide();
                break;
            case 'positions':
                $('#initial_position_div').hide();
                $('#north_div').hide();
                break;
            case 'north':
                $('#initial_position_div').hide();
                $('#north_div').show();
                break;
            case 'effects':
            case 'bulk':
                $('#initial_position_div').hide();
                $('#north_div').hide();
                break;
        }
    }

    window.set_session_tab = function(page,tab) {
        if(page=='edit_room_preview') {
            show_info_edit_room(tab);
        }
        $.ajax({
            url: "ajax/set_session_tab.php",
            type: "POST",
            data: {
                page: page,
                tab: tab
            },
            async: true,
            success: function (json) {}
        });
    }

    window.set_session_theme_color = function(theme_color,sidebar_color_1,sidebar_color_2,theme_color_dark,sidebar_color_1_dark,sidebar_color_2_dark) {
        if(theme_color!='') {
            $.ajax({
                url: "ajax/set_session_theme_color.php",
                type: "POST",
                data: {
                    theme_color: theme_color,
                    sidebar_color_1: sidebar_color_1,
                    sidebar_color_2: sidebar_color_2,
                    theme_color_dark: theme_color_dark,
                    sidebar_color_1_dark: sidebar_color_1_dark,
                    sidebar_color_2_dark: sidebar_color_2_dark
                },
                async: true,
                success: function (json) {
                    var current_href = $('#css_theme').attr("href").split('?')[0];
                    $('#css_theme').attr("href", current_href + "?v=" + new Date().getMilliseconds());
                    var current_href = $('#css_theme_dark').attr("href").split('?')[0];
                    $('#css_theme_dark').attr("href", current_href + "?v=" + new Date().getMilliseconds());
                }
            });
        }
    }

    window.change_virtualtour = function() {
        var id = $('#virtualtour_selector option:selected').attr('id');
        $.ajax({
            url: "ajax/set_session_vt.php",
            type: "POST",
            data: {
                id_virtualtour: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    var url = window.location.href;
                    url = removeParam('id_vt',url);
                    url = removeParam('id_room',url);
                    url = removeParam('version',url);
                    url = url.replace(/#\s*$/, "");
                    location.href = url;
                    return false;
                }
            }
        });
    }

    window.change_protect_type = function () {
        var protect_type = $('#protect_type option:selected').attr('id');
        switch (protect_type) {
            case 'none':
                $('#passcode_title').parent().parent().removeClass('d-none');
                $('#passcode_description').parent().parent().removeClass('d-none');
                $('#passcode_code').parent().parent().removeClass('d-none');
                $('#protect_send_email').parent().parent().removeClass('d-none');
                $('#protect_email').parent().parent().removeClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().removeClass('d-none');
                $('#protect_mc_form').parent().parent().addClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().removeClass('d-none');
                $('#passcode_title').parent().addClass('disabled');
                $('#passcode_description').parent().addClass('disabled');
                $('#passcode_code').parent().addClass('disabled');
                $('#protect_send_email').parent().addClass('disabled');
                $('#protect_email').parent().addClass('disabled');
                $('#protect_lead_webhook_url').parent().addClass('disabled');
                $('#protect_remember').parent().addClass('disabled');
                $('#protect_name_enabled').parent().parent().addClass('disabled');
                $('#protect_company_enabled').parent().parent().addClass('disabled');
                $('#protect_email_enabled').parent().parent().addClass('disabled');
                $('#protect_phone_enabled').parent().parent().addClass('disabled');
                break;
            case 'passcode':
                $('#passcode_title').parent().parent().removeClass('d-none');
                $('#passcode_description').parent().parent().removeClass('d-none');
                $('#passcode_code').parent().parent().removeClass('d-none');
                $('#protect_send_email').parent().parent().removeClass('d-none');
                $('#protect_email').parent().parent().removeClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().removeClass('d-none');
                $('#protect_mc_form').parent().parent().addClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().removeClass('d-none');
                $('#passcode_title').parent().removeClass('disabled');
                $('#passcode_description').parent().removeClass('disabled');
                $('#passcode_code').parent().removeClass('disabled');
                $('#protect_send_email').parent().addClass('disabled');
                $('#protect_email').parent().addClass('disabled');
                $('#protect_lead_webhook_url').parent().addClass('disabled');
                $('#protect_remember').parent().removeClass('disabled');
                $('#protect_name_enabled').parent().parent().addClass('disabled');
                $('#protect_company_enabled').parent().parent().addClass('disabled');
                $('#protect_email_enabled').parent().parent().addClass('disabled');
                $('#protect_phone_enabled').parent().parent().addClass('disabled');
                break;
            case 'leads':
                $('#passcode_title').parent().parent().removeClass('d-none');
                $('#passcode_description').parent().parent().removeClass('d-none');
                $('#passcode_code').parent().parent().removeClass('d-none');
                $('#protect_send_email').parent().parent().removeClass('d-none');
                $('#protect_email').parent().parent().removeClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().removeClass('d-none');
                $('#protect_mc_form').parent().parent().addClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().removeClass('d-none');
                $('#passcode_title').parent().removeClass('disabled');
                $('#passcode_description').parent().removeClass('disabled');
                $('#passcode_code').parent().addClass('disabled');
                $('#protect_send_email').parent().removeClass('disabled');
                $('#protect_email').parent().removeClass('disabled');
                $('#protect_lead_webhook_url').parent().removeClass('disabled');
                $('#protect_remember').parent().removeClass('disabled');
                $('#protect_name_enabled').parent().parent().removeClass('disabled');
                $('#protect_company_enabled').parent().parent().removeClass('disabled');
                $('#protect_email_enabled').parent().parent().removeClass('disabled');
                $('#protect_phone_enabled').parent().parent().removeClass('disabled');
                break;
            case 'mailchimp':
                $('#passcode_title').parent().parent().addClass('d-none');
                $('#passcode_description').parent().parent().addClass('d-none');
                $('#passcode_code').parent().parent().addClass('d-none');
                $('#protect_send_email').parent().parent().addClass('d-none');
                $('#protect_email').parent().parent().addClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().addClass('d-none');
                $('#protect_mc_form').parent().parent().removeClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().addClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().addClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().addClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().addClass('d-none');
                $('#passcode_code').parent().addClass('disabled');
                $('#passcode_title').parent().removeClass('disabled');
                $('#passcode_description').parent().removeClass('disabled');
                $('#protect_send_email').parent().removeClass('disabled');
                $('#protect_email').parent().removeClass('disabled');
                $('#protect_lead_webhook_url').parent().removeClass('disabled');
                $('#protect_remember').parent().removeClass('disabled');
                $('#protect_name_enabled').parent().parent().addClass('disabled');
                $('#protect_company_enabled').parent().parent().addClass('disabled');
                $('#protect_email_enabled').parent().parent().addClass('disabled');
                $('#protect_phone_enabled').parent().parent().addClass('disabled');
                break;
        }
    }

    window.change_type_protection = function() {
        var protect_type = $('#protect_type option:selected').attr('id');
        switch (protect_type) {
            case 'none':
                $('#vt_password_title').parent().parent().removeClass('d-none');
                $('#vt_password_description').parent().parent().removeClass('d-none');
                $('#vt_password').parent().parent().removeClass('d-none');
                $('#protect_send_email').parent().parent().removeClass('d-none');
                $('#protect_email').parent().parent().removeClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().removeClass('d-none');
                $('#protect_mc_form').parent().parent().addClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().removeClass('d-none');
                $('#vt_password').parent().addClass('disabled');
                $('#vt_password_title').parent().addClass('disabled');
                $('#vt_password_description').parent().addClass('disabled');
                $('#protect_send_email').parent().addClass('disabled');
                $('#protect_email').parent().addClass('disabled');
                $('#protect_lead_webhook_url').parent().addClass('disabled');
                $('#protect_remember').parent().addClass('disabled');
                $('#protect_name_enabled').parent().parent().addClass('disabled');
                $('#protect_company_enabled').parent().parent().addClass('disabled');
                $('#protect_email_enabled').parent().parent().addClass('disabled');
                $('#protect_phone_enabled').parent().parent().addClass('disabled');
                break;
            case 'password':
                $('#vt_password_title').parent().parent().removeClass('d-none');
                $('#vt_password_description').parent().parent().removeClass('d-none');
                $('#vt_password').parent().parent().removeClass('d-none');
                $('#protect_send_email').parent().parent().removeClass('d-none');
                $('#protect_email').parent().parent().removeClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().removeClass('d-none');
                $('#protect_mc_form').parent().parent().addClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().removeClass('d-none');
                $('#vt_password').parent().removeClass('disabled');
                $('#vt_password_title').parent().removeClass('disabled');
                $('#vt_password_description').parent().removeClass('disabled');
                $('#protect_send_email').parent().addClass('disabled');
                $('#protect_email').parent().addClass('disabled');
                $('#protect_lead_webhook_url').parent().addClass('disabled');
                $('#protect_remember').parent().removeClass('disabled');
                $('#protect_name_enabled').parent().parent().addClass('disabled');
                $('#protect_company_enabled').parent().parent().addClass('disabled');
                $('#protect_email_enabled').parent().parent().addClass('disabled');
                $('#protect_phone_enabled').parent().parent().addClass('disabled');
                break;
            case 'lead':
                $('#vt_password_title').parent().parent().removeClass('d-none');
                $('#vt_password_description').parent().parent().removeClass('d-none');
                $('#vt_password').parent().parent().removeClass('d-none');
                $('#protect_send_email').parent().parent().removeClass('d-none');
                $('#protect_email').parent().parent().removeClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().removeClass('d-none');
                $('#protect_mc_form').parent().parent().addClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().removeClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().removeClass('d-none');
                $('#vt_password').parent().addClass('disabled');
                $('#vt_password_title').parent().removeClass('disabled');
                $('#vt_password_description').parent().removeClass('disabled');
                $('#protect_send_email').parent().removeClass('disabled');
                $('#protect_email').parent().removeClass('disabled');
                $('#protect_lead_webhook_url').parent().removeClass('disabled');
                $('#protect_remember').parent().removeClass('disabled');
                $('#protect_name_enabled').parent().parent().removeClass('disabled');
                $('#protect_company_enabled').parent().parent().removeClass('disabled');
                $('#protect_email_enabled').parent().parent().removeClass('disabled');
                $('#protect_phone_enabled').parent().parent().removeClass('disabled');
                break;
            case 'mailchimp':
                $('#vt_password_title').parent().parent().addClass('d-none');
                $('#vt_password_description').parent().parent().addClass('d-none');
                $('#vt_password').parent().parent().addClass('d-none');
                $('#protect_send_email').parent().parent().addClass('d-none');
                $('#protect_email').parent().parent().addClass('d-none');
                $('#protect_lead_webhook_url').parent().parent().addClass('d-none');
                $('#protect_mc_form').parent().parent().removeClass('d-none');
                $('#protect_name_enabled').parent().parent().parent().addClass('d-none');
                $('#protect_company_enabled').parent().parent().parent().addClass('d-none');
                $('#protect_email_enabled').parent().parent().parent().addClass('d-none');
                $('#protect_phone_enabled').parent().parent().parent().addClass('d-none');
                $('#vt_password').parent().addClass('disabled');
                $('#vt_password_title').parent().removeClass('disabled');
                $('#vt_password_description').parent().removeClass('disabled');
                $('#protect_send_email').parent().removeClass('disabled');
                $('#protect_email').parent().removeClass('disabled');
                $('#protect_lead_webhook_url').parent().removeClass('disabled');
                $('#protect_remember').parent().removeClass('disabled');
                $('#protect_name_enabled').parent().parent().addClass('disabled');
                $('#protect_company_enabled').parent().parent().addClass('disabled');
                $('#protect_email_enabled').parent().parent().addClass('disabled');
                $('#protect_phone_enabled').parent().parent().addClass('disabled');
                break;
        }
    }

    function removeParam(key, sourceURL) {
        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[0];
                if (param === key) {
                    params_arr.splice(i, 1);
                }
            }
            rtn = rtn + "?" + params_arr.join("&");
        }
        return rtn;
    }

    window.adjust_ratio_hfov = function (id_panorama,viewer,hfov,min_hfov,max_hfov) {
        var c_w = parseFloat($('#'+id_panorama).css('width').replace('px',''));
        var c_h = parseFloat($('#'+id_panorama).css('height').replace('px',''));
        var ratio_panorama = c_w / c_h;
        var ratio_hfov = 1.7771428571428571 / ratio_panorama;
        var min_hfov_t = min_hfov / ratio_hfov;
        var max_hfov_t = max_hfov / ratio_hfov;
        var hfov_t = hfov / ratio_hfov;
        viewer.setHfovBounds([min_hfov_t,max_hfov_t]);
        viewer.setHfov(hfov_t,false);
    }

    window.get_statistics = function (elem) {
        if(location.href.includes('edit_user')) {
            var id_virtualtour = null;
            var id_user = window.id_user_edit;
        } else {
            var id_virtualtour = window.id_virtualtour;
            var id_user = null;
        }
        $.ajax({
            url: "ajax/get_statistics.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                id_user: id_user,
                elem: elem
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if($('body').hasClass('dark_mode')) {
                    var label_color = '#FFFFFFA8';
                } else {
                    var label_color = '';
                }
                switch (elem) {
                    case 'chart_visitor_vt':
                        var data = rsp.data;
                        if($('body').hasClass('dark_mode')) {
                            Highcharts.stockChart('chart_visitor_vt', {
                                tooltip: {
                                    backgroundColor: 'rgba(0, 0, 0, 0.85)',
                                    style: {
                                        color: '#F0F0F0'
                                    },
                                    xDateFormat: '%e %B %Y',
                                    pointFormatter: function() {
                                        var point = this;
                                        return '<span style="color:' + point.color + '">\u25CF</span> <b>' + point.y.toFixed(0) + '</b>';
                                    }
                                },
                                xAxis: {
                                    gridLineColor: '#707073',
                                    labels: {
                                        style: {
                                            color: '#E0E0E3'
                                        }
                                    },
                                    lineColor: '#707073',
                                    minorGridLineColor: '#505053',
                                    tickColor: '#707073',
                                    title: {
                                        style: {
                                            color: '#A0A0A3'
                                        }
                                    },
                                    reversed: (window.rtl==1) ? true : false
                                },
                                yAxis: {
                                    gridLineColor: '#707073',
                                    labels: {
                                        style: {
                                            color: '#E0E0E3'
                                        }
                                    },
                                    lineColor: '#707073',
                                    minorGridLineColor: '#505053',
                                    tickColor: '#707073',
                                    tickWidth: 1,
                                    title: {
                                        style: {
                                            color: '#A0A0A3'
                                        }
                                    },
                                    opposite: (window.rtl==1) ? true : false
                                },
                                chart: {
                                    backgroundColor: {
                                        linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
                                        stops: [
                                            [0, '#2a2a2b'],
                                            [1, '#3e3e40']
                                        ]
                                    },
                                    plotBorderColor: '#606063',
                                    height: 400,
                                    rtl: (window.rtl==1) ? true : false
                                },
                                title: {
                                    text: ''
                                },
                                subtitle: {
                                    text: ''
                                },
                                rangeSelector: {
                                    buttonTheme: {
                                        fill: '#505053',
                                        stroke: '#000000',
                                        style: {
                                            color: '#CCC'
                                        },
                                        states: {
                                            hover: {
                                                fill: '#707073',
                                                stroke: '#000000',
                                                style: {
                                                    color: 'white'
                                                }
                                            },
                                            select: {
                                                fill: '#000003',
                                                stroke: '#000000',
                                                style: {
                                                    color: 'white'
                                                }
                                            }
                                        }
                                    },
                                    inputBoxBorderColor: '#505053',
                                    inputStyle: {
                                        backgroundColor: '#333',
                                        color: 'silver'
                                    },
                                    labelStyle: {
                                        color: 'silver'
                                    },
                                    inputDateFormat: '%d/%m/%Y',
                                    selected: 4,
                                    buttons: [{
                                        type: 'day',
                                        count: 7,
                                        text: '1W',
                                    },{
                                        type: 'month',
                                        count: 1,
                                        text: '1M',
                                    }, {
                                        type: 'month',
                                        count: 3,
                                        text: '3M'
                                    }, {
                                        type: 'month',
                                        count: 6,
                                        text: '6M'
                                    }, {
                                        type: 'year',
                                        count: 1,
                                        text: '1A'
                                    }, {
                                        type: 'all',
                                        text: 'ALL'
                                    }]
                                },
                                credits: {
                                    style: {
                                        color: '#2a2a2b'
                                    }
                                },
                                labels: {
                                    style: {
                                        color: '#707073'
                                    }
                                },
                                drilldown: {
                                    activeAxisLabelStyle: {
                                        color: '#F0F0F3'
                                    },
                                    activeDataLabelStyle: {
                                        color: '#F0F0F3'
                                    }
                                },
                                navigation: {
                                    buttonOptions: {
                                        symbolStroke: '#DDDDDD',
                                        theme: {
                                            fill: '#505053'
                                        }
                                    }
                                },
                                navigator: {
                                    handles: {
                                        backgroundColor: '#666',
                                        borderColor: '#AAA'
                                    },
                                    outlineColor: '#CCC',
                                    maskFill: 'rgba(255,255,255,0.1)',
                                    series: {
                                        color: '#7798BF',
                                        lineColor: '#A6C7ED'
                                    },
                                    xAxis: {
                                        gridLineColor: '#505053'
                                    }
                                },
                                scrollbar: {
                                    barBackgroundColor: '#808083',
                                    barBorderColor: '#808083',
                                    buttonArrowColor: '#CCC',
                                    buttonBackgroundColor: '#606063',
                                    buttonBorderColor: '#606063',
                                    rifleColor: '#FFF',
                                    trackBackgroundColor: '#404043',
                                    trackBorderColor: '#404043'
                                },
                                plotOptions: {
                                    series: {
                                        color: window.theme_color,
                                        dataGrouping: {
                                            approximation: "sum",
                                            units: [
                                                ['day', [1]],
                                                ['week', [1]],
                                                ['month', [1]],
                                            ],
                                            groupPixelWidth: 100
                                        }
                                    }
                                },
                                series: [{
                                    name: '',
                                    data: data,
                                    type: 'areaspline',
                                    threshold: null,
                                    tooltip: {
                                        valueDecimals: 0
                                    }
                                }],
                                responsive: {
                                    rules: [{
                                        condition: {
                                            maxWidth: 500
                                        },
                                        chartOptions: {
                                            chart: {
                                                height: 300
                                            },
                                            subtitle: {
                                                text: null
                                            },
                                            navigator: {
                                                enabled: false
                                            }
                                        }
                                    }]
                                }
                            });
                            Highcharts.setOptions(Highcharts.theme);
                        } else {
                            Highcharts.stockChart('chart_visitor_vt', {
                                tooltip: {
                                    xDateFormat: '%e %B %Y',
                                    pointFormatter: function() {
                                        var point = this;
                                        return '<span style="color:' + point.color + '">\u25CF</span> <b>' + point.y.toFixed(0) + '</b>';
                                    }
                                },
                                xAxis: {
                                    reversed: (window.rtl==1) ? true : false
                                },
                                yAxis: {
                                    opposite: (window.rtl==1) ? true : false
                                },
                                chart: {
                                    height: 400,
                                    rtl: (window.rtl==1) ? true : false
                                },
                                title: {
                                    text: ''
                                },
                                subtitle: {
                                    text: ''
                                },
                                rangeSelector: {
                                    inputDateFormat: '%d/%m/%Y',
                                    selected: 4,
                                    buttons: [{
                                        type: 'day',
                                        count: 7,
                                        text: '1W',
                                    },{
                                        type: 'month',
                                        count: 1,
                                        text: '1M',
                                    }, {
                                        type: 'month',
                                        count: 3,
                                        text: '3M'
                                    }, {
                                        type: 'month',
                                        count: 6,
                                        text: '6M'
                                    }, {
                                        type: 'year',
                                        count: 1,
                                        text: '1A'
                                    }, {
                                        type: 'all',
                                        text: 'ALL'
                                    }]
                                },
                                plotOptions: {
                                    series: {
                                        color: window.theme_color,
                                        dataGrouping: {
                                            approximation: "sum",
                                            units: [
                                                ['day', [1]],
                                                ['week', [1]],
                                                ['month', [1]],
                                            ],
                                            groupPixelWidth: 100
                                        }
                                    }
                                },
                                series: [{
                                    name: '',
                                    data: data,
                                    type: 'areaspline',
                                    threshold: null,
                                    tooltip: {
                                        valueDecimals: 0
                                    }
                                }],
                                responsive: {
                                    rules: [{
                                        condition: {
                                            maxWidth: 500
                                        },
                                        chartOptions: {
                                            chart: {
                                                height: 300
                                            },
                                            subtitle: {
                                                text: null
                                            },
                                            navigator: {
                                                enabled: false
                                            }
                                        }
                                    }]
                                }
                            });
                        }
                        break;
                    case 'chart_rooms_access':
                        var num_rooms = rsp.data.length;
                        new Chart(document.getElementById("chart_rooms_access"), {
                            type: 'horizontalBar',
                            data: {
                                labels: rsp.labels,
                                datasets: [{
                                    data: rsp.data,
                                    backgroundColor: window.theme_color,
                                    borderColor: window.theme_color,
                                    fill: false
                                }]
                            },
                            options: {
                                maintainAspectRatio: false,
                                legend: {
                                    display: false
                                },
                                scales: {
                                    xAxes: [{
                                        ticks: {
                                            fontColor: label_color,
                                            beginAtZero: true,
                                            reverse: (window.rtl==1) ? true : false
                                        }
                                    }],
                                    yAxes: [{
                                        position: (window.rtl==1) ? 'right' : 'left',
                                        ticks: {
                                            fontColor: label_color
                                        }
                                    }]
                                }
                            }
                        });
                        var height_chart = (num_rooms*20)+40;
                        $('#chart_rooms_access').css('height',height_chart+'px');
                        break;
                    case 'chart_rooms_time':
                        var num_rooms = rsp.data.length;
                        new Chart(document.getElementById("chart_rooms_time"), {
                            type: 'horizontalBar',
                            data: {
                                labels: rsp.labels,
                                datasets: [{
                                    data: rsp.data,
                                    backgroundColor: window.theme_color,
                                    borderColor: window.theme_color,
                                    fill: false
                                }]
                            },
                            options: {
                                maintainAspectRatio: false,
                                legend: {
                                    display: false
                                },
                                scales: {
                                    xAxes: [{
                                        ticks: {
                                            fontColor: label_color,
                                            beginAtZero: true,
                                            reverse: (window.rtl==1) ? true : false
                                        }
                                    }],
                                    yAxes: [{
                                        position: (window.rtl==1) ? 'right' : 'left',
                                        ticks: {
                                            fontColor: label_color,
                                        }
                                    }]
                                }
                            }
                        });
                        var height_chart = (num_rooms*20)+40;
                        $('#chart_rooms_time').css('height',height_chart+'px');
                        break;
                    case 'chart_poi_views':
                        var total_access = rsp.total_poi;
                        var html_pois = '';
                        jQuery.each(rsp.pois, function(index, poi) {
                            var room = poi.room;
                            var type = poi.type;
                            var content = poi.content;
                            var params = poi.params;
                            content = $($.parseHTML(content)).text();
                            switch (type) {
                                case 'image':
                                    type = window.backend_labels.image;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'video':
                                    type = window.backend_labels.video;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'video360':
                                    type = window.backend_labels.video360;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'download':
                                    type = window.backend_labels.download;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'gallery':
                                    type = window.backend_labels.image_gallery;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b>";
                                    break;
                                case 'audio':
                                    type = window.backend_labels.audio;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'link':
                                    type = window.backend_labels.link;
                                    if(content.length>100) {
                                        content = content.substring(0, 100)+"...";
                                    }
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'pdf':
                                    type = window.backend_labels.pdf;
                                    if(content.length>100) {
                                        content = content.substring(0, 100)+"...";
                                    }
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'pointclouds':
                                    type = window.backend_labels.pointclouds;
                                    if(content.length>100) {
                                        content = content.substring(0, 100)+"...";
                                    }
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'link_ext':
                                    type = window.backend_labels.link_ext;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'html':
                                    type = window.backend_labels.html;
                                    if(content.length>100) {
                                        content = content.substring(0, 100)+"...";
                                    }
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'html_sc':
                                    type = window.backend_labels.html_sc;
                                    if(content.length>100) {
                                        content = content.substring(0, 100)+"...";
                                    }
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'form':
                                    type = window.backend_labels.form;
                                    content = JSON.parse(content)[0].title;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'google_maps':
                                    type = window.backend_labels.google_maps;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b>";
                                    break;
                                case 'object360':
                                    type = window.backend_labels.object360;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b>";
                                    break;
                                case 'object3d':
                                    type = window.backend_labels.object3d;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b>";
                                    break;
                                case 'lottie':
                                    var name_poi = room+" - <b>Lottie</b>";
                                    break;
                                case 'product':
                                    type = window.backend_labels.product;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'callout':
                                    type = window.backend_labels.callout;
                                    type = type.substr(0,1).toUpperCase()+type.substr(1);
                                    try {
                                        var json = JSON.parse(params);
                                        content = json.title;
                                    } catch (e) {
                                        var content = '';
                                    }
                                    var name_poi = room+" - <b>"+type+"</b> - <i style='font-size:10px;'>"+content+"</i>";
                                    break;
                                case 'staging':
                                    type = window.backend_labels.staging;
                                    var name_poi = room+" - <b>"+type+"</b>";
                                    break;
                            }
                            var count = poi.access_count;
                            var perc = count / total_access * 100;
                            perc = Math.round(perc);
                            html_pois += '<h4 style="margin-bottom:1px;" class="small font-weight-bold">'+name_poi+' <span class="float-right"><b>'+count+'</b>/'+total_access+'</span></h4>\n' +
                                '                <div class="progress mb-2">\n' +
                                '                    <div class="progress-bar bg-primary" role="progressbar" style="width: '+perc+'%" aria-valuenow="'+perc+'" aria-valuemin="0" aria-valuemax="100"></div>\n' +
                                '                </div>';
                        });
                        $('#chart_poi_views').html(html_pois);
                        break;
                    case 'chart_time_slot':
                        new Chart(document.getElementById("chart_time_slot"), {
                            type: 'doughnut',
                            data: {
                                labels: rsp.labels,
                                datasets: [{
                                    data: rsp.data,
                                    backgroundColor: [
                                        'rgb(0, 204, 204)',
                                        'rgb(255, 128, 0)',
                                        'rgb(255, 205, 86)',
                                        'rgb(0, 0, 102)'
                                    ],
                                    hoverOffset: 30,
                                    fill: false
                                }]
                            },
                            options: {
                                elements: {
                                    arc: {
                                        borderWidth: 0
                                    }
                                },
                                aspectRatio: 1.5,
                                legend: {
                                    display: true,
                                    labels: {
                                        fontColor: label_color
                                    }
                                },
                                tooltips: {
                                    callbacks: {
                                        label: function(tooltipItem, data) {
                                            var value = data.datasets[0].data[tooltipItem.index];
                                            return value + " %";
                                        }
                                    }
                                }
                            }
                        });
                        break;
                }
            }
        });
    }

    window.get_statistics_learning = function (elem) {
        $.ajax({
            url: "ajax/get_statistics_learning.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                elem: elem
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                switch(elem) {
                    case 'summary':
                        $('#num_sessions').html(rsp.num_sessions);
                        $('#num_rooms_visited').html(rsp.num_rooms_visited);
                        $('#num_pois_visited').html(rsp.num_pois_visited);
                        $('#average_score').html(rsp.average_score);
                        $('#total_score span').html(rsp.total_score);
                        break;
                    case 'chart_learning_sessions':
                        var data = rsp.data;
                        if($('body').hasClass('dark_mode')) {
                            Highcharts.stockChart('chart_learning_sessions', {
                                tooltip: {
                                    backgroundColor: 'rgba(0, 0, 0, 0.85)',
                                    style: {
                                        color: '#F0F0F0'
                                    },
                                    xDateFormat: '%e %B %Y',
                                    pointFormatter: function() {
                                        var point = this;
                                        return '<span style="color:' + point.color + '">\u25CF</span> <b>' + point.y.toFixed(0) + '</b>';
                                    }
                                },
                                xAxis: {
                                    gridLineColor: '#707073',
                                    labels: {
                                        style: {
                                            color: '#E0E0E3'
                                        }
                                    },
                                    lineColor: '#707073',
                                    minorGridLineColor: '#505053',
                                    tickColor: '#707073',
                                    title: {
                                        style: {
                                            color: '#A0A0A3'
                                        }
                                    },
                                    reversed: (window.rtl==1) ? true : false
                                },
                                yAxis: {
                                    gridLineColor: '#707073',
                                    labels: {
                                        style: {
                                            color: '#E0E0E3'
                                        }
                                    },
                                    lineColor: '#707073',
                                    minorGridLineColor: '#505053',
                                    tickColor: '#707073',
                                    tickWidth: 1,
                                    title: {
                                        style: {
                                            color: '#A0A0A3'
                                        }
                                    },
                                    opposite: (window.rtl==1) ? true : false
                                },
                                chart: {
                                    backgroundColor: {
                                        linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
                                        stops: [
                                            [0, '#2a2a2b'],
                                            [1, '#3e3e40']
                                        ]
                                    },
                                    plotBorderColor: '#606063',
                                    height: 400,
                                    rtl: (window.rtl==1) ? true : false
                                },
                                title: {
                                    text: ''
                                },
                                subtitle: {
                                    text: ''
                                },
                                rangeSelector: {
                                    buttonTheme: {
                                        fill: '#505053',
                                        stroke: '#000000',
                                        style: {
                                            color: '#CCC'
                                        },
                                        states: {
                                            hover: {
                                                fill: '#707073',
                                                stroke: '#000000',
                                                style: {
                                                    color: 'white'
                                                }
                                            },
                                            select: {
                                                fill: '#000003',
                                                stroke: '#000000',
                                                style: {
                                                    color: 'white'
                                                }
                                            }
                                        }
                                    },
                                    inputBoxBorderColor: '#505053',
                                    inputStyle: {
                                        backgroundColor: '#333',
                                        color: 'silver'
                                    },
                                    labelStyle: {
                                        color: 'silver'
                                    },
                                    inputDateFormat: '%d/%m/%Y',
                                    selected: 4,
                                    buttons: [{
                                        type: 'day',
                                        count: 7,
                                        text: '1W',
                                    },{
                                        type: 'month',
                                        count: 1,
                                        text: '1M',
                                    }, {
                                        type: 'month',
                                        count: 3,
                                        text: '3M'
                                    }, {
                                        type: 'month',
                                        count: 6,
                                        text: '6M'
                                    }, {
                                        type: 'year',
                                        count: 1,
                                        text: '1A'
                                    }, {
                                        type: 'all',
                                        text: 'ALL'
                                    }]
                                },
                                credits: {
                                    style: {
                                        color: '#2a2a2b'
                                    }
                                },
                                labels: {
                                    style: {
                                        color: '#707073'
                                    }
                                },
                                drilldown: {
                                    activeAxisLabelStyle: {
                                        color: '#F0F0F3'
                                    },
                                    activeDataLabelStyle: {
                                        color: '#F0F0F3'
                                    }
                                },
                                navigation: {
                                    buttonOptions: {
                                        symbolStroke: '#DDDDDD',
                                        theme: {
                                            fill: '#505053'
                                        }
                                    }
                                },
                                navigator: {
                                    handles: {
                                        backgroundColor: '#666',
                                        borderColor: '#AAA'
                                    },
                                    outlineColor: '#CCC',
                                    maskFill: 'rgba(255,255,255,0.1)',
                                    series: {
                                        color: '#7798BF',
                                        lineColor: '#A6C7ED'
                                    },
                                    xAxis: {
                                        gridLineColor: '#505053'
                                    }
                                },
                                scrollbar: {
                                    barBackgroundColor: '#808083',
                                    barBorderColor: '#808083',
                                    buttonArrowColor: '#CCC',
                                    buttonBackgroundColor: '#606063',
                                    buttonBorderColor: '#606063',
                                    rifleColor: '#FFF',
                                    trackBackgroundColor: '#404043',
                                    trackBorderColor: '#404043'
                                },
                                plotOptions: {
                                    series: {
                                        color: window.theme_color,
                                        dataGrouping: {
                                            approximation: "sum",
                                            units: [
                                                ['day', [1]],
                                                ['week', [1]],
                                                ['month', [1]],
                                            ],
                                            groupPixelWidth: 100
                                        }
                                    }
                                },
                                series: [{
                                    name: '',
                                    data: data,
                                    type: 'areaspline',
                                    threshold: null,
                                    tooltip: {
                                        valueDecimals: 0
                                    }
                                }],
                                responsive: {
                                    rules: [{
                                        condition: {
                                            maxWidth: 500
                                        },
                                        chartOptions: {
                                            chart: {
                                                height: 300
                                            },
                                            subtitle: {
                                                text: null
                                            },
                                            navigator: {
                                                enabled: false
                                            }
                                        }
                                    }]
                                }
                            });
                            Highcharts.setOptions(Highcharts.theme);
                        } else {
                            Highcharts.stockChart('chart_learning_sessions', {
                                tooltip: {
                                    xDateFormat: '%e %B %Y',
                                    pointFormatter: function() {
                                        var point = this;
                                        return '<span style="color:' + point.color + '">\u25CF</span> <b>' + point.y.toFixed(0) + '</b>';
                                    }
                                },
                                xAxis: {
                                    reversed: (window.rtl==1) ? true : false
                                },
                                yAxis: {
                                    opposite: (window.rtl==1) ? true : false
                                },
                                chart: {
                                    height: 400,
                                    rtl: (window.rtl==1) ? true : false
                                },
                                title: {
                                    text: ''
                                },
                                subtitle: {
                                    text: ''
                                },
                                rangeSelector: {
                                    inputDateFormat: '%d/%m/%Y',
                                    selected: 4,
                                    buttons: [{
                                        type: 'day',
                                        count: 7,
                                        text: '1W',
                                    },{
                                        type: 'month',
                                        count: 1,
                                        text: '1M',
                                    }, {
                                        type: 'month',
                                        count: 3,
                                        text: '3M'
                                    }, {
                                        type: 'month',
                                        count: 6,
                                        text: '6M'
                                    }, {
                                        type: 'year',
                                        count: 1,
                                        text: '1A'
                                    }, {
                                        type: 'all',
                                        text: 'ALL'
                                    }]
                                },
                                plotOptions: {
                                    series: {
                                        color: window.theme_color,
                                        dataGrouping: {
                                            approximation: "sum",
                                            units: [
                                                ['day', [1]],
                                                ['week', [1]],
                                                ['month', [1]],
                                            ],
                                            groupPixelWidth: 100
                                        }
                                    }
                                },
                                series: [{
                                    name: '',
                                    data: data,
                                    type: 'areaspline',
                                    threshold: null,
                                    tooltip: {
                                        valueDecimals: 0
                                    }
                                }],
                                responsive: {
                                    rules: [{
                                        condition: {
                                            maxWidth: 500
                                        },
                                        chartOptions: {
                                            chart: {
                                                height: 300
                                            },
                                            subtitle: {
                                                text: null
                                            },
                                            navigator: {
                                                enabled: false
                                            }
                                        }
                                    }]
                                }
                            });
                        }
                        break;
                }
            },
            error: function() {}
        });
    }

    window.save_landing = function(id,html) {
        $.ajax({
            url: "ajax/save_landing.php",
            type: "POST",
            data: {
                id_virtualtour: id,
                html: html
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#landing_saving').hide();
                    $('#landing_editor').show();
                }
            }
        });
    }

    window.save_info = function(id,html,lang) {
        $.ajax({
            url: "ajax/save_info.php",
            type: "POST",
            data: {
                id_virtualtour: id,
                html: html,
                lang: lang
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#info_saving').hide();
                    if(lang=='') {
                        $('#info_editor').show();
                    } else {
                        $('#info_editor_'+lang).show();
                    }
                }
            }
        });
    }

    window.change_user_role = function () {
        var role = $('#role option:selected').attr('id');
        if(role=='editor') {
            $('.stats_div').hide();
            $('.plan_div').hide();
            $('.assign_vt_div').show();
        } else {
            $('.stats_div').show();
            $('.plan_div').show();
            $('.assign_vt_div').hide();
        }
    }

    window.check_multires_req = function () {
        $('#btn_check_multires_req').addClass('disabled');
        var multires = $('#multires option:selected').attr('id');
        var multires_cloud_url = $('#multires_cloud_url').val();
        switch(multires) {
            case 'local':
                var url = '../services/generate_multires.php';
                break;
            case 'cloud':
                var url = '../services/generate_multires_cloud.php';
                break;
        }
        $.ajax({
            url: url,
            type: "GET",
            data: {
                check_req: 1,
                multires_cloud_url: multires_cloud_url
            },
            async: true,
            success: function (json) {
                $('#btn_check_multires_req').removeClass('disabled');
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_check_multires_req .modal-body').css('color','green');
                } else {
                    $('#modal_check_multires_req .modal-body').css('color','red');
                }
                $('#modal_check_multires_req .modal-body').html(rsp.msg);
                $('#modal_check_multires_req').modal('show');
            }
        });
    }

    window.check_video360_req = function () {
        $('#btn_check_video360_req').addClass('disabled');
        var video360 = $('#video360 option:selected').attr('id');
        var video360_cloud_url = $('#video360_cloud_url').val();
        switch(video360) {
            case 'local':
                var url = '../services/generate_360video.php';
                break;
            case 'cloud':
                var url = '../services/generate_360video_cloud.php';
                break;
        }
        $.ajax({
            url: url,
            type: "GET",
            data: {
                check_req: 1,
                video360_cloud_url: video360_cloud_url
            },
            async: true,
            success: function (json) {
                $('#btn_check_video360_req').removeClass('disabled');
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_check_video360_req .modal-body').css('color','green');
                } else {
                    $('#modal_check_video360_req .modal-body').css('color','red');
                }
                $('#modal_check_video360_req .modal-body').html(rsp.msg);
                $('#modal_check_video360_req').modal('show');
            }
        });
    }

    window.check_slideshow_req = function () {
        $('#btn_check_slideshow_req').addClass('disabled');
        var slideshow = $('#slideshow option:selected').attr('id');
        var slideshow_cloud_url = $('#slideshow_cloud_url').val();
        switch(slideshow) {
            case 'local':
                var url = '../services/generate_slideshow.php';
                break;
            case 'cloud':
                var url = '../services/generate_slideshow_cloud.php';
                break;
        }
        $.ajax({
            url: url,
            type: "GET",
            data: {
                check_req: 1,
                slideshow_cloud_url: slideshow_cloud_url
            },
            async: true,
            success: function (json) {
                $('#btn_check_slideshow_req').removeClass('disabled');
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_check_slideshow_req .modal-body').css('color','green');
                } else {
                    $('#modal_check_slideshow_req .modal-body').css('color','red');
                }
                $('#modal_check_slideshow_req .modal-body').html(rsp.msg);
                $('#modal_check_slideshow_req').modal('show');
            }
        });
    }

    window.check_video_project_req = function () {
        $('#btn_check_video_project_req').addClass('disabled');
        var video_project = $('#video_project option:selected').attr('id');
        var video_project_url = $('#video_project_url').val();
        switch(video_project) {
            case 'local':
                var url = '../services/generate_video.php';
                break;
            case 'cloud':
                var url = '../services/generate_video_cloud.php';
                break;
        }
        $.ajax({
            url: url,
            type: "GET",
            data: {
                check_req: 1,
                video_project_url: video_project_url
            },
            async: true,
            success: function (json) {
                $('#btn_check_video_project_req').removeClass('disabled');
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_check_video_project_req .modal-body').css('color','green');
                } else {
                    $('#modal_check_video_project_req .modal-body').css('color','red');
                }
                $('#modal_check_video_project_req .modal-body').html(rsp.msg);
                $('#modal_check_video_project_req').modal('show');
            }
        });
    }

    window.regenerate_panoramas = function () {
        $('#btn_regenerate_panoramas').addClass('disabled');
        var compress_jpg = $('#compress_jpg').val();
        var max_width_compress = $('#max_width_compress').val();
        var enable_multires = $('#enable_multires').is(':checked');
        if(enable_multires) {
            switch(window.multires) {
                case 'local':
                    var url = '../services/generate_multires.php';
                    break;
                case 'cloud':
                    var url = '../services/generate_multires_cloud.php';
                    break;
            }
            $.ajax({
                url: url,
                type: "GET",
                data: {
                    check_req: 1
                },
                async: true,
                success: function (json) {
                    $('#btn_check_multires_req').removeClass('disabled');
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $.ajax({
                            url: "ajax/regenerate_multires.php",
                            type: "POST",
                            data: {
                                id_virtualtour: window.id_virtualtour,
                                compress_jpg: compress_jpg,
                                max_width_compress: max_width_compress,
                                enable_multires: enable_multires
                            },
                            async: true,
                            success: function (json) {
                                $('#btn_regenerate_panoramas').removeClass('disabled');
                                $('#modal_regenerate_multires .modal-body .error_msg').hide();
                                $('#modal_regenerate_multires .modal-body .ok_msg').show();
                                $('#modal_regenerate_multires').modal('show');
                            }
                        });
                    } else {
                        $('#btn_regenerate_panoramas').removeClass('disabled');
                        $('#modal_regenerate_multires .modal-body .error_msg').show();
                        $('#modal_regenerate_multires .modal-body .ok_msg').hide();
                        $('#modal_regenerate_multires').modal('show');
                    }
                }
            });
        } else {
            var keep_original_panorama = ($('#keep_original_panorama').is(':checked')) ? 1 : 0;
            $('#modal_regenerate_panoramas').modal('show');
            $.ajax({
                url: "../services/resize_panoramas.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    compress_jpg: compress_jpg,
                    max_width_compress: max_width_compress,
                    enable_multires: enable_multires,
                    keep_original_panorama: keep_original_panorama
                },
                async: true,
                success: function (json) {
                    $('#btn_regenerate_panoramas').removeClass('disabled');
                    $('#modal_regenerate_panoramas').modal('hide');
                }
            });
        }
    }

    window.delete_original_panoramas = function () {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            var html_btn = $('#btn_delete_original_panoramas').html();
            $('#btn_delete_original_panoramas').html('<i class="fas fa-spinner fa-circle-notch"></i>');
            $('#btn_delete_original_panoramas').addClass('disabled');
            $.ajax({
                url: "../services/clean_original_images.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour
                },
                async: true,
                success: function (json) {
                    $('#btn_delete_original_panoramas').html('<i class="fas fa-check"></i>');
                    setTimeout(function() {
                        $('#btn_delete_original_panoramas').removeClass('disabled');
                        $('#btn_delete_original_panoramas').html(html_btn);
                    },500);
                }
            });
        } else {
            return false;
        }
    }

    window.change_editor_css = function () {
        var id = $('#css_name option:selected').attr('id').replace('css_','');
        $('.editors_css').hide();
        $('#custom_b').show();
        $('#'+id).show();
    }

    window.change_editor_js = function () {
        var id = $('#js_name option:selected').attr('id').replace('js_custom','custom_js');
        $('.editors_js').hide();
        $('#custom_b_js').show();
        $('#'+id).show();
    }

    window.change_editor_head = function () {
        var id = $('#head_name option:selected').attr('id').replace('head_custom','custom_head');
        $('.editors_head').hide();
        $('#custom_b_head').show();
        $('#'+id).show();
    }

    window.change_editor_head_php = function () {
        var id = $('#head_name_php option:selected').attr('id').replace('head_custom_php','custom_head_php');
        $('.editors_head_php').hide();
        $('#custom_b_head_php').show();
        $('#'+id).show();
    }

    window.redirect_to_setup = function() {
        $('#modal_redirect_setup').modal('show');
        var postData = new FormData();
        postData.append('endpoint','setup_session');
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(session) {
            if(session.status=='ok') {
                return stripe.redirectToCheckout({ sessionId: session.id });
            } else {
                $('#modal_redirect_setup').modal('hide');
                alert(session.msg);
            }
        }).then(function(result) {
            if (result.error) {
                $('#modal_redirect_setup').modal('hide');
                alert(result.error.message);
            }
        }).catch(function(error) {
            $('#modal_redirect_setup').modal('hide');
        });
    }

    window.get_payment_method = function() {
        var postData = new FormData();
        postData.append('endpoint', 'payment_method');
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                $('#card_num').html("&bull;&bull;&bull;&bull; &bull;&bull;&bull;&bull; &bull;&bull;&bull;&bull; "+result.card);
            }
        });
    }

    window.open_inline_checkout = function(id_product,id_product2,email,url,live,id_plan) {
        $('#modal_redirect_checkout').modal('show');
        var postData = new FormData();
        postData.append('endpoint','create_customer');
        postData.append('id_user', window.id_user);
        fetch('../payments/2checkout_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(session) {
            if(session.status=='ok') {
                $('#modal_redirect_checkout').modal('hide');
                TwoCoInlineCart.products.removeAll();
                if($('#switcher_'+id_plan).length) {
                    if(!$('#switcher_'+id_plan).is(':checked')) {
                        id_product=id_product2;
                    }
                }
                TwoCoInlineCart.cart.setReset(true);
                TwoCoInlineCart.products.add({
                    code: id_product,
                    quantity: 1
                });
                TwoCoInlineCart.billing.setEmail(email);
                if(!live) {
                    TwoCoInlineCart.cart.setTest(true);
                }
                if(session.id!=0) {
                    TwoCoInlineCart.cart.setCustomerReference(session.id);
                }
                TwoCoInlineCart.cart.setReturnMethod({
                    type: 'redirect',
                    url : url
                });
                TwoCoInlineCart.cart.setCartLockedFlag(true);
                TwoCoInlineCart.cart.checkout();
            } else {
                $('#modal_redirect_checkout').modal('hide');
                alert(session.msg);
            }
        }).then(function(result) {
            if (result.error) {
                $('#modal_redirect_checkout').modal('hide');
                alert(result.error.message);
            }
        }).catch(function(error) {
            $('#modal_redirect_checkout').modal('hide');
        });
    }

    window.open_secure_checkout = function(id_product,id_product2,email,url,live,id_plan) {
        $('#modal_redirect_checkout').modal('show');
        var postData = new FormData();
        if($('#switcher_'+id_plan).length) {
            if(!$('#switcher_'+id_plan).is(':checked')) {
                id_product=id_product2;
            }
        }
        postData.append('endpoint','create_customer');
        postData.append('id_user', window.id_user);
        postData.append('id_product', id_product);
        postData.append('url', url);
        postData.append('origin_url', location.href);
        postData.append('live', live);
        fetch('../payments/2checkout_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(session) {
            if(session.status=='ok') {
                $('#modal_redirect_checkout').modal('hide');
                alert(session.url);
                location.href = session.url;
                /*var link = "https://secure.2checkout.com/checkout/buy/?merchant="+merchant_code+"&tpl=default&email="+email+"&prod="+id_product+"&qty=1&lock=1&empty-cart=1&return-url="+encodeURIComponent(url)+"&return-type=redirect&origin-url="+encodeURIComponent(location.href);
                if(session.id!=0) {
                    link += "&customer-ref="+session.id;
                }
                if(!live) {
                    link += "&test=1";
                }
                alert(link);
                location.href = link;*/
            } else {
                $('#modal_redirect_checkout').modal('hide');
                alert(session.msg);
            }
        }).then(function(result) {
            if (result.error) {
                $('#modal_redirect_checkout').modal('hide');
                alert(result.error.message);
            }
        }).catch(function(error) {
            $('#modal_redirect_checkout').modal('hide');
        });
    }

    window.redirect_to_checkout = function(id_plan) {
        $('#modal_redirect_checkout').modal('show');
        var second_price = 0;
        if($('#switcher_'+id_plan).length) {
            if(!$('#switcher_'+id_plan).is(':checked')) {
                second_price=1;
            }
        }
        var postData = new FormData();
        postData.append('endpoint','checkout_session');
        postData.append('id_plan', id_plan);
        postData.append('second_price', second_price);
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(session) {
            if(session.status=='ok') {
                return stripe.redirectToCheckout({ sessionId: session.id });
            } else {
                $('#modal_redirect_checkout').modal('hide');
                alert(session.msg);
            }
        }).then(function(result) {
            if (result.error) {
                $('#modal_redirect_checkout').modal('hide');
                alert(result.error.message);
            }
        }).catch(function(error) {
            $('#modal_redirect_checkout').modal('hide');
        });
    }

    window.redirect_to_checkout_service = function(id_service) {
        $('#modal_redirect_checkout').modal('show');
        var id_vt = 0;
        var count = 1;
        if($('#vt_sel_service_'+id_service).length) {
            id_vt = $('#vt_sel_service_'+id_service+' option:selected').val();
            count = $('#num_sel_rooms_'+id_service).val();
        }
        var note = $('#note_'+id_service).val();
        var postData = new FormData();
        postData.append('endpoint','checkout_session_service');
        postData.append('id_service', id_service);
        postData.append('id_vt', id_vt);
        postData.append('count', count);
        postData.append('note', note);
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(session) {
            if(session.status=='ok') {
                return stripe.redirectToCheckout({ sessionId: session.id });
            } else {
                $('#modal_redirect_checkout').modal('hide');
                alert(session.msg);
            }
        }).then(function(result) {
            if (result.error) {
                $('#modal_redirect_checkout').modal('hide');
                alert(result.error.message);
            }
        }).catch(function(error) {
            $('#modal_redirect_checkout').modal('hide');
        });
    }

    window.change_plan_proration = function(id_plan) {
        $('#new_plan').html("--");
        $('#next_payment').html("--");
        $('#subseq_payments').html("--");
        $('#btn_change_plan').addClass("disabled");
        $('#btn_change_plan').attr('onclick','change_subscription('+id_plan+')');
        $('#modal_change_plan').modal('show');
        var second_price = 0;
        if($('#switcher_'+id_plan).length) {
            if(!$('#switcher_'+id_plan).is(':checked')) {
                second_price=1;
            }
        }
        var postData = new FormData();
        postData.append('endpoint', 'proration');
        postData.append('id_plan', id_plan);
        postData.append('second_price', second_price);
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                $('#new_plan').html(result.plan.name);
                $('#next_payment').html(result.next_price);
                $('#subseq_payments').html(result.subseq_price);
                $('#btn_change_plan').removeClass("disabled");
            } else {
                $('#modal_change_plan').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_change_plan').modal('hide');
        });
    }

    window.change_subscription = function(id_plan) {
        $('#btn_change_plan').addClass("disabled");
        var second_price = 0;
        if($('#switcher_'+id_plan).length) {
            if(!$('#switcher_'+id_plan).is(':checked')) {
                second_price=1;
            }
        }
        var postData = new FormData();
        postData.append('endpoint','change_subscription');
        postData.append('id_plan', id_plan);
        postData.append('second_price', second_price);
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                location.reload();
            } else {
                $('#modal_change_plan').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_change_plan').modal('hide');
        });
    }

    window.open_modal_delete_plan = function () {
        $('#actual_plan').html("--");
        $('#active_until').html("--");
        $('#btn_delete_plan').addClass("disabled");
        $('#modal_delete_plan').modal('show');
        var postData = new FormData();
        postData.append('endpoint', 'subscription_end_date');
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                $('#actual_plan').html(result.name);
                $('#active_until').html(result.end_date);
                $('#btn_delete_plan').removeClass("disabled");
            } else {
                $('#modal_delete_plan').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_delete_plan').modal('hide');
        });
    }

    window.open_modal_delete_plan_2checkout = function () {
        $('#actual_plan_2checkout').html("--");
        $('#active_until_2checkout').html("--");
        $('#btn_delete_plan_2checkout').addClass("disabled");
        $('#modal_delete_plan_2checkout').modal('show');
        var postData = new FormData();
        postData.append('endpoint', 'subscription_end_date');
        fetch('../payments/2checkout_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                $('#actual_plan_2checkout').html(result.name);
                $('#active_until_2checkout').html(result.end_date);
                $('#btn_delete_plan_2checkout').removeClass("disabled");
            } else {
                $('#modal_delete_plan_2checkout').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_delete_plan_2checkout').modal('hide');
        });
    }

    window.open_modal_delete_plan_paypal = function () {
        $('#actual_plan_paypal').html("--");
        $('#active_until_paypal').html("--");
        $('#btn_delete_plan_paypal').addClass("disabled");
        $('#modal_delete_plan_paypal').modal('show');
        $.ajax({
            url: "ajax/get_paypal_subscription.php",
            type: "POST",
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    $('#actual_plan_paypal').html(rsp.name);
                    $('#active_until_paypal').html(rsp.end_date);
                    $('#btn_delete_plan_paypal').removeClass("disabled");
                }
            }
        });
    }

    window.cancel_subscription = function() {
        $('#btn_delete_plan').addClass("disabled");
        var postData = new FormData();
        postData.append('endpoint', 'cancel_subscription');
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                location.reload();
            } else {
                $('#modal_delete_plan').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_delete_plan').modal('hide');
        });
    }

    window.cancel_subscription_2checkout = function() {
        $('#btn_delete_plan_2checkout').addClass("disabled");
        var postData = new FormData();
        postData.append('endpoint', 'cancel_subscription');
        fetch('../payments/2checkout_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                location.reload();
            } else {
                $('#modal_delete_plan_2checkout').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_delete_plan_2checkout').modal('hide');
        });
    }

    window.cancel_subscription_paypal = function() {
        $('#btn_delete_plan_paypal').addClass("disabled");
        $.ajax({
            url: "ajax/cancel_paypal_subscription.php",
            type: "POST",
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    location.reload();
                } else {
                    $('#modal_delete_plan_paypal').modal('hide');
                    alert(rsp.msg);
                }
            }
        });
    }

    window.open_modal_reactivate_subscription = function () {
        $('#btn_reactivate_plan').removeClass("disabled");
        $('#modal_reactivate_plan').modal('show');
    }

    window.reactivate_subscription = function() {
        $('#btn_reactivate_plan').addClass("disabled");
        var postData = new FormData();
        postData.append('endpoint', 'reactivate_subscription');
        fetch('../payments/stripe_api.php', {
            method: 'POST',
            body: postData
        }).then(function(response) {
            return response.json();
        }).then(function(result) {
            if(result.status=='ok') {
                location.reload();
            } else {
                $('#modal_reactivate_plan').modal('hide');
                alert(result.msg);
            }
        }).catch(function(error) {
            $('#modal_reactivate_plan').modal('hide');
        });
    }

    window.apply_markers_lookat_all = function() {
        $('#modal_markers_lookat_apply').addClass("disabled");
        var lookat = $('#lookat option:selected').attr('id');
        $.ajax({
            url: "ajax/apply_markers_lookat_all.php",
            type: "POST",
            data: {
                lookat: lookat
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_markers_lookat_apply').modal('hide');
                    jQuery.each(window.markers, function(index, marker) {
                        window.markers[index].lookat = lookat;
                    });
                }
                $('#modal_markers_lookat_apply').removeClass("disabled");
            },
            error: function() {
                $('#modal_markers_lookat_apply').removeClass("disabled");
            }
        });
    }

    window.apply_default_moves = function(p) {
        var element = p;
        $('#modal_'+p+'_move_apply button').addClass("disabled");
        var rotateX = $('#rotateX').val();
        var rotateZ = $('#rotateZ').val();
        var size = $('#size_scale').val();
        var scale = $('#scale').is(':checked') ? 1 : 0;
        var sticky = $('#sticky').is(':checked') ? 1 : 0;
        var set_as_default = $('#set_as_default_m').is(':checked') ? 1 : 0;
        switch(p) {
            case 'markers':
                var apply_perspective = $('#apply_marker_perspective').is(':checked')?1:0;
                var apply_size = $('#apply_marker_size').is(':checked')?1:0;
                var apply_scale = $('#apply_marker_scale').is(':checked')?1:0;
                var apply_sticky = $('#apply_marker_sticky').is(':checked')?1:0;
                break;
            case 'pois':
                var apply_perspective = $('#apply_poi_perspective').is(':checked')?1:0;
                var apply_size = $('#apply_poi_size').is(':checked')?1:0;
                var apply_scale = $('#apply_poi_scale').is(':checked')?1:0;
                var apply_sticky = $('#apply_poi_sticky').is(':checked')?1:0;
                break;
        }
        if(apply_perspective==1 || apply_size==1 || apply_scale==1 || apply_sticky==1) {
            $.ajax({
                url: "ajax/apply_default_moves.php",
                type: "POST",
                data: {
                    p: element,
                    rotateX: rotateX,
                    rotateZ: rotateZ,
                    size: size,
                    scale: scale,
                    sticky: sticky,
                    apply_perspective: apply_perspective,
                    apply_size: apply_size,
                    apply_scale: apply_scale,
                    apply_sticky: apply_sticky,
                    set_as_default: set_as_default
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_'+element+'_move_apply').modal('hide');
                        switch(p) {
                            case 'markers':
                                if(window.id_room_sel!=0) {
                                    jQuery.each(window.rooms, function(index, room) {
                                        var id = room.id;
                                        var image = room.panorama_image;
                                        if(id==window.id_room_sel) {
                                            exit_move_marker(marker_id_edit,marker_index_edit);
                                            setTimeout(function() {
                                                select_room_marker(id,image,null);
                                            },210);
                                        }
                                    });
                                }
                                break;
                            case 'pois':
                                if(window.id_room_sel!=0) {
                                    jQuery.each(window.rooms, function(index, room) {
                                        var id = room.id;
                                        var image = room.panorama_image;
                                        if(id==window.id_room_sel) {
                                            exit_move_poi(poi_id_edit,poi_index_edit);
                                            setTimeout(function() {
                                                select_room_poi(id,image,null);
                                            },210);
                                        }
                                    });
                                }
                                break;
                        }
                    } else {
                        alert(rsp.msg);
                    }
                    $('#modal_'+element+'_move_apply button').removeClass("disabled");
                }
            });
        } else {
            $('#modal_'+element+'_move_apply button').removeClass("disabled");
        }
    }

    window.apply_default_styles = function(p) {
        var element = p;
        $('#modal_'+p+'_style_apply button').addClass("disabled");
        switch(p) {
            case 'markers':
                var icon = $('#markers_icon').val();
                var id_icon_library = $('#marker_library_icon').val();
                var color = $('#markers_color').val();
                var background = $('#markers_background').val();
                var style = $('#markers_style option:selected').attr('id');
                var icon_type = $('#markers_icon_type option:selected').attr('id');
                var tooltip_type = $('#markers_tooltip_type option:selected').attr('id');
                var tooltip_visibility = $('#markers_tooltip_visibility option:selected').attr('id');
                var tooltip_background = $('#markers_tooltip_background').val();
                var tooltip_color = $('#markers_tooltip_color').val();
                var default_scale = $('#markers_default_scale').is(':checked')?1:0;
                var default_sticky = $('#markers_default_sticky').is(':checked')?1:0;
                var rotateX = $('#markers_default_rotateX').val();
                var rotateZ = $('#markers_default_rotateZ').val();
                var size_scale = $('#markers_default_size_scale').val();
                var sound = $('#markers_default_sound option:selected').attr('id');
                var animation = $('#markers_animation option:selected').attr('id');
                var apply_style = $('#apply_marker_style').is(':checked')?1:0;
                var apply_icon = $('#apply_marker_icon').is(':checked')?1:0;
                var apply_color = $('#apply_marker_color').is(':checked')?1:0;
                var apply_background = $('#apply_marker_background').is(':checked')?1:0;
                var apply_icon_type = $('#apply_marker_icon_type').is(':checked')?1:0;
                var apply_tooltip_type = $('#apply_marker_tooltip_type').is(':checked')?1:0;
                var apply_tooltip_visibility = $('#apply_marker_tooltip_visibility').is(':checked')?1:0;
                var apply_tooltip_background = $('#apply_marker_tooltip_background').is(':checked')?1:0;
                var apply_tooltip_color = $('#apply_marker_tooltip_color').is(':checked')?1:0;
                var apply_default_scale = $('#apply_marker_default_scale').is(':checked')?1:0;
                var apply_default_sticky = $('#apply_marker_default_sticky').is(':checked')?1:0;
                var apply_perspective = $('#apply_marker_perspective').is(':checked')?1:0;
                var apply_size_scale = $('#apply_marker_size_scale').is(':checked')?1:0;
                var apply_sound = $('#apply_marker_default_sound').is(':checked')?1:0;
                var apply_animation = $('#apply_marker_animation').is(':checked')?1:0;
                var set_as_default = 0;
                switch(style) {
                    case 'room_and_icon':
                        style = 2;
                        break;
                    case 'icon_and_room':
                        style = 1;
                        break;
                    case 'only_icon':
                        style = 0;
                        break;
                    case 'only_room':
                        style = 3;
                        break;
                    case 'custom_icon':
                        style = 4;
                        break;
                    case 'preview_room':
                        style = 5;
                        break;
                    case 'label_and_icon':
                        style = 7;
                        break;
                    case 'icon_and_label':
                        style = 6;
                        break;
                    case 'only_label':
                        style = 8;
                        break;
                }
                break;
            case 'markers_e':
                element = 'markers';
                var icon = $('#marker_icon').val();
                var id_icon_library = $('#marker_library_icon').val();
                var color = $('#marker_color').val();
                var background = $('#marker_background').val();
                var style = $('#marker_style option:selected').attr('id');
                var icon_type = $('#marker_icon_type option:selected').attr('id');
                var tooltip_type = $('#tooltip_type option:selected').attr('id');
                var tooltip_visibility = $('#tooltip_visibility option:selected').attr('id');
                var tooltip_background = $('#tooltip_background').val();
                var tooltip_color = $('#tooltip_color').val();
                var default_scale = 0;
                var default_sticky = 0;
                var rotateX = 0;
                var rotateZ = 0;
                var size_scale = 0;
                var sound = $('#marker_sound option:selected').attr('id');
                var animation = $('#marker_animation option:selected').attr('id');
                var apply_style = $('#apply_marker_style').is(':checked')?1:0;
                var apply_tooltip_type = $('#apply_marker_tooltip_type').is(':checked')?1:0;
                var apply_icon = $('#apply_marker_icon').is(':checked')?1:0;
                var apply_color = $('#apply_marker_color').is(':checked')?1:0;
                var apply_background = $('#apply_marker_background').is(':checked')?1:0;
                var apply_icon_type = $('#apply_marker_icon_type').is(':checked')?1:0;
                var apply_tooltip_visibility = $('#apply_marker_tooltip_visibility').is(':checked')?1:0;
                var apply_tooltip_background = $('#apply_marker_tooltip_background').is(':checked')?1:0;
                var apply_tooltip_color = $('#apply_marker_tooltip_color').is(':checked')?1:0;
                var apply_default_scale = 0;
                var apply_default_sticky = 0;
                var apply_perspective = 0;
                var apply_size_scale = 0;
                var apply_sound = $('#apply_marker_sound').is(':checked')?1:0;
                var apply_animation = $('#apply_marker_animation').is(':checked')?1:0;
                var set_as_default = $('#set_as_default').is(':checked')?1:0;
                switch(style) {
                    case 'room_and_icon':
                        style = 2;
                        break;
                    case 'icon_and_room':
                        style = 1;
                        break;
                    case 'only_icon':
                        style = 0;
                        break;
                    case 'only_room':
                        style = 3;
                        break;
                    case 'custom_icon':
                        style = 4;
                        break;
                    case 'preview_room':
                        style = 5;
                        break;
                    case 'label_and_icon':
                        style = 7;
                        break;
                    case 'icon_and_label':
                        style = 6;
                        break;
                    case 'only_label':
                        style = 8;
                        break;
                }
                break;
            case 'pois':
                var icon = $('#pois_icon').val();
                var id_icon_library = $('#poi_library_icon').val();
                var color = $('#pois_color').val();
                var background = $('#pois_background').val();
                var style = $('#pois_style option:selected').attr('id');
                var icon_type = $('#pois_icon_type option:selected').attr('id');
                var tooltip_type = $('#pois_tooltip_type option:selected').attr('id');
                var tooltip_visibility = $('#pois_tooltip_visibility option:selected').attr('id');
                var tooltip_background = $('#pois_tooltip_background').val();
                var tooltip_color = $('#pois_tooltip_color').val();
                var default_scale = $('#pois_default_scale').is(':checked')?1:0;
                var default_sticky = $('#pois_default_sticky').is(':checked')?1:0;
                var rotateX = $('#pois_default_rotateX').val();
                var rotateZ = $('#pois_default_rotateZ').val();
                var size_scale = $('#pois_default_size_scale').val();
                var sound = $('#pois_default_sound option:selected').attr('id');
                var animation = $('#pois_animation option:selected').attr('id');
                var apply_style = $('#apply_poi_style').is(':checked')?1:0;
                var apply_icon = $('#apply_poi_icon').is(':checked')?1:0;
                var apply_color = $('#apply_poi_color').is(':checked')?1:0;
                var apply_background = $('#apply_poi_background').is(':checked')?1:0;
                var apply_icon_type = $('#apply_poi_icon_type').is(':checked')?1:0;
                var apply_tooltip_type = $('#apply_poi_tooltip_type').is(':checked')?1:0;
                var apply_tooltip_visibility = $('#apply_poi_tooltip_visibility').is(':checked')?1:0;
                var apply_tooltip_background = $('#apply_poi_tooltip_background').is(':checked')?1:0;
                var apply_tooltip_color = $('#apply_poi_tooltip_color').is(':checked')?1:0;
                var apply_default_scale = $('#apply_poi_default_scale').is(':checked')?1:0;
                var apply_default_sticky = $('#apply_poi_default_sticky').is(':checked')?1:0;
                var apply_perspective = $('#apply_poi_perspective').is(':checked')?1:0;
                var apply_size_scale = $('#apply_poi_size_scale').is(':checked')?1:0;
                var apply_sound = $('#apply_poi_default_sound').is(':checked')?1:0;
                var apply_animation = $('#apply_poi_animation').is(':checked')?1:0;
                var set_as_default = 0;
                switch(style) {
                    case 'label_and_icon':
                        style = 3;
                        break;
                    case 'icon_and_label':
                        style = 2;
                        break;
                    case 'only_icon':
                        style = 0;
                        break;
                    case 'only_label':
                        style = 4;
                        break;
                    case 'custom_icon':
                        style = 1;
                        break;
                }
                break;
            case 'pois_e':
                element = 'pois';
                var icon = $('#poi_icon').val();
                var id_icon_library = $('#poi_library_icon').val();
                var color = $('#poi_color').val();
                var background = $('#poi_background').val();
                var style = $('#poi_style option:selected').attr('id');
                var icon_type = $('#poi_icon_type option:selected').attr('id');
                var tooltip_type = $('#tooltip_type option:selected').attr('id');
                var tooltip_visibility = $('#tooltip_visibility option:selected').attr('id');
                var tooltip_background = $('#tooltip_background').val();
                var tooltip_color = $('#tooltip_color').val();
                var default_scale = 0;
                var default_sticky = 0;
                var rotateX = 0;
                var rotateZ = 0;
                var size_scale = 0;
                var sound = $('#poi_sound option:selected').attr('id');
                var animation = $('#poi_animation option:selected').attr('id');
                var apply_style = $('#apply_poi_style').is(':checked')?1:0;
                var apply_tooltip_type = $('#apply_poi_tooltip_type').is(':checked')?1:0;
                var apply_icon = $('#apply_poi_icon').is(':checked')?1:0;
                var apply_color = $('#apply_poi_color').is(':checked')?1:0;
                var apply_background = $('#apply_poi_background').is(':checked')?1:0;
                var apply_icon_type = $('#apply_poi_icon_type').is(':checked')?1:0;
                var apply_tooltip_visibility = $('#apply_poi_tooltip_visibility').is(':checked')?1:0;
                var apply_tooltip_background = $('#apply_poi_tooltip_background').is(':checked')?1:0;
                var apply_tooltip_color = $('#apply_poi_tooltip_color').is(':checked')?1:0;
                var apply_default_scale = 0;
                var apply_default_sticky = 0;
                var apply_perspective = 0;
                var apply_size_scale = 0;
                var apply_sound = $('#apply_poi_sound').is(':checked')?1:0;
                var apply_animation = $('#apply_poi_animation').is(':checked')?1:0;
                var set_as_default = $('#set_as_default').is(':checked')?1:0;
                switch(style) {
                    case 'label_and_icon':
                        style = 3;
                        break;
                    case 'icon_and_label':
                        style = 2;
                        break;
                    case 'only_icon':
                        style = 0;
                        break;
                    case 'only_label':
                        style = 4;
                        break;
                    case 'custom_icon':
                        style = 1;
                        break;
                }
                break;
        }
        if(p=='markers_e') change_exclude_apply_all('marker');
        if(p=='pois_e') change_exclude_apply_all('poi');
        $.ajax({
            url: "ajax/apply_default_styles.php",
            type: "POST",
            data: {
                element: element,
                p: p,
                icon: icon,
                icon_type: icon_type,
                id_icon_library: id_icon_library,
                color: color,
                background: background,
                style: style,
                tooltip_type: tooltip_type,
                tooltip_visibility: tooltip_visibility,
                tooltip_background: tooltip_background,
                tooltip_color: tooltip_color,
                default_scale: default_scale,
                default_sticky: default_sticky,
                rotateX: rotateX,
                rotateZ: rotateZ,
                size_scale: size_scale,
                sound: sound,
                animation: animation,
                apply_style: apply_style,
                apply_icon: apply_icon,
                apply_color: apply_color,
                apply_background: apply_background,
                apply_icon_type: apply_icon_type,
                apply_tooltip_type: apply_tooltip_type,
                apply_tooltip_visibility: apply_tooltip_visibility,
                apply_tooltip_background: apply_tooltip_background,
                apply_tooltip_color: apply_tooltip_color,
                apply_default_scale: apply_default_scale,
                apply_default_sticky: apply_default_sticky,
                apply_perspective: apply_perspective,
                apply_size_scale: apply_size_scale,
                apply_sound: apply_sound,
                apply_animation: apply_animation,
                set_as_default: set_as_default
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_'+element+'_style_apply').modal('hide');
                    switch(p) {
                        case 'markers_e':
                            if(window.id_room_sel!=0) {
                                jQuery.each(window.rooms, function(index, room) {
                                    var id = room.id;
                                    var image = room.panorama_image;
                                    if(id==window.id_room_sel) {
                                        exit_edit_marker(marker_id_edit,marker_index_edit);
                                        setTimeout(function() {
                                            select_room_marker(id,image,null);
                                        },210);
                                    }
                                });
                            }
                            break;
                        case 'pois_e':
                            if(window.id_room_sel!=0) {
                                jQuery.each(window.rooms, function(index, room) {
                                    var id = room.id;
                                    var image = room.panorama_image;
                                    if(id==window.id_room_sel) {
                                        exit_edit_poi(poi_id_edit,poi_index_edit);
                                        setTimeout(function() {
                                            select_room_poi(id,image,null);
                                        },210);
                                    }
                                });
                            }
                            break;
                    }
                } else {
                    alert(rsp.msg);
                }
                $('#modal_'+element+'_style_apply button').removeClass("disabled");
            }
        });
    }

    window.apply_default_initial_pos = function() {
        $('#modal_initial_position_apply button').addClass("disabled");
        var apply_yaw = $('#apply_initial_pos_yaw').is(':checked') ? 1 : 0;
        var apply_pitch = $('#apply_initial_pos_pitch').is(':checked') ? 1 : 0;
        var yaw_pitch = $('#yaw_pitch').val();
        var yaw = yaw_pitch.split(",")[0];
        var pitch = yaw_pitch.split(",")[1];
        if(apply_yaw==1 || apply_pitch==1) {
            $.ajax({
                url: "ajax/apply_default_initial_pos.php",
                type: "POST",
                data: {
                    yaw: yaw,
                    pitch: pitch,
                    apply_yaw: apply_yaw,
                    apply_pitch: apply_pitch
                },
                async: true,
                success: function () {
                    $('#modal_initial_position_apply').modal('hide');
                    $('#modal_initial_position_apply button').removeClass("disabled");
                }
            });
        } else {
            $('#modal_initial_position_apply button').removeClass("disabled");
        }
    }

    window.apply_default_north = function() {
        var north = $('#northOffset').val();
        $('#modal_north_apply button').addClass("disabled");
        $.ajax({
            url: "ajax/apply_default_north.php",
            type: "POST",
            data: {
                north: north,
            },
            async: true,
            success: function () {
                $('#modal_north_apply').modal('hide');
                $('#modal_north_apply button').removeClass("disabled");
            }
        });
    }

    window.apply_default_effects = function() {
        var brightness = $('#brightness').val();
        var contrast = $('#contrast').val();
        var saturate = $('#saturate').val();
        var grayscale = $('#grayscale').val();
        $('#modal_effects_apply button').addClass("disabled");
        $.ajax({
            url: "ajax/apply_default_effects.php",
            type: "POST",
            data: {
                brightness: brightness,
                contrast: contrast,
                saturate: saturate,
                grayscale: grayscale
            },
            async: true,
            success: function () {
                $('#modal_effects_apply').modal('hide');
                $('#modal_effects_apply button').removeClass("disabled");
            }
        });
    }

    window.view_preview_panorama_image = function() {
        $('#preview_image img').hide();
        $('#btn_preview_panorama_image').hide();
        $('#preview_panorama_image').show();
        $('#btn_close_panorama_image').show();
        $('#btn_full_panorama_image').show();
    }

    window.fullscreen_preview_panorama_image = function() {
        var type = $('#type_pano option:selected').attr('id');
        switch (type) {
            case 'video':
                toggle_fullscreen_div('video_viewer');
                break;
            default:
                toggle_fullscreen_div('preview_panorama_image');
                break;
        }
    }

    window.close_preview_panorama_image = function() {
        $('#preview_image img').show();
        $('#btn_preview_panorama_image').show();
        $('#preview_panorama_image').hide();
        $('#btn_close_panorama_image').hide();
        $('#btn_full_panorama_image').hide();
    }

    window.view_preview_panorama_ai = function() {
        $('#preview_image_ai img').hide();
        $('#btn_preview_panorama_ai').hide();
        $('#preview_panorama_ai').show();
        $('#btn_close_panorama_ai').show();
        $('#btn_full_panorama_ai').show();
    }

    window.fullscreen_preview_panorama_ai = function() {
        toggle_fullscreen_div('preview_panorama_ai');
    }

    window.close_preview_panorama_ai = function() {
        $('#preview_image_ai img').show();
        $('#btn_preview_panorama_ai').show();
        $('#preview_panorama_ai').hide();
        $('#btn_close_panorama_ai').hide();
        $('#btn_full_panorama_ai').hide();
    }

    window.load_viewer_preview_room = function (elem,panorama_image) {
        try {
            window.viewer_preview_room.destroy();
        } catch (e) {}
        try {
            window.viewer_video.pnlmViewer.destroy();
            window.viewer_video.dispose();
            window.viewer_video = null;
            $('#'+elem).empty();
        } catch (e) {}
        window.viewer_preview_room = pannellum.viewer(elem, {
            "type": "equirectangular",
            "panorama": panorama_image,
            "autoLoad": true,
            "showFullscreenCtrl": true,
            "showControls": false,
            "hfov": 100,
            "yaw": 0,
            "pitch": 0,
            "compass": false,
            "friction": 1,
            "strings": {
                "loadingLabel": window.backend_labels.loading+"...",
            },
        });
    }

    window.load_viewer_preview_room_l = function (elem,panorama_image,panorama_json) {
        try {
            window.viewer_preview_room.destroy();
        } catch (e) {}
        try {
            window.viewer_video.pnlmViewer.destroy();
            window.viewer_video.dispose();
            window.viewer_video = null;
            $('#'+elem).empty();
        } catch (e) {}
        var img_lottie = new Image();
        img_lottie.onload = function() {
            var canvas = document.createElement('canvas');
            canvas.width = this.width;
            canvas.height = this.height;
            var lottie_context = canvas.getContext('2d');
            lottie_context.drawImage(img_lottie, 0, 0);
            var lottie_pano = bodymovin.loadAnimation({
                renderer: 'canvas',
                loop: true,
                autoplay: true,
                path: panorama_json+(window.s3_enabled) ? '?s3=1' : '',
                rendererSettings: {
                    context: lottie_context,
                    progressiveLoad: true,
                }
            });
            window.viewer_preview_room = pannellum.viewer(elem, {
                "type": "equirectangular",
                "panorama": canvas,
                "autoLoad": true,
                "dynamic": true,
                "dynamicUpdate": true,
                "showFullscreenCtrl": false,
                "showControls": false,
                "multiResMinHfov": true,
                "hfov": 100,
                "yaw": 0,
                "pitch": 0,
                "compass": false,
                "friction": 1,
                "strings": {
                    "loadingLabel": window.backend_labels.loading + "...",
                },
            });
        }
        img_lottie.crossOrigin = false;
        img_lottie.src = panorama_image;
    }

    window.load_viewer_preview_room_v = function (elem,panorama_video) {
        try {
            window.viewer_preview_room.destroy();
        } catch (e) {}
        try {
            window.viewer_video.pnlmViewer.destroy();
            window.viewer_video.dispose();
            window.viewer_video = null;
            $('#'+elem).empty();
        } catch (e) {}
        var fileExt = panorama_video.split('.').pop().toLowerCase();
        switch(fileExt) {
            case 'webm':
                var type_video = 'video/webm';
                break;
            default:
                var type_video = 'video/mp4';
                break;
        }
        $('#'+elem).append('<video playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="width: 100%;height: 232px;margin: 0 auto;" muted preload="none" crossorigin="anonymous"><source src="'+panorama_video+'" type="'+type_video+'"/></video>');
        window.viewer_video = videojs('video_viewer', {
            loop: true,
            autoload: true,
            muted: true,
            plugins: {
                pannellum: {
                    "autoLoad": true,
                    "showFullscreenCtrl": false,
                    "showControls": false,
                    "hfov": 100,
                    "yaw": 0,
                    "pitch": 0,
                    "compass": false,
                    "friction": 1,
                    "strings": {
                        "loadingLabel": window.backend_labels.loading+"...",
                    },
                }
            }
        });
        window.viewer_video.load();
        window.viewer_video.on('ready', function() {
            window.viewer_video.play();
        });
    }

    window.load_viewer_pos = function (elem,id_room,panorama_image,yaw,pitch,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,hfov,northOffset=null) {
        try {
            window.viewer_pos.destroy();
        } catch (e) {}
        switch(elem) {
            case 'panorama_pos_slide':
                var min_hov = 40;
                var max_hfov = 140;
                break;
            case 'panorama_pos_presentation':
                var min_hov = parseFloat(window.p_min_hfov);
                var max_hfov = parseFloat(window.p_max_hfov);
                break;
            default:
                var min_hov = 100;
                var max_hfov = 100;
                break
        }
        window.viewer_pos = pannellum.viewer(elem, {
            "id_room": parseInt(id_room),
            "type": "equirectangular",
            "panorama": panorama_image,
            "autoLoad": true,
            "showFullscreenCtrl": false,
            "showControls": false,
            "horizonPitch": parseInt(h_pitch),
            "horizonRoll": parseInt(h_roll),
            "hfov": hfov,
            "minHfov": min_hov,
            "maxHfov": max_hfov,
            "yaw": yaw,
            "pitch": pitch,
            "minPitch": parseInt(min_pitch),
            "maxPitch" : parseInt(max_pitch),
            "minYaw": parseInt(min_yaw),
            "maxYaw" : parseInt(max_yaw),
            "haov": parseInt(haov),
            "vaov": parseInt(vaov),
            "compass": false,
            "friction": 1,
            "strings": {
                "loadingLabel": window.backend_labels.loading+"...",
            },
        });
        window.viewer_pos.on('load', function () {
            $('#confirm_edit .btn_confirm').removeClass("disabled");
            $('#confirm_edit .btn_confirm_go').removeClass("disabled");
            $('#btn_new_marker').removeClass("disabled");
            switch(elem) {
                case 'panorama_pos_slide':
                    $('#play_slide_panorama_btn').removeClass('disabled');
                    $('#panorama_slide_start_btn').removeClass('disabled');
                    $('#panorama_slide_end_btn').removeClass('disabled');
                    break;
                case 'panorama_pos_presentation':
                    $('#btn_add_p_room').removeClass('disabled');
                    break;
            }
        });
        window.viewer_pos.on('animatefinished',function () {
            switch(elem) {
                case 'panorama_pos_slide':
                    var yaw = parseInt(window.viewer_pos.getYaw());
                    var pitch = parseInt(window.viewer_pos.getPitch());
                    var hfov = parseInt(window.viewer_pos.getHfov());
                    $('#slide_yaw').html(yaw);
                    $('#slide_pitch').html(pitch);
                    $('#slide_hfov').html(hfov);
                    break;
                case 'panorama_pos_presentation':
                    var yaw = parseFloat(window.viewer_pos.getYaw()).toFixed(2);
                    var pitch = parseFloat(window.viewer_pos.getPitch()).toFixed(2);
                    var hfov = parseInt(window.viewer_pos.getHfov());
                    $('#presentation_room_pos').html(yaw+","+pitch+" ("+hfov+")");
                    break;
            }
        });
        window.viewer_pos.on('mousedown', function () {
            switch(elem) {
                case 'panorama_pos_add':
                    $('#override_pos_add').prop('checked',true);
                    var event = new Event('change');
                    $('#override_pos_add')[0].dispatchEvent(event);
                    break;
                case 'panorama_pos_edit':
                    $('#override_pos_edit').prop('checked',true);
                    var event = new Event('change');
                    $('#override_pos_edit')[0].dispatchEvent(event);
                    break;
                case 'panorama_pos_presentation':
                    $('#override_pos_presentation').prop('checked',true);
                    break;
            }
        });
    }

    window.load_viewer_look = function (elem,id_room,panorama_image,yaw,pitch,h_pitch,h_roll,min_pitch,max_pitch,haov,vaov,min_yaw,max_yaw,hfov) {
        try {
            window.viewer_look.destroy();
        } catch (e) {}
        switch(elem) {
            default:
                var min_hov = 100;
                var max_hfov = 100;
                break
        }
        window.viewer_look = pannellum.viewer(elem, {
            "id_room": parseInt(id_room),
            "type": "equirectangular",
            "panorama": panorama_image,
            "autoLoad": true,
            "showFullscreenCtrl": false,
            "showControls": false,
            "horizonPitch": parseInt(h_pitch),
            "horizonRoll": parseInt(h_roll),
            "hfov": hfov,
            "minHfov": min_hov,
            "maxHfov": max_hfov,
            "yaw": yaw,
            "pitch": pitch,
            "minPitch": parseInt(min_pitch),
            "maxPitch" : parseInt(max_pitch),
            "minYaw": parseInt(min_yaw),
            "maxYaw" : parseInt(max_yaw),
            "haov": parseInt(haov),
            "vaov": parseInt(vaov),
            "compass": false,
            "friction": 1,
            "strings": {
                "loadingLabel": window.backend_labels.loading+"...",
            },
        });
        window.viewer_look.on('load', function () {

        });
        window.viewer_look.on('animatefinished',function () {

        });
        window.viewer_look.on('mousedown', function () {
            switch(elem) {
                case 'panorama_look_add':
                    $('#override_look_add').prop('checked',true);
                    var event = new Event('change');
                    $('#override_look_add')[0].dispatchEvent(event);
                    break;
                case 'panorama_look_edit':
                    $('#override_look_edit').prop('checked',true);
                    var event = new Event('change');
                    $('#override_look_edit')[0].dispatchEvent(event);
                    break;
            }
        });
    }

    window.close_edit_thumbnail = function() {
        $('#div_thumbnail').hide();
        $('#div_panorama').show();
        $('#btn_edit_thumbnail').removeClass('disabled');
        $('#frm_thumb').removeClass('disabled');
        $(window).trigger('resize');
    }

    window.edit_thumbnail = function() {
        $('#btn_edit_thumbnail').addClass('disabled');
        $('#frm_thumb').addClass('disabled');
        if(window.room_type=='image' || window.room_type=='hls' || window.room_type=='lottie' || (window.room_type=='video' && window.is_mobile)) {
            var dataURL = window.viewer.getRenderer().render(window.viewer.getPitch() / 180 * Math.PI,
                window.viewer.getYaw() / 180 * Math.PI,
                window.viewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'image/jpeg'});
            $('#div_panorama').hide();
            $('#div_thumbnail').show();
            window.cropper_thumb.replace(dataURL);
        } else {
            var dataURL = window.viewer_video.pnlmViewer.getRenderer().render(window.viewer_video.pnlmViewer.getPitch() / 180 * Math.PI,
                window.viewer_video.pnlmViewer.getYaw() / 180 * Math.PI,
                window.viewer_video.pnlmViewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'image/jpeg'});
            $('#div_panorama').hide();
            $('#div_thumbnail').show();
            window.cropper_thumb.replace(dataURL);
        }
    }

    window.initialize_cropper_thumbnail = function(dataURL) {
        $('#frm_thumb').removeClass('disabled');
        if(window.cropper_thumb==null) {
            var $img = $("#panorama_image_edit");
            $img.on('load',function(){
                setTimeout(function () {
                    var image = document.getElementById('panorama_image_edit');
                    window.cropper_thumb = new Cropper(image, {
                        zoomable: false,
                        zoomOnTouch: false,
                        zoomOnWheel: false,
                        movable: false,
                        dragMode: 'none',
                        aspectRatio: 16 / 9,
                    });
                    $img.off('load');
                    $('#btn_edit_thumbnail').removeClass('disabled');
                },200);
            });
            $img.attr('src',dataURL);
        }
    }

    window.crop_thumbnail = function () {
        $('#frm_thumb').addClass('disabled');
        $('#div_thumbnail button').addClass('disabled');
        var crop_data = window.cropper_thumb.getData();
        var image = $('#panorama_image_edit').attr('src');
        $.ajax({
            url: "ajax/crop_thumbnail.php",
            type: "POST",
            data: {
                id_room: window.id_room,
                image: image,
                crop_data: crop_data
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    window.thumb_image = rsp.thumb_image;
                    if(window.s3_enabled==1) {
                        $('#thumb_image').attr('src',window.s3_url+'viewer/panoramas/thumb_custom/'+rsp.thumb_image);
                    } else {
                        $('#thumb_image').attr('src','../viewer/panoramas/thumb_custom/'+rsp.thumb_image);
                    }
                    $('#div_thumbnail').hide();
                    $('#div_panorama').show();
                    $('#btn_edit_thumbnail').removeClass('disabled');
                    $('#frm_thumb').removeClass('disabled');
                }
                $('#div_thumbnail button').removeClass('disabled');
                $(window).trigger('resize');
            }
        });
    }

    window.reset_statistics = function () {
        $('#modal_reset_statistics button').addClass("disabled");
        $.ajax({
            url: "ajax/reset_statistics.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_reset_statistics button').removeClass("disabled");
                    $('#modal_reset_statistics').modal("hide");
                    location.reload();
                } else {
                    $('#modal_reset_statistics button').removeClass("disabled");
                }
            }
        });
    }

    window.reset_leads = function () {
        $('#modal_reset_leads button').addClass("disabled");
        $.ajax({
            url: "ajax/reset_leads.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_reset_leads button').removeClass("disabled");
                    $('#modal_reset_leads').modal("hide");
                    location.reload();
                } else {
                    $('#modal_reset_leads button').removeClass("disabled");
                }
            }
        });
    }

    window.reset_forms_data = function () {
        $('#modal_reset_forms_data button').addClass("disabled");
        $.ajax({
            url: "ajax/reset_forms_data.php",
            type: "POST",
            data: {
                id_user: window.id_user,
                id_virtualtour: window.id_virtualtour
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_reset_forms_data button').removeClass("disabled");
                    $('#modal_reset_forms_data').modal("hide");
                    location.reload();
                } else {
                    $('#modal_reset_forms_data button').removeClass("disabled");
                }
            }
        });
    }

    window.show_grid_position = function() {
        $('.grid_position').show();
    }

    window.hide_grid_position = function() {
        $('.grid_position').hide();
    }

    window.show_btn_toggle_effects = function () {
        $('#btn_toggle_effetcs').show();
    }

    window.hide_btn_toggle_effects = function () {
        $('#btn_toggle_effetcs').hide();
    }

    window.show_btn_screenshot = function () {
        $('#btn_screenshot').show();
    }

    window.hide_btn_screenshot = function () {
        $('#btn_screenshot').hide();
    }

    window.toggle_effects = function() {
        if(room_type=='video' && !window.is_mobile) {
            var canvas = viewer_video.pnlmViewer.getRenderer().getCanvas();
        } else {
            var canvas = viewer.getRenderer().getCanvas();
        }
        if($('#btn_toggle_effetcs i').hasClass('active')) {
            $('#btn_toggle_effetcs i').removeClass('active');
            $('.snow_effect').hide();
            $('.rain_effect').hide();
            $('.fog_effect').hide();
            $('.fireworks_effect').hide();
            $('.confetti_effect').hide();
            $('.sparkle_effect').hide();
            canvas.style.filter='';
        } else {
            $('#btn_toggle_effetcs i').addClass('active');
            $('.snow_effect').show();
            $('.rain_effect').show();
            $('.fog_effect').show();
            $('.fireworks_effect').show();
            $('.confetti_effect').show();
            $('.sparkle_effect').show();
            var brightness = $('#brightness').val();
            $('#brightness_val').html(brightness+'%');
            var contrast = $('#contrast').val();
            $('#contrast_val').html(contrast+'%');
            var saturate = $('#saturate').val();
            $('#saturate_val').html(saturate+'%');
            var grayscale = $('#grayscale').val();
            $('#grayscale_val').html(grayscale+'%');
            var filter = '';
            if(brightness!=100) {
                filter += 'brightness('+brightness+'%) ';
            }
            if(contrast!=100) {
                filter += 'contrast('+contrast+'%) ';
            }
            if(saturate!=100) {
                filter += 'saturate('+saturate+'%) ';
            }
            if(grayscale!=0) {
                filter += 'grayscale('+grayscale+'%) ';
            }
            canvas.style.filter = filter;
        }
    }

    window.add_category = function () {
        var name = $('#category_name').val();
        if(name!='') {
            $('#modal_add_category button').addClass("disabled");
            $.ajax({
                url: "ajax/add_category.php",
                type: "POST",
                data: {
                    name: name
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#modal_add_category button').removeClass("disabled");
                        $('#modal_add_category').modal("hide");
                        var id = rsp.id;
                        $('#category').append("<option id='"+id+"' selected>"+name+"</option>");
                        $('#category').selectpicker('refresh');
                        var val = $('#category').selectpicker('val');
                        $('#category').selectpicker('val', val);
                    } else {
                        $('#modal_add_category button').removeClass("disabled");
                    }
                }
            });
        }
    }

    function edit_all_categories() {
        $('.cat_tr').each(function() {
            var id = $(this).data('id');
            edit_category(id);
        })
    }

    window.remove_cat_icon = function(id) {
        $('#cat_tr_'+id+' #cat_'+id+'_icon').val('');
        $('#cat_tr_'+id+' #cat_'+id+'_icon_preview').removeClass();
        $('#cat_tr_'+id+' .btn_delete_cat_icon').addClass('disabled');
    }

    window.edit_category = function(id) {
        var name = $('#cat_tr_'+id+' .name').val();
        var icon = $('#cat_tr_'+id+' #cat_'+id+'_icon').val();
        var background = $('#cat_tr_'+id+' .background').val();
        var color = $('#cat_tr_'+id+' .color').val();
        var position = $('#cat_tr_'+id+' .position').val();
        var array_lang = {};
        array_lang['name'] = {};
        $('.input_lang[data-target-id="cat_name_'+id+'"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['name'][lang]=value;
        });
        if(name!='') {
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/edit_category.php",
                type: "POST",
                data: {
                    id: id,
                    name: name,
                    icon: icon,
                    background: background,
                    color: color,
                    position: position,
                    array_lang: array_lang_json
                },
                async: false,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#cat_tr_'+id+' .name').addClass('success-highlight');
                        setTimeout(function() {
                            $('#cat_tr_'+id+' .name').removeClass('success-highlight');
                        },500);
                    } else {
                        $('#cat_tr_'+id+' .name').addClass('error-highlight');
                        setTimeout(function() {
                            $('#cat_tr_'+id+' .name').removeClass('error-highlight');
                        },500);
                    }
                }
            });
        }
    }

    window.modal_delete_category = function(id) {
        $('#btn_delete_category').attr('onclick','delete_category('+id+');');
        $('#modal_delete_category').modal("show");
    }

    window.delete_category = function (id) {
        $('#modal_delete_category button').addClass("disabled");
        $.ajax({
            url: "ajax/delete_category.php",
            type: "POST",
            data: {
                id: id
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#modal_delete_category button').removeClass("disabled");
                    $('#modal_delete_category').modal("hide");
                    $('#cat_tr_'+id).remove();
                } else {
                    $('#modal_delete_category button').removeClass("disabled");
                }
            }
        });
    };

    window.add_category_s = function () {
        var name = $('#cat_tr_new .name').val();
        var icon = $('#cat_tr_new #cat_new_icon').val();
        var background = $('#cat_tr_new .background').val();
        var color = $('#cat_tr_new .color').val();
        var position = $('#cat_tr_new .position').val();
        if(name!='') {
            $('#btn_add_category').addClass("disabled");
            $.ajax({
                url: "ajax/add_category.php",
                type: "POST",
                data: {
                    name: name,
                    icon: icon,
                    background: background,
                    color: color,
                    position: position
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#btn_add_category').removeClass("disabled");
                        $('#cat_tr_new .name').val('');
                        $('#cat_tr_new .background').val('#f8f9fa');
                        $('#cat_tr_new .color').val('#000000');
                        $('#cat_tr_new #cat_new_icon').val('');
                        $('#cat_new_icon_preview').removeClass();
                        get_categories();
                    } else {
                        $('#cat_tr_new .name').addClass('error-highlight');
                        setTimeout(function() {
                            $('#cat_tr_new .name').removeClass('error-highlight');
                        },500);
                    }
                }
            });
        } else {
            $('#cat_tr_new .name').addClass('error-highlight');
            setTimeout(function() {
                $('#cat_tr_new .name').removeClass('error-highlight');
            },500);
            $('#cat_tr_new .name').focus();
        }
    }

    window.get_categories = function() {
        $.ajax({
            url: "ajax/get_categories.php",
            type: "POST",
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#table_categories tbody').html(rsp.html).promise().done(function() {
                        $('.icon_picker_cat').each(function() {
                            var id = $(this).attr('id');
                            IconPicker.Run('#'+id, function(){
                                var id_cat = id.replace('GetIconPicker_cat_','');
                                $('#cat_tr_'+id_cat+' .btn_delete_cat_icon').removeClass('disabled');
                            });
                        });
                        $('.cat_tr .background').each(function() {
                            $(this).spectrum({
                                type: "text",
                                preferredFormat: "hex",
                                showAlpha: false,
                                showButtons: true,
                                allowEmpty: false,
                                cancelText: window.backend_labels.cancel,
                                chooseText: window.backend_labels.choose,
                            });
                        });
                        $('.cat_tr .color').each(function() {
                            $(this).spectrum({
                                type: "text",
                                preferredFormat: "hex",
                                showAlpha: false,
                                showButtons: true,
                                allowEmpty: false,
                                cancelText: window.backend_labels.cancel,
                                chooseText: window.backend_labels.choose,
                            });
                        });
                    });
                }
            }
        });
    }

    window.change_keyboard_mode = function() {
        var keyborad_mode = $('#keyboard_mode option:selected').attr('id');
        $('#keyboard_msg_0').addClass('d-none');
        $('#keyboard_msg_1').addClass('d-none');
        $('#keyboard_msg_2').addClass('d-none');
        $('#keyboard_msg_'+keyborad_mode).removeClass('d-none');
    }

    window.change_frequency = function(id) {
        var frequency = $('#frequency'+id+' option:selected').attr('id');
        switch (frequency) {
            case 'one_time':
                $('#interval_count'+id).prop('disabled',true);
                $('#price2'+id).prop('disabled',true);
                break;
            case 'month_year':
                $('#interval_count'+id).prop('disabled',true);
                $('#price2'+id).prop('disabled',false);
                break;
            case 'recurring':
                $('#interval_count'+id).prop('disabled',false);
                $('#price2'+id).prop('disabled',true);
                break;
        }
    }

    window.change_price = function(id) {
        var price = parseInt($('#price'+id+'').val());
        if(price==0) {
            $('#price_label'+id).prop('disabled',false);
            $('.input_lang[data-target-id="price_label'+id+'"]').prop('disabled', false);
        } else {
            $('#price_label'+id).prop('disabled',true);
            $('.input_lang[data-target-id="price_label'+id+'"]').prop('disabled', true);
        }
    }

    window.change_service_type = function(id) {
        var type = $('#type'+id+' option:selected').attr('id');
        switch (type) {
            case 'generic':
                $('#price_n_image_label'+id).hide();
                $('#credit_n_image_label'+id).hide();
                $('#block_tour'+id).prop('disabled',true);
                break;
            case 'tour_service':
                $('#price_n_image_label'+id).show();
                $('#credit_n_image_label'+id).show();
                $('#block_tour'+id).prop('disabled',false);
                break;
            case 'tour_generic':
                $('#price_n_image_label'+id).hide();
                $('#credit_n_image_label'+id).hide();
                $('#block_tour'+id).prop('disabled',false);
                break;
        }
    }

    window.change_ai_generate_mode = function(id) {
        var frequency = $('#ai_generate_mode'+id+' option:selected').attr('id');
        switch (frequency) {
            case 'credit':
                $('#n_ai_generate_month'+id).prop('disabled',true);
                break;
            case 'month':
                $('#n_ai_generate_month'+id).prop('disabled',false);
                break;
        }
    }

    window.change_autoenhance_generate_mode = function(id) {
        var frequency = $('#autoenhance_generate_mode'+id+' option:selected').attr('id');
        switch (frequency) {
            case 'credit':
                $('#n_autoenhance_generate_month'+id).prop('disabled',true);
                break;
            case 'month':
                $('#n_autoenhance_generate_month'+id).prop('disabled',false);
                break;
        }
    }

    window.change_gsv_publish_mode = function(id) {
        var frequency = $('#gsv_publish_mode'+id+' option:selected').attr('id');
        switch (frequency) {
            case 'credit':
                $('#n_gsv_publish_month'+id).prop('disabled',true);
                break;
            case 'month':
                $('#n_gsv_publish_month'+id).prop('disabled',false);
                break;
        }
    }

    window.open_qr_code_modal = function (link) {
        var qrcode_src = "https://api.qrserver.com/v1/create-qr-code/?size=400x400&data="+encodeURIComponent(link);
        $('#modal_qrcode').modal('show');
        $('#modal_qrcode i').show();
        $('#modal_qrcode img').hide();
        $('#modal_qrcode img').on("load", function() {
            $('#modal_qrcode i').hide();
            $('#modal_qrcode img').show();
        }).attr("src", qrcode_src);
    }

    window.translate_deepl_cats = function() {
        $('.cat_name').each(function() {
            var elem = $(this).attr('id');
            translate_deepl(elem);
        });
    }

    window.translate_deepl = function (elem) {
        if(elem.lastIndexOf("feature_",0)===0) {
            var feature = elem.replace('feature_','').replace('_content','');
            var text = window.feature_content_editor[feature].root.innerHTML;
        } else {
            switch (elem) {
                case 'description_product':
                case 'description_service':
                    var text = window.description_editor.root.innerHTML;
                    break;
                case 'description_edit_service':
                    var text = window.description_edit_editor.root.innerHTML;
                    break;
                case 'tooltip_text_html':
                    var text = window.tooltip_text_editor.root.innerHTML;
                    break;
                case 'tooltip_text_mobile_html':
                    var text = window.tooltip_text_mobile_editor.root.innerHTML;
                    break;
                case 'poi_content_html':
                    var text = window.html_editor.root.innerHTML;
                    break;
                case 'poi_embed_content_html':
                    var text = window.poi_embed_content_html_editor.root.innerHTML;
                    break;
                case 'welcome_msg':
                    var text = window.welcome_msg_editor.root.innerHTML;
                    break;
                case 'learning_modal_description':
                    var text = window.learning_modal_description_editor.root.innerHTML;
                    break;
                case 'footer_value_1':
                    var text = window.footer_value_1.root.innerHTML;
                    break;
                case 'footer_value_2':
                    var text = window.footer_value_2.root.innerHTML;
                    break;
                case 'footer_value_3':
                    var text = window.footer_value_3.root.innerHTML;
                    break;
                case 'mail_activate_body':
                    var text = window.mail_activate_body_editor.root.innerHTML;
                    break;
                case 'mail_user_add_body':
                    var text = window.mail_user_add_body_editor.root.innerHTML;
                    break;
                case 'mail_forgot_body':
                    var text = window.mail_forgot_body_editor.root.innerHTML;
                    break;
                case 'mail_plan_expiring_body':
                    var text = window.mail_plan_expiring_body_editor.root.innerHTML;
                    break;
                case 'mail_plan_expired_body':
                    var text = window.mail_plan_expired_body_editor.root.innerHTML;
                    break;
                case 'mail_plan_changed_body':
                    var text = window.mail_plan_changed_body_editor.root.innerHTML;
                    break;
                case 'mail_plan_canceled_body':
                    var text = window.mail_plan_canceled_body_editor.root.innerHTML;
                    break;
                case 'mail_service_purchased_body':
                    var text = window.mail_service_purchased_body_editor.root.innerHTML;
                    break;
                default:
                    var text = $('#'+elem).val();
                    break;
            }
        }
        if(text==='<p><br></p>') text='';
        if(text!='') {
            $('.lang_input_switcher[data-elem="'+elem+'"] .translate_deepl_btn').addClass('disabled');
            $('.lang_input_switcher[data-elem="'+elem+'"] .translate_deepl_btn i').removeClass('fa-globe').addClass('fa-circle-notch').addClass('fa-spin');
            $.ajax({
                url: "ajax/translate_deepl.php",
                type: "POST",
                async: true,
                data: {
                    language: window.selected_language,
                    text: text
                },
                success: function (rsp) {
                    $('.lang_input_switcher[data-elem="'+elem+'"] .translate_deepl_btn').removeClass('disabled');
                    $('.lang_input_switcher[data-elem="'+elem+'"] .translate_deepl_btn i').addClass('fa-globe').removeClass('fa-circle-notch').removeClass('fa-spin');
                    if(rsp!='') {
                        rsp = rsp.replace(/^\s+|\s+$/g, '');
                        if(elem.lastIndexOf("feature_",0)===0) {
                            var feature = elem.replace('feature_','').replace('_content','');
                            window.feature_content_editor_lang[feature][window.selected_language].root.innerHTML=rsp;
                        } else {
                            switch (elem) {
                                case 'description_product':
                                case 'description_service':
                                    window.description_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'description_edit_service':
                                    window.description_edit_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'tooltip_text_html':
                                    window.tooltip_text_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'tooltip_text_mobile_html':
                                    window.tooltip_text_mobile_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'poi_content_html':
                                    window.html_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'poi_embed_content_html':
                                    window.poi_embed_content_html_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'welcome_msg':
                                    window.welcome_msg_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'learning_modal_description':
                                    window.learning_modal_description_editor_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'footer_value_1':
                                    var text = window.footer_value_1_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'footer_value_2':
                                    var text = window.footer_value_2_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'footer_value_3':
                                    var text = window.footer_value_3_lang[window.selected_language].root.innerHTML=rsp;
                                    break;
                                case 'mail_activate_body':
                                    var text = window.mail_activate_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_user_add_body':
                                    var text = window.mail_user_add_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_forgot_body':
                                    var text = window.mail_forgot_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_plan_expiring_body':
                                    var text = window.mail_plan_expiring_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_plan_expired_body':
                                    var text = window.mail_plan_expired_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_plan_changed_body':
                                    var text = window.mail_plan_changed_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_plan_canceled_body':
                                    var text = window.mail_plan_canceled_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                case 'mail_service_purchased_body':
                                    var text = window.mail_service_purchased_body_editor_lang[window.selected_language].root.innerHTML = rsp;
                                    break;
                                default:
                                    $('.input_lang[data-target-id="'+elem+'"][data-lang="'+window.selected_language+'"]').val(rsp);
                                    break;
                            }
                        }
                        if(elem=='callout_title' || elem=='callout_description') change_callout_params();
                        if(elem=='meta_title') {
                            $('.input_lang[data-target-id="meta_title"][data-lang="'+window.selected_language+'"]').trigger('input');
                            change_meta_title();
                        }
                        if(elem=='meta_description') {
                            $('.input_lang[data-target-id="meta_description"][data-lang="'+window.selected_language+'"]').trigger('input');
                            change_meta_description();
                        }
                    }
                }, error: function() {
                    $('.lang_input_switcher[data-elem="'+elem+'"] .translate_deepl_btn').removeClass('disabled');
                    $('.lang_input_switcher[data-elem="'+elem+'"] .translate_deepl_btn i').addClass('fa-globe').removeClass('fa-circle-notch').removeClass('fa-spin');
                }
            });
        }
    }

    window.switch_input_language = function (lang,default_lang,elem,bulk=true) {
        var orig_elem = elem;
        window.selected_language=lang;
        var url = new URL(location.href);
        var url_params = new URLSearchParams(url.search);
        var page_section = url_params.get('p');
        sessionStorage.setItem('lang_'+window.id_virtualtour+'_'+page_section,lang);
        $('#dropdown_lang_'+elem+' img').attr("src","img/flags_lang/"+lang+'.png?v=2');
        var feature_multiple = false;
        if(orig_elem.lastIndexOf("feature_",0)===0) {
            feature_multiple = true;
            elem = elem.replace('feature_','');
            var feature = $('#'+elem).attr('data-feature');
            $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
            if(lang!=default_lang) {
                $('#'+elem).parent().hide();
                $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                if(!bulk) {
                    try {
                        window.feature_content_editor_lang[feature][lang].focus();
                        var length = window.feature_content_editor_lang[feature][lang].getLength();
                        window.feature_content_editor_lang[feature][lang].setSelection(length);
                    } catch (e) {}
                }
            } else {
                $('#'+elem).parent().show();
                if(!bulk) {
                    try {
                        window.feature_content_editor[feature].focus();
                        var length = window.feature_content_editor[feature].getLength();
                        window.feature_content_editor[feature].setSelection(length);
                    } catch (e) {}
                }
            }
        } else {
            switch(elem) {
                case 'cat_name':
                    $('.cat_name_lang').hide();
                    if(lang!=default_lang) {
                        $('.cat_name').hide();
                        $('.cat_name_lang[data-lang="'+lang+'"]').show();
                    } else {
                        $('.cat_name').show();
                    }
                    break;
                case 'info_box':
                    $('#iframe_info_editor').contents().find(".info_editor_lang").hide();
                    if(lang!=default_lang) {
                        window.active_lang = lang;
                        $('#iframe_info_editor').contents().find("#info_editor").hide();
                        if(window.info_mode=='editor') {
                            $('#iframe_info_editor').contents().find("#info_editor_"+lang).show();
                        }
                    } else {
                        window.active_lang = '';
                        if(window.info_mode=='editor') {
                            $('#iframe_info_editor').contents().find("#info_editor").show();
                        }
                    }
                    break;
                case 'rooms_menu_list':
                    get_rooms_menu_list(window.id_vt_rm);
                    break;
                case 'description_product':
                case 'description_service':
                    elem = 'description';
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.description_editor_lang[lang].focus();
                                var length = window.description_editor_lang[lang].getLength();
                                window.description_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.description_editor.focus();
                                var length = window.description_editor.getLength();
                                window.description_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'description_edit_service':
                    elem = 'description_edit';
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.description_edit_editor_lang[lang].focus();
                                var length = window.description_edit_editor_lang[lang].getLength();
                                window.description_edit_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.description_edit_editor.focus();
                                var length = window.description_edit_editor.getLength();
                                window.description_edit_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'welcome_msg':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.welcome_msg_editor_lang[lang].focus();
                                var length = window.welcome_msg_editor_lang[lang].getLength();
                                window.welcome_msg_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.welcome_msg_editor.focus();
                                var length = window.welcome_msg_editor.getLength();
                                window.welcome_msg_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'learning_modal_description':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.learning_modal_description_editor_lang[lang].focus();
                                var length = window.learning_modal_description_editor_lang[lang].getLength();
                                window.learning_modal_description_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.learning_modal_description_editor.focus();
                                var length = window.learning_modal_description_editor.getLength();
                                window.learning_modal_description_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'footer_value_1':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.footer_value_1_lang[lang].focus();
                                var length = window.footer_value_1_lang[lang].getLength();
                                window.footer_value_1_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.footer_value_1.focus();
                                var length = window.footer_value_1.getLength();
                                window.footer_value_1.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'footer_value_2':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.footer_value_2_lang[lang].focus();
                                var length = window.footer_value_2_lang[lang].getLength();
                                window.footer_value_2_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.footer_value_2.focus();
                                var length = window.footer_value_2.getLength();
                                window.footer_value_2.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'footer_value_3':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.footer_value_3_lang[lang].focus();
                                var length = window.footer_value_3_lang[lang].getLength();
                                window.footer_value_3_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.footer_value_3.focus();
                                var length = window.footer_value_3.getLength();
                                window.footer_value_3.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'tooltip_text_html':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.tooltip_text_editor_lang[lang].focus();
                                var length = window.tooltip_text_editor_lang[lang].getLength();
                                window.tooltip_text_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.tooltip_text_editor.focus();
                                var length = window.tooltip_text_editor.getLength();
                                window.tooltip_text_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'tooltip_text_mobile_html':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.tooltip_text_mobile_editor_lang[lang].focus();
                                var length = window.tooltip_text_mobile_editor_lang[lang].getLength();
                                window.tooltip_text_mobile_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.tooltip_text_mobile_editor.focus();
                                var length = window.tooltip_text_mobile_editor.getLength();
                                window.tooltip_text_mobile_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'poi_content_html':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.html_editor_lang[lang].focus();
                                var length = window.html_editor_lang[lang].getLength();
                                window.html_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.html_editor.focus();
                                var length = window.html_editor.getLength();
                                window.html_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                case 'poi_content_html_sc':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) {
                            try {
                                window.poi_content_html_sc_lang[lang].focus();
                                window.poi_content_html_sc_lang[lang].navigateFileEnd();
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).show();
                        if(!bulk) {
                            try {
                                window.poi_content_html_sc.focus();
                                window.poi_content_html_sc.navigateFileEnd();
                            } catch (e) {}
                        }
                    }
                    break;
                case 'header_html':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) {
                            try {
                                window.editor_html_h_langs[lang].focus();
                                window.editor_html_h_langs[lang].navigateFileEnd();
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).show();
                        if(!bulk) {
                            try {
                                window.editor_html_h.focus();
                                window.editor_html_h.navigateFileEnd();
                            } catch (e) {}
                        }
                    }
                    break;
                case 'footer_html':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) {
                            try {
                                window.editor_html_f_langs[lang].focus();
                                window.editor_html_f_langs[lang].navigateFileEnd();
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).show();
                        if(!bulk) {
                            try {
                                window.editor_html_f.focus();
                                window.editor_html_f.navigateFileEnd();
                            } catch (e) {}
                        }
                    }
                    break;
                case 'poi_embed_content':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        var value = $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').val();
                    } else {
                        $('#'+elem).show();
                        var value = $('#'+elem).val();
                    }
                    switch(window.pois[poi_index_edit].embed_type) {
                        case 'image':
                        case 'video':
                        case 'video_transparent':
                        case 'link':
                        case 'object3d':
                            window.pois[poi_index_edit].embed_content = value;
                            setTimeout(function() {
                                if(!bulk) render_poi(poi_id_edit,poi_index_edit);
                            },250);
                            break;
                        case 'video_chroma':
                            $('.input_lang[data-target-id="chroma_color"]').hide();
                            $('.input_lang[data-target-id="chroma_tolerance"]').hide();
                            if(lang!=default_lang) {
                                $('#chroma_color').hide();
                                $('#chroma_tolerance').hide();
                                $('.input_lang[data-target-id="chroma_color"][data-lang="'+lang+'"]').show();
                                $('.input_lang[data-target-id="chroma_tolerance"][data-lang="'+lang+'"]').show();
                            } else {
                                $('#chroma_color').show();
                                $('#chroma_tolerance').show();
                            }
                            window.pois[poi_index_edit].embed_content = value;
                            setTimeout(function() {
                                if(!bulk) render_poi(poi_id_edit,poi_index_edit);
                            },250);
                            break;
                    }
                    break;
                case 'poi_embed_content_html':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.poi_embed_content_html_editor_lang[lang].focus();
                                var length = window.poi_embed_content_html_editor_lang[lang].getLength();
                                window.poi_embed_content_html_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.poi_embed_content_html_editor.focus();
                                var length = window.poi_embed_content_html_editor.getLength();
                                window.poi_embed_content_html_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    setTimeout(function() {
                        if(!bulk) render_poi(poi_id_edit,poi_index_edit);
                    },250);
                    break;
                case 'poi_embed_content_html_sc':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) {
                            try {
                                window.poi_embed_content_html_sc_lang[lang].focus();
                                window.poi_embed_content_html_sc_lang[lang].navigateFileEnd();
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).show();
                        if(!bulk) {
                            try {
                                window.poi_embed_content_html_sc.focus();
                                window.poi_embed_content_html_sc.navigateFileEnd();
                            } catch (e) {}
                        }
                    }
                    setTimeout(function() {
                        if(!bulk) render_poi(poi_id_edit,poi_index_edit);
                    },250);
                    break;
                case 'poi_label':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').focus();
                    } else {
                        $('#'+elem).show();
                        if(!bulk) $('#'+elem).focus();
                    }
                    setTimeout(function() {
                        if(!bulk) render_poi(poi_id_edit,poi_index_edit);
                    },250);
                    break;
                case 'marker_label':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').focus();
                    } else {
                        $('#'+elem).show();
                        if(!bulk) $('#'+elem).focus();
                    }
                    setTimeout(function() {
                        if(!bulk) render_marker(marker_id_edit,marker_index_edit);
                    },250);
                    break;
                case 'meta_title':
                case 'meta_description':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').focus();
                    } else {
                        $('#'+elem).show();
                        if(!bulk) $('#'+elem).focus();
                    }
                    change_meta_title();
                    change_meta_description();
                    break;
                case 'link':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    $('.input_lang[data-target-id="open_link"]').hide();
                    $('.input_lang[data-target-id="copy_link"]').hide();
                    $('.input_lang[data-target-id="qrcode_link"]').hide();
                    $('.input_lang[data-target-id="share_link"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('#open_link').hide();
                        $('#copy_link').hide();
                        $('#qrcode_link').hide();
                        $('#share_link').hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="open_link"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="copy_link"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="qrcode_link"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="share_link"][data-lang="'+lang+'"]').show();
                    } else {
                        $('#'+elem).show();
                        $('#open_link').show();
                        $('#copy_link').show();
                        $('#qrcode_link').show();
                        $('#share_link').show();
                    }
                    if(window.cookie_consent) {
                        if (!CookieConsent.acceptedService('Social Share (AddToAny)', 'functionality')) {
                            $('.input_lang[data-target-id="share_link"]').hide();
                        }
                    }
                    setTimeout(function() {
                        change_vt_version();
                    },10);
                    break;
                case 'link_f':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    $('.input_lang[data-target-id="open_link_f"]').hide();
                    $('.input_lang[data-target-id="copy_link_f"]').hide();
                    $('.input_lang[data-target-id="qrcode_link_f"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('#open_link_f').hide();
                        $('#copy_link_f').hide();
                        $('#qrcode_link_f').hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="open_link_f"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="copy_link_f"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="qrcode_link_f"][data-lang="'+lang+'"]').show();
                    } else {
                        $('#'+elem).show();
                        $('#open_link_f').show();
                        $('#copy_link_f').show();
                        $('#qrcode_link_f').show();
                    }
                    break;
                case 'code':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    $('.input_lang[data-target-id="copy_code"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('#copy_code').hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="copy_code"][data-lang="'+lang+'"]').show();
                    } else {
                        $('#'+elem).show();
                        $('#copy_code').show();
                    }
                    break;
                case 'poi_content':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        switch(window.pois[poi_index_edit].type) {
                            case 'link_ext':
                            case 'link':
                                if(!bulk) $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').focus();
                                break;
                        }
                    } else {
                        $('#'+elem).show();
                        switch(window.pois[poi_index_edit].type) {
                            case 'link_ext':
                            case 'link':
                                if(!bulk) $('#'+elem).focus();
                                break;
                        }
                    }
                    break;
                case 'callout_title':
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').focus();
                    } else {
                        $('#'+elem).show();
                        if(!bulk) $('#'+elem).focus();
                    }
                    if(!bulk) {
                        setTimeout(function() {
                            change_callout_params();
                        },250);
                    }
                    break;
                case 'callout_description':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if(lang!=default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if(!bulk) {
                            try {
                                window.callout_description_editor_lang[lang].focus();
                                var length = window.callout_description_editor_lang[lang].getLength();
                                window.callout_description_editor_lang[lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if(!bulk) {
                            try {
                                window.callout_description_editor.focus();
                                var length = window.callout_description_editor.getLength();
                                window.callout_description_editor.setSelection(length);
                            } catch (e) {}
                        }
                    }
                    if(!bulk) {
                        setTimeout(function() {
                            change_callout_params();
                        },250);
                    }
                    break;
                case 'avatar_video':
                    $('.input_lang[data-target-id="div_avatar_video_extensions"]').hide();
                    $('.input_lang[data-target-id="div_avatar_video_preview"]').hide();
                    $('.input_lang[data-target-id="div_delete_avatar_video"]').hide();
                    $('#div_avatar_video_extensions').hide();
                    $('#div_avatar_video_preview').hide();
                    $('#div_delete_avatar_video').hide();
                    if(lang!=default_lang) {
                        $('.input_lang[data-target-id="div_avatar_video_extensions"][data-lang="'+lang+'"]').show();
                        var avatar_video = $('#avatar_video_content_'+lang).val();
                        if(avatar_video=='' || avatar_video==null) {
                            $('.input_lang[data-target-id="div_delete_avatar_video"][data-lang="'+lang+'"]').hide();
                            $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"]').hide();
                            $('#div_upload_avatar_video').show();
                        } else {
                            $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"]').show();
                            $('.input_lang[data-target-id="div_delete_avatar_video"][data-lang="'+lang+'"]').show();
                            preview_avatar_video(avatar_video,'');
                        }
                    } else {
                        $('#div_avatar_video_extensions').show();
                        var avatar_video = $('#avatar_video_content').val();
                        if(avatar_video=='' || avatar_video==null) {
                            $('#div_avatar_video_preview').hide();
                            $('#div_delete_avatar_video').hide();
                        } else {
                            $('#div_avatar_video_preview').show();
                            $('#div_delete_avatar_video').show();
                            preview_avatar_video(avatar_video,'');
                        }
                    }
                    break;
                case 'media_file':
                    $('.input_lang[data-target-id="div_image_media"]').hide();
                    $('.input_lang[data-target-id="div_exist_media"]').hide();
                    $('#div_image_media').hide();
                    $('#div_exist_media').hide();
                    $('#div_delete_media').hide();
                    $('#div_upload_media').hide();
                    if(lang!=default_lang) {
                        if($('#div_image_media_'+lang+' img').attr('src')!='' || $('#div_image_media_'+lang+' video').find('source:first').attr('src')!='') {
                            $('.input_lang[data-target-id="div_image_media"][data-lang="'+lang+'"]').show();
                            $('#div_delete_media').show();
                        } else {
                            $('.input_lang[data-target-id="div_exist_media"][data-lang="'+lang+'"]').show();
                            $('#div_upload_media').show();
                        }
                        if($('#selectator_exist_media_'+lang).length==0) {
                            $('#exist_media_'+lang).selectator({
                                useSearch: false
                            });
                        }
                    } else {
                        if($('#div_image_media img').attr('src')!='' || $('#div_image_media video').find('source:first').attr('src')!='') {
                            $('#div_image_media').show();
                            $('#div_delete_media').show();
                        } else {
                            $('#div_exist_media').show();
                            $('#div_upload_media').show();
                        }
                    }
                    break;
                case 'intro_desktop':
                    $('.input_lang[data-target-id="div_image_introd"]').hide();
                    $('.input_lang[data-target-id="div_exist_introd"]').hide();
                    $('#div_image_introd').hide();
                    $('#div_exist_introd').hide();
                    $('#div_delete_introd').hide();
                    $('#div_upload_introd').hide();
                    if(lang!=default_lang) {
                        if($('#div_image_introd_'+lang+' img').attr('src')!='') {
                            $('.input_lang[data-target-id="div_image_introd"][data-lang="'+lang+'"]').show();
                            $('#div_delete_introd').show();
                        } else {
                            $('.input_lang[data-target-id="div_exist_introd"][data-lang="'+lang+'"]').show();
                            $('#div_upload_introd').show();
                        }
                        if($('#selectator_exist_introd_'+lang).length==0) {
                            $('#exist_introd_'+lang).selectator({
                                useSearch: false
                            });
                        }
                    } else {
                        if($('#div_image_introd img').attr('src')!='') {
                            $('#div_image_introd').show();
                            $('#div_delete_introd').show();
                        } else {
                            $('#div_exist_introd').show();
                            $('#div_upload_introd').show();
                        }
                    }
                    break;
                case 'intro_mobile':
                    $('.input_lang[data-target-id="div_image_introm"]').hide();
                    $('.input_lang[data-target-id="div_exist_introm"]').hide();
                    $('#div_image_introm').hide();
                    $('#div_exist_introm').hide();
                    $('#div_delete_introm').hide();
                    $('#div_upload_introm').hide();
                    if(lang!=default_lang) {
                        if($('#div_image_introm_'+lang+' img').attr('src')!='') {
                            $('.input_lang[data-target-id="div_image_introm"][data-lang="'+lang+'"]').show();
                            $('#div_delete_introm').show();
                        } else {
                            $('.input_lang[data-target-id="div_exist_introm"][data-lang="'+lang+'"]').show();
                            $('#div_upload_introm').show();
                        }
                        if($('#selectator_exist_introm_'+lang).length==0) {
                            $('#exist_introm_'+lang).selectator({
                                useSearch: false
                            });
                        }
                    } else {
                        if($('#div_image_introm img').attr('src')!='') {
                            $('#div_image_introm').show();
                            $('#div_delete_introm').show();
                        } else {
                            $('#div_exist_introm').show();
                            $('#div_upload_introm').show();
                        }
                    }
                    break;
                case 'mail_activate_body':
                case 'mail_user_add_body':
                case 'mail_forgot_body':
                case 'mail_plan_expiring_body':
                case 'mail_plan_expired_body':
                case 'mail_plan_changed_body':
                case 'mail_plan_canceled_body':
                case 'mail_service_purchased_body':
                    $('.input_lang[data-target-id="'+elem+'"]').parent().hide();
                    if (lang != default_lang) {
                        $('#'+elem).parent().hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').parent().show();
                        if (!bulk) {
                            try {
                                window[elem + '_editor_lang'][lang].focus();
                                var length = window[elem + '_editor_lang'][lang].getLength();
                                window[elem + '_editor_lang'][lang].setSelection(length);
                            } catch (e) {}
                        }
                    } else {
                        $('#'+elem).parent().show();
                        if (!bulk) {
                            try {
                                window[elem + '_editor'].focus();
                                var length = window[elem + '_editor'].getLength();
                                window[elem + '_editor'].setSelection(length);
                            } catch (e) {}
                        }
                    }
                    break;
                default:
                    $('.input_lang[data-target-id="'+elem+'"]').hide();
                    if(lang!=default_lang) {
                        $('#'+elem).hide();
                        $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').show();
                        if(!bulk) $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').focus();
                    } else {
                        $('#'+elem).show();
                        if(!bulk) $('#'+elem).focus();
                    }
                    break;
            }
        }
        try {
            if(lang!=default_lang) {
                if(!bulk) {
                    var value = $('.input_lang[data-target-id="' + elem + '"][data-lang="' + lang + '"]').val();
                    $('.input_lang[data-target-id="' + elem + '"][data-lang="' + lang + '"]').val('');
                    $('.input_lang[data-target-id="' + elem + '"][data-lang="' + lang + '"]').val(value);
                }
                if(feature_multiple) {
                    var feature = $('#'+elem).attr('data-feature');
                    window.feature_content_editor_lang[feature][lang].root.dataset.placeholder = truncateString(window.feature_content_editor[feature].getText(),100);
                } else {
                    switch (orig_elem) {
                        case 'description_product':
                        case 'description_service':
                            window.description_editor_lang[lang].root.dataset.placeholder = truncateString(window.description_editor.getText(),100);
                            break;
                        case 'description_edit_service':
                            window.description_edit_editor_lang[lang].root.dataset.placeholder = truncateString(window.description_edit_editor.getText(),100);
                            break;
                        case 'tooltip_text_html':
                            window.tooltip_text_editor_lang[lang].root.dataset.placeholder = truncateString(window.tooltip_text_editor.getText(),100);
                            break;
                        case 'tooltip_text_mobile_html':
                            window.tooltip_text_mobile_editor_lang[lang].root.dataset.placeholder = truncateString(window.tooltip_text_mobile_editor.getText(),100);
                            break;
                        case 'poi_content_html':
                            window.html_editor_lang[lang].root.dataset.placeholder = truncateString(window.html_editor.getText(),100);
                            break;
                        case 'callout_description':
                            window.callout_description_editor_lang[lang].root.dataset.placeholder = truncateString(window.callout_description_editor.getText(),100);
                            break;
                        case 'poi_embed_content_html':
                            window.poi_embed_content_html_editor_lang[lang].root.dataset.placeholder = truncateString(window.poi_embed_content_html_editor.getText(),100);
                            break;
                        case 'cat_name':
                            $('.cat_name_lang').each(function() {
                                var elem = $(this).attr('data-target-id');
                                $(this).attr('placeholder',$('#'+elem).val());
                            });
                            break;
                        case 'welcome_msg':
                            window.welcome_msg_editor_lang[lang].root.dataset.placeholder = truncateString(window.welcome_msg_editor.getText(),100);
                            break;
                        case 'learning_modal_description':
                            window.learning_modal_description_editor_lang[lang].root.dataset.placeholder = truncateString(window.learning_modal_description_editor.getText(),100);
                            break;
                        case 'footer_value_1':
                            window.footer_value_1_lang[lang].root.dataset.placeholder = truncateString(window.footer_value_1.getText(),100);
                            break;
                        case 'footer_value_2':
                            window.footer_value_2_lang[lang].root.dataset.placeholder = truncateString(window.footer_value_2.getText(),100);
                            break;
                        case 'footer_value_3':
                            window.footer_value_3_lang[lang].root.dataset.placeholder = truncateString(window.footer_value_3.getText(),100);
                            break;
                        case 'mail_activate_body':
                        case 'mail_user_add_body':
                        case 'mail_forgot_body':
                        case 'mail_plan_expiring_body':
                        case 'mail_plan_expired_body':
                        case 'mail_plan_changed_body':
                        case 'mail_plan_canceled_body':
                        case 'mail_service_purchased_body':
                            try {
                                window[elem + '_editor_lang'][lang].root.dataset.placeholder = truncateString(window[elem + '_editor'].getText(), 100);
                            } catch (e) {}
                            break;
                        default:
                            $('.input_lang[data-target-id="'+elem+'"][data-lang="'+lang+'"]').attr('placeholder',$('#'+elem).val());
                            break;
                    }
                }
            } else {
                if(!bulk) {
                    var value = $('#' + elem).val();
                    $('#' + elem).val('');
                    $('#' + elem).val(value);
                }
            }
        } catch (e) {}
        $('.lang_input_switcher[data-elem="'+orig_elem+'"] .translate_deepl_btn').hide();
        if (window.deepl===1 && (($('#'+elem).is(':input:not([readonly]):not(#poi_content):not(#poi_embed_content):not(#poi_gm_map):not(#poi_gm_street):not(#link):not(#link_f):not(#code)')) || (orig_elem === 'description_product') || (orig_elem === 'description_service') || (orig_elem === 'description_edit_service') || (orig_elem === 'tooltip_text_html') || (orig_elem === 'tooltip_text_mobile_html') || (orig_elem === 'poi_content_html') || (orig_elem === 'callout_description') || (orig_elem === 'poi_embed_content_html') || (orig_elem === 'cat_name') || (orig_elem === 'welcome_msg') || (orig_elem === 'learning_modal_description') || (orig_elem === 'footer_value_1') || (orig_elem === 'footer_value_2') || (orig_elem === 'footer_value_3') || (orig_elem === 'mail_activate_body') || (orig_elem === 'mail_user_add_body') || (orig_elem === 'mail_forgot_body') || (orig_elem === 'mail_plan_expiring_body') || (orig_elem === 'mail_plan_expired_body') || (orig_elem === 'mail_plan_changed_body') || (orig_elem === 'mail_plan_canceled_body') || (orig_elem === 'mail_service_purchased_body') || (feature_multiple))) {
            if(lang!=default_lang) {
                var value_check = '';
                if(feature_multiple) {
                    var feature = $('#'+elem).attr('data-feature');
                    try {
                        var value_check =  window.feature_content_editor[feature].root.innerHTML;
                    } catch (e) {}
                } else {
                    switch (orig_elem) {
                        case 'description_product':
                        case 'description_service':
                            try {
                                var value_check = window.description_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'description_edit_service':
                            try {
                                var value_check = window.description_edit_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'tooltip_text_html':
                            try {
                                var value_check = window.tooltip_text_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'tooltip_text_mobile_html':
                            try {
                                var value_check = window.tooltip_text_mobile_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'poi_content_html':
                            try {
                                var value_check = window.html_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'callout_description':
                            try {
                                var value_check = window.callout_description_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'poi_embed_content_html':
                            try {
                                var value_check = window.poi_embed_content_html_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'cat_name':
                            var value_check = '';
                            $('.cat_name').each(function() {
                                var value = $(this).val();
                                if(value!='') value_check = value;
                            });
                            break;
                        case 'welcome_msg':
                            try {
                                var value_check = window.welcome_msg_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'learning_modal_description':
                            try {
                                var value_check = window.learning_modal_description_editor.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'footer_value_1':
                            try {
                                var value_check = window.footer_value_1.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'footer_value_2':
                            try {
                                var value_check = window.footer_value_2.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'footer_value_3':
                            try {
                                var value_check = window.footer_value_3.root.innerHTML;
                            } catch (e) {}
                            break;
                        case 'mail_activate_body':
                        case 'mail_user_add_body':
                        case 'mail_forgot_body':
                        case 'mail_plan_expiring_body':
                        case 'mail_plan_expired_body':
                        case 'mail_plan_changed_body':
                        case 'mail_plan_canceled_body':
                        case 'mail_service_purchased_body':
                            try {
                                var value_check = window[elem + '_editor'].root.innerHTML;
                            } catch (e) {}
                            break;
                        default:
                            try {
                                var value_check = $('#'+elem).val();
                            } catch (e) {}
                            break;
                    }
                }
                if(value_check==='<p><br></p>') value_check='';
                if(orig_elem=='gm_map' || orig_elem=='gm_street') value_check='';
                if(value_check!='') {
                    $('.lang_input_switcher[data-elem="'+orig_elem+'"] .translate_deepl_btn').removeClass('disabled');
                    $('.lang_input_switcher[data-elem="'+orig_elem+'"] .translate_deepl_btn').css('display','inline-block');
                } else {
                    $('.lang_input_switcher[data-elem="'+orig_elem+'"] .translate_deepl_btn').addClass('disabled');
                    $('.lang_input_switcher[data-elem="'+orig_elem+'"] .translate_deepl_btn').css('display','inline-block');
                }
            }
        }
        if(!bulk) {
            $('.lang_input_switcher:not([data-elem="'+orig_elem+'"])').each(function() {
                var elem_d = $(this).attr('data-elem');
                switch_input_language(lang,default_lang,elem_d,true);
            });
        }
    }

    function truncateString(str, num) {
        if (str.length <= num) {
            return str;
        }
        return str.slice(0, num) + '...';
    }

    window.switch_language = function (lang) {
        $.ajax({
            url: "ajax/switch_language.php",
            type: "POST",
            data: {
                lang: lang
            },
            async: false,
            success: function () {
                location.reload();
            }
        });
    }

    window.assign_vt_editor = function (id,checked) {
        $.ajax({
            url: "ajax/assign_vt_editor.php",
            type: "POST",
            data: {
                id_vt: id,
                id_user: window.id_user_edit,
                checked: checked
            },
            async: false,
            success: function() {
                if(checked==1) {
                    $('#assign_vt_table').DataTable().ajax.reload();
                }
            }
        });
    }

    window.assign_user_editor = function (id,checked) {
        $.ajax({
            url: "ajax/assign_vt_editor.php",
            type: "POST",
            data: {
                id_vt: window.id_virtualtour,
                id_user: id,
                checked: checked
            },
            async: false,
            success: function() {
                if(checked==1) {
                    $('#assign_editors_table').DataTable().ajax.reload();
                }
            }
        });
    }

    window.set_permission_vt_editor = function (id,field,checked) {
        $.ajax({
            url: "ajax/set_permission_vt_editor.php",
            type: "POST",
            data: {
                id_vt: id,
                id_user: window.id_user_edit,
                field: field,
                checked: checked
            },
            async: true,
            success: function() {}
        });
    }

    window.set_permission_user_editor = function (id,field,checked) {
        $.ajax({
            url: "ajax/set_permission_vt_editor.php",
            type: "POST",
            data: {
                id_vt: window.id_virtualtour,
                id_user: id,
                field: field,
                checked: checked
            },
            async: true,
            success: function() {}
        });
    }

    window.change_poi_view_type = function () {
        var view_type = $('#view_type option:selected').attr('id');
        switch (view_type) {
            case '0':
                $('#box_pos').prop('disabled',true);
                $('#box_max_width').prop('disabled',true);
                $('#box_maximize').prop('disabled',true);
                break;
            case '1':
            case '2':
                $('#box_pos').prop('disabled',false);
                $('#box_max_width').prop('disabled',false);
                $('#box_maximize').prop('disabled',false);
                break;
        }
    }

    window.change_form_field_type = function(id) {
        var type = $('#form_field_type_'+id+' option:selected').attr('id');
        switch(type) {
            case 'select':
                $('#form_field_label_'+id).attr('placeholder','Label;Option1;Option2;Option3;...');
                break;
            case 'file':
                $('#form_field_label_'+id).attr('placeholder','Label;Accept (image/jpeg);Upload limit in MB');
                break;
            case 'textarea':
                $('#form_field_label_'+id).attr('placeholder','Label;N.Lines');
                break;
            default:
                $('#form_field_label_'+id).attr('placeholder','');
                break;
        }
    }

    window.session_library = function (w) {
        $.ajax({
            url: "ajax/set_session_library.php",
            type: "POST",
            async: true,
            data: {
                w: w
            },
            success: function (json) {
                location.reload();
            }
        });
    }

    window.session_statistics = function (w) {
        $.ajax({
            url: "ajax/set_session_statistics.php",
            type: "POST",
            async: true,
            data: {
                w: w
            },
            success: function (json) {
                location.reload();
            }
        });
    }

    window.landing_mode = function (w) {
        switch(w) {
            case 'editor':
                $('.editor_mode').show();
                $('.html_mode').hide();
                $('#btn_editor_mode').addClass('btn-primary').removeClass('btn-outline-primary');
                $('#btn_html_mode').removeClass('btn-primary').addClass('btn-outline-primary');
                break;
            case 'html':
                $('.editor_mode').hide();
                $('.html_mode').show();
                $('#btn_editor_mode').removeClass('btn-primary').addClass('btn-outline-primary');
                $('#btn_html_mode').addClass('btn-primary').removeClass('btn-outline-primary');
                break;
        }
    }

    window.save_preset = function (type) {
        var id_preset = $('#presets option:selected').attr('id');
        if(id_preset==0) {
            $('#name_preset').val('');
            $('#btn_add_new_preset').attr('onclick','add_preset(\''+type+'\');')
            $('#modal_new_preset').modal('show');
        } else {
            $('#modal_save_preset').modal('show');
        }
    }

    window.save_exist_preset = function (type) {
        $('#modal_save_preset button').addClass('disabled');
        var id_preset = $('#presets option:selected').attr('id');
        var allow_pitch = $('#allow_pitch').is(':checked');
        var allow_hfov = $('#allow_hfov').is(':checked');
        var min_pitch = $('#min_pitch').val();
        var max_pitch = $('#max_pitch').val();
        var min_yaw = $('#min_yaw').val();
        var max_yaw = $('#max_yaw').val();
        var haov = $('#haov').val();
        var vaov = $('#vaov').val();
        var hfov = $('#hfov').val();
        var h_pitch = $('#h_pitch').val();
        var h_roll = $('#h_roll').val();
        var background_color = window.background_color;
        var value = {};
        value['allow_pitch'] = allow_pitch;
        value['allow_hfov'] = allow_hfov;
        value['min_pitch'] = min_pitch;
        value['max_pitch'] = max_pitch;
        value['min_yaw'] = min_yaw;
        value['max_yaw'] = max_yaw;
        value['haov'] = haov;
        value['vaov'] = vaov;
        value['hfov'] = hfov;
        value['h_pitch'] = h_pitch;
        value['h_roll'] = h_roll;
        value['background_color'] = background_color;
        var value_json = JSON.stringify(value);
        $.ajax({
            url: "ajax/save_preset.php",
            type: "POST",
            async: true,
            data: {
                id: id_preset,
                type: type,
                value: value_json
            },
            success: function (json) {
                $("#presets option[id='"+id_preset+"']").attr('data-value',value_json);
                $('#modal_save_preset button').removeClass('disabled');
                $('#modal_save_preset').modal('hide');
            }
        });
    }

    window.add_preset = function (type) {
        var name = $('#name_preset').val();
        if(name!='') {
            $('#modal_new_preset button').addClass('disabled');
            var allow_pitch = $('#allow_pitch').is(':checked');
            var allow_hfov = $('#allow_hfov').is(':checked');
            var min_pitch = $('#min_pitch').val();
            var max_pitch = $('#max_pitch').val();
            var min_yaw = $('#min_yaw').val();
            var max_yaw = $('#max_yaw').val();
            var haov = $('#haov').val();
            var vaov = $('#vaov').val();
            var hfov = $('#hfov').val();
            var h_pitch = $('#h_pitch').val();
            var h_roll = $('#h_roll').val();
            var background_color = window.background_color;
            var value = {};
            value['allow_pitch'] = allow_pitch;
            value['allow_hfov'] = allow_hfov;
            value['min_pitch'] = min_pitch;
            value['max_pitch'] = max_pitch;
            value['min_yaw'] = min_yaw;
            value['max_yaw'] = max_yaw;
            value['haov'] = haov;
            value['vaov'] = vaov;
            value['hfov'] = hfov;
            value['h_pitch'] = h_pitch;
            value['h_roll'] = h_roll;
            value['background_color'] = background_color;
            var value_json = JSON.stringify(value);
            $.ajax({
                url: "ajax/add_preset.php",
                type: "POST",
                async: true,
                data: {
                    id_virtualtour: window.id_virtualtour,
                    name: name,
                    type: type,
                    value: value_json
                },
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        var id=rsp.id;
                        $('#presets').append("<option data-value='"+value_json+"' id='"+id+"'>"+name+"</option>");
                        $("#presets option").prop("selected", false);
                        $("#presets option[id='"+id+"']").prop("selected", true);
                        $('#btn_apply_preset_room').removeClass('disabled');
                        $('#btn_apply_preset_tour').removeClass('disabled');
                        $('#btn_delete_preset').removeClass('disabled');
                    }
                    $('#modal_new_preset button').removeClass('disabled');
                    $('#modal_new_preset').modal("hide");
                }
            });
        }
    }

    window.change_preset = function () {
        var id_preset = $('#presets option:selected').attr('id');
        if(id_preset==0) {
            $('#btn_apply_preset_room').addClass('disabled');
            $('#btn_apply_preset_tour').addClass('disabled');
            $('#btn_delete_preset').addClass('disabled');
        } else {
            $('#btn_apply_preset_room').removeClass('disabled');
            $('#btn_apply_preset_tour').removeClass('disabled');
            $('#btn_delete_preset').removeClass('disabled');
        }
    }

    window.delete_preset = function (type) {
        var id_preset = $('#presets option:selected').attr('id');
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $('#btn_apply_preset_room').addClass('disabled');
            $('#btn_apply_preset_tour').addClass('disabled');
            $('#btn_delete_preset').addClass("disabled");
            $.ajax({
                url: "ajax/delete_preset.php",
                type: "POST",
                data: {
                    id: id_preset
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $("#presets option[id='"+id_preset+"']").remove();
                        $("#presets option").prop("selected", false);
                        $("#presets option[id='0']").prop("selected", true);
                    }
                }
            });
        } else {
            return false;
        }
    };

    window.change_duplicate_items_vt = function () {
        var duplicate_rooms = $('#duplicate_rooms').is(':checked');
        if(!duplicate_rooms) {
            $('#duplicate_markers').prop('checked',false);
            $('#duplicate_markers').prop('disabled',true);
            $('#duplicate_pois').prop('checked',false);
            $('#duplicate_pois').prop('disabled',true);
            $('#duplicate_presentation').prop('checked',false);
            $('#duplicate_presentation').prop('disabled',true);
        } else {
            $('#duplicate_markers').prop('disabled',false);
            $('#duplicate_pois').prop('disabled',false);
            $('#duplicate_presentation').prop('disabled',false);
        }
    };

    window.change_scale_p = function () {
        var scale = $('#scale').is(':checked');
        if(scale) {
            window.pois[window.poi_index_edit].scale = 1;
        } else {
            window.pois[window.poi_index_edit].scale = 0;
        }
        window.viewer.setScaleHs("p"+window.poi_id_edit,scale);
    }

    window.change_scale_m = function () {
        var scale = $('#scale').is(':checked');
        if(scale) {
            window.markers[window.marker_index_edit].scale = 1;
        } else {
            window.markers[window.marker_index_edit].scale = 0;
        }
        window.viewer.setScaleHs("m"+window.marker_id_edit,scale);
    }

    window.change_transform3d = function () {
        var transform3d = $('#transform3d').is(':checked');
        if(transform3d) {
            window.pois[window.poi_index_edit].transform3d = 1;
            var yaw = parseFloat(window.pois[window.poi_index_edit].yaw);
            var pitch = parseFloat(window.pois[window.poi_index_edit].pitch);
            var embed_size = window.pois[window.poi_index_edit].embed_size;
            var tmp = embed_size.split(",");
            var ew = parseFloat(tmp[0])/30;
            var eh = parseFloat(tmp[1])/30;
            var poi_embed_helpers = [[0,0],[0,0],[0,0],[0,0]];
            poi_embed_helpers[0][0] = pitch + eh;
            poi_embed_helpers[0][1] = yaw - ew;
            poi_embed_helpers[1][0] = pitch - eh;
            poi_embed_helpers[1][1] = yaw - ew;
            poi_embed_helpers[2][0] = pitch + eh;
            poi_embed_helpers[2][1] = yaw + ew;
            poi_embed_helpers[3][0] = pitch - eh;
            poi_embed_helpers[3][1] = yaw + ew;
            var embed_coords = poi_embed_helpers[0][0]+","+poi_embed_helpers[0][1]+"|"+poi_embed_helpers[1][0]+","+poi_embed_helpers[1][1]+"|"+poi_embed_helpers[2][0]+","+poi_embed_helpers[2][1]+"|"+poi_embed_helpers[3][0]+","+poi_embed_helpers[3][1];
            window.pois[window.poi_index_edit].embed_coords = embed_coords;
        } else {
            window.pois[window.poi_index_edit].transform3d = 0;
            window.pois[window.poi_index_edit].embed_size = window.pois_initial[window.poi_index_edit].embed_size;
        }
        render_poi_move(window.poi_id_edit,window.poi_index_edit);
        (window.poi_id_edit,window.poi_index_edit,null);
    }

    window.minimize_box_edit = function () {
        $('.tab-content').toggle();
    }

    window.maximize_box_edit = function () {
        if(!$('.tab-content').is(':visible')) {
            setTimeout(function () {
                $('.tab-content').show();
            },150);
        }
    }

    window.change_product_type = function () {
        var type = $('#type option:selected').attr('id');
        switch (type) {
            case 't_none':
                $('#link').prop('disabled',true);
                $('#button_text').prop('disabled',true);
                $('.input_lang[data-target-id="button_text"]').prop('disabled',true);
                $('#button_background').prop('disabled',true);
                $('#button_color').prop('disabled',true);
                $('#button_text').attr('placeholder','');
                $('#custom_currency').prop('disabled',false);
                break;
            case 't_cart':
                $('#link').prop('disabled',true);
                $('#button_text').prop('disabled',false);
                $('.input_lang[data-target-id="button_text"]').prop('disabled',false);
                $('#button_background').prop('disabled',false);
                $('#button_color').prop('disabled',false);
                $('#custom_currency').prop('disabled',true);
                $('#button_text').attr('placeholder',window.cart_ph);
                break;
            case 't_link':
            case 't_popup':
                $('#link').prop('disabled',false);
                $('#button_text').prop('disabled',false);
                $('.input_lang[data-target-id="button_text"]').prop('disabled',false);
                $('#button_background').prop('disabled',false);
                $('#button_color').prop('disabled',false);
                $('#custom_currency').prop('disabled',false);
                $('#button_text').attr('placeholder',window.buy_ph);
                break;
        }
    }

    function wizard_progress_bar(index) {
        const currentStepElement = wizard_tour.currentStep.el;
        const header = currentStepElement.querySelector('.shepherd-content');
        const progress = document.createElement('div');
        const innerBar = document.createElement('span');
        const progressPercentage = ((index)/30)*100 + '%';
        progress.className='shepherd-progress-bar';
        innerBar.style.width=progressPercentage;
        progress.appendChild(innerBar);
        header.insertBefore(progress, currentStepElement.querySelector('.shepherd-text'));
        $('.shepherd-header').append('<button onclick="close_wizard()" aria-label="Close Tour" class="shepherd-cancel-icon" type="button"><span aria-hidden="true">×</span></button>');
    }

    window.close_wizard = function() {
        var r = confirm(window.backend_labels.wizard_close);
        if (r == true) {
            wizard_tour.cancel();
            location.href = 'index.php?p=dashboard';
        }
    }

    window.create_wizard = function (initial_index) {
        var windowWidth = $(window).width();
        if(windowWidth<=767) {
            var small_b = true;
        } else {
            var small_b = false;
        }
        wizard_tour = new Shepherd.Tour({
            defaultStepOptions: {
                cancelIcon: {
                    enabled: false
                },
                scrollTo: { behavior: 'smooth', block: 'center' },
            },
            useModalOverlay: true
        });
        if(initial_index<1) {
            wizard_steps[0] = wizard_tour.addStep({
                title: '1 - ' + window.backend_labels.wizard_title_1,
                text: window.backend_labels.wizard_text_1,
                attachTo: {
                    element: '#virtual_tours_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                modalOverlayOpeningRadius: 5,
                advanceOn: {selector: '#virtual_tours_menu_item', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(1);
                    }
                },
            });
        }
        if(initial_index<2) {
            wizard_steps[1] = wizard_tour.addStep({
                title: '2 - ' + window.backend_labels.wizard_title_1,
                text: window.backend_labels.wizard_text_2,
                attachTo: {
                    element: '#list_tour_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                modalOverlayOpeningRadius: 5,
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(2);
                    }
                },
            });
        }
        if(initial_index<3) {
            wizard_steps[2] = wizard_tour.addStep({
                title: '3 - ' + window.backend_labels.wizard_title_1,
                text: window.backend_labels.wizard_text_3,
                attachTo: {
                    element: '#add_vt_form',
                    on: 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                canClickTarget: false,
                buttons: [
                    {
                        text: 'Continue',
                        action: wizard_tour.next
                    }
                ],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(3);
                    }
                },
            });
        }
        if(initial_index<4) {
            wizard_steps[3] = wizard_tour.addStep({
                title: '4 - ' + window.backend_labels.wizard_title_1,
                text: window.backend_labels.wizard_text_4,
                attachTo: {
                    element: '#name_div',
                    on: 'bottom'
                },
                modalOverlayOpeningPadding: 10,
                modalOverlayOpeningRadius: 5,
                scrollTo: false,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: function () {
                        if($('#name').val()=='') {
                            $('#name').focus();
                            return false;
                        } else {
                            Shepherd.activeTour.next();
                        }
                    }
                }],
                when: {
                    show: function() {
                        const vElement = this.getElement();
                        if (vElement) vElement.focus = () => {};
                        wizard_progress_bar(4);
                        setTimeout(function () {
                            $('#name').focus();
                        },400);
                    }
                },
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                }
            });
        }
        if(initial_index<5) {
            wizard_steps[4] = wizard_tour.addStep({
                title: '5 - ' + window.backend_labels.wizard_title_1,
                text: window.backend_labels.wizard_text_5,
                attachTo: {
                    element: '#btn_create_tour',
                    on: (small_b) ? 'bottom' : 'left'
                },
                modalOverlayOpeningRadius: 5,
                scrollTo: false,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(5);
                    }
                },
            });
        }
        if(initial_index<6) {
            wizard_steps[5] = wizard_tour.addStep({
                title: '6 - ' + window.backend_labels.wizard_title_2,
                text: window.backend_labels.wizard_text_6,
                attachTo: {
                    element: '#room_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                beforeShowPromise: function() {
                    if(small_b) {
                        if(!$('#collapse_vt').hasClass('show')) {
                            $('#virtual_tours_menu_item').click();
                        }
                    }
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                when: {
                    show() {
                        wizard_progress_bar(6);
                    }
                },
            });
        }
        if(initial_index<7) {
            wizard_steps[6] = wizard_tour.addStep({
                title: '7 - ' + window.backend_labels.wizard_title_2,
                text: window.backend_labels.wizard_text_7,
                attachTo: {
                    element: '#btn_modal_create_room',
                    on: (small_b) ? 'bottom' : 'left'
                },
                scrollTo: false,
                modalOverlayOpeningRadius: 20,
                advanceOn: {selector: '#btn_modal_create_room', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 30]}}]
                },
                when: {
                    show() {
                        $('#btn_view_panorama_uploaded').addClass('disabled');
                        wizard_progress_bar(7);
                    }
                },
            });
        }
        if(initial_index<8) {
            wizard_steps[7] = wizard_tour.addStep({
                title: '8 - ' + window.backend_labels.wizard_title_2,
                text: window.backend_labels.wizard_text_8,
                attachTo: {
                    element: '#name_div',
                    on: (small_b) ? 'top' : 'bottom'
                },
                modalOverlayOpeningPadding: 5,
                modalOverlayOpeningRadius: 5,
                scrollTo: false,
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: function () {
                        if($('#name').val()=='') {
                            $('#name').focus();
                            return false;
                        } else {
                            Shepherd.activeTour.next();
                        }
                    }
                }],
                when: {
                    show: function() {
                        const vElement = this.getElement();
                        if (vElement) vElement.focus = () => {};
                        wizard_progress_bar(8);
                        setTimeout(function () {
                            $('#name').focus();
                        },400);
                    }
                },
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 20]}}]
                }
            });
        }
        if(initial_index<9) {
            wizard_steps[8] = wizard_tour.addStep({
                title: '9 - ' + window.backend_labels.wizard_title_2,
                text: window.backend_labels.wizard_text_9,
                attachTo: {
                    element: '#frm',
                    on: 'top'
                },
                scrollTo: false,
                modalOverlayOpeningPadding: 5,
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 20]}}]
                },
                when: {
                    show() {
                        $('#btn_view_panorama_uploaded').addClass('disabled');
                        wizard_progress_bar(9);
                    }
                },
            });
        }
        if(initial_index<10) {
            wizard_steps[9] = wizard_tour.addStep({
                title: '10 - ' + window.backend_labels.wizard_title_2,
                text: window.backend_labels.wizard_text_10,
                attachTo: {
                    element: '#btn_create_room',
                    on: 'top'
                },
                scrollTo: true,
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(10);
                    }
                },
            });
        }
        if(initial_index<11) {
            wizard_steps[10] = wizard_tour.addStep({
                title: '11 - ' + window.backend_labels.wizard_title_2,
                text: window.backend_labels.wizard_text_11,
                scrollTo: false,
                modalOverlayOpeningRadius: 5,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 0]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(11);
                    }
                },
            });
        }
        if(initial_index<12) {
            wizard_steps[11] = wizard_tour.addStep({
                title: '12 - ' + window.backend_labels.wizard_title_3,
                text: window.backend_labels.wizard_text_6,
                attachTo: {
                    element: '#room_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                beforeShowPromise: function() {
                    if(small_b) {
                        if(!$('#collapse_vt').hasClass('show')) {
                            $('#virtual_tours_menu_item').click();
                        }
                    }
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                when: {
                    show() {
                        wizard_progress_bar(12);
                    }
                },
            });
        }
        if(initial_index<13) {
            wizard_steps[12] = wizard_tour.addStep({
                title: '13 - ' + window.backend_labels.wizard_title_3,
                text: window.backend_labels.wizard_text_7,
                attachTo: {
                    element: '#btn_modal_create_room',
                    on: (small_b) ? 'bottom' : 'left'
                },
                scrollTo: false,
                modalOverlayOpeningRadius: 20,
                advanceOn: {selector: '#btn_modal_create_room', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 30]}}]
                },
                when: {
                    show() {
                        $('#btn_view_panorama_uploaded').addClass('disabled');
                        wizard_progress_bar(13);
                    }
                },
            });
        }
        if(initial_index<14) {
            wizard_steps[13] = wizard_tour.addStep({
                title: '14 - ' + window.backend_labels.wizard_title_3,
                text: window.backend_labels.wizard_text_8,
                attachTo: {
                    element: '#name_div',
                    on: (small_b) ? 'top' : 'bottom'
                },
                scrollTo: false,
                modalOverlayOpeningPadding: 5,
                modalOverlayOpeningRadius: 5,
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: function () {
                        if($('#name').val()=='') {
                            $('#name').focus();
                            return false;
                        } else {
                            Shepherd.activeTour.next();
                        }
                    }
                }],
                when: {
                    show: function() {
                        const vElement = this.getElement();
                        if (vElement) vElement.focus = () => {};
                        wizard_progress_bar(14);
                        setTimeout(function () {
                            $('#name').focus();
                        },400);
                    }
                },
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 20]}}]
                }
            });
        }
        if(initial_index<15) {
            wizard_steps[14] = wizard_tour.addStep({
                title: '15 - ' + window.backend_labels.wizard_title_3,
                text: window.backend_labels.wizard_text_9,
                attachTo: {
                    element: '#frm',
                    on: 'top'
                },
                scrollTo: false,
                modalOverlayOpeningPadding: 5,
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 20]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(15);
                    }
                },
            });
        }
        if(initial_index<16) {
            wizard_steps[15] = wizard_tour.addStep({
                title: '16 - ' + window.backend_labels.wizard_title_3,
                text: window.backend_labels.wizard_text_10,
                scrollTo: true,
                attachTo: {
                    element: '#btn_create_room',
                    on: 'top'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(16);
                    }
                },
            });
        }
        if(initial_index<17) {
            wizard_steps[16] = wizard_tour.addStep({
                title: '17 - ' + window.backend_labels.wizard_title_3,
                text: window.backend_labels.wizard_text_17,
                scrollTo: false,
                modalOverlayOpeningRadius: 5,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 0]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(17);
                    }
                },
            });
        }
        if(initial_index<18) {
            wizard_steps[17] = wizard_tour.addStep({
                title: '18 - ' + window.backend_labels.wizard_title_4,
                text: window.backend_labels.wizard_text_18,
                attachTo: {
                    element: '#markers_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                beforeShowPromise: function() {
                    if(small_b) {
                        if(!$('#collapse_vt').hasClass('show')) {
                            $('#virtual_tours_menu_item').click();
                        }
                    }
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                when: {
                    show() {
                        wizard_progress_bar(18);
                    }
                },
            });
        }
        /*if(initial_index<19) {
            wizard_steps[18] = wizard_tour.addStep({
                title: '19 - ' + window.backend_labels.wizard_title_4,
                text:  window.backend_labels.wizard_text_19,
                attachTo: {
                    element: '#rooms_slider_m .slick-slide:first-child',
                    on: 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(19);
                    }
                },
            });
        }*/
        /*if(initial_index<19) {
            wizard_steps[18] = wizard_tour.addStep({
                title: '19 - ' + window.backend_labels.wizard_title_4,
                text:  window.backend_labels.wizard_text_20,
                attachTo: {
                    element: '#panorama_markers .pnlm-render-container canvas',
                    on: (small_b) ? 'top' : 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(19);
                    }
                },
            });
        }*/
        if(initial_index<19) {
            wizard_steps[18] = wizard_tour.addStep({
                title: '19 - ' + window.backend_labels.wizard_title_4,
                text: window.backend_labels.wizard_text_7,
                attachTo: {
                    element: '#btn_add_marker',
                    on: (small_b) ? 'bottom' : 'left'
                },
                modalOverlayOpeningRadius: 20,
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                when: {
                    show: function() {
                        wizard_progress_bar(19);
                    }
                },
                advanceOn: {selector: '#btn_add_marker', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                }
            });
        }
        if(initial_index<20) {
            wizard_steps[19] = wizard_tour.addStep({
                title: '20 - ' + window.backend_labels.wizard_title_4,
                text:  window.backend_labels.wizard_text_22,
                attachTo: {
                    element: '#room_target_add_div',
                    on: 'bottom'
                },
                canClickTarget: false,
                modalOverlayOpeningPadding: 5,
                modalOverlayOpeningRadius: 5,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 20]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(20);
                    }
                },
            });
        }
        if(initial_index<21) {
            wizard_steps[20] = wizard_tour.addStep({
                title: '21 - ' + window.backend_labels.wizard_title_4,
                text:  window.backend_labels.wizard_text_23,
                attachTo: {
                    element: '#btn_new_marker',
                    on: (small_b) ? 'top' : 'left'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(21);
                    }
                },
            });
        }
        if(initial_index<22) {
            wizard_steps[21] = wizard_tour.addStep({
                title: '22 - ' + window.backend_labels.wizard_title_4,
                text:  window.backend_labels.wizard_text_24,
                attachTo: {
                    element: '.div_marker_wrapper:first-child',
                    on: 'bottom'
                },
                scrollTo: false,
                canClickTarget: false,
                modalOverlayOpeningPadding: 10,
                modalOverlayOpeningRadius: 20,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(22);
                    }
                },
            });
        }
        if(initial_index<23) {
            wizard_steps[22] = wizard_tour.addStep({
                title: '23 - ' + window.backend_labels.wizard_title_6,
                text: window.backend_labels.wizard_text_26,
                attachTo: {
                    element: '#pois_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                beforeShowPromise: function() {
                    if(small_b) {
                        if(!$('#collapse_vt').hasClass('show')) {
                            $('#virtual_tours_menu_item').click();
                        }
                    }
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                when: {
                    show() {
                        wizard_progress_bar(23);
                    }
                },
            });
        }
        /*if(initial_index<26) {
            wizard_steps[25] = wizard_tour.addStep({
                title: '26 - ' + window.backend_labels.wizard_title_6,
                text:  window.backend_labels.wizard_text_27,
                attachTo: {
                    element: '#rooms_slider_p .slick-slide:first-child',
                    on: 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(26);
                    }
                },
            });
        }*/
        /*if(initial_index<25) {
            wizard_steps[24] = wizard_tour.addStep({
                title: '25 - ' + window.backend_labels.wizard_title_6,
                text:  window.backend_labels.wizard_text_28,
                attachTo: {
                    element: '#panorama_pois .pnlm-render-container canvas',
                    on: (small_b) ? 'top' : 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(25);
                    }
                },
            });
        }*/
        if(initial_index<24) {
            wizard_steps[23] = wizard_tour.addStep({
                title: '24 - ' + window.backend_labels.wizard_title_6,
                text: window.backend_labels.wizard_text_7,
                attachTo: {
                    element: '#btn_add_poi',
                    on: (small_b) ? 'bottom' : 'left'
                },
                modalOverlayOpeningRadius: 20,
                when: {
                    show: function() {
                        wizard_progress_bar(24);
                        $('#btn_add_poi').removeClass('disabled');
                    }
                },
                advanceOn: {selector: '#btn_add_poi', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                }
            });
        }
        if(initial_index<25) {
            wizard_steps[24] = wizard_tour.addStep({
                title: '25 - ' + window.backend_labels.wizard_title_6,
                text: window.backend_labels.wizard_text_29,
                attachTo: {
                    element: '#modal_add_poi .modal-body',
                    on: (small_b) ? 'top' : 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                canClickTarget: false,
                buttons: [
                    {
                        text: 'Continue',
                        action: wizard_tour.next
                    }
                ],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(25);
                    }
                },
            });
        }
        if(initial_index<26) {
            wizard_steps[25] = wizard_tour.addStep({
                title: '26 - ' + window.backend_labels.wizard_title_6,
                text: window.backend_labels.wizard_text_30,
                attachTo: {
                    element: '#btn_new_poi_image',
                    on: (small_b) ? 'top' : 'bottom'
                },
                modalOverlayOpeningRadius: 5,
                when: {
                    show: function() {
                        wizard_progress_bar(26);
                    }
                },
                advanceOn: {selector: '#btn_new_poi_image', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                }
            });
        }
        if(initial_index<27) {
            wizard_steps[26] = wizard_tour.addStep({
                title: '27 - ' + window.backend_labels.wizard_title_6,
                text: window.backend_labels.wizard_text_31,
                attachTo: {
                    element: '#frm_edit',
                    on: 'top'
                },
                scrollTo: false,
                modalOverlayOpeningPadding: 5,
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 20]}}]
                },
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },1000);
                    });
                },
                when: {
                    show() {
                        wizard_progress_bar(27);
                    }
                }
            });
        }
        if(initial_index<28) {
            wizard_steps[27] = wizard_tour.addStep({
                title: '28 - ' + window.backend_labels.wizard_title_6,
                text: window.backend_labels.wizard_text_32,
                attachTo: {
                    element: '#confirm_edit .btn_confirm',
                    on: 'bottom'
                },
                modalOverlayOpeningRadius: 10,
                when: {
                    show: function() {
                        wizard_progress_bar(28);
                    }
                },
                advanceOn: {selector: '#confirm_edit .btn_confirm', event: 'click'},
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                }
            });
        }
        if(initial_index<29) {
            wizard_steps[28] = wizard_tour.addStep({
                title: '29 - ' + window.backend_labels.wizard_title_6,
                text:  window.backend_labels.wizard_text_33,
                attachTo: {
                    element: '.div_poi_wrapper:first-child',
                    on: 'bottom'
                },
                beforeShowPromise: function() {
                    return new Promise(function(resolve) {
                        setTimeout(function () {
                            resolve();
                        },250);
                    });
                },
                scrollTo: false,
                canClickTarget: false,
                modalOverlayOpeningPadding: 10,
                modalOverlayOpeningRadius: 20,
                buttons: [{
                    text: window.backend_labels.wizard_continue,
                    action: wizard_tour.next
                }],
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 25]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(29);
                    }
                },
            });
        }
        if(initial_index<30) {
            wizard_steps[29] = wizard_tour.addStep({
                title: '30 - ' + window.backend_labels.wizard_title_5,
                text:  window.backend_labels.wizard_text_25,
                attachTo: {
                    element: '#preview_menu_item',
                    on: (small_b) ? 'bottom' : 'right'
                },
                scrollTo: true,
                modalOverlayOpeningRadius: 5,
                popperOptions: {
                    modifiers: [{name: 'offset', options: {offset: [0, 15]}}]
                },
                when: {
                    show() {
                        wizard_progress_bar(30);
                    }
                },
            });
        }
    }

    $(document).ready(function() {
        if(window.wizard_step!=-1 && window.wizard_step!=18 && window.wizard_step!=23) {
            create_wizard(window.wizard_step);
            wizard_tour_open = true;
            wizard_tour.start();
        }
    });

    window.save_vt_ui = function (save,preset_save,apply_preset,reload=false,save_version=false,apply_version=false) {
        var array_lang = {};
        setTimeout(function () {
            fix_colors_menu();
        },200);
        var buttons_style = $('#buttons_style option:selected').attr('id');
        var buttons_size = $('#buttons_size option:selected').attr('id');
        $('.controls_bottom').removeClass('square-btn');
        $('.controls_bottom').removeClass('bar-btn');
        $('.controls_bottom').removeClass('small-btn');
        $('.controls_bottom').removeClass('large-btn');
        if(buttons_style!='default') {
            $('.controls_bottom').addClass(buttons_style+'-btn');
        }
        if(buttons_size!='default') {
            $('.controls_bottom').addClass(buttons_size+'-btn');
        }
        var menu_type = $('#menu_type option:selected').attr('id');
        if(menu_type=='sidebar') {
            $('#list_alt_menu').addClass('ui_hidden');
            $('.song_control_icon').css('left','45px');
        } else {
            $('#list_alt_menu').removeClass('ui_hidden');
            $('.song_control_icon').css('left','75px');
        }
        if($('#menu_type').is(':visible')) {
            switch(menu_type) {
                case 'dropdown':
                    $('.menu_controls .dropdown')[0].classList.add('down');
                    $('.menu_controls .arrow')[0].classList.add('gone');
                    setTimeout(function() {
                        $('.menu_controls .dropdown')[0].style.overflow = 'visible';
                    }, 100)
                    $('#menu_sidebar').removeClass('open');
                    break;
                case 'sidebar':
                    $('.menu_controls .dropdown')[0].classList.remove('down');
                    $('.menu_controls .arrow')[0].classList.remove('gone');
                    $('.menu_controls .dropdown')[0].style.overflow = 'hidden';
                    $('#menu_sidebar').addClass('open');
                    break;
            }
        }
        var sidebar_glass = $('#sidebar_glass').is(':checked') ? 1 : 0;
        if(sidebar_glass==1) {
            $('#menu_sidebar').addClass('glass');
        } else {
            $('#menu_sidebar').removeClass('glass');
        }
        var sidebar_logo_height = $('#sidebar_logo_height').val();
        if(sidebar_logo_height==0) {
            $('#ms_logo').addClass('ui_hidden');
        } else {
            $('#ms_logo img').css('max-height',sidebar_logo_height+'px');
            $('#ms_logo').removeClass('ui_hidden');
        }
        var show_vt_title = parseInt($('#show_vt_title option:selected').attr('id'));
        switch(show_vt_title) {
            case 0:
                $('.name_vt, .room_vt').addClass('ui_disabled');
                $('#list_editor_ui_items li[data-ui-target="ui_edit_title"] i').css('color','darkorange');
                break;
            case 1:
                $('.name_vt, .room_vt').removeClass('ui_disabled');
                $('#list_editor_ui_items li[data-ui-target="ui_edit_title"] i').css('color','darkgreen');
                break;
            case 2:
                $('.name_vt').removeClass('ui_disabled');
                $('.room_vt').addClass('ui_disabled');
                $('#list_editor_ui_items li[data-ui-target="ui_edit_title"] i').css('color','darkgreen');
                break;
            case 3:
                $('.name_vt').addClass('ui_disabled');
                $('.room_vt').removeClass('ui_disabled');
                $('#list_editor_ui_items li[data-ui-target="ui_edit_title"] i').css('color','darkgreen');
                break;
        }
        var vt_title_height = $('#vt_title_height').val();
        $('.header_vt').css('height',vt_title_height+'px');
        var multiple_room_views_size = $('#multiple_room_views_size').val();
        $('.rooms_view_sel img').css({'width':multiple_room_views_size+'px','height':multiple_room_views_size+'px'});
        var multiple_room_views_style = $('#multiple_room_views_style option:selected').attr('id');
        switch(multiple_room_views_style) {
            case 'square':
                $('.rooms_view_sel img').css('border-radius',(multiple_room_views_size/10)+'px');
                break;
            case 'round':
                $('.rooms_view_sel img').css('border-radius','50%');
                break;
        }
        var multiple_room_views_border = $('#multiple_room_views_border').val();
        var multiple_room_views_border_color = $('#multiple_room_views_border_color').val();
        $('.rooms_view_sel img').css('border-width',multiple_room_views_border+'px');
        var show_audio = ($('#show_audio').is(':checked')) ? 1 : 0;
        if(show_audio==1) {
            $('.song_control').removeClass('ui_disabled');
            $('.song_alt_control').removeClass('ui_disabled');
        } else {
            $('.song_control').addClass('ui_disabled');
            $('.song_alt_control').addClass('ui_disabled');
        }
        var song_autoplay = parseInt($('#song_autoplay option:selected').attr('id'));
        if(song_autoplay==0) {
            $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
        } else {
            $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
        }
        var show_fullscreen = parseInt($('#show_fullscreen option:selected').attr('id'));
        if(show_fullscreen==0) {
            $('.fullscreen_control').addClass('ui_disabled');
            $('.fullscreen_alt_control').addClass('ui_disabled');
        } else {
            $('.fullscreen_control').removeClass('ui_disabled');
            $('.fullscreen_alt_control').removeClass('ui_disabled');
        }
        var show_map = parseInt($('#show_map option:selected').attr('id'));
        switch (show_map) {
            case 0:
                $('.map_control').addClass('ui_disabled');
                $('.floorplan_alt_control').addClass('ui_disabled');
                $('.map .all_maps').addClass('ui_disabled');
                $('.map .map_bar').addClass('ui_disabled');
                $('.map_control i').removeClass('icon-map_on').addClass('icon-map_off');
                $('.floorplan_alt_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
            case 2:
                $('.map_control').removeClass('ui_disabled');
                $('.floorplan_alt_control').removeClass('ui_disabled');
                $('.map .all_maps').removeClass('ui_disabled');
                $('.map .map_bar').removeClass('ui_disabled');
                $('.map_control i').removeClass('icon-map_on').addClass('icon-map_off');
                $('.floorplan_alt_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 3:
            case 5:
                $('.map_control').removeClass('ui_disabled');
                $('.floorplan_alt_control').removeClass('ui_disabled');
                $('.map .all_maps').removeClass('ui_disabled');
                $('.map .map_bar').removeClass('ui_disabled');
                $('.map_control i').removeClass('icon-map_off').addClass('icon-map_on');
                $('.floorplan_alt_control .fa-circle').removeClass('not_active').addClass('active');
                break;
            case 4:
                $('.map_control').removeClass('ui_disabled');
                $('.floorplan_alt_control').removeClass('ui_disabled');
                $('.map .all_maps').addClass('ui_disabled');
                $('.map .map_bar').addClass('ui_disabled');
                $('.map_control i').removeClass('icon-map_on').addClass('icon-map_off');
                $('.floorplan_alt_control .fa-circle').removeClass('active').addClass('not_active');
                break;
        }
        var show_map_tour = parseInt($('#show_map_tour option:selected').attr('id'));
        switch (show_map_tour) {
            case 0:
                $('.map_tour_control').addClass('ui_disabled');
                $('.map_alt_control').addClass('ui_disabled');
                $('.map_tour_control i').removeClass('fas').addClass('far');
                $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
                $('.map_tour_control').removeClass('ui_disabled');
                $('.map_alt_control').removeClass('ui_disabled');
                $('.map_tour_control i').removeClass('fas').addClass('far');
                $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
            case 3:
            case 4:
                $('.map_tour_control').removeClass('ui_disabled');
                $('.map_alt_control').removeClass('ui_disabled');
                $('.map_tour_control i').removeClass('far').addClass('fas');
                $('.map_alt_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        var show_list_alt = parseInt($('#show_list_alt option:selected').attr('id'));
        switch (show_list_alt) {
            case 0:
                $('.list_alt_menu').addClass('ui_disabled');
                break;
            case 1:
                $('.list_alt_menu').removeClass('ui_disabled');
                break;
            case 2:
                $('.list_alt_menu').removeClass('ui_disabled');
                break;
        }
        var show_annotations = parseInt($('#show_annotations option:selected').attr('id'));
        switch (show_annotations) {
            case 0:
                $('.annotations_control').addClass('ui_disabled');
                $('.annotation').addClass('ui_disabled');
                $('.annotations_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
                $('.annotations_control').removeClass('ui_disabled');
                $('.annotation').addClass('ui_disabled');
                $('.annotations_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
                $('.annotations_control').removeClass('ui_disabled');
                $('.annotation').removeClass('ui_disabled');
                $('.annotations_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        var show_inline_form = $('#show_inline_form').is(':checked') ? 1 : 0;
        switch (show_inline_form) {
            case 0:
                $('.inline_form').addClass('ui_disabled');
                break;
            case 1:
                $('.inline_form').removeClass('ui_disabled');
                break;
        }
        var show_logo = parseInt($('#show_logo option:selected').attr('id'));
        if(show_logo>0) {
            $('.logo img').removeClass('ui_disabled');
        } else {
            $('.logo img').addClass('ui_disabled');
            $(this).css('opacity','');
        }
        var logo_opacity = $('#logo_opacity').val();
        var logo_opacity_hover = $('#logo_opacity_hover').val();
        $('#logo_opacity_val').html('('+logo_opacity+')');
        $('#logo_opacity_hover_val').html('('+logo_opacity_hover+')');
        $('.logo').css('opacity',logo_opacity);
        $(".logo").hover(function() {
            if(show_logo>0) {
                $(this).css('opacity',logo_opacity_hover);
            } else {
                $(this).css('opacity','');
            }
        }, function() {
            if(show_logo>0) {
                $(this).css('opacity',logo_opacity);
            } else {
                $(this).css('opacity','');
            }
        });
        var show_avatar_video = ($('#show_avatar_video').is(':checked')) ? 1 : 0;
        if(show_avatar_video==1) {
            $('.avatar_video img').removeClass('ui_disabled');
            $('.avatar_video video').removeClass('ui_disabled');
        } else {
            $('.avatar_video img').addClass('ui_disabled');
            $('.avatar_video video').addClass('ui_disabled');
        }
        var show_poweredby = parseInt($('#show_poweredby option:selected').attr('id'));
        if(show_poweredby>0) {
            $('.poweredby img').removeClass('ui_disabled');
            $('.poweredby span').removeClass('ui_disabled');
        } else {
            $('.poweredby img').addClass('ui_disabled');
            $('.poweredby span').addClass('ui_disabled');
            $(this).css('opacity','');
        }
        var poweredby_opacity = $('#poweredby_opacity').val();
        var poweredby_opacity_hover = $('#poweredby_opacity_hover').val();
        $('#poweredby_opacity_val').html('('+poweredby_opacity+')');
        $('#poweredby_opacity_hover_val').html('('+poweredby_opacity_hover+')');
        $('.poweredby').css('opacity',poweredby_opacity);
        $(".poweredby").hover(function() {
            if(show_poweredby>0) {
                $(this).css('opacity',poweredby_opacity_hover);
            } else {
                $(this).css('opacity','');
            }
        }, function() {
            if(show_poweredby>0) {
                $(this).css('opacity',poweredby_opacity);
            } else {
                $(this).css('opacity','');
            }
        });
        var show_nav_control = ($('#show_nav_control').is(':checked')) ? 1 : 0;
        if(show_nav_control==1) {
            $('.nav_control').removeClass('ui_disabled');
        } else {
            $('.nav_control').addClass('ui_disabled');
        }
        var show_comments = parseInt($('#show_comments option:selected').attr('id'));
        switch (show_comments) {
            case 0:
                $('.comments_vt').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.comments_vt').removeClass('ui_disabled');
                break;
        }
        var enable_rooms_multiple = ($('#enable_rooms_multiple').is(':checked')) ? 1 : 0;
        if(enable_rooms_multiple==0) {
            $('.rooms_view_sel').addClass('ui_disabled');
        } else {
            $('.rooms_view_sel').removeClass('ui_disabled');
        }
        var voice_commands = parseInt($('#voice_commands option:selected').attr('id'));
        switch (voice_commands) {
            case 0:
                $('#skitt-ui').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('#skitt-ui').removeClass('ui_disabled');
                break;
        }
        var show_custom = parseInt($('#show_custom option:selected').attr('id'));
        switch (show_custom) {
            case 0:
                $('.custom_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.custom_control').removeClass('ui_disabled');
                break;
        }
        var show_custom2 = parseInt($('#show_custom2 option:selected').attr('id'));
        switch (show_custom2) {
            case 0:
                $('.custom2_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.custom2_control').removeClass('ui_disabled');
                break;
        }
        var show_custom3 = parseInt($('#show_custom3 option:selected').attr('id'));
        switch (show_custom3) {
            case 0:
                $('.custom3_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.custom3_control').removeClass('ui_disabled');
                break;
        }
        var show_custom4 = parseInt($('#show_custom4 option:selected').attr('id'));
        switch (show_custom4) {
            case 0:
                $('.custom4_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.custom4_control').removeClass('ui_disabled');
                break;
        }
        var show_custom5 = parseInt($('#show_custom5 option:selected').attr('id'));
        switch (show_custom5) {
            case 0:
                $('.custom5_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.custom5_control').removeClass('ui_disabled');
                break;
        }
        var show_location = parseInt($('#show_location option:selected').attr('id'));
        switch (show_location) {
            case 0:
                $('.location_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.location_control').removeClass('ui_disabled');
                break;
        }
        var show_media = parseInt($('#show_media option:selected').attr('id'));
        switch (show_media) {
            case 0:
                $('.media_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.media_control').removeClass('ui_disabled');
                break;
        }
        var show_info = parseInt($('#show_info option:selected').attr('id'));
        switch (show_info) {
            case 0:
                $('.info_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.info_control').removeClass('ui_disabled');
                break;
        }
        var info_box_type = $('#info_box_type option:selected').attr('id');
        var show_dollhouse = parseInt($('#show_dollhouse option:selected').attr('id'));
        switch (show_dollhouse) {
            case 0:
                $('.dollhouse_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.dollhouse_control').removeClass('ui_disabled');
                break;
        }
        var show_gallery = parseInt($('#show_gallery option:selected').attr('id'));
        switch (show_gallery) {
            case 0:
                $('.gallery_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.gallery_control').removeClass('ui_disabled');
                break;
        }
        var compass = ($('#compass').is(':checked')) ? 1 : 0;
        if(compass==1) {
            $('.compass_control').removeClass('ui_disabled');
        } else {
            $('.compass_control').addClass('ui_disabled');
        }
        var fb_messenger = ($('#fb_messenger').is(':checked')) ? 1 : 0;
        if(fb_messenger==1) {
            $('.facebook_control').removeClass('ui_disabled');
        } else {
            $('.facebook_control').addClass('ui_disabled');
        }
        var whatsapp_chat = ($('#whatsapp_chat').is(':checked')) ? 1 : 0;
        if(whatsapp_chat==1) {
            $('.whatsapp_control').removeClass('ui_disabled');
        } else {
            $('.whatsapp_control').addClass('ui_disabled');
        }
        var arrows_nav = parseInt($('#arrows_nav option:selected').attr('id'));
        switch (arrows_nav) {
            case 0:
                $('.prev_arrow').addClass('ui_disabled');
                $('.next_arrow').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.prev_arrow').removeClass('ui_disabled');
                $('.next_arrow').removeClass('ui_disabled');
                break;
        }
        var auto_show_slider = parseInt($('#auto_show_slider option:selected').attr('id'));
        switch (auto_show_slider) {
            case 2:
                $('.list_control').addClass('ui_disabled');
                $('.list_control_alt').addClass('ui_disabled');
                $('.list_control i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
                $('.list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
                $('.list_slider ul').addClass('ui_disabled');
                $('.list_slider li').addClass('ui_disabled');
                $('.list_slider ,list_left').addClass('ui_disabled');
                $('.list_slider ,list_right').addClass('ui_disabled');
                break;
            case 1:
                $('.list_control').removeClass('ui_disabled');
                $('.list_control_alt').removeClass('ui_disabled');
                $('.list_control i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
                $('.list_control_alt').removeClass('fa-chevron-up').addClass('fa-chevron-down');
                $('.list_slider ul').removeClass('ui_disabled');
                $('.list_slider li').removeClass('ui_disabled');
                $('.list_slider ,list_left').removeClass('ui_disabled');
                $('.list_slider ,list_right').removeClass('ui_disabled');
                break;
            case 0:
                $('.list_control').removeClass('ui_disabled');
                $('.list_control_alt').removeClass('ui_disabled');
                $('.list_control i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
                $('.list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
                $('.list_slider ul').removeClass('ui_disabled');
                $('.list_slider li').removeClass('ui_disabled');
                $('.list_slider ,list_left').removeClass('ui_disabled');
                $('.list_slider ,list_right').removeClass('ui_disabled');
                break;
        }
        var nav_slider = parseInt($('#nav_slider option:selected').attr('id'));
        switch (nav_slider) {
            case 2:
                $('.list_slider .list_left').addClass('ui_disabled');
                $('.list_slider .list_right').addClass('ui_disabled');
                break;
            case 0:
            case 1:
                if(auto_show_slider!=2) {
                    $('.list_slider .list_left').removeClass('ui_disabled');
                    $('.list_slider .list_right').removeClass('ui_disabled');
                }
                break;
        }
        var nav_slider_mode = parseInt($('#nav_slider_mode option:selected').attr('id'));
        var show_icons_toggle = parseInt($('#show_icons_toggle option:selected').attr('id'));
        switch (show_icons_toggle) {
            case 0:
                $('.icons_control').addClass('ui_disabled');
                $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
                $('.icons_control').removeClass('ui_disabled');
                $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
                $('.icons_control').removeClass('ui_disabled');
                $('.icons_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        var show_icons_content_toggle = parseInt($('#show_icons_content_toggle option:selected').attr('id'));
        switch (show_icons_content_toggle) {
            case 0:
                $('.icons_content_control').addClass('ui_disabled');
                $('.icons_content_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
                $('.icons_content_control').removeClass('ui_disabled');
                $('.icons_content_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
                $('.icons_content_control').removeClass('ui_disabled');
                $('.icons_content_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        var show_icons_nav_toggle = parseInt($('#show_icons_nav_toggle option:selected').attr('id'));
        switch (show_icons_nav_toggle) {
            case 0:
                $('.icons_nav_control').addClass('ui_disabled');
                $('.icons_nav_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
                $('.icons_nav_control').removeClass('ui_disabled');
                $('.icons_nav_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
                $('.icons_nav_control').removeClass('ui_disabled');
                $('.icons_nav_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        if(show_icons_content_toggle>0 || show_icons_nav_toggle>0) {
            $('.icons_control').addClass('ui_disabled');
            $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
        }
        var show_snapshot = ($('#show_snapshot').is(':checked')) ? 1 : 0;
        if(show_snapshot==1) {
            $('.snapshot_control').removeClass('ui_disabled');
        } else {
            $('.snapshot_control').addClass('ui_disabled');
        }
        var selects_snapshots = {
            'snapshot_top_left': 'top_left',
            'snapshot_top_right': 'top_right',
            'snapshot_bottom_left': 'bottom_left',
            'snapshot_bottom_right': 'bottom_right'
        };
        var snapshot_params = {};
        for (var selectId in selects_snapshots) {
            var selectElement = document.getElementById(selectId);
            var selectedValue = selectElement.value;
            if (selectedValue !== 'none') {
                snapshot_params[selectedValue] = selects_snapshots[selectId];
            }
        }
        snapshot_params = JSON.stringify(snapshot_params);
        var show_measures_toggle = parseInt($('#show_measures_toggle option:selected').attr('id'));
        switch (show_measures_toggle) {
            case 0:
                $('.measures_control').addClass('ui_disabled');
                $('.measures_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
                $('.measures_control').removeClass('ui_disabled');
                $('.measures_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 1:
                $('.measures_control').removeClass('ui_disabled');
                $('.measures_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        var show_autorotation_toggle = parseInt($('#show_autorotation_toggle option:selected').attr('id'));
        var autorotate_speed = parseInt($('#autorotate_speed').val());
        if(autorotate_speed==0) {
            $('.autorotate_control').addClass('ui_disabled');
            $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
        } else {
            switch (show_autorotation_toggle) {
                case 0:
                    $('.autorotate_control').addClass('ui_disabled');
                    $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
                    break;
                case 3:
                    $('.autorotate_control').addClass('ui_disabled');
                    $('.autorotate_control .fa-circle').removeClass('not_active').addClass('active');
                    break;
                case 2:
                    $('.autorotate_control').removeClass('ui_disabled');
                    $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
                    break;
                case 1:
                    $('.autorotate_control').removeClass('ui_disabled');
                    $('.autorotate_control .fa-circle').removeClass('not_active').addClass('active');
                    break;
            }
        }
        var show_device_orientation = parseInt($('#show_device_orientation option:selected').attr('id'));
        switch (show_device_orientation) {
            case 0:
                $('.orient_control').addClass('ui_disabled');
                $('.orient_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 3:
                $('.orient_control').addClass('ui_disabled');
                $('.orient_control .fa-circle').removeClass('not_active').addClass('active');
                break;
            case 1:
                $('.orient_control').removeClass('ui_disabled');
                $('.orient_control .fa-circle').removeClass('active').addClass('not_active');
                break;
            case 2:
                $('.orient_control').removeClass('ui_disabled');
                $('.orient_control .fa-circle').removeClass('not_active').addClass('active');
                break;
        }
        var drag_device_orientation = ($('#drag_device_orientation').is(':checked')) ? 1 : 0;
        var show_webvr = ($('#show_webvr').is(':checked')) ? 1 : 0;
        if(show_webvr==1) {
            $('.vr_control').removeClass('ui_disabled');
        } else {
            $('.vr_control').addClass('ui_disabled');
        }
        var webvr_new_window = ($('#webvr_new_window').is(':checked')) ? 1 : 0;
        var show_presentation = parseInt($('#show_presentation option:selected').attr('id'));
        switch (show_presentation) {
            case 0:
                $('.presentation_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.presentation_control').removeClass('ui_disabled');
                $('.presentation_control').removeClass('ui_disabled');
                break;
        }
        var enable_visitor_rt = ($('#enable_visitor_rt').is(':checked')) ? 1 : 0;
        var enable_views_stat = ($('#enable_views_stat').is(':checked')) ? 1 : 0;
        var interval_visitor_rt = $('#interval_visitor_rt').val();
        if(enable_visitor_rt==1 || enable_views_stat==1) {
            $('.visitors_rt_stats').removeClass('ui_disabled');
        } else {
            $('.visitors_rt_stats').addClass('ui_disabled');
        }
        var show_share = $('#show_share option:selected').attr('id');
        if(show_share>0) {
            $('.share_control').removeClass('ui_disabled');
        } else {
            $('.share_control').addClass('ui_disabled');
        }
        var share_providers_t = $('#share_providers option');
        var share_providers = '';
        $(share_providers_t).each(function(index, elem){
            var id = $(this).attr('id');
            if(id !== undefined) {
                id = id.replace('provider_','');
                if($(this).is(':selected')) {
                    share_providers = share_providers+id+',';
                }
            }
        });
        if(share_providers!='') {
            share_providers = share_providers.substring(0,share_providers.length-1);
        }
        var show_main_form = ($('#show_main_form').is(':checked')) ? 1 : 0;
        if(show_main_form==1) {
            $('.form_control').removeClass('ui_disabled');
        } else {
            $('.form_control').addClass('ui_disabled');
        }
        var meeting = parseInt($('#meeting option:selected').attr('id'));
        switch (meeting) {
            case 0:
                $('.meeting_control').addClass('ui_disabled');
                break;
            case 1:
            case 2:
                $('.meeting_control').removeClass('ui_disabled');
                $('.meeting_control').removeClass('ui_disabled');
                break;
        }
        var live_session = ($('#live_session').is(':checked')) ? 1 : 0;
        if(live_session==1) {
            $('.live_control').removeClass('ui_disabled');
        } else {
            $('.live_control').addClass('ui_disabled');
        }
        var logo_height = $('#logo_height').val();
        if(logo_height=='') logo_height=40;
        $('.logo img').css('height',logo_height+'px');
        var poweredby_height = $('#poweredby_height').val();
        if(poweredby_height=='') poweredby_height=40;
        $('.poweredby img').css('height',poweredby_height+'px');
        var poweredby_font_size = $('#poweredby_font_size').val();
        if(poweredby_font_size=='') poweredby_font_size=12;
        var poweredby_font_color = $('#poweredby_font_color').val();
        $('.poweredby span').css('font-size',poweredby_font_size+'px');
        var logo_padding_left = $('#logo_padding_left').val();
        if(logo_padding_left=='') logo_padding_left=0;
        $('.logo img').css('margin-left',logo_padding_left+'px');
        var logo_padding_top = $('#logo_padding_top').val();
        if(logo_padding_top=='') logo_padding_top=0;
        $('.logo img').css('margin-top',logo_padding_top+'px');
        var logo_padding_right = $('#logo_padding_right').val();
        if(logo_padding_right=='') logo_padding_right=0;
        $('.logo img').css('margin-right',logo_padding_right+'px');
        var logo_position = $('#logo_position option:selected').attr('id');
        $('.logo').removeClass('logo_top_left').removeClass('logo_top_right').removeClass('logo_top_center').addClass('logo_'+logo_position);
        var avatar_video_height = $('#avatar_video_height').val();
        if(avatar_video_height=='') avatar_video_height=300;
        var avatar_video_width = $('#avatar_video_width').val();
        if(avatar_video_width=='') avatar_video_width=170;
        $('.avatar_video').css('width',(avatar_video_width==0) ? 'auto' : avatar_video_width+'px');
        $('.avatar_video').css('height',(avatar_video_height==0) ? 'auto' : avatar_video_height+'px');
        var avatar_video_padding_left = $('#avatar_video_padding_left').val();
        if(avatar_video_padding_left=='') avatar_video_padding_left=0;
        $('.avatar_video').css('margin-left',avatar_video_padding_left+'px');
        var avatar_video_padding_bottom = $('#avatar_video_padding_bottom').val();
        if(avatar_video_padding_bottom=='') avatar_video_padding_bottom=0;
        $('.avatar_video').css('margin-bottom',avatar_video_padding_bottom+'px');
        var avatar_video_padding_right = $('#avatar_video_padding_right').val();
        if(avatar_video_padding_right=='') avatar_video_padding_right=0;
        $('.avatar_video').css('margin-right',avatar_video_padding_right+'px');
        var avatar_video_position = $('#avatar_video_position option:selected').attr('id');
        $('.avatar_video').removeClass('avatar_video_bottom_left').removeClass('avatar_video_bottom_right').removeClass('avatar_video_bottom_center').addClass('avatar_video_'+avatar_video_position);
        var poweredby_position = $('#poweredby_position option:selected').attr('id');
        $('.poweredby').removeClass('poweredby_bottom_left').removeClass('poweredby_bottom_right').removeClass('poweredby_bottom_center').addClass('poweredby_'+poweredby_position);
        var annotation_position = $('#annotation_position option:selected').attr('id');
        $('.annotation').removeClass('annotation_top_left').removeClass('annotation_top_right').addClass('annotation_'+annotation_position);
        var map_position = $('#map_position option:selected').attr('id');
        $('.map').removeClass('map_top_left').removeClass('map_top_right').addClass('map_'+map_position);
        var inline_form_position = $('#inline_form_position option:selected').attr('id');
        $('.inline_form').removeClass('inline_form_top_left').removeClass('inline_form_top_right').addClass('inline_form_'+inline_form_position);
        var autoclose_menu = ($('#autoclose_menu').is(':checked')) ? 1 : 0;
        var autoopen_menu = ($('#autoopen_menu').is(':checked')) ? 1 : 0;
        var autoclose_list_alt = ($('#autoclose_list_alt').is(':checked')) ? 1 : 0;
        var autoclose_slider = ($('#autoclose_slider').is(':checked')) ? 1 : 0;
        var grouped_list_alt = ($('#grouped_list_alt').is(':checked')) ? 1 : 0;
        var autoclose_map = ($('#autoclose_map').is(':checked')) ? 1 : 0;
        var array_colors = {};
        $('.color_picker').each(function () {
            var id_cp = $(this).attr('id');
            array_colors[id_cp]=$(this).val();
        });
        $('.color_picker_bg').each(function () {
            var id_cp = $(this).attr('id');
            array_colors[id_cp]=$(this).val();
        });
        var array_positions = {};
        $('.position_select').each(function () {
            var id_pos = $(this).attr('id');
            array_positions[id_pos]=$("#"+id_pos+' option:selected').attr('id');
        });
        var array_orders = {};
        $('#controls_bottom_left div').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                array_orders[id]=$(this).css('order');
            }
        });
        $('#controls_bottom_center div').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                array_orders[id]=$(this).css('order');
            }
        });
        $('#controls_bottom_right div').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                array_orders[id]=$(this).css('order');
            }
        });
        if(menu_type=='sidebar') {
            $('#ms_controls .ms_control').each(function () {
                var id = $(this).attr('id');
                if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                    array_orders[id]=$(this).css('order');
                }
            });
        } else {
            $('.menu_controls .dropdown p').each(function () {
                var id = $(this).attr('id');
                if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                    array_orders[id]=$(this).css('order');
                }
            });
        }
        var array_icons = {};
        $('.icon_picker_value').each(function () {
            var id = $(this).attr('id').replace("_icon","");
            if(id!=null) {
                array_icons[id]=$(this).val();
            }
        });
        var array_library_icons = {};
        $('.library_icon_value').each(function () {
            var id = $(this).attr('id').replace("_library_icon","");
            if(id!=null) {
                var library_icon = $(this).val();
                if(library_icon=='') {
                    library_icon=0;
                } else {
                    library_icon = parseInt(library_icon);
                }
                array_library_icons[id]=library_icon;
            }
        });
        var custom_title = $('#custom_title').val();
        var custom_content = window.custom_content_html.getValue();
        var custom2_title = $('#custom2_title').val();
        var custom2_content = window.custom2_content_html.getValue();
        var custom3_title = $('#custom3_title').val();
        var custom3_content = window.custom3_content_html.getValue();
        var custom4_title = $('#custom4_title').val();
        var custom4_content = window.custom4_content_html.getValue();
        var custom5_title = $('#custom5_title').val();
        var custom5_content = window.custom5_content_html.getValue();
        var location_title = $('#location_title').val();
        var location_content = $('#gm_map').val()+"|"+$('#gm_street').val();
        var media_title = $('#media_title').val();
        var markers_icon = $('#markers_icon').val();
        var markers_icon_type = $('#markers_icon_type option:selected').attr('id');
        var markers_id_icon_library = $('#marker_library_icon').val();
        var markers_color = $('#markers_color').val();
        var markers_background = $('#markers_background').val();
        var markers_style = $('#markers_style option:selected').attr('id');
        var markers_tooltip_type = $('#markers_tooltip_type option:selected').attr('id');
        var markers_tooltip_visibility = $('#markers_tooltip_visibility option:selected').attr('id');
        var markers_tooltip_color = $('#markers_tooltip_color').val();
        var markers_tooltip_background = $('#markers_tooltip_background').val();
        var markers_default_scale = ($('#markers_default_scale').is(':checked')) ? 1 : 0;
        var markers_default_sticky = ($('#markers_default_sticky').is(':checked')) ? 1 : 0;
        var markers_default_rotateX = $('#markers_default_rotateX').val();
        var markers_default_rotateZ = $('#markers_default_rotateZ').val();
        var markers_default_size_scale = $('#markers_default_size_scale').val();
        var markers_default_sound = $('#markers_default_sound option:selected').attr('id');
        var markers_animation = $('#markers_animation option:selected').attr('id');
        var pois_icon = $('#pois_icon').val();
        var pois_icon_type = $('#pois_icon_type option:selected').attr('id');
        var pois_id_icon_library = $('#poi_library_icon').val();
        var pois_color = $('#pois_color').val();
        var pois_background = $('#pois_background').val();
        var pois_style = $('#pois_style option:selected').attr('id');
        var pois_tooltip_type = $('#pois_tooltip_type option:selected').attr('id');
        var pois_tooltip_visibility = $('#pois_tooltip_visibility option:selected').attr('id');
        var pois_tooltip_color = $('#pois_tooltip_color').val();
        var pois_tooltip_background = $('#pois_tooltip_background').val();
        var pois_default_scale = ($('#pois_default_scale').is(':checked')) ? 1 : 0;
        var pois_default_sticky = ($('#pois_default_sticky').is(':checked')) ? 1 : 0;
        var pois_default_rotateX = $('#pois_default_rotateX').val();
        var pois_default_rotateZ = $('#pois_default_rotateZ').val();
        var pois_default_size_scale = $('#pois_default_size_scale').val();
        var pois_default_sound = $('#pois_default_sound option:selected').attr('id');
        var pois_animation = $('#pois_animation option:selected').attr('id');
        switch(markers_style) {
            case 'room_and_icon':
                var markers_show_room = 2;
                break;
            case 'icon_and_room':
                var markers_show_room = 1;
                break;
            case 'only_icon':
                var markers_show_room = 0;
                break;
            case 'only_room':
                var markers_show_room = 3;
                break;
            case 'custom_icon':
                var markers_show_room = 4;
                break;
            case 'preview_room':
                var markers_show_room = 5;
                break;
            case 'label_and_icon':
                var markers_show_room = 7;
                break;
            case 'icon_and_label':
                var markers_show_room = 6;
                break;
            case 'only_label':
                var markers_show_room = 8;
                break;
        }
        switch(pois_style) {
            case 'label_and_icon':
                var pois_style_t = 3;
                break;
            case 'icon_and_label':
                var pois_style_t = 2;
                break;
            case 'only_icon':
                var pois_style_t = 0;
                break;
            case 'only_label':
                var pois_style_t = 4;
                break;
            case 'custom_icon':
                var pois_style_t = 1;
                break;
        }
        if(window.font_provider=='systems') {
            var font_viewer = $('#font_viewer_system option:selected').attr('id');
        } else {
            var font_viewer = $('#font_viewer').val();
        }
        var icons_tooltips = ($('#icons_tooltips').is(':checked')) ? 1 : 0;
        var preview_room_slider = ($('#preview_room_slider').is(':checked')) ? 1 : 0;
        var autorotate_inactivity = $('#autorotate_inactivity').val();
        var fb_page_id = $('#fb_page_id').val();
        var whatsapp_number = $('#whatsapp_number').val();
        var password_meeting = $('#password_meeting').val();
        var password_livesession = $('#password_livesession').val();
        var disqus_shortname = $('#disqus_shortname').val();
        var disqus_public_key = $('#disqus_public_key').val();
        var language = $('#language option:selected').attr('id');
        var languages_enabled_t = $('#languages_enabled option');
        var languages_enabled = {};
        var count_lang_enabled = 1;
        $(languages_enabled_t).each(function(index, elem){
            var id = $(this).attr('id').replace('ls_','');
            if($(this).is(':selected')) {
                languages_enabled[id]=1;
                $('#lang_btn_'+id).removeClass('ui_hidden');
                if(id!=window.default_language) {
                    count_lang_enabled++;
                }
            } else {
                languages_enabled[id]=0;
                $('#lang_btn_'+id).addClass('ui_hidden');
            }
        });
        var languages_enabled_json = JSON.stringify(languages_enabled);
        $('#ms_language_switcher img').removeClass('active');
        if(language=='') {
            $('#lang_btn_'+window.default_language).removeClass('ui_hidden');
            $('#lang_btn_'+window.default_language).addClass('active');
            $('.language_control img').attr('src','img/flags_lang/'+window.default_language+'.png?v=2');
            $('.language_alt_control img').attr('src','img/flags_lang/'+window.default_language+'.png?v=2');
        } else {
            $('#lang_btn_'+language).removeClass('ui_hidden');
            $('#lang_btn_'+language).addClass('active');
            $('.language_control img').attr('src','img/flags_lang/'+language+'.png?v=2');
            $('.language_alt_control img').attr('src','img/flags_lang/'+language+'.png?v=2');
        }
        var show_language = ($('#show_language').is(':checked')) ? 1 : 0;
        if(show_language==1 && count_lang_enabled>1) {
            $('.language_control').removeClass('ui_disabled');
            $('.language_alt_control').removeClass('ui_disabled');
            $('#ms_language_switcher').removeClass('ui_disabled');
        } else {
            $('.language_control').addClass('ui_disabled');
            $('.language_alt_control').addClass('ui_disabled');
            $('#ms_language_switcher').addClass('ui_disabled');
        }
        toggle_menu_control_disabled_ui();
        adjust_elements_positions();
        if(preset_save) {
            apply_preset=0;
            var id_preset = parseInt($('#presets_editor_ui option:selected').attr('id'));
            if(id_preset!=0) {
                var r = confirm(window.backend_labels.confirm_save_preset);
                if (r == false) {
                    save = false;
                    return;
                }
            }
            var name_preset = $('#preset_new_name').val();
            var preset_public = ($('#preset_public').is(':checked')) ? 1 : 0;
            if(id_preset==0 && name_preset=='') {
                $('#preset_new_name').addClass('error-highlight');
                save = false;
                return;
            } else {
                $('#preset_new_name').removeClass('error-highlight');
            }
        } else if(apply_preset) {
            apply_preset=1;
            var id_preset = parseInt($('#presets_editor_ui option:selected').attr('id'));
            var name_preset = '';
            var preset_public = 0;
        } else {
            apply_preset=0;
            var id_preset = null;
            var name_preset = '';
            var preset_public = 0;
        }
        array_lang['media_file'] = {};
        $.each(window.media_file_langs,function(lang,value) {
            array_lang['media_file'][lang]=value;
        });
        array_lang['media_title'] = {};
        $('.input_lang[data-target-id="media_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['media_title'][lang]=value;
        });
        array_lang['location_title'] = {};
        $('.input_lang[data-target-id="location_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['location_title'][lang]=value;
        });
        array_lang['location_content'] = {};
        $('.input_lang[data-target-id="gm_map"]').each(function() {
            var lang = $(this).attr('data-lang');
            var gm_map = $(this).val();
            var gm_street = $('.input_lang[data-target-id="gm_street"][data-lang="'+lang+'"]').val();
            array_lang['location_content'][lang]=gm_map+"|"+gm_street;
        });
        array_lang['custom_title'] = {};
        $('.input_lang[data-target-id="custom_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom_title'][lang]=value;
        });
        array_lang['custom_content'] = {};
        $('.input_lang[data-target-id="custom_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.custom_content_html_langs[lang].getValue();
            array_lang['custom_content'][lang]=value;
        });
        array_lang['custom2_title'] = {};
        $('.input_lang[data-target-id="custom2_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom2_title'][lang]=value;
        });
        array_lang['custom2_content'] = {};
        $('.input_lang[data-target-id="custom2_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.custom2_content_html_langs[lang].getValue();
            array_lang['custom2_content'][lang]=value;
        });
        array_lang['custom3_title'] = {};
        $('.input_lang[data-target-id="custom3_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom3_title'][lang]=value;
        });
        array_lang['custom3_content'] = {};
        $('.input_lang[data-target-id="custom3_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.custom3_content_html_langs[lang].getValue();
            array_lang['custom3_content'][lang]=value;
        });
        array_lang['custom4_title'] = {};
        $('.input_lang[data-target-id="custom4_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom4_title'][lang]=value;
        });
        array_lang['custom4_content'] = {};
        $('.input_lang[data-target-id="custom4_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.custom4_content_html_langs[lang].getValue();
            array_lang['custom4_content'][lang]=value;
        });
        array_lang['custom5_title'] = {};
        $('.input_lang[data-target-id="custom5_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['custom5_title'][lang]=value;
        });
        array_lang['custom5_content'] = {};
        $('.input_lang[data-target-id="custom5_content"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = window.custom5_content_html_langs[lang].getValue();
            array_lang['custom5_content'][lang]=value;
        });
        check_all_editor_ui_items();
        if(save_version) {
            var id_version = parseInt($('#versions_editor_ui option:selected').attr('id'));
            var name_version = $('#version_new_name').val();
            if(id_version==-1 && name_version=='') {
                $('#version_new_name').focus();
                return;
            }
        } else {
            var id_version = 0;
            var name_version = '';
        }
        var form_background = $('#form_background_m').val();
        var form_color = $('#form_color_m').val();
        var form_button_background = $('#form_background_button').val();
        var form_button_color = $('#form_color_button').val();
        if(save) {
            if(reload) $('#modal_change_languages').modal('hide');
            $('#modal_presets button').prop('disabled',true);
            $('#modal_versions button').prop('disabled',true);
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            var array_lang_json = JSON.stringify(array_lang);
            $.ajax({
                url: "ajax/save_virtual_tour_ui.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    id_user: window.id_user,
                    form_background: form_background,
                    form_color: form_color,
                    form_button_background: form_button_background,
                    form_button_color: form_button_color,
                    sidebar_enable: (menu_type=='sidebar') ? 1 : 0,
                    sidebar_glass: sidebar_glass,
                    sidebar_logo_height: sidebar_logo_height,
                    arrows_nav: arrows_nav,
                    voice_commands: voice_commands,
                    compass: compass,
                    auto_show_slider: auto_show_slider,
                    nav_slider: nav_slider,
                    nav_slider_mode: nav_slider_mode,
                    show_list_alt: show_list_alt,
                    show_custom: show_custom,
                    show_custom2: show_custom2,
                    show_custom3: show_custom3,
                    show_custom4: show_custom4,
                    show_custom5: show_custom5,
                    show_location: show_location,
                    show_media: show_media,
                    show_snapshot: show_snapshot,
                    snapshot_params: snapshot_params,
                    show_info: show_info,
                    info_box_type: info_box_type,
                    show_dollhouse: show_dollhouse,
                    show_gallery: show_gallery,
                    show_icons_toggle: show_icons_toggle,
                    show_icons_content_toggle: show_icons_content_toggle,
                    show_icons_nav_toggle: show_icons_nav_toggle,
                    show_measures_toggle: show_measures_toggle,
                    show_autorotation_toggle: show_autorotation_toggle,
                    show_nav_control: show_nav_control,
                    show_presentation: show_presentation,
                    show_main_form: show_main_form,
                    show_share: show_share,
                    share_providers: share_providers,
                    show_device_orientation: show_device_orientation,
                    drag_device_orientation: drag_device_orientation,
                    show_webvr: show_webvr,
                    webvr_new_window: webvr_new_window,
                    show_audio: show_audio,
                    show_vt_title: show_vt_title,
                    vt_title_height: vt_title_height,
                    show_fullscreen: show_fullscreen,
                    show_map: show_map,
                    show_map_tour: show_map_tour,
                    live_session: live_session,
                    meeting: meeting,
                    show_annotations: show_annotations,
                    show_inline_form: show_inline_form,
                    autoclose_menu: autoclose_menu,
                    autoopen_menu: autoopen_menu,
                    autoclose_list_alt: autoclose_list_alt,
                    autoclose_slider: autoclose_slider,
                    grouped_list_alt: grouped_list_alt,
                    autoclose_map: autoclose_map,
                    show_logo: show_logo,
                    logo_opacity: logo_opacity,
                    logo_opacity_hover: logo_opacity_hover,
                    fb_messenger: fb_messenger,
                    whatsapp_chat: whatsapp_chat,
                    array_colors: array_colors,
                    array_positions: array_positions,
                    array_orders: array_orders,
                    array_icons: array_icons,
                    array_library_icons: array_library_icons,
                    annotation_position: annotation_position,
                    inline_form_position: inline_form_position,
                    map_position: map_position,
                    logo_position: logo_position,
                    logo_height: logo_height,
                    logo_padding_left: logo_padding_left,
                    logo_padding_top: logo_padding_top,
                    logo_padding_right: logo_padding_right,
                    custom_title: custom_title,
                    custom2_title: custom2_title,
                    custom3_title: custom3_title,
                    custom4_title: custom4_title,
                    custom5_title: custom5_title,
                    custom_content: custom_content,
                    custom2_content: custom2_content,
                    custom3_content: custom3_content,
                    custom4_content: custom4_content,
                    custom5_content: custom5_content,
                    location_title: location_title,
                    location_content: location_content,
                    media_title: media_title,
                    markers_icon: markers_icon,
                    markers_icon_type: markers_icon_type,
                    markers_id_icon_library: markers_id_icon_library,
                    markers_color: markers_color,
                    markers_background: markers_background,
                    markers_show_room: markers_show_room,
                    markers_tooltip_type: markers_tooltip_type,
                    markers_tooltip_visibility: markers_tooltip_visibility,
                    markers_tooltip_background: markers_tooltip_background,
                    markers_tooltip_color: markers_tooltip_color,
                    markers_default_scale: markers_default_scale,
                    markers_default_sticky: markers_default_sticky,
                    markers_default_rotateX: markers_default_rotateX,
                    markers_default_rotateZ: markers_default_rotateZ,
                    markers_default_size_scale: markers_default_size_scale,
                    markers_default_sound: markers_default_sound,
                    markers_animation: markers_animation,
                    pois_icon: pois_icon,
                    pois_icon_type: pois_icon_type,
                    pois_id_icon_library: pois_id_icon_library,
                    pois_color: pois_color,
                    pois_background: pois_background,
                    pois_style: pois_style_t,
                    pois_tooltip_type: pois_tooltip_type,
                    pois_tooltip_visibility: pois_tooltip_visibility,
                    pois_tooltip_background: pois_tooltip_background,
                    pois_tooltip_color: pois_tooltip_color,
                    pois_default_scale: pois_default_scale,
                    pois_default_sticky: pois_default_sticky,
                    pois_default_rotateX: pois_default_rotateX,
                    pois_default_rotateZ: pois_default_rotateZ,
                    pois_default_size_scale: pois_default_size_scale,
                    pois_default_sound: pois_default_sound,
                    pois_animation: pois_animation,
                    font_viewer: font_viewer,
                    id_preset: id_preset,
                    name_preset: name_preset,
                    preset_public: preset_public,
                    apply_preset: apply_preset,
                    nadir_size: nadir_size,
                    icons_tooltips: icons_tooltips,
                    autorotate_inactivity: autorotate_inactivity,
                    autorotate_speed: autorotate_speed,
                    song_autoplay: song_autoplay,
                    fb_page_id: fb_page_id,
                    whatsapp_number: whatsapp_number,
                    password_meeting: password_meeting,
                    password_livesession: password_livesession,
                    preview_room_slider: preview_room_slider,
                    show_comments: show_comments,
                    disqus_shortname: disqus_shortname,
                    disqus_public_key: disqus_public_key,
                    language: language,
                    languages_enabled: languages_enabled_json,
                    show_language: show_language,
                    show_poweredby: show_poweredby,
                    poweredby_opacity: poweredby_opacity,
                    poweredby_opacity_hover: poweredby_opacity_hover,
                    poweredby_height: poweredby_height,
                    poweredby_font_size: poweredby_font_size,
                    poweredby_font_color: poweredby_font_color,
                    poweredby_position: poweredby_position,
                    media_file: window.media_file,
                    show_avatar_video: show_avatar_video,
                    avatar_video_position: avatar_video_position,
                    avatar_video_width: avatar_video_width,
                    avatar_video_height: avatar_video_height,
                    avatar_video_padding_left: avatar_video_padding_left,
                    avatar_video_padding_bottom: avatar_video_padding_bottom,
                    avatar_video_padding_right: avatar_video_padding_right,
                    multiple_room_views_size: multiple_room_views_size,
                    multiple_room_views_style: multiple_room_views_style,
                    multiple_room_views_border: multiple_room_views_border,
                    multiple_room_views_border_color: multiple_room_views_border,
                    array_lang: array_lang_json,
                    enable_visitor_rt: enable_visitor_rt,
                    enable_views_stat: enable_views_stat,
                    enable_rooms_multiple: enable_rooms_multiple,
                    interval_visitor_rt: interval_visitor_rt,
                    buttons_style: buttons_style,
                    buttons_size: buttons_size,
                    id_version_sel: window.id_version_sel,
                    id_version: id_version,
                    name_version: name_version
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        if(apply_preset==1) {
                            window.ui_need_save = false;
                            location.reload();
                        } else if(preset_save) {
                            if(id_preset==0) {
                                var id_new_preset = rsp.id_preset;
                                get_editor_ui_presets(id_new_preset);
                            } else {
                                get_editor_ui_presets(id_preset);
                            }
                            $('#modal_presets button').prop('disabled',false);
                            $('#modal_versions button').prop('disabled',false);
                            $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                            setTimeout(function () {
                                $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                                $('#save_btn').removeClass("disabled");
                            },1000);
                        } else {
                            window.ui_need_save = false;
                            $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                            if(save_version) {
                                var id_version = rsp.id_version;
                                var mode_version = rsp.mode_version;
                                switch(mode_version) {
                                    case 'add':
                                        location.href = 'index.php?p=edit_virtual_tour_ui&version='+id_version;
                                        break;
                                    case 'update':
                                        $('#active_version_name').html(name_version);
                                        $('#versions_editor_ui option[id='+id_version+']').text(name_version);
                                        $('#versions_editor_ui option[id='+id_version+']').attr('data-name',name_version);
                                        break;
                                }
                            } else if(apply_version) {
                                var id_version = parseInt($('#versions_editor_ui option:selected').attr('id'));
                                if(id_version==0) {
                                    location.href = 'index.php?p=edit_virtual_tour_ui';
                                } else {
                                    location.href = 'index.php?p=edit_virtual_tour_ui&version='+id_version;
                                }
                            } else {
                                if(reload) location.reload();
                            }
                            setTimeout(function () {
                                $('#modal_presets button').prop('disabled',false);
                                $('#modal_versions button').prop('disabled',false);
                                $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                                $('#save_btn').removeClass("disabled");
                            },1000);
                        }
                    } else {
                        $('#modal_presets button').prop('disabled',false);
                        $('#modal_versions button').prop('disabled',false);
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                    }
                },
                error: function() {
                    $('#modal_presets button').prop('disabled',false);
                    $('#modal_versions button').prop('disabled',false);
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                }
            });
        }
    }

    window.toggle_editor_ui_items = function() {
        if($('#list_editor_ui_items').hasClass('open')) {
            $('#list_editor_ui_items').removeClass('open');
            $('#ui_container').removeClass('ui_container_open');
            $('#list_editor_ui_items').hide();
        } else {
            $('#list_editor_ui_items').addClass('open');
            $('#ui_container').addClass('ui_container_open');
            $('#list_editor_ui_items').show();
        }
    }

    window.check_all_editor_ui_items = function() {
        $('#list_editor_ui_items li').not('[data-ui-target="ui_edit_title"]').not('[data-ui-target="ui_edit_multiple_room_views"]').find('i.fas').css('color', 'darkgreen');
        const elementsWithDataUiTarget = document.querySelectorAll('[data-ui-target]');
        elementsWithDataUiTarget.forEach(element => {
            if ((element.getAttribute('data-ui-target')!='ui_edit_title') && (element.classList.contains('ui_disabled'))) {
                $('#list_editor_ui_items li[data-ui-target="'+element.getAttribute('data-ui-target')+'"] i.fas').css('color','darkorange');
            }
        });
        var show_vt_title = parseInt($('#show_vt_title option:selected').attr('id'));
        switch(show_vt_title) {
            case 0:
                $('#list_editor_ui_items li[data-ui-target="ui_edit_title"] i.fas').css('color','darkorange');
                break;
            case 1:
            case 2:
            case 3:
                $('#list_editor_ui_items li[data-ui-target="ui_edit_title"] i.fas').css('color','darkgreen');
                break;
        }
    }

    window.close_edit_box = function() {
        $('#list_editor_ui_items li').removeClass('active');
        $('#ui_container .avatar_video').css('z-index',30);
        $('.ui_edit_box').hide();
    }

    window.change_ui_position = function (id) {
        var position = $('#'+id+' option:selected').attr('id');
        var target = $('#'+id).attr('data-target');
        switch(target) {
            case 'list_control':
            case 'arrows_control':
                $('.controls_arrows').addClass('ui_hidden');
                $('.list_control').addClass('ui_hidden');
                $('.list_control_alt').addClass('ui_hidden');
                $('.arrows_nav').addClass('ui_hidden');
                $('.prev_arrow').addClass('ui_hidden');
                $('.next_arrow').addClass('ui_hidden');
                var position_list = $('#position_list option:selected').attr('id');
                var position_arrows = $('#position_arrows option:selected').attr('id');
                if(target=='list_control' && position_list!='default' && position_arrows!='default') {
                    $('#position_arrows option').prop('selected',false);
                    $('#position_arrows option[id="'+position_list+'"]').prop('selected',true);
                    position_arrows = position_list;
                }
                if(target=='arrows_control' && position_list!='default' && position_arrows!='default') {
                    $('#position_list option').prop('selected',false);
                    $('#position_list option[id="'+position_arrows+'"]').prop('selected',true);
                    position_list = position_arrows;
                }
                position_list = position_list.replace('button_','');
                position_arrows = position_arrows.replace('button_','');
                if(position_list!='default') {
                    $('#controls_bottom_'+position_list+' .list_control_alt').removeClass('ui_hidden');
                    $('#list_background').removeClass('d-none');
                    $('#list_background_hover').removeClass('d-none');
                } else {
                    $('.list_control').removeClass('ui_hidden');
                    $('#list_background').addClass('d-none');
                    $('#list_background_hover').addClass('d-none');
                }
                if(position_arrows!='default') {
                    $('#controls_bottom_'+position_arrows+' .prev_arrow').removeClass('ui_hidden');
                    $('#controls_bottom_'+position_arrows+' .next_arrow').removeClass('ui_hidden');
                    $('#arrows_background').removeClass('d-none');
                    $('#arrows_background_hover').removeClass('d-none');
                    $('.controls_arrows').css('background-color',$('#arrows_background').val());
                } else {
                    $('.arrows_nav').removeClass('ui_hidden');
                    $('.arrows_nav .prev_arrow').removeClass('ui_hidden');
                    $('.arrows_nav .next_arrow').removeClass('ui_hidden');
                    $('#arrows_background').addClass('d-none');
                    $('#arrows_background_hover').addClass('d-none');
                    $('.controls_arrows').css('background-color','transparent');
                }
                $('.controls_arrows i:not(.ui_hidden):first').css('margin-right','0');
                $('.controls_arrows i:not(.ui_hidden):nth-child(2)').css('margin-right','0');
                if((position_list!='default') || (position_arrows!='default')) {
                    if(position_list!='default') {
                        $('#controls_arrow_'+position_list+'').removeClass('ui_hidden');
                        if(!$('#controls_arrow_'+position_list+' .prev_arrow').hasClass('ui_hidden')) {
                            $('.controls_arrows i:not(.ui_hidden):first').css('margin-right','-7px');
                            $('.controls_arrows i:not(.ui_hidden):nth-child(2)').css('margin-right','-9px');
                        }
                    }
                    if(position_arrows!='default') {
                        $('#controls_arrow_'+position_arrows+'').removeClass('ui_hidden');
                        if(!$('#controls_arrow_'+position_arrows+' .prev_arrow').hasClass('ui_hidden')) {
                            $('.controls_arrows i:not(.ui_hidden):first').css('margin-right','-7px');
                            $('.controls_arrows i:not(.ui_hidden):nth-child(2)').css('margin-right','-9px');
                        }
                    }
                }
                if($('.list_control').hasClass('ui_hidden')) {
                    $('#controls_bottom_center').css('bottom','112px');
                } else {
                    $('#controls_bottom_center').css('bottom','136px');
                }
                break;
            default:
                let containerSelector = '';
                switch (position) {
                    case 'button_left':
                        containerSelector = '#controls_bottom_left';
                        break;
                    case 'button_center':
                        containerSelector = '#controls_bottom_center';
                        break;
                    case 'button_right':
                        containerSelector = '#controls_bottom_right';
                        break;
                    case 'menu':
                        containerSelector = '.menu_controls .dropdown';
                        break;
                    case 'menulist':
                        containerSelector = '.menu_controls .dropdown';
                        break;
                }
                switch (target) {
                    case 'fullscreen_alt_control':
                        switch(position) {
                            case 'menu':
                                $('.fullscreen_colors').removeClass('d-none');
                                $('.fullscreen_alt_colors').addClass('d-none');
                                $('.fullscreen_control_icon').removeClass('ui_hidden');
                                $('.menu_controls .dropdown .fullscreen_alt_control').addClass('ui_hidden');
                                $('.controls_btn.fullscreen_alt_control').addClass('ui_hidden');
                                break;
                            case 'menulist':
                                $('.fullscreen_colors').addClass('d-none');
                                $('.fullscreen_alt_colors').removeClass('d-none');
                                $('.fullscreen_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .fullscreen_alt_control').removeClass('ui_hidden');
                                $('.controls_btn.fullscreen_alt_control').addClass('ui_hidden');
                                break;
                            default:
                                $('.fullscreen_colors').addClass('d-none');
                                $('.fullscreen_alt_colors').removeClass('d-none');
                                $('.fullscreen_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .fullscreen_alt_control').addClass('ui_hidden');
                                $('.controls_btn.fullscreen_alt_control').addClass('ui_hidden');
                                $(`${containerSelector} .controls_btn.fullscreen_alt_control`).removeClass('ui_hidden');
                                break;
                        }
                        break;
                    case 'floorplan_alt_control':
                        switch(position) {
                            case 'menu':
                                $('.floorplan_colors').removeClass('d-none');
                                $('.floorplan_alt_colors').addClass('d-none');
                                $('.map_control_icon').removeClass('ui_hidden');
                                $('.menu_controls .dropdown .floorplan_alt_control').addClass('ui_hidden');
                                $('.controls_btn.floorplan_alt_control').addClass('ui_hidden');
                                break;
                            case 'menulist':
                                $('.floorplan_colors').addClass('d-none');
                                $('.floorplan_alt_colors').removeClass('d-none');
                                $('.map_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .floorplan_alt_control').removeClass('ui_hidden');
                                $('.controls_btn.floorplan_alt_control').addClass('ui_hidden');
                                break;
                            default:
                                $('.floorplan_colors').addClass('d-none');
                                $('.floorplan_alt_colors').removeClass('d-none');
                                $('.map_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .floorplan_alt_control').addClass('ui_hidden');
                                $('.controls_btn.floorplan_alt_control').addClass('ui_hidden');
                                $(`${containerSelector} .controls_btn.floorplan_alt_control`).removeClass('ui_hidden');
                                break;
                        }
                        break;
                    case 'map_alt_control':
                        switch(position) {
                            case 'menu':
                                $('.map_colors').removeClass('d-none');
                                $('.map_alt_colors').addClass('d-none');
                                $('.map_tour_control_icon').removeClass('ui_hidden');
                                $('.menu_controls .dropdown .map_alt_control').addClass('ui_hidden');
                                $('.controls_btn.map_alt_control').addClass('ui_hidden');
                                break;
                            case 'menulist':
                                $('.map_colors').addClass('d-none');
                                $('.map_alt_colors').removeClass('d-none');
                                $('.map_tour_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .map_alt_control').removeClass('ui_hidden');
                                $('.controls_btn.map_alt_control').addClass('ui_hidden');
                                break;
                            default:
                                $('.map_colors').addClass('d-none');
                                $('.map_alt_colors').removeClass('d-none');
                                $('.map_tour_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .map_alt_control').addClass('ui_hidden');
                                $('.controls_btn.map_alt_control').addClass('ui_hidden');
                                $(`${containerSelector} .controls_btn.map_alt_control`).removeClass('ui_hidden');
                                break;
                        }
                        break;
                    case 'language_alt_control':
                        switch(position) {
                            case 'menu':
                                $('.language_control_icon').removeClass('ui_hidden');
                                $('#ms_language_switcher').addClass('ui_hidden');
                                $('.menu_controls .dropdown .language_alt_control').addClass('ui_hidden');
                                $('.controls_btn.language_alt_control').addClass('ui_hidden');
                                break;
                            case 'menulist':
                                $('.language_control_icon').addClass('ui_hidden');
                                $('#ms_language_switcher').removeClass('ui_hidden');
                                $('.menu_controls .dropdown .language_alt_control').removeClass('ui_hidden');
                                $('.controls_btn.language_alt_control').addClass('ui_hidden');
                                break;
                        }
                        break;
                    case 'song_alt_control':
                        switch(position) {
                            case 'menu':
                                $('.song_colors').removeClass('d-none');
                                $('.song_alt_colors').addClass('d-none');
                                $('.song_control_icon').removeClass('ui_hidden');
                                $('.menu_controls .dropdown .song_alt_control').addClass('ui_hidden');
                                $('.controls_btn.song_alt_control').addClass('ui_hidden');
                                break;
                            case 'menulist':
                                $('.song_colors').addClass('d-none');
                                $('.song_alt_colors').removeClass('d-none');
                                $('.song_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .song_alt_control').removeClass('ui_hidden');
                                $('.controls_btn.song_alt_control').addClass('ui_hidden');
                                break;
                            default:
                                $('.song_colors').addClass('d-none');
                                $('.song_alt_colors').removeClass('d-none');
                                $('.song_control_icon').addClass('ui_hidden');
                                $('.menu_controls .dropdown .song_alt_control').addClass('ui_hidden');
                                $('.controls_btn.song_alt_control').addClass('ui_hidden');
                                $(`${containerSelector} .controls_btn.song_alt_control`).removeClass('ui_hidden');
                                break;
                        }
                        break;
                    default:
                        $(`.${target}`).addClass('ui_hidden');
                        $(`${containerSelector} .${target}`).removeClass('ui_hidden');
                        break;
                }
        }
        if(position=='menulist' || position=='menu') {
            $(`#ms_controls .${target}`).removeClass('ui_hidden');
        }
        var menu_type = $('#menu_type option:selected').attr('id');
        if(position=='menulist' && target!='language_alt_control') {
            switch(menu_type) {
                case 'dropdown':
                    if(!$('.menu_controls .dropdown').hasClass('down')) {
                        click_menu_controls();
                    }
                    break;
                case 'sidebar':
                    if(!$('#menu_sidebar').hasClass('open')) {
                        click_menu_controls();
                    }
                    break;
            }
        } else if(position=='menulist' && target=='language_alt_control' && menu_type=='sidebar') {
            if(!$('#menu_sidebar').hasClass('open')) {
                click_menu_controls();
            }
        }
        fix_ui_order();
        save_vt_ui(false,false,false);
    }

    window.change_ui_order = function (direction, id_curr, id_pos) {
        let container = '';
        let elements = '';
        const position = $('#' + id_pos + ' option:selected').attr('id');
        switch (position) {
            case 'button_left':
                container = '#controls_bottom_left';
                elements = container + ' div';
                break;
            case 'button_center':
                container = '#controls_bottom_center';
                elements = container + ' div';
                break;
            case 'button_right':
                container = '#controls_bottom_right';
                elements = container + ' div';
                break;
            case 'menulist':
            case 'menu':
                var menu_type = $('#menu_type option:selected').attr('id');
                if(menu_type=='sidebar') {
                    container = '#ms_controls';
                    elements = container + ' .ms_control';
                } else {
                    container = '.menu_controls .dropdown';
                    elements = container + ' p';
                }
                break;
        }
        const current_selector = container + ' .' + id_curr;
        const current_order = $(current_selector).css('order');
        const array_orders = [];
        $(elements).each(function () {
            const id = $(this).attr('id');
            if (id && id !== 'skitt-ui' && !$(this).hasClass('ui_hidden')) {
                const order = $(this).css('order');
                array_orders.push({ id, order: parseInt(order, 10) });
            }
        });
        array_orders.sort((a, b) => a.order - b.order);
        for (let i = 0; i < array_orders.length; i++) {
            if (current_order == array_orders[i].order) {
                const current = array_orders[i];
                if (direction === 'next') {
                    const next = array_orders[(i + 1) % array_orders.length];
                    const next_order = $('#' + next.id).css('order');
                    $('.' + id_curr).css('order', next_order);
                    $('#' + next.id).css('order', current_order);
                } else if (direction === 'prev') {
                    const prev = array_orders[(i + array_orders.length - 1) % array_orders.length];
                    const prev_order = $('#' + prev.id).css('order');
                    $('.' + id_curr).css('order', prev_order);
                    $('#' + prev.id).css('order', current_order);
                }

                break;
            }
        }
        setTimeout(() => {
            save_vt_ui(false, false, false);
        }, 200);
    }

    window.fix_ui_order = function () {
        var array_orders = [];
        $('#controls_bottom_right div').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                var order = $(this).css('order');
                array_orders.push({'id':id,'order':order});
            }
        });
        array_orders.sort((a,b) =>  a.order-b.order);
        var len = array_orders.length;
        for(var i=0;i<len;i++) {
            $("#"+array_orders[i].id).css('order',i);
        }
        array_orders = [];
        $('#controls_bottom_center div').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                var order = $(this).css('order');
                array_orders.push({'id':id,'order':order});
            }
        });
        array_orders.sort((a,b) =>  a.order-b.order);
        var len = array_orders.length;
        for(var i=0;i<len;i++) {
            $("#"+array_orders[i].id).css('order',i);
        }
        array_orders = [];
        $('#controls_bottom_left div').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                var order = $(this).css('order');
                array_orders.push({'id':id,'order':order});
            }
        });
        array_orders.sort((a,b) =>  a.order-b.order);
        var len = array_orders.length;
        for(var i=0;i<len;i++) {
            $("#"+array_orders[i].id).css('order',i);
        }
        array_orders = [];
        $('.menu_controls .dropdown p').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                var order = $(this).css('order');
                array_orders.push({'id':id,'order':order});
            }
        });
        array_orders.sort((a,b) =>  a.order-b.order);
        var len = array_orders.length;
        for(var i=0;i<len;i++) {
            $("#"+array_orders[i].id).css('order',i);
        }
        array_orders = [];
        $('#ms_controls .ms_control').each(function () {
            var id = $(this).attr('id');
            if(id!=null && id!='skitt-ui' && !$(this).hasClass('ui_hidden')) {
                var order = $(this).css('order');
                array_orders.push({'id':id,'order':order});
            }
        });
        array_orders.sort((a,b) =>  a.order-b.order);
        var len = array_orders.length;
        for(var i=0;i<len;i++) {
            $("#"+array_orders[i].id).css('order',i);
        }
    }

    window.toggle_menu_control_disabled_ui = function () {
        var all_disabled = true;
        $('.menu_controls .dropdown p').each(function () {
            if(!$(this).hasClass("ui_hidden")) {
                if(!$(this).hasClass('ui_disabled')) {
                    all_disabled = false;
                }
            }
        });
        if(all_disabled) {
            $('#list_editor_ui_items li[data-ui-target="ui_edit_menu"] i').css('color','darkorange');
            $('.menu_controls #menu_icon').addClass('ui_disabled');
        } else {
            $('#list_editor_ui_items li[data-ui-target="ui_edit_menu"] i').css('color','darkgreen');
            $('.menu_controls #menu_icon').removeClass('ui_disabled');
        }
    }

    window.save_paypal_subscription_id = function (id_user,intent,subscriptionID,note="") {
        $.ajax({
            url: "ajax/save_paypal_subscription_id.php",
            type: "POST",
            data: {
                id_user: id_user,
                intent: intent,
                subscriptionID: subscriptionID,
                note: note
            },
            async: false,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=="ok") {
                    if(intent=='service') {
                        location.href = 'index.php?p=buy_service&response=success&uid='+rsp.uid;
                    } else {
                        location.reload();
                    }
                } else {
                    alert(rsp.msg);
                }
            }, error: function() {
                alert(window.backend_labels.error_msg);
            }
        });
    }

    window.change_version_editor_ui = function () {
        id_version_sel = parseInt(id_version_sel);
        var id_version = parseInt($('#versions_editor_ui option:selected').attr('id'));
        var version_name = $('#versions_editor_ui option:selected').attr('data-name');
        $('#version_new_name').val(version_name);
        switch(id_version) {
            case -1:
                $('#btn_delete_version').addClass('disabled');
                $('#btn_add_version').removeClass('disabled');
                $('#version_new_name').removeClass('disabled');
                $('#btn_apply_version').addClass('disabled');
                $('#version_new_name').focus();
                break;
            case 0:
                $('#btn_delete_version').addClass('disabled');
                $('#btn_add_version').addClass('disabled');
                $('#version_new_name').addClass('disabled');
                if(id_version_sel==0) {
                    $('#btn_apply_version').addClass('disabled');
                } else {
                    $('#btn_apply_version').removeClass('disabled');
                }
                break;
            default:
                $('#btn_delete_version').removeClass('disabled');
                $('#btn_update_version').removeClass('disabled');
                $('#btn_add_version').removeClass('disabled');
                $('#version_new_name').removeClass('disabled');
                $('#btn_delete_version').attr('onclick','delete_editor_ui_version('+id_version+')');
                if(id_version==id_version_sel) {
                    $('#btn_apply_version').addClass('disabled');
                } else {
                    $('#btn_apply_version').removeClass('disabled');
                }
                break;
        }
    }

    window.change_preset_editor_ui = function () {
        var id_preset = parseInt($('#presets_editor_ui option:selected').attr('id'));
        var preset_name = $('#presets_editor_ui option:selected').attr('data-name');
        var preset_public = parseInt($('#presets_editor_ui option:selected').attr('data-public'));
        var preset_delete = parseInt($('#presets_editor_ui option:selected').attr('data-delete'));
        var preset_update = parseInt($('#presets_editor_ui option:selected').attr('data-update'));
        $('#preset_new_name').val(preset_name);
        if(preset_public==1) {
            $('#preset_public').prop('checked',true);
        } else {
            $('#preset_public').prop('checked',false);
        }
        if(preset_delete==1) {
            $('#btn_delete_preset').removeClass('disabled');
            $('#btn_delete_preset').attr('onclick','delete_editor_ui_preset('+id_preset+')');
        } else {
            $('#btn_delete_preset').addClass('disabled');
            $('#btn_delete_preset').attr('onclick','');
        }
        if(preset_update==1) {
            $('#btn_update_preset').removeClass('disabled');
            $('#preset_new_name').removeClass('disabled');
        } else {
            $('#btn_update_preset').addClass('disabled');
            $('#preset_new_name').addClass('disabled');
        }
        if(id_preset==0) {
            $('#btn_apply_preset').addClass('disabled');
            $('#preset_new_name').focus();
        } else {
            $('#btn_apply_preset').removeClass('disabled');
        }
    }

    window.get_editor_ui_presets = function (id_preset) {
        $.ajax({
            url: "ajax/get_editor_ui_presets.php",
            type: "POST",
            data: {
                id_preset: id_preset
            },
            async: false,
            success: function (json) {
                var rsp = JSON.parse(json);
                var html = rsp.html;
                $('#presets_editor_ui').html(html).promise().done(function () {
                    change_preset_editor_ui();
                });
            }
        });
    }

    window.delete_editor_ui_preset = function (id_preset) {
        var r = confirm(window.backend_labels.confirm_delete_preset);
        if (r == true) {
            $('#modal_presets button').addClass('disabled');
            $.ajax({
                url: "ajax/delete_editor_ui_preset.php",
                type: "POST",
                data: {
                    id_preset: id_preset
                },
                async: true,
                success: function (json) {
                    $('#modal_presets button').removeClass('disabled');
                    get_editor_ui_presets(0);
                }
            });
        }
    }

    window.delete_editor_ui_version = function (id_version) {
        var r = confirm(window.backend_labels.confirm_delete_version);
        if (r == true) {
            $('#modal_versions button').prop('disabled',true);
            $.ajax({
                url: "ajax/delete_editor_ui_version.php",
                type: "POST",
                data: {
                    id_version: id_version
                },
                async: true,
                success: function (json) {
                    location.href = 'index.php?p=edit_virtual_tour_ui';
                },
                error: function() {
                    location.href = 'index.php?p=edit_virtual_tour_ui';
                }
            });
        }
    }

    window.apply_editor_ui_preset = function () {
        var r = confirm(window.backend_labels.confirm_apply_preset);
        if (r == true) {
            $('#modal_presets button').addClass('disabled');
            save_vt_ui(true,false,true);
        }
    }

    window.change_multires = function () {
        var multires = $('#multires option:selected').attr('id');
        switch (multires) {
            case 'local':
                $('#multires_cloud_url').prop('disabled',true);
                break;
            case 'cloud':
                $('#multires_cloud_url').prop('disabled',false);
                break;
        }
    }

    window.change_video360 = function () {
        var video360 = $('#video360 option:selected').attr('id');
        switch (video360) {
            case 'local':
                $('#video360_cloud_url').prop('disabled',true);
                break;
            case 'cloud':
                $('#video360_cloud_url').prop('disabled',false);
                break;
        }
    }

    window.change_slideshow = function () {
        var slideshow = $('#slideshow option:selected').attr('id');
        switch (slideshow) {
            case 'local':
                $('#slideshow_cloud_url').prop('disabled',true);
                break;
            case 'cloud':
                $('#slideshow_cloud_url').prop('disabled',false);
                break;
        }
    }

    window.change_video_project = function () {
        var slideshow = $('#video_project option:selected').attr('id');
        switch (slideshow) {
            case 'local':
                $('#video_project_url').prop('disabled',true);
                break;
            case 'cloud':
                $('#video_project_url').prop('disabled',false);
                break;
        }
    }

    window.change_presentation_type = function() {
        var type = $('#presentation_type option:selected').attr('id');
        switch (type) {
            case 'manual':
                $('.automatic_presentation').addClass('d-none');
                $('.manual_presentation').removeClass('d-none');
                $('.video_presentation').addClass('d-none');
                $('#presentation_loop').parent().removeClass('disabled');
                $('#presentation_stop_click').parent().removeClass('disabled');
                $('#presentation_stop_id_room').parent().removeClass('disabled');
                $('#presentation_view_pois').parent().removeClass('disabled');
                $('#presentation_view_measures').parent().removeClass('disabled');
                break;
            case 'automatic':
                $('.automatic_presentation').removeClass('d-none');
                $('.manual_presentation').addClass('d-none');
                $('.video_presentation').addClass('d-none');
                $('#presentation_loop').parent().removeClass('disabled');
                $('#presentation_stop_click').parent().removeClass('disabled');
                $('#presentation_stop_id_room').parent().removeClass('disabled');
                $('#presentation_view_pois').parent().removeClass('disabled');
                $('#presentation_view_measures').parent().removeClass('disabled');
                break;
            case 'video':
                $('.automatic_presentation').addClass('d-none');
                $('.manual_presentation').addClass('d-none');
                $('.video_presentation').removeClass('d-none');
                $('#presentation_loop').parent().addClass('disabled');
                $('#presentation_stop_click').parent().addClass('disabled');
                $('#presentation_stop_id_room').parent().addClass('disabled');
                $('#presentation_view_pois').parent().addClass('disabled');
                $('#presentation_view_measures').parent().addClass('disabled');
                break;
        }
    }

    window.delete_video360 = function(id_vt,file_name) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_video360.php",
                type: "POST",
                data: {
                    id_virtualtour: id_vt,
                    file_name: file_name
                },
                async: false,
                success: function (json) {
                    location.reload();
                }
            });
        }
    }

    window.delete_slideshow = function(id_vt) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_vt_slideshow.php",
                type: "POST",
                data: {
                    id_virtualtour: id_vt
                },
                async: false,
                success: function (json) {
                    location.reload();
                }
            });
        }
    }

    window.delete_video = function(id_video) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $.ajax({
                url: "ajax/delete_vt_video.php",
                type: "POST",
                data: {
                    id_video: id_video
                },
                async: false,
                success: function (json) {
                    window.video_need_save = false;
                    location.reload();
                }
            });
        }
    }

    window.get_job_queue = function (id_virtualtour,id_video,type,array_jobs) {
        $.ajax({
            url: "ajax/get_job_queue.php",
            type: "POST",
            data: {
                id_virtualtour: id_virtualtour,
                id_video: id_video,
                type: type
            },
            async: true,
            success: function (json) {
                var running_jobs = JSON.parse(json);
                for(var i=0;i<array_jobs.length;i++) {
                    var id_job = array_jobs[i];
                    if(!running_jobs.includes(id_job)) {
                        $('.background_job[data-id='+id_job+'] i.fa-circle-notch').hide();
                        $('.background_job[data-id='+id_job+'] i.fa-check').show();
                        $('.btn_progress_'+id_job).hide();
                        $('.btn_reload_'+id_job).show();
                    }
                }
            }
        });
    }

    window.abort_job_queue = function(id) {
        $.ajax({
            url: "ajax/abort_job_queue.php",
            type: "POST",
            data: {
                id: id
            },
            async: false,
            success: function () {
                window.location.reload();
            }
        });
    }

    window.get_rooms_video360 = function(id_vt) {
        $.ajax({
            url: "ajax/get_rooms_video360.php",
            type: "POST",
            data: {
                id_virtualtour: id_vt
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                var html = '';
                $.each(rsp,function (index, room) {
                    var room_id = room.id;
                    var room_name = room.name;
                    var room_image = room.panorama;
                    var room_thumb = room.thumb_image;
                    html += '<div data-name="'+room_name+'" data-panorama="'+room_image+'" data-id="'+room_id+'" class="room_video360 active noselect">';
                    html += '<img onclick="toggle_video360_active('+room_id+')" class="room_video360_handle" src="'+room_thumb+'" />';
                    html += '<p class="room_video360_name">'+room_name+'</p>';
                    html += '<input oninput="calculate_video_duration()" onchange="calculate_video_duration()" type="number" min="1" class="form-control form-control-sm room_video360_duration" value="10" />';
                    html += '</div>';
                })
                $('#list_room_video360').html(html).promise().done(function () {
                    var el = document.getElementById('list_room_video360');
                    Sortable.create(el,{
                        handle: '.room_video360_handle',
                        filter: ".no_drag",
                        onMove: function (e) { return e.related.className.indexOf('no_drag') === -1;  }
                    });
                    calculate_video_duration();
                });
                if(rsp.length>0) {
                    $('#btn_create_video360').removeClass("disabled");
                }
            }
        });
    }

    window.toggle_video360_active = function (room_id) {
        if($('.room_video360[data-id="'+room_id+'"]').hasClass('active')) {
            $('.room_video360[data-id="'+room_id+'"]').removeClass('active');
            $('.room_video360[data-id="'+room_id+'"] input').prop('disabled',true);
        } else {
            $('.room_video360[data-id="'+room_id+'"]').addClass('active');
            $('.room_video360[data-id="'+room_id+'"] input').prop('disabled',false);
        }
        calculate_video_duration();
    }

    window.select_room_video360 = function (w) {
        switch (w) {
            case 'all':
                $('.room_video360').addClass('active');
                break;
            case 'none':
                $('.room_video360').removeClass('active');
                break;
        }
        calculate_video_duration();
    }

    window.select_duration_video360 = function () {
        var duration = parseInt($('#video360_slide_duration').val());
        if(duration!='' && duration>0) {
            $('.room_video360_duration').val(duration);
        }
        calculate_video_duration();
    }

    window.sync_with_audio_video360 = function() {
        var num_slides = 0;
        $('.room_video360').each(function () {
            if($(this).hasClass('active')) {
                num_slides++;
            }
        })
        if(window.audio_duration!=0) {
            var duration = window.audio_duration / num_slides;
            $('#video360_slide_duration').val(duration.toFixed(0));
            select_duration_video360();
        }
    }

    window.sync_with_audio_slideshow = function() {
        var num_slides=0;
        jQuery.each(window.gallery_images, function(index, image) {
            if(image.visible==1) {
                num_slides++;
            }
        });
        var fade_duration = parseFloat($('#s_fade_duration').val());
        if(window.audio_duration!=0) {
            var duration = (parseFloat(window.audio_duration)+(fade_duration*(num_slides-1))) / num_slides;
            $('#s_slide_duration').val(duration.toFixed(1));
        }
    }

    window.calculate_video_duration = function() {
        var total_duration = 0;
        $('.room_video360').each(function () {
            if($(this).hasClass('active')) {
                var duration = $(this).find('input').val();
                if(duration=='') duration=0;
                duration = parseInt(duration);
                total_duration = total_duration + duration;
            }
        })
        if(total_duration==0) {
            $('#btn_generate_video360').addClass('disabled');
        } else {
            $('#btn_generate_video360').removeClass('disabled');
        }
        $('#video360_duration').html(secondsToTime(total_duration));
    }

    function secondsToTime(e){
        var h = Math.floor(e / 3600).toString().padStart(2,'0'),
            m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
            s = Math.floor(e % 60).toString().padStart(2,'0');
        return h + ':' + m + ':' + s;
    }

    function fancyTimeFormat(duration) {
        var hrs = ~~(duration / 3600);
        var mins = ~~((duration % 3600) / 60);
        var secs = ~~duration % 60;
        var ret = "";
        if (hrs > 0) {
            ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
        }
        ret += "" + mins + ":" + (secs < 10 ? "0" : "");
        ret += "" + secs;
        return ret;
    }

    window.create_video360 = function() {
        $('#div_exist_video360').hide();
        $('#div_create_video360').show();
        $('#btn_create_video360').parent().parent().hide();
    }

    window.close_video360 = function() {
        $('#div_exist_video360').show();
        $('#div_create_video360').hide();
        $('#btn_create_video360').parent().parent().show();
    }

    window.generate_video360 = function () {
        $('#btn_generate_video360').addClass('disabled');
        $('#modal_generate_video360').modal('show');
        setTimeout(function () {
            $('#btn_continue_w').removeClass('d-none');
        },10000);
        var resolution = $('#video360_resolution option:selected').attr('id');
        var audio = $('#s_audio option:selected').attr('id');
        if(audio=='0') audio='';
        var total_duration = 0;
        var array_slides = [];
        $('.room_video360').each(function () {
            if($(this).hasClass('active')) {
                var duration = $(this).find('input').val();
                if(duration=='') duration=0;
                duration = parseInt(duration);
                total_duration = total_duration + duration;
                var tmp = {};
                tmp['name'] = $(this).attr('data-name');
                tmp['panorama_image'] = $(this).attr('data-panorama');
                tmp['duration'] = duration;
                array_slides.push(tmp);
            }
        })
        switch(window.video360_type) {
            case 'local':
                var url_ajax = "../services/generate_360video.php";
                break;
            case 'cloud':
                var url_ajax = "../services/generate_360video_cloud.php";
                break;
        }
        $.ajax({
            url: url_ajax,
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                resolution: resolution,
                audio: audio,
                array_slides: array_slides,
                duration: total_duration
            },
            async: true,
            success: function (json) {
                try {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        $('#modal_generate_video360').modal('hide');
                        location.reload();
                    } else {
                        $('#btn_generate_video360').removeClass('disabled');
                        $('#modal_generate_video360').modal('hide');
                        alert(rsp.msg);
                    }
                } catch (e) {
                    $('#btn_generate_video360').removeClass('disabled');
                    $('#modal_generate_video360').modal('hide');
                    alert(window.backend_labels.generic_error_msg);
                }
            },
            error: function () {
                $('#btn_generate_video360').removeClass('disabled');
                $('#modal_generate_video360').modal('hide');
                alert(window.backend_labels.generic_error_msg);
            }
        })
    }

    window.save_video = function(id_video,generate) {
        var complete = true;
        var name = $('#name').val();
        var fade = $('#fade').val();
        var fps = $('#fps option:selected').attr('id');
        var resolution = $('#resolution option:selected').attr('id');
        var parts = resolution.split("x");
        var resolution_w = parts[0];
        var resolution_h = parts[1];
        var audio = $('#audio option:selected').attr('id');
        var watermark_pos = $('#watermark_pos option:selected').attr('id');
        var watermark_opacity = $('#watermark_opacity').val();
        if(name=='') {
            complete = false;
            $('#name').addClass("error-highlight");
        } else {
            $('#name').removeClass("error-highlight");
        }
        if(complete) {
            $('#save_btn .icon i').removeClass('far fa-circle').addClass('fas fa-circle-notch fa-spin');
            $('#save_btn').addClass("disabled");
            if(generate) {
                $('#btn_generate_video').addClass('disabled');
                $('#modal_generate_video').modal('show');
                setTimeout(function () {
                    $('#btn_continue_w').removeClass('d-none');
                },10000);
            }
            $.ajax({
                url: "ajax/save_video.php",
                type: "POST",
                data: {
                    id: id_video,
                    name: name,
                    fade: fade,
                    fps: fps,
                    resolution_w: resolution_w,
                    resolution_h: resolution_h,
                    audio: audio,
                    watermark_logo: window.watermark_logo,
                    watermark_pos: watermark_pos,
                    watermark_opacity: watermark_opacity,
                    voice: window.voice
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=="ok") {
                        window.video_need_save = false;
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-check');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-check').addClass('far fa-circle');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                        if(generate) {
                            switch(window.video_type) {
                                case 'local':
                                    var url_ajax = "../services/generate_video.php";
                                    break;
                                case 'cloud':
                                    var url_ajax = "../services/generate_video_cloud.php";
                                    break;
                            }
                            $.ajax({
                                url: url_ajax,
                                type: "POST",
                                data: {
                                    id_virtualtour: id_virtualtour,
                                    id_video: id_video
                                },
                                async: true,
                                success: function (json) {
                                    try {
                                        var rsp = JSON.parse(json);
                                        if(rsp.status=='ok') {
                                            $('#modal_generate_video').modal('hide');
                                            location.reload();
                                        } else {
                                            $('#btn_generate_video').removeClass('disabled');
                                            $('#modal_generate_video').modal('hide');
                                            alert(rsp.msg);
                                        }
                                    } catch (e) {
                                        $('#btn_generate_video').removeClass('disabled');
                                        $('#modal_generate_video').modal('hide');
                                        alert(window.backend_labels.generic_error_msg);
                                    }
                                },
                                error: function () {
                                    $('#btn_generate_video').removeClass('disabled');
                                    $('#modal_generate_video').modal('hide');
                                    alert(window.backend_labels.generic_error_msg);
                                }
                            });
                        }
                    } else {
                        $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                        $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                        setTimeout(function () {
                            $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                            $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                            $('#save_btn').removeClass("disabled");
                        },1000);
                        if(generate) {
                            $('#btn_generate_video').removeClass('disabled');
                        }
                    }
                },
                error: function() {
                    $('#save_btn .icon i').removeClass('fas fa-circle-notch fa-spin').addClass('fas fa-times');
                    $('#save_btn').removeClass('btn-success').addClass('btn-danger');
                    setTimeout(function () {
                        $('#save_btn .icon i').removeClass('fas fa-times').addClass('far fa-circle');
                        $('#save_btn').removeClass('btn-danger').addClass('btn-success');
                        $('#save_btn').removeClass("disabled");
                    },1000);
                    if(generate) {
                        $('#btn_generate_video').removeClass('disabled');
                    }
                }
            });
        }
    }

    window.continue_w_video360 = function() {
        window.open(location.href.replace('p=video360','p=dashboard'), '_blank').focus();
        $('#btn_continue_w').hide();
    }

    window.continue_w_video = function() {
        window.open(location.href.replace('p=edit_video&id='+window.id_video,'p=dashboard'), '_blank').focus();
        $('#btn_continue_w').hide();
    }

    window.continue_w_slideshow = function() {
        window.open(location.href.replace('p=gallery','p=dashboard'), '_blank').focus();
        $('#btn_continue_w').hide();
    }

    var points_selection = '', activePoint_selection, cursor_selection, dragging_selection = false, handler_selection = true, canvas_selection, ctx_selection, polygon_selection, request_selection_id = undefined;
    var mouse_selection = {x: 0, y: 0, button: 0, lx: 0, ly: 0, update: true};
    var init_canvas_mode = '';

    function init_canvas_selection(id) {
        init_canvas_mode = 'poi';
        stop_canvas_selection(id);
        points_selection = window.pois[poi_index_edit].embed_params;
        canvas_selection = document.getElementById('canvas_selection_'+id);
        ctx_selection = canvas_selection.getContext("2d");
        ctx_selection.lineWidth = window.pois[poi_index_edit].embed_content.replace('border-width:','').replace('px;','');;
        ctx_selection.strokeStyle = window.pois[poi_index_edit].background;
        if(!request_selection_id) {
            request_selection_id = requestAnimationFrame(update_canvas_selection);
        }
        ["mousedown", "mouseup", "mousemove"].forEach(name => canvas_selection.addEventListener(name, mouseEvents_selection));
        polygon_selection = poly_selection();
        if(points_selection!='') {
            polygon_selection.points = JSON.parse(points_selection);
            polygon_selection.closed = true;
        }
    }

    function init_canvas_selection_m(id) {
        init_canvas_mode = 'marker';
        stop_canvas_selection(id);
        points_selection = window.markers[marker_index_edit].embed_params;
        canvas_selection = document.getElementById('canvas_selection_'+id);
        ctx_selection = canvas_selection.getContext("2d");
        ctx_selection.lineWidth = window.markers[marker_index_edit].embed_content.replace('border-width:','').replace('px;','');;
        ctx_selection.strokeStyle = window.markers[marker_index_edit].background;
        if(!request_selection_id) {
            request_selection_id = requestAnimationFrame(update_canvas_selection);
        }
        ["mousedown", "mouseup", "mousemove"].forEach(name => canvas_selection.addEventListener(name, mouseEvents_selection));
        polygon_selection = poly_selection();
        if(points_selection!='') {
            polygon_selection.points = JSON.parse(points_selection);
            polygon_selection.closed = true;
        }
    }

    function stop_canvas_selection() {
        if (request_selection_id) {
            cancelAnimationFrame(request_selection_id);
            request_selection_id = undefined;
        }
    }

    function mouseEvents_selection(e) {
        mouse_selection.x = e.offsetX;
        mouse_selection.y = e.offsetY;
        mouse_selection.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse_selection.button;
        mouse_selection.update = true;
    }

    const point_selection = (x, y) => ({x, y});
    const poly_selection = () => ({
        points: [],
        closed: false,
        addPoint(p) {
            if(!polygon_selection.closed) {
                this.points.push(point_selection(p.x, p.y));
            }
        },
        draw() {
            switch(init_canvas_mode) {
                case 'poi':
                    ctx_selection.lineWidth = window.pois[poi_index_edit].embed_content.replace('border-width:','').replace('px;','');
                    ctx_selection.strokeStyle = window.pois[poi_index_edit].color;
                    ctx_selection.fillStyle = window.pois[poi_index_edit].background;
                    break;
                case 'marker':
                    ctx_selection.lineWidth = window.markers[marker_index_edit].embed_content.replace('border-width:','').replace('px;','');
                    ctx_selection.strokeStyle = window.markers[marker_index_edit].color;
                    ctx_selection.fillStyle = window.markers[marker_index_edit].background;
                    break;
            }
            ctx_selection.beginPath();
            for (const p of this.points) { ctx_selection.lineTo(p.x, p.y) }
            this.closed && ctx_selection.closePath();
            ctx_selection.stroke();
            this.closed && ctx_selection.fill();
            if(handler_selection) {
                var num_p = 0;
                for (const p of this.points) {
                    if(num_p==0 && !this.closed) {
                        ctx_selection.fillStyle = 'rgba(255, 255, 255, 0.7)';
                        ctx_selection.strokeStyle = 'rgba(255, 255, 255, 0.9)';
                    } else {
                        switch(init_canvas_mode) {
                            case 'poi':
                                ctx_selection.fillStyle = window.pois[poi_index_edit].background;
                                ctx_selection.strokeStyle = window.pois[poi_index_edit].color;
                                break;
                            case 'marker':
                                ctx_selection.fillStyle = window.markers[marker_index_edit].background;
                                ctx_selection.strokeStyle = window.markers[marker_index_edit].color;
                                break;
                        }
                    }
                    ctx_selection.beginPath();
                    ctx_selection.moveTo(p.x + 5, p.y);
                    ctx_selection.arc(p.x, p.y, 5, 0, Math.PI * 2);
                    ctx_selection.fill();
                    ctx_selection.stroke();
                    num_p++;
                }
                if(num_p>0) {
                    if(this.closed) {
                        $('#btn_save_polygon').removeClass('disabled');
                    }
                    $('#btn_clear_polygon').removeClass('disabled');
                }
            }
        },
        closest(pos, dist = 5) {
            var i = 0,
                index = -1;
            dist *= dist;
            for (const p of this.points) {
                var x = pos.x - p.x;
                var y = pos.y - p.y;
                var d2 = x * x + y * y;
                if (d2 < dist) {
                    dist = d2;
                    index = i;
                }
                i++;
            }
            if (index > -1) { return this.points[index] }
        }
    });

    function draw_polygon(ctx_selection,points,border,background,color) {
        ctx_selection.lineWidth = border;
        ctx_selection.strokeStyle = color;
        ctx_selection.fillStyle = background;
        var pol = new Path2D();
        for (const p of points) { pol.lineTo(p.x, p.y) }
        pol.closePath();
        ctx_selection.stroke(pol);
        ctx_selection.fill(pol);
    }

    function drawCircle_selection(pos, color = "black", size = 5) {
        ctx_selection.strokeStyle = color;
        ctx_selection.beginPath();
        ctx_selection.arc(pos.x, pos.y, size, 0, Math.PI * 2);
        ctx_selection.stroke();
    }

    function update_canvas_selection() {
        request_selection_id = undefined;
        if (mouse_selection.update) {
            cursor_selection = "crosshair";
            ctx_selection.clearRect(0, 0, canvas_selection.width, canvas_selection.height);
            if (!dragging_selection) { activePoint_selection = polygon_selection.closest(mouse_selection) }
            if (activePoint_selection === undefined && mouse_selection.button) {
                polygon_selection.addPoint(mouse_selection);
                mouse_selection.button = false;
            } else if (activePoint_selection) {
                if (mouse_selection.button) {
                    if (dragging_selection) {
                        activePoint_selection.x += mouse_selection.x - mouse_selection.lx;
                        activePoint_selection.y += mouse_selection.y - mouse_selection.ly;
                    } else {
                        if (!polygon_selection.closed && polygon_selection.points.length > 2 && activePoint_selection === polygon_selection.points[0]) {
                            polygon_selection.closed = true;
                        }
                        dragging_selection = true
                    }
                } else { dragging_selection = false }
            }
            polygon_selection.draw();
            if (activePoint_selection && handler_selection) {
                drawCircle_selection(activePoint_selection);
                cursor_selection = "move";
            }
            mouse_selection.lx = mouse_selection.x;
            mouse_selection.ly = mouse_selection.y;
            canvas_selection.style.cursor = cursor_selection;
            mouse_selection.update = false;
        }
        if(!request_selection_id) {
            request_selection_id = requestAnimationFrame(update_canvas_selection);
        }
    }

    window.draw_polygon_selection = function () {
        window.draw_polygon_mode = 1;
        var id = window.poi_id_edit;
        $('#btn_clear_polygon').addClass('disabled');
        $('#btn_save_polygon').addClass('disabled');
        $('#poi_embded_move_'+id).css({'opacity':0,'pointer-events':'none'});
        $('#poi_embded_helper_'+id+'_1').css({'opacity':0,'pointer-events':'none'});
        $('#poi_embded_helper_'+id+'_2').css({'opacity':0,'pointer-events':'none'});
        $('#poi_embded_helper_'+id+'_3').css({'opacity':0,'pointer-events':'none'});
        $('#poi_embded_helper_'+id+'_4').css({'opacity':0,'pointer-events':'none'});
        $('.poi_embed_'+id+' .poi_embed_selection').css('background','none');
        $('.poi_embed_'+id+' .poi_embed_selection').css('border-color','rgba(255,255,255,0.4)');
        init_canvas_selection(id);
        $('#confirm_move').hide();
        $('#confirm_polygon').show();
    }

    window.draw_polygon_selection_m = function () {
        window.draw_polygon_mode = 1;
        var id = window.marker_id_edit;
        $('#btn_clear_polygon').addClass('disabled');
        $('#btn_save_polygon').addClass('disabled');
        $('#marker_embded_move_'+id).css({'opacity':0,'pointer-events':'none'});
        $('#marker_embded_helper_'+id+'_1').css({'opacity':0,'pointer-events':'none'});
        $('#marker_embded_helper_'+id+'_2').css({'opacity':0,'pointer-events':'none'});
        $('#marker_embded_helper_'+id+'_3').css({'opacity':0,'pointer-events':'none'});
        $('#marker_embded_helper_'+id+'_4').css({'opacity':0,'pointer-events':'none'});
        $('.marker_embed_'+id+' .marker_embed_selection').css('background','none');
        $('.marker_embed_'+id+' .marker_embed_selection').css('border-color','rgba(255,255,255,0.4)');
        init_canvas_selection_m(id);
        $('#confirm_move').hide();
        $('#confirm_polygon').show();
    }

    window.close_polygon_selection = function () {
        window.draw_polygon_mode = 0;
        var id = window.poi_id_edit;
        stop_canvas_selection();
        render_poi(window.poi_id_edit,window.poi_index_edit);
        $('#poi_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
        $('#poi_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
        $('#poi_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
        $('#poi_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
        $('#poi_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_move').show();
        $('#confirm_polygon').hide();
    }

    window.close_polygon_selection_m = function () {
        window.draw_polygon_mode = 0;
        var id = window.marker_id_edit;
        stop_canvas_selection();
        render_marker(window.marker_id_edit,window.marker_index_edit);
        $('#marker_embded_move_'+id).css({'opacity':1,'pointer-events':'initial'});
        $('#marker_embded_helper_'+id+'_1').css({'opacity':1,'pointer-events':'initial'});
        $('#marker_embded_helper_'+id+'_2').css({'opacity':1,'pointer-events':'initial'});
        $('#marker_embded_helper_'+id+'_3').css({'opacity':1,'pointer-events':'initial'});
        $('#marker_embded_helper_'+id+'_4').css({'opacity':1,'pointer-events':'initial'});
        $('#confirm_move').show();
        $('#confirm_polygon').hide();
    }

    window.clear_polygon_selection = function() {
        points_selection = '';
        window.pois[poi_index_edit].embed_params = '';
        var id = window.poi_id_edit;
        $('#btn_clear_polygon').addClass('disabled');
        $('#btn_save_polygon').addClass('disabled');
        stop_canvas_selection();
        canvas_selection = document.getElementById('canvas_selection_'+id);
        ctx_selection = canvas_selection.getContext("2d");
        ctx_selection.clearRect(0, 0, canvas_selection.width, canvas_selection.height);
        init_canvas_selection(id);
        $('.poi_embed_'+id+' .poi_embed_selection canvas').trigger('click');
    }

    window.clear_polygon_selection_m = function() {
        points_selection = '';
        window.markers[marker_index_edit].embed_params = '';
        var id = window.marker_id_edit;
        $('#btn_clear_polygon').addClass('disabled');
        $('#btn_save_polygon').addClass('disabled');
        stop_canvas_selection();
        canvas_selection = document.getElementById('canvas_selection_'+id);
        ctx_selection = canvas_selection.getContext("2d");
        ctx_selection.clearRect(0, 0, canvas_selection.width, canvas_selection.height);
        init_canvas_selection_m(id);
        $('.marker_embed_'+id+' .marker_embed_selection canvas').trigger('click');
    }

    window.save_polygon_selection = function () {
        var points = JSON.stringify(polygon_selection.points);
        window.pois[poi_index_edit].embed_params = points;
        close_polygon_selection();
    }

    window.save_polygon_selection_m = function () {
        var points = JSON.stringify(polygon_selection.points);
        window.markers[marker_index_edit].embed_params = points;
        close_polygon_selection_m();
    }

    window.toggle_fullscreen_div = function(id) {
        if (
            document.fullscreenElement ||
            document.webkitFullscreenElement ||
            document.mozFullScreenElement ||
            document.msFullscreenElement
        ) {
            window.is_fullscreen = false;
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        } else {
            window.is_fullscreen = true;
            var element = $('#'+id).get(0);
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if (element.webkitRequestFullscreen) {
                element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            } else if (element.msRequestFullscreen) {
                element.msRequestFullscreen();
            }
        }
    }

    window.set_friendly_url = function() {
        var friendly_url = $('#friendly_url').val();
        $('#btn_friendly_url').addClass('disabled');
        $.ajax({
            url: "ajax/set_friendly_url.php",
            type: "POST",
            data: {
                type: 'virtual_tour',
                id: window.id_virtualtour,
                friendly_url: friendly_url
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == "ok") {
                    $('#friendly_url').removeClass('error-highlight');
                    location.reload();
                } else {
                    $('#btn_friendly_url').removeClass('disabled');
                    $('#friendly_url').addClass('error-highlight');
                }
            }
        });
    }

    window.change_friendly_url = function(type,id_elem,id) {
        var friendly_url = $('#'+id_elem).val();
        if(friendly_url=='') {
            $('#'+id_elem).parent().find('.input-group-append').addClass('disabled');
            $('#link_f_vr').parent().addClass('disabled');
        } else {
            $('#'+id_elem).parent().find('.input-group-append').removeClass('disabled');
            $('#link_f_vr').parent().removeClass('disabled');
        }
        var url = window.link_f+friendly_url;
        var url_vr = window.link_f_vr+friendly_url;
        $.ajax({
            url: 'ajax/set_friendly_url.php',
            type: "POST",
            data: {
                type: type,
                id: id,
                friendly_url: friendly_url
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    $('#open_link_f').attr('href',url);
                    $('#copy_link_f').attr('data-clipboard-text',url);
                    $('#qrcode_link_f').attr('onclick','open_qr_code_modal(\''+url+'\')');
                    $('#link_open_vr').attr('href',url_vr);
                    $('#link_copy_vr').attr('data-clipboard-text',url_vr);
                    $('#link_qr_vr').attr('onclick','open_qr_code_modal(\''+url_vr+'\')');
                    $('#link_f_vr').val(url_vr);
                    $('#link_f').attr('data-default-value',url);
                    $('.input_lang[data-target-id="link_f"]').each(function() {
                        var lang = $(this).attr('data-lang');
                        if($('#link_f').val()=='') {
                            $(this).val('');
                            var link_f = '';
                        } else {
                            $(this).val($('#link_f').val()+"@"+lang);
                            var link_f = window.link_f+$('#link_f').val()+"@"+lang;
                        }
                        $('.input_lang[data-target-id="link_f"][data-lang="'+lang+'"]').attr('data-default-value',link_f);
                        $('.input_lang[data-target-id="open_link_f"][data-lang="'+lang+'"]').attr('href',link_f);
                        $('.input_lang[data-target-id="copy_link_f"][data-lang="'+lang+'"]').attr('data-clipboard-text',link_f);
                        $('.input_lang[data-target-id="qrcode_link_f"][data-lang="'+lang+'"]').attr('onclick','open_qr_code_modal(\''+link_f+'\')');
                    });
                    $('#'+id_elem).removeClass('error-highlight');
                    $('#'+id_elem).css('color','unset');
                } else {
                    $('#'+id_elem).addClass('error-highlight');
                    $('#'+id_elem).css('color','red');
                }
            }
        })
    }

    window.delete_image_meta = function (type,id) {
        window.image_meta = '';
        $('#div_delete_image_meta').hide();
        $('#div_upload_image_meta').show();
        if(window.image_meta_default=='') {
            $('.facebook-preview__image').addClass('d-none');
            $('.facebook-preview__image').attr('src','');
        } else {
            $('.facebook-preview__image').removeClass('d-none');
            switch(type) {
                case 'landing':
                case 'virtual_tour':
                    if(window.s3_enabled==1) {
                        $('.facebook-preview__image').attr('src',window.s3_url+'viewer/content/'+window.image_meta_default);
                    } else {
                        $('.facebook-preview__image').attr('src','../viewer/content/'+window.image_meta_default);
                    }
                    break;
                case 'settings':
                    $('.facebook-preview__image').attr('src','assets/'+window.image_meta_default);
                    break;
                default:
                    $('.facebook-preview__image').attr('src','../viewer/content/'+window.image_meta_default);
                    break;
            }
        }
        if(type!='settings') {
            save_metadata(type,id);
        }
    }

    window.change_meta_title = function() {
        var meta_title = '';
        if($('#meta_title').is(':visible')) {
            meta_title = $('#meta_title').val();
        } else {
            $('.input_lang[data-target-id="meta_title"]').each(function() {
                if($(this).is(':visible')) {
                    meta_title = $(this).val();
                }
            });
        }
        meta_title = DOMPurify.sanitize(meta_title);
        if(meta_title=='') {
            if(window.title_meta_default=='') {
                $('.facebook-preview__title').html('');
            } else {
                $('.facebook-preview__title').html(title_meta_default);
            }
        } else {
            $('.facebook-preview__title').html(meta_title);
        }
    }

    window.change_meta_description = function() {
        var meta_description = '';
        if($('#meta_description').is(':visible')) {
            meta_description = $('#meta_description').val();
        } else {
            $('.input_lang[data-target-id="meta_description"]').each(function() {
                if($(this).is(':visible')) {
                    meta_description = $(this).val();
                }
            });
        }
        meta_description = DOMPurify.sanitize(meta_description);
        if(meta_description=='') {
            if(window.description_meta_default=='') {
                $('.facebook-preview__description').html('');
            } else {
                $('.facebook-preview__description').html(description_meta_default);
            }
        } else {
            $('.facebook-preview__description').html(meta_description);
        }
    }

    window.save_metadata = function(type,id) {
        var meta_title = $('#meta_title').val();
        var meta_description = $('#meta_description').val();
        var array_lang = {};
        array_lang['meta_title'] = {};
        $('.input_lang[data-target-id="meta_title"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['meta_title'][lang]=value;
        });
        array_lang['meta_description'] = {};
        $('.input_lang[data-target-id="meta_description"]').each(function() {
            var lang = $(this).attr('data-lang');
            var value = $(this).val();
            array_lang['meta_description'][lang]=value;
        });
        var array_lang_json = JSON.stringify(array_lang);
        $.ajax({
            url: 'ajax/save_metadata.php',
            type: "POST",
            data: {
                type: type,
                id: id,
                meta_title: meta_title,
                meta_description: meta_description,
                meta_image: window.image_meta,
                array_lang: array_lang_json
            },
            async: true,
            success: function (json) {}
        })
    }

    window.switch_custom_mode = function(mode) {
        switch(mode) {
            case 'backend':
                $('#btn_custom_backend').removeClass('btn-outline-primary').addClass('btn-primary');
                $('#btn_custom_viewer').addClass('btn-outline-primary').removeClass('btn-primary');
                $('#custom_viewer_div').addClass('d-none');
                $('#custom_backend_div').removeClass('d-none');
                break;
            case 'viewer':
                $('#btn_custom_viewer').removeClass('btn-outline-primary').addClass('btn-primary');
                $('#btn_custom_backend').addClass('btn-outline-primary').removeClass('btn-primary');
                $('#custom_viewer_div').removeClass('d-none');
                $('#custom_backend_div').addClass('d-none');
                break;
        }
    }

    window.refresh_session = function() {
        $.ajax({
            url: 'ajax/refresh_session.php',
            type: "POST",
            data: {
                url: window.base_url,
                v: window.v
            },
            async: true,
            success: function (json) {}
        });
        setInterval(function() {
            $.ajax({
                url: 'ajax/refresh_session.php',
                type: "POST",
                data: {
                    url: window.base_url,
                    v: window.v
                },
                async: true,
                success: function (json) {}
            });
        },60000);
    }

    window.change_delete_user_assign = function() {
        var id = $('#user_assign option:selected').attr('id');
        if(id==0) {
            $('#warning_delete_msg').show();
        } else {
            $('#warning_delete_msg').hide();
        }
    }

    window.generate_favicons = function(url) {
        if(url=='manual') {
            var url_ajax = '../services/generate_favicons.php?what=all';
            $('#modal_pwa').modal('show');
        } else {
            var url_ajax = url;
        }
        $.ajax({
            url: url_ajax,
            type: "POST",
            async: true,
            success: function() {
                if(url=='manual') {
                    $('#modal_pwa').modal('hide');
                }
            },
            error: function() {
                if(url=='manual') {
                    $('#modal_pwa').modal('hide');
                }
            }
        })
    }

    window.click_tab_resize = function() {
        setTimeout(function() {
            $(window).trigger('resize');
        },50);
    }

    window.assign_all_tour_to_editor = function() {
        var retVal = confirm(window.backend_labels.assign_sure_msg);
        if( retVal == true ) {
            $('#btn_assign_all').addClass('disabled');
            $('#btn_unassign_all').addClass('disabled');
            $.ajax({
                url: "ajax/assign_all_tour_to_editor.php",
                type: "POST",
                data: {
                    id_svt: window.id_user_edit,
                    assign: 1
                },
                async: true,
                success: function (json) {
                    $('#assign_vt_table').DataTable().ajax.reload();
                }
            });
        } else {
            return false;
        }
    }

    window.unassign_all_tour_to_editor = function() {
        var retVal = confirm(window.backend_labels.unassign_sure_msg);
        if( retVal == true ) {
            $('#btn_assign_all').addClass('disabled');
            $('#btn_unassign_all').addClass('disabled');
            $.ajax({
                url: "ajax/assign_all_tour_to_editor.php",
                type: "POST",
                data: {
                    id_svt: window.id_user_edit,
                    assign: 0
                },
                async: true,
                success: function (json) {
                    $('#assign_vt_table').DataTable().ajax.reload();
                }
            });
        } else {
            return false;
        }
    }

    window.assign_all_editor_to_tour = function() {
        var retVal = confirm(window.backend_labels.assign_sure_msg);
        if( retVal == true ) {
            $('#btn_assign_all').addClass('disabled');
            $('#btn_unassign_all').addClass('disabled');
            $.ajax({
                url: "ajax/assign_all_editor_to_tour.php",
                type: "POST",
                data: {
                    id_svt: window.id_virtualtour,
                    assign: 1
                },
                async: true,
                success: function (json) {
                    $('#assign_editors_table').DataTable().ajax.reload();
                }
            });
        } else {
            return false;
        }
    }

    window.unassign_all_editor_to_tour = function() {
        var retVal = confirm(window.backend_labels.unassign_sure_msg);
        if( retVal == true ) {
            $('#btn_assign_all').addClass('disabled');
            $('#btn_unassign_all').addClass('disabled');
            $.ajax({
                url: "ajax/assign_all_editor_to_tour.php",
                type: "POST",
                data: {
                    id_svt: window.id_virtualtour,
                    assign: 0
                },
                async: true,
                success: function (json) {
                    $('#assign_editors_table').DataTable().ajax.reload();
                }
            });
        } else {
            return false;
        }
    }

    window.switch_dark_mode = function() {
        if(window.localStorage.getItem("dark_mode")=='1') {
            var dark_mode = 1;
        } else {
            var dark_mode = 0;
        }
        if(dark_mode==0) {
            window.localStorage.setItem("dark_mode",'1');
            $('.btn_mode_switcher').attr('id','btn_dark_mode');
            $('.btn_mode_switcher').removeClass('fa-sun').addClass('fa-moon');
            document.body.classList.add("dark_mode");
            document.documentElement.classList.add('cc--darkmode');
        } else {
            window.localStorage.setItem("dark_mode",'0');
            $('.btn_mode_switcher').attr('id','btn_light_mode');
            $('.btn_mode_switcher').removeClass('fa-moon').addClass('fa-sun');
            document.body.classList.remove("dark_mode");
            document.documentElement.classList.remove('cc--darkmode');
        }
    }

    window.change_aws_s3_type = function() {
        var type = $('#aws_s3_type option:selected').attr('id');
        switch(type) {
            case 'aws':
                $('#aws_instructions').removeClass('d-none');
                $('#r2_instructions').addClass('d-none');
                $('#digitalocean_instructions').addClass('d-none');
                $('#wasabi_instructions').addClass('d-none');
                $('#storj_instructions').addClass('d-none');
                $('#backblaze_instructions').addClass('d-none');
                $('#aws_s3_region').removeClass('d-none');
                $('#aws_s3_region_wasabi').addClass('d-none');
                $('#aws_s3_region_digitalocean').addClass('d-none');
                $('#aws_s3_region_storj').addClass('d-none');
                $('#aws_s3_region_r2').addClass('d-none');
                $('#aws_s3_region_backblaze').addClass('d-none');
                $('#aws_s3_accountid').prop('disabled',true);
                break;
            case 'wasabi':
                $('#aws_instructions').addClass('d-none');
                $('#r2_instructions').addClass('d-none');
                $('#digitalocean_instructions').addClass('d-none');
                $('#wasabi_instructions').removeClass('d-none');
                $('#storj_instructions').addClass('d-none');
                $('#backblaze_instructions').addClass('d-none');
                $('#aws_s3_region_wasabi').removeClass('d-none');
                $('#aws_s3_region').addClass('d-none');
                $('#aws_s3_region_digitalocean').addClass('d-none');
                $('#aws_s3_region_storj').addClass('d-none');
                $('#aws_s3_region_r2').addClass('d-none');
                $('#aws_s3_region_backblaze').addClass('d-none');
                $('#aws_s3_accountid').prop('disabled',true);
                break;
            case 'r2':
                $('#aws_instructions').addClass('d-none');
                $('#r2_instructions').removeClass('d-none');
                $('#digitalocean_instructions').addClass('d-none');
                $('#wasabi_instructions').addClass('d-none');
                $('#backblaze_instructions').addClass('d-none');
                $('#storj_instructions').addClass('d-none');
                $('#aws_s3_region').addClass('d-none');
                $('#aws_s3_region_wasabi').addClass('d-none');
                $('#aws_s3_region_digitalocean').addClass('d-none');
                $('#aws_s3_region_storj').addClass('d-none');
                $('#aws_s3_region_r2').removeClass('d-none');
                $('#aws_s3_region_backblaze').addClass('d-none');
                $('#aws_s3_accountid').prop('disabled',false);
                break;
            case 'digitalocean':
                $('#aws_instructions').addClass('d-none');
                $('#r2_instructions').addClass('d-none');
                $('#digitalocean_instructions').removeClass('d-none');
                $('#wasabi_instructions').addClass('d-none');
                $('#backblaze_instructions').addClass('d-none');
                $('#storj_instructions').addClass('d-none');
                $('#aws_s3_region').addClass('d-none');
                $('#aws_s3_region_wasabi').addClass('d-none');
                $('#aws_s3_region_digitalocean').removeClass('d-none');
                $('#aws_s3_region_storj').addClass('d-none');
                $('#aws_s3_region_r2').addClass('d-none');
                $('#aws_s3_region_backblaze').addClass('d-none');
                $('#aws_s3_accountid').prop('disabled',true);
                break;
            case 'storj':
                $('#aws_instructions').addClass('d-none');
                $('#r2_instructions').addClass('d-none');
                $('#digitalocean_instructions').addClass('d-none');
                $('#wasabi_instructions').addClass('d-none');
                $('#backblaze_instructions').addClass('d-none');
                $('#storj_instructions').removeClass('d-none');
                $('#aws_s3_region').addClass('d-none');
                $('#aws_s3_region_wasabi').addClass('d-none');
                $('#aws_s3_region_digitalocean').addClass('d-none');
                $('#aws_s3_region_storj').removeClass('d-none');
                $('#aws_s3_region_r2').addClass('d-none');
                $('#aws_s3_region_backblaze').addClass('d-none');
                $('#aws_s3_accountid').prop('disabled',true);
                break;
            case 'backblaze':
                $('#aws_instructions').addClass('d-none');
                $('#r2_instructions').addClass('d-none');
                $('#digitalocean_instructions').addClass('d-none');
                $('#wasabi_instructions').addClass('d-none');
                $('#storj_instructions').addClass('d-none');
                $('#backblaze_instructions').removeClass('d-none');
                $('#aws_s3_region').addClass('d-none');
                $('#aws_s3_region_wasabi').addClass('d-none');
                $('#aws_s3_region_digitalocean').addClass('d-none');
                $('#aws_s3_region_storj').addClass('d-none');
                $('#aws_s3_region_backblaze').removeClass('d-none');
                $('#aws_s3_region_r2').addClass('d-none');
                $('#aws_s3_accountid').prop('disabled',true);
                break;
        }
        $('#aws_s3_enabled').prop('disabled',true);
        $('#aws_s3_enabled').prop('checked',false);
    }

    window.change_aws_s3_region = function() {
        $('#aws_s3_enabled').prop('disabled',true);
        $('#aws_s3_enabled').prop('checked',false);
    }

    window.change_globe_type = function() {
        var type = $('#type option:selected').attr('id');
        switch (type) {
            case 'google':
                $('#default_view').addClass('disabled');
                break;
            default:
                $('#default_view').removeClass('disabled');
                break;
        }
    }

    window.change_shop_type = function() {
        var type = $('#shop_type option:selected').attr('id');
        switch (type) {
            case 'woocommerce':
                $('.snipcart_setting').addClass('d-none');
                $('.woocommerce_setting').removeClass('d-none');
                break;
            default:
                $('.snipcart_setting').removeClass('d-none');
                $('.woocommerce_setting').addClass('d-none');
                break;
        }
    }

    window.change_font_provider = function() {
        var font_provider = $('#font_provider option:selected').attr('id');
        switch(font_provider) {
            case 'systems':
                $('.font-picker').addClass('d-none');
                $('#font_backend_system').removeClass('d-none');
                apply_system_font();
                break;
            case 'google':
                $('.font-picker').removeClass('d-none');
                $('#font_backend_system').addClass('d-none');
                var font_family = $('#font_backend').val();
                $('#font_backend_link').attr('href','https://fonts.googleapis.com/css?family='+font_family);
                $('#style_css').html("* { font-family:'"+font_family+"',sans-serif; }");
                break;
            case 'collabs':
                $('.font-picker').removeClass('d-none');
                $('#font_backend_system').addClass('d-none');
                var font_family = $('#font_backend').val();
                $('#font_backend_link').attr('href','https://api.fonts.coollabs.io/css2?family='+font_family+'&display=swap');
                $('#style_css').html("* { font-family:'"+font_family+"',sans-serif; }");
                break;
        }
    }

    window.apply_system_font = function() {
        var font_family = $('#font_backend_system option:selected').attr('id');
        $('#style_css').html("*:not(i):not(.fas):not(.far):not(.fab):not(.leader-line):not(.leader-line *):not(.vjs-icon-placeholder):not(.vjs-play-progress) { font-family:'"+font_family+"',sans-serif; }");
    }

    window.apply_system_font_editor_ui = function() {
        var font_family = $('#font_viewer_system option:selected').attr('id');
        $('#ui_container *:not(i):not(.controls_btn):not(.menu_controls):not(.list_alt_menu):not(.song_control):not(.title):not(.dropdown)').css('font-family',"'"+font_family+"', sans-serif");
    }

    var sound_hb = new Audio();
    window.play_sound = function(id_select) {
        try {
            sound_hb.pause();
        } catch (e) {}
        var sound = $('#'+id_select+' option:selected').attr('id');
        if(sound!='') {
            sound_hb.src = ((window.s3_enabled) ? window.s3_url : '../viewer/') + 'content/'+sound;
            try {
                sound_hb.play();
            } catch (e) {}
        }
    }

    window.change_auto_presentation_speed = function() {
        var value = $('#auto_presentation_speed').val();
        $('#auto_presentation_speed_value').html(value);
    }

    window.open_list_hs = function() {
        $('#slider_hs_list').addClass('open');
    }

    window.close_list_hs = function() {
        $('#slider_hs_list').removeClass('open');
    }

    window.changeTimezone = function() {
        var selectedTimezone = $('#timezone').val();
        $.ajax({
            type: 'POST',
            url: 'ajax/preview_timezone.php',
            data: { timezone: selectedTimezone },
            success: function(response) {
                $('#preview_timezone').html(response);
            }
        });
    }

    window.change_song_bg_volume = function() {
        var volume = $('#song_bg_volume').val();
        $('#song_bg_volume_value').html(volume*100+'%');
    }

    window.change_song_volume = function() {
        var volume = $('#song_volume').val();
        $('#song_volume_value').html(volume*100+'%');
    }

    window.change_poi_song_bg_volume = function() {
        var volume = $('#poi_song_bg_volume').val();
        $('#poi_song_bg_volume_value').html(volume*100+'%');
    }

    window.change_poi_song_player = function(render) {
        var player = $('#poi_song_player option:selected').attr('id');
        switch(player) {
            case 'default':
                $('#poi_style option[id="1"]').prop('disabled',false);
                $('#poi_style option[id="4"]').prop('disabled',false);
                $("#poi_style option").prop("selected", false);
                $("#poi_style option[id='"+window.pois[window.poi_index_edit].style+"']").prop("selected", true);
                $('#poi_icon').parent().parent().removeClass('disabled_d');
                break;
            case 'minimal':
                $('#poi_style option[id="1"]').prop('disabled',true);
                $('#poi_style option[id="4"]').prop('disabled',true);
                var style = parseInt($('#poi_style option:selected').attr('id'));
                if(style==1 || style==4) {
                    $("#poi_style option").prop("selected", false);
                    $("#poi_style option[id='0']").prop("selected", true);
                }
                $('#poi_icon').parent().parent().addClass('disabled_d');
                break;
        }
        if(render) {
            render_poi(window.poi_id_edit,window.poi_index_edit);
        }
    }

    window.change_default_perspective_m = function() {
        var rotateX = $('#markers_default_rotateX').val();
        var rotateZ = $('#markers_default_rotateZ').val();
        $('#markers_default_perspective_values').html('('+rotateX+','+rotateZ+')');
        adjust_marker_preview();
    }

    window.change_default_perspective_p = function() {
        var rotateX = $('#pois_default_rotateX').val();
        var rotateZ = $('#pois_default_rotateZ').val();
        $('#pois_default_perspective_values').html('('+rotateX+','+rotateZ+')');
        adjust_poi_preview();
    }

    window.change_default_size_m = function() {
        var size = $('#markers_default_size_scale').val();
        $('#markers_default_size_values').html('('+size+')');
        adjust_marker_preview();
    }

    window.change_default_size_p = function() {
        var size = $('#pois_default_size_scale').val();
        $('#pois_default_size_values').html('('+size+')');
        adjust_poi_preview();
    }

    function adjust_marker_preview() {
        var rotateX = $('#markers_default_rotateX').val();
        var rotateZ = $('#markers_default_rotateZ').val();
        var size = $('#markers_default_size_scale').val();
        var transform = ' scale(' + size  + ')';
        transform += ' perspective(500px) rotateX(' + rotateX + 'deg) rotateZ(' + rotateZ + 'deg)';
        $('#marker_preview_div .pnlm-hotspot-base').css('transform',transform);
    }

    function adjust_poi_preview() {
        var rotateX = $('#pois_default_rotateX').val();
        var rotateZ = $('#pois_default_rotateZ').val();
        var size = $('#pois_default_size_scale').val();
        var transform = ' scale(' + size  + ')';
        transform += ' perspective(500px) rotateX(' + rotateX + 'deg) rotateZ(' + rotateZ + 'deg)';
        $('#poi_preview_div .pnlm-hotspot-base').css('transform',transform);
    }

    window.delete_import_export_file = function(type,file_name) {
        var retVal = confirm(window.backend_labels.delete_sure_msg);
        if( retVal == true ) {
            $('#export_table tr td .btn').addClass('disabled');
            $('#import_table tr td .btn').addClass('disabled');
            $.ajax({
                url: "ajax/delete_import_export_file.php",
                type: "POST",
                data: {
                    type: type,
                    file_name: file_name
                },
                async: false,
                success: function () {
                    $('#export_table tr td .btn').removeClass('disabled');
                    $('#import_table tr td .btn').removeClass('disabled');
                    switch(type) {
                        case 'export':
                            get_export_files();
                            break;
                        case 'import':
                            get_import_files();
                            break;
                    }
                }, error: function() {
                    $('#export_table tr td .btn').removeClass('disabled');
                    $('#import_table tr td .btn').removeClass('disabled');
                }
            });
        }
    }

    window.import_tour_check = function(file_name) {
        var retVal = confirm(window.backend_labels.import_sure_msg);
        if( retVal == true ) {
            import_tour(file_name,true);
        }
    }

    window.generate_api_key = function() {
        var api_key = $('#api_key').val();
        if(api_key=='') {
            var retVal = true;
        } else {
            var retVal = confirm(window.backend_labels.api_key_replace_msg);
        }
        if( retVal == true ) {
            $('#btn_generate_api_key').addClass('disabled');
            $.ajax({
                url: "ajax/generate_api_key.php",
                type: "POST",
                data: {},
                async: false,
                success: function (rsp) {
                    $('#btn_generate_api_key').removeClass('disabled');
                    $('#btn_remove_api_key').removeClass('disabled');
                    $('#api_key').val(rsp);
                }, error: function() {
                    $('#btn_generate_api_key').removeClass('disabled');
                }
            });
        }
    }

    window.remove_api_key = function() {
        $('#api_key').val('');
        $('#btn_remove_api_key').addClass('disabled');
    }

    window.change_id_vt_sample = function() {
        var id_vt_sample = $('#id_vt_sample option:selected').attr('id');
        if(id_vt_sample==-1) {
            $('#btn_create_sample_tour').addClass('disabled');
        } else {
            $('#btn_create_sample_tour').removeClass('disabled');
        }
    }

    window.preview_avatar_video = function(exists_videos,file_uploaded) {
        if($('#div_avatar_video_extensions').css('display')=='flex') {
            $('#mov_uploaded').css('color','orange');
            $('#webm_uploaded').css('color','orange');
        } else {
            $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                if($(this).css('display')=='flex') {
                    var lang = $(this).attr('data-lang');
                    $('#mov_uploaded_'+lang).css('color','orange');
                    $('#webm_uploaded_'+lang).css('color','orange');
                }
            });
        }
        if(exists_videos!='') {
            var array_videos = exists_videos.split(",");
        } else {
            var array_videos = [];
        }
        var mov_video = '', webm_video = '';
        jQuery.each(array_videos, function(index_s, video_s) {
            if(video_s.split('.').pop().toLowerCase()=='mov') {
                mov_video = video_s;
                if($('#div_avatar_video_extensions').css('display')=='flex') {
                    $('#mov_uploaded').css('color','green');
                } else {
                    $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                        if($(this).css('display')=='flex') {
                            var lang = $(this).attr('data-lang');
                            $('#mov_uploaded_'+lang).css('color','green');
                        }
                    });
                }
            }
            if(video_s.split('.').pop().toLowerCase()=='webm') {
                webm_video = video_s;
                if($('#div_avatar_video_extensions').css('display')=='flex') {
                    $('#webm_uploaded').css('color','green');
                } else {
                    $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                        if($(this).css('display')=='flex') {
                            var lang = $(this).attr('data-lang');
                            $('#webm_uploaded_'+lang).css('color','green');
                        }
                    });
                }
            }
        });
        if(file_uploaded.split('.').pop().toLowerCase()=='mov') {
            mov_video = file_uploaded;
            if($('#div_avatar_video_extensions').css('display')=='flex') {
                $('#mov_uploaded').css('color','green');
            } else {
                $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                    if($(this).css('display')=='flex') {
                        var lang = $(this).attr('data-lang');
                        $('#mov_uploaded_'+lang).css('color','green');
                    }
                });
            }
        }
        if(file_uploaded.split('.').pop().toLowerCase()=='webm') {
            webm_video = file_uploaded;
            if($('#div_avatar_video_extensions').css('display')=='flex') {
                $('#webm_uploaded').css('color','green');
            } else {
                $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                    if($(this).css('display')=='flex') {
                        var lang = $(this).attr('data-lang');
                        $('#webm_uploaded_'+lang).css('color','green');
                    }
                });
            }
        }
        if(webm_video!='' && mov_video!='') {
            var avatar_video_content = webm_video+','+mov_video;
            if(supportsHEVCAlpha()) {
                if(window.s3_enabled==1) {
                    var src = window.s3_url+'viewer/'+mov_video;
                } else {
                    var src = '../viewer/'+mov_video;
                }
            } else {
                if(window.s3_enabled==1) {
                    var src = window.s3_url+'viewer/'+webm_video;
                } else {
                    var src = '../viewer/'+webm_video;
                }
            }
            if($('#div_avatar_video_extensions').css('display')=='flex') {
                $('#div_avatar_video_preview video').attr('src',src);
                $('#div_delete_avatar_video').show();
                $('#div_avatar_video_preview').show();
            } else {
                $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                    if($(this).css('display')=='flex') {
                        var lang = $(this).attr('data-lang');
                        $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"] video').attr('src',src);
                        $('.input_lang[data-target-id="div_delete_avatar_video"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"]').show();
                    }
                });
            }
        } else if(webm_video!='' && mov_video=='') {
            var avatar_video_content = webm_video;
            if(window.s3_enabled==1) {
                var src = window.s3_url+'viewer/'+webm_video;
            } else {
                var src = '../viewer/'+webm_video;
            }
            if($('#div_avatar_video_extensions').css('display')=='flex') {
                $('#div_avatar_video_preview video').attr('src',src);
                $('#div_delete_avatar_video').show();
                $('#div_avatar_video_preview').show();
            } else {
                $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                    if($(this).css('display')=='flex') {
                        var lang = $(this).attr('data-lang');
                        $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"] video').attr('src',src);
                        $('.input_lang[data-target-id="div_delete_avatar_video"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"]').show();
                    }
                });
            }
        } else if(webm_video=='' && mov_video!='') {
            var avatar_video_content = mov_video;
            if(window.s3_enabled==1) {
                var src = window.s3_url+'viewer/'+mov_video;
            } else {
                var src = '../viewer/'+mov_video;
            }
            if($('#div_avatar_video_extensions').css('display')=='flex') {
                $('#div_avatar_video_preview video').attr('src',src);
                $('#div_delete_avatar_video').show();
                $('#div_avatar_video_preview').show();
            } else {
                $('.input_lang[data-target-id="div_avatar_video_extensions"]').each(function() {
                    if($(this).css('display')=='flex') {
                        var lang = $(this).attr('data-lang');
                        $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"] video').attr('src',src);
                        $('.input_lang[data-target-id="div_delete_avatar_video"][data-lang="'+lang+'"]').show();
                        $('.input_lang[data-target-id="div_avatar_video_preview"][data-lang="'+lang+'"]').show();
                    }
                });
            }
        }
        return avatar_video_content;
    }

    window.change_custom_domain = function() {
        var id_custom_domain = $('#custom_domain option:selected').attr('id');
        if(id_custom_domain==window.id_custom_domain_sel) {
            $('#btn_apply_custom_domain').prop('disabled',true);
        } else {
            $('#btn_apply_custom_domain').prop('disabled',false);
        }
    }

    window.apply_custom_domain = function(type,id) {
        var id_custom_domain = $('#custom_domain option:selected').attr('id');
        $('#btn_apply_custom_domain').addClass('disabled');
        $.ajax({
            url: "ajax/apply_custom_domain.php",
            type: "POST",
            data: {
                type: type,
                id: id,
                id_custom_domain: id_custom_domain
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    switch(type) {
                        case 'vt':
                            location.reload();
                            break;
                        case 'showcase':
                            save_showcase(window.id_showcase,true);
                            break;
                        case 'globe':
                            save_globe(window.id_globe,'cd');
                            break;
                    }
                } else {
                    $('#btn_apply_custom_domain').removeClass('disabled');
                }
            },
            error: function() {
                $('#btn_apply_custom_domain').removeClass('disabled');
            }
        });
    }

    window.get_option_products_wc = function(id_vt) {
        $.ajax({
            url: "ajax/get_products_wc_options.php",
            type: "POST",
            data: {
                id_vt: id_vt,
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    $('#poi_content_product').html(rsp.products).promise().done(function() {
                        $('#poi_content_product').prop('disabled',false);
                        $('#poi_content_product').selectpicker('render');
                        get_rooms(window.id_virtualtour,'poi');
                    });
                } else {
                    get_rooms(window.id_virtualtour,'poi');
                }
            },
            error: function() {
                get_rooms(window.id_virtualtour,'poi');
            }
        });
    }

    window.send_activation_email = function() {
        var email = $('#email').val();
        var language = $('#language option:selected').attr('id');
        if(email!=='') {
            $('#btn_resend_activation_email').addClass('disabled');
            $.ajax({
                url: "ajax/send_email.php",
                type: "POST",
                data: {
                    type: 'activate',
                    email: email,
                    id_user: window.id_user_edit,
                    language: language
                },
                timeout: 15000,
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == "ok") {
                        $('#btn_resend_activation_email').addClass('btn-success').removeClass('btn-primary');
                    } else {
                        $('#btn_resend_activation_email').removeClass('disabled');
                        $('#btn_resend_activation_email').addClass('btn-error').removeClass('btn-primary');
                        setTimeout(function() {
                            $('#btn_resend_activation_email').removeClass('btn-error').addClass('btn-primary');
                        },2000);
                        alert(rsp.msg);
                    }
                },
                error: function() {
                    $('#btn_resend_activation_email').removeClass('disabled');
                    $('#btn_resend_activation_email').addClass('btn-error').removeClass('btn-primary');
                    setTimeout(function() {
                        $('#btn_resend_activation_email').removeClass('btn-error').addClass('btn-primary');
                    },2000);
                },
            });
        }
    }

    window.remove_learning_modal_icon = function() {
        $('#learning_modal_icon').val('');
        $('#learning_modal_icon_preview').removeClass();
        $('.btn_delete_learning_modal_icon').addClass('disabled');
    }

    window.change_learning_show_modal = function() {
        if($('#learning_show_modal').is(':checked')) {
            $('.learning_modal_settings').removeClass('disabled');
        } else {
            $('.learning_modal_settings').addClass('disabled');
        }
    }

    window.change_nadir_round = function() {
        if($('#nadir_round').is(':checked')) {
            $('#div_image_nadir_logo img').addClass('nadir_round');
        } else {
            $('#div_image_nadir_logo img').removeClass('nadir_round');
        }
    }

    window.change_field_form_checkbox = function(i) {
        if($('#form_field_'+i).is(':checked')) {
            $('#field_div_'+i).css('opacity',1);
        } else {
            $('#field_div_'+i).css('opacity',0.6);
        }
    }

    function fix_all_embeds_pos() {
        count_adjust_embed_helpers_all=0;
        clearInterval(interval_adjust_embed_helpers_all);
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=500) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    function isSVG(fileName) {
        return /\.svg$/i.test(fileName);
    }
})(jQuery); // End of use strict