(function ($) {
    'use strict';
    var pano_viewer_vr, video_viewer_vr, pano_viewer_alt;
    var index_preload_image = 0, index_preload_image_alt = 0, id_current_map = null, len = 0, progress_circle=null, interval_progress=null, step_progress=0.6;
    var first_image = "", imgs = [], imgs_alt = [], imgs_loaded = [], gallery, poi_gallery, intro_desktop = '', intro_mobile = '', intro_desktop_hide = 5, intro_mobile_hide = 5, sly, sly_cat = {};
    var panoramas = [], panoramas_tmp = [], array_maps = [], gallery_images = [], controls_status = [], array_presentation = [], array_id_room_nav = [], array_base64 = [], args_callout = [];
    var html_map, html_logo, list_alt = '', nadir_logo = "", nadir_round = 0, nadir_size = "100px", gallery_mode = "images", gallery_params = [];
    var hfov = 100, min_hfov = 60, max_hfov = 100, autorotate_speed = 0, autorotate_inactivity = 0, initial_feedback = 1200, mouse_follow_feedback = 1.0, timeout_initial_inactivity = null;
    var info_box = "", info_box_type = "popup", author = "", name_virtual_tour = "", custom_box = "", custom2_box = "", custom3_box = "", custom4_box = "", custom5_box = "", location_box = "", avatar_video = "", avatar_video_playing = false, avatar_video_autoplay = 1, avatar_video_hide_end = 1, avatar_video_pause = 1;
    var song_bg = "", audio_player = new Audio(), audio_player_room = new Audio(), array_sound_hs = [], song_bg_volume_sel=1, main_song_bg_volume=1;
    var first_song_play = true, song_autoplay = 0, song_is_playng = false, audio_prompt = null, audio_prompt_open = false;
    var keyboard_mode = 1, confirm_password_modal = null, wl = null, array_panoramas_category = {};
    var voice_commands_enable = 0, arrows_nav = false, show_audio = false, show_vt_title = 0, show_logo = 0, show_poweredby = 0, show_avatar_video = false, show_compass = false, show_gallery = 0, show_info = 0, show_custom = 0, show_custom2 = 0, show_custom3 = 0, show_custom4 = 0, show_custom5 = 0, show_location = 0, show_media = 0, media_file = '', show_dollhouse = 0, show_icons_toggle = 0, show_icons_content_toggle = 0, show_icons_nav_toggle = 0, show_measures_toggle = 0, show_autorotation_toggle = 0, show_nav_control = false, show_presentation = 0, show_device_orientation = 0, drag_device_orientation = true, show_webvr = false, webvr_new_window = false, show_fullscreen = 0, show_map = 0, show_map_tour = 0, show_live_session = false, show_meeting = false, show_annotations = 0, show_list_alt = 0, show_language = false;
    var sameAzimuth = false, virtual_staging = false, config_alt = null, autoclose_menu = false, autoopen_menu = false, autoclose_list_alt = false, autoclose_slider, autoclose_map = false;
    var interval_access_time_avg = null, access_time_avg = 0, access_time_id = 0, enable_visitor_rt = 0, enable_views_stat = true, interval_visitor_rt = 5000, interval_auto_close_poi;
    var auto_show_slider = 0, nav_slider = 0, nav_slider_mode = 0, timeout_destroy, timeout_destroy_marker, timeout_destroy_tooltip, panorama_preview = null, panorama_preview_marker = null, panorama_preview_tooltip = null;
    var form_lightbox = null, show_inline_form = 0, show_main_form = 0, form_content = '', product_lightbox = null;
    var slider_index = 0, index_initial = 0, drag_slider = false, drag_slider_start=0, drag_slider_end=0;
    var live_session_connected = false, lock_viewer = true, interval_live_session = null, id_live_session = '', call_session = null, api_jitsi = null, webcam_audio = true, webcam_video=true;
    var poi_open = false, video_opened = false, map_opened = false, schedule_enabled = false;
    var interval_automatic_presentation = null, automatic_presentation_first_index = null, presentation_type = 'manual', presentation_loop = false, presentation_stop_click = false, presentation_stop_id_room = 0, auto_presentation_speed = 0, presentation_inactivity = 0, timeout_presentation_inactivity = null, presentation_goto_sleep_ms=null, presentation_goto_index=null, presentation_video_playing=false, presentation_goto_params=null, presentation_video_playing_interval=null, presentation_video_wait_end=0, presentation_view_pois=0, presentation_view_measures=0, icons_active=0, measures_active=0;
    var whatsapp_chat = false, whatsapp_number = '', show_facebook = false, show_snapshot = false;
    var transition_loading = true, transition_time = 300, transition_zoom = 30, transition_fadeout = 200, transition_effect = 'fade', transition_hfov = 0, transition_hfov_time = 300;
    var flyin_scene, flyin_renderer, flyin_camera, flyin_geometry, flyin_mesh, flyin_texture, flyin_material, flyin_loader, flyin_duration=2000, viewer_flyin_lp, animatedValues_flyin_lp;
    var interval_check_pois_schedule = null, interval_video_loading_check = null, interval_position = null, goto_timeout = null, interval_callout = null;
    var video_p = null, app_p = null, app_p_vr = null;
    var external = 0, external_url = '', shop_type = 'snipcart', wc_product_attributes = null, wc_product_variations = [], wc_selectOptions = {}, wc_selectElements = {}, wc_default_price_html = '', wc_default_stock_html = '';
    var map_tour = [], map_tour_points = [], map_tour_l = null, map_selector_open = false, panzoom_map = [], drag_pointer = false, drag_pointer_start=0, drag_pointer_end=0;
    var announce = null, announce_interval = null, announce_open = false, first_change_rooms_alt = false;
    var preload_panoramas = 1, click_anywhere = 0, hide_markers = 0, hover_markers = 0;
    var time_version = new Date().getMilliseconds(), in_idle=false, main_avtar_video_playing = false;
    var poi_embed_ids = [], marker_embed_ids = [], video_embeds = [], video360_poi = [], video360_f_poi, measure_rooms = [], measure_rooms_alt = [], list_id_visited = [];
    var interval_adjust_embed_helpers_all = null, count_adjust_embed_helpers_all = 0, autorotate_timeout = null;
    var pan_speed_vt = 1, pan_speed_mobile_vt = 2, friction_vt = 0.1, friction_mobile_vt = 0.4, zoom_friction_vt = 0.05, zoom_friction_mobile_vt = 0.05;
    var camera_dollhouse, scene_dollhouse,  renderer_dollhouse, css_renderer_dollhouse, controls_dollhouse, group_rooms_dollhouse = [];
    var domEvents_dollhouse, dollhouse_div, count_loaded_texture_dollhouse = 0, interval_load_texture_dollhouse, dollhouse_autorotate_timeout;
    var rooms_dollhouse = [], levels_dollhouse = [], textures_dollhouse = [], meshes_dollhouse = [], geometries_dollhouse=[], pointers_c_dollhouse=[], pointers_t_dollhouse=[];
    var dollhouse_loaded = false, json_dollhouse = '', dollhouse_glb = '', array_dollhouse = [], can_click_pointer_dollhouse = false, is_animating_pointer_dollhouse = false, level_sel_dollhouse = 'all', camera_pos_dollhouse = '', total_measure_label = '';
    var event_simulate_click = new Event('simulate_click');
    var button_ar = '', running_in = 'web', leave_poi_open = 1, close_poi_click_outside = 1, snapshot_params, look_target_animating = false;
    var list_mrv_panoramas = [], mrv_panoramas = [], mrv_count_panoramas = 0, index_current_mrv_panorama = 1, prev_current_mrv_panorama = 0, mrv_initialized = 0, mrv_next_timeout = null, ticker_mrv;
    var array_languages = [], default_language = '', params_lang = null;
    var currentBaseImage = '', currentBitmapImage = null, staging_item_id_sel = 0, array_staging_bitmap = {}, worker = null, worker_image = null;
    var id_learning = 0,learning_poi_visited = [], learning_room_enabled = [], learning_room_targets = [], learning_poi_room = {}, learning_marker_room = {}, learning_score_global_ring = null, learning_score_partial_ring = null;
    var s3_version = Date.now();
    window.pano_viewer = null;
    window.video_viewer = null;
    window.current_id_panorama = null;
    window.current_panorama_type = 'image';
    window.show_share = 0;
    window.vr_enabled = false;
    window.poi_embed_originals_pos = [];
    window.marker_embed_originals_pos = [];
    window.measure_lines = [];
    window.measure_lines_alt = [];
    window.poi_box_open = false;
    window.sync_virtual_staging_enabled = false;
    window.changed_room_alt = false;
    window.id_room_alt_sel = 0;
    window.index_room_alt_sel = null;
    window.changed_room_alt_poi = false;
    window.sync_poi_embed_enabled = false;
    window.sync_marker_embed_enabled = false;
    window.viewer_mov_follow_mouse = false;
    window.viewer_mov_pos_change = false;
    window.c_width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    window.c_height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    window.check_svt = function () {
        var params_lang_json = sessionStorage.getItem('params_lang');
        if(params_lang_json!==null) {
            try {
                params_lang = JSON.parse(params_lang_json);
            } catch (e) {
                params_lang = null;
            }
        }
        if(params_lang!==null) {
            window.flyin=0;
            window.flyin_enabled=0;
            window.auto_start=true;
            window.password_protected=false;
            window.background_video = '';
            window.initial_id_room = params_lang['id_room'];
            window.initial_yaw = params_lang['yaw'];
            window.initial_pitch = params_lang['pitch'];
            window.initial_hfov = params_lang['hfov'];
        }
        sessionStorage.removeItem('params_lang');
        var md = new MobileDetect(window.navigator.userAgent);
        if(md.mobile()==null && window.force_mobile==0) {
            window.is_mobile = false;
        } else {
            window.is_mobile = true;
        }
        setupSafariFullscreenXHandler();
        var r = parseInt(window.loading_text_color.substring(1, 3), 16);
        var g = parseInt(window.loading_text_color.substring(3, 5), 16);
        var b = parseInt(window.loading_text_color.substring(5, 7), 16);
        var rgba =  "rgba(" + r + ", " + g + ", " + b + ",0.25)";
        $('#vt_password').css('background-color',rgba);
        progress_circle = new ProgressBar.Circle('.progress-circle', {
            strokeWidth: 5,
            easing: 'easeInOut',
            duration: 500,
            color: window.loading_text_color,
            trailColor: rgba,
            trailWidth: 1,
            from: { width: 1 },
            to: { width: 5 },
            text: {
                autoStyleContainer: false
            },
            step: function(state, circle) {
                circle.path.setAttribute('stroke-width', state.width);
                circle.trail.setAttribute('stroke-width', state.width);
                var value = Math.round(circle.value() * 100);
                if (value <= 0) {
                    circle.setText('');
                } else {
                    circle.setText(value);
                }
            }
        });
        $('.progress-circle').append('<div id="progress_msg"><span>'+window.viewer_labels.progress_initializing+'</span>&nbsp;<img src="css/dots_loading.gif"></div>');
        $('.progress-circle').fadeIn();
        progress_circle.animate(0);
        detectHeadsetVR();
    };

    document.addEventListener('snipcart.ready', () => {
        Snipcart.api.session.setCurrency(window.snipcart_currency.toString());
    });

    window.init_svt = function () {
        if(window.is_mobile) {
            window.background_image = window.background_image_mobile;
            window.background_video = window.background_video_mobile;
            window.background_video_delay = window.background_video_delay_mobile;
            window.background_video_skip = window.background_video_skip_mobile;
        }
        var userAgent = navigator.userAgent.toLowerCase();
        if (typeof window.cordova === 'undefined' && userAgent.indexOf(' electron/') === -1) {
            if( window.location.protocol == 'file:' ){
                alert("Due to browser security restrictions, a web server must be used locally as well.");
                window.stop();
                throw new Error("Due to browser security restrictions, a web server must be used locally as well.");
            }
        }
        try {
            if (Capacitor.getPlatform() === 'ios') {
                running_in = 'ios';
            } else if (Capacitor.getPlatform() === 'android') {
                running_in = 'android';
            } else {
                running_in = 'web';
            }
        } catch (e) {
            running_in = 'web';
        }
        if(window.hide_loading==0) {
            $('.loading').removeClass('hidden');
            $('#background_loading').addClass('background_opacity');
        } else {
            if(window.auto_start && window.password_protected==0) {
                $('.loading').addClass('hidden');
                $('#background_loading').removeClass('background_opacity');
            }
        }
        if(window.background_video!='') {
            var loop = '';
            if(window.background_video_delay>0) {
                loop = 'loop';
            }
            var video_html = '<video id="video_loading" preload="auto" '+loop+' autoplay playsinline webkit-playsinline ><source src="'+((window.s3_enabled) ? window.s3_url : '')+'content/'+window.background_video+'" type="video/mp4"></video>';
            $('#background_loading').html(video_html).promise().done(function () {
                var video_loading = document.getElementById('video_loading');
                if(window.background_video_delay==0) {
                    video_loading.addEventListener('ended',video_loading_ended,false);
                    function video_loading_ended() {
                        window.video_loading_ended = true;
                    }
                } else {
                    video_loading.addEventListener('playing',video_loading_playing,false);
                    function video_loading_playing() {
                        var video_loading = document.getElementById('video_loading');
                        $('#video_loading').css('opacity',1);
                        if(window.background_video_skip==1) setTimeout(function() { $('#skip_video_intro').fadeIn(); },1000);
                        if(window.interval_background_video_elapsed==null) {
                            window.interval_background_video_elapsed = setInterval(function () {
                                if (!video_loading.paused && video_loading.currentTime > 0 && !video_loading.ended) {
                                    window.background_video_elapsed++;
                                    if (window.background_video_elapsed >= window.background_video_delay) {
                                        clearInterval(window.interval_background_video_elapsed);
                                        window.video_loading_ended = true;
                                    }
                                }
                            }, 1000);
                        }
                    }
                }
                $('#background_loading').fadeIn(100);
                if(window.auto_start) {
                    video_loading.play().then(() => {
                        if(window.auto_start) {
                            $('#video_loading').css('opacity',1);
                            start_vt();
                        } else {
                            show_icon_play();
                        }
                    }).catch(error => {
                        show_icon_play();
                    });
                } else {
                    show_icon_play();
                }
            });
        } else if(background_image!='') {
            if($('#intro_slider').length) {
                $('#background_loading').fadeIn(100);
                if(window.auto_start) {
                    progress_circle.animate(0.1);
                    start_vt();
                } else {
                    show_icon_play();
                }
            } else {
                var background_image_load = new Image();
                background_image_load.crossOrigin = 'anonymous';
                $(background_image_load).on('load',function () {
                    $('#background_loading').css('background-image',"url('"+((window.s3_enabled) ? window.s3_url : '')+"content/"+window.background_image+((window.s3_enabled) ? '?s3='+s3_version : '')+"')");
                    $('#background_loading').fadeIn(100);
                    if(window.auto_start) {
                        progress_circle.animate(0.1);
                        start_vt();
                    } else {
                        show_icon_play();
                    }
                }).attr('src',((window.s3_enabled) ? window.s3_url : '')+'content/'+window.background_image+((window.s3_enabled) ? '?s3='+s3_version : ''));
            }
        } else {
            if($('#intro_slider').length) {
                $('#background_loading').fadeIn(100);
            }
            if(window.auto_start) {
                progress_circle.animate(0.1);
                start_vt();
            } else {
                show_icon_play();
            }
        }
    };

    var timer;
    var fadeInBuffer = false;
    $(document).mousemove(function() {
        if (!fadeInBuffer && timer) {
            clearTimeout(timer);
            timer = 0;
        } else {
            $('.pnlm-ui').css({
                cursor: ""
            });
            fadeInBuffer = false;
        }
        timer = setTimeout(function() {
            $('.pnlm-ui').css({
                cursor: 'none'
            });
            fadeInBuffer = true;
        }, 3000);
    });

    window.get_rooms = function (code) {
        $('#lead_mc_form_vt').empty();
        $('#progress_msg').show();
        $('.progress-circle').fadeIn();
        $('#progress_msg span').html(window.viewer_labels.progress_loading_contents);
        if(redirect_to_vr_v) {
            redirect_to_vr();
            return;
        }
        progress_circle.animate(0.2);
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.rooms_json,function(rsp) {
                if(rsp.status=='ok') {
                    rooms_init(rsp);
                }
            });
        } else {
            $.ajax({
                url: "ajax/get_rooms.php",
                type: "POST",
                data: {
                    language: window.language,
                    code: code,
                    export_mode: window.export_mode,
                    preview: window.preview,
                    nostat: (params_lang!=null) ? 1 : window.nostat,
                    ip_visitor: window.ip_visitor,
                    version: window.version
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        rooms_init(rsp);
                    }
                }
            });
        }
    };

    function rooms_init(rsp) {
        $('#progress_msg span').html(window.viewer_labels.progress_init_rooms);
        progress_circle.animate(0.3);
        $('.loading').show();
        external = parseInt(rsp.external);
        external_url = rsp.external_url;
        if(external==1) {
            $('#progress_msg').html('<span>'+window.viewer_labels.progress_finish+'</span>&nbsp;&nbsp;<i class="fas fa-check"></i>');
            progress_circle.animate(1);
            setTimeout(function () {
                if(window.external_embed==1) {
                    $('body').append('<iframe id="external_iframe" style="display:block;position:absolute;top:0;left:0;bottom:0;right:0;width:100%;max-width:100%;height:100%;max-height:100%;border:0;opacity:0" src="'+external_url+'" width="100%" frameborder="none" allowfullscreen allow="accelerometer; camera; display-capture; fullscreen; geolocation; gyroscope; magnetometer; microphone; midi; xr-spatial-tracking;" loading="lazy"></iframe>');                    setTimeout(function () {
                        $('div').not('#external_iframe').remove();
                        $('#external_iframe').css('opacity',1);
                    },1000);
                } else {
                    location.href = external_url;
                }
            },500);
            return;
        }
        array_base64 = rsp.array_base64;
        name_virtual_tour = rsp.name_virtualtour;
        author = rsp.author;
        hfov = parseInt(rsp.hfov);
        min_hfov = parseInt(rsp.min_hfov);
        max_hfov = parseInt(rsp.max_hfov);
        song_bg = rsp.song;
        main_song_bg_volume = parseFloat(rsp.song_bg_volume);
        song_autoplay = parseInt(rsp.song_autoplay);
        nadir_logo = rsp.nadir_logo;
        nadir_round = parseInt(rsp.nadir_round);
        nadir_size = rsp.nadir_size;
        autorotate_speed = parseInt(rsp.autorotate_speed);
        autorotate_inactivity = parseInt(rsp.autorotate_inactivity);
        initial_feedback = parseInt(rsp.initial_feedback);
        if(window.initial_hfov!=='') {
            initial_feedback=0;
        }
        mouse_follow_feedback = parseFloat(rsp.mouse_follow_feedback);
        if(window.is_mobile) {
            mouse_follow_feedback = 0;
        } else {
            mouse_follow_feedback = parseFloat(rsp.mouse_follow_feedback);
        }
        arrows_nav = parseInt(rsp.arrows_nav);
        if (('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
            voice_commands_enable = parseInt(rsp.voice_commands);
        } else {
            voice_commands_enable = 0;
        }
        show_audio = parseInt(rsp.show_audio);
        show_vt_title = parseInt(rsp.show_vt_title);
        show_logo = parseInt(rsp.show_logo);
        show_poweredby = parseInt(rsp.show_poweredby);
        show_avatar_video = parseInt(rsp.show_avatar_video);
        avatar_video = rsp.avatar_video;
        avatar_video_autoplay = parseInt(rsp.avatar_video_autoplay);
        avatar_video_pause = parseInt(rsp.avatar_video_pause);
        avatar_video_hide_end = parseInt(rsp.avatar_video_hide_end);
        show_compass = parseInt(rsp.compass);
        show_gallery = parseInt(rsp.show_gallery);
        gallery_mode = rsp.gallery_mode;
        gallery_params = rsp.gallery_params;
        show_info = parseInt(rsp.show_info);
        show_custom = parseInt(rsp.show_custom);
        show_custom2 = parseInt(rsp.show_custom2);
        show_custom3 = parseInt(rsp.show_custom3);
        show_custom4 = parseInt(rsp.show_custom4);
        show_custom5 = parseInt(rsp.show_custom5);
        show_location = parseInt(rsp.show_location);
        show_media = parseInt(rsp.show_media);
        media_file = rsp.media_file;
        show_dollhouse = parseInt(rsp.show_dollhouse);
        json_dollhouse = rsp.dollhouse;
        dollhouse_glb = rsp.dollhouse_glb;
        show_icons_toggle = parseInt(rsp.show_icons_toggle);
        show_icons_content_toggle = parseInt(rsp.show_icons_content_toggle);
        show_icons_nav_toggle = parseInt(rsp.show_icons_nav_toggle);
        show_measures_toggle = parseInt(rsp.show_measures_toggle);
        show_autorotation_toggle = parseInt(rsp.show_autorotation_toggle);
        if(autorotate_speed==0) show_autorotation_toggle=0;
        show_nav_control = parseInt(rsp.show_nav_control);
        show_presentation = parseInt(rsp.show_presentation);
        window.show_share = parseInt(rsp.show_share);
        show_snapshot = parseInt(rsp.show_snapshot);
        if (window.DeviceOrientationEvent && location.protocol == 'https:' && (/Pacific Build|OculusBrowser|SamsungBrowser|VR Safari|MobileVR|chrome|chromium|mobi|Mac/i.test(window.navigator.userAgent) && navigator.maxTouchPoints && navigator.maxTouchPoints > 0)) {
            show_device_orientation = parseInt(rsp.show_device_orientation);
            drag_device_orientation = parseInt(rsp.drag_device_orientation);
            show_webvr = parseInt(rsp.show_webvr);
        } else {
            show_device_orientation = 0;
            show_webvr = 0;
        }
        webvr_new_window = parseInt(rsp.webvr_new_window);
        if (running_in=='web' && ('fullscreen' in document || 'mozFullScreen' in document || 'webkitIsFullScreen' in document || 'msFullscreenElement' in document)) {
            show_fullscreen = parseInt(rsp.show_fullscreen);
        } else {
            show_fullscreen = 0;
        }
        show_map = parseInt(rsp.show_map);
        show_map_tour = parseInt(rsp.show_map_tour);
        show_live_session = parseInt(rsp.live_session);
        if(window.live_session_force) { show_live_session=true; }
        show_meeting = parseInt(rsp.meeting);
        if(window.meeting_force) { show_meeting=true; }
        show_annotations = parseInt(rsp.show_annotations);
        show_list_alt = parseInt(rsp.show_list_alt);
        list_alt = rsp.list_alt;
        sameAzimuth = parseInt(rsp.sameAzimuth);
        auto_show_slider = parseInt(rsp.auto_show_slider);
        nav_slider = parseInt(rsp.nav_slider);
        nav_slider_mode = parseInt(rsp.nav_slider_mode);
        show_main_form = parseInt(rsp.show_main_form);
        show_inline_form = parseInt(rsp.show_inline_form);
        form_content = rsp.form_content;
        intro_desktop = rsp.intro_desktop;
        intro_mobile = rsp.intro_mobile;
        intro_desktop_hide = parseInt(rsp.intro_desktop_hide);
        intro_mobile_hide = parseInt(rsp.intro_mobile_hide);
        presentation_inactivity = parseInt(rsp.presentation_inactivity);
        if(presentation_inactivity>0) presentation_inactivity=presentation_inactivity*1000;
        presentation_type = rsp.presentation_type;
        auto_presentation_speed = parseInt(rsp.auto_presentation_speed);
        if(window.preview_presentation!=-1) {
            presentation_loop = 1;
            presentation_stop_click = 0;
        } else {
            presentation_loop = parseInt(rsp.presentation_loop);
            presentation_stop_click = parseInt(rsp.presentation_stop_click);
        }
        presentation_stop_id_room = parseInt(rsp.presentation_stop_id_room);
        presentation_view_pois = parseInt(rsp.presentation_view_pois);
        presentation_view_measures = parseInt(rsp.presentation_view_measures);
        whatsapp_chat = parseInt(rsp.whatsapp_chat);
        show_facebook = parseInt(rsp.show_facebook);
        whatsapp_number = rsp.whatsapp_number;
        transition_time = parseInt(rsp.transition_time);
        transition_fadeout = parseInt(rsp.transition_fadeout);
        transition_zoom = parseInt(rsp.transition_zoom);
        transition_loading = parseInt(rsp.transition_loading);
        transition_effect = rsp.transition_effect;
        transition_hfov = parseInt(rsp.transition_hfov);
        transition_hfov_time = parseInt(rsp.transition_hfov_time);
        keyboard_mode = parseInt(rsp.keyboard_mode);
        preload_panoramas = parseInt(rsp.preload_panoramas);
        click_anywhere = parseInt(rsp.click_anywhere);
        hide_markers = parseInt(rsp.hide_markers);
        hover_markers = parseInt(rsp.hover_markers);
        autoclose_menu = parseInt(rsp.autoclose_menu);
        autoopen_menu = parseInt(rsp.autoopen_menu);
        autoclose_list_alt = parseInt(rsp.autoclose_list_alt);
        autoclose_slider = parseInt(rsp.autoclose_slider);
        autoclose_map = parseInt(rsp.autoclose_map);
        pan_speed_vt = parseFloat(rsp.pan_speed);
        pan_speed_mobile_vt = parseFloat(rsp.pan_speed_mobile);
        friction_vt = parseFloat(rsp.friction);
        friction_mobile_vt = parseFloat(rsp.friction_mobile);
        zoom_friction_vt = parseFloat(rsp.zoom_friction);
        zoom_friction_mobile_vt = parseFloat(rsp.zoom_friction_mobile);
        enable_visitor_rt = parseInt(rsp.enable_visitor_rt);
        enable_views_stat = parseInt(rsp.enable_views_stat);
        interval_visitor_rt = parseInt(rsp.interval_visitor_rt);
        flyin_duration = parseInt(rsp.flyin_duration);
        shop_type = rsp.shop_type;
        wc_product_attributes = rsp.product_attributes;
        leave_poi_open = parseInt(rsp.leave_poi_open);
        close_poi_click_outside = parseInt(rsp.close_poi_click_outside);
        snapshot_params = rsp.snapshot_params;
        show_language = parseInt(rsp.show_language);
        array_languages = rsp.array_languages;
        default_language = rsp.default_language;
        if(window.preview==1) {
            show_audio = 0;
            song_bg = '';
            show_list_alt = 0;
            auto_show_slider = 2;
            show_map = 0;
            show_map_tour = 0;
            intro_desktop = '';
            intro_mobile = '';
            show_annotations = 0;
            arrows_nav = 0;
            show_logo = 0;
            show_poweredby = 0;
            show_avatar_video = 0;
            show_fullscreen = 0;
            voice_commands_enable = 0;
            show_info = 0;
            show_custom = 0;
            show_custom2 = 0;
            show_custom3 = 0;
            show_custom4 = 0;
            show_custom5 = 0;
            show_location = 0;
            show_media = 0;
            show_dollhouse = 0;
            show_gallery = 0;
            show_facebook = 0;
            whatsapp_chat = 0;
            show_compass = 0;
            show_icons_toggle = 0;
            show_icons_content_toggle = 0;
            show_icons_nav_toggle = 0;
            show_measures_toggle = 0;
            show_autorotation_toggle = 0;
            show_presentation = 0;
            window.show_share = 0;
            show_snapshot = 0;
            show_main_form = 0;
            show_inline_form = 0;
            show_meeting = 0;
            show_live_session = 0;
            show_webvr = 0;
            show_device_orientation = 0;
            show_nav_control = 0;
            show_vt_title = 0;
            show_language = 0;
            window.comments = 0;
            enable_visitor_rt = 0;
            enable_views_stat = 0;
        }
        if(window.nostat==1) {
            enable_visitor_rt = 0;
        }
        if(window.is_mobile) {
            if(intro_mobile!='') {
                $('.intro_img img').attr('src',((window.s3_enabled) ? window.s3_url : '')+'content/'+intro_mobile);
            }
        } else {
            if(intro_desktop!='') {
                $('.intro_img img').attr('src',((window.s3_enabled) ? window.s3_url : '')+'content/'+intro_desktop);
            }
        }
        if(rsp.rooms.length==1) {
            arrows_nav=0;
        }
        if(nav_slider==2 || (window.is_mobile && nav_slider==1)) {
            $('.list_sliders .list_left').addClass('hidden');
            $('.list_sliders .list_right').addClass('hidden');
        }
        if(window.comments==0) {
            $('.comments_vt').hide();
        }
        if(window.grouped_list_alt == 1) {
            function traverseCategoryTree(tree, parentId = null, parentName = '') {
                for (var i = 0; i < tree.length; i++) {
                    var item = tree[i];
                    if (item.type === 'category') {
                        var currentId = item.id;
                        var currentName = item.name;
                        var children = item.childrens || [];
                        array_panoramas_category[currentId] = [parentId, currentName];
                        traverseCategoryTree(children, currentId, currentName);
                    } else if (item.type === 'room') {
                        array_panoramas_category["r_"+item.id] = [parentId, parentName];
                    }
                }
            }
            traverseCategoryTree(list_alt);
        }
        function removeUnusedCategories(data) {
            const categoryIds = Object.keys(data).filter(key => key.startsWith('c'));
            const usedCategoryIds = new Set();
            function findUsedCategories(categoryId) {
                if (usedCategoryIds.has(categoryId)) return;
                usedCategoryIds.add(categoryId);
                const parentCategory = data[categoryId]?.[0];
                if (parentCategory) {
                    findUsedCategories(parentCategory);
                }
            }
            Object.entries(data)
                .filter(([key]) => key.startsWith('r_'))
                .forEach(([key, [parentCategory]]) => {
                    findUsedCategories(parentCategory);
                });
            for (const categoryId of categoryIds) {
                if (!usedCategoryIds.has(categoryId)) {
                    delete data[categoryId];
                }
            }
            return data;
        }
        array_panoramas_category = removeUnusedCategories(array_panoramas_category);
        jQuery.each(rsp.rooms, function(index, room) {
            panoramas[index] = {};
            panoramas[index].id = room.id;
            panoramas[index].name = room.name;
            panoramas[index].logo = room.logo;
            panoramas[index].logo_height = room.logo_height;
            panoramas[index].type = room.type;
            panoramas[index].filters = room.filters;
            panoramas[index].effect = room.effect;
            panoramas[index].virtual_staging = parseInt(room.virtual_staging);
            panoramas[index].lp_duration = parseInt(room.lp_duration);
            panoramas[index].lp_fade = parseInt(room.lp_fade);
            panoramas[index].main_view_tooltip = room.main_view_tooltip;
            panoramas[index].multires = parseInt(room.multires);
            panoramas[index].multires_dir = room.multires_dir;
            panoramas[index].multires_config = room.multires_config;
            panoramas[index].panorama_blob = '';
            panoramas[index].background_color = room.background_color.split(',');
            panoramas[index].id_poi_autoopen = room.id_poi_autoopen;
            panoramas[index].avatar_video = room.avatar_video;
            panoramas[index].avatar_video_play_once = parseInt(room.avatar_video_play_once);
            panoramas[index].avatar_video_autoplay = parseInt(room.avatar_video_autoplay);
            panoramas[index].avatar_video_pause = parseInt(room.avatar_video_pause);
            panoramas[index].avatar_video_hide_end = parseInt(room.avatar_video_hide_end);
            panoramas[index].avatar_video_played = 0;
            panoramas[index].panorama_url = room.panorama_url;
            panoramas[index].panorama_json = "panoramas/"+room.panorama_json;
            panoramas[index].panorama_3d = "panoramas/"+room.panorama_3d;
            if(window.is_mobile) {
                if(parseInt(room.pano_mobile)==1) {
                    panoramas[index].panorama_image = "panoramas/mobile/"+room.panorama_image;
                } else {
                    panoramas[index].panorama_image = "panoramas/"+room.panorama_image;
                }
            } else {
                panoramas[index].panorama_image = "panoramas/"+room.panorama_image;
            }
            panoramas[index].panorama_video = "videos/"+room.panorama_video;
            if(room.thumb_image!='') {
                panoramas[index].thumb_image = "panoramas/thumb_custom/"+room.thumb_image;
            } else {
                panoramas[index].thumb_image = "panoramas/preview/"+room.panorama_image;
            }
            panoramas[index].array_rooms_alt = {};
            jQuery.each(room.array_rooms_alt, function(index_alt, room_alt) {
                panoramas[index].array_rooms_alt[index_alt] = {};
                panoramas[index].array_rooms_alt[index_alt].id = parseInt(room_alt.id);
                panoramas[index].array_rooms_alt[index_alt].poi = parseInt(room_alt.poi);
                panoramas[index].array_rooms_alt[index_alt].view_tooltip = room_alt.view_tooltip;
                panoramas[index].array_rooms_alt[index_alt].multires = parseInt(room_alt.multires);
                panoramas[index].array_rooms_alt[index_alt].multires_dir = room_alt.multires_dir;
                panoramas[index].array_rooms_alt[index_alt].multires_config = room_alt.multires_config;
                panoramas[index].array_rooms_alt[index_alt].auto_open = parseInt(room_alt.auto_open);
                panoramas[index].array_rooms_alt[index_alt].from_hour = room_alt.from_hour;
                panoramas[index].array_rooms_alt[index_alt].to_hour = room_alt.to_hour;
                if(window.is_mobile) {
                    if(parseInt(room_alt.pano_mobile)==1) {
                        panoramas[index].array_rooms_alt[index_alt].panorama_image = "panoramas/mobile/"+room_alt.panorama_image;
                    } else {
                        panoramas[index].array_rooms_alt[index_alt].panorama_image = "panoramas/"+room_alt.panorama_image;
                    }
                } else {
                    panoramas[index].array_rooms_alt[index_alt].panorama_image = "panoramas/"+room_alt.panorama_image;
                }
                panoramas[index].array_rooms_alt[index_alt].thumb_image = "panoramas/preview/"+room_alt.panorama_image;
                panoramas[index].array_rooms_alt[index_alt].panorama_blob = '';
            });
            panoramas[index].northOffset = parseInt(room.northOffset);
            panoramas[index].show_nadir = parseInt(room.show_nadir);
            panoramas[index].pitch = parseInt(room.pitch);
            panoramas[index].yaw = parseInt(room.yaw);
            panoramas[index].hfov = parseInt(room.hfov);
            panoramas[index].h_pitch = parseInt(room.h_pitch);
            panoramas[index].h_roll = parseInt(room.h_roll);
            panoramas[index].allow_pitch = parseInt(room.allow_pitch);
            panoramas[index].allow_hfov = parseInt(room.allow_hfov);
            panoramas[index].min_pitch = parseInt(room.min_pitch);
            panoramas[index].max_pitch = parseInt(room.max_pitch);
            panoramas[index].min_yaw = parseInt(room.min_yaw);
            panoramas[index].max_yaw = parseInt(room.max_yaw);
            panoramas[index].haov = parseInt(room.haov);
            panoramas[index].vaov = parseInt(room.vaov);
            panoramas[index].id_map = parseInt(room.id_map);
            panoramas[index].map_north = 0;
            panoramas[index].map_top = parseInt(room.map_top);
            panoramas[index].map_left = parseInt(room.map_left);
            panoramas[index].lat = room.lat;
            panoramas[index].lon = room.lon;
            panoramas[index].visible_list = parseInt(room.visible_list);
            panoramas[index].video_end_goto = parseInt(room.video_end_goto);
            panoramas[index].song = room.song;
            panoramas[index].song_bg_volume = parseFloat(room.song_bg_volume);
            panoramas[index].song_volume = parseFloat(room.song_volume);
            panoramas[index].song_loop = parseFloat(room.song_loop);
            panoramas[index].song_once = parseFloat(room.song_once);
            panoramas[index].song_played = false;
            panoramas[index].audio_track_enable = parseInt(room.audio_track_enable);
            panoramas[index].annotation_title = room.annotation_title;
            panoramas[index].annotation_description = room.annotation_description;
            panoramas[index].protect_type = room.protect_type;
            panoramas[index].protect_pc = room.protect_pc;
            panoramas[index].protect_mc_form = room.protect_mc_form;
            panoramas[index].protect_remember = parseInt(room.protect_remember);
            panoramas[index].passcode_title = room.passcode_title;
            panoramas[index].protect_lead_params = room.protect_lead_params;
            panoramas[index].passcode_description = room.passcode_description;
            panoramas[index].protect_send_email = room.protect_send_email;
            if(room.protect_send_email) {
                panoramas[index].protect_email = room.protect_email;
            } else {
                panoramas[index].protect_email = '';
            }
            panoramas[index].protected = parseInt(room.protected);
            if(panoramas[index].protect_remember==1) {
                switch(room.protect_type) {
                    case 'passcode':
                        var cookie_pc = getCookie('svt_pc_'+window.id_virtualtour+'_'+room.id+'_'+room.protect_pc);
                        if(cookie_pc) {
                            if(cookie_pc==1) { panoramas[index].protected=0; }
                        }
                        break;
                    case 'leads':
                        var cookie_l = getCookie('svt_l_'+window.id_virtualtour+'_'+room.id);
                        if(cookie_l) {
                            if(cookie_l==1) { panoramas[index].protected=0; }
                        }
                        break;
                    case 'mailchimp':
                        var cookie_mc = getCookie('svt_mc_'+window.id_virtualtour+'_'+room.id);
                        if(cookie_mc) {
                            if(cookie_mc==1) { panoramas[index].protected=0; }
                        }
                        break;
                }
            }
            panoramas[index].transition_override = parseInt(room.transition_override);
            if(panoramas[index].transition_override==1) {
                panoramas[index].transition_time = parseInt(room.transition_time);
                panoramas[index].transition_zoom = parseInt(room.transition_zoom);
                panoramas[index].transition_fadeout = parseInt(room.transition_fadeout);
                panoramas[index].transition_effect = room.transition_effect;
                panoramas[index].transition_hfov = parseInt(room.transition_hfov);
                panoramas[index].transition_hfov_time = parseInt(room.transition_hfov_time);
            }
            panoramas[index].autorotate_override = parseInt(room.autorotate_override);
            if(panoramas[index].autorotate_override==1) {
                panoramas[index].autorotate_speed = parseInt(room.autorotate_speed);
                panoramas[index].autorotate_inactivity = parseInt(room.autorotate_inactivity);
            }
            panoramas[index].hotSpots = [];
            panoramas[index].hotSpots_vr = [];
            panoramas[index].hotSpots_alt = [];
            if(nadir_logo!='' && panoramas[index].show_nadir==1) {
                panoramas[index].hotSpots.push({
                    "type": "nadir",
                    "view_type": 0,
                    "object": "nadir",
                    "transform3d": false,
                    "pitch": -90,
                    "yaw": 0,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "scale": true,
                    "cssClass": "nadir-hotspot",
                    "createTooltipFunc": hotspot_nadir,
                    "createTooltipArgs": [nadir_logo,nadir_round]
                });
                panoramas[index].hotSpots_alt.push({
                    "type": "nadir",
                    "view_type": 0,
                    "object": "nadir",
                    "transform3d": false,
                    "pitch": -90,
                    "yaw": 0,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "scale": true,
                    "cssClass": "nadir-hotspot custom-hotspot_alt",
                    "createTooltipFunc": hotspot_nadir,
                    "createTooltipArgs": [nadir_logo,nadir_round]
                });
                panoramas[index].hotSpots_vr.push({
                    "type": "nadir",
                    "view_type": 0,
                    "object": "nadir",
                    "transform3d": false,
                    "pitch": -90,
                    "yaw": 0,
                    "rotateX": 0,
                    "rotateZ": 0,
                    "scale": true,
                    "cssClass": "nadir-hotspot",
                    "createTooltipFunc": hotspot_nadir,
                    "createTooltipArgs": [nadir_logo,nadir_round]
                });
            }
            if(learning_poi_room["r"+room.id]==undefined) {
                learning_poi_room["r"+room.id] = {};
            }
            if(learning_marker_room[room.id]==undefined) {
                learning_marker_room[room.id] = {};
            }
            var learning_poi_room_tmp = [];
            jQuery.each(room.markers, function(index_m, marker_m) {
                if(marker_m.object=='poi' && marker_m.type!=null && marker_m.type!='' && marker_m.type!='grouped' && parseInt(marker_m.learning)==1) {
                    learning_poi_room_tmp.push(marker_m);
                }
                if(marker_m.object=='marker') {
                    var id_room_target = parseInt(marker_m.id_room_target);
                    learning_marker_room[room.id][marker_m.id]=id_room_target;
                    if(!learning_room_targets.includes(id_room_target)) learning_room_targets.push(id_room_target);
                }
                if(marker_m.object=='poi' && marker_m.schedule!='') {
                    schedule_enabled = true;
                }
                if(marker_m.sound!='') {
                    if(!array_sound_hs.hasOwnProperty(marker_m.sound)) {
                        array_sound_hs[marker_m.sound] = new Howl({
                            src: [((window.s3_enabled) ? window.s3_url : '')+marker_m.sound],
                            autoplay: false,
                            loop: false,
                            preload: true
                        });
                    }
                }
                switch(marker_m.object) {
                    case 'marker':
                        if(marker_m.embed_type=='') {
                            panoramas[index].hotSpots.push({
                                "id": marker_m.id,
                                "type": marker_m.type,
                                "view_type": 0,
                                "object": "marker",
                                "transform3d": false,
                                "scale": (marker_m.scale==1) ? true : false,
                                "tooltip_type": marker_m.tooltip_type,
                                "tooltip_visibility": marker_m.tooltip_visibility,
                                "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),
                                "animation": marker_m.animation,
                                "cssClass": "custom-hotspot",
                                "createTooltipFunc": hotspot,
                                "createTooltipArgs": marker_m,
                                "clickHandlerFunc": goto,
                                "clickHandlerArgs": [marker_m.id_room_target,parseFloat(marker_m.pitch),parseFloat(marker_m.yaw),marker_m.pitch_room_target,marker_m.yaw_room_target,null,parseInt(marker_m.lookat),marker_m.sound,marker_m.id,marker_m.pitch_look_room_target,marker_m.yaw_look_room_target,marker_m.duration_look_room_target]
                            });
                            panoramas[index].hotSpots_alt.push({
                                "id": "alt"+marker_m.id,
                                "type": marker_m.type,
                                "view_type": 0,
                                "object": "marker",
                                "transform3d": false,
                                "scale": (marker_m.scale==1) ? true : false,
                                "tooltip_type": marker_m.tooltip_type,
                                "tooltip_visibility": marker_m.tooltip_visibility,
                                "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),
                                "animation": marker_m.animation,
                                "cssClass": "custom-hotspot custom-hotspot_alt",
                                "createTooltipFunc": hotspot,
                                "createTooltipArgs": marker_m,
                                "clickHandlerFunc": goto,
                                "clickHandlerArgs": [marker_m.id_room_target,parseFloat(marker_m.pitch),parseFloat(marker_m.yaw),marker_m.pitch_room_target,marker_m.yaw_room_target,null,parseInt(marker_m.lookat),marker_m.sound,marker_m.id,marker_m.pitch_look_room_target,marker_m.yaw_look_room_target,marker_m.duration_look_room_target]
                            });
                            panoramas[index].hotSpots_vr.push({
                                "id": marker_m.id,
                                "type": marker_m.type,
                                "view_type": 0,
                                "object": "marker",
                                "transform3d": false,
                                "scale": (marker_m.scale==1) ? true : false,
                                "tooltip_type": marker_m.tooltip_type,
                                "tooltip_visibility": marker_m.tooltip_visibility,
                                "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),
                                "animation": "none",
                                "cssClass": "custom-hotspot custom-hotspot_vr",
                                "createTooltipFunc": hotspot,
                                "createTooltipArgs": marker_m,
                                "clickHandlerFunc": goto,
                                "clickHandlerArgs": [marker_m.id_room_target,parseFloat(marker_m.pitch),parseFloat(marker_m.yaw),marker_m.pitch_room_target,marker_m.yaw_room_target,null,parseInt(marker_m.lookat),marker_m.sound,marker_m.id,marker_m.pitch_look_room_target,marker_m.yaw_look_room_target,marker_m.duration_look_room_target]
                            });
                        } else {
                            panoramas[index].hotSpots.push({
                                "id": marker_m.id,
                                "type": marker_m.embed_type,
                                "view_type": 0,
                                "object": "marker_embed",
                                "transform3d": parseInt(marker_m.transform3d),
                                "tooltip_type": marker_m.tooltip_type,
                                "tooltip_visibility": marker_m.tooltip_visibility,
                                "pitch": parseFloat(marker_m.pitch),
                                "yaw": parseFloat(marker_m.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "cssClass": "hotspot-embed",
                                "animation": "none",
                                "createTooltipFunc": hotspot_embed_m,
                                "createTooltipArgs": marker_m,
                                "clickHandlerFunc": goto,
                                "clickHandlerArgs": [marker_m.id_room_target,parseFloat(marker_m.pitch),parseFloat(marker_m.yaw),marker_m.pitch_room_target,marker_m.yaw_room_target,null,parseInt(marker_m.lookat),marker_m.sound,marker_m.id,marker_m.pitch_look_room_target,marker_m.yaw_look_room_target,marker_m.duration_look_room_target]
                            });
                            panoramas[index].hotSpots_alt.push({
                                "id": "alt"+marker_m.id,
                                "type": marker_m.embed_type,
                                "view_type": 0,
                                "object": "marker_embed",
                                "transform3d": parseInt(marker_m.transform3d),
                                "tooltip_type": marker_m.tooltip_type,
                                "tooltip_visibility": marker_m.tooltip_visibility,
                                "pitch": parseFloat(marker_m.pitch),
                                "yaw": parseFloat(marker_m.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "animation": "none",
                                "cssClass": "hotspot-embed custom-hotspot_alt",
                                "createTooltipFunc": hotspot_embed_m,
                                "createTooltipArgs": marker_m,
                                "clickHandlerFunc": goto,
                                "clickHandlerArgs": [marker_m.id_room_target,parseFloat(marker_m.pitch),parseFloat(marker_m.yaw),marker_m.pitch_room_target,marker_m.yaw_room_target,null,parseInt(marker_m.lookat),marker_m.sound,marker_m.id,marker_m.pitch_look_room_target,marker_m.yaw_look_room_target,marker_m.duration_look_room_target]
                            });
                            panoramas[index].hotSpots_vr.push({
                                "id": marker_m.id,
                                "type": marker_m.type,
                                "view_type": 0,
                                "object": "marker",
                                "transform3d": false,
                                "tooltip_type": marker_m.tooltip_type,
                                "tooltip_visibility": marker_m.tooltip_visibility,
                                "pitch": parseFloat(marker_m.pitch),
                                "yaw": parseFloat(marker_m.yaw),
                                "rotateX": 0,
                                "rotateZ": 0,
                                "size_scale": 1,
                                "animation": "none",
                                "cssClass": "custom-hotspot custom-hotspot_vr",
                                "createTooltipFunc": hotspot,
                                "createTooltipArgs": marker_m,
                                "clickHandlerFunc": goto,
                                "clickHandlerArgs": [marker_m.id_room_target,parseFloat(marker_m.pitch),parseFloat(marker_m.yaw),marker_m.pitch_room_target,marker_m.yaw_room_target,null,parseInt(marker_m.lookat),marker_m.sound,marker_m.id,marker_m.pitch_look_room_target,marker_m.yaw_look_room_target,marker_m.duration_look_room_target]
                            });
                            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) {
                                panoramas[index].hotSpots.push({
                                    "type": 'pointer',
                                    "view_type": 0,
                                    "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": false,
                                    "cssClass": "hotspot-helper",
                                    "createTooltipFunc": hotspot_embed_helper_m,
                                    "createTooltipArgs": [marker_m.id,(index_h+1)]
                                });
                            });
                        }
                        break;
                    case 'poi':
                        switch(marker_m.embed_type) {
                            case 'image':
                            case 'text':
                            case 'html':
                            case 'selection':
                            case 'object3d':
                                switch(marker_m.type) {
                                    case 'image':
                                    case 'gallery':
                                    case 'video360':
                                    case 'audio':
                                    case 'html':
                                    case 'html_sc':
                                    case 'form':
                                    case 'google_maps':
                                    case 'object360':
                                    case 'object3d':
                                    case 'download':
                                    case 'video':
                                    case 'link':
                                    case 'link_ext':
                                    case 'lottie':
                                    case 'product':
                                    case 'pdf':
                                    case 'pointclouds':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": "none",
                                            "cssClass": "hotspot-embed",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": "alt"+marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": "none",
                                            "cssClass": "hotspot-embed custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                    case 'switch_pano':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": "none",
                                            "cssClass": "hotspot-embed",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": change_room_alt_poi,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": "alt"+marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": "none",
                                            "cssClass": "hotspot-embed custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": change_room_alt_poi,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                    default:
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": "none",
                                            "cssClass": "hotspot-embed",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": "alt"+marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": "none",
                                            "cssClass": "hotspot-embed custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                }
                                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) {
                                        panoramas[index].hotSpots.push({
                                            "type": 'pointer',
                                            "view_type": 0,
                                            "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": false,
                                            "cssClass": "hotspot-helper",
                                            "createTooltipFunc": hotspot_embed_helper,
                                            "createTooltipArgs": [marker_m.id,(index_h+1)]
                                        });
                                    });
                                }
                                break;
                            case 'gallery':
                            case 'video':
                            case 'video_transparent':
                            case 'video_chroma':
                            case 'link':
                                switch(marker_m.type) {
                                    default:
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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": "hotspot-embed",
                                            "animation": "none",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": empty_function,
                                            "clickHandlerArgs": null,
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": "alt"+marker_m.id,
                                            "type": marker_m.embed_type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi_embed",
                                            "transform3d": parseInt(marker_m.transform3d),
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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": "hotspot-embed custom-hotspot_alt",
                                            "animation": "none",
                                            "createTooltipFunc": hotspot_embed,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": empty_function,
                                            "clickHandlerArgs": null,
                                        });
                                        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) {
                                                panoramas[index].hotSpots.push({
                                                    "type": 'pointer',
                                                    "view_type": 0,
                                                    "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": false,
                                                    "cssClass": "hotspot-helper",
                                                    "createTooltipFunc": hotspot_embed_helper,
                                                    "createTooltipArgs": [marker_m.id, (index_h + 1)]
                                                });
                                            });
                                        }
                                        break;
                                }
                                break;
                            default:
                                switch(marker_m.type) {
                                    case 'image':
                                    case 'gallery':
                                    case 'video360':
                                    case 'audio':
                                    case 'html':
                                    case 'html_sc':
                                    case 'form':
                                    case 'google_maps':
                                    case 'object360':
                                    case 'object3d':
                                    case 'download':
                                    case 'video':
                                    case 'link':
                                    case 'link_ext':
                                    case 'lottie':
                                    case 'product':
                                    case 'pdf':
                                    case 'pointclouds':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                    case 'switch_pano':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": change_room_alt_poi,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": change_room_alt_poi,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                    case 'callout':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "pitch": parseFloat(marker_m.pitch),
                                            "yaw": parseFloat(marker_m.yaw),
                                            "rotateX": 0,
                                            "rotateZ": 0,
                                            "size_scale": 1,
                                            "animation": '',
                                            "cssClass": "custom-hotspot-content",
                                            "createTooltipFunc": hotspot_callout,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": toggle_callout,
                                            "clickHandlerArgs": marker_m.id
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": "alt"+marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "pitch": parseFloat(marker_m.pitch),
                                            "yaw": parseFloat(marker_m.yaw),
                                            "rotateX": 0,
                                            "rotateZ": 0,
                                            "size_scale": 1,
                                            "animation": '',
                                            "cssClass": "custom-hotspot-content custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_callout,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": toggle_callout,
                                            "clickHandlerArgs": "alt"+marker_m.id
                                        });
                                        break;
                                    case 'staging':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "pitch": parseFloat(marker_m.pitch),
                                            "yaw": parseFloat(marker_m.yaw),
                                            "rotateX": 0,
                                            "rotateZ": 0,
                                            "size_scale": 1,
                                            "animation": '',
                                            "cssClass": "custom-hotspot-content staging-hotspot",
                                            "createTooltipFunc": hotspot_staging,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": toggle_staging,
                                            "clickHandlerArgs": marker_m.id
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": "alt"+marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "pitch": parseFloat(marker_m.pitch),
                                            "yaw": parseFloat(marker_m.yaw),
                                            "rotateX": 0,
                                            "rotateZ": 0,
                                            "size_scale": 1,
                                            "animation": '',
                                            "cssClass": "custom-hotspot-content custom-hotspot_alt staging-hotspot",
                                            "createTooltipFunc": hotspot_staging,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": toggle_staging,
                                            "clickHandlerArgs": "alt"+marker_m.id
                                        });
                                        break;
                                    case 'grouped':
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content grouped_hs",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_grouped,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content custom-hotspot_alt grouped_hs",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_grouped,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                    default:
                                        panoramas[index].hotSpots.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        panoramas[index].hotSpots_alt.push({
                                            "id": marker_m.id,
                                            "type": marker_m.type,
                                            "view_type": parseInt(marker_m.view_type),
                                            "object": "poi",
                                            "transform3d": false,
                                            "scale": (marker_m.scale==1) ? true : false,
                                            "tooltip_type": marker_m.tooltip_type,
                                            "tooltip_visibility": marker_m.tooltip_visibility,
                                            "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),
                                            "animation": marker_m.animation,
                                            "cssClass": "custom-hotspot-content custom-hotspot_alt",
                                            "createTooltipFunc": hotspot_content,
                                            "createTooltipArgs": marker_m,
                                            "clickHandlerFunc": view_content,
                                            "clickHandlerArgs": marker_m
                                        });
                                        break;
                                }
                                break;
                        }
                        break;
                }
            });
            jQuery.each(room.measures, function(index_ms, measure) {
                measure_rooms.push(measure);
                measure_rooms_alt.push(measure);
                panoramas[index].hotSpots.push({
                    "id": 'measure_'+measure.id+'_start',
                    "type": 'measure',
                    "view_type": 0,
                    "object": "measure",
                    "transform3d": false,
                    "scale": false,
                    "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',visible_multiview_ids:measure.visible_multiview_ids},
                    "clickHandlerFunc": false,
                    "clickHandlerArgs": ''
                });
                panoramas[index].hotSpots.push({
                    "id": 'measure_'+measure.id+'_end',
                    "type": 'measure',
                    "view_type": 0,
                    "object": "measure",
                    "transform3d": false,
                    "scale": false,
                    "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',visible_multiview_ids:measure.visible_multiview_ids},
                    "clickHandlerFunc": false,
                    "clickHandlerArgs": ''
                });
                panoramas[index].hotSpots_alt.push({
                    "id": 'measure_'+measure.id+'_start_alt',
                    "type": 'measure',
                    "view_type": 0,
                    "object": "measure",
                    "transform3d": false,
                    "scale": false,
                    "tooltip_type": '',
                    "pitch": parseFloat(measure.pitch_start),
                    "yaw": parseFloat(measure.yaw_start),
                    "rotateX": 0,
                    "rotateZ": 0,
                    "size_scale": 1,
                    "animation": '',
                    "cssClass": "custom-hotspot-measure custom-hotspot_alt",
                    "createTooltipFunc": hotspot_measure,
                    "createTooltipArgs": {id:measure.id,dir:'start_alt',visible_multiview_ids:measure.visible_multiview_ids},
                    "clickHandlerFunc": false,
                    "clickHandlerArgs": ''
                });
                panoramas[index].hotSpots_alt.push({
                    "id": 'measure_'+measure.id+'_end_alt',
                    "type": 'measure',
                    "view_type": 0,
                    "object": "measure",
                    "transform3d": false,
                    "scale": false,
                    "tooltip_type": '',
                    "pitch": parseFloat(measure.pitch_end),
                    "yaw": parseFloat(measure.yaw_end),
                    "rotateX": 0,
                    "rotateZ": 0,
                    "size_scale": 1,
                    "animation": '',
                    "cssClass": "custom-hotspot-measure custom-hotspot_alt",
                    "createTooltipFunc": hotspot_measure,
                    "createTooltipArgs": {id:measure.id,dir:'end_alt',visible_multiview_ids:measure.visible_multiview_ids},
                    "clickHandlerFunc": false,
                    "clickHandlerArgs": ''
                });
            });
            learning_poi_room_tmp.sort(function(a, b) {
                return (parseInt(a.learning_priority) || 0) - (parseInt(b.learning_priority) || 0);
            });
            jQuery.each(learning_poi_room_tmp, function(index_m, marker_m) {
                learning_poi_room["r"+room.id]["p"+marker_m.id] = 0;
            });
        });
        for(var i=0; i < panoramas.length; i++) {
            if (ObjectLength(panoramas[i].array_rooms_alt) > 0) {
                jQuery.each(panoramas[i].array_rooms_alt, function (index_alt, room_alt) {
                    var img_alt = room_alt.panorama_image;
                    imgs_alt.push(img_alt);
                });
            }
        }
        if(window.learning_mode>0) {
            if(window.learning_unlock_marker) {
                learning_room_enabled.push(parseInt(panoramas[index_initial].id));
            }
        }
        jQuery.each(rsp.rooms, function(index, room) {
            var id_room = parseInt(room.id);
            if(!learning_room_targets.includes(id_room)) {
                if(!learning_room_enabled.includes(id_room)) learning_room_enabled.push(id_room);
            }
        });
        initialize_slider(panoramas);
        if(window.initial_id_room!='') {
            index_initial = get_id_viewer(parseInt(window.initial_id_room));
            slider_index = index_initial;
        }
        if(window.lat_panorama!='' && window.lon_panorama!='') {
            var index_tmp = goto_room_coordinates(window.lat_panorama,window.lon_panorama,false);
            if(index_tmp!=false) {
                index_initial = index_tmp;
                slider_index = index_initial;
            }
        }
        get_maps();
    }

    function findMainCategoryFromArray(startCategoryId, categoryMap) {
        if (!startCategoryId || !categoryMap[startCategoryId]) {
            return null;
        }
        let currentId = startCategoryId;
        let parentId = categoryMap[currentId][0];
        while (parentId !== null) {
            currentId = parentId;
            if (!categoryMap[currentId]) { return null; }
            parentId = categoryMap[currentId][0];
        }
        return currentId;
    }

    function countTotalRoomsRecursive(categoryId, data) {
        const childrenMap = {};
        const rooms = [];
        for (const key in data) {
            const [parentId] = data[key];
            if (key.startsWith("c")) {
                const parentKey = parentId === null ? 'null' : parentId;
                if (!childrenMap[parentKey]) childrenMap[parentKey] = [];
                childrenMap[parentKey].push(key);
            } else if (key.startsWith("r")) {
                rooms.push({ id: key, parentId });
            }
        }
        const categoryIds = new Set();
        const visited = new Set();
        function collectCategories(id) {
            if (!id || visited.has(id)) return;
            visited.add(id);
            categoryIds.add(id);
            const children = childrenMap[id] || [];
            for (const child of children) {
                collectCategories(child);
            }
        }
        collectCategories(categoryId);
        return rooms.filter(room => categoryIds.has(room.parentId)).length;
    }

    function initialize_slider(panoramas) {
        var i_slider = 0;
        var i_slider_cat = {};
        if ($('#list_slider_main .slidee').length === 0 && $('#list_slider_main').length > 0) {
            $('#list_slider_main').append('<ul class="slidee"></ul>');
        } else if ($('#list_slider_main .slidee').length > 0) {
            $('#list_slider_main .slidee').empty();
        }
        if ($('.list_sliders .list_slider_cat').length > 0) { $('.list_sliders .list_slider_cat').remove(); }
        for (const categoryId in array_panoramas_category) {
            if (!categoryId.startsWith('c')) continue;
            const categoryInfo = array_panoramas_category[categoryId];
            const parentId = categoryInfo[0];
            const categoryName = categoryInfo[1];
            if ($('#list_slider_cat_' + categoryId).length === 0) {
                var catSliderHtml =
                    '<div data-id="' + categoryId + '" id="list_slider_cat_' + categoryId + '" class="list_slider list_slider_cat hidden_slider">' +
                    '<div class="slider_category_name"><span>' + categoryName + '</span></div>' +
                    '<ul id="slidee_cat_' + categoryId + '" class="slidee_cat slidee"></ul>' +
                    '<i data-id-category="' + categoryId + '" class="fa fa-chevron-left list_left"></i>' +
                    '<i data-id-category="' + categoryId + '" class="fa fa-chevron-right list_right"></i>' +
                    '</div>';
                $('.list_sliders').append(catSliderHtml);
                $('#slidee_cat_' + categoryId).append('<li class="pointer_list_back"><i class="fa-solid fa-turn-up"></i></li>');
                i_slider_cat[categoryId] = 1;
            }
            let $parentSlideeUL = null;
            let itemIndex = 0;
            if (parentId === null) {
                $parentSlideeUL = $('#list_slider_main .slidee');
                i_slider++;
                itemIndex = i_slider;
            } else if (array_panoramas_category[parentId]) {
                $parentSlideeUL = $('#slidee_cat_' + parentId);
                if (!$parentSlideeUL || $parentSlideeUL.length === 0) continue;
                if (!i_slider_cat[parentId]) i_slider_cat[parentId] = 1;
                itemIndex = i_slider_cat[parentId];
            } else { continue; }
            if ($parentSlideeUL && $parentSlideeUL.length > 0 && $parentSlideeUL.find('.pointer_list_cat_' + categoryId).length === 0) {
                var catLiHtml =
                    '<li data-index_id="' + itemIndex + '" data-count="0" data-id-category="' + categoryId + '" class="pointer_list_cat pointer_list_cat_' + categoryId + '">' +
                    '<span class="noselect room_name_slider">' + categoryName + '</span>' +
                    '<span class="noselect room_count_slider">0</span>' +
                    '<div class="stat_visitors_rt_rooms hidden"><i class="fas fa-user"></i>&nbsp;<span id="count_visitors_rt_room_cat_' + categoryId + '">0</span></div>' +
                    '<span class="room_visited room_visited_cat_' + categoryId + '"><i class="fas fa-check"></i></span>' +
                    '<div class="cat_image_grid"></div>' +
                    '</li>';
                $parentSlideeUL.append(catLiHtml);
                if (parentId !== null) { i_slider_cat[parentId]++; }
            }
        }
        for (var i = 0; i < panoramas.length; i++) {
            var panorama = panoramas[i];
            var id = panorama.id;
            var nome = panorama.name;
            var visible_list = panorama.visible_list;
            var img = panorama.panorama_image;
            var thumb = panorama.thumb_image;
            if(!panoramas.multires) { imgs.push(img+'|'+id); }
            if (!visible_list) continue;
            try {
                var img_s = '';
                var s3_enabled = typeof window !== 'undefined' && window.s3_enabled;
                var s3_url = (typeof window !== 'undefined' && window.s3_url) || '';
                var live_session_connected = typeof window !== 'undefined' && window.live_session_connected;
                var vr_enabled = typeof window !== 'undefined' && window.vr_enabled;
                if (panorama.protected && !live_session_connected && !vr_enabled) {
                    img_s = '<img data-id-room="' + id + '" style=\'filter:blur(16px);\' src="' + (s3_enabled ? s3_url : '') + thumb + '">';
                } else {
                    img_s = '<img data-id-room="' + id + '" src="' + (s3_enabled ? s3_url : '') + thumb + '">';
                }
                var learning_disabled = "";
                var learning_mode = typeof window !== 'undefined' && window.learning_mode;
                var learning_unlock_marker = typeof window !== 'undefined' && window.learning_unlock_marker;
                if (learning_mode > 0 && learning_unlock_marker) {
                    if (typeof learning_check_marker_locked === 'function' && learning_check_marker_locked(id)) {
                        learning_disabled = 'disabled_l';
                    }
                }
                var pano_props = {
                    protected: panorama.protected, min_yaw: panorama.min_yaw, haov: panorama.haov,
                    vaov: panorama.vaov, hfov: panorama.hfov, max_yaw: panorama.max_yaw,
                    img_path: img
                };
                var roomMapKey = "r_" + id;
                var roomCategoryInfo = array_panoramas_category[roomMapKey];
                if (roomCategoryInfo !== undefined) {
                    var immediateCategoryId = roomCategoryInfo[0];
                    var $immediateParentSlideeUL = immediateCategoryId === null ? $('#list_slider_main .slidee') : $('#slidee_cat_' + immediateCategoryId);
                    if ($immediateParentSlideeUL.length > 0) {
                        if (!i_slider_cat[immediateCategoryId]) i_slider_cat[immediateCategoryId] = 1;
                        var roomLiHtml =
                            '<li data-index_id="' + i_slider_cat[immediateCategoryId] + '" data-id="' + id + '" data-id-category="' + immediateCategoryId + '" ' +
                            'data-protected="' + pano_props.protected + '" data-min_yaw="' + pano_props.min_yaw + '" data-haov="' + pano_props.haov + '" ' +
                            'data-vaov="' + pano_props.vaov + '" data-hfov="' + pano_props.hfov + '" data-max_yaw="' + pano_props.max_yaw + '" ' +
                            'data-panorama="' + (pano_props.img_path ? pano_props.img_path.replace('panoramas/','') : '') + '" ' +
                            'class="disabled ' + learning_disabled + ' pointer_list pointer_list_' + id + '">' +
                            '<div id="panorama_preview_' + id + '" class="panorama_preview"></div>' +
                            (img_s || '') +
                            '<span class="noselect room_name_slider"><i class="fas fa-spin fa-circle-notch"></i>' + nome + '</span>' +
                            '<div class="stat_visitors_rt_rooms hidden"><i class="fas fa-user"></i>&nbsp;<span id="count_visitors_rt_room_' + id + '">0</span></div>' +
                            '<span class="room_visited room_visited_' + id + '"><i class="fas fa-check"></i></span>' +
                            '</li>';
                        $immediateParentSlideeUL.append(roomLiHtml);
                        i_slider_cat[immediateCategoryId]++;
                    }
                } else {
                    var $mainSlidee = $('#list_slider_main .slidee');
                    if ($mainSlidee.length > 0) {
                        var uncatRoomHtml =
                            '<li data-index_id="' + i_slider + '" data-id="' + id + '" data-id-category="0" ' +
                            'data-protected="' + pano_props.protected + '" data-min_yaw="' + pano_props.min_yaw + '" data-haov="' + pano_props.haov + '" ' +
                            'data-vaov="' + pano_props.vaov + '" data-hfov="' + pano_props.hfov + '" data-max_yaw="' + pano_props.max_yaw + '" ' +
                            'data-panorama="' + (pano_props.img_path ? pano_props.img_path.replace('panoramas/','') : '') + '" ' +
                            'class="disabled ' + learning_disabled + ' pointer_list pointer_list_' + id + '">' +
                            '<div id="panorama_preview_' + id + '" class="panorama_preview"></div>' +
                            (img_s || '') +
                            '<span class="noselect room_name_slider"><i class="fas fa-spin fa-circle-notch"></i>' + nome + '</span>' +
                            '<div class="stat_visitors_rt_rooms hidden"><i class="fas fa-user"></i>&nbsp;<span id="count_visitors_rt_room_' + id + '">0</span></div>' +
                            '<span class="room_visited room_visited_' + id + '"><i class="fas fa-check"></i></span>' +
                            '</li>';
                        $mainSlidee.append(uncatRoomHtml);
                        i_slider++;
                    }
                }
            } catch (error) {
                console.error(error);
            }
        }
        $('.pointer_list_cat').each(function() {
            var $categoryLi = $(this);
            var categoryId = $categoryLi.data('id-category');
            if (categoryId && typeof array_panoramas_category !== 'undefined') {
                var totalRooms = countTotalRoomsRecursive(categoryId, array_panoramas_category);
                $categoryLi.attr('data-count', totalRooms);
                $categoryLi.find('.room_count_slider').html(totalRooms);
                var $imageGrid = $categoryLi.find('.cat_image_grid');
                $imageGrid.empty();
                var thumbsAdded = 0;
                var thumbsHtml = '';
                var roomIdsInGrid = {};
                function collectThumbsRecursive(catId, limit, visited = new Set()) {
                    if (thumbsAdded >= limit || visited.has(catId)) return;
                    visited.add(catId);
                    var $sliderUL = $('#slidee_cat_' + catId);
                    if ($sliderUL.length === 0) return;
                    $sliderUL.children('li.pointer_list:not(.pointer_list_cat):not(.pointer_list_back)').each(function() {
                        if (thumbsAdded < limit) {
                            var roomId = $(this).data('id');
                            if (roomId && !roomIdsInGrid[roomId]) {
                                var $thumb = $(this).find('img[data-id-room]').first();
                                if ($thumb.length > 0) {
                                    thumbsHtml += $thumb.prop('outerHTML');
                                    thumbsAdded++;
                                    roomIdsInGrid[roomId] = true;
                                }
                            }
                        }
                    });
                    if (thumbsAdded < limit) {
                        $sliderUL.children('li.pointer_list_cat').each(function() {
                            if (thumbsAdded < limit) {
                                var subCatId = $(this).data('id-category');
                                if (subCatId) {
                                    collectThumbsRecursive(subCatId, limit, visited);
                                }
                            }
                        });
                    }
                }
                collectThumbsRecursive(categoryId, 6);
                $imageGrid.append(thumbsHtml);
                var gridClassCount = Math.min(thumbsAdded, 6);
                $imageGrid.removeClass('i1 i2 i3 i4 i5 i6');
                if (gridClassCount > 0) {
                    $imageGrid.addClass('i' + gridClassCount);
                }
            }
        });
        try {
            var nav_slider = typeof window !== 'undefined' ? window.nav_slider : 1;
            var is_mobile = typeof window !== 'undefined' && window.is_mobile;
            if (nav_slider == 2 || (is_mobile && nav_slider == 1)) {
                $('.list_sliders .list_left').addClass('hidden');
                $('.list_sliders .list_right').addClass('hidden');
            }
            if (typeof len !== 'undefined') {
                len = imgs.length;
            }
        } catch (finalError) {
            console.error(finalError);
        }
    }

    function initialize_measures(index) {
        for(var i=0; i<measure_rooms.length; i++) {
            measure_rooms[i].index_line = '';
        }
        window.measure_lines = [];
        var index_line = 0;
        for(var i=0; i<measure_rooms.length; i++) {
            if(parseInt(measure_rooms[i].id_room)===parseInt(panoramas[index].id)) {
                var id_line = parseInt(measure_rooms[i].id);
                var params = JSON.parse(measure_rooms[i].params);
                var label = measure_rooms[i].label;
                measure_rooms[i].index_line = index_line;
                window.measure_lines[index_line] = new LeaderLine(
                    LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_start'), x: 0, y: 0}),
                    LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_end'), x: 0, 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, fontSize: params.size_text+'px', outlineColor: params.color_outline_text})
                    }
                );
                index_line++;
            }
        }
        $(".leader-line").detach().appendTo("#panorama_viewer .pnlm-dragfix");
        adjust_measurements();
    }

    function initialize_measures_alt(index) {
        for(var i=0; i<measure_rooms_alt.length; i++) {
            measure_rooms_alt[i].index_line = '';
        }
        window.measure_lines_alt = [];
        var index_line = 0;
        for(var i=0; i<measure_rooms_alt.length; i++) {
            if(parseInt(measure_rooms_alt[i].id_room)===parseInt(panoramas[index].id)) {
                var id_line = parseInt(measure_rooms_alt[i].id);
                var params = JSON.parse(measure_rooms_alt[i].params);
                var label = measure_rooms_alt[i].label;
                measure_rooms_alt[i].index_line = index_line;
                window.measure_lines_alt[index_line] = new LeaderLine(
                    LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_start_alt'), x: 0, y: 0}),
                    LeaderLine.pointAnchor({element: document.getElementById('measure_'+id_line+'_end_alt'), x: 0, 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, fontSize: params.size_text+'px', outlineColor: params.color_outline_text})
                    }
                );
                index_line++;
            }
        }
        $('.leader-line').each(function() {
            if ($(this).parent(':not(.pnlm-dragfix)').length) {
                $(this).detach().appendTo("#panorama_viewer_alt .pnlm-dragfix");
            }
        });
        adjust_measurements();
    }

    window.adjust_measurements = function() {
        for(var i=0; i<measure_rooms.length; i++) {
            if(measure_rooms[i].index_line!=='') {
                var id_line = measure_rooms[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[measure_rooms[i].index_line].hide('none', {duration: 0});
                } else {
                    window.measure_lines[measure_rooms[i].index_line].show('fade', {duration: 100});
                    window.measure_lines[measure_rooms[i].index_line].position();
                }
            }
        }
        for(var i=0; i<measure_rooms_alt.length; i++) {
            if(measure_rooms_alt[i].index_line!=='') {
                var id_line = measure_rooms_alt[i].id;
                if($('#measure_'+id_line+'_start_alt').length) {
                    var visible_start = $('#measure_'+id_line+'_start_alt').parent().css('visibility');
                    var visible_end = $('#measure_'+id_line+'_end_alt').parent().css('visibility');
                    if(visible_start=='hidden' || visible_end=='hidden') {
                        window.measure_lines_alt[measure_rooms_alt[i].index_line].hide('none', {duration: 0});
                    } else {
                        window.measure_lines_alt[measure_rooms_alt[i].index_line].show('fade', {duration: 100});
                        window.measure_lines_alt[measure_rooms_alt[i].index_line].position();
                    }
                }
            }
        }
        var x = $('#vt_container').offset().left;
        var y = $('#vt_container').offset().top;
        $('.leader-line').css('transform','translate(-'+x+'px,-'+y+'px)');
        if (!controls_status['measures']) {
            $('.leader-line').addClass('hidden_icons');
        } else {
            $('.leader-line').removeClass('hidden_icons');
        }
    };

    function hotspot_measure(hotSpotDiv, args) {
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        var div = document.createElement('div');
        div.id = 'measure_'+args.id+'_'+args.dir;
        div.innerHTML = '';
        hotSpotDiv.appendChild(div);
    }

    window.empty_function = function () {};

    window.toggle_lead_already = function () {
        if($('#lead_input_already').is(':checked')) {
            $('#lead_name').parent().addClass('disabled');
            $('#lead_company').parent().addClass('disabled');
            $('#lead_phone').parent().addClass('disabled');
            $('#lead_name').removeAttr('required');
            $('#lead_company').removeAttr('required');
            $('#lead_phone').removeAttr('required');
        } else {
            $('#lead_name').parent().removeClass('disabled');
            $('#lead_company').parent().removeClass('disabled');
            $('#lead_phone').parent().removeClass('disabled');
            if($('#lead_name').attr('data-required')==1) {
                $('#lead_name').attr('required','');
            }
            if($('#lead_company').attr('data-required')==1) {
                $('#lead_company').attr('required','');
            }
            if($('#lead_phone').attr('data-required')==1) {
                $('#lead_phone').attr('required','');
            }
        }
    }

    window.toggle_lead_already_vt = function () {
        if($('#lead_input_already_vt').is(':checked')) {
            $('#lead_name_vt').parent().addClass('disabled');
            $('#lead_company_vt').parent().addClass('disabled');
            $('#lead_phone_vt').parent().addClass('disabled');
            $('#lead_name_vt').removeAttr('required');
            $('#lead_company_vt').removeAttr('required');
            $('#lead_phone_vt').removeAttr('required');
        } else {
            $('#lead_name_vt').parent().removeClass('disabled');
            $('#lead_company_vt').parent().removeClass('disabled');
            $('#lead_phone_vt').parent().removeClass('disabled');
            if($('#lead_name_vt').attr('data-required')==1) {
                $('#lead_name_vt').attr('required','');
            }
            if($('#lead_company_vt').attr('data-required')==1) {
                $('#lead_company_vt').attr('required','');
            }
            if($('#lead_phone_vt').attr('data-required')==1) {
                $('#lead_phone_vt').attr('required','');
            }
        }
    }

    function view_protect_form(cb,id) {
        var protect_type = panoramas[id].protect_type;
        if(panoramas[id].protected && !live_session_connected && !vr_enabled) {
            $('.panorama').css('filter','blur(16px)');
            $('#background_pano').css('filter','blur(16px)');
            $('.custom-hotspot-content').addClass("hidden_p");
            $('.header-line').addClass("hidden_p");
            $('.custom-hotspot').addClass("hidden_p");
            $('.custom-hotspot img').addClass("hidden_p");
            switch(protect_type) {
                case 'passcode':
                    $('.passcode_div h2').html(panoramas[id].passcode_title.toUpperCase());
                    $('.passcode_div p').html(panoramas[id].passcode_description);
                    if(!cb) {
                        setTimeout(function () {
                            $('.passcode_div').show();
                        },2000);
                    } else {
                        $('.passcode_div').show();
                    }
                    break;
                case 'leads':
                    var protect_lead_params = JSON.parse(panoramas[id].protect_lead_params);
                    if(parseInt(protect_lead_params.protect_email_enabled)==1 && parseInt(protect_lead_params.protect_email_mandatory)==1) {
                        $('#lead_input_already').parent().show();
                    } else {
                        $('#lead_input_already').parent().hide();
                    }
                    if(parseInt(protect_lead_params.protect_name_enabled)==1) {
                        $('#lead_name').parent().show();
                    } else {
                        $('#lead_name').parent().hide();
                    }
                    $('#lead_name').attr('data-required',protect_lead_params.protect_name_mandatory);
                    var label = $('#lead_name').parent().find('label').html();
                    if(parseInt(protect_lead_params.protect_name_mandatory)==1) {
                        if (!label.endsWith(" *")) {
                            label = label + " *";
                        }
                        $('#lead_name').attr('required','');
                    } else {
                        if (label.endsWith(" *")) {
                            label = label.replace(/ \*$/, '');
                        }
                        $('#lead_name').removeAttr('required');
                    }
                    $('#lead_name').parent().find('label').html(label);
                    if(parseInt(protect_lead_params.protect_company_enabled)==1) {
                        $('#lead_company').parent().show();
                    } else {
                        $('#lead_company').parent().hide();
                    }
                    $('#lead_company').attr('data-required',protect_lead_params.protect_company_mandatory);
                    var label = $('#lead_company').parent().find('label').html();
                    if(parseInt(protect_lead_params.protect_company_mandatory)==1) {
                        if (!label.endsWith(" *")) {
                            label = label + " *";
                        }
                        $('#lead_company').attr('required','');
                    } else {
                        if (label.endsWith(" *")) {
                            label = label.replace(/ \*$/, '');
                        }
                        $('#lead_company').removeAttr('required');
                    }
                    $('#lead_company').parent().find('label').html(label);
                    if(parseInt(protect_lead_params.protect_email_enabled)==1) {
                        $('#lead_email').parent().show();
                    } else {
                        $('#lead_email').parent().hide();
                    }
                    $('#lead_email').attr('data-required',protect_lead_params.protect_email_mandatory);
                    var label = $('#lead_email').parent().find('label').html();
                    if(parseInt(protect_lead_params.protect_email_mandatory)==1) {
                        if (!label.endsWith(" *")) {
                            label = label + " *";
                        }
                        $('#lead_email').attr('required','');
                    } else {
                        if (label.endsWith(" *")) {
                            label = label.replace(/ \*$/, '');
                        }
                        $('#lead_email').removeAttr('required');
                    }
                    $('#lead_email').parent().find('label').html(label);
                    if(parseInt(protect_lead_params.protect_phone_enabled)==1) {
                        $('#lead_phone').parent().show();
                    } else {
                        $('#lead_phone').parent().hide();
                    }
                    $('#lead_phone').attr('data-required',protect_lead_params.protect_phone_mandatory);
                    var label = $('#lead_phone').parent().find('label').html();
                    if(parseInt(protect_lead_params.protect_phone_mandatory)==1) {
                        if (!label.endsWith(" *")) {
                            label = label + " *";
                        }
                        $('#lead_phone').attr('required','');
                    } else {
                        if (label.endsWith(" *")) {
                            label = label.replace(/ \*$/, '');
                        }
                        $('#lead_phone').removeAttr('required');
                    }
                    $('#lead_phone').parent().find('label').html(label);
                    $('.leads_div h2').html(panoramas[id].passcode_title.toUpperCase());
                    $('.leads_div p').html(panoramas[id].passcode_description);
                    $('#protect_email').val(panoramas[id].protect_email);
                    if(!cb) {
                        setTimeout(function () {
                            $('.leads_div').show();
                        },2000);
                    } else {
                        $('.leads_div').show();
                    }
                    break;
                case 'mailchimp':
                    var html_form = '<i onclick="close_protect_form();" id="btn_close_mc_form" class="fas fa-times"></i><div style="color:black;" id="lead_mc_form_room">'+panoramas[id].protect_mc_form+'</div>';
                    $('.mailchimp_form_div').html(html_form).promise().done(function () {
                        if(!cb) {
                            setTimeout(function () {
                                $('.mailchimp_form_div').show();
                            },2000);
                        } else {
                            $('.mailchimp_form_div').show();
                        }
                    });
                    break;
            }
        } else {
            $('.panorama').css('filter','none');
            apply_room_filters(panoramas[id].filters,'pano');
            $('.custom-hotspot-content').removeClass("hidden_p");
            $('.header-line').removeClass("hidden_p");
            $('.custom-hotspot').removeClass("hidden_p");
            $('.custom-hotspot img').removeClass("hidden_p");
            $('.passcode_div').hide();
            $('.leads_div').hide();
        }
    }

    window.check_mc_subscribe_room = function() {
        var id = get_id_viewer(current_id_panorama);
        var id_room = panoramas[id].id;
        var protect_remember = panoramas[id].protect_remember;
        if(protect_remember==1) {
            setCookie('svt_mc_'+window.id_virtualtour+'_'+id_room,1,365);
        }
        panoramas[id].protected = 0;
        $('.panorama').css('filter','none');
        apply_room_filters(panoramas[id].filters,'pano');
        $('.pointer_list_'+id_room+' img').css('filter','none');
        $('.pointer_list_cat img[data-id-room="'+id_room+'"]').css('filter','none');
        $('.custom-hotspot-content').removeClass("hidden_p");
        $('.header-line').removeClass("hidden_p");
        $('.custom-hotspot').removeClass("hidden_p");
        $('.custom-hotspot img').removeClass("hidden_p");
        $('.arrows_nav').removeClass("hidden_p");
        $('.mailchimp_form_div').hide();
        $('.mailchimp_form_div').empty();
    }

    window.close_protect_form = function () {
        if(array_id_room_nav.length>1) {
            var id_room = array_id_room_nav[array_id_room_nav.length-2];
            goto('',[id_room,null,null,null,null,null,null,null]);
        }
    }

    window.check_passcode = function () {
        var passcode = $('#passcode').val();
        var id = get_id_viewer(current_id_panorama);
        var id_room = panoramas[id].id;
        var protect_pc = panoramas[id].protect_pc;
        var protect_remember = panoramas[id].protect_remember;
        if(passcode!='') {
            $('#btn_check_passcode').addClass("disabled");
            $.ajax({
                url: "ajax/check_passcode.php",
                type: "POST",
                data: {
                    id_room: id_room,
                    passcode: passcode
                },
                async: false,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        if(protect_remember==1) {
                            setCookie('svt_pc_'+window.id_virtualtour+'_'+id_room+'_'+protect_pc,1,365);
                        }
                        $('#btn_check_passcode').css('color','green');
                        setTimeout(function () {
                            panoramas[id].protected = 0;
                            $('.panorama').css('filter','none');
                            apply_room_filters(panoramas[id].filters,'pano');
                            $('.pointer_list_'+id_room+' img').css('filter','none');
                            $('.pointer_list_cat img[data-id-room="'+id_room+'"]').css('filter','none');
                            $('.custom-hotspot-content').removeClass("hidden_p");
                            $('.header-line').removeClass("hidden_p");
                            $('.custom-hotspot').removeClass("hidden_p");
                            $('.custom-hotspot img').removeClass("hidden_p");
                            $('.arrows_nav').removeClass("hidden_p");
                            $('.passcode_div').hide();
                            $('#btn_check_passcode').css('color','black');
                            $('#btn_check_passcode').removeClass("disabled");
                        },250);
                    } else {
                        $('#btn_check_passcode').css('color','red');
                        setTimeout(function () {
                            $('#btn_check_passcode').css('color','black');
                            $('#btn_check_passcode').removeClass("disabled");
                        },250);
                        $('#passcode').val('');
                        $('#passcode').focus();
                    }
                }
            });
        }
    }

    $(".form_leads").submit(function(e){
        var lead_name = $('#lead_name').val();
        var lead_company = $('#lead_company').val();
        var lead_email = $('#lead_email').val();
        var lead_phone = $('#lead_phone').val();
        $('#btn_check_leads').addClass("disabled");
        if($('#lead_input_already').is(':checked')) var check=1; else var check=0;
        $.ajax({
            url: "ajax/store_lead.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                name: lead_name,
                company: lead_company,
                email: lead_email,
                phone: lead_phone,
                check: check
            },
            async: false,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    var index = get_id_viewer(current_id_panorama);
                    var protect_remember = panoramas[index].protect_remember;
                    if(protect_remember==1) {
                        setCookie('svt_l_'+window.id_virtualtour+'_'+current_id_panorama,1,365);
                    }
                    var email = $('#protect_email').val();
                    if(email!='' && check==0) {
                        var room_name = panoramas[index].name;
                        $.ajax({
                            url: "../backend/ajax/send_email.php",
                            type: "POST",
                            data: {
                                type: 'lead',
                                email: email,
                                vt_name: window.name_vt,
                                room_name: room_name,
                                lead_name: lead_name,
                                lead_company: lead_company,
                                lead_email: lead_email,
                                lead_phone: lead_phone
                            },
                            timeout: 15000,
                            async: true,
                            success: function () {}
                        });
                    }
                    $('#btn_check_leads').css('color','green');
                    setTimeout(function () {
                        for(var i=0; i < panoramas.length; i++) {
                            var protect_type = panoramas[i].protect_type;
                            if(protect_type=='leads') {
                                panoramas[i].protected = 0;
                                var id_room = panoramas[i].id;
                                $('.pointer_list_'+id_room+' img').css('filter','none');
                                $('.pointer_list_cat img[data-id-room="'+id_room+'"]').css('filter','none');
                            }
                        }
                        $('.panorama').css('filter','none');
                        $('#background_pano').css('filter','none');
                        $('.custom-hotspot-content').removeClass("hidden_p");
                        $('.header-line').removeClass("hidden_p");
                        $('.custom-hotspot').removeClass("hidden_p");
                        $('.custom-hotspot img').removeClass("hidden_p");
                        $('.arrows_nav').removeClass("hidden_p");
                        $('.leads_div').hide();
                        $('#btn_check_leads').css('color','black');
                        $('#btn_check_leads').removeClass("disabled");
                    },250);
                } else {
                    $('#btn_check_leads').css('color','red');
                    setTimeout(function () {
                        $('#btn_check_leads').css('color','black');
                        $('#btn_check_leads').removeClass("disabled");
                    },250);
                }
            }
        });
        e.preventDefault();
    });

    $(".form_leads_vt").submit(function(e){
        var lead_name = $('#lead_name_vt').val();
        var lead_company = $('#lead_company_vt').val();
        var lead_email = $('#lead_email_vt').val();
        var lead_phone = $('#lead_phone_vt').val();
        $('#btn_check_leads_vt').addClass("disabled");
        if($('#lead_input_already_vt').is(':checked')) var check=1; else var check=0;
        $.ajax({
            url: "ajax/store_lead.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                name: lead_name,
                company: lead_company,
                email: lead_email,
                phone: lead_phone,
                check: check
            },
            async: false,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    if(window.protect_remember==1) {
                        setCookie('svt_lvt_'+window.id_virtualtour,1,365);
                    }
                    var email = $('#protect_email_vt').val();
                    if(email!='' && check==0) {
                        $.ajax({
                            url: "../backend/ajax/send_email.php",
                            type: "POST",
                            data: {
                                type: 'lead',
                                email: email,
                                vt_name: window.name_vt,
                                lead_name: lead_name,
                                lead_company: lead_company,
                                lead_email: lead_email,
                                lead_phone: lead_phone
                            },
                            timeout: 15000,
                            async: true,
                            success: function () {}
                        });
                    }
                    $('#btn_check_leads_vt').addClass('ok_lead');
                    setTimeout(function() {
                        $('.progress-circle').fadeIn();
                        $('.protect').fadeOut();
                        if(window.hide_loading==1) {
                            $('.loading').addClass('hidden');
                            $('#background_loading').removeClass('background_opacity');
                        }
                        get_rooms(window.code);
                    },500);
                } else {
                    $('#btn_check_leads_vt').addClass('error_lead');
                    setTimeout(function () {
                        $('#btn_check_leads_vt').removeClass('error_lead');
                        $('#btn_check_leads_vt').removeClass("disabled");
                    },250);
                }
            }
        });
        e.preventDefault();
    });

    window.check_mc_subscribe_vt = function() {
        if(window.protect_remember==1) {
            setCookie('svt_mcvt_' + window.id_virtualtour, 1, 365);
        }
        $('.progress-circle').fadeIn();
        $('.protect').fadeOut();
        if(window.hide_loading==1) {
            $('.loading').addClass('hidden');
            $('#background_loading').removeClass('background_opacity');
        }
        get_rooms(window.code);
    }

    window.check_password_vt = function () {
        var password = $('#vt_password').val();
        if(password!='') {
            $('#btn_check_password').addClass('disabled');
            $.ajax({
                url: "ajax/check_password_vt.php",
                type: "POST",
                data: {
                    code: window.code,
                    password: password
                },
                async: false,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.status=='ok') {
                        if(window.protect_remember==1) {
                            setCookie('svt_pcvt_' + window.id_virtualtour + '_' + window.protect_pc, 1, 365);
                        }
                        $('#btn_check_password').removeClass("disabled");
                        $('#btn_check_password').css('pointer-events','none');
                        $('#btn_check_password').addClass('ok_lead');
                        setTimeout(function() {
                            $('.progress-circle').fadeIn();
                            $('.protect').fadeOut();
                            if(window.hide_loading==1) {
                                $('.loading').addClass('hidden');
                                $('#background_loading').removeClass('background_opacity');
                            }
                            get_rooms(window.code);
                        },500);
                    } else {
                        $('#btn_check_password').removeClass("disabled");
                        $('#btn_check_password').css('pointer-events','none');
                        $('#btn_check_password').addClass('error_lead');
                        setTimeout(function () {
                            $('#btn_check_password').removeClass('error_lead');
                            $('#btn_check_password').css('pointer-events','initial');
                        },250);
                        $('#vt_password').val('');
                    }
                }
            });
        }
    }

    window.skip_video_intro = function() {
        window.video_loading_ended = true;
        clearInterval(interval_video_loading_check);
        clearInterval(window.interval_background_video_elapsed);
        $('#skip_video_intro').hide();
        if(window.initial_yaw!='') {
            var yaw_i = parseFloat(window.initial_yaw);
        } else {
            var yaw_i = null;
        }
        if(window.initial_pitch!='') {
            var pitch_i = parseFloat(window.initial_pitch);
        } else {
            var pitch_i = null;
        }
        initialize_room(index_initial,false,false,pitch_i,yaw_i,null, null,false);
        setTimeout(function() {
            switch(window.flyin) {
                case 0:
                    complete_init();
                    break;
                case 1:
                    init_flyin(panoramas[index_initial].panorama_image,panoramas[index_initial].yaw,panoramas[index_initial].pitch);
                    break;
                case 2:
                    init_flyin_lp(panoramas[index_initial].panorama_image,panoramas[index_initial].yaw,panoramas[index_initial].pitch,hfov);
                    break;
            }
        },1000);
    }

    window.start_vt = function () {
        if(window.show_fullscreen==2) toggle_fullscreen();
        $('#icon_play').hide();
        if($('#video_loading').length) {
            if (!(document.getElementById('video_loading').paused) && !(document.getElementById('video_loading').ended) && document.getElementById('video_loading').readyState > 2) {

            } else {
                document.getElementById('video_loading').play().then(() => {
                    $('#video_loading').css('opacity',1);
                }).catch(error => {
                    document.getElementById('video_loading').muted = true;
                    document.getElementById('video_loading').play();
                    $('#video_loading').css('opacity',1);
                });
            }
        }
        if(window.password_protected && window.export_mode==0) {
            switch(window.protect_type) {
                case 'lead':
                    var cookie_l = getCookie('svt_lvt_'+window.id_virtualtour);
                    if(cookie_l) {
                        if(cookie_l==1 && window.protect_remember==1) {
                            if(window.hide_loading==1) {
                                $('.loading').addClass('hidden');
                                $('#background_loading').removeClass('background_opacity');
                            }
                            get_rooms(code);
                        } else {
                            show_password_input();
                        }
                    } else {
                        show_password_input();
                    }
                    break;
                case 'password':
                    var cookie_pc = getCookie('svt_pcvt_'+window.id_virtualtour+'_'+window.protect_pc);
                    if(cookie_pc) {
                        if(cookie_pc==1 && window.protect_remember==1) {
                            if(window.hide_loading==1) {
                                $('.loading').addClass('hidden');
                                $('#background_loading').removeClass('background_opacity');
                            }
                            get_rooms(code);
                        } else {
                            show_password_input();
                        }
                    } else {
                        show_password_input();
                    }
                    break;
                case 'mailchimp':
                    var height = $('.progress').height();
                    $('.protect_mc').css('max-height','calc(100% - '+(height+46)+'px)')
                    var cookie_mc = getCookie('svt_mcvt_'+window.id_virtualtour);
                    if(cookie_mc) {
                        if(cookie_mc==1 && window.protect_remember==1) {
                            if(window.hide_loading==1) {
                                $('.loading').addClass('hidden');
                                $('#background_loading').removeClass('background_opacity');
                            }
                            get_rooms(code);
                        } else {
                            show_password_input();
                        }
                    } else {
                        show_password_input();
                    }
                    break;
            }
        } else {
            if(window.hide_loading==1) {
                $('.loading').addClass('hidden');
                $('#background_loading').removeClass('background_opacity');
            }
            get_rooms(code);
        }
    }

    window.show_password_input = function () {
        $('.progress-circle').fadeOut();
        $('#progress_msg').hide();
        $('.protect').fadeIn();
        $('.loading').removeClass('hidden');
        $('#background_loading').addClass('background_opacity');
        $(document).keyup(function(event) {
            if($('.protect').is(':visible')) {
                if (event.key == "Enter") {
                    event.preventDefault();
                    check_password_vt();
                }
            }
        });
    }

    window.show_icon_play = function () {
        progress_circle.setText('');
        progress_circle.set(0);
        $('.progress-circle').fadeIn();
        $('#progress_msg').hide();
        $('#icon_play').fadeIn();
        $('.loading').removeClass('hidden');
        $('#background_loading').addClass('background_opacity');
    }

    function IsNaN(o) {
        return typeof(o) === 'number' && isNaN(o);
    }

    window.zoom_map = function () {
        if(show_map!=4) {
            if($(".map").hasClass("map_zoomed")) {
                $(".map").removeClass('map_zoomed');
                $('#map_zoomed_background').hide();
                $('.map_zoom_control i').addClass('fa-expand-alt').removeClass('fa-compress-alt');
            } else {
                $(".map").addClass('map_zoomed');
                $('#map_zoomed_background').show();
                $('.map_zoom_control i').removeClass('fa-expand-alt').addClass('fa-compress-alt');
            }
            resize_maps();
        } else {
            toggle_map();
        }
        try {
            var id = get_id_viewer(current_id_panorama);
            if(!isNaN(panoramas[id].id_map)) {
                panzoom_map[panoramas[id].id_map].reset();
                $('.map_zoom_minus_control').css({'opacity':0.5,'pointer-events':'none'});
                $('.map_zoom_plus_control').css({'opacity':1,'pointer-events':'initial'});
            }
        } catch (e) {}
    }

    window.zoom_floorplan_minus = function () {
        var id = get_id_viewer(current_id_panorama);
        if(!isNaN(panoramas[id].id_map)) {
            panzoom_map[panoramas[id].id_map].zoomOut();
        }
    }
    window.zoom_floorplan_plus = function () {
        var id = get_id_viewer(current_id_panorama);
        if(!isNaN(panoramas[id].id_map)) {
            panzoom_map[panoramas[id].id_map].zoomIn();
        }
    }

    function hexToRgb(hex) {
        var hex=hex.replace('#', '');
        var bigint = parseInt(hex, 16);
        var r = (bigint >> 16) & 255;
        var g = (bigint >> 8) & 255;
        var b = bigint & 255;
        return r + "," + g + "," + b;
    }

    function hexToRgba(hex, alpha = 1) {
        hex = hex.replace(/^#/, '');
        if (hex.length === 3) {
            hex = hex.split('').map(char => char + char).join('');
        }
        if (hex.length !== 6) {
            throw new Error("Invalid hex color.");
        }
        const bigint = parseInt(hex, 16);
        const r = (bigint >> 16) & 255;
        const g = (bigint >> 8) & 255;
        const b = bigint & 255;
        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }

    function percentage(partialValue, totalValue) {
        return (100 * partialValue) / totalValue;
    }

    function loading_config() {
        if(window.logo!='') {
            if(window.link_logo!='') {
                html_logo = "<img style='cursor:pointer;pointer-events:initial' onclick=\"window.open('"+window.link_logo+"', '_blank');\" class='noselect' draggable=\"false\" src=\""+((window.s3_enabled) ? window.s3_url : '')+"content/"+logo+"\">";
            } else {
                html_logo = "<img class='noselect' draggable=\"false\" src=\""+((window.s3_enabled) ? window.s3_url : '')+"content/"+logo+"\">";
                $('.logo').addClass('poi_not_selectable');
            }
        }
        if(array_maps.length>0) {
            html_map = '';
            for(var i=0; i < array_maps.length; i++) {
                var map_width_m = array_maps[i].width_m;
                var map_width_d = array_maps[i].width_d;
                if((window.innerWidth<540) || (window.innerHeight<540)) {
                    var map_width = map_width_m;
                } else {
                    var map_width = map_width_d;
                }
                if(array_maps[i].info_link!='') {
                    var info_map = '<i onclick="open_info_map(\''+array_maps[i].info_link+'\',\''+array_maps[i].info_type+'\');" class="fas fa-info-circle info_map_btn"></i>&nbsp;&nbsp;';
                } else {
                    var info_map = '';
                }
                html_map += "<div data-id='"+array_maps[i].id+"' class='all_maps map_"+array_maps[i].id+"'>";
                html_map += "<div class='map_wrapper'>";
                html_map += "<img data-map_width_d='"+map_width_d+"' data-map_width_m='"+map_width_m+"' style='width:"+map_width+"px;' class='map_image' draggable=\"false\" src=\""+((window.s3_enabled) ? window.s3_url : '')+"maps/"+array_maps[i].map+"\">";
                for(var j=0; j < panoramas.length; j++) {
                    if(panoramas[j].id_map==array_maps[i].id) {
                        var bg_color = '#000000';
                        var point_size = 20;
                        var map_ratio = 1.0;
                        var view_size = 80;
                        var view_color = '#000000';
                        if(array_maps[i].id==panoramas[j].id_map) {
                            panoramas[j].map_north = array_maps[i].north_degree;
                            map_ratio = parseFloat(array_maps[i].map_ratio);
                        }
                        if(!IsNaN(panoramas[j].map_top)) {
                            if(panoramas[j].id_map==array_maps[i].id) {
                                bg_color = array_maps[i].point_color;
                                point_size = parseInt(array_maps[i].point_size);
                                view_size = parseInt(array_maps[i].point_view_size);
                                view_color = array_maps[i].point_view_color;
                            }
                            var scale = point_size/20;
                            var map_left = percentage(panoramas[j].map_left,300);
                            var map_top = percentage(panoramas[j].map_top,300/map_ratio);
                            var rgb = hexToRgb(bg_color);
                            var learning_disabled = "";
                            if(window.learning_mode>0) {
                                if(window.learning_unlock_marker) {
                                    if(learning_check_marker_locked(panoramas[j].id)) {
                                        learning_disabled = 'disabled_l';
                                    }
                                }
                            }
                            html_map += "<div data-scale='"+scale+"' style='transform: rotate(0deg) scale("+scale+");top:"+map_top+"%;left:"+map_left+"%;' id='pointer_f_"+panoramas[j].id+"' class='disabled hide "+learning_disabled+" map_pointer_container pointer_map_"+panoramas[j].id_map+"'><i style='margin-top:10px;font-size:21px !important;vertical-align:top;' class=\"fas fa-spin fa-circle-notch\"></i><div style='width:"+(view_size*2)+"px;height:"+(view_size*2)+"px;' data-view-size='"+view_size+"' data-view-color='"+view_color+"' class=\"map_pointer_view\"></div><div style='width:"+point_size+"px;height:"+point_size+"px;background-color:"+bg_color+";border-color:"+rgb+";' title=\""+panoramas[j].name+"\" data-id='"+panoramas[j].id+"' class=\"map_pointer_circle\"></div></div>";
                        }
                    }
                }
                html_map += '</div>';
                html_map += "</div>";
            }
            html_map += "<div class='map_selector'>\n" +
                "<ul>\n";
            for(var i=0; i < array_maps.length; i++) {
                html_map += "<li onclick='change_map("+array_maps[i].id+");'><a class='noselect'>"+array_maps[i].name+"</a></li>\n";
            }
            html_map += "</ul>\n";
            html_map += "</div>";
            html_map += '<div class="map_bar">';
            html_map += '<div onclick="open_map_selector();" class="map_selector_control small-element noselect"><i class="fas fa-layer-group"></i></div>';
            html_map += '<div class="map_name noselect"></div>';
            html_map += '<div class="map_controls_btn">';
            html_map += '<div onclick="zoom_floorplan_minus();" class="map_zoom_minus_control small-element noselect"><i class="fas fa-minus"></i></div>';
            html_map += '<div onclick="zoom_floorplan_plus();" class="map_zoom_plus_control small-element noselect"><i class="fas fa-plus"></i></div>';
            html_map += '<div onclick="zoom_map();" class="map_zoom_control small-element noselect"><i class="fas fa-expand-alt"></i></div>';
            html_map += '<div onclick="toggle_map();" class="map_close_control small-element noselect"><i class="fas fa-times-circle"></i></div>';
            html_map += '</div>';
            html_map += "</div>";
        }
        if(array_maps.length>0) {
            var image_map = array_maps[0].map;
            var id_map_image = panoramas[index_initial].id_map;
            if(!isNaN(id_map_image)) {
                for(var i=0; i < array_maps.length; i++) {
                    if(array_maps[i].id==id_map_image) {
                        image_map = array_maps[i].map;
                    }
                }
            }
            var image_map_load = new Image();
            image_map_load.crossOrigin = 'anonymous';
            $(image_map_load).on('load',function () {
                preload_first_image();
            }).on('error',function () {
                preload_first_image();
            }).attr('src',((window.s3_enabled) ? window.s3_url : '')+'maps/'+image_map+((window.s3_enabled) ? '?s3='+s3_version : ''));
        } else {
            preload_first_image();
        }
    }

    $(document).on("mousedown touchstart",function(e){
        if($('.intro_img').is(':visible')) {
            if(!audio_prompt_open && !announce_open) {
                $('.intro_img').fadeOut();
            }
        }
        var comments = $('.disqus_thread');
        var comments_control = $('#comments_control');
        var comments_count = $('.disqus-comment-count');
        var comments_div = $('.comments_vt');
        if ((!comments.is(e.target) && comments.has(e.target).length === 0) && (!comments_control.is(e.target) && comments_control.has(e.target).length === 0) && (!comments_count.is(e.target) && comments_count.has(e.target).length === 0) && (!comments_div.is(e.target) && comments_div.has(e.target).length === 0)) {
            $('#comments_div').hide();
            $('#comments_control').removeClass('active');
        }
        var map = $('.map');
        if (!map.is(e.target) && map.has(e.target).length === 0) {
            close_map_selector();
        }
        var menu = $('.menu_controls');
        if (!menu.is(e.target) && menu.has(e.target).length === 0) {
            close_menu_controls();
        }
        var menu_alt = $('.list_alt_menu');
        if (!menu_alt.is(e.target) && menu_alt.has(e.target).length === 0) {
            close_list_alt_menu();
        }
        var map_zoomed_background = $('#map_zoomed_background');
        if (map_zoomed_background.is(e.target)) {
            zoom_map();
        }
        if(presentation_inactivity!=0 && window.virtual_tour_initialized) {
            if(timeout_presentation_inactivity!=null) {
                clearTimeout(timeout_presentation_inactivity);
            }
            if((presentation_type=='video') && ($('.fancybox-video').is(':visible'))) { return; }
            if((presentation_type=='automatic' || presentation_type=='manual') && (controls_status['presentation'])) { return; }
            timeout_presentation_inactivity = setTimeout(function () {
                switch(presentation_type) {
                    case 'video':
                        $('.presentation_control').trigger('click');
                        break;
                    default:
                        start_presentation();
                        break;
                }
            },presentation_inactivity);
        }
    });

    document.addEventListener('keyup', event => {
        if($('.intro_img').is(':visible')) {
            if(!audio_prompt_open && !announce_open) {
                $('.intro_img').css('display','none');
            }
        }
        if ((event.code === 'Space') && (keyboard_mode != 0) && !$('.passcode_div').is(':visible')) {
            if(!live_session_connected) {
                if (!poi_open) {
                    $('.pnlm-pointer.hotspot_hover').trigger('click');
                    $('.pnlm-pointer.hotspot_hover a').trigger('click');
                }
            }
        }
        if (event.code === "Escape" && !$('.passcode_div').is(':visible')) {
            if(!live_session_connected) {
                poi_open = false;
                $('.pnlm-container').focus();
                $('.pnlm-container').trigger('click');
            }
        }
    });

    window.change_map = function(id) {
        $('.all_maps').hide();
        $('.map_pointer_container').hide();
        $('.map_'+id).show();
        $('.pointer_map_'+id).show();
        close_map_selector();
        resize_maps();
        for(var k=0; k < array_maps.length; k++) {
            if(array_maps[k].id==id) {
                if(array_maps[k].info_link!='') {
                    var info_map = '&nbsp;&nbsp;<i onclick="open_info_map(\''+array_maps[k].info_link+'\',\''+array_maps[k].info_type+'\');" class="fas fa-info-circle info_map_btn"></i>';
                } else {
                    var info_map = '';
                }
                $('.map_name').html(array_maps[k].name+info_map);
                var id_room_default = array_maps[k].id_room_default;
                if(id_room_default!='' && current_id_panorama!=id_room_default) {
                    goto('',[id_room_default,null,null,null,null,null,null,null]);
                }
                return;
            }
        }
    }

    window.open_map_selector = function () {
        if(array_maps.length>1) {
            if($('.map_selector').is(':visible')) {
                $('.map_image').removeClass('darker_img');
                $('.map_pointer_container').css('visibility', 'visible');
                $('.map_selector').hide();
                map_selector_open = false;
            } else {
                $('.map_image').addClass('darker_img');
                $('.map_pointer_container').css('visibility','hidden');
                $('.map_selector').css('display','flex');
                map_selector_open = true;
            }
        }
    }

    window.close_map_selector = function () {
        if(map_selector_open) {
            $('.map_image').removeClass('darker_img');
            $('.map_pointer_container').css('visibility', 'visible');
            $('.map_selector').hide();
            map_selector_open = false;
        }
    }

    function loadXHR(url,id,index) {
        if(window.s3_enabled==1) {
            url += "?s3="+s3_version;
        }
        return new Promise(function(resolve) {
            try {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", url);
                xhr.responseType = "blob";
                xhr.onerror = function() {resolve(["",id,index])};
                xhr.onload = function() {
                    if (xhr.status === 200) {resolve([xhr.response,id,index])}
                    else {resolve(["",id,index])}
                };
                xhr.send();
            }
            catch(err) {resolve(["",id,index])}
        });
    }

    function preload_dollhouse() {
        $('#progress_msg span').html(window.viewer_labels.progress_almost_done);
        if(show_dollhouse>0 && (json_dollhouse!='' || dollhouse_glb!='')) {
            progress_circle.animate(0.9);
            step_progress = 0.9;
            setTimeout(function() {
                init_dollhouse();
            },500);
        } else {
            progress_circle.animate(0.9);
            setTimeout(function() {
                initialize();
            },500);
        }
    }

    function preload_first_image() {
        if(panoramas[index_initial].multires && window.flyin==0) {
            $('#progress_msg span').html(window.viewer_labels.progress_almost_done);
            progress_circle.animate(0.8);
            setTimeout(function () {
                preload_dollhouse();
            },500);
        } else {
            var img = panoramas[index_initial].panorama_image;
            var id = panoramas[index_initial].id;
            $('#progress_msg span').html(window.viewer_labels.progress_loading_images);
            progress_circle.animate(0.5);
            interval_progress = setInterval(function () {
                if(step_progress>=0.8) {
                    clearInterval(interval_progress);
                } else {
                    progress_circle.animate(step_progress);
                    step_progress = step_progress + 0.1;
                }
            },500);
            first_image = new Image();
            first_image.crossOrigin = 'anonymous';
            $(first_image).on('load',function () {
                loadXHR(((window.s3_enabled) ? window.s3_url : '')+img,id,0).then(function(response) {
                    if(response[0]!='') {
                        var blob_url = URL.createObjectURL(response[0]);
                        panoramas[index_initial].panorama_blob = blob_url;
                    }
                    clearInterval(interval_progress);
                    $('#progress_msg span').html(window.viewer_labels.progress_almost_done);
                    progress_circle.animate(0.8);
                    imgs_loaded.push(response[1]);
                    $('.marker_img_'+id).removeClass('fas fa-spin fa-circle-notch');
                    $('.marker_img_'+id).parent().parent().removeClass('disabled');
                    $('.marker_img_'+id).parent().removeClass('disabled');
                    $('.marker_img_'+id).each(function () {
                        var icon = $(this)[0].getAttribute('data-icon');
                        $(this).addClass(icon);
                    });
                    $('.pointer_list_'+id+' .fa-spin').remove();
                    $('.pointer_list_'+id).removeClass('disabled');
                    $('#pointer_f_'+id+' i').remove();
                    $('#pointer_f_'+id).removeClass('disabled');
                    $(".arrows_nav").find("[data-roomtarget='" + id + "']").removeClass('disabled');
                    $(".controls_arrows").find("[data-roomtarget='" + id + "']").removeClass('disabled');
                    $('.list_alt_'+id).removeClass('disabled');
                    preload_dollhouse();
                });
            }).attr('src',((window.s3_enabled) ? window.s3_url : '')+img+((window.s3_enabled) ? '?s3='+s3_version : ''));
        }
    }

    function preload_next_image() {
        if(preload_panoramas==1) {
            if (index_preload_image < imgs.length) {
                var index = 0;
                var id = 0;
                var img = '';
                for (var t = 0; t < panoramas.length; t++) {
                    if (imgs[index_preload_image] == panoramas[t].panorama_image+'|'+panoramas[t].id) {
                        index = t;
                        id = panoramas[t].id;
                        img = imgs[index_preload_image].replace('|'+id,'');
                        break;
                    }
                }
                loadXHR(((window.s3_enabled) ? window.s3_url : '')+img, id, index).then(function (response) {
                    var id = response[1];
                    var i = response[2];
                    if (response[0] != '') {
                        var blob_url = URL.createObjectURL(response[0]);
                        panoramas[i].panorama_blob = blob_url;
                    }
                    imgs_loaded.push(id);
                    $('.marker_img_' + id).removeClass('fas fa-spin fa-circle-notch');
                    $('.marker_img_' + id).parent().parent().removeClass('disabled');
                    $('.marker_img_' + id).parent().removeClass('disabled');
                    $('.marker_img_' + id).each(function () {
                        var icon = $(this)[0].getAttribute('data-icon');
                        $(this).addClass(icon);
                    });
                    $('.pointer_list_' + id + ' .fa-spin').remove();
                    $('.pointer_list_' + id).removeClass('disabled');
                    $('#pointer_f_' + id + ' i').remove();
                    $('#pointer_f_' + id).removeClass('disabled');
                    $(".arrows_nav").find("[data-roomtarget='" + id + "']").removeClass('disabled');
                    $(".controls_arrows").find("[data-roomtarget='" + id + "']").removeClass('disabled');
                    $('.list_alt_' + id).removeClass('disabled');
                    index_preload_image++;
                    preload_next_image();
                });
            } else {
                if (imgs_alt.length > 0) {
                    preload_next_image_alt();
                }
            }
        }
    }

    function preload_next_image_alt() {
        if(index_preload_image_alt<imgs_alt.length) {
            var index = 0;
            var id = 0;
            var img = '';
            for(var t=0;t<panoramas.length;t++) {
                if(ObjectLength(panoramas[t].array_rooms_alt)>0) {
                    jQuery.each(panoramas[t].array_rooms_alt, function(index_alt, room_alt) {
                        if(room_alt.panorama_image==imgs_alt[index_preload_image_alt]) {
                            index = index_alt;
                            img = imgs_alt[index_preload_image_alt];
                            id = t;
                        }
                    });
                }
            }
            loadXHR(((window.s3_enabled) ? window.s3_url : '')+img,id,index).then(function(response) {
                if(response[0]!='') {
                    var blob_url = URL.createObjectURL(response[0]);
                    var index1 = response[1];
                    var index2 = response[2];
                    panoramas[index1].array_rooms_alt[index2].panorama_blob = blob_url;
                }
                index_preload_image_alt++;
                preload_next_image_alt();
            });
        }
    }

    function preload_images() {
        for(var i=0; i < panoramas.length; i++) {
            var id = panoramas[i].id;
            if(panoramas[i].multires || preload_panoramas==0) {
                imgs_loaded.push(id);
                $('.marker_img_'+id).removeClass('fas fa-spin fa-circle-notch');
                $('.marker_img_'+id).parent().parent().removeClass('disabled');
                $('.marker_img_'+id).parent().removeClass('disabled');
                $('.marker_img_'+id).each(function () {
                    var icon = $(this)[0].getAttribute('data-icon');
                    $(this).addClass(icon);
                });
                $('.pointer_list_'+id+' .fa-spin').remove();
                $('.pointer_list_'+id).removeClass('disabled');
                $('#pointer_f_'+id+' i').remove();
                $('#pointer_f_'+id).removeClass('disabled');
                $(".arrows_nav").find("[data-roomtarget='" + id + "']").removeClass('disabled');
                $(".controls_arrows").find("[data-roomtarget='" + id + "']").removeClass('disabled');
                $('.list_alt_'+id).removeClass('disabled');
            }
        }
        preload_next_image();
    }

    function add_custom_controls() {
        if(song_bg!='') {
            if(window.song_type=='menu') {
                $('.song_control').show();
                $('.song_alt_control').hide();
            } else {
                $('.song_control').addClass('hidden');
                $('.song_alt_control').show();
            }
        } else {
            $('.song_control').hide();
            $('.song_alt_control').hide();
            for(var i=0; i < panoramas.length; i++) {
                var song = panoramas[i].song;
                var audio_track_enable = panoramas[i].audio_track_enable;
                if((song!='') || (audio_track_enable)) {
                    if(window.song_type=='menu') {
                        $('.song_control').show();
                        $('.song_alt_control').hide();
                    } else {
                        $('.song_control').addClass('hidden');
                        $('.song_alt_control').show();
                    }
                }
            }
        }
        var info_control = false;
        var voice_control = false;
        var gallery_control = false;
        if(show_info>0) {
            info_control = true;
        }
        if(voice_commands_enable>0) {
            if(peer_id=='') {
                voice_control = true;
                initialize_speech();
            }
        }
        if(gallery_images.length>0 && gallery_mode=='images') {
            if(show_gallery>0) {
                gallery_control = true;
            }
        } else if(gallery_mode=='slideshow') {
            if(show_gallery>0) {
                gallery_control = true;
            }
        }
        if(show_compass) {
            $('.controls_btn.compass_control').css('display','inline-block');
        } else {
            $('.compass_control').addClass('hidden');
        }
        if(info_control) {
            $('.controls_btn.info_control').css('display','inline-block');
        } else {
            $('.info_control').addClass('hidden');
        }
        if(show_custom>0) {
            $('.controls_btn.custom_control').css('display','inline-block');
        } else {
            $('.custom_control').addClass('hidden');
        }
        if(show_custom2>0) {
            $('.controls_btn.custom2_control').css('display','inline-block');
        } else {
            $('.custom2_control').addClass('hidden');
        }
        if(show_custom3>0) {
            $('.controls_btn.custom3_control').css('display','inline-block');
        } else {
            $('.custom3_control').addClass('hidden');
        }
        if(show_custom4>0) {
            $('.controls_btn.custom4_control').css('display','inline-block');
        } else {
            $('.custom4_control').addClass('hidden');
        }
        if(show_custom5>0) {
            $('.controls_btn.custom5_control').css('display','inline-block');
        } else {
            $('.custom5_control').addClass('hidden');
        }
        if(show_location>0) {
            $('.controls_btn.location_control').css('display','inline-block');
        } else {
            $('.location_control').addClass('hidden');
        }
        if(show_media>0) {
            $('.media_control').attr('data-fancybox','');
            $('.media_control').attr('data-src',((window.s3_enabled) ? window.s3_url : '')+"content/"+media_file);
            $('.controls_btn.media_control').css('display','inline-block');
        } else {
            $('.media_control').addClass('hidden');
        }
        if(show_dollhouse>0) {
            $('.controls_btn.dollhouse_control').css('display','inline-block');
        } else {
            $('.dollhouse_control').addClass('hidden');
        }
        if(!voice_control) {
            $('.voice_control').addClass('hidden');
        }
        if(gallery_control) {
            $('.controls_btn.gallery_control').css('display','inline-block');
        } else {
            $('.gallery_control').addClass('hidden');
        }
        if((whatsapp_chat) && (whatsapp_number!='')) {
            $('.controls_btn.whatsapp_control').css('display','inline-block');
            if(window.is_mobile) {
                var link_whatsapp = 'https://api.whatsapp.com/send?phone='+whatsapp_number;
            } else {
                var link_whatsapp = 'https://web.whatsapp.com/send?phone='+whatsapp_number;
            }
            $('.controls_btn.whatsapp_control').attr('href',link_whatsapp);
            $('.ms_control.whatsapp_control').attr('onclick',"open_whatsapp('"+link_whatsapp+"')");
            $('.dropdown .whatsapp_control').attr('onclick',"open_whatsapp('"+link_whatsapp+"')");
        } else {
            $('.whatsapp_control').addClass('hidden');
        }
        if((array_presentation.length>0) || (presentation_type=='automatic') || (presentation_type=='video')) {
            $('.presentation_control').show();
        } else {
            $('.presentation_control').hide();
        }
        if(show_main_form==1 || show_inline_form==1) {
            try {
                form_content = JSON.parse(form_content);
                var title = form_content[0].title;
                $('#mform_name').html(title);
            } catch (e) {}
        }
        if(show_main_form==1) {
            $('.controls_btn.form_control').attr('title',title);
            $('.ms_control.form_control').attr('title',title);
            $('.controls_btn.form_control').css('display','inline-block');
        } else {
            $('.form_control').addClass('hidden');
        }
        if(show_inline_form==1) {
            render_inline_form(form_content);
            $('#inline_form_title').html(title);
        }
        if(window.icon_tooltips==1) {
            $('.tooltip').tooltipster({
                theme: 'tooltipster-borderless',
                animation: 'grow',
                delay: 0,
                arrow: false
            });
        } else {
            $('.tooltip').removeAttr('title');
        }
        $('.pnlm-orientation-button').hide();
        if(!show_audio) {
            $('.song_control').addClass('hidden');
            $('.song_alt_control').addClass('hidden');
            controls_status['song']=false;
        }
        switch(show_vt_title) {
            case 0:
                $('.name_vt').css({'height':0,'pointer-events':'none','opacity':0});
                $('.room_vt').addClass('hidden');
                $('.category_room_vt').addClass('hidden');
                break;
            case 2:
                $('.room_vt').addClass('hidden');
                $('.category_room_vt').addClass('hidden');
                break;
            case 3:
                $('.name_vt').css({'height':0,'pointer-events':'none','opacity':0});
                break;
        }
        switch(show_logo) {
            case 0:
                $('.logo').addClass('hidden');
                break;
            case 2:
                if(window.is_mobile) $('.logo').addClass('hidden');
                break;
            case 3:
                if(!window.is_mobile) $('.logo').addClass('hidden');
                break;
        }
        switch(show_poweredby) {
            case 0:
                $('.poweredby').addClass('hidden');
                break;
            case 2:
                if(window.is_mobile) $('.poweredby').addClass('hidden');
                break;
            case 3:
                if(!window.is_mobile) $('.poweredby').addClass('hidden');
                break;
        }
        if(show_avatar_video==0) {
            $('.avatar_video').addClass('hidden');
        }
        switch(show_icons_toggle) {
            case 0:
                $('.icons_control').addClass('hidden');
                break;
            case 1:
                $('.controls_btn.icons_control').css('display','inline-block');
                $('.icons_control').addClass('active_control');
                break;
            case 2:
                $('.controls_btn.icons_control').css('display','inline-block');
                $('.custom-hotspot').addClass('hidden_icons');
                $('.custom-hotspot img').addClass('hidden_icons');
                $('.custom-hotspot-content').addClass('hidden_icons');
                $('.poi_embed').addClass('hidden_icons');
                $('.marker_embed').addClass('hidden_icons');
                $('.tooltip_text').addClass('hidden_icons');
                $('.tooltip_preview').addClass('hidden_icons');
                $('.tooltip_preview_square').addClass('hidden_icons');
                $('.tooltip_preview_rect').addClass('hidden_icons');
                $('.div_poi_wrapper').removeClass('pulse_icon_hover');
                $('.div_poi_wrapper').removeClass('pulse_image_hover');
                $('.div_marker_wrapper').removeClass('pulse_icon_hover');
                $('.div_marker_wrapper').removeClass('pulse_image_hover');
                $('.pnlm-pointer').removeClass('hotspot_hover');
                $('.icons_control').removeClass('active_control');
                $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['icons_content']=false;
                controls_status['icons_nav']=false;
                break;
        }
        switch(show_icons_content_toggle) {
            case 0:
                $('.icons_content_control').addClass('hidden');
                break;
            case 1:
                $('.controls_btn.icons_content_control').css('display','inline-block');
                $('.icons_content_control').addClass('active_control');
                break;
            case 2:
                $('.controls_btn.icons_content_control').css('display','inline-block');
                $('.custom-hotspot-content').addClass('hidden_icons');
                $('.poi_embed').addClass('hidden_icons');
                $('.tooltip_poi').addClass('hidden_icons');
                $('.div_poi_wrapper').removeClass('pulse_icon_hover');
                $('.div_poi_wrapper').removeClass('pulse_image_hover');
                $('.pnlm-pointer').removeClass('hotspot_hover');
                $('.icons_content_control').removeClass('active_control');
                $('.icons_content_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['icons_content']=false;
                break;
        }
        switch(show_icons_nav_toggle) {
            case 0:
                $('.icons_nav_control').addClass('hidden');
                break;
            case 1:
                $('.controls_btn.icons_nav_control').css('display','inline-block');
                $('.icons_nav_control').addClass('active_control');
                break;
            case 2:
                $('.controls_btn.icons_nav_control').css('display','inline-block');
                $('.custom-hotspot').addClass('hidden_icons');
                $('.custom-hotspot img').addClass('hidden_icons');
                $('.marker_embed').addClass('hidden_icons');
                $('.tooltip_marker').addClass('hidden_icons');
                $('.div_marker_wrapper').removeClass('pulse_icon_hover');
                $('.div_marker_wrapper').removeClass('pulse_image_hover');
                $('.pnlm-pointer').removeClass('hotspot_hover');
                $('.icons_nav_control').removeClass('active_control');
                $('.icons_nav_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['icons_nav']=false;
                break;
        }
        switch(show_annotations) {
            case 0:
                $('.annotations_control').addClass('hidden');
                break;
            case 1:
                $('.controls_btn.annotations_control').css('display','inline-block');
                $('.annotations_control').addClass('active_control');
                break;
            case 2:
                $('.annotation').css({'opacity':0,'pointer-events':'none'});
                $('.controls_btn.annotations_control').css('display','inline-block');
                $('.annotations_control').removeClass('active_control');
                $('.annotations_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['annotations']=false;
                break;
        }
        switch(show_measures_toggle) {
            case 0:
                $('.measures_control').addClass('hidden');
                break;
            case 1:
                $('.controls_btn.measures_control').css('display','inline-block');
                $('.measures_control').addClass('active_control');
                break;
            case 2:
                $('.leader-line').addClass('hidden_icons');
                $('.controls_btn.measures_control').css('display','inline-block');
                $('.measures_control').removeClass('active_control');
                $('.measures_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['measures']=false;
                break;
        }
        switch(show_autorotation_toggle) {
            case 0:
                $('.autorotate_control').addClass('hidden');
                controls_status['auto_rotate']=false;
                break;
            case 3:
                $('.autorotate_control').addClass('hidden');
                controls_status['auto_rotate']=true;
                break;
            case 1:
                $('.controls_btn.autorotate_control').css('display','inline-block');
                $('.autorotate_control').addClass('active_control');
                break;
            case 2:
                $('.controls_btn.autorotate_control').css('display','inline-block');
                $('.autorotate_control').removeClass('active_control');
                $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['auto_rotate']=false;
                break;
        }
        if(!show_nav_control) {
            $(".nav_control").addClass('hidden');
        } else {
            if(autorotate_speed==0 || show_autorotation_toggle==2) {
                $(".nav_control .nav_rotate").addClass('disabled');
            } else {
                $(".nav_control .nav_rotate").addClass('active_rotate');
            }
            $('.nav_control').show();
            $(".nav_control").draggable({ containment: "#vt_container" });
        }
        if(show_presentation==0) {
            $('.presentation_control').addClass('hidden');
        }
        if(window.show_share>0) {
            $('.controls_btn.share_control').css('display','inline-block');
        } else {
            $('.share_control').addClass('hidden');
        }
        if(show_snapshot>0) {
            $('.controls_btn.snapshot_control').css('display','inline-block');
        } else {
            $('.snapshot_control').addClass('hidden');
        }
        if(show_device_orientation==0 || show_device_orientation==3) {
            $('.orient_control').addClass('hidden');
        } else {
            $('.controls_btn.orient_control').css('display','inline-block');
        }
        if(show_webvr) {
            $('.controls_btn.vr_control').css('display','inline-block');
        } else {
            $('.vr_control').addClass('hidden');
        }
        if(show_facebook) {
            $('.controls_btn.facebook_control').css('display','inline-block');
        } else {
            $('.facebook_control').addClass('hidden');
        }
        if(!whatsapp_chat) {
            $('.whatsapp_control').addClass('hidden');
        }
        if(array_maps.length==0) {
            show_map=0;
        }
        if(map_tour.length==0) {
            show_map_tour=0;
        }
        switch (show_map) {
            case 0:
                $('.map_control').addClass('hidden');
                $('.floorplan_alt_control').addClass('hidden');
                $('.map_alt_control').addClass('hidden');
                break;
            case 1:
            case 2:
            case 3:
            case 4:
                if(controls_status['map']) {
                    $('.map_control').addClass('active_control');
                    $('.floorplan_alt_control').addClass('active_control');
                    $('.map_control i').removeClass('icon-map_off').addClass('icon-map_on');
                    $('.floorplan_alt_control .fa-circle').removeClass('not_active').addClass('active');
                } else {
                    $('.map_control').removeClass('active_control');
                    $('.floorplan_alt_control').removeClass('active_control');
                    $('.map_control i').removeClass('icon-map_on').addClass('icon-map_off');
                    $('.floorplan_alt_control .fa-circle').removeClass('active').addClass('not_active');
                }
                break;
        }
        if(show_fullscreen!=0) {
            if(window.fullscreen_type=='menu') {
                $('.fullscreen_control').show();
                $('.fullscreen_alt_control').hide();
            } else {
                $('.fullscreen_control').addClass('hidden');
                $('.fullscreen_alt_control').show();
            }
        } else {
            $('.fullscreen_control').addClass('hidden');
            $('.fullscreen_alt_control').addClass('hidden');
        }
        if(show_map!=0) {
            if(window.floorplan_type=='menu') {
                $('.map_control').show();
                $('.floorplan_alt_control').hide();
            } else {
                $('.map_control').addClass('hidden');
                $('.floorplan_alt_control').show();
            }
        } else {
            $('.map_control').addClass('hidden');
            $('.floorplan_alt_control').addClass('hidden');
        }
        if(show_map_tour!=0) {
            if(window.map_type=='menu') {
                $('.map_tour_control').show();
                $('.map_alt_control').hide();
            } else {
                $('.map_tour_control').addClass('hidden');
                $('.map_alt_control').show();
            }
        } else {
            $('.map_tour_control').addClass('hidden');
            $('.map_alt_control').addClass('hidden');
        }
        if(show_language) {
            $('.language_menu').show();
        } else {
            $('.language_menu').addClass('hidden');
            $('#ms_language_switcher').addClass('hidden');
        }
        if((show_fullscreen!=0 && window.fullscreen_type=='menu') && (show_map!=0 && window.floorplan_type=='menu') && (show_map_tour!=0 && window.map_type=='menu')) {
            $('.fullscreen_control').css('right','12px');
            $('.map_control').css('right','40px');
            $('.map_tour_control').css('right','72px');
            if(show_language) $('.language_menu').css('right','106px');
        } else if((show_fullscreen==0 || window.fullscreen_type=='button') && (show_map!=0 && window.floorplan_type=='menu') && (show_map_tour!=0 && window.map_type=='menu')) {
            $('.map_control').css('right','12px');
            $('.map_tour_control').css('right','44px');
            if(show_language) $('.language_menu').css('right','78px');
        } else if((show_fullscreen!=0 && window.fullscreen_type=='menu') && (show_map==0 || window.floorplan_type=='button') && (show_map_tour!=0 && window.map_type=='menu')) {
            $('.fullscreen_control').css('right','12px');
            $('.map_tour_control').css('right','40px');
            if(show_language) $('.language_menu').css('right','72px');
        } else if((show_fullscreen!=0 && window.fullscreen_type=='menu') && (show_map!=0 && window.floorplan_type=='menu') && (show_map_tour==0 || window.map_type=='button')) {
            $('.fullscreen_control').css('right','12px');
            $('.map_control').css('right','40px');
            if(show_language) $('.language_menu').css('right','72px');
        } else if((show_fullscreen==0 || window.fullscreen_type=='button') && (show_map==0 || window.floorplan_type=='button') && (show_map_tour!=0 && window.map_type=='menu')) {
            $('.map_tour_control').css('right','12px');
            if(show_language) $('.language_menu').css('right','44px');
        } else if((show_fullscreen==0 || window.fullscreen_type=='button') && (show_map!=0 && window.floorplan_type=='menu') && (show_map_tour==0 || window.map_type=='button')) {
            $('.map_control').css('right','12px');
            if(show_language) $('.language_menu').css('right','44px');
        } else if((show_fullscreen!=0 && window.fullscreen_type=='menu') && (show_map==0 || window.floorplan_type=='button') && (show_map_tour==0 || window.map_type=='button')) {
            $('.fullscreen_control').css('right','12px');
            if(show_language) $('.language_menu').css('right','40px');
        } else {
            if(show_language) $('.language_menu').css('right','12px');
        }
        switch(show_map_tour) {
            case 2:
                $('.map_tour_control i').removeClass('far').addClass('fas');
                $('.map_alt_control .fa-circle').removeClass('not_active').addClass('active');
                $('.map_tour_control').addClass('active_control');
                $('.map_alt_control').addClass('active_control');
                open_map_tour();
                break;
            case 3:
                $('.map_tour_control i').removeClass('far').addClass('fas');
                $('.map_alt_control .fa-circle').removeClass('not_active').addClass('active');
                $('.map_tour_control').addClass('active_control');
                $('.map_alt_control').addClass('active_control');
                open_map_tour();
                $('#map_tour_div').addClass('fullscreen');
                setTimeout(function(){ map_tour_l.invalidateSize()}, 10);
                break;
            case 4:
                if(!window.is_mobile) {
                    $('.map_tour_control i').removeClass('far').addClass('fas');
                    $('.map_alt_control .fa-circle').removeClass('not_active').addClass('active');
                    $('.map_tour_control').addClass('active_control');
                    $('.map_alt_control').addClass('active_control');
                    open_map_tour();
                }
                break;
            default:
                $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
                break;
        }
        if(auto_show_slider==2) {
            $('.list_control').addClass('hidden');
            $('.list_control_alt').addClass('hidden');
        }
        if (location.protocol == 'https:') {
            if(show_live_session) {
                $('.controls_btn.live_control').css('display','inline-block');
                if(peer_id!='') {
                    $('.live_control').addClass('hidden');
                }
            } else {
                $('.live_control').addClass('hidden');
            }
        } else {
            $('.live_control').addClass('hidden');
        }
        if(show_meeting) {
            $('.controls_btn.meeting_control').css('display','inline-block');
        } else {
            $('.meeting_control').addClass('hidden');
        }
        var all_menu_hidden = true;
        if(window.sidebar_enable==1) {
            if(!$('#ms_language_switcher').hasClass('hidden')) {
                all_menu_hidden = false;
            }
            if(show_list_alt!=0) {
                all_menu_hidden = false;
            }
            if($('#ms_logo').length) {
                all_menu_hidden = false;
            }
            $('#ms_controls .ms_control').each(function () {
                if(($(this).is(':visible')) && (!$(this).hasClass('hidden'))) {
                    all_menu_hidden = false;
                }
            });
        } else {
            $('.menu_controls .dropdown p').each(function () {
                if(($(this).is(':visible')) && (!$(this).hasClass('hidden'))) {
                    all_menu_hidden = false;
                }
            });
        }
        if(window.sidebar_enable==1) {
            $('#list_alt_menu_icon').addClass('hidden');
        }
        if(all_menu_hidden) {
            $('.song_control').css('left','8px');
            $('.menu_controls').addClass('hidden');
        }
        switch (show_list_alt) {
            case 0:
                $('.list_alt_menu').addClass('hidden');
                break;
            case 1:
            case 2:
                if(all_menu_hidden) {
                    if(window.sidebar_enable==1) {
                        $('.list_alt_menu').css('left','3px');
                        $('.song_control').css('left','6px');
                    } else {
                        $('.list_alt_menu').css('left','3px');
                        $('.song_control').css('left','45px');
                    }
                } else {
                    if(window.sidebar_enable==1) {
                        $('.list_alt_menu').css('left','40px');
                        $('.song_control').css('left','46px');
                    } else {
                        $('.list_alt_menu').css('left','40px');
                        $('.song_control').css('left','75px');
                    }
                }
                var id_open_cat = 0;
            function render_list_alt(items, parentId = 'root', indent = 0) {
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    var id = item.id;
                    var name = item.name;
                    var type = item.type;
                    var hide = parseInt(item.hide || 0);
                    var margin = 15 * indent + "px";
                    var learning_disabled = "";
                    if (window.learning_mode > 0 && window.learning_unlock_marker) {
                        if (learning_check_marker_locked(id)) {
                            learning_disabled = 'disabled_l';
                        }
                    }
                    if (type === "room" && hide === 0) {
                        var icon = 'far fa-circle';
                        if (parseInt(id) === parseInt(panoramas[index_initial].id)) {
                            id_open_cat = parentId;
                        }
                        $('.list_alt_menu .dropdown').append(
                            `<p style="display:none; margin-left: ${margin};" data-cat="${parentId}" class="disabled ${learning_disabled} children list_alt_${id} cat_parent_${parentId}" onclick="goto('', [${id}, null, null, null, null, null, null, null]);">
                        <i class="${icon}"></i>&nbsp;&nbsp;&nbsp;${name}
                    </p>`
                        );
                    }
                    if (type === "category") {
                        $('.list_alt_menu .dropdown').append(
                            `<p style="display:none; margin-left: ${margin};" data-cat="${parentId}" class="cat cat_${id} cat_parent_${parentId}" onclick="open_cat_list_alt('${id}')">
                        <i class="fas fa-chevron-right"></i>&nbsp;&nbsp;&nbsp;${name}
                    </p>`
                        );
                        if (item.childrens && item.childrens.length > 0) {
                            render_list_alt(item.childrens, id, indent + 1);
                        }
                    }
                }
            }
                $('.list_alt_menu .dropdown').empty();
                render_list_alt(list_alt);
                removeEmptyCategories();
                $('.list_alt_menu .dropdown [data-cat="root"]').show();
                $('.list_alt_menu').show();
                if(id_open_cat!=0) {
                    const $currentItemElement = $('.list_alt_'+panoramas[index_initial].id);
                    if ($currentItemElement.length > 0) {
                        $currentItemElement.find('i').removeClass('fas fa-circle').removeClass('far fa-circle').addClass('fas fa-dot-circle');
                        if ($currentItemElement.is('[class*="cat_parent_"]')) {
                            const immediateParentId = $currentItemElement.data('cat');
                            const mainAncestorId = getMainAncestorId(immediateParentId);
                            if (mainAncestorId) {
                                $('.list_alt_menu .cat_parent_root').each(function() {
                                    const $otherMainCat = $(this);
                                    const otherMainCatMatch = $otherMainCat.attr('class').match(/cat_(c\d+)/);
                                    if (otherMainCatMatch && otherMainCatMatch[1]) {
                                        const otherMainCatId = otherMainCatMatch[1];
                                        if (otherMainCatId !== mainAncestorId) {
                                            $otherMainCat.find('i.fas').removeClass('fa-chevron-down').addClass('fa-chevron-right');
                                            $otherMainCat.find('i.fas').parent().removeClass('open');
                                            hideAllDescendants(otherMainCatId);
                                        }
                                    }
                                });
                                ensureCategoryOpen(immediateParentId);
                            }
                        }
                    }
                }
                if(show_list_alt==2) click_list_alt_menu();
                break;
        }
    }

    function render_inline_form(form_content) {
        const toggleButtonText = document.querySelector('#inline_form_toggle span');
        const formElement = document.getElementById('inline_form_main');
        const toggleButton = document.getElementById('inline_form_toggle');
        const formContainer = document.getElementById('inline_form_content');
        const arrowIcon = document.getElementById('inline_form_arrow_icon');
        formElement.innerHTML = '';
        const config = form_content[0] || {};
        const title = config.title || window.viewer_labels.contact_form;
        const description = config.description || '';
        const buttonText = config.button || window.viewer_labels.submit;
        const privacy_policy = config.privacy_policy || false;
        const email = config.email || '';
        const webhook_url = config.webhook_url || '';
        toggleButtonText.textContent = title.toUpperCase();
        let fieldsHtml = '';
        if (description) {
            fieldsHtml += `<p class="inline_form_description">${description}</p>`;
        }
        for (let i = 1; i <= 10; i++) {
            if (!form_content[i] || !form_content[i].enabled) continue;
            const field = form_content[i];
            field.type = field.type || 'text';
            const requiredTag = field.required ? 'required' : '';
            const requiredLabel = field.required ? '*' : '';
            let labelText = '';
            let fieldHtml = '';
            switch (field.type) {
                case 'select':
                    const selectLabels = field.label.split(';');
                    labelText = selectLabels[0];
                    fieldHtml += `<label for="form_field_${i}" class="inline_form_label">${labelText} ${requiredLabel}</label>`;
                    fieldHtml += `<select id="form_field_${i}" name="form_field_${i}" class="inline_form_select" ${requiredTag}>`;
                    fieldHtml += `<option value="" disabled selected>${window.viewer_labels.select_an_option}</option>`;
                    for (let k = 1; k < selectLabels.length; k++) {
                        fieldHtml += `<option value="${selectLabels[k]}">${selectLabels[k]}</option>`;
                    }
                    fieldHtml += `</select>`;
                    fieldsHtml += `<div class="inline_form_group">${fieldHtml}</div>`;
                    break;
                case 'checkbox':
                    labelText = field.label;
                    fieldHtml += `<input type="checkbox" id="form_field_${i}" name="form_field_${i}" ${requiredTag}>`;
                    fieldHtml += `<label for="form_field_${i}">${labelText} ${requiredLabel}</label>`;
                    fieldsHtml += `<div class="inline_form_group_checkbox">${fieldHtml}</div>`;
                    break;
                case 'file':
                    const fileLabels = field.label.split(';');
                    labelText = fileLabels[0];
                    const acceptTypes = fileLabels[1] || '';
                    fieldHtml += `<label for="form_field_${i}" class="inline_form_label">${labelText} ${requiredLabel}</label>`;
                    fieldHtml += `<input type="file" id="form_field_${i}" name="form_field_${i}" class="inline_form_input" accept="${acceptTypes}" ${requiredTag}>`;
                    fieldsHtml += `<div class="inline_form_group">${fieldHtml}</div>`;
                    break;
                case 'textarea':
                    const textareaLabels = field.label.split(';');
                    labelText = textareaLabels[0];
                    const rows = textareaLabels[1] || 3;
                    fieldHtml += `<label for="form_field_${i}" class="inline_form_label">${labelText} ${requiredLabel}</label>`;
                    fieldHtml += `<textarea id="form_field_${i}" name="form_field_${i}" class="inline_form_textarea" rows="${rows}" ${requiredTag}></textarea>`;
                    fieldsHtml += `<div class="inline_form_group">${fieldHtml}</div>`;
                    break;
                default:
                    labelText = field.label;
                    fieldHtml += `<label for="form_field_${i}" class="inline_form_label">${labelText} ${requiredLabel}</label>`;
                    fieldHtml += `<input type="${field.type}" id="form_field_${i}" name="form_field_${i}" class="inline_form_input" ${requiredTag}>`;
                    fieldsHtml += `<div class="inline_form_group">${fieldHtml}</div>`;
                    break;
            }
            fieldsHtml += `<input type="hidden" name="form_label_${i}" value="${labelText}">`;
        }
        const id_virtualtour = window.id_virtualtour || '';
        fieldsHtml += `<input type="hidden" name="id_room" value="0">`;
        fieldsHtml += `<input type="hidden" name="title" value="${title}">`;
        fieldsHtml += `<input type="hidden" name="email" value="${email}">`;
        fieldsHtml += `<input type="hidden" name="webhook_url" value="${webhook_url}">`;
        fieldsHtml += `<input type="hidden" name="id_virtualtour" value="${id_virtualtour}">`;
        if (privacy_policy) {
            fieldsHtml += `<div class="inline_form_group_checkbox">
                    <input type="checkbox" id="privacy_policy" required>
                    <label for="privacy_policy">${window.viewer_labels.agree_privacy_policy}</label>
                </div>`;
        }
        fieldsHtml += `<div class="inline_form_button_container">
                <button type="submit" class="inline_form_submit_button">${buttonText}</button>
            </div>`;
        formElement.innerHTML = fieldsHtml;
        formElement.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const response = (form_content[0] && form_content[0].response) || '';
            confirm_main_form(formData, response, 'inline');
        });
        toggleButton.addEventListener('click', () => {
            const isOpening = !formContainer.classList.contains('open');
            arrowIcon.style.transform = isOpening ? 'rotate(180deg)' : 'rotate(0deg)';
            if (isOpening) {
                toggleButton.classList.add('form_is_open');
                formContainer.classList.add('open');
            } else {
                formContainer.classList.remove('open');
                formContainer.addEventListener('transitionend', () => {
                    toggleButton.classList.remove('form_is_open');
                }, { once: true });
            }
        });
    }

    function removeEmptyCategories() {
        const container = document.querySelector('.list_alt_menu .dropdown');
        if (!container) return;
        const roomElements = container.querySelectorAll('.children');
        const usedCategories = new Set();
        roomElements.forEach(room => {
            const parentClass = [...room.classList].find(cls => cls.startsWith('cat_parent_'));
            if (parentClass) {
                const catId = parentClass.replace('cat_parent_', '');
                usedCategories.add(catId);
            }
        });
        let added = true;
        while (added) {
            added = false;
            container.querySelectorAll('p.cat').forEach(catEl => {
                const catIdMatch = [...catEl.classList].find(cls => cls.startsWith('cat_') && cls !== 'cat');
                const parentMatch = [...catEl.classList].find(cls => cls.startsWith('cat_parent_'));
                if (catIdMatch && parentMatch) {
                    const catId = catIdMatch.replace('cat_', '');
                    const parentId = parentMatch.replace('cat_parent_', '');
                    if (usedCategories.has(catId) && !usedCategories.has(parentId)) {
                        usedCategories.add(parentId);
                        added = true;
                    }
                }
            });
        }
        container.querySelectorAll('p.cat').forEach(catEl => {
            const catIdMatch = [...catEl.classList].find(cls => cls.startsWith('cat_') && cls !== 'cat');
            if (catIdMatch) {
                const catId = catIdMatch.replace('cat_', '');
                if (!usedCategories.has(catId)) {
                    catEl.remove();
                }
            }
        });
    }

    window.open_whatsapp = function(link) {
        window.open(link,'_blank');
    }

    window.open_info_map = function (link,type) {
        switch (type) {
            case 'blank':
                window.open(link,'_blank');
                break;
            case 'iframe':
                var custom_box_html = '<div style="padding:0 !important;width:90%;height:90%;overflow:hidden;" class="info_map_content"><iframe style="width:100%;height:100%;border:0;" src="'+link+'"></iframe></div>';
                $.fancybox.open({
                    src  : custom_box_html,
                    type : 'html',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false
                });
                break;
        }
    }

    function showDirectChildren(parentId) {
        $(`.cat_parent_${parentId}`).each(function() {
            const $child = $(this);
            $child.show();
            if ($child.hasClass('cat')) {
                const subCatMatch = $child.attr('class').match(/cat_(c\d+)/);
                if (subCatMatch && subCatMatch[1]) {
                    const subCatId = subCatMatch[1];
                    $child.find('i.fas').removeClass('fa-chevron-down').addClass('fa-chevron-right');
                    $child.find('i.fas').parent().removeClass('open');
                    $(`.cat_parent_${subCatId}`).hide();
                }
            }
        });
    }

    function hideAllDescendants(parentId, visited = new Set()) {
        if (visited.has(parentId)) return;
        visited.add(parentId);
        const $directChildren = $(`.cat_parent_${parentId}`);
        $directChildren.each(function () {
            const $child = $(this);
            $child.hide();
            if ($child.hasClass('cat')) {
                const subCatMatch = $child.attr('class').match(/cat_(c\d+)/);
                if (subCatMatch && subCatMatch[1]) {
                    const subCatId = subCatMatch[1];
                    $child.find('i.fas').removeClass('fa-chevron-down').addClass('fa-chevron-right');
                    $child.find('i.fas').parent().removeClass('open');
                    hideAllDescendants(subCatId, visited);
                }
            }
        });
    }

    function close_all_categories() {
        $('.list_alt_menu i.fas.fa-chevron-down').removeClass('fa-chevron-down').addClass('fa-chevron-right');
        $('.list_alt_menu i.fas.fa-chevron-down').parent().removeClass('open');
        $('[class*="cat_"]').each(function () {
            const match = $(this).attr('class').match(/cat_(c\d+)/);
            if (match && match[1]) {
                const catId = match[1];
                hideAllDescendants(catId);
            }
        });
    };

    function ensureCategoryOpen(id) {
        if (!id || id === 'root') { return; }
        const $categoryElement = $(`.cat_${id}`);
        if ($categoryElement.length === 0) { return; }
        const icon = $categoryElement.find('i.fas');
        const isCurrentlyOpen = icon.hasClass('fa-chevron-down');
        const parentId = $categoryElement.data('cat');
        if (!isCurrentlyOpen) {
            if(icon.hasClass('fa-chevron-right')) {
                icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
                icon.parent().addClass('open');
                $(`.cat_parent_${id}`).show();
            }
        }
        ensureCategoryOpen(parentId);
    }

    function getMainAncestorId(categoryId) {
        if (!categoryId || categoryId === 'root') {
            return null;
        }
        let currentId = categoryId;
        let $currentElement = $(`.cat_${currentId}`);
        if ($currentElement.length === 0 || !$currentElement.hasClass('cat')) {
            const parentFromData = $(`.list_alt_${categoryId}`).data('cat') || $(`[class*="cat_parent_${categoryId}"]`).data('cat');
            if(parentFromData && parentFromData !== 'root') {
                currentId = parentFromData;
                $currentElement = $(`.cat_${currentId}`);
                if ($currentElement.length === 0 || !$currentElement.hasClass('cat')) return null;
            } else {
                return null;
            }
        }
        let parentId = $currentElement.data('cat');
        while (parentId && parentId !== 'root') {
            currentId = parentId;
            $currentElement = $(`.cat_${currentId}`);
            if ($currentElement.length === 0) return null;
            parentId = $currentElement.data('cat');
        }
        if (parentId === 'root') {
            return currentId;
        } else {
            return null;
        }
    }

    window.open_cat_list_alt = function(id, expand=false) {
        function openCategory(catId) {
            const $el = $(`.cat_${catId}`);
            const icon = $el.find('i.fas');
            if (!icon.hasClass('fa-chevron-down')) {
                icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
                icon.parent().addClass('open');
                showDirectChildren(catId);
            }
        }
        if(expand) {
            let currentId = id;
            while (true) {
                const $el = $(`.cat_${currentId}`);
                if ($el.length === 0) break;
                openCategory(currentId);
                const parentClass = [...$el[0].classList].find(cls => cls.startsWith('cat_parent_'));
                if (!parentClass || parentClass === 'cat_parent_root') break;
                currentId = parentClass.replace('cat_parent_', '');
            }
        }
        const $clickedElement = $(`.cat_${id}`);
        if ($clickedElement.length === 0) return;
        const icon = $clickedElement.find('i.fas');
        const isOpen = icon.hasClass('fa-chevron-down');
        const isMainCategory = $clickedElement.hasClass('cat_parent_root');
        if (isMainCategory) {
            $('.cat_parent_root').not($clickedElement).each(function () {
                const $other = $(this);
                const match = $other.attr('class').match(/cat_(c\d+)/);
                if (match && match[1]) {
                    const otherId = match[1];
                    $other.find('i.fas').removeClass('fa-chevron-down').addClass('fa-chevron-right');
                    $other.find('i.fas').parent().removeClass('open');
                    hideAllDescendants(otherId);
                }
            });
        } else if (!isOpen) {
            const parentMatch = [...$clickedElement[0].classList].find(cls => cls.startsWith('cat_parent_'));
            if (parentMatch) {
                const parentId = parentMatch.replace('cat_parent_', '');
                $(`.cat_parent_${parentId}.cat`).not($clickedElement).each(function () {
                    const $sibling = $(this);
                    const siblingMatch = $sibling.attr('class').match(/cat_(c\d+)/);
                    if (siblingMatch && siblingMatch[1]) {
                        const siblingId = siblingMatch[1];
                        $sibling.find('i.fas').removeClass('fa-chevron-down').addClass('fa-chevron-right');
                        $sibling.find('i.fas').parent().removeClass('open');
                        hideAllDescendants(siblingId);
                    }
                });
            }
        }
        if (isOpen) {
            icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
            icon.parent().removeClass('open');
            hideAllDescendants(id);
        } else {
            icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
            icon.parent().addClass('open');
            showDirectChildren(id);
        }
    };

    function initialize() {
        controls_status['fullscreen']=false;
        controls_status['orient']=false;
        if(song_autoplay>0) {
            controls_status['song']=true;
        } else {
            controls_status['song']=false;
        }
        controls_status['map']=false;
        controls_status['icons_content']=true;
        controls_status['icons_nav']=true;
        controls_status['measures']=true;
        controls_status['auto_rotate']=(show_autorotation_toggle==2 || show_autorotation_toggle==0 || window.flyin_enabled==1) ? false : true;
        controls_status['list']=false;
        controls_status['share']=false;
        controls_status['hide']=false;
        controls_status['presentation']=false;
        current_id_panorama = panoramas[index_initial].id;
        $('.room_visited_'+current_id_panorama).show();
        list_id_visited.push(parseInt(current_id_panorama));
        check_list_sliders_visited();
        if(!transition_loading) {
            $('#loading_pano').addClass('hidden');
        }
        audio_player.src = "";
        audio_player_room.src = "";
        if (typeof audio_player_room.loop == 'boolean') {
            if(parseInt(panoramas[index_initial].song_loop)==1) {
                audio_player_room.loop = true;
            } else {
                audio_player_room.loop = false;
            }
        } else {
            audio_player_room.addEventListener('ended', function () {
                var index = get_id_viewer(current_id_panorama);
                if(parseInt(panoramas[index].song_loop)==1) {
                    this.currentTime = 0;
                    this.play();
                }
            }, false);
        }
        song_bg_volume_sel = main_song_bg_volume;
        audio_player.volume = main_song_bg_volume;
        if(panoramas[index_initial].song!='') {
            if(panoramas[index_initial].song_once==0 || (panoramas[index_initial].song_once==1 && !panoramas[index_initial].song_played)) {
                audio_player_room.src = ((window.s3_enabled) ? window.s3_url : '')+"content/"+panoramas[index_initial].song;
                song_bg_volume_sel = panoramas[index_initial].song_bg_volume;
                audio_player.volume = panoramas[index_initial].song_bg_volume;
                audio_player_room.volume = panoramas[index_initial].song_volume;
                audio_player_room.load();
                audio_player_room.play();
                if(panoramas[index_initial].song_loop==0) {
                    audio_player_room.addEventListener('ended', function() {
                        song_bg_volume_sel = main_song_bg_volume;
                        if(controls_status['song']) fadeVolume(audio_player, main_song_bg_volume, 500);
                    }, false);
                }
                panoramas[index_initial].song_played = true;
            }
        }
        if(song_bg!='') {
            audio_player.src = ((window.s3_enabled) ? window.s3_url : '')+"content/"+song_bg;
        }
        if (typeof audio_player.loop == 'boolean') {
            audio_player.loop = true;
        } else {
            audio_player.addEventListener('ended', function() {
                this.currentTime = 0;
                this.play();
            }, false);
        }
        audio_player.load();
        audio_player.onplay = function() {
            if(first_song_play) {
                first_song_play = false;
                unmute_audio(true,true);
                $('.song_control').addClass('active_control');
                $('.song_alt_control').addClass('active_control');
                $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                controls_status['song']=true;
            }
        };
        var check_room_song = false;
        if(show_audio) {
            for(var i=0; i < panoramas.length; i++) {
                var song = panoramas[i].song;
                var audio_track_enable = panoramas[i].audio_track_enable;
                if((song!='') || (audio_track_enable)) {
                    check_room_song = true;
                }
            }
        }
        if((song_bg!='' || check_room_song) && (peer_id=='')) {
            if(song_autoplay==3) {
                audio_prompt = $.confirm({
                    lazyOpen: true,
                    theme: 'modern,audio_prompt',
                    useBootstrap: false,
                    closeIcon: false,
                    typeAnimated: true,
                    title: window.viewer_labels.enable_audio,
                    content: '',
                    boxWidth: '250px',
                    buttons: {
                        yes: {
                            text: window.viewer_labels.yes,
                            btnClass: 'btn-green',
                            action: function(){
                                if(panoramas[index_initial].audio_track_enable) {
                                    unmute_audio(true,true);
                                } else {
                                    unmute_audio(true,false);
                                }
                                $('.song_control').addClass('active_control');
                                $('.song_alt_control').addClass('active_control');
                                $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                                $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                                first_song_play = false;
                                audio_prompt_open = false;
                                controls_status['song']=true;
                                try {
                                    audio_player.play().catch(function() {});
                                } catch (e) {}
                                try {
                                    audio_player_room.play().catch(function() {});
                                    fadeVolume(audio_player_room, panoramas[index_initial].song_volume, 500);
                                } catch (e) {}
                            }
                        },
                        cancel : {
                            text: window.viewer_labels.no,
                            action: function(){
                                mute_audio(true,true);
                                $('.song_control').removeClass('active_control');
                                $('.song_alt_control').removeClass('active_control');
                                $('.song_control i').addClass('fa-volume-mute').removeClass('fa-volume-down');
                                $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
                                first_song_play = false;
                                audio_prompt_open = false;
                                controls_status['song']=false;
                                try {
                                    audio_player.pause();
                                } catch (e) {}
                                try {
                                    audio_player_room.pause();
                                } catch (e) {}
                            }
                        },
                    }
                });
            } else if(song_autoplay>0) {
                $('.song_control').addClass('active_control');
                $('.song_alt_control').addClass('active_control');
                $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                audio_player.play().then(function() {
                    if(first_song_play) {
                        if(panoramas[index_initial].audio_track_enable) {
                            unmute_audio(true,true);
                        } else {
                            unmute_audio(true,false);
                        }
                        $('.song_control').addClass('active_control');
                        $('.song_alt_control').addClass('active_control');
                        $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                        $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                        first_song_play = false;
                        audio_prompt_open = false;
                        controls_status['song']=true;
                        try {
                            audio_player.play().catch(function () {});
                        } catch (e) {}
                        if(panoramas[index_initial].song!='') {
                            audio_player_room.play().catch(function() {});
                            fadeVolume(audio_player_room, panoramas[index_initial].song_volume, 500);
                        }
                    }
                }).catch(function(error) {
                    switch(song_autoplay) {
                        case 2:
                            $(document).one("mousedown touchstart",function(e){
                                if(first_song_play) {
                                    if(panoramas[index_initial].audio_track_enable) {
                                        unmute_audio(true,true);
                                    } else {
                                        unmute_audio(true,false);
                                    }
                                    $('.song_control').addClass('active_control');
                                    $('.song_alt_control').addClass('active_control');
                                    $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                                    $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                                    first_song_play = false;
                                    audio_prompt_open = false;
                                    controls_status['song']=true;
                                    try {
                                        audio_player.play().catch(function () {});
                                    } catch (e) {}
                                    if(panoramas[index_initial].song!='') {
                                        audio_player_room.play().catch(function() {});
                                        fadeVolume(audio_player_room, panoramas[index_initial].song_volume, 500);
                                    }
                                }
                            });
                            break;
                        case 1:
                            audio_prompt = $.confirm({
                                lazyOpen: true,
                                theme: 'modern,audio_prompt',
                                useBootstrap: false,
                                closeIcon: false,
                                typeAnimated: true,
                                title: window.viewer_labels.enable_audio,
                                content: '',
                                boxWidth: '250px',
                                buttons: {
                                    yes: {
                                        text: window.viewer_labels.yes,
                                        btnClass: 'btn-green',
                                        action: function(){
                                            if(panoramas[index_initial].audio_track_enable) {
                                                unmute_audio(true,true);
                                            } else {
                                                unmute_audio(true,false);
                                            }
                                            $('.song_control').addClass('active_control');
                                            $('.song_alt_control').addClass('active_control');
                                            $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                                            $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                                            first_song_play = false;
                                            audio_prompt_open = false;
                                            controls_status['song']=true;
                                            try {
                                                audio_player.play().catch(function() {});
                                            } catch (e) {}
                                            try {
                                                audio_player_room.play().catch(function() {});
                                                fadeVolume(audio_player_room, panoramas[index_initial].song_volume, 500);
                                            } catch (e) {}
                                        }
                                    },
                                    cancel : {
                                        text: window.viewer_labels.no,
                                        action: function(){
                                            mute_audio(true,true);
                                            $('.song_control').removeClass('active_control');
                                            $('.song_alt_control').removeClass('active_control');
                                            $('.song_control i').addClass('fa-volume-mute').removeClass('fa-volume-down');
                                            $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
                                            first_song_play = false;
                                            audio_prompt_open = false;
                                            controls_status['song']=false;
                                            try {
                                                audio_player.pause();
                                            } catch (e) {}
                                            try {
                                                audio_player_room.pause();
                                            } catch (e) {}
                                        }
                                    },
                                }
                            });
                            break;
                    }
                });
            }
        } else {
            mute_audio(true,true);
            $('.song_control').removeClass('active_control');
            $('.song_alt_control').removeClass('active_control');
            $('.song_control i').addClass('fa-volume-mute').removeClass('fa-volume-down');
            $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
            first_song_play = false;
            controls_status['song']=false;
            try {
                audio_player.pause();
            } catch (e) {}
        }
        if(array_maps.length>0) {
            $('.map').append(html_map);
            if(array_maps.length>1) {
                $('.map_selector_control').show();
                $('.map_name').css('padding-left','2px');
            } else {
                $('.map_selector_control').hide();
            }
            $('.map_pointer_circle').tooltipster({
                animation: 'grow',
                delay: 0,
                arrow: false,
                theme: 'tooltipster-borderless',
                side: 'bottom'
            });
            $('.all_maps').hide();
            $('.map_pointer_container').hide();
            id_current_map = panoramas[index_initial].id_map;
            if(!isNaN(id_current_map)) {
                $('.map_'+id_current_map).show();
                $('.pointer_map_'+id_current_map).show();
            } else {
                id_current_map = array_maps[0].id;
                $('.map_'+id_current_map).show();
                $('.pointer_map_'+id_current_map).show();
            }
            for(var k=0; k < array_maps.length; k++) {
                if(array_maps[k].id==id_current_map) {
                    if(array_maps[k].info_link!='') {
                        var info_map = '&nbsp;&nbsp;<i onclick="open_info_map(\''+array_maps[k].info_link+'\',\''+array_maps[k].info_type+'\');" class="fas fa-info-circle info_map_btn"></i>';
                    } else {
                        var info_map = '';
                    }
                    $('.map_name').html(array_maps[k].name+info_map);
                }
            }
            jQuery.each(imgs_loaded, function(index, id_load) {
                $('#pointer_f_'+id_load+' i').remove();
                $('#pointer_f_'+id_load).removeClass('disabled');
            });
            $('.map_pointer_circle').on('click',function () {
                var id_room_target = $(this).data('id');
                if(id_room_target==current_id_panorama) return;
                goto('',[id_room_target,null,null,null,null,null,null,null]);
            });
            $('.all_maps').each(function () {
                var id_map = $(this).attr('data-id');
                var map_elem = $('.map_'+id_map+' .map_wrapper')[0];
                panzoom_map[id_map] = Panzoom(map_elem, {
                    cursor: 'default',
                    maxScale: 3,
                    minScale: 1,
                    step: 0.3,
                    panOnlyWhenZoomed: true,
                    contain: 'outside',
                    excludeClass: 'map_pointer_circle'
                });
                map_elem.parentElement.addEventListener('wheel', panzoom_map[id_map].zoomWithWheel);
                map_elem.addEventListener('panzoomchange', (event) => {
                    var current_scale = parseFloat(event.detail.scale).toFixed(1);
                    if(current_scale<=1) {
                        $('.map_zoom_minus_control').css({'opacity':0.5,'pointer-events':'none'});
                        $('.map_zoom_plus_control').css({'opacity':1,'pointer-events':'initial'});
                    } else if (current_scale>=3) {
                        $('.map_zoom_plus_control').css({'opacity':0.5,'pointer-events':'none'});
                        $('.map_zoom_minus_control').css({'opacity':1,'pointer-events':'initial'});
                    } else {
                        $('.map_zoom_plus_control').css({'opacity':1,'pointer-events':'initial'});
                        $('.map_zoom_minus_control').css({'opacity':1,'pointer-events':'initial'});
                    }
                })
            });
        }
        if(window.initial_yaw!='') {
            var yaw_i = parseFloat(window.initial_yaw);
        } else {
            var yaw_i = null;
        }
        if(window.initial_pitch!='') {
            var pitch_i = parseFloat(window.initial_pitch);
        } else {
            var pitch_i = null;
        }
        if(panoramas[index_initial].virtual_staging!=0 && window.flyin!=0) {
            $('#background_pano').css('opacity',0);
            $('#vs_slider').css('opacity',0);
            $('#vs_grab').css('opacity',0);
        }
        if(window.background_video=='') {
            initialize_room(index_initial,false,false,pitch_i,yaw_i,null, null,false);
        }
        $('#progress_msg').html('<span>'+window.viewer_labels.progress_finish+'</span>&nbsp;&nbsp;<i class="fas fa-check"></i>');
        progress_circle.animate(1);
        if(window.background_video!='') {
            if(window.background_video_skip==1) setTimeout(function() { $('#skip_video_intro').fadeIn(); },500);
            $('.progress-circle').animate({opacity: 0}, 1500);
            setTimeout(function() {
                $('#progress_msg').hide();
            },1500);
            interval_video_loading_check = setInterval(function() {
                if(window.video_loading_ended) {
                    clearInterval(interval_video_loading_check);
                    $('#skip_video_intro').hide();
                    initialize_room(index_initial,false,false,pitch_i,yaw_i,null, null,false);
                    setTimeout(function () {
                        switch(window.flyin) {
                            case 0:
                                complete_init();
                                break;
                            case 1:
                                init_flyin(panoramas[index_initial].panorama_image,panoramas[index_initial].yaw,panoramas[index_initial].pitch);
                                break;
                            case 2:
                                init_flyin_lp(panoramas[index_initial].panorama_image,panoramas[index_initial].yaw,panoramas[index_initial].pitch,hfov);
                                break;
                        }
                    },1000);
                }
            },1000);
        } else {
            setTimeout(function () {
                setTimeout(function() {
                    $('#progress_msg').hide();
                },1500);
                switch(window.flyin) {
                    case 0:
                        $('.progress-circle').animate({opacity: 0}, 1500);
                        complete_init();
                        break;
                    case 1:
                        $('.progress-circle').animate({opacity: 0}, 1500);
                        init_flyin(panoramas[index_initial].panorama_image,panoramas[index_initial].yaw,panoramas[index_initial].pitch);
                        break;
                    case 2:
                        init_flyin_lp(panoramas[index_initial].panorama_image,panoramas[index_initial].yaw,panoramas[index_initial].pitch,hfov);
                        break;
                }
            },1000);
        }
    }

    window.change_disqus = function (index) {
        window.disqus_identifier = window.id_virtualtour+'_room'+panoramas[index].id;
        window.disqus_title = window.name_vt+' - '+panoramas[index].name;
        window.disqus_url = window.url_vt+"/index.php?code="+window.code+'/#!'+panoramas[index].id;
        $('.disqus-comment-count').attr('data-disqus-identifier',disqus_identifier);
        DISQUS.reset({
            reload: true,
            config: function () {
                this.page.identifier = window.disqus_identifier;
                this.page.title = window.disqus_title;
                this.page.url = window.disqus_url;
                this.callbacks.onNewComment = [function(comment) {
                    if(window.disqus_public_key=='') {
                        DISQUSWIDGETS.getCount({reset: true});
                    } else {
                        get_disqus_comments_count(disqus_identifier);
                    }
                }];
            }
        });
        if(window.disqus_public_key=='') {
            DISQUSWIDGETS.getCount({reset: true});
        } else {
            get_disqus_comments_count(disqus_identifier);
        }
    };

    function get_disqus_comments_count() {
        $.ajax({
            url: 'https://disqus.com/api/3.0/threads/details.json',
            type: 'GET',
            async: true,
            data: {
                api_key: window.disqus_public_key,
                forum: disqus_shortname,
                thread: 'ident:' + disqus_identifier
            },
            success: function(result) {
                var commentsCount = result.response.posts;
                if(commentsCount==1) {
                    commentsCount = '<strong>'+commentsCount.toString() + '</strong> <span class="comments_label">' + window.viewer_labels.comment + '</span>';
                } else {
                    commentsCount = '<strong>'+commentsCount.toString() + '</strong> <span class="comments_label">' + window.viewer_labels.comments + '</span>';
                }
                $('.disqus-comment-count').html(commentsCount);
            },
            error: function() {
                DISQUSWIDGETS.getCount({reset: true});
            }
        });
    }

    window.initialize_disqus = function() {
        switch(window.comments) {
            case 1:
                window.disqus_identifier = window.id_virtualtour;
                window.disqus_title = window.name_vt;
                window.disqus_url = window.url_vt+"/index.php?code="+window.code;
                break;
            case 2:
                window.disqus_identifier = window.id_virtualtour+'_room'+panoramas[index_initial].id;
                window.disqus_title = window.name_vt+' - '+panoramas[index_initial].name;
                window.disqus_url = window.url_vt+"/index.php?code="+window.code+'/#!'+panoramas[index_initial].id;
                break;
        }
        var disqus_config = function () {
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
            this.page.url = disqus_url;
            this.callbacks.onNewComment = [function(comment) {
                if(window.disqus_public_key=='') {
                    DISQUSWIDGETS.getCount({reset: true});
                } else {
                    get_disqus_comments_count(disqus_identifier);
                }
            }];
        };
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.id = "disqus_script";
            dsq.src = location.protocol + '//' + window.disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
            dsq.onload = function() {
                $('.disqus-comment-count').attr('data-disqus-identifier',disqus_identifier);
                $('.comments_vt').removeClass('disabled_cookie');
                $('#comments_control').removeClass('loading_spinner_icon');
                if(window.disqus_public_key=='') {
                    DISQUSWIDGETS.getCount({reset: true});
                } else {
                    get_disqus_comments_count(disqus_identifier);
                }
            }
        })();
    }

    function complete_init() {
        if(announce!=null) view_announce();
        $('.loading').animate({
            opacity: 0
        }, { duration: 500, queue: false });
        if(window.learning_mode>0) {
            if($('#learning-intro-modal').length) {
                setTimeout(function() {
                    $('#learning-intro-modal').animate({
                        opacity: 1
                    }, { duration: 500, queue: false });
                    $('#learning-intro-modal').css('pointer-events','initial');
                },0);
            } else {
                start_learning();
            }
        }
        if(panoramas[index_initial].autorotate_override==1) {
            var autorotate_speed_h = panoramas[index_initial].autorotate_speed;
            var autorotate_inactivity_h = panoramas[index_initial].autorotate_inactivity;
        } else {
            var autorotate_speed_h = autorotate_speed;
            var autorotate_inactivity_h = autorotate_inactivity;
        }
        setTimeout(function () {
            if(window.comments!=0) {
                if(window.cookie_consent==0) {
                    initialize_disqus();
                } else {
                    if(CookieConsent.acceptedService('Comments (Disqus)', 'functionality')) {
                        initialize_disqus();
                    }
                }
            }
            if(show_dollhouse==2) {
                view_dollhouse();
            }
            if(show_inline_form==1) {
                $('.inline_form').show();
            }
            $('.loading').css('z-index',0);
            $('.loading').hide();
            $('#background_loading').hide();
            setTimeout(function() {
                adjustCenterDiv();
                adjust_elements_positions();
                $('.map_pointer_container').removeClass('hide');
            },210);
            setTimeout(function() {
                $('#intro_slider').empty();
            },500);
            if(initial_feedback!=0 && show_presentation!=2 && !live_session_connected) {
                $('.pnlm-dragfix').css('pointer-events','none');
                var time_feedback = initial_feedback/4;
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    if(autorotate_speed_h!=0) {
                        try { pano_viewer.stopAutoRotate(); } catch (e) {}
                    }
                    var yaw = parseFloat(pano_viewer.getYaw());
                    var pitch = parseFloat(pano_viewer.getPitch());
                    var hfov = parseFloat(pano_viewer.getHfov());
                    try {
                        setTimeout(function() {
                            pano_viewer.lookAt(pitch,(yaw+4),hfov,time_feedback,function() {
                                pano_viewer.lookAt(pitch,(yaw-4),hfov,time_feedback*2,function() {
                                    pano_viewer.lookAt(pitch,(yaw),hfov,time_feedback,function() {
                                        $('.pnlm-dragfix').css('pointer-events','initial');
                                        if(mouse_follow_feedback!=0) {
                                            window.viewer_mov_follow_mouse = true;
                                        }
                                        first_mov_follow_mouse = false;
                                        if(autorotate_speed_h!=0 && show_autorotation_toggle!=2 && show_autorotation_toggle!=0) {
                                            pano_viewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                                            timeout_initial_inactivity = setTimeout(function () {
                                                pano_viewer.startAutoRotate(autorotate_speed_h);
                                            },autorotate_inactivity_h);
                                        }
                                    });
                                })
                            });
                        },250);
                    } catch (e) {
                        $('.pnlm-dragfix').css('pointer-events','initial');
                    }
                } else {
                    if(autorotate_speed_h!=0) {
                        try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
                    }
                    var yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
                    var hfov = parseFloat(video_viewer.pnlmViewer.getHfov());
                    try {
                        setTimeout(function() {
                            video_viewer.pnlmViewer.lookAt(pitch,(yaw+4),hfov,time_feedback,function() {
                                video_viewer.pnlmViewer.lookAt(pitch,(yaw-4),hfov,time_feedback*2,function() {
                                    video_viewer.pnlmViewer.lookAt(pitch,(yaw),hfov,time_feedback,function() {
                                        $('.pnlm-dragfix').css('pointer-events','initial');
                                        if(mouse_follow_feedback!=0) {
                                            window.viewer_mov_follow_mouse = true;
                                        }
                                        first_mov_follow_mouse = false;
                                        if(autorotate_speed_h!=0) {
                                            video_viewer.pnlmViewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                                            timeout_initial_inactivity = setTimeout(function () {
                                                video_viewer.pnlmViewer.startAutoRotate(autorotate_speed_h);
                                            },autorotate_inactivity_h);
                                        }
                                    });
                                })
                            });
                        },250);
                    } catch (e) {
                        $('.pnlm-dragfix').css('pointer-events','initial');
                    }
                }
            } else {
                if(mouse_follow_feedback!=0) {
                    window.viewer_mov_follow_mouse = true;
                }
                first_mov_follow_mouse = false;
            }
            if(panoramas[index_initial].virtual_staging==2) {
                mrv_initialized = 1;
                next_mrv_panorama(panoramas[index_initial].lp_duration,panoramas[index_initial].lp_fade);
            }
        },500);
        if(window.ar_simulator==1) {
            setTimeout(function () {
                init_ar_simulator();
            },0);
        }
        if(audio_prompt!=null && !$('#learning-intro-modal').length) {
            audio_prompt_open = true;
            audio_prompt.open();
        }
        $('.panorama').css('z-index','unset');
        if(panoramas[index_initial].type=='image' || (panoramas[index_initial].type=='video' && window.is_mobile) || panoramas[index_initial].type=='hls' || panoramas[index_initial].type=='lottie') {
            $('#panorama_viewer').animate({
                opacity: 1
            }, { duration: 250, queue: false });
            $('#panorama_viewer').css('z-index',10);
            if(panoramas[index_initial].virtual_staging!=0) {
                $('#background_pano').css('opacity',1);
                $('#panorama_viewer_alt').animate({
                    opacity: 1
                }, { duration: 250, queue: false });
                $('#panorama_viewer_alt').css('z-index',10);
                $('#vs_slider').css('opacity',1);
                $('#vs_grab').css('opacity',1);
            }
        } else {
            $('#video_viewer').animate({
                opacity: 1
            }, { duration: 250, queue: false });
            $('#video_viewer').css('z-index',10);
        }
        $('.header_vt').show();
        var annotation_title = panoramas[index_initial].annotation_title;
        var annotation_description = panoramas[index_initial].annotation_description;
        if(((annotation_title!='') || (annotation_description!='')) && (show_annotations!=0)) {
            var a_both = 0;
            if(annotation_title!='') {
                $('.annotation_title').html(annotation_title);
                a_both++;
            }
            if(annotation_description!='') {
                $('.annotation_description').html(annotation_description);
                a_both++;
            }
            if(a_both==2) {
                $('.annotation hr').show();
            } else {
                $('.annotation hr').hide();
            }
            $('.annotation').show();
        } else {
            $('.annotation').hide();
        }
        if(array_maps.length>0) {
            switch (show_map) {
                case 0:
                    controls_status['map']=false;
                    $('.map').hide();
                    break;
                case 1:
                    if(window.is_mobile) {
                        $('.map').hide();
                        controls_status['map']=false;
                    } else {
                        $('.map').show();
                        controls_status['map']=true;
                    }
                    break;
                case 2:
                    $('.map').hide();
                    controls_status['map']=false;
                    break;
                case 3:
                    $('.map').show();
                    controls_status['map']=true;
                    break;
                case 4:
                    $('.map').hide();
                    $(".map").addClass('map_zoomed');
                    $('.map_zoom_control').hide();
                    $('.map_close_control').css('right','2px');
                    controls_status['map']=false;
                    break;
                case 5:
                    $('.map').show();
                    zoom_map();
                    controls_status['map']=true;
                    break;
            }
        } else {
            $('.map').hide();
            controls_status['map']=false;
        }
        $('.menu_controls').show();
        add_custom_controls();
        $(document).trigger('resize');
        if (logo !== '' && show_logo > 0) {
            let shouldShow_l = false;
            switch (show_logo) {
                case 1:
                    shouldShow_l = true;
                    break;
                case 2:
                    shouldShow_l = !window.is_mobile;
                    break;
                case 3:
                    shouldShow_l = window.is_mobile;
                    break;
            }
            if (shouldShow_l) {
                $('.logo').html(html_logo).show();
            }
        }
        adjust_elements_positions();
        $('.fullscreen_control').show();
        switch(arrows_nav) {
            case 0:
                $('.arrows_nav').hide();
                $('.arrows_nav').addClass('hidden');
                $('.controls_arrows .prev_arrow').addClass('hidden');
                $('.controls_arrows .next_arrow').addClass('hidden');
                break;
            case 1:
                $('.arrows_nav').show();
                break;
            case 2:
                if(window.is_mobile) {
                    $('.arrows_nav').hide();
                    $('.arrows_nav').addClass('hidden');
                    $('.controls_arrows .prev_arrow').addClass('hidden');
                    $('.controls_arrows .next_arrow').addClass('hidden');
                } else {
                    $('.arrows_nav').show();
                }
                break;
        }
        $('.map_pointer_container').removeClass('active');
        $('#pointer_f_'+panoramas[index_initial].id).addClass('active');
        var poi_embed_count = $('.poi_embed').length;
        if(poi_embed_count>0) {
            init_poi_embed();
        }
        var marker_embed_count = $('.marker_embed').length;
        if(marker_embed_count>0) {
            init_marker_embed();
        }
        setTimeout(function () {
            if(auto_show_slider!=2) {
                sly = new Sly('#list_slider_main', {
                    slidee: '#list_slider_main .slidee',
                    horizontal: 1,
                    itemNav: 'centered',
                    smart: 1,
                    mouseDragging: 1,
                    touchDragging: 1,
                    releaseSwing: 1,
                    scrollBy: 1,
                    speed: 300,
                    elasticBounds: 1,
                    dragHandle: 1,
                    dynamicHandle: 1,
                    clickBar: 1,
                    startAt: index_initial,
                });
                sly.init();
                $('.list_slider_cat').each(function() {
                    var id_category = $(this).attr('data-id');
                    sly_cat[id_category] = new Sly('#list_slider_cat_'+id_category, {
                        slidee: '#list_slider_cat_'+id_category+' .slidee_cat',
                        horizontal: 1,
                        itemNav: 'centered',
                        smart: 1,
                        mouseDragging: 1,
                        touchDragging: 1,
                        releaseSwing: 1,
                        scrollBy: 1,
                        speed: 300,
                        elasticBounds: 1,
                        dragHandle: 1,
                        dynamicHandle: 1,
                        clickBar: 1,
                        startAt: 0,
                    });
                    sly_cat[id_category].init();
                });
            }
            $('.pointer_list').removeClass('active');
            $('.pointer_list_cat').removeClass('active');
            $('.pointer_list_'+panoramas[index_initial].id).addClass('active');
            $('#list_slider_main .cat_image_grid img').each(function() {
                var id_room_sg = $(this).attr('data-id-room');
                if(parseInt(id_room_sg) == parseInt(panoramas[index_initial].id)) {
                    $(this).parent().parent().addClass('active');
                    return;
                }
            });
            $('.pointer_list').on('mouseenter', function () {
                if(!window.is_mobile && window.preview_room_slider==1) {
                    var id = $(this).attr('data-id');
                    var image = $(this).attr('data-panorama');
                    var protect = $(this).attr('data-protected');
                    var min_yaw = $(this).attr('data-min_yaw');
                    var max_yaw = $(this).attr('data-max_yaw');
                    var haov = $(this).attr('data-haov');
                    var vaov = $(this).attr('data-vaov');
                    var hfov = $(this).attr('data-hfov');
                    if(image!='') {
                        clearTimeout(timeout_destroy);
                        if(protect==0) {
                            initialize_panorama_preview(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                        } else {
                            try {
                                panorama_preview.destroy();
                            } catch (e) {}
                        }
                    }
                }
            });
            $('.pointer_list').on('mouseleave', function () {
                if(!window.is_mobile && window.preview_room_slider==1) {
                    $('.panorama_preview').css('opacity', 0);
                    timeout_destroy = setTimeout(function () {
                        try {
                            panorama_preview.destroy();
                        } catch (e) {}
                    }, 300);
                }
            });
            $('.pointer_list').on('mousedown touchstart',function () {
                drag_slider_start = new Date().getTime();
                drag_slider = false;
            });
            $('.pointer_list').on('mousemove touchmove',function () {
                drag_slider_end = new Date().getTime();
                drag_slider = true;
            });
            $('.pointer_list').on('click',function (event) {
                var id_room_target = parseInt($(this).data('id'));
                if(current_id_panorama==id_room_target) return;
                var diff_drag = drag_slider_end - drag_slider_start;
                if(drag_slider == false || diff_drag < 80) {
                    if(!event.target.classList.contains('panorama_preview')) {
                        $('.panorama_preview').css('opacity', 0);
                        try {
                            panorama_preview.destroy();
                        } catch (e) {}
                        goto('', [id_room_target,null,null,null,null,null,null,null]);
                    }
                }
            });
            $('.pointer_list_cat').on('mousedown touchstart',function () {
                drag_slider_start = new Date().getTime();
                drag_slider = false;
            });
            $('.pointer_list_cat').on('mousemove touchmove',function () {
                drag_slider_end = new Date().getTime();
                drag_slider = true;
            });
            $('.pointer_list_cat').on('click',function (event) {
                var id_category = $(this).attr('data-id-category');
                var diff_drag = drag_slider_end - drag_slider_start;
                if(drag_slider == false || diff_drag < 80) {
                    $('.list_slider').addClass('hidden_slider');
                    $('#list_slider_cat_'+id_category).removeClass('hidden_slider');
                    sliders_reload();
                }
            });
            $('.pointer_list_back').on('mousedown touchstart',function () {
                drag_slider_start = new Date().getTime();
                drag_slider = false;
            });
            $('.pointer_list_back').on('mousemove touchmove',function () {
                drag_slider_end = new Date().getTime();
                drag_slider = true;
            });
            $('.pointer_list_back').on('click',function (event) {
                var diff_drag = drag_slider_end - drag_slider_start;
                if(drag_slider == false || diff_drag < 80) {
                    const $currentSlider = $(this).closest('.list_slider_cat');
                    const currentCatId = $currentSlider.data('id');
                    if (!currentCatId || typeof array_panoramas_category === 'undefined' || !array_panoramas_category[currentCatId]) {
                        if ($currentSlider.length > 0) $currentSlider.addClass('hidden_slider');
                        $('#list_slider_main').removeClass('hidden_slider');
                        if (typeof sliders_reload === 'function') {
                            sliders_reload();
                        }
                        return;
                    }
                    const parentId = array_panoramas_category[currentCatId][0];
                    $currentSlider.addClass('hidden_slider');
                    let $sliderToShow = null;
                    if (parentId === null) {
                        $sliderToShow = $('#list_slider_main');
                    } else {
                        $sliderToShow = $('#list_slider_cat_' + parentId);
                    }
                    if ($sliderToShow && $sliderToShow.length > 0) {
                        $sliderToShow.removeClass('hidden_slider');
                        if (typeof sliders_reload === 'function') {
                            sliders_reload();
                        }
                    } else {
                        $('#list_slider_main').removeClass('hidden_slider');
                        if (typeof sliders_reload === 'function') {
                            sliders_reload();
                        }
                    }
                }
            });
            $('.list_right').on('click',function () {
                switch (nav_slider_mode) {
                    case 0:
                        var len = panoramas.length;
                        var index = get_id_viewer(current_id_panorama);
                        do {
                            var next_panorama = panoramas[(index+1)%len];
                            var visible_list = next_panorama.visible_list;
                            index++;
                        } while(visible_list==0);
                        var id_room_target = next_panorama.id;
                        goto('',[id_room_target,null,null,null,null,null,null,null]);
                        break;
                    case 1:
                        if(auto_show_slider!=2) {
                            var id_category = $(this).attr('data-id-category');
                            if(id_category==undefined) {
                                sly.nextPage();
                            } else {
                                sly_cat[id_category].nextPage();
                            }
                        }
                        break;
                }
            });
            $('.list_left').on('click',function () {
                switch (nav_slider_mode) {
                    case 0:
                        var len = panoramas.length;
                        var index = get_id_viewer(current_id_panorama);
                        do {
                            var prev_panorama = panoramas[(index+len-1)%len];
                            var visible_list = prev_panorama.visible_list;
                            index--;
                        } while(visible_list==0);
                        var id_room_target = prev_panorama.id;
                        goto('',[id_room_target,null,null,null,null,null,null,null]);
                        break;
                    case 1:
                        if(auto_show_slider!=2) {
                            var id_category = $(this).attr('data-id-category');
                            if(id_category==undefined) {
                                sly.prevPage();
                            } else {
                                sly_cat[id_category].prevPage();
                            }
                        }
                        break;
                }
            });
            switch(auto_show_slider) {
                case 0:
                    $('.list_control').show();
                    controls_status['list']=true;
                    break;
                case 1:
                    $('.list_control').show();
                    $('.list_sliders').css('z-index',1000);
                    $('.list_sliders').css('opacity',1);
                    $('.list_control').addClass('active_control');
                    reposition_bottom_controls(true,false,0);
                    $('.list_control i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
                    $('.list_control_alt').removeClass('fa-chevron-up').addClass('fa-chevron-down');
                    controls_status['list']=true;
                    break;
                case 2:
                    $('.list_control').addClass('hidden');
                    $('.list_control_alt').addClass('hidden');
                    controls_status['list']=false;
                    break;
            }
            if((show_device_orientation==2 || show_device_orientation==3) && window.is_mobile) {
                if (typeof DeviceOrientationEvent !== 'undefined' &&
                    typeof DeviceOrientationEvent.requestPermission === 'function') {
                    DeviceOrientationEvent.requestPermission().then(response => {
                        if(response == "granted") {
                            toggle_orient();
                        }
                    }).catch(function () {
                        $.confirm({
                            lazyOpen: false,
                            theme: 'modern,deivce_motion_prompt',
                            useBootstrap: false,
                            closeIcon: false,
                            typeAnimated: true,
                            title: window.viewer_labels.enable_device_motion,
                            content: '',
                            boxWidth: '250px',
                            buttons: {
                                yes: {
                                    text: window.viewer_labels.yes,
                                    btnClass: 'btn-green',
                                    action: function(){
                                        $('.orient_control').addClass('active_control');
                                        $('.orient_control .fa-circle').removeClass('not_active').addClass('active');
                                        controls_status['orient']=true;
                                        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                            pano_viewer.startOrientation();
                                        } else {
                                            video_viewer.pnlmViewer.startOrientation();
                                        }
                                        close_menu_controls();
                                        if(drag_device_orientation==0) $('.pnlm-dragfix').css('pointer-events','none');
                                    }
                                },
                                cancel : {
                                    text: window.viewer_labels.no,
                                    action: function(){
                                        $('.orient_control').removeClass('active_control');
                                        $('.orient_control .fa-circle').removeClass('active').addClass('not_active');
                                        controls_status['orient']=false;
                                        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                            pano_viewer.stopOrientation();
                                        } else {
                                            video_viewer.pnlmViewer.stopOrientation();
                                        }
                                    }
                                },
                            }
                        });
                    });
                } else {
                    $('.orient_control').addClass('active_control');
                    $('.orient_control .fa-circle').removeClass('not_active').addClass('active');
                    controls_status['orient']=true;
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        pano_viewer.startOrientation();
                    } else {
                        video_viewer.pnlmViewer.startOrientation();
                    }
                    close_menu_controls();
                    if(drag_device_orientation==0) $('.pnlm-dragfix').css('pointer-events','none');
                }
            }
            if((whatsapp_chat) && (whatsapp_number!='')) {
                $('.whatsapp_control').show();
                $('.whatsapp_control').css({'opacity':1,'pointer-events':'initial'});
            }
            $('.facebook_control').css({'opacity':1,'pointer-events':'initial'});
            if(show_compass) {
                $('.compass_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_fullscreen!=0 && window.fullscreen_type=='button') {
                $('.fullscreen_alt_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_map!=0 && window.floorplan_type=='button') {
                $('.floorplan_alt_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_map_tour!=0 && window.map_type=='button') {
                $('.map_alt_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_audio) {
                $('.song_alt_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_presentation!=0) {
                $('.presentation_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_info) {
                $('.info_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_custom) {
                $('.custom_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_custom2) {
                $('.custom2_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_custom3) {
                $('.custom3_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_custom4) {
                $('.custom4_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_custom5) {
                $('.custom5_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_location) {
                $('.location_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_media) {
                $('.media_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_dollhouse>0) {
                $('.dollhouse_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_gallery) {
                $('.gallery_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(window.show_share>0) {
                $('.share_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_snapshot>0) {
                $('.snapshot_control').css({'opacity':1,'pointer-events':'initial'});
                init_snapshot();
            }
            if(show_autorotation_toggle>0 && show_autorotation_toggle!=3){
                $('.autorotate_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_icons_toggle>0){
                $('.icons_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_icons_content_toggle>0){
                $('.icons_content_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_icons_nav_toggle>0){
                $('.icons_nav_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_measures_toggle>0){
                $('.measures_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_annotations>0){
                $('.annotations_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_device_orientation>0 && show_device_orientation!=3) {
                $('.orient_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_live_session) {
                $('.live_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_meeting) {
                $('.meeting_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_webvr) {
                $('.vr_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(show_main_form==1) {
                $('.form_control').css({'opacity':1,'pointer-events':'initial'});
            }
            if(auto_show_slider!=2 || arrows_nav!=0) {
                $('.controls_arrows').css({'opacity':1,'pointer-events':'initial','display':'flex'});
                if($('.controls_arrows .prev_arrow').is(':visible')) {
                    $('.controls_arrows i:not(.hidden):first-child').css('margin-right','-7px');
                    $('.controls_arrows i:not(.hidden):nth-child(2)').css('margin-right','-9px');
                }
            }
            if(window.peer_id!='') {
                init_peer();
            } else {
                if(window.is_mobile) {
                    if(intro_mobile!='') {
                        $('.intro_img').css('display','flex');
                        if(intro_mobile_hide!=0) {
                            setTimeout(function () {
                                $('.intro_img').fadeOut();
                            },(intro_mobile_hide*1000));
                        }
                    }
                } else {
                    if(intro_desktop!='') {
                        $('.intro_img').css('display','flex');
                        if(intro_desktop_hide!=0) {
                            setTimeout(function () {
                                $('.intro_img').fadeOut();
                            },(intro_desktop_hide*1000));
                        }
                    }
                }
            }
            get_info_box();
            get_custom_box();
            preload_images();
            if(window.meeting==2) {
                toggle_meeting();
            }
            if((gallery_images.length>0 || gallery_mode=='slideshow') && show_gallery==2) {
                open_gallery();
            }
            if(autoopen_menu) {
                click_menu_controls();
            }
            if(window.background_video!='') {
                var video_loading = $("#video_loading").get(0);
                video_loading.muted = true;
                setTimeout(function () {
                    video_loading.pause();
                    video_loading.currentTime = 0;
                    $("#video_loading").remove();
                    $('#skip_video_intro').hide();
                },1000);
            }
            $('.snipcart-checkout').css({'opacity':1,'pointer-events':'initial'});
            $('.woocommerce-checkout').css({'opacity':1});
            if(shop_type=='woocommerce') {
                get_total_cart_wc();
            }
            if($('.list_sliders').css('opacity')==1) {
                reposition_bottom_controls(true, false,0);
            } else {
                reposition_bottom_controls(false, false,0);
            }
            $('#controls_bottom_center,#controls_bottom_left,#controls_bottom_right,.voice_control').css('opacity',1);
            if (show_poweredby > 0) {
                let shouldShow_p = false;
                switch (show_poweredby) {
                    case 1:
                        shouldShow_p = true;
                        break;
                    case 2:
                        shouldShow_p = !window.is_mobile;
                        break;
                    case 3:
                        shouldShow_p = window.is_mobile;
                        break;
                }
                if (shouldShow_p) {
                    $('.poweredby').show();
                    $('.poweredby').css('opacity',1);
                }
            }
            if(((presentation_type=='manual' && array_presentation.length>0) || presentation_type=='automatic') && (show_presentation==2 || window.preview_presentation!=-1)) {
                start_presentation();
            } else if(presentation_type=='video' && show_presentation==2) {
                $('.presentation_control').first().trigger('click');
            }
            if(window.flyin_enabled!=0 && autorotate_speed_h!=0 && show_autorotation_toggle!=2 && show_autorotation_toggle!=0 && !live_session_connected) {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    try {
                        pano_viewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                        autorotate_timeout = setTimeout(function () {
                            pano_viewer.startAutoRotate(autorotate_speed_h);
                        },(autorotate_inactivity_h+initial_feedback));
                    } catch (e) {}
                } else {
                    try {
                        video_viewer.pnlmViewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                        autorotate_timeout = setTimeout(function () {
                            video_viewer.pnlmViewer.startAutoRotate(autorotate_speed_h);
                        },(autorotate_inactivity_h+initial_feedback));
                    } catch (e) {}
                }
            }
            if(show_media==2) {
                $('.media_control:visible').trigger('click');
            }
            if(window.export_mode==0 && window.ip_visitor!='') {
                store_visitor_init();
            }
            if($.trim($("#custom_html").html())!='') {
                $('#custom_html').fadeIn();
            }
            idleTimeout();
            fix_colors_menu();
            var room_avatar_video = '';
            if(panoramas[index_initial].avatar_video!='') {
                room_avatar_video = panoramas[index_initial].avatar_video;
            }
            if(!controls_status['presentation'] && !live_session_connected) {
                if(show_avatar_video && avatar_video!='') {
                    initialize_avatar_video('main',0,avatar_video,avatar_video_autoplay,avatar_video_hide_end,avatar_video_pause);
                } else if(show_avatar_video && room_avatar_video!='') {
                    initialize_avatar_video('room',index_initial,room_avatar_video,panoramas[index_initial].avatar_video_autoplay,panoramas[index_initial].avatar_video_hide_end,panoramas[index_initial].avatar_video_pause);
                }
            }
            window.virtual_tour_initialized = true;
            parent.postMessage({payload:'initialized'}, "*");
        },500);
        if(autoclose_menu) {
            $('body').on('click', '.menu_controls .dropdown p', function () {
                close_menu_controls();
            });
            $('body').on('click', '#ms_controls .ms_control', function () {
                close_menu_sidebar();
            });
        }
        if(autoclose_list_alt) {
            $('body').on('click', '.list_alt_menu .dropdown p:not(.cat)', function () {
                close_list_alt_menu();
            });
            $('body').on('click', '#ms_list_rooms .dropdown p:not(.cat)', function () {
                close_menu_sidebar();
            });
        }
        if(autoclose_slider) {
            $('body').on('click', '.pointer_list', function () {
                close_list();
            });
        }
        if(autoclose_map) {
            $('body').on('click', '.map_pointer_container', function () {
                if(show_map==4) {
                    toggle_map();
                } else {
                    if($(".map").hasClass("map_zoomed")) {
                        $(".map").removeClass('map_zoomed');
                        $('#map_zoomed_background').hide();
                        $('.map_zoom_control i').addClass('fa-expand-alt').removeClass('fa-compress-alt');
                        resize_maps();
                        try {
                            var id = get_id_viewer(current_id_panorama);
                            if(!isNaN(panoramas[id].id_map)) {
                                panzoom_map[panoramas[id].id_map].reset();
                                $('.map_zoom_minus_control').css({'opacity':0.5,'pointer-events':'none'});
                                $('.map_zoom_plus_control').css({'opacity':1,'pointer-events':'initial'});
                            }
                        } catch (e) {}
                    }
                }
            });
        }
    }

    let loadedmetadataListener, clickListener, errorListener, timeupdateListener, canplaythroughListener, loadeddataListener, endedListener, mouseoverListener, mouseoutListener;
    function initialize_avatar_video(type,index_a,avatar_video,autoplay,hide_end,pause) {
        $('.avatar_video').show();
        if(pause) {
            $('.avatar_video').addClass('can_pause');
        } else {
            $('.avatar_video').removeClass('can_pause');
        }
        $('.avatar_video .div_play_btn').hide();
        $('.avatar_video .div_pause_btn').hide();
        $('.avatar_video').css('opacity',1);
        $('.avatar_video video').css('opacity',0);
        var video = $('.avatar_video video')[0];
        video.currentTime = 0;
        video.pause();
        if(clickListener) {
            video.removeEventListener('click', clickListener);
        }
        if(mouseoverListener) {
            video.removeEventListener('mousemove', mouseoverListener);
        }
        if(mouseoutListener) {
            video.removeEventListener('mouseout', mouseoutListener);
        }
        if (loadedmetadataListener) {
            video.removeEventListener('loadedmetadata', loadedmetadataListener);
        }
        if (errorListener) {
            video.removeEventListener('error', errorListener);
        }
        if (timeupdateListener) {
            video.removeEventListener('timeupdate', timeupdateListener);
        }
        if (canplaythroughListener) {
            video.removeEventListener('canplaythrough', canplaythroughListener);
        }
        if (loadeddataListener) {
            video.removeEventListener('loadeddata', loadeddataListener);
        }
        if (endedListener) {
            video.removeEventListener('ended', endedListener);
        }
        if(pause) {
            if(window.is_mobile) {
                clickListener = (event) => {
                    if (!video.paused) {
                        pause_avatar_video();
                    }
                };
                video.addEventListener('click', clickListener);
            } else {
                mouseoverListener = (event) => {
                    if (!video.paused) {
                        $('.avatar_video .div_pause_btn').show();
                    } else {
                        $('.avatar_video .div_pause_btn').hide();
                    }
                };
                video.addEventListener('mousemove', mouseoverListener);
                mouseoutListener = (event) => {
                    if (!event.relatedTarget || !event.relatedTarget.closest('.div_pause_btn')) {
                        $('.avatar_video .div_pause_btn').hide();
                    }
                };
                video.addEventListener('mouseout', mouseoutListener);
            }
        }
        loadedmetadataListener = (event) => {
            $('.avatar_video .div_loading_avatar').fadeIn();
        };
        video.addEventListener('loadedmetadata', loadedmetadataListener);
        errorListener = (event) => {
            $('.avatar_video .div_loading_avatar').fadeOut();
            video.removeAttribute('src');
            $('.avatar_video').hide();
            $('.avatar_video').css('opacity', 0);
        };
        video.addEventListener('error', errorListener);
        timeupdateListener = function() {
            if (!video.paused) {
                if(video.currentTime>0) {
                    $('.avatar_video .div_play_btn').hide();
                    switch(type) {
                        case 'main':
                            main_avtar_video_playing = true;
                            break;
                        case 'room':
                            panoramas[index_a].avatar_video_played = 1;
                            break;
                    }
                }
            }
        };
        video.addEventListener('timeupdate', timeupdateListener);
        var first_time_canplay = false;
        canplaythroughListener = (event) => {
            if(!first_time_canplay) {
                first_time_canplay = true;
                if(autoplay==1) {
                    $('.avatar_video .div_loading_avatar').fadeOut();
                    _checkAutoPlay(video.play(),'video_avatar');
                } else {
                    $('.avatar_video .div_loading_avatar').hide();
                    $('.avatar_video .div_play_btn').show();
                    video.currentTime = 0;
                    video.pause();
                }
            }
        };
        video.addEventListener('canplaythrough', canplaythroughListener);
        loadeddataListener = (event) => {
            setTimeout(function() {
                $('.avatar_video video').animate({opacity: 1}, 300);
                video.currentTime = 0;
            },300);
        };
        video.addEventListener('loadeddata', loadeddataListener);
        endedListener = (event) => {
            var index_panorama = get_id_viewer(current_id_panorama);
            if(panoramas[index_panorama].avatar_video!='' && type=='main') {
                hide_end=1;
            }
            if(hide_end==1) {
                var opacity_to = 0;
                var opacity_time = 300;
            } else {
                var opacity_to = 1;
                var opacity_time = 0;
            }
            $('.avatar_video video').animate({opacity: opacity_to}, opacity_time, false, function() {
                video.currentTime = 0;
                video.pause();
                if(hide_end==1) {
                    video.removeAttribute('src');
                    video.load();
                    $('.avatar_video').hide();
                    $('.avatar_video').css('opacity',0);
                } else {
                    $('.avatar_video .div_play_btn').show();
                }
                if(main_avtar_video_playing) {
                    main_avtar_video_playing = false;
                    var room_avatar_video = '';
                    var index_panorama = get_id_viewer(current_id_panorama);
                    if(panoramas[index_panorama].avatar_video!='') {
                        room_avatar_video = panoramas[index_panorama].avatar_video;
                        initialize_avatar_video('room',index_panorama,room_avatar_video,panoramas[index_panorama].avatar_video_autoplay,panoramas[index_panorama].avatar_video_hide_end,panoramas[index_panorama].avatar_video_pause);
                    }
                } else {
                    avatar_video_playing = false;
                    if(controls_status['song']) {
                        fadeVolume(audio_player, song_bg_volume_sel, 500);
                        var index_panorama = get_id_viewer(current_id_panorama);
                        fadeVolume(audio_player_room, panoramas[index_panorama].song_volume, 500);
                        try {
                            var video_elem = document.getElementById('video_viewer_html5_api');
                            fadeVolume(video_elem, 1, 500);
                        } catch (e) {}
                        try {
                            fadeVolume(video_p, 1, 500);
                        } catch (e) {}
                    }
                }
            });
        };
        video.addEventListener('ended', endedListener);
        video.src = get_video_src_support(avatar_video);
        video.load();
    }

    function sliders_reload() {
        var vt_container = document.getElementById('vt_container');
        var width_vt_container = vt_container.innerWidth || vt_container.clientWidth;
        setTimeout(function() {
            try {
                if(auto_show_slider!=2) sly.reload();
            } catch (e) {}
            try {
                if(auto_show_slider!=2) {
                    jQuery.each(sly_cat, function(id_c, sly_c) {
                        sly_c.reload();
                    });
                }
            } catch (e) {}
            if (nav_slider !== 2 && (window.is_mobile === false || nav_slider !== 1)) {
                $('.list_slider').each(function() {
                    var width_slider = parseInt($(this).find('ul').css('width').replace('px',''));
                    if(width_slider>(width_vt_container+90)) {
                        $(this).find('.list_left').removeClass('hidden');
                        $(this).find('.list_right').removeClass('hidden');
                    } else {
                        $(this).find('.list_left').addClass('hidden');
                        $(this).find('.list_right').addClass('hidden');
                    }
                });
                $('.list_slider_cat').each(function() {
                    var back_elem = $(this).find('.pointer_list_back')[0];
                    var arrow_left = $(this).find('.fa-chevron-left')[0];
                    if(isOverlapping(back_elem,arrow_left)) {
                        back_elem.style.marginLeft = '30px';
                    } else {
                        back_elem.style.marginLeft = '0';
                    }
                });
            }
            check_slider_cat_name();
        },10);
    }

    function get_video_src_support(avatar_video) {
        var src = '';
        var array_videos = avatar_video.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(webm_video!='' && mov_video!='') {
            if(supportsHEVCAlpha()) {
                if(window.s3_enabled==1) {
                    src = window.s3_url+mov_video;
                } else {
                    src = mov_video;
                }
            } else {
                if(window.s3_enabled==1) {
                    src = window.s3_url+webm_video;
                } else {
                    src = webm_video;
                }
            }
        } else if(webm_video!='' && mov_video=='') {
            if(window.s3_enabled==1) {
                src = window.s3_url+webm_video;
            } else {
                src = webm_video;
            }
        } else if(webm_video=='' && mov_video!='') {
            if(window.s3_enabled==1) {
                src = window.s3_url+mov_video;
            } else {
                src = mov_video;
            }
        }
        return src;
    }

    function initialize_panorama_preview(id,image,min_yaw,max_yaw,haov,vaov,hfov) {
        if(hfov==0) { hfov=90; } else { hfov=hfov*0.8; }
        try {
            panorama_preview.destroy();
        } catch (e) {}
        panorama_preview = pannellum.viewer('panorama_preview_'+id, {
            "type": "equirectangular",
            "autoLoad": true,
            "avoidShowingBackground": true,
            "autoRotate": -20,
            "showControls": false,
            "compass": false,
            "minYaw": parseInt(min_yaw),
            "maxYaw": parseInt(max_yaw),
            "haov": parseInt(haov),
            "vaov": parseInt(vaov),
            "hfov": parseInt(hfov),
            "panorama": ((window.s3_enabled) ? window.s3_url : '')+"panoramas/lowres/"+image+((window.s3_enabled) ? '?s3='+s3_version : '')
        });
        panorama_preview.on('load',function () {
            setTimeout(function () {
                $('#panorama_preview_'+id).css('opacity',1);
            },50);
        });
        $('.panorama_preview').css('opacity',0);
    }

    function isAnyElementVisible(id) {
        var controlsBottomLeft = document.getElementById(id);
        if(controlsBottomLeft!==null && controlsBottomLeft!==undefined) {
            var childElements = controlsBottomLeft.children;
            for (var i = 0; i < childElements.length; i++) {
                var element = childElements[i];
                var style = window.getComputedStyle(element);
                if (style.display !== 'none' && style.visibility !== 'hidden') {
                    return true;
                }
            }
        }
        return false;
    }

    window.adjust_elements_positions = function () {
        if(!isAnyElementVisible('controls_arrows_left')) {
            $('#controls_arrows_left').addClass('hidden');
        }
        if(!isAnyElementVisible('controls_arrows_center')) {
            $('#controls_arrows_center').addClass('hidden');
        }
        if(!isAnyElementVisible('controls_arrows_right')) {
            $('#controls_arrows_right').addClass('hidden');
        }
        if(isAnyElementVisible('controls_bottom_right')) {
            var height_b_right = $('#controls_bottom_right')[0].getBoundingClientRect().height;
            height_b_right = height_b_right + 8;
        } else {
            var height_b_right = 0;
        }
        if(isAnyElementVisible('controls_bottom_left')) {
            var height_b_left = $('#controls_bottom_left')[0].getBoundingClientRect().height;
            height_b_left = height_b_left + 8;
        } else {
            var height_b_left = 0;
        }
        if(isAnyElementVisible('controls_bottom_center')) {
            var height_b_center = $('#controls_bottom_center')[0].getBoundingClientRect().height;
            var margin_bottom = parseFloat($('#controls_bottom_center').css('margin-bottom').replace('px',''));
            height_b_center = height_b_center + margin_bottom + 8;
        } else {
            if(isAnyElementVisible('controls_bottom_left')) {
                var height_b_center = $('#controls_bottom_left')[0].getBoundingClientRect().height;
            } else if(isAnyElementVisible('controls_bottom_right')) {
                var height_b_center = $('#controls_bottom_right')[0].getBoundingClientRect().height;
            } else {
                var height_b_center = 0;
            }
            if($('.list_control ').is(':visible')) {
                height_b_center = height_b_center + 8 - 26;
            } else {
                height_b_center = height_b_center + 8;
            }
        }
        if($('.poweredby_bottom_right').hasClass('moved') && isAnyElementVisible('controls_bottom_center')) {
            var height_p_center = $('#controls_bottom_center')[0].getBoundingClientRect().height;
            height_b_right = height_b_right + height_p_center;
        }
        if($('.poweredby_bottom_left').hasClass('moved') && isAnyElementVisible('controls_bottom_center')) {
            var height_p_center = $('#controls_bottom_center')[0].getBoundingClientRect().height;
            height_b_left = height_b_left + height_p_center;
        }
        if(!isAnyElementVisible('controls_bottom_center') && (isAnyElementVisible('controls_bottom_left') || isAnyElementVisible('controls_bottom_right'))) {
            var bottom = 0;
            if(isAnyElementVisible('controls_bottom_left')) {
                bottom = parseFloat($('#controls_bottom_left').css('bottom').replace('px',''));
            } else if (isAnyElementVisible('controls_bottom_right')) {
                bottom = parseFloat($('#controls_bottom_right').css('bottom').replace('px',''));
            }
            if($('.list_sliders').css('opacity')==1 && bottom!=0) {
                var height_slider = $('.list_sliders').height();
                bottom = bottom - height_slider;
            }
            height_b_center = height_b_center + bottom;
        }
        $('.poweredby_bottom_right').css('margin-bottom',height_b_right+'px');
        $('.poweredby_bottom_left').css('margin-bottom',height_b_left+'px');
        $('.poweredby_bottom_center').css('margin-bottom',height_b_center+'px');
        var logo_h = $('.logo')[0].getBoundingClientRect().height;
        var annotation_h = $('.annotation')[0].getBoundingClientRect().height;
        var inline_form_h = $('#inline_form_toggle')[0].getBoundingClientRect().height;
        if(($('.menu_controls').hasClass('hidden')) && ($('.list_alt_menu').hasClass('hidden')) && ($('.song_control').hasClass('hidden'))) {
            var top_left = 5;
            $('.logo_top_left').css('top','5px');
        } else {
            var top_left = 45;
        }
        if(($('.map_control').hasClass('hidden')) && ($('.map_tour_control').hasClass('hidden')) && ($('.fullscreen_control').hasClass('hidden')) && ($('.language_menu').hasClass('hidden'))) {
            var top_right = 5;
            $('.logo_top_right').css('top','5px');
        } else {
            var top_right = 45;
        }
        $('.map_top_right').css('top',top_right+'px');
        $('.annotation_top_right').css('top',top_right+'px');
        $('.inline_form_top_right').css('top',top_right+'px');
        $('.map_top_left').css('top',top_left+'px');
        $('.annotation_top_left').css('top',top_left+'px');
        $('.inline_form_top_left').css('top',top_left+'px');
        if($('.logo').hasClass('logo_top_right') && $('.logo').is(':visible') && $('.logo').css('opacity')==1) {
            top_right += logo_h+5;
            $('.map_top_right').css('top',top_right+'px');
            $('.annotation_top_right').css('top',top_right+'px');
            $('.inline_form_top_right').css('top',top_right+'px');
        }
        if($('.annotation').hasClass('annotation_top_right') && $('.annotation').is(':visible') && $('.annotation').css('opacity')==1) {
            top_right += annotation_h+5;
            $('.map_top_right').css('top',top_right+'px');
            $('.inline_form_top_right').css('top',top_right+'px');
        }
        if($('.inline_form').hasClass('inline_form_top_right') && $('.inline_form').is(':visible')) {
            top_right += inline_form_h+5;
            $('.map_top_right').css('top',top_right+'px');
        }
        if($('.logo').hasClass('logo_top_left') && $('.logo').is(':visible') && $('.logo').css('opacity')==1) {
            top_left += logo_h+5;
            $('.map_top_left').css('top',top_left+'px');
            $('.annotation_top_left').css('top',top_left+'px');
            $('.inline_form_top_left').css('top',top_left+'px');
        }
        if($('.annotation').hasClass('annotation_top_left') && $('.annotation').is(':visible') && $('.annotation').css('opacity')==1) {
            top_left += annotation_h+5;
            $('.map_top_left').css('top',top_left+'px');
            $('.inline_form_top_left').css('top',top_left+'px');
        }
        if($('.inline_form').hasClass('inline_form_top_left') && $('.inline_form').is(':visible')) {
            top_left += inline_form_h+5;
            $('.map_top_left').css('top',top_left+'px');
        }
        if($('.logo').hasClass('logo_top_center') && $('.logo').is(':visible')) {
            $('.name_vt').css('margin-top',(logo_h+3)+'px');
        }
    }

    function enter_fullscreen() {
        var elem_body = document.getElementsByTagName("html")[0];
        try {
            if (elem_body.requestFullscreen) {
                elem_body.requestFullscreen();
            } else if (elem_body.mozRequestFullScreen) {
                elem_body.mozRequestFullScreen();
            } else if (elem_body.msRequestFullscreen) {
                elem_body.msRequestFullscreen();
            } else {
                elem_body.webkitRequestFullScreen();
            }
        } catch(event) {
            // Fullscreen doesn't work
        }
    }

    function exit_fullscreen() {
        var elem_body = document.getElementsByTagName("html")[0];
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }

    window.toggle_fullscreen = function () {
        if($('.fullscreen_control').hasClass('active_control')) {
            $('.fullscreen_control').removeClass('active_control');
            $('.fullscreen_control i').removeClass('fa-compress').addClass('fa-expand');
            $('.fullscreen_alt_control i').removeClass('fa-compress').addClass('fa-expand');
            exit_fullscreen();
            controls_status['fullscreen']=false;
        } else {
            $('.fullscreen_control').addClass('active_control');
            $('.fullscreen_control i').removeClass('fa-expand').addClass('fa-compress');
            $('.fullscreen_alt_control i').removeClass('fa-expand').addClass('fa-compress');
            enter_fullscreen();
            controls_status['fullscreen']=true;
        }
        window.scrollTo(0, 0);
        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();
            window.count_adjust_measures++;
        },1);
    }

    window.toggle_jitsi_fullscreen = function () {
        if($('#btn_jitsi_fullscreen').hasClass('active_control')) {
            $('#btn_jitsi_fullscreen').removeClass('active_control');
            $('#btn_jitsi_fullscreen').removeClass('fa-compress').addClass('fa-expand');
            $('#jitsi_div').removeClass('visible_jitsi_meet_fullscreen').addClass('visible_jitsi_meet');
        } else {
            $('#btn_jitsi_fullscreen').addClass('active_control');
            $('#btn_jitsi_fullscreen').removeClass('fa-expand').addClass('fa-compress');
            $('#jitsi_div').removeClass('visible_jitsi_meet').addClass('visible_jitsi_meet_fullscreen');
        }
    }

    window.toggle_jitsi_hide = function () {
        if($('#btn_jitsi_hide').hasClass('active_control')) {
            $('#jitsi_show').hide();
            $('#btn_jitsi_hide').removeClass('active_control');
            $('#jitsi_div').addClass('visible_jitsi_meet');
            if($('#vt_container').hasClass('open_map_tour')) {
                $('#vt_container').addClass('open_jitsi_meet_map_tour');
                $('#vt_container').removeClass('open_map_tour');
            } else {
                $('#vt_container').addClass('open_jitsi_meet');
            }
        } else {
            $('#jitsi_show').show();
            $('#btn_jitsi_hide').addClass('active_control');
            $('#btn_jitsi_fullscreen').removeClass('fa-compress').addClass('fa-expand');
            $('#btn_jitsi_fullscreen').removeClass('active_control');
            $('#jitsi_div').removeClass('visible_jitsi_meet').removeClass('visible_jitsi_meet_fullscreen');
            $('#btn_jitsi_fullscreen').removeClass('fa-compress').addClass('fa-expand');
            if($('#vt_container').hasClass('open_jitsi_meet_map_tour')) {
                $('#vt_container').removeClass('open_jitsi_meet_map_tour');
                $('#vt_container').addClass('open_map_tour');
            } else {
                $('#vt_container').removeClass('open_jitsi_meet');
            }
        }
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.close_live = function () {
        $.confirm({
            useBootstrap: false,
            closeIcon: false,
            type: 'red',
            typeAnimated: true,
            title: window.viewer_labels.lsc_title,
            content: window.viewer_labels.lsc_content,
            buttons: {
                end_call: {
                    text: window.viewer_labels.lsc_endcall,
                    btnClass: 'btn-red',
                    action: function(){
                        try {
                            window.stream_sender.getTracks().forEach(function(track) { track.stop(); })
                        } catch (e) {}
                        try {
                            call_session.close();
                        } catch (e) {}
                        $('#webcam_my').hide();
                        peer.destroy();
                        live_session_connected = false;
                        clearInterval(interval_live_session);
                        $('.live_call').hide();
                        $('.live_control').removeClass('active_control');
                        $('.live_control').removeClass('disabled');
                        $('.meeting_control').removeClass('disabled');
                        exit_sender_viewer();
                    }
                },
                cancel : {
                    text: window.viewer_labels.cancel
                },
            }
        });
    }

    window.close_live_receiver = function () {
        $.confirm({
            useBootstrap: false,
            closeIcon: false,
            type: 'red',
            typeAnimated: true,
            title: window.viewer_labels.lsc_title,
            content: window.viewer_labels.lsc_content2,
            buttons: {
                end_call: {
                    text: window.viewer_labels.lsc_endcall,
                    btnClass: 'btn-red',
                    action: function(){
                        try {
                            window.stream_sender.getTracks().forEach(function(track) { track.stop(); })
                        } catch (e) {}
                        try {
                            call_session.close();
                        } catch (e) {}
                        $('#webcam_my').hide();
                        peer.destroy();
                        $('.live_call').hide();
                    }
                },
                cancel : {
                    text: window.viewer_labels.cancel
                },
            }
        });
    }

    window.toggle_live = function () {
        if($('.live_control').hasClass('active_control')) {
            close_live();
        } else {
            if(window.livesession_protected==1) {
                confirm_password_modal = $.confirm({
                    useBootstrap: false,
                    closeIcon: false,
                    type: 'blue',
                    typeAnimated: true,
                    title: window.viewer_labels.password_livesession,
                    content: '<div style="margin: 0;overflow: hidden" class="input_material"><input autocomplete="off" id="password_livesession" type="text" /><span class="highlight"></span><span class="bar"></span></div>',
                    buttons: {
                        check: {
                            text: window.viewer_labels.check,
                            btnClass: 'btn-green',
                            action: function(){
                                $('#password_livesession').removeClass('error_input');
                                var password_livesession = $('#password_livesession').val();
                                if(password_livesession!='') {
                                    $('.jconfirm-buttons .btn').addClass('disabled');
                                    $.ajax({
                                        url: "ajax/check_password.php",
                                        type: "POST",
                                        data: {
                                            id_virtualtour: window.id_virtualtour,
                                            password: password_livesession,
                                            type: 'livesession'
                                        },
                                        async: true,
                                        success: function (json) {
                                            $('.jconfirm-buttons .btn').removeClass('disabled');
                                            var rsp = JSON.parse(json);
                                            if(rsp.status=='ok') {
                                                confirm_password_modal.close();
                                                toggle_live_enable();
                                            } else {
                                                $('#password_livesession').addClass('error_input');
                                            }
                                        }
                                    });
                                } else {
                                    $('#password_livesession').addClass('error_input');
                                }
                                return false;
                            }
                        },
                        cancel : {
                            text: window.viewer_labels.cancel
                        },
                    }
                });
            } else {
                toggle_live_enable();
            }
        }
    }

    function toggle_live_enable() {
        $('.live_control').addClass('active_control');
        $('.live_control').addClass('disabled');
        $('.meeting_control').addClass('disabled');
        close_menu_controls();
        close_list_alt_menu();
        init_peer();
    }

    window.toggle_meeting = function () {
        if($('.meeting_control').hasClass('active_control')) {
            close_menu_controls();
            close_jitsi_meet();
        } else {
            if(window.meeting_protected==1) {
                confirm_password_modal = $.confirm({
                    useBootstrap: false,
                    closeIcon: false,
                    type: 'blue',
                    typeAnimated: true,
                    title: window.viewer_labels.password_meeting,
                    content: '<div style="margin: 0;overflow: hidden" class="input_material"><input autocomplete="off" id="password_meeting" type="text" /><span class="highlight"></span><span class="bar"></span></div>',
                    buttons: {
                        check: {
                            text: window.viewer_labels.check,
                            btnClass: 'btn-green',
                            action: function(){
                                $('#password_meeting').removeClass('error_input');
                                var password_meeting = $('#password_meeting').val();
                                if(password_meeting!='') {
                                    $('.jconfirm-buttons .btn').addClass('disabled');
                                    $.ajax({
                                        url: "ajax/check_password.php",
                                        type: "POST",
                                        data: {
                                            id_virtualtour: window.id_virtualtour,
                                            password: password_meeting,
                                            type: 'meeting'
                                        },
                                        async: true,
                                        success: function (json) {
                                            $('.jconfirm-buttons .btn').removeClass('disabled');
                                            var rsp = JSON.parse(json);
                                            if(rsp.status=='ok') {
                                                confirm_password_modal.close();
                                                toggle_meeting_enable();
                                            } else {
                                                $('#password_meeting').addClass('error_input');
                                            }
                                        }
                                    });
                                } else {
                                    $('#password_meeting').addClass('error_input');
                                }
                                return false;
                            }
                        },
                        cancel : {
                            text: window.viewer_labels.cancel
                        },
                    }
                });
            } else {
                toggle_meeting_enable();
            }
        }
    }

    function toggle_meeting_enable() {
        $('.meeting_control:not(".controls_btn") span').html(window.viewer_labels.exit_meeting);
        $('.controls_btn.meeting_control').attr('title',window.viewer_labels.exit_meeting);
        $('.controls_btn.meeting_control').tooltipster('content', window.viewer_labels.exit_meeting);
        $('.meeting_control').addClass('active_control');
        $('.live_control').addClass('disabled');
        if(voice_commands_enable>0) {
            $('.voice_control').hide();
            $('#controls_bottom_left').css('padding-left','0px');
            try {
                SpeechKITT.hide();
                if (annyang) { annyang.pause(); }
            } catch (e) {}
        }
        close_menu_controls();
        open_jitsi_meet();
    }

    window.open_info_panel = function () {
        if($('#vt_container').hasClass('open_map_tour')) {
            $('#vt_container').addClass('open_jitsi_meet_map_tour');
            $('#vt_container').removeClass('open_map_tour');
        } else {
            $('#vt_container').addClass('open_jitsi_meet');
        }
        $('#info_panel_div').addClass('visible_info_panel');
        $('#info_panel_div').show();
        $('#info_panel_div').css('opacity',1);
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.close_info_panel = function () {
        close_menu_controls();
        if($('#vt_container').hasClass('open_jitsi_meet_map_tour')) {
            $('#vt_container').removeClass('open_jitsi_meet_map_tour');
            $('#vt_container').addClass('open_map_tour');
        } else {
            $('#vt_container').removeClass('open_jitsi_meet');
        }
        $('#info_panel_div').removeClass('visible_info_panel');
        setTimeout(function() {
            $('#info_panel_div').css('opacity',0);
            $('#info_panel_div').hide();
        },300);
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.close_jitsi_meet = function () {
        api_jitsi.dispose();
        $('.meeting_control:not(".controls_btn") span').html(window.viewer_labels.join_meeting);
        $('.controls_btn.meeting_control').attr('title',window.viewer_labels.join_meeting);
        $('.controls_btn.meeting_control').tooltipster('content', window.viewer_labels.join_meeting);
        $('.meeting_control').removeClass('active_control');
        $('#jitsi_show').hide();
        $('#btn_jitsi_fullscreen').removeClass('fa-compress').addClass('fa-expand');
        if(voice_commands_enable>0) {
            $('.voice_control').show();
            reposition_voice_control();
            try {
                SpeechKITT.show();
            } catch (e) {}
            if(voice_commands_enable==2) {
                try {
                    if (annyang) { annyang.resume(); }
                } catch (e) {}
            }
        }
        $('.live_control').removeClass('disabled');
        close_menu_controls();
        if($('#vt_container').hasClass('open_jitsi_meet_map_tour')) {
            $('#vt_container').removeClass('open_jitsi_meet_map_tour');
            $('#vt_container').addClass('open_map_tour');
        } else {
            $('#vt_container').removeClass('open_jitsi_meet');
        }
        $('#jitsi_div').removeClass('visible_jitsi_meet');
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.toggle_orient = function () {
        if($('.orient_control').hasClass('active_control')) {
            $('.orient_control').removeClass('active_control');
            $('.orient_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['orient']=false;
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.stopOrientation();
            } else {
                video_viewer.pnlmViewer.stopOrientation();
            }
            if(drag_device_orientation==0) {
                $('.pnlm-dragfix').css('pointer-events','initial');
            }
        } else {
            $('.orient_control').addClass('active_control');
            $('.orient_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['orient']=true;
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.startOrientation();
            } else {
                video_viewer.pnlmViewer.startOrientation();
            }
            close_menu_controls();
            if(drag_device_orientation==0) {
                $('.pnlm-dragfix').css('pointer-events','none');
            }
        }
    }

    window.open_gallery = function () {
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.stopOrientation();
        } else {
            video_viewer.pnlmViewer.stopOrientation();
        }
        switch(gallery_mode) {
            case 'images':
                if(live_session_connected) {
                    var autoplay = false;
                } else {
                    var autoplay = (parseInt(gallery_params['gallery_autoplay'])==1) ? true : false;
                }
                try {
                    $('#gallery_container').nanogallery2('destroy');
                } catch (e) {}
                var download = (parseInt(gallery_params['gallery_allow_download'])==1) ? true : false;
                gallery = $("#gallery_container").nanogallery2({
                    imageTransition: gallery_params['gallery_transition'],
                    slideshowAutoStart: autoplay,
                    slideshowDelay: parseFloat(gallery_params['gallery_slide_duration'])*1000,
                    viewerGallery: gallery_params['gallery_thumbs'],
                    thumbnailHeight:  150,
                    thumbnailWidth:   150,
                    items: gallery_images,
                    allowHTMLinData: true,
                    viewerHideToolsDelay: 30000,
                    viewerToolbar:    {
                        display:    true,
                        autoMinimize: false,
                        standard:  (download) ? 'label, downloadButton' : 'label',
                    },
                    viewerTools:    {
                        topLeft:    'pageCounter, playPauseButton',
                        topRight:   'zoomButton, closeButton'
                    }
                });
                gallery.nanogallery2('displayItem', '-1/1');
                $('.nGY2Viewer .closeButton').on('click',function () {
                    if(live_session_connected) {
                        try {
                            peer_conn.send({type:'close_gallery'});
                        } catch (e) {}
                    }
                    restart_autorotate();
                });
                break;
            case 'slideshow':
                $.fancybox.open({
                    src  : ((window.s3_enabled) ? window.s3_url : '')+'gallery/'+id_virtualtour+'_slideshow.mp4',
                    type : 'video',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false,
                    afterShow: function(current, slide) {
                        slide.$slide.find("video").on("ended", function() {
                            $.fancybox.close();
                        });
                    }
                });
                break;
        }
        if(live_session_connected) {
            try {
                peer_conn.send({type:'open_gallery'});
            } catch (e) {}
        }
    }

    window.open_product_gallery = function (id_product) {
        var product_images = [];
        var index = 1, index_active = 1;
        $('#carouselIndicators_'+id_product+' .carousel-item img').each(function() {
            var src = $(this).attr('src');
            var src_t = src.replace('products/','products/thumb/');
            var active = $(this).parent().hasClass('active');
            if(active) {
                index_active = index;
            }
            product_images.push({
                "ID":index,
                "kind":'image',
                "src":src,
                "srct":src_t,
            });
            index++;
        });
        try {
            $('#gallery_container').nanogallery2('destroy');
        } catch (e) {}
        gallery = $("#gallery_container").nanogallery2({
            imageTransition: 'swipe',
            thumbnailHeight:  150,
            thumbnailWidth:   150,
            items: product_images,
            allowHTMLinData: true,
            viewerHideToolsDelay: 30000,
            viewerToolbar:    {
                display:    true,
                autoMinimize: false,
                standard:   'label'
            },
            viewerTools:    {
                topLeft:    'pageCounter, playPauseButton',
                topRight:   'zoomButton, closeButton'
            }
        });
        gallery.nanogallery2('displayItem', '-1/'+index_active);
    }

    window.toggle_map = function () {
        if($('.map_control').hasClass('active_control')) {
            $('.map').fadeOut(200);
            $('#map_zoomed_background').fadeOut(200);
            $('.map_control').removeClass('active_control');
            $('.floorplan_alt_control').removeClass('active_control');
            $('.map_control i').removeClass('icon-map_on').addClass('icon-map_off');
            $('.floorplan_alt_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['map']=false;
            if(live_session_connected) {
                try {
                    peer_conn.send({type:'close_map'});
                } catch (e) {}
            }
        } else {
            $('.map').fadeIn(200);
            if($('.map').hasClass('map_zoomed')) {
                $('#map_zoomed_background').fadeIn(200);
            }
            $('.map_control').addClass('active_control');
            $('.floorplan_alt_control').addClass('active_control');
            $('.map_control i').removeClass('icon-map_off').addClass('icon-map_on');
            $('.floorplan_alt_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['map']=true;
            if(live_session_connected) {
                try {
                    peer_conn.send({type:'open_map'});
                } catch (e) {}
            }
        }
        setTimeout(function() {
            resize_maps();
        },200);
    }

    window.open_map = function() {
        $('.map').fadeIn(200);
        if($('.map').hasClass('map_zoomed')) {
            $('#map_zoomed_background').fadeIn(200);
        }
        $('.map_control').addClass('active_control');
        $('.floorplan_alt_control').addClass('active_control');
        $('.map_control i').removeClass('icon-map_off').addClass('icon-map_on');
        $('.floorplan_alt_control .fa-circle').removeClass('not_active').addClass('active');
        controls_status['map']=true;
        setTimeout(function() {
            resize_maps();
        },200);
    }

    window.close_map = function() {
        $('.map').fadeOut(200);
        $('#map_zoomed_background').fadeOut(200);
        $('.map_control').removeClass('active_control');
        $('.floorplan_alt_control').removeClass('active_control');
        $('.map_control i').removeClass('icon-map_on').addClass('icon-map_off');
        $('.floorplan_alt_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['map']=false;
        setTimeout(function() {
            resize_maps();
        },200);
    }

    window.toggle_tour_map = function () {
        if($('.map_tour_control').hasClass('active_control')) {
            $('.map_tour_control i').removeClass('fas').addClass('far');
            $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
            $('.map_tour_control').removeClass('active_control');
            $('.map_alt_control').removeClass('active_control');
            close_map_tour();
        } else {
            $('.map_tour_control i').removeClass('far').addClass('fas');
            $('.map_alt_control .fa-circle').removeClass('not_active').addClass('active');
            $('.map_tour_control').addClass('active_control');
            $('.map_alt_control').addClass('active_control');
            open_map_tour();
        }
    }

    window.toggle_info_panel = function (info_box_html) {
        if($('.info_control').hasClass('active_control')) {
            $('.info_control').removeClass('active_control');
            close_info_panel();
        } else {
            $('.info_control').addClass('active_control');
            $('#info_panel_div').html(info_box_html).promise().done(function() {
                open_info_panel();
            });
        }
    }

    window.close_info = function() {
        $('.info_control').removeClass('active_control');
        close_info_panel();
    }

    window.close_list = function () {
        $('.list_control').removeClass('active_control');
        reposition_bottom_controls(false,false,300);
        $('.list_control i, .list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
        controls_status['list']=false;
    }

    window.toggle_list = function () {
        if($('.list_control').hasClass('active_control')) {
            $('.list_control').removeClass('active_control');
            reposition_bottom_controls(false,false,300);
            $('.list_control i, .list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
            controls_status['list']=false;
        } else {
            $('.list_sliders').css('z-index',1000);
            $('.list_sliders').css('opacity',1);
            $('.list_control').addClass('active_control');
            reposition_bottom_controls(true,false,300);
            $('.list_control i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
            $('.list_control_alt').removeClass('fa-chevron-up').addClass('fa-chevron-down');
            controls_status['list']=true;
        }
        setTimeout(function() {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.resize();
            } else {
                video_viewer.pnlmViewer.resize();
            }
            sliders_reload();
        },300);
    }

    function reposition_bottom_controls(open,force,anim_duration) {
        window.c_width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var f_h = parseInt($('.list_sliders').height());
        var width_blc = $('#controls_bottom_left')[0].getBoundingClientRect().width+20;
        var width_brc = $('#controls_bottom_right')[0].getBoundingClientRect().width+20;
        var half_width = window.c_width/2;
        if($('.list_control').is(':visible')) {
            var bottom = 6;
            var bottom_h = 32;
            if((width_blc>=half_width) || (width_brc>=half_width)) {
                bottom = 32;
            }
        } else {
            var bottom = 6;
            var bottom_h = 6;
        }
        if(open) {
            if(force) {
                $(".list_control").animate({
                    bottom: f_h+'px',
                }, {duration: anim_duration, easing: 'easeOut',  queue: false});
                $("#controls_bottom_left,#controls_bottom_right,.voice_control").animate({
                    bottom: (f_h+bottom)+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $("#controls_bottom_center").animate({
                    bottom: (f_h+bottom_h)+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".poweredby_bottom_right,.poweredby_bottom_left").animate({
                    bottom: (f_h+bottom)+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".poweredby_bottom_center").animate({
                    bottom: (f_h+bottom_h)+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".list_sliders").animate({
                    bottom: '0px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".nav_control").animate({
                    bottom: (f_h+46)+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
            } else {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    $(".list_control").animate({
                        bottom: f_h+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_left,#controls_bottom_right,.voice_control").animate({
                        bottom: (f_h+bottom)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_center").animate({
                        bottom: (f_h+bottom_h)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_right,.poweredby_bottom_left").animate({
                        bottom: (f_h+bottom)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_center").animate({
                        bottom: (f_h+bottom_h)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".list_sliders").animate({
                        bottom: '0px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".nav_control").animate({
                        bottom: (f_h+46)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                }  else {
                    $(".list_control").animate({
                        bottom: (f_h+30)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_left,#controls_bottom_right,.voice_control").animate({
                        bottom: (f_h+30+bottom)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_center").animate({
                        bottom: (f_h+30+bottom_h)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_right,.poweredby_bottom_left").animate({
                        bottom: (f_h+30+bottom)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_cemter").animate({
                        bottom: (f_h+30+bottom_h)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".list_sliders").animate({
                        bottom: '30px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".nav_control").animate({
                        bottom: ((f_h+30+bottom_h)+46)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                }
            }
        } else {
            if(force) {
                $(".list_control").animate({
                    bottom: '0px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $("#controls_bottom_left,#controls_bottom_right,.voice_control").animate({
                    bottom: bottom+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $("#controls_bottom_center").animate({
                    bottom: bottom_h+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".poweredby_bottom_right,.poweredby_bottom_left").animate({
                    bottom: bottom+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".poweredby_bottom_center").animate({
                    bottom: bottom_h+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".list_sliders").animate({
                    bottom: '-'+f_h+'px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
                $(".nav_control").animate({
                    bottom: '46px',
                }, {duration: anim_duration, easing: 'swing', queue: false});
            } else {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    $(".list_control").animate({
                        bottom: '0px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_left,#controls_bottom_right,.voice_control").animate({
                        bottom: bottom+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_center").animate({
                        bottom: bottom_h+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_right,.poweredby_bottom_left").animate({
                        bottom: bottom+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_center").animate({
                        bottom: bottom_h+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".list_sliders").animate({
                        bottom: '-'+f_h+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".nav_control").animate({
                        bottom: '46px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                } else {
                    $(".list_control").animate({
                        bottom: '30px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_left,#controls_bottom_right,.voice_control").animate({
                        bottom: (bottom+30)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $("#controls_bottom_center").animate({
                        bottom: (bottom_h+30)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_right,.poweredby_bottom_left").animate({
                        bottom: (bottom+30)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".poweredby_bottom_center").animate({
                        bottom: (bottom_h+30)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".list_sliders").animate({
                        bottom: '-'+(f_h-30)+'px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                    $(".nav_control").animate({
                        bottom: '76px',
                    }, {duration: anim_duration, easing: 'swing', queue: false});
                }
            }
            setTimeout(function() {
                $('.list_sliders').css('z-index',0);
                $('.list_sliders').css('opacity',0);
                check_slider_cat_name();
            },300);
        }
        check_slider_cat_name();
        setTimeout(function() {
            adjustCenterDiv();
            adjust_elements_positions();
            check_slider_cat_name();
        },anim_duration);
    }

    function check_slider_cat_name() {
        if($('#controls_bottom_center').hasClass('moved')) {
            $('#controls_bottom_center').css('margin-bottom','');
            return;
        }
        if($('.list_sliders').css('opacity')==0) {
            $('#controls_bottom_center').css('margin-bottom','0');
        } else {
            let listSliderElements = $('.list_slider_cat');
            let hiddenSliderElements = listSliderElements.filter('.hidden_slider');
            if(hiddenSliderElements.length === listSliderElements.length) {
                $('#controls_bottom_center').css('margin-bottom','0');
            } else {
                $('#controls_bottom_center').css('margin-bottom','6px');
            }
        }
    }

    window.toggle_share = function () {
        if($('.share_control').hasClass('disabled_cookie')) {
            var alert_cookie = $.alert({
                theme: 'material',
                useBootstrap: false,
                boxWidth: '80%',
                type: 'dark',
                icon: 'fa-solid fa-cookie',
                title: window.viewer_labels.addtoany_social_share,
                content: window.viewer_labels.cookie_denied_msg,
                buttons: {
                    cancel: {
                        text: window.viewer_labels.cancel,
                        action: function () {
                        }
                    },
                    accept: {
                        btnClass: 'btn-black',
                        text: window.viewer_labels.open_cookie_pref,
                        action: function () {
                            alert_cookie.close();
                            CookieConsent.showPreferences();
                        }
                    }
                }
            });
        } else {
            if($('.share_control').hasClass('active_control')) {
                $('.share_popup').removeClass('show');
                $('.share_control').removeClass('active_control');
                $('.share_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['share']=false;
            } else {
                set_share_link();
                $('.share_popup').addClass('show');
                $('.share_control').addClass('active_control');
                $('.share_control .fa-circle').removeClass('not_active').addClass('active');
                controls_status['share']=true;
            }
        }
    }

    window.set_share_link = function() {
        var url_vt = '';
        switch(show_share) {
            case 1:
                url_vt =  removeURLParameters(location.href, ['nostat', 'ignore_embedded','no_pwa']);
                break;
            case 2:
                if(current_panorama_type=='image' || is_iOS() || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var current_yaw = parseFloat(pano_viewer.getYaw());
                    var current_pitch = parseFloat(pano_viewer.getPitch());
                    var current_hfov = parseFloat(pano_viewer.getHfov());
                } else {
                    var current_yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var current_pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
                    var current_hfov = parseFloat(video_viewer.pnlmViewer.getHfov());
                }
                current_yaw = current_yaw.toFixed(2);
                current_pitch = current_pitch.toFixed(2);
                current_hfov = current_hfov.toFixed(2);
                var url_base = location.href.split('/').slice(0, -1).join('/');
                if(window.friendly_url!=='') {
                    if(window.vt_language_force!=='') {
                        url_vt = url_base+'/'+window.friendly_url+'?room='+current_id_panorama+'&yaw='+current_yaw+'&pitch='+current_pitch+'&hfov='+current_hfov+'&lang='+window.vt_language_force;
                    } else {
                        url_vt = url_base+'/'+window.friendly_url+'?room='+current_id_panorama+'&yaw='+current_yaw+'&pitch='+current_pitch+'&hfov='+current_hfov;
                    }
                } else {
                    if(window.vt_language_force!=='') {
                        url_vt = url_base+'/index.php?code='+window.code+'&room='+current_id_panorama+'&yaw='+current_yaw+'&pitch='+current_pitch+'&hfov='+current_hfov+'&lang='+window.vt_language_force;
                    } else {
                        url_vt = url_base+'/index.php?code='+window.code+'&room='+current_id_panorama+'&yaw='+current_yaw+'&pitch='+current_pitch+'&hfov='+current_hfov;
                    }
                }
                break;
        }
        $('#share_link').val(url_vt);
        return url_vt;
    }

    window.close_share = function() {
        $('.share_popup').removeClass('show');
        $('.share_control').removeClass('active_control');
        $('.share_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['share']=false;
    }

    window.toggle_icons = function () {
        if($('.icons_control').hasClass('active_control')) {
            $('.custom-hotspot').addClass('hidden_icons');
            $('.custom-hotspot img').addClass('hidden_icons');
            $('.custom-hotspot-content').addClass('hidden_icons');
            $('.poi_embed').addClass('hidden_icons');
            $('.marker_embed').addClass('hidden_icons');
            $('.tooltip_text').addClass('hidden_icons');
            $('.tooltip_preview').addClass('hidden_icons');
            $('.tooltip_preview_square').addClass('hidden_icons');
            $('.tooltip_preview_rect').addClass('hidden_icons');
            $('.div_poi_wrapper').removeClass('pulse_icon_hover');
            $('.div_poi_wrapper').removeClass('pulse_image_hover');
            $('.div_marker_wrapper').removeClass('pulse_icon_hover');
            $('.div_marker_wrapper').removeClass('pulse_image_hover');
            $('.pnlm-pointer').removeClass('hotspot_hover');
            $('.icons_control').removeClass('active_control');
            $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['icons_content']=false;
            controls_status['icons_nav']=false;
        } else {
            $('.custom-hotspot').removeClass('hidden_icons');
            $('.custom-hotspot img').removeClass('hidden_icons');
            $('.custom-hotspot-content').removeClass('hidden_icons');
            $('.poi_embed').removeClass('hidden_icons');
            $('.marker_embed').removeClass('hidden_icons');
            $('.tooltip_text').removeClass('hidden_icons');
            $('.tooltip_preview').removeClass('hidden_icons');
            $('.tooltip_preview_square').removeClass('hidden_icons');
            $('.tooltip_preview_rect').removeClass('hidden_icons');
            $('.icons_control').addClass('active_control');
            $('.icons_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['icons_content']=true;
            controls_status['icons_nav']=true;
        }
    }

    window.toggle_icons_content = function () {
        if($('.icons_content_control').hasClass('active_control')) {
            $('.custom-hotspot-content').addClass('hidden_icons');
            $('.poi_embed').addClass('hidden_icons');
            $('.tooltip_poi').addClass('hidden_icons');
            $('.div_poi_wrapper').removeClass('pulse_icon_hover');
            $('.div_poi_wrapper').removeClass('pulse_image_hover');
            $('.pnlm-pointer').removeClass('hotspot_hover');
            $('.icons_content_control').removeClass('active_control');
            $('.icons_content_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['icons_content']=false;
        } else {
            $('.custom-hotspot-content').removeClass('hidden_icons');
            $('.poi_embed').removeClass('hidden_icons');
            $('.tooltip_poi').removeClass('hidden_icons');
            $('.icons_content_control').addClass('active_control');
            $('.icons_content_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['icons_content']=true;
        }
    }

    window.toggle_icons_nav = function () {
        if($('.icons_nav_control').hasClass('active_control')) {
            $('.custom-hotspot').addClass('hidden_icons');
            $('.custom-hotspot img').addClass('hidden_icons');
            $('.marker_embed').addClass('hidden_icons');
            $('.tooltip_marker').addClass('hidden_icons');
            $('.div_marker_wrapper').removeClass('pulse_icon_hover');
            $('.div_marker_wrapper').removeClass('pulse_image_hover');
            $('.pnlm-pointer').removeClass('hotspot_hover');
            $('.icons_nav_control').removeClass('active_control');
            $('.icons_nav_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['icons_nav']=false;
        } else {
            $('.custom-hotspot').removeClass('hidden_icons');
            $('.custom-hotspot img').removeClass('hidden_icons');
            $('.marker_embed').removeClass('hidden_icons');
            $('.tooltip_marker').removeClass('hidden_icons');
            $('.icons_nav_control').addClass('active_control');
            $('.icons_nav_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['icons_nav']=true;
        }
    }

    window.toggle_measures = function () {
        if($('.measures_control').hasClass('active_control')) {
            $('.leader-line').addClass('hidden_icons');
            $('.measures_control').removeClass('active_control');
            $('.measures_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['measures']=false;
        } else {
            $('.leader-line').removeClass('hidden_icons');
            $('.measures_control').addClass('active_control');
            $('.measures_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['measures']=true;
        }
    }

    function hide_icons() {
        $('.custom-hotspot').addClass('hidden_icons');
        $('.custom-hotspot img').addClass('hidden_icons');
        $('.custom-hotspot-content').addClass('hidden_icons');
        $('.leader-line').addClass('hidden_icons');
        $('.poi_embed').addClass('hidden_icons');
        $('.marker_embed').addClass('hidden_icons');
        $('.tooltip_text').addClass('hidden_icons');
        $('.tooltip_preview').addClass('hidden_icons');
        $('.tooltip_preview_square').addClass('hidden_icons');
        $('.tooltip_preview_rect').addClass('hidden_icons');
        $('.div_poi_wrapper').removeClass('pulse_icon_hover');
        $('.div_poi_wrapper').removeClass('pulse_image_hover');
        $('.div_marker_wrapper').removeClass('pulse_icon_hover');
        $('.div_marker_wrapper').removeClass('pulse_image_hover');
        $('.pnlm-pointer').removeClass('hotspot_hover');
        $('.icons_control').removeClass('active_control');
        $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['icons_content']=false;
        controls_status['icons_nav']=false;
    }

    function show_icons() {
        $('.custom-hotspot').removeClass('hidden_icons');
        $('.custom-hotspot img').removeClass('hidden_icons');
        $('.custom-hotspot-content').removeClass('hidden_icons');
        $('.leader-line').removeClass('hidden_icons');
        $('.poi_embed').removeClass('hidden_icons');
        $('.marker_embed').removeClass('hidden_icons');
        $('.tooltip_text').removeClass('hidden_icons');
        $('.tooltip_preview').removeClass('hidden_icons');
        $('.tooltip_preview_square').removeClass('hidden_icons');
        $('.tooltip_preview_rect').removeClass('hidden_icons');
        $('.icons_control').addClass('active_control');
        $('.icons_control .fa-circle').removeClass('not_active').addClass('active');
        controls_status['icons_content']=true;
        controls_status['icons_nav']=true;
    }

    window.toggle_autorotate = function () {
        var index_current = get_id_viewer(current_id_panorama);
        if(panoramas[index_current].autorotate_override==1) {
            var autorotate_speed_h = panoramas[index_current].autorotate_speed;
            var autorotate_inactivity_h = panoramas[index_current].autorotate_inactivity;
        } else {
            var autorotate_speed_h = autorotate_speed;
            var autorotate_inactivity_h = autorotate_inactivity;
        }
        if($('.autorotate_control').hasClass('active_control')) {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                try { pano_viewer.stopAutoRotate(); } catch (e) {}
            } else {
                try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
            }
            $('.nav_rotate').removeClass('active_rotate');
            $('.autorotate_control').removeClass('active_control');
            $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['auto_rotate']=false;
        } else {
            if(autorotate_speed_h!=0) {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    pano_viewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                    pano_viewer.startAutoRotate();
                } else {
                    video_viewer.pnlmViewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                    video_viewer.pnlmViewer.startAutoRotate();
                }
                $('.nav_rotate').addClass('active_rotate');
                $('.autorotate_control').addClass('active_control');
                $('.autorotate_control .fa-circle').removeClass('not_active').addClass('active');
                controls_status['auto_rotate']=true;
            }
        }
    }

    window.toggle_annotations = function () {
        if($('.annotations_control').hasClass('active_control')) {
            $('.annotation').css({'opacity':0,'pointer-events':'none'});
            $('.annotations_control').removeClass('active_control');
            $('.annotations_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['annotations']=false;
            if(live_session_connected) {
                try {
                    peer_conn.send({type:'close_annotations'});
                } catch (e) {}
            }
        } else {
            $('.annotation').css({'opacity':1,'pointer-events':'initial'});
            $('.annotations_control').addClass('active_control');
            $('.annotations_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['annotations']=true;
            if(live_session_connected) {
                try {
                    peer_conn.send({type:'open_annotations'});
                } catch (e) {}
            }
        }
        adjust_elements_positions();
    }

    window.open_annotations = function() {
        $('.annotation').css({'opacity':1,'pointer-events':'initial'});
        $('.annotations_control').addClass('active_control');
        $('.annotations_control .fa-circle').removeClass('not_active').addClass('active');
        controls_status['annotations']=true;
        adjust_elements_positions();
    }

    window.close_annotations = function() {
        $('.annotation').css({'opacity':0,'pointer-events':'none'});
        $('.annotations_control').removeClass('active_control');
        $('.annotations_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['annotations']=false;
        adjust_elements_positions();
    }

    function audio_isPlaying() {
        return !audio_player.paused && !audio_player.ended && 0 < audio_player.currentTime;
    }

    function fadeVolume(audioElement, targetVolume, duration) {
        if(audioElement===null) return;
        targetVolume = Math.max(0, Math.min(1, targetVolume));
        let currentVolume = audioElement.volume;
        let steps = Math.abs(targetVolume - currentVolume) / (duration / 50);
        let isFadingIn = targetVolume > currentVolume;
        let fadeInterval = setInterval(function() {
            if (isFadingIn) {
                currentVolume = Math.min(targetVolume, currentVolume + steps);
            } else {
                currentVolume = Math.max(targetVolume, currentVolume - steps);
            }
            audioElement.volume = currentVolume;
            if ((isFadingIn && currentVolume >= targetVolume) || (!isFadingIn && currentVolume <= targetVolume)) {
                audioElement.volume = targetVolume;
                clearInterval(fadeInterval);
            }
        }, 50);
    }

    function set_audio_volume(volume,volume_room,duration=500) {
        if(volume_room===-1) volume_room=volume;
        if(isIOS() && volume==0) {
            try {
                if(!audio_player.paused) audio_player.muted = true;
            } catch (e) {}
            try {
                if(!audio_player_room.paused) audio_player_room.muted = true;
            } catch (e) {}
            try {
                if(video_p!==null) {
                    if(!video_p.paused) video_p.muted = true;
                }
            } catch (e) {}
            try {
                var video_elem = document.getElementById('video_viewer_html5_api');
                if(video_elem!==null && video_elem!==undefined) {
                    if(!video_elem.paused) video_elem.muted = true;
                }
            } catch (e) {}
        } else if(isIOS() && volume>0 && controls_status['song']) {
            try {
                if(!audio_player.paused) audio_player.muted = false;
            } catch (e) {}
            try {
                if(!audio_player_room.paused) audio_player_room.muted = false;
            } catch (e) {}
            try {
                if(!video_p.paused) video_p.muted = false;
            } catch (e) {}
            try {
                var video_elem = document.getElementById('video_viewer_html5_api');
                if(video_elem!==null && video_elem!==undefined) {
                    if(!video_elem.paused) video_elem.muted = false;
                }
            } catch (e) {}
        } else {
            try {
                if(!audio_player.paused) fadeVolume(audio_player, volume, duration);
            } catch (e) {}
            if(volume_room!==-1) {
                try {
                    if(!audio_player_room.paused) fadeVolume(audio_player_room, volume_room, duration);
                } catch (e) {}
            }
            try {
                if(!video_p.paused) fadeVolume(video_p, volume, duration);
            } catch (e) {}
            try {
                var video_elem = document.getElementById('video_viewer_html5_api');
                if(video_elem!==null && video_elem!==undefined) {
                    if(!video_elem.paused) fadeVolume(video_elem, volume, duration);
                }
            } catch (e) {}
        }
    }

    function unmute_audio(song,video,duration=500) {
        if(is_iOS() || current_panorama_type=='hls') {
            if(song) {
                audio_player.muted = false;
                fadeVolume(audio_player, (avatar_video_playing) ? song_bg_volume_sel/3 : song_bg_volume_sel, duration);
                audio_player_room.muted = false;
                var index_panorama = get_id_viewer(current_id_panorama);
                fadeVolume(audio_player_room, (avatar_video_playing) ? panoramas[index_panorama].song_volume/3 : panoramas[index_panorama].song_volume, duration);
            }
            if(video) {
                try {
                    fadeVolume(video_p, (avatar_video_playing) ? 0.3 : 1, duration);
                } catch (e) {}
                try {
                    video_p.muted = false;
                } catch (e) {}
                try {
                    var video_elem = document.getElementById('video_viewer_html5_api');
                    if(video_elem!==null && video_elem!==undefined) {
                        video_elem.muted = false;
                    }
                } catch (e) {}
            }
        } else {
            if(song) {
                fadeVolume(audio_player, (avatar_video_playing) ? song_bg_volume_sel/3 : song_bg_volume_sel, duration);
                var index_panorama = get_id_viewer(current_id_panorama);
                fadeVolume(audio_player_room, (avatar_video_playing) ? panoramas[index_panorama].song_volume/3 : panoramas[index_panorama].song_volume, duration);
            }
            if(video) {
                try {
                    var video_elem = document.getElementById('video_viewer_html5_api');
                    if(video_elem!==null && video_elem!==undefined) {
                        fadeVolume(video_elem, (avatar_video_playing) ? 0.3 : 1, duration);
                        video_elem.muted = false;
                    }
                } catch (e) {}
                try {
                    video_viewer.muted(false);
                } catch (e) {}
            }
        }
    }

    function mute_audio(song,video,duration=500) {
        if(is_iOS() || current_panorama_type=='hls') {
            if(song) {
                fadeVolume(audio_player, 0, duration);
                fadeVolume(audio_player_room, 0, duration);
                setTimeout(function() {
                    audio_player.muted = true;
                    audio_player_room.muted = true;
                },duration)
            }
            if(video) {
                try {
                    if(video_p!==null) {
                        fadeVolume(video_p, 0, duration);
                        setTimeout(function () {
                            video_p.muted = true;
                        }, duration)
                    }
                } catch (e) {}
                try {
                    var video_elem = document.getElementById('video_viewer_html5_api');
                    if(video_elem!==null && video_elem!==undefined) {
                        video_elem.muted = true;
                    }
                } catch (e) {}
            }
        } else {
            if(song) {
                fadeVolume(audio_player, 0, duration);
                fadeVolume(audio_player_room, 0, duration);
            }
            if(video) {
                try {
                    var video_elem = document.getElementById('video_viewer_html5_api');
                    if(video_elem!==null && video_elem!==undefined) {
                        fadeVolume(video_elem, 0, duration);
                        setTimeout(function() {
                            video_elem.muted = true;
                        },duration)
                    }
                } catch (e) {}
                try {
                    video_viewer.muted(true);
                } catch (e) {}
            }
        }
    }

    var force_audio_muted = false;
    window.force_mute_audio = function() {
        if(controls_status['song']) {
            song_is_playng = true;
        } else {
            song_is_playng = false;
        }
        controls_status['song']=false;
        $('.song_control').removeClass('active_control');
        $('.song_alt_control').removeClass('active_control');
        $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
        $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
        mute_audio(true,true);
        force_audio_muted = true;
    }

    $(document).on('afterShow.fb', function( e, instance, slide ) {
        try {
            if((slide.type=='video' || slide.contentType=='video') && controls_status['song']) {
                mute_audio(true,true);
                $('.song_control').removeClass('active_control');
                $('.song_alt_control').removeClass('active_control');
                $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
                $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
                controls_status['song']=false;
                force_audio_muted = true;
                song_is_playng = true;
            }
        } catch (e) {}
    });

    $(document).on('afterClose.fb', function( e, instance, slide ) {
        if(force_audio_muted) {
            if(song_is_playng) {
                unmute_audio(true,true);
                $('.song_control').addClass('active_control');
                $('.song_alt_control').addClass('active_control');
                $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                controls_status['song']=true;
                force_audio_muted = false;
            }
        }
        poi_open = false;
        if(!live_session_connected) {
            if(video_opened) {
                if(controls_status['song']) {
                    if(current_panorama_type=='video') {
                        unmute_audio(false,true);
                    } else {
                        unmute_audio(true,false);
                    }
                }
                video_opened = false;
            }
        } else {
            try {
                peer_conn.send({type:'close_content'});
            } catch (e) {}
        }
        clearTimeout(interval_auto_close_poi);
        restart_autorotate();
    });

    window.toggle_song = function () {
        if($('.song_control').hasClass('active_control')) {
            mute_audio(true,true);
            $('.song_control').removeClass('active_control');
            $('.song_alt_control').removeClass('active_control');
            $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
            $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
            controls_status['song']=false;
        } else {
            var index = get_id_viewer(current_id_panorama);
            if(panoramas[index].audio_track_enable) {
                if(panoramas[index].song!='') {
                    unmute_audio(true,true);
                } else {
                    unmute_audio(false,true);
                }
            } else {
                unmute_audio(true,false);
            }
            $('.song_control').addClass('active_control');
            $('.song_alt_control').addClass('active_control');
            $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
            $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['song']=true;
            if(!audio_isPlaying()) {
                try {
                    audio_player.play();
                } catch (e) {}
            }
        }
    }

    window.toggle_comments = function() {
        if($('.comments_vt').hasClass('disabled_cookie')) {
            var alert_cookie = $.alert({
                theme: 'material',
                useBootstrap: false,
                boxWidth: '80%',
                type: 'dark',
                icon: 'fa-solid fa-cookie',
                title: window.viewer_labels.disqus_comments,
                content: window.viewer_labels.cookie_denied_msg,
                buttons: {
                    cancel: {
                        text: window.viewer_labels.cancel,
                        action: function () {
                        }
                    },
                    accept: {
                        btnClass: 'btn-black',
                        text: window.viewer_labels.open_cookie_pref,
                        action: function () {
                            alert_cookie.close();
                            CookieConsent.showPreferences();
                        }
                    }
                }
            });
        } else {
            if($('#comments_control').hasClass('active')) {
                $('#comments_div').hide();
                $('#comments_control').removeClass('active');
            } else {
                $('#comments_div').show();
                $('#comments_control').addClass('active');
            }
        }
    }

    window.view_facebook_messenger = function () {
        window.open('https://m.me/'+window.facebook_page_id);
    }

    window.view_info_box = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'open_info'});
            } catch (e) {}
        }
        switch(info_box_type) {
            case 'popup':
                poi_open = true;
                var info_box_html = '<div class="bootstrap-iso info_box_content">'+info_box+'</div>';
                $.fancybox.open({
                    src  : info_box_html,
                    type : 'html',
                    touch: false
                });
                break;
            case 'panel':
                var info_box_html = '<div id="div_close_info_panel"><i onclick="view_info_box();" id="close_info_panel_icon" class="fas fa-times"></i></div><div class="bootstrap-iso info_panel_content">'+info_box+'</div>';
                toggle_info_panel(info_box_html);
                break;
        }
    }

    window.view_custom_box = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_custom_box'});
            } catch (e) {}
        }
        poi_open = true;
        if(custom_box!='' && custom_box!==undefined && custom_box!=null) {
            if(custom_box.startsWith('function:')) {
                eval(custom_box.replace('function:',''));
            } else if(custom_box.startsWith('http')) {
                window.open(custom_box,'_blank');
            } else {
                if (custom_box.includes('iframe')) {
                    var style = "padding:0 !important;width:90%;height:90%;";
                } else {
                    var style = '';
                }
                var custom_box_html = '<div style="' + style + '" class="custom_box_content">' + custom_box + '</div>';
                $.fancybox.open({
                    src: custom_box_html,
                    type: 'html',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false
                });
            }
        }
    }

    window.view_custom2_box = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_custom2_box'});
            } catch (e) {}
        }
        poi_open = true;
        if(custom2_box!='' && custom2_box!==undefined && custom2_box!=null) {
            if(custom2_box.startsWith('function:')) {
                eval(custom2_box.replace('function:',''));
            } else if(custom2_box.startsWith('http')) {
                window.open(custom2_box,'_blank');
            } else {
                if (custom2_box.includes('iframe')) {
                    var style = "padding:0 !important;width:90%;height:90%;";
                } else {
                    var style = '';
                }
                var custom2_box_html = '<div style="' + style + '" class="custom_box_content">' + custom2_box + '</div>';
                $.fancybox.open({
                    src: custom2_box_html,
                    type: 'html',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false
                });
            }
        }
    }

    window.view_custom3_box = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_custom3_box'});
            } catch (e) {}
        }
        poi_open = true;
        if(custom3_box!='' && custom3_box!==undefined && custom3_box!=null) {
            if(custom3_box.startsWith('function:')) {
                eval(custom3_box.replace('function:',''));
            } else if(custom3_box.startsWith('http')) {
                window.open(custom3_box,'_blank');
            } else {
                if (custom3_box.includes('iframe')) {
                    var style = "padding:0 !important;width:90%;height:90%;";
                } else {
                    var style = '';
                }
                var custom3_box_html = '<div style="' + style + '" class="custom_box_content">' + custom3_box + '</div>';
                $.fancybox.open({
                    src: custom3_box_html,
                    type: 'html',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false
                });
            }
        }
    }

    window.view_custom4_box = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_custom4_box'});
            } catch (e) {}
        }
        poi_open = true;
        if(custom4_box!='' && custom4_box!==undefined && custom4_box!=null) {
            if(custom4_box.startsWith('function:')) {
                eval(custom4_box.replace('function:',''));
            } else if(custom4_box.startsWith('http')) {
                window.open(custom4_box,'_blank');
            } else {
                if (custom4_box.includes('iframe')) {
                    var style = "padding:0 !important;width:90%;height:90%;";
                } else {
                    var style = '';
                }
                var custom4_box_html = '<div style="' + style + '" class="custom_box_content">' + custom4_box + '</div>';
                $.fancybox.open({
                    src: custom4_box_html,
                    type: 'html',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false
                });
            }
        }
    }

    window.view_custom5_box = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_custom5_box'});
            } catch (e) {}
        }
        poi_open = true;
        if(custom5_box!='' && custom5_box!==undefined && custom5_box!=null) {
            if(custom5_box.startsWith('function:')) {
                eval(custom5_box.replace('function:',''));
            } else if(custom5_box.startsWith('http')) {
                window.open(custom5_box,'_blank');
            } else {
                if (custom5_box.includes('iframe')) {
                    var style = "padding:0 !important;width:90%;height:90%;";
                } else {
                    var style = '';
                }
                var custom5_box_html = '<div style="' + style + '" class="custom_box_content">' + custom5_box + '</div>';
                $.fancybox.open({
                    src: custom5_box_html,
                    type: 'html',
                    touch: false,
                    smallBtn: false,
                    clickOutside: false
                });
            }
        }
    }

    window.view_location_box = function () {
        if(location_box!='' && location_box!==undefined && location_box!=null) {
            if(live_session_connected) {
                try {
                    peer_conn.send({type:'view_location_box'});
                } catch (e) {}
            }
            var gm_map = location_box.split('|')[0];
            var gm_street = location_box.split('|')[1];
            if (gm_map.startsWith('http')) {
                gm_map = '<iframe src="'+gm_map+'" frameborder="0" width="100%" height="100%"></iframe>';
            }
            if (gm_street.startsWith('http')) {
                gm_street = '<iframe src="'+gm_street+'" frameborder="0" width="100%" height="100%"></iframe>';
            }
            var content = '<div class="poi_google_maps_content">'+gm_map+' '+gm_street+'</div>';
            $.fancybox.open({
                src  : content,
                type : 'html',
                touch: false,
                smallBtn: false,
                afterShow : function() {
                    if((gm_map=='') || (gm_street=='')) {
                        $('.poi_google_maps_content iframe:nth-child(1)').addClass('poi_google_maps_full_width');
                    }
                }
            });
        }
    }

    function parse_form_content(content,id_room,id_poi) {
        var html_content = '';
        var title = content[0].title;
        var button = content[0].button;
        if(button=='') button = window.viewer_labels.submit;
        var description = content[0].description;
        var send_email = content[0].send_email;
        if(send_email) {
            var email = content[0].email;
        } else {
            var email = '';
        }
        var background = content[0].background;
        if(background==null) background = 'rgba(255,255,255,1.0)';
        var color = content[0].color;
        if(color==null) color = '#000000';
        var background_button = content[0].background_button;
        if(background_button==null) background_button = '#000000';
        var color_button = content[0].color_button;
        if(color_button==null) color_button = '#ffffff';
        var privacy_policy = content[0].privacy_policy;
        if(privacy_policy==null) privacy_policy=false;
        var webhook_url = content[0].webhook_url;
        if(webhook_url==null) webhook_url='';
        html_content += '<form method="post" enctype="multipart/form-data" action="#" id="form_poi_'+id_poi+'" class="form_poi" style="text-align: center;">';
        html_content += '<style>' +
            '#form_poi_'+id_poi+' .select:after {' +
            'border-top: 6px solid ' + color + ';' +
            '}' +
            '#form_poi_'+id_poi+' .pure-material-checkbox > span::before {' +
            'border-color:' + color + ';' +
            '}' +
            '#form_poi_'+id_poi+' .input_material .bar:before {' +
            'background:' + color + ';' +
            '}' +
            '#form_poi_'+id_poi+' .select-bar:before, #form_poi_'+id_poi+' .select-bar:after {' +
            'background:' + color + ';' +
            '}' +
            '</style>';
        if(title!='') {
            html_content += '<h2 style="margin-bottom:5px;margin-top:5px;">'+title.toUpperCase()+'</h2>';
        }
        if(description!='') {
            html_content += '<p>'+description+'</p><br>';
        }
        for(var i=1;i<=10;i++) {
            if(!('type' in content[i])) content[i]['type']='text';
            if(content[i]['enabled']) {
                if(content[i]['required']) {
                    var required_tag = 'required';
                    var required_label = '*';
                } else {
                    var required_tag = '';
                    var required_label = '';
                }
                switch(content[i]['type']) {
                    case 'select':
                        var labels = content[i]['label'].split(';');
                        html_content += '<div style="color: '+color+';" class="select">\n' +
                            ' <select style="color: '+color+';border-bottom: 1px solid '+color+';" id="form_field_'+i+'" name="form_field_'+i+'" data-chosen="" onchange="this.dataset.chosen = this.value;" class="select-text" '+required_tag+'>\n' +
                            '   <option value="" selected></option>\n';
                        for(var k=1;k<labels.length;k++) {
                            html_content += '<option value="'+labels[k]+'">'+labels[k]+'</option>\n';
                        }
                        html_content += '</select>\n' +
                            ' <span style="color: '+color+';" class="select-highlight"></span>\n' +
                            ' <span style="color: '+color+';" class="select-bar"></span>\n' +
                            ' <label style="color: '+color+';" class="select-label">'+labels[0]+' '+required_label+'</label>\n' +
                            '</div>';
                        var label = labels[0];
                        break;
                    case 'checkbox':
                        html_content += '<div><label style="color: '+color+';" class="pure-material-checkbox">\n' +
                            '<input style="color: '+color+';" type="checkbox" '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'">\n' +
                            '<span style="color: '+color+';">'+content[i]['label']+' '+required_label+'</span>\n' +
                            '</label></div>';
                        var label = content[i]['label'];
                        break;
                    case 'file':
                        var labels = content[i]['label'].split(';');
                        var file_upload_limit = labels[2];
                        html_content += '<div style="color: '+color+';" class="input_material">\n' +
                            '      <input onchange="form_upload_file_check('+i+','+file_upload_limit+');" accept="'+labels[1]+'" style="color: '+color+';border-bottom: 1px solid '+color+';" placeholder=" " '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'" type="file" />\n' +
                            '      <label style="color: '+color+';">'+labels[0]+' '+required_label+'</label>\n' +
                            '    </div>';
                        var label = labels[0];
                        break;
                    case 'textarea':
                        var labels = content[i]['label'].split(';');
                        if(labels[1]!==null) {
                            var rows = labels[1];
                        } else {
                            var rows = 2;
                        }
                        html_content += '<div style="color: '+color+';" class="input_material">\n' +
                            '      <textarea rows="'+rows+'" style="color: '+color+';border-bottom: 1px solid '+color+';" placeholder=" " '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'"></textarea><span class="highlight"></span><span class="bar"></span>\n' +
                            '      <label style="color: '+color+';">'+labels[0]+' '+required_label+'</label>\n' +
                            '    </div>';
                        var label = labels[0];
                        break;
                    default:
                        html_content += '<div style="color: '+color+';" class="input_material">\n' +
                            '      <input style="color: '+color+';border-bottom: 1px solid '+color+';" placeholder=" " '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'" type="'+content[i]['type']+'" /><span style="color: '+color+';" class="highlight"></span><span style="color: '+color+';" class="bar"></span>\n' +
                            '      <label style="color: '+color+';">'+content[i]['label']+' '+required_label+'</label>\n' +
                            '    </div>';
                        var label = content[i]['label'];
                        break;
                }
                html_content += '<input type="hidden" name="form_label_'+i+'" value="'+label+'" />';
                html_content += '<br>';
            }
        }
        html_content += '<input type="hidden" name="id_room" value="'+id_room+'" />';
        html_content += '<input type="hidden" name="title" value="'+title+'" />';
        html_content += '<input type="hidden" name="email" value="'+email+'" />';
        html_content += '<input type="hidden" name="webhook_url" value="'+webhook_url+'" />';
        if(privacy_policy) {
            html_content += '<div style="margin-bottom:5px;"><label id="form_input_privacy" style="color: '+color+';" class="pure-material-checkbox">\n' +
                '<input type="checkbox" required>\n' +
                '<span style="color: '+color+';">'+window.viewer_labels.agree_privacy_policy+'</span>\n' +
                '</label></div>';
        }
        html_content += '<input type="hidden" name="id_virtualtour" value="'+window.id_virtualtour+'" />';
        html_content += '<button class="button_material" type="submit" style="margin-top: 10px;background-color: '+background_button+';color: '+color_button+';"">'+button+'</button>';
        html_content += '</form>';
        return html_content;
    }

    window.view_form = function() {
        poi_open = true;
        var html_content = '';
        var content = form_content;
        try {
            var title = content[0].title;
            var button = content[0].button;
            var response = content[0].response;
            var send_email = content[0].send_email;
            var background = content[0].background;
            if(background==null) background = 'rgba(255,255,255,1.0)';
            var color = content[0].color;
            if(color==null) color = '#000000';
            var background_button = content[0].background_button;
            if(background_button==null) background_button = '#000000';
            var color_button = content[0].color_button;
            if(color_button==null) color_button = '#ffffff';
            if(send_email) {
                var email = content[0].email;
            } else {
                var email = '';
            }
            if(button=='') button = window.viewer_labels.submit;
            var description = content[0].description;
            var privacy_policy = content[0].privacy_policy;
            if(privacy_policy==null) privacy_policy=false;
            var webhook_url = content[0].webhook_url;
            if(webhook_url==null) webhook_url='';
            html_content += '<div style="background-color: '+background+';color: '+color+';"><form method="post" enctype="multipart/form-data" action="#" class="form_main" style="text-align: center;">'
            html_content += '<style>' +
                '.form_main .select:after {' +
                'border-top: 6px solid ' + color + ';' +
                '}' +
                '.form_main .pure-material-checkbox > span::before {' +
                'border-color:' + color + ';' +
                '}' +
                '.form_main .input_material .bar:before {' +
                'background:' + color + ';' +
                '}' +
                '.form_main .select-bar:before, .form_main .select-bar:after {' +
                'background:' + color + ';' +
                '}' +
                '</style>';
            if(title!='') {
                html_content += '<h2 style="margin-bottom:5px;margin-top:5px;">'+title.toUpperCase()+'</h2>';
            }
            if(description!='') {
                html_content += '<p>'+description+'</p><br>';
            }
            for(var i=1;i<=10;i++) {
                if(!('type' in content[i])) content[i]['type']='text';
                if(content[i]['enabled']) {
                    if(content[i]['required']) {
                        var required_tag = 'required';
                        var required_label = '*';
                    } else {
                        var required_tag = '';
                        var required_label = '';
                    }
                    switch(content[i]['type']) {
                        case 'select':
                            var labels = content[i]['label'].split(';');
                            html_content += '<div class="select">\n' +
                                ' <select style="color: '+color+';border-bottom: 1px solid '+color+';" id="form_field_'+i+'" name="form_field_'+i+'" data-chosen="" onchange="this.dataset.chosen = this.value;" class="select-text" '+required_tag+'>\n' +
                                '   <option value="" selected></option>\n';
                            for(var k=1;k<labels.length;k++) {
                                html_content += '<option value="'+labels[k]+'">'+labels[k]+'</option>\n';
                            }
                            html_content += '</select>\n' +
                                ' <span style="color: '+color+';" class="select-highlight"></span>\n' +
                                ' <span style="color: '+color+';" class="select-bar"></span>\n' +
                                ' <label style="color: '+color+';" class="select-label">'+labels[0]+' '+required_label+'</label>\n' +
                                '</div>';
                            var label = labels[0];
                            break;
                        case 'checkbox':
                            html_content += '<div><label style="color: '+color+';" class="pure-material-checkbox">\n' +
                                '<input type="checkbox" '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'">\n' +
                                '<span style="color: '+color+';">'+content[i]['label']+' '+required_label+'</span>\n' +
                                '</label></div>';
                            var label = content[i]['label'];
                            break;
                        case 'file':
                            var labels = content[i]['label'].split(';');
                            var file_upload_limit = labels[2];
                            html_content += '<div style="color: '+color+';" class="input_material">\n' +
                                '      <input onchange="form_upload_file_check('+i+','+file_upload_limit+');" accept="'+labels[1]+'" style="color: '+color+';border-bottom: 1px solid '+color+';" placeholder=" " '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'" type="file" />\n' +
                                '      <label style="color: '+color+';">'+labels[0]+' '+required_label+'</label>\n' +
                                '    </div>';
                            var label = labels[0];
                            break;
                        case 'textarea':
                            var labels = content[i]['label'].split(';');
                            if(labels[1]!==null) {
                                var rows = labels[1];
                            } else {
                                var rows = 2;
                            }
                            html_content += '<div style="color: '+color+';" class="input_material">\n' +
                                '      <textarea rows="'+rows+'" style="color: '+color+';border-bottom: 1px solid '+color+';" placeholder=" " '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'"></textarea><span class="highlight"></span><span class="bar"></span>\n' +
                                '      <label style="color: '+color+';">'+labels[0]+' '+required_label+'</label>\n' +
                                '    </div>';
                            var label = labels[0];
                            break;
                        default:
                            html_content += '<div style="color: '+color+';" class="input_material">\n' +
                                '      <input style="color: '+color+';border-bottom: 1px solid '+color+';" placeholder=" " '+required_tag+' id="form_field_'+i+'" name="form_field_'+i+'" type="'+content[i]['type']+'" /><span class="highlight"></span><span class="bar"></span>\n' +
                                '      <label style="color: '+color+';">'+content[i]['label']+' '+required_label+'</label>\n' +
                                '    </div>';
                            var label = content[i]['label'];
                            break;
                    }
                    html_content += '<input type="hidden" name="form_label_'+i+'" value="'+label+'" />';
                    html_content += '<br>';
                }
            }
            html_content += '<input type="hidden" name="id_room" value="0" />';
            html_content += '<input type="hidden" name="title" value="'+title+'" />';
            html_content += '<input type="hidden" name="email" value="'+email+'" />';
            html_content += '<input type="hidden" name="webhook_url" value="'+webhook_url+'" />';
            if(privacy_policy) {
                html_content += '<div style="margin-bottom:5px;"><label id="form_input_privacy" style="color: '+color+';" class="pure-material-checkbox">\n' +
                    '<input type="checkbox" required>\n' +
                    '<span style="color: '+color+';">'+window.viewer_labels.agree_privacy_policy+'</span>\n' +
                    '</label></div>';
            }
            html_content += '<button class="button_material" type="submit" style="margin-top: 10px;background-color: '+background_button+';color: '+color_button+';">'+button+'</button>';
            html_content += '<input type="hidden" name="id_virtualtour" value="'+window.id_virtualtour+'" />';
            html_content += '</form></div>';
            form_lightbox = $.fancybox.open({
                src  : html_content,
                type : 'html',
                touch: false
            });
            $(".form_main").submit(function(e){
                var form_data = new FormData(this);
                confirm_main_form(form_data,response,'main');
                e.preventDefault();
            });
        } catch (e) {
            console.error(e);
        }
    }

    window.form_upload_file_check = function(id,max_file_size) {
        if(max_file_size!='' && max_file_size!=0) {
            var max_file_size_b = max_file_size * 1024;
            const fi = document.getElementById('form_field_'+id);
            if (fi.files.length > 0) {
                for (var i = 0; i <= fi.files.length - 1; i++) {
                    const fsize = fi.files.item(i).size;
                    const file = Math.round((fsize / 1024));
                    if (file >= max_file_size_b) {
                        fi.value = ''
                        if(!/safari/i.test(navigator.userAgent)){
                            fi.type = ''
                            fi.type = 'file'
                        }
                        alert(window.viewer_labels.file_too_big+' '+max_file_size+" MB");
                    }
                }
            }
        }
    }

    window.open_video = function (id) {
        video_opened = true;
        mute_audio(true,true);
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_video',id:id});
            } catch (e) {}
        }
    }

    function play_sound_hs(sound) {
        for (let key in array_sound_hs) {
            if (array_sound_hs.hasOwnProperty(key) && array_sound_hs[key].playing()) {
                array_sound_hs[key].stop();
            }
        }
        if(array_sound_hs.hasOwnProperty(sound)) {
            try {
                array_sound_hs[sound].play();
            } catch (e) {}
        }
    }

    function view_grouped(hotSpotDiv, args) {
        var current_index_panorama = get_id_viewer(current_id_panorama);
        var all_hs = panoramas[current_index_panorama].hotSpots;
        if(args.sound!='') {
            play_sound_hs(args.sound);
        }
        var grouped_open = false;
        $('.hotspot_'+args.id).addClass('grouped_disabled');
        if($('.hotspot_'+args.id).hasClass('grouped_open')) {
            $('.hotspot_'+args.id).removeClass('grouped_open');
        } else {
            if(leave_poi_open==0) close_all_pois();
            $('.hotspot_'+args.id).addClass('grouped_open');
            grouped_open = true;
        }
        var id_grouped_pois = args.content;
        var params = args.params;
        if(params=='') {
            var grouped_delay = 0;
            var grouped_hide_when_open = 0;
        } else {
            params = params.split(",");
            grouped_delay = params[1];
            if(params[2]==undefined) {
                grouped_hide_when_open = 0;
            } else {
                grouped_hide_when_open = params[2];
            }
        }
        if(grouped_hide_when_open==1) {
            $('.hotspot_'+args.id).fadeOut(function() {
                $(this).addClass('hidden');
            });
        }
        var first_delay = true;
        if(id_grouped_pois!='') {
            id_grouped_pois = id_grouped_pois.split(",");
            var delay = grouped_delay;
            if(!grouped_open) {
                delay = 0;
            }
            function toggleHotspotVisibilityWithDelay(all_hs,index) {
                setTimeout(function() {
                    first_delay = false;
                    var id_grouped_poi = id_grouped_pois[index];
                    if(grouped_open) {
                        $('.hotspot_'+id_grouped_poi).removeClass('hidden_grouped');
                        $('.hotspot_alt'+id_grouped_poi).removeClass('hidden_grouped');
                        if($('video#video_embed_'+id_grouped_poi).length) {
                            if($('video#video_embed_'+id_grouped_poi).attr('data-autoplay')==1) {
                                $('video#video_embed_'+id_grouped_poi)[0].play();
                            }
                        }
                        if($('video#video_embed_'+id_grouped_poi+'_html5_api').length) {
                            if($('video#video_embed_'+id_grouped_poi+'_html5_api').attr('data-autoplay')==1) {
                                $('video#video_embed_'+id_grouped_poi+'_html5_api')[0].play();
                            }
                        }
                    } else {
                        $('.hotspot_'+id_grouped_poi).addClass('hidden_grouped');
                        $('.hotspot_alt'+id_grouped_poi).addClass('hidden_grouped');
                        if($('video#video_embed_'+id_grouped_poi).length) {
                            $('video#video_embed_'+id_grouped_poi)[0].pause();
                        }
                        if($('video#video_embed_'+id_grouped_poi+'_html5_api').length) {
                            $('video#video_embed_'+id_grouped_poi+'_html5_api')[0].pause();
                        }
                        recursiveCloseGrouped(all_hs,id_grouped_poi);
                    }
                    if (index < id_grouped_pois.length - 1) {
                        toggleHotspotVisibilityWithDelay(all_hs,index + 1);
                    } else {
                        $('.hotspot_'+args.id).removeClass('grouped_disabled');
                    }
                }, (first_delay) ? 0 : delay);
            }
            toggleHotspotVisibilityWithDelay(all_hs,0);
        }
    }

    function recursiveCloseGrouped(all_hs,id_grouped_poi) {
        $.each(all_hs,function(index_hs,hs) {
            if(hs.id==id_grouped_poi && hs.type=='grouped') {
                var id_grouped_pois = hs.createTooltipArgs.content;
                if(id_grouped_pois!='') {
                    id_grouped_pois = id_grouped_pois.split(",");
                    $.each(id_grouped_pois,function(index_igs,igs) {
                        $('.hotspot_'+igs).addClass('hidden_grouped');
                        $('.hotspot_alt'+igs).addClass('hidden_grouped');
                        if($('video#video_embed_'+igs).length) {
                            $('video#video_embed_'+igs)[0].pause();
                        }
                        if($('video#video_embed_'+igs+'_html5_api').length) {
                            $('video#video_embed_'+igs+'_html5_api')[0].pause();
                        }
                        recursiveCloseGrouped(all_hs,igs)
                    });
                }
            }
        });
    }

    function check_click_outbound_hs(id,yaw,pitch) {
        var outbound_element = document.querySelector('.hs_'+id);
        if (outbound_element && outbound_element.classList.contains('outbound_hs')) {
            var outbound_element_yaw = parseFloat(yaw);
            var outbound_element_pitch = parseFloat(pitch);
            window.viewer_mov_pos_change = false;
            window.viewer_mov_follow_mouse = false;
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.lookAt(outbound_element_pitch,outbound_element_yaw,parseInt(hfov),600,function() {
                    window.viewer_mov_pos_change = true;
                    current_viewer_pitch = outbound_element_pitch;
                    current_viewer_yaw = outbound_element_yaw;
                    if(mouse_follow_feedback!=0) {
                        window.viewer_mov_follow_mouse = true;
                    }
                });
            } else {
                video_viewer.pnlmViewer.lookAt(outbound_element_pitch,outbound_element_yaw,parseInt(hfov),600,function() {
                    window.viewer_mov_pos_change = true;
                    current_viewer_pitch = outbound_element_pitch;
                    current_viewer_yaw = outbound_element_yaw;
                    if(mouse_follow_feedback!=0) {
                        window.viewer_mov_follow_mouse = true;
                    }
                });
            }
            return true;
        } else {
            return false;
        }
    }

    function view_content(hotSpotDiv, args) {
        if(hotSpotDiv!='') {
            if(check_click_outbound_hs("p"+args.id,args.yaw,args.pitch)) return;
        }
        if(leave_poi_open==0) close_all_pois();
        if(args.sound!='') {
            play_sound_hs(args.sound);
        }
        if(args.title==null) args.title = '';
        if(args.description==null) args.description = '';
        if(args.type=='html' || args.type=='html_sc') {
            if(((args.content=='') || (args.content=='<p><br></p>')) && ((args.title=='') && (args.description==''))) return;
        } else {
            if((args.content=='') || (args.content=='<p><br></p>')) return;
        }
        poi_open = true;
        if(args.view_type==0) {
            set_poi_statistics('',args.id);
        }
        if(window.learning_mode>0) {
            unlock_poi_learning(args.id,args.id_room);
            calculate_learning_score(0);
            calculate_learning_score(args.id_room);
            save_learning_log(0);
        }
        if(live_session_connected) {
            try {
                peer_conn.send({type:'view_content',args:args});
            } catch (e) {}
        }
        if((args.title!='') && (args.description!='')) {
            var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
        } else if((args.title!='') && (args.description=='')) {
            var caption = '<b>'+args.title+'</b>';
        } else if((args.title=='') && (args.description!='')) {
            var caption = '<i>'+args.description+'</i>';
        } else {
            var caption = '';
        }
        var view_type = parseInt(args.view_type);
        switch(args.type) {
            case 'image':
                switch(view_type) {
                    case 0:
                        $.fancybox.open({
                            src  : ((window.s3_enabled) ? window.s3_url : '')+args.content,
                            type : 'image',
                            caption : caption,
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'gallery':
                switch(view_type) {
                    case 0:
                        try {
                            $('#gallery_container').nanogallery2('destroy');
                        } catch (e) {}
                        var gallery_transition = 'swipe';
                        var gallery_thumbs = 'bottomOverMedia';
                        var gallery_autoplay = false;
                        var gallery_allow_download = false;
                        var gallery_slide_duration = 4;
                        if(args.params!='') {
                            try {
                                var array_params = JSON.parse(args.params);
                                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) {}
                        }
                        poi_gallery = $("#gallery_container").nanogallery2({
                            imageTransition: gallery_transition,
                            slideshowAutoStart: (parseInt(gallery_autoplay)==1) ? true : false,
                            slideshowDelay: parseFloat(gallery_slide_duration)*1000,
                            viewerGallery: gallery_thumbs,
                            thumbnailHeight:  150,
                            thumbnailWidth:   150,
                            items: args.content,
                            allowHTMLinData: true,
                            viewerHideToolsDelay: 30000,
                            viewerToolbar:    {
                                display:    true,
                                autoMinimize: false,
                                standard:   (parseInt(gallery_allow_download)==1) ? 'label, downloadButton' : 'label',
                            },
                            viewerTools:    {
                                topLeft:    'pageCounter, playPauseButton',
                                topRight:   'zoomButton, closeButton'
                            }
                        });
                        poi_gallery.nanogallery2('displayItem', '-1/1');
                        $('.nGY2Viewer .closeButton').on('click',function () {
                            if(live_session_connected) {
                                try {
                                    peer_conn.send({type:'close_gallery'});
                                } catch (e) {}
                            }
                            restart_autorotate();
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'link':
            case 'video':
            case 'pdf':
                switch(view_type) {
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'pointclouds':
                switch(view_type) {
                    case 0:
                        if (args.content.startsWith('http')) {
                            var url_file = args.content;
                        } else {
                            if(export_mode==1) {
                                var url_file = args.content;
                            } else {
                                var url_file = ((window.s3_enabled) ? window.s3_url : '')+args.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="vendor/potree/viewer/index.html?id_poi='+args.id+'&file='+url_file+'"></iframe>';
                        var html = '<div style="overflow:hidden;padding:0;width:calc(100% - 0px);height:calc(100% - 0px);background-color: '+args.box_background+';color: '+args.box_color+';">'+iframe+'</div>';
                        $.fancybox.open({
                            src  : html,
                            type : 'html',
                            touch: false,
                            smallBtn: false,
                            clickOutside: false,
                            caption : caption,
                            afterShow: function(instance, current) {
                                $('.fancybox-toolbar').addClass('always-visible');
                            },
                            beforeClose: function(instance, current) {
                                $('.fancybox-toolbar').removeClass('always-visible');
                            }
                        });
                        break;
                }
                break;
            case 'html':
            case 'html_sc':
                switch(view_type) {
                    case 0:
                        var html = '<div style="background-color: '+args.box_background+';color: '+args.box_color+';">'+args.content+'</div>';
                        $.fancybox.open({
                            src  : html,
                            type : 'html',
                            caption : caption,
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'object360':
                switch(view_type) {
                    case 0:
                        var html = '<div class="poi_object360_content"><div' +
                            '   class="cloudimage-360"' +
                            '   data-folder="'+((window.s3_enabled) ? window.s3_url : '')+'objects360/"' +
                            '   data-filename="'+args.content.name_images+'?v='+time_version+'"' +
                            '   data-amount="'+args.content.count_images+'"' +
                            '   data-bottom-circle data-hide-360-logo data-spin-reverse data-autoplay data-autoplay-reverse data-play-once' +
                            '></div>';
                        $.fancybox.open({
                            src  : html,
                            type : 'html',
                            touch: false,
                            smallBtn: false,
                            clickOutside: false,
                            caption : caption,
                            afterShow : function() {
                                window.CI360.init();
                            }
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'product':
                switch(view_type) {
                    case 0:
                        if(args.product!='') {
                            var html = '<div style="max-width:90%;background-color: '+args.box_background+';">'+get_product_html(args.product,args.product_images,args.id,args.box_color,args.product.button_background,args.product.button_color)+'</div>';
                            product_lightbox = $.fancybox.open({
                                src  : html,
                                type : 'html',
                                touch: false,
                                smallBtn: false,
                                clickOutside: false,
                                caption : caption,
                                afterShow : function() {
                                    $("#product_"+args.id+" .carousel").swipe({
                                        swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
                                            if (direction == 'left') $(this).carousel('next');
                                            if (direction == 'right') $(this).carousel('prev');
                                        },
                                        allowPageScroll: "vertical"
                                    });
                                }
                            });
                        }
                        break;
                    case 1:
                    case 2:
                        if(args.product!='') {
                            view_poi_box(args.id,false);
                        }
                        break;
                }
                break;
            case 'object3d':
                var array_files = args.content.split(",");
                var glb_file = '', usdz_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(file_s.split('.').pop().toLowerCase()=='usdz') {
                        usdz_file = file_s;
                    }
                });
                switch(view_type) {
                    case 0:
                        if(args.params!='') {
                            var tmp = args.params.split(",");
                            var placement = tmp[0];
                            if(tmp[1]!==undefined) {
                                var interaction = parseInt(tmp[1]);
                            } else {
                                var interaction = 1;
                            }
                            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 animation = tmp[4];
                                if(animation=='none') {
                                    animation = '';
                                    var autoplay = '';
                                } else {
                                    var autoplay = 'autoplay';
                                }
                            } else {
                                var animation = '';
                                var autoplay = '';
                            }
                            if(tmp[5]!==undefined) {
                                var autorotate = tmp[5];
                            } else {
                                var autorotate = 'auto-rotate';
                            }
                            if(tmp[6]!==undefined) {
                                var disable_zoom = tmp[6];
                            } else {
                                var disable_zoom = 'disable-zoom';
                            }
                            if(tmp[7]!==undefined) {
                                var disable_pan = tmp[7];
                            } else {
                                var disable_pan = 'disable-pan';
                            }
                        } else {
                            var placement = '';
                            var interaction = 1;
                            var exposure = 1;
                            var environment = 'legacy';
                            var animation = '';
                            var autoplay = '';
                            var autorotate = 'auto-rotate';
                            var disable_zoom = 'disable-zoom';
                            var disable_pan = 'disable-pan';
                        }
                        switch(interaction) {
                            case 0: //disabled
                                var camera_controls = '';
                                var rotate_3d_object = '';
                                break;
                            case 1: //horizontal and vertical
                                var camera_controls = 'camera-controls';
                                var rotate_3d_object = '';
                                break;
                            case 2: //horizontal
                                var camera_controls = 'camera-controls';
                                var rotate_3d_object = 'camera-orbit="0deg 75deg" min-camera-orbit="auto 75deg auto" max-camera-orbit="auto 75deg auto"';
                                break;
                            case 3: //vertical
                                var camera_controls = 'camera-controls';
                                var rotate_3d_object = 'camera-orbit="0deg 75deg" min-camera-orbit="0deg 22.5deg auto" max-camera-orbit="0deg 157.5deg auto"';
                                break;
                        }
                        switch(placement) {
                            case 'floor':
                            case 'wall':
                                if(usdz_file!='') {
                                    var html = '<div class="poi_object3d_content"><model-viewer disable-tap '+disable_pan+' '+disable_zoom+' '+autorotate+' '+rotate_3d_object+' exposure="'+exposure+'" '+autoplay+' animation-name="'+animation+'" src="'+((window.s3_enabled) ? window.s3_url : '')+glb_file+'" ios-src="'+((window.s3_enabled) ? window.s3_url : '')+usdz_file+'" alt="" ar ar-modes="webxr scene-viewer quick-look" ar-placement="'+args.params+'" environment-image="'+environment+'" shadow-intensity="0" '+rotate_3d_object+' '+camera_controls+'>'+button_ar+'</model-viewer></div>';
                                } else {
                                    var html = '<div class="poi_object3d_content"><model-viewer disable-tap '+disable_pan+' '+disable_zoom+' '+autorotate+' '+rotate_3d_object+' exposure="'+exposure+'" '+autoplay+' animation-name="'+animation+'" src="'+((window.s3_enabled) ? window.s3_url : '')+glb_file+'" alt="" ar ar-modes="webxr scene-viewer quick-look" ar-placement="'+args.params+'" environment-image="'+environment+'" shadow-intensity="0" '+rotate_3d_object+' '+camera_controls+'>'+button_ar+'</model-viewer></div>';
                                }
                                break;
                            default:
                                var html = '<div class="poi_object3d_content"><model-viewer disable-tap '+disable_pan+' '+disable_zoom+' '+autorotate+' '+rotate_3d_object+' exposure="'+exposure+'" '+autoplay+' animation-name="'+animation+'" src="'+((window.s3_enabled) ? window.s3_url : '')+glb_file+'" alt="" environment-image="'+environment+'" shadow-intensity="0" '+rotate_3d_object+' '+camera_controls+'></model-viewer></div>';
                                break;
                        }
                        $.fancybox.open({
                            src  : html,
                            type : 'html',
                            touch: false,
                            smallBtn: false,
                            clickOutside: false,
                            caption : caption,
                            afterShow : function() {}
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'lottie':
                switch(view_type) {
                    case 0:
                        var html = '<div id="poi_lottie_'+args.id+'" class="poi_lottie_content"></div>';
                        $.fancybox.open({
                            src  : html,
                            type : 'html',
                            touch: false,
                            smallBtn: false,
                            clickOutside: false,
                            afterShow : function() {
                                bodymovin.loadAnimation({
                                    container: document.getElementById('poi_lottie_'+args.id),
                                    renderer: 'svg',
                                    loop: true,
                                    autoplay: true,
                                    path: ((window.s3_enabled) ? window.s3_url : '')+args.content+((window.s3_enabled) ? '?s3='+s3_version : ''),
                                    rendererSettings: {
                                        progressiveLoad: true,
                                    }
                                });
                            }
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'google_maps':
                switch(view_type) {
                    case 0:
                        var gm_map = args.content.split('|')[0];
                        var gm_street = args.content.split('|')[1];
                        if (gm_map.startsWith('http')) {
                            gm_map = '<iframe src="'+gm_map+'" frameborder="0" width="100%" height="100%"></iframe>';
                        }
                        if (gm_street.startsWith('http')) {
                            gm_street = '<iframe src="'+gm_street+'" frameborder="0" width="100%" height="100%"></iframe>';
                        }
                        var content = '<div class="poi_google_maps_content">'+gm_map+' '+gm_street+'</div>';
                        $.fancybox.open({
                            src  : content,
                            type : 'html',
                            touch: false,
                            smallBtn: false,
                            caption : caption,
                            afterShow : function() {
                                if((gm_map=='') || (gm_street=='')) {
                                    $('.poi_google_maps_content iframe:nth-child(1)').addClass('poi_google_maps_full_width');
                                }
                            }
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'audio':
                if(parseInt($('.audio_poi_'+args.id).attr('data-playing'))==0) {
                    $('.audio_poi').each(function() {
                        $(this).css('opacity',0);
                        $(this).css('pointer-events','none');
                        try {
                            $(this).find('audio')[0].pause();
                            $(this).find('audio')[0].currentTime = 0;
                        } catch (e) {}
                    });
                    if(args.params=='minimal') {
                        $('.hotspot_'+args.id+' i').removeClass('fa-play').addClass('fa-stop');
                    } else {
                        $('.audio_poi_'+args.id).css('opacity',1);
                        $('.audio_poi_'+args.id).css('pointer-events','initial');
                    }
                    $('.audio_poi_'+args.id).attr('data-playing',1);
                    $('.audio_poi_'+args.id+' audio')[0].addEventListener("playing", function(){
                        if(controls_status['song']) {
                            if(isIOS()) {
                                set_audio_volume(0,-1);
                            } else {
                                set_audio_volume(args.song_bg_volume,-1);
                            }
                        }
                    });
                    $('.audio_poi_'+args.id+' audio')[0].addEventListener("pause", function(){
                        if(!live_session_connected) {
                            if(controls_status['song']) {
                                set_audio_volume(main_song_bg_volume,-1);
                            }
                        }
                    });
                    $('.audio_poi_'+args.id+' audio')[0].addEventListener("ended", function(){
                        if(args.params=='minimal') {
                            $('.hotspot_'+args.id+' i').removeClass('fa-stop').addClass('fa-play');
                        } else {
                            $('.audio_poi_'+args.id).css('opacity',0);
                            $('.audio_poi_'+args.id).css('pointer-events','none');
                        }
                        $('.audio_poi_'+args.id).attr('data-playing',0);
                        $('.audio_poi_'+args.id+' audio')[0].pause();
                        $('.audio_poi_'+args.id+' audio')[0].currentTime=0;
                        if(!live_session_connected) {
                            if(controls_status['song']) {
                                set_audio_volume(main_song_bg_volume,-1);
                            }
                        }
                    });
                    $('.audio_poi_'+args.id+' audio')[0].play();
                } else {
                    if(args.params=='minimal') {
                        $('.hotspot_'+args.id+' i').removeClass('fa-stop').addClass('fa-play');
                    } else {
                        $('.audio_poi_'+args.id).css('opacity',0);
                        $('.audio_poi_'+args.id).css('pointer-events','none');
                    }
                    $('.audio_poi_'+args.id).attr('data-playing',0);
                    $('.audio_poi_'+args.id+' audio')[0].pause();
                    $('.audio_poi_'+args.id+' audio')[0].currentTime=0;
                    if(!live_session_connected) {
                        if(controls_status['song']) {
                            set_audio_volume(main_song_bg_volume,-1);
                        }
                    }
                }
                break;
            case 'video360':
                switch(view_type) {
                    case 0:
                        var html_content = '';
                        html_content += '<div style="width:calc(100% - 20px);height:calc(100% - 20px);background:transparent;">' +
                            '<video style="width:100%;height:100%" crossorigin="anonymous" preload controls playsinline webkit-playsinline class="video-js vjs-default-skin vjs-big-play-centered" id="video360_'+args.id+'">' +
                            '<source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="video/mp4">' +
                            '</video>' +
                            '</div>';
                        $.fancybox.open({
                            src  : html_content,
                            type : 'html',
                            caption : caption,
                            touch : false,
                            smallBtn: false,
                            beforeShow: function () {
                                try {
                                    video360_poi[args.id].dispose();
                                } catch (e) {}
                            },
                            afterShow: function () {
                                video360_poi[args.id] = videojs('video360_'+args.id,{
                                    autoplay: false,
                                    controlBar: {
                                        pictureInPictureToggle: false
                                    }
                                });
                                video360_poi[args.id].vr({projection: '360'});
                                video360_poi[args.id].pause();
                                video360_poi[args.id].on('play',function () {
                                    mute_audio(true,true);
                                });
                                video360_poi[args.id].on('end',function () {
                                    if(!live_session_connected) {
                                        if(controls_status['song']) {
                                            unmute_audio(true,true);
                                        }
                                    }
                                });
                            },
                            beforeClose: function() {
                                video360_poi[args.id].dispose();
                                if(!live_session_connected) {
                                    if(controls_status['song']) {
                                        unmute_audio(true,true);
                                    }
                                }
                            }
                        });
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        break;
                }
                break;
            case 'form':
                switch(view_type) {
                    case 0:
                        try {
                            var content = JSON.parse(args.content);
                            var response = content[0].response;
                            var background = content[0].background;
                            if(background==null) background = 'rgba(255,255,255,1.0)';
                            var color = content[0].color;
                            if(color==null) color = '#000000';
                            var html_content = '<div style="background-color:'+background+';color:'+color+';">'+parse_form_content(content,args.id_room,args.id)+'</div>';
                            form_lightbox = $.fancybox.open({
                                src  : html_content,
                                type : 'html',
                                touch: false
                            });
                            $(".form_poi").submit(function(e){
                                var form_data = new FormData(this);
                                confirm_poi_form(form_data,response,null);
                                e.preventDefault();
                            });
                        } catch (e) {}
                        break;
                    case 1:
                    case 2:
                        view_poi_box(args.id,false);
                        var content = JSON.parse(args.content);
                        var response = content[0].response;
                        $(".form_poi").submit(function(e){
                            var form_data = new FormData(this);
                            confirm_poi_form(form_data,response,args.id);
                            e.preventDefault();
                        });
                        break;
                }
                break;
        }
        switch(view_type) {
            case 0:
                if(args.auto_close!=0) {
                    clearTimeout(interval_auto_close_poi);
                    interval_auto_close_poi = setTimeout(function() {
                        $.fancybox.close(true);
                        restart_autorotate();
                    },args.auto_close);
                }
                break;
            case 1:
            case 2:
                if(args.auto_close!=0) {
                    clearTimeout(interval_auto_close_poi);
                    interval_auto_close_poi = setTimeout(function() {
                        close_poi_box(args.id);
                    },args.auto_close);
                }
                break;
        }
    }

    function restart_autorotate() {
        clearTimeout(autorotate_timeout);
        var index_current = get_id_viewer(current_id_panorama);
        if(panoramas[index_current].autorotate_override==1) {
            var autorotate_speed_h = panoramas[index_current].autorotate_speed;
            var autorotate_inactivity_h = panoramas[index_current].autorotate_inactivity;
        } else {
            var autorotate_speed_h = autorotate_speed;
            var autorotate_inactivity_h = autorotate_inactivity;
        }
        if(autorotate_speed_h!=0 && controls_status['auto_rotate'] && !live_session_connected) {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                try {
                    pano_viewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                    autorotate_timeout = setTimeout(function () {
                        pano_viewer.startAutoRotate(autorotate_speed_h);
                    },autorotate_inactivity_h);
                } catch (e) {}
            } else {
                try {
                    video_viewer.pnlmViewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                    autorotate_timeout = setTimeout(function () {
                        video_viewer.pnlmViewer.startAutoRotate(autorotate_speed_h);
                    },autorotate_inactivity_h);
                } catch (e) {}
            }
        }
    }

    function close_poi_box(id) {
        $('.tooltip_poi_'+id).removeClass('hidden_pb');
        $('.box_poi_'+id).css({'opacity':0,'pointer-events':'none'});
        $('.box_poi_'+id).hide();
        window.poi_box_open = false;
        restart_autorotate();
    }

    function view_poi_box(id,keep_open) {
        if($('.box_poi_'+id).css('opacity')==1 && keep_open==false) {
            $('.tooltip_poi_'+id).removeClass('hidden_pb');
            $('.box_poi_'+id).css({'opacity':0,'pointer-events':'none'});
            $('.box_poi_'+id).hide();
            window.poi_box_open = false;
            clearTimeout(interval_auto_close_poi);
        } else {
            $('.tooltip_poi_'+id).addClass('hidden_pb');
            $('.box_poi_'+id).show();
            window.poi_box_open = true;
            if ($('.box_poi_'+id+' video').length == 1) {
                setTimeout(function() {
                    var video = $('.box_poi_'+id+' video')[0];
                    if (video.paused) {
                        video.play();
                    }
                },250);
            }
            $(window).trigger('resize');
            setTimeout(function() {
                if($('.box_poi_'+id).css('opacity')==0) {
                    set_poi_statistics('',id);
                }
                setTimeout(function() {
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        pano_viewer.resize();
                    } else {
                        video_viewer.pnlmViewer.resize();
                    }
                    $('.box_poi_'+id).css({'opacity':1,'pointer-events':'initial'});
                },50);
                setTimeout(function() {
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        pano_viewer.resize();
                    } else {
                        video_viewer.pnlmViewer.resize();
                    }
                },150);
            },20);
        }
    }

    function get_product_html(product,product_images,id,color,button_background,button_color) {
        var html = '<div style="background: transparent;" id="product_'+id+'" class="product-wrapper bootstrap-iso">\n' +
            '<div class="container-fluid">\n' +
            '<div class="row">\n';
        var col = 12;
        var text_center = 'text-center';
        var first_image = '';
        var margin_auto = 'm-auto';
        if(product_images.length>0) {
            if(product_images.length==1) {
                var image_d = 'd-none';
            } else {
                var image_d = '';
            }
            col = 6;
            text_center = '';
            first_image = product_images[0].src;
            margin_auto = '';
            html += '<div class="col-12 col-sm-12 col-md-6 product-slider">\n' +
                '<i onclick="open_product_gallery('+id+');" class="zoom_product fas fa-search-plus"></i>\n' +
                '<div id="carouselIndicators_'+id+'" class="carousel slide" data-ride="carousel">\n' +
                '<ol class="carousel-indicators '+image_d+'">\n';
            jQuery.each(product_images, function(index, product_image) {
                var image = product_image.src_thumb;
                var active = '';
                if(index==0) active='active';
                html += '<li data-target="#carouselIndicators_'+id+'" data-slide-to="'+index+'" class="'+active+'"><img src="'+((window.s3_enabled) ? window.s3_url : '')+image+'" class="d-block w-100"></li>\n';
            });
            html += '</ol>\n' +
                '<div class="carousel-inner">\n';
            jQuery.each(product_images, function(index, product_image) {
                var image = product_image.src;
                var active = '';
                if(index==0) active='active';
                html +='<div class="carousel-item '+active+'">\n' +
                    '<img draggable="false" src="'+((window.s3_enabled && shop_type=='snipcart') ? window.s3_url : '')+image+'" class="d-block">\n' +
                    '</div>\n';
            });
            html += '<a class="carousel-control-prev '+image_d+'" href="#carouselIndicators_'+id+'" role="button" data-slide="prev">\n' +
                '   <span class="carousel-control-prev-icon" aria-hidden="true"></span>\n' +
                '   <span class="sr-only">Previous</span>\n' +
                '</a>\n' +
                '<a class="carousel-control-next '+image_d+'" href="#carouselIndicators_'+id+'" role="button" data-slide="next">\n' +
                '   <span class="carousel-control-next-icon" aria-hidden="true"></span>\n' +
                '   <span class="sr-only">Next</span>\n' +
                '</a>\n' +
                '</div>\n</div>\n</div>\n';
        }
        var stock_html = '';
        if(product.source=='woocommerce' && product.type!='external') {
            stock_html += '<div class="product-stock">';
            switch(product.status) {
                case 'outofstock':
                    stock_html += '<i class="fas fa-circle" style="color:red"></i>&nbsp;&nbsp;'+window.viewer_labels.out_of_stock.toLowerCase();
                    break;
                default:
                    if(product.stock_quantity==null || product.stock_quantity==0) {
                        stock_html += '<i class="fas fa-circle" style="color:green"></i>&nbsp;&nbsp;'+window.viewer_labels.in_stock.toLowerCase();
                    } else {
                        stock_html += '<i class="fas fa-circle" style="color:green"></i>&nbsp;&nbsp;'+window.viewer_labels.in_stock.toLowerCase()+' ('+product.stock_quantity+' '+window.viewer_labels.available.toLowerCase()+')';
                    }
                    break;
            }
            stock_html += '</div>';
        }
        html += '<div class="col-12 col-sm-12 col-md-'+col+' '+text_center+' product-content" style="color:'+color+';background: transparent;">\n' +
            '<div class="product-title" style="color:'+color+'">\n' +
            '   <span>'+product.name+'</span>\n' +
            '</div>\n' +
            '<div class="product-price" style="color:'+color+'">\n' + product.price_html + '</div>\n' + stock_html +
            '<div class="product-description" style="color:'+color+'">\n' + product.description + '</div>\n';
        wc_default_price_html = product.price_html;
        wc_default_stock_html = stock_html;
        var button_icon = product.button_icon;
        var button_text = product.button_text;
        switch(product.source) {
            case 'snipcart':
                if(button_text=='') {
                    switch(product.purchase_type) {
                        case 'cart':
                            button_text = window.viewer_labels.add_to_cart;
                            break;
                        case 'popup':
                        case 'link':
                            button_text = window.viewer_labels.buy;
                            break;
                    }
                }
                switch(product.purchase_type) {
                    case 'popup':
                        html += '<div class="btn-wrapper">\n' +
                            '<a class="'+margin_auto+'" data-fancybox data-type="iframe" data-src="'+product.link+'" href="javascript:;"><span style="background-color:'+button_background+';color:'+button_color+';" class="btn"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</span></a>\n' +
                            '</div>\n';
                        break;
                    case 'link':
                        html += '<div class="btn-wrapper">\n' +
                            '<a class="'+margin_auto+'" href="'+product.link+'" target="_blank"><span style="background-color:'+button_background+';color:'+button_color+';" class="btn"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</span></a>\n' +
                            '</div>\n';
                        break;
                    case 'cart':
                        if(product.price>0) {
                            html += '<div class="btn-wrapper">\n' +
                                '<button style="background-color:'+button_background+';color:'+button_color+';" onclick="close_product('+id+');" class="snipcart-add-item btn '+margin_auto+'" data-item-has-taxes-included="true" data-item-url="'+window.base_url+'services/product_json.php?id='+product.id+'" data-item-id="'+product.id+'" data-item-price="'+product.price+'" data-item-description="'+product.description.replace( /(<([^>]+)>)/ig, '')+'" data-item-image="'+first_image+'" data-item-name="'+product.name+'"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</button>\n' +
                                '</div>\n';
                        }
                        break;
                }
                break;
            case 'woocommerce':
                var button_text = window.viewer_labels.add_to_cart;
                switch(product.type) {
                    case 'simple':
                        if(product.status=='outofstock') {
                            var button_icon = 'fas fa-shopping-cart';
                            var button_disabled = 'disabled';
                        } else {
                            var button_icon = 'fas fa-cart-plus';
                            var button_disabled = '';
                        }
                        html += '<div class="btn-wrapper">\n' +
                            '<button id="btn_add_to_cart_wc_'+id+'" '+button_disabled+' onclick="add_to_cart_wc('+product.id+',\''+product.type+'\','+id+',\'\');" class="btn '+button_disabled+'"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</button>\n' +
                            '</div>\n';
                        break;
                    case 'grouped':
                        if(product.status=='outofstock') {
                            var button_icon = 'fas fa-shopping-cart';
                            var button_disabled = 'disabled';
                        } else {
                            var button_icon = 'fas fa-cart-plus';
                            var button_disabled = '';
                        }
                        html += '<div class="btn-wrapper">\n' +
                            '<button id="btn_add_to_cart_wc_'+id+'" '+button_disabled+' onclick="add_to_cart_wc('+product.id+',\''+product.type+'\','+id+',\''+product.grouped_products.toString()+'\');" class="btn '+button_disabled+'"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</button>\n' +
                            '</div>\n';
                        break;
                    case 'variable':
                        if(product.status=='outofstock') {
                            var button_icon = 'fas fa-shopping-cart';
                        } else {
                            var button_icon = 'fas fa-cart-plus';
                        }
                        var attributes = product.attributes;
                        wc_product_variations = product.variations;
                        wc_product_variations.sort((a, b) => a.id - b.id);
                        html += '<div class="row" id="wc_product_attributes_'+id+'">';
                        jQuery.each(attributes, function(index_a, attribute) {
                            var attribute_slug = '';
                            jQuery.each(wc_product_attributes, function(index_pa, product_attribute) {
                                if(product_attribute.name==attribute.name) {
                                    attribute_slug = product_attribute.slug;
                                }
                            });
                            if(attribute_slug=='') {
                                attribute_slug=attribute.name.toLowerCase().replace(' ','-');
                            }
                            html += '<div class="col-12 col-md-6">';
                            html += '<div>'+attribute.name+'</div>';
                            html += '<div class="wc_select_wrapper">';
                            html += '<select onchange="change_wc_product_attribute('+id+');" class="wc_product_attribute" data-name="'+attribute.name+'" id="attribute_'+attribute_slug+'">';
                            html += '<option id="-1">'+window.viewer_labels.choose_an_option+'</option>';
                            jQuery.each(attribute.options, function(index_o, option) {
                                html += '<option id="'+option.replace(/"/g, '|dq|')+'">'+option+'</option>';
                            });
                            html += '</select>';
                            html += '<div class="select_arrow"></div>';
                            html += '</div>';
                            html += '</div>';
                        });
                        html += '</div>';
                        html += '<input type="hidden" id="wc_id_variation" value="">';
                        html += '<div class="row mt-2">';
                        html += '<div class="col-12">';
                        html += '<div class="btn-wrapper">\n' +
                            '<button id="btn_add_to_cart_wc_'+id+'" disabled onclick="add_to_cart_wc('+product.id+',\''+product.type+'\','+id+',\''+product.grouped_products.toString()+'\');" class="btn disabled"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</button>\n' +
                            '</div>\n';
                        html += '</div>';
                        html += '</div>';
                        break;
                    case 'external':
                        var button_icon = 'fas fa-external-link-alt';
                        var button_text = (product.button_text!='') ? product.button_text : window.viewer_labels.buy;
                        html += '<div class="btn-wrapper">\n' +
                            '<a class="'+margin_auto+'" href="'+product.external_url+'" target="_blank"><span class="btn"><i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text+'</span></a>\n' +
                            '</div>\n';
                        break;
                }
                break;
        }
        html += '</div>\n</div>\n</div>\n</div>\n';
        return html;
    }

    function wc_selected_attributes(id_poi) {
        var selects = [];
        var selectedValues = {};
        var combinations = [];
        jQuery.each(wc_product_variations,function(index_pv,variation) {
            var tmp = {};
            jQuery.each(variation.attributes,function(index_a,attribute) {
                tmp[attribute.name] = attribute.option;
            });
            combinations.push(tmp);
        });
        $('#wc_product_attributes_' + id_poi + ' .wc_product_attribute').each(function() {
            var id_select = $(this).attr('id');
            var name_attribute = $(this).attr('data-name');
            var select_tmp = {
                id: id_select,
                name: name_attribute
            };
            selects.push(select_tmp);
        });
        function wc_isAttributePresent(attribute) {
            return combinations.some(obj => attribute in obj);
        }
        var all_option_selected = true;
        selects.forEach(select => {
            var selectElement = $('#wc_product_attributes_' + id_poi + ' #'+select.id)[0];
            var selectedOption = selectElement.options[selectElement.selectedIndex];
            if (selectedOption.id !== '-1') {
                if(wc_isAttributePresent(select.name)) {
                    selectedValues[select.name] = selectedOption.id;
                }
            } else {
                all_option_selected = false;
            }
        });
        const desiredVariation = wc_product_variations.find((prototype) => {
            return Object.entries(selectedValues).every(([key, value]) => {
                return prototype.attributes.some((attribute) => {
                    return attribute.name === key && attribute.option.replace(/"/g, '|dq|') === value.replace(/"/g, '|dq|');
                });
            });
        });
        if(all_option_selected) {
            var price = desiredVariation.price;
            var button_text = window.viewer_labels.add_to_cart;
            if(desiredVariation.stock_status=='outofstock') {
                $('#btn_add_to_cart_wc_'+id_poi).prop('disabled',true);
                $('#btn_add_to_cart_wc_'+id_poi).addClass('disabled');
                var button_icon = 'fas fa-shopping-cart';
                var stock_html = '<i class="fas fa-circle" style="color:red"></i>&nbsp;&nbsp;'+window.viewer_labels.out_of_stock.toLowerCase();
            } else {
                $('#btn_add_to_cart_wc_'+id_poi).prop('disabled',false);
                $('#btn_add_to_cart_wc_'+id_poi).removeClass('disabled');
                var button_icon = 'fas fa-cart-plus';
                if(desiredVariation.stock_quantity==null || desiredVariation.stock_quantity==0) {
                    var stock_html = '<i class="fas fa-circle" style="color:green"></i>&nbsp;&nbsp;'+window.viewer_labels.in_stock.toLowerCase();
                } else {
                    var stock_html = '<i class="fas fa-circle" style="color:green"></i>&nbsp;&nbsp;'+window.viewer_labels.in_stock.toLowerCase()+' ('+desiredVariation.stock_quantity+' '+window.viewer_labels.available.toLowerCase()+')';
                }
            }
            $('#product_'+id_poi+' .product-stock').html(stock_html);
            $('#btn_add_to_cart_wc_'+id_poi).html('<i class="'+button_icon+'"></i>&nbsp;&nbsp;'+button_text);
            $('#wc_id_variation').val(desiredVariation.id);
        } else {
            var price = wc_default_price_html;
            $('#btn_add_to_cart_wc_'+id_poi).prop('disabled',true);
            $('#btn_add_to_cart_wc_'+id_poi).addClass('disabled');
            $('#product_'+id_poi+' .product-stock').html(wc_default_stock_html);
        }
        $('#product_'+id_poi+' .product-price').html(price);
        var image_src = '';
        try {
            image_src = desiredVariation.image.src;
        } catch (e) {}
        if(image_src!='') {
            $('#carouselIndicators_'+id_poi+' .carousel-indicators li img[src="'+image_src+'"]').parent().trigger('click');
        }
    }

    function wc_check_options(id_poi) {
        wc_selectOptions = {};
        wc_selectElements = {};
        var combinations = [];
        jQuery.each(wc_product_variations,function(index_pv,variation) {
            var tmp = {};
            jQuery.each(variation.attributes,function(index_a,attribute) {
                tmp[attribute.name] = attribute.option;
            });
            combinations.push(tmp);
        });
        $('#wc_product_attributes_' + id_poi + ' .wc_product_attribute').each(function() {
            var name_attribute = $(this).attr('data-name');
            wc_selectElements[name_attribute] = $(this)[0];
            if (!wc_selectOptions[name_attribute]) {
                wc_selectOptions[name_attribute] = [];
            }
            $(this).find('option').each(function() {
                var option = $(this).attr('id');
                if(option!='-1') {
                    if (!wc_selectOptions[name_attribute].includes(option)) {
                        wc_selectOptions[name_attribute].push(option);
                    }
                }
            });
        });
        function wc_isAttributePresent(attribute) {
            return combinations.some(obj => attribute in obj);
        }
        function wc_updateOptionAvailability() {
            const selectedValues = {};
            for (const key in wc_selectElements) {
                selectedValues[key] = wc_selectElements[key].options[wc_selectElements[key].selectedIndex].id;
            }
            for (const key in wc_selectElements) {
                const currentSelect = wc_selectElements[key];
                wc_selectOptions[key].forEach(option => {
                    const combination = { ...selectedValues, [key]: option };
                    const isValidCombination = combinations.some(c => {
                        return Object.entries(combination).every(([key, value]) => c[key] === value || value === "-1" || !wc_isAttributePresent(key));
                    });
                    const optionElement = currentSelect.querySelector(`option[id="${option}"]`);
                    optionElement.disabled = !isValidCombination;
                });
            }
        }
        wc_updateOptionAvailability();
    }

    window.change_wc_product_attribute = function(id_poi) {
        wc_check_options(id_poi);
        wc_selected_attributes(id_poi);
    }

    window.add_to_cart_wc = function(id,type,id_poi,groped_products) {
        var html_btn = $('#btn_add_to_cart_wc_'+id_poi).html();
        $('#btn_add_to_cart_wc_'+id_poi).addClass('disabled');
        $('#btn_add_to_cart_wc_'+id_poi).html('<i class="fas fa-circle-notch fa-spin"></i>');
        var variation = {};
        var id_variation = null;
        if(type=='variable') {
            $('#wc_product_attributes_' + id_poi + ' .wc_product_attribute').each(function() {
                var id_attribute = $(this).attr('id');
                var sel_attribute = $(this).find('option:selected').attr('id');
                variation[id_attribute]=sel_attribute.toLowerCase();
            });
            id_variation = $('#wc_id_variation').val();
        }
        $.ajax({
            url: "ajax/add_to_cart_wc.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                woocommerce_store_url: woocommerce_store_url,
                woocommerce_store_cart: woocommerce_store_cart,
                id_product: id,
                product_type: type,
                groped_products: groped_products,
                id_variation: id_variation,
                variation: variation
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == 'ok' || (rsp.status=='error' && rsp.response.includes('cocart_product_out_of_stock'))) {
                    close_product(id);
                    get_total_cart_wc(id_poi,html_btn);
                    open_cart_wc(true);
                } else {
                    $('#btn_add_to_cart_wc_'+id_poi).removeClass('disabled');
                    $('#btn_add_to_cart_wc_'+id_poi).html(html_btn);
                }
            },
            error: function() {
                $('#btn_add_to_cart_wc_'+id_poi).removeClass('disabled');
                $('#btn_add_to_cart_wc_'+id_poi).html(html_btn);
            }
        });
    }

    window.remove_to_cart_wc = function(item_key) {
        $.ajax({
            url: "ajax/remove_to_cart_wc.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                woocommerce_store_url: woocommerce_store_url,
                item_key: item_key
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == 'ok') {
                    get_total_cart_wc();
                }
            },
            error: function() {

            }
        });
    }

    window.open_cart_wc = function(force) {
        if($('.wc').is(':visible') && !force) {
            close_cart_wc();
        } else {
            $('.wc').show();
            $('.wc .wc-modal__container').removeClass('wc-transition--slide-in-leave-active');
            $('.wc .wc-modal__container').addClass('wc-transition--slide-in-enter-active');
        }
    }

    window.close_cart_wc = function() {
        $('.wc .wc-modal__container').removeClass('wc-transition--slide-in-enter-active');
        $('.wc .wc-modal__container').addClass('wc-transition--slide-in-leave-active');
        setTimeout(function() {
            $('.wc').hide();
        },300);
    }

    window.get_total_cart_wc = function(id_poi=null,html_btn=null) {
        $.ajax({
            url: "ajax/get_total_cart_wc.php",
            type: "POST",
            data: {
                id_virtualtour: window.id_virtualtour,
                woocommerce_store_url: window.woocommerce_store_url,
                woocommerce_store_cart: window.woocommerce_store_cart,
                woocommerce_store_checkout: window.woocommerce_store_checkout
            },
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if (rsp.status == 'ok') {
                    var total = rsp.total;
                    var item_count = rsp.item_count;
                    var url_cart = rsp.url_cart;
                    var url_checkout = rsp.url_checkout;
                    var items = rsp.items;
                    if(item_count==0) {
                        $('.wc-cart__content').hide();
                        $('.wc-empty-cart').show();
                    } else {
                        parse_cart_items(items);
                        $('.wc-cart__content').show();
                        $('.wc-empty-cart').hide();
                    }
                    $('#checkout_url_btn').css('pointer-events','initial');
                    $('#cart_url_btn').css('pointer-events','initial');
                    if(window.woocommerce_modal) {
                        $('#cart_url_btn').attr('data-fancybox','');
                        $('#cart_url_btn').attr('data-type','iframe');
                        $('#cart_url_btn').attr('data-src',url_cart);
                        $('#cart_url_btn').attr('href','#');
                        $('#checkout_url_btn').attr('data-fancybox','');
                        $('#checkout_url_btn').attr('data-type','iframe');
                        $('#checkout_url_btn').attr('data-src',url_checkout);
                        $('#checkout_url_btn').attr('href','#');
                    } else {
                        $('#cart_url_btn').attr('href',url_cart);
                        $('#checkout_url_btn').attr('href',url_checkout);
                    }
                    $('.wc-summary-fees__amount').html(total);
                    $('.woocommerce-total-price').html(total);
                    $('.woocommerce-items-count').html(item_count);
                } else {
                    $('.wc-cart__content').hide();
                    $('.wc-empty-cart').show();
                    $('#checkout_url_btn').css('pointer-events','none');
                    $('#cart_url_btn').css('pointer-events','none');
                }
                if(id_poi!=null) {
                    $('#btn_add_to_cart_wc_'+id_poi).removeClass('disabled');
                    $('#btn_add_to_cart_wc_'+id_poi).html(html_btn);
                }
            },
            error: function() {
                $('.wc-cart__content').hide();
                $('.wc-empty-cart').show();
                $('#checkout_url_btn').css('pointer-events','none');
                if(id_poi!=null) {
                    $('#btn_add_to_cart_wc_'+id_poi).removeClass('disabled');
                    $('#btn_add_to_cart_wc_'+id_poi).html(html_btn);
                }
            }
        });
    }

    window.update_quantity_wc = function(item_key,direction,min_purchase,max_purchase) {
        var quantity = parseInt($('#wc_quantity_'+item_key).html());
        var ok_quantity = true;
        if(max_purchase==-1) max_purchase=99999;
        switch(direction) {
            case 'up':
                if(quantity<max_purchase) {
                    quantity = quantity + 1;
                } else {
                    ok_quantity = false;
                }
                break;
            case 'down':
                if(quantity>min_purchase) {
                    quantity = quantity - 1;
                } else {
                    ok_quantity = false;
                }
                break;
        }
        if(ok_quantity) {
            $.ajax({
                url: "ajax/update_quantity_wc.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    woocommerce_store_url: woocommerce_store_url,
                    item_key: item_key,
                    quantity: quantity
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == 'ok') {
                        $('#wc_quantity_'+item_key).html(quantity);
                        get_total_cart_wc();
                    }
                },
                error: function () {

                }
            });
        }
    }

    function parse_cart_items(items) {
        var html = '';
        for(var i=0;i<items.length;i++) {
            var item_key = items[i].item_key;
            var title = items[i].name;
            var image = items[i].featured_image;
            var quantity = items[i].quantity.value;
            var min_purchase = items[i].quantity.min_purchase;
            var max_purchase = items[i].quantity.max_purchase;
            var price = items[i].price_heml;
            var total = items[i].totals.total_html;
            html += '<li class="wc-item-line wc-item-line--cart-edit">';
            html += '<div class="wc-item-line__container"><div class="wc-item-line__product">\n' +
                '                                        <div class="wc-item-line__header">\n' +
                '                                            <figure class="wc-item-line__media wc-item-line__media--small">\n' +
                '                                                <img src="'+image+'"\n' +
                '                                                     class="wc-item-line__image"></figure>\n' +
                '                                            <h2 class="wc-item-line__title wc__font--xlarge wc__font--secondary wc__font--black">\n' +
                '                                                '+title+' </h2>\n' +
                '                                            <button onclick="remove_to_cart_wc(\''+item_key+'\');" aria-label="Remove item" title="Remove item"\n' +
                '                                                    class="wc-button-icon is-danger">\n' +
                '                                                <svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"\n' +
                '                                                     alt="" title="" class="wc__icon">\n' +
                '                                                    <path fill-rule="evenodd" clip-rule="evenodd"\n' +
                '                                                          d="M22 4v6.47H12v3.236h40V10.47H42V4H22zm3.333 6.47V7.235H38.67v3.235H25.333zm20.001 9.707h3.333V59H15.334V20.177h3.333v35.588h26.667V20.177zm-15 29.116V23.412h3.334v25.881h-3.334z"\n' +
                '                                                          fill="currentColor"></path>\n' +
                '                                                </svg>\n' +
                '                                            </button>\n' +
                '                                        </div>\n' +
                '                                        <div class="wc-item-line__content">\n' +
                '                                            <div class="wc-item-line__body">\n' +
                '                                                <div class="wc-item-line__info"></div>\n' +
                '                                                <div class="wc-item-line__variants">\n' +
                '                                                    <div>\n' +
                '                                                        <div class="wc-item-custom-fields"></div>\n' +
                '                                                    </div>\n' +
                '                                                    <div class="wc-item-quantity wc-item-line__quantity">\n' +
                '                                                        <label class="wc-item-quantity__label wc__font--tiny">\n' +
                '                                                            '+window.viewer_labels.quantity+' </label>\n' +
                '                                                        <div class="wc-item-quantity__quantity-price-container">\n' +
                '                                                            <div class="wc-item-quantity__quantity wc__font--std">\n' +
                '                                                                <button onclick="update_quantity_wc(\''+item_key+'\',\'down\','+min_purchase+','+max_purchase+');" aria-label="Decrement quantity"\n' +
                '                                                                        title="Decrement quantity"\n' +
                '                                                                        class="wc-button-icon is-small is-secondary">\n' +
                '                                                                    <svg viewBox="0 0 64 64" fill="none"\n' +
                '                                                                         xmlns="http://www.w3.org/2000/svg" alt=""\n' +
                '                                                                         title="" class="wc__icon">\n' +
                '                                                                        <path d="M48 31H16v2.462h32V31z"\n' +
                '                                                                              fill="currentColor"></path>\n' +
                '                                                                    </svg>\n' +
                '                                                                </button>\n' +
                '                                                                <span id="wc_quantity_'+item_key+'" class="wc__font--secondary wc__font--regular">'+quantity+'</span>\n' +
                '                                                                <button onclick="update_quantity_wc(\''+item_key+'\',\'up\','+min_purchase+','+max_purchase+');" aria-label="Increment quantity"\n' +
                '                                                                        title="Increment quantity"\n' +
                '                                                                        class="wc-button-icon is-small is-secondary">\n' +
                '                                                                    <svg viewBox="0 0 64 64" fill="none"\n' +
                '                                                                         xmlns="http://www.w3.org/2000/svg" alt=""\n' +
                '                                                                         title="" class="wc__icon">\n' +
                '                                                                        <path d="M33.23 30.77H48v2.46H33.23V48h-2.46V33.23H16v-2.46h14.77V16h2.46v14.77z"\n' +
                '                                                                              fill="currentColor"></path>\n' +
                '                                                                    </svg>\n' +
                '                                                                </button>\n' +
                '                                                            </div>\n' +
                '                                                            <div class="wc-item-quantity__total-price wc__font--bold wc__font--secondary">\n' +
                '                                                                '+total+'\n' +
                '                                                            </div>\n' +
                '                                                        </div>\n' +
                '                                                    </div>\n' +
                '                                                </div>\n' +
                '                                            </div>\n' +
                '                                        </div>\n' +
                '                                    </div></div>';
            html += '</li>';
        }
        $('.wc-item-list').html(html);
    }

    window.close_product = function(id) {
        if(leave_poi_open==0) close_all_pois();
        try {
            product_lightbox.close();
        } catch (e) {}
        restart_autorotate();
    }

    window.confirm_poi_form = function(form_data,response,id) {
        var btn_c = $('.form_poi button').html();
        $('.form_poi button').addClass("disabled");
        $('.form_poi button').html("<i class='fas fa-circle-notch fa-spin'></i>");
        $.ajax({
            url: "ajax/store_form_data.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    $('.form_poi button').addClass("button_success_form");
                    $('.form_poi button').html("<i class='fas fa-check'></i>");
                    setTimeout(function () {
                        $('.form_poi button').removeClass("disabled");
                        $('.form_poi button').removeClass("button_success_form");
                        if(id==null) {
                            form_lightbox.close();
                        } else {
                            view_poi_box(id,false);
                        }
                        if(response!='') {
                            $.alert({
                                theme: 'modern',
                                useBootstrap: false,
                                boxWidth: '300px',
                                type: 'green',
                                title: '',
                                content: response,
                            });
                        }
                    },1000);
                    if(rsp.email!='') {
                        var array_form = {};
                        for (var pair of form_data.entries()) {
                            array_form[pair[0]] = pair[1];
                        }
                        $.ajax({
                            url: "../backend/ajax/send_email.php",
                            type: "POST",
                            data: {
                                type: 'form',
                                email: rsp.email,
                                form_data: array_form
                            },
                            timeout: 15000,
                            async: true,
                            success: function (json) {

                            }
                        });
                    }
                } else {
                    $('.form_poi button').html(btn_c);
                    $('.form_poi button').removeClass("disabled");
                }
            }, error: function() {
                $('.form_poi button').html(btn_c);
                $('.form_poi button').removeClass("disabled");
            }
        });
    }

    function close_reset_inline_form() {
        const formElement = document.getElementById('inline_form_main');
        const toggleButton = document.getElementById('inline_form_toggle');
        const formContainer = document.getElementById('inline_form_content');
        const arrowIcon = document.getElementById('inline_form_arrow_icon');
        if(formElement) {
            formElement.reset();
            const fileInputs = formElement.querySelectorAll('input[type="file"]');
            fileInputs.forEach(input => input.value = '');
        }
        if (formContainer.classList.contains('open')) {
            arrowIcon.style.transform = 'rotate(0deg)';
            formContainer.classList.remove('open');
            formContainer.addEventListener('transitionend', () => {
                toggleButton.classList.remove('form_is_open');
            }, { once: true });
        }
    }

    window.confirm_main_form = function(form_data,response,type) {
        switch(type) {
            case 'main':
                var btn_c = $('.form_main button').html();
                $('.form_main button').addClass("disabled");
                $('.form_main button').html("<i class='fas fa-circle-notch fa-spin'></i>");
                break;
            case 'inline':
                var btn_c = $('.inline_form_submit_button').html();
                $('.inline_form_submit_button').addClass("disabled");
                $('.inline_form_submit_button').html("<i class='fas fa-circle-notch fa-spin'></i>");
                break;
        }
        $.ajax({
            url: "ajax/store_form_data.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            async: true,
            success: function (json) {
                var rsp = JSON.parse(json);
                if(rsp.status=='ok') {
                    switch(type) {
                        case 'main':
                            $('.form_main button').addClass("button_success_form");
                            $('.form_main button').html("<i class='fas fa-check'></i>");
                            break;
                        case 'inline':
                            $('.inline_form_submit_button').addClass("button_success_form");
                            $('.inline_form_submit_button').html("<i class='fas fa-check'></i>");
                            break;
                    }
                    setTimeout(function () {
                        switch(type) {
                            case 'main':
                                $('.form_main button').removeClass("disabled");
                                $('.form_main button').removeClass("button_success_form");
                                form_lightbox.close();
                                break;
                            case 'inline':
                                $('.inline_form_submit_button').removeClass("disabled");
                                $('.inline_form_submit_button').removeClass("button_success_form");
                                close_reset_inline_form();
                                $('.inline_form_submit_button').html(btn_c);
                                break;
                        }
                        if(response!='') {
                            $.alert({
                                theme: 'modern',
                                useBootstrap: false,
                                boxWidth: '300px',
                                type: 'green',
                                title: '',
                                content: response,
                            });
                        }
                    },1000);
                    if(rsp.email!='') {
                        var array_form = {};
                        for (var pair of form_data.entries()) {
                            array_form[pair[0]] = pair[1];
                        }
                        $.ajax({
                            url: "../backend/ajax/send_email.php",
                            type: "POST",
                            data: {
                                type: 'form',
                                email: rsp.email,
                                form_data: array_form
                            },
                            timeout: 15000,
                            async: true,
                            success: function (json) {}
                        });
                    }
                } else {
                    switch(type) {
                        case 'main':
                            $('.form_main button').html(btn_c);
                            $('.form_main button').removeClass("disabled");
                            break;
                        case 'inline':
                            $('.inline_form_submit_button').html(btn_c);
                            $('.inline_form_submit_button').removeClass("disabled");
                            break;
                    }
                }
            },
            error: function() {
                switch(type) {
                    case 'main':
                        $('.form_main button').html(btn_c);
                        $('.form_main button').removeClass("disabled");
                        break;
                    case 'inline':
                        $('.inline_form_submit_button').html(btn_c);
                        $('.inline_form_submit_button').removeClass("disabled");
                        break;
                }
            }
        });
    }

    window.set_poi_statistics = function(hotSpotDiv,id) {
        if(!$('#callout_'+id).length) {
            if(leave_poi_open==0) close_all_poi_box();
        }
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try { pano_viewer.stopAutoRotate(); } catch (e) {}
        } else {
            try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
        }
        if(window.export_mode==0 && window.preview==0 && window.nostat==0) {
            Pace.ignore(function(){
                $.ajax({
                    url: "ajax/set_statistics.php",
                    type: "POST",
                    data: {
                        type: 'poi',
                        id: id.replace('alt',''),
                        ip_visitor: window.ip_visitor
                    },
                    async: true
                });
            });
        }
    }

    function hotspot_nadir(hotSpotDiv, args) {
        var image = args[0];
        var round = args[1];
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.style = "background-image:url("+((window.s3_enabled) ? window.s3_url : '')+"content/"+image+");background-size:cover !important;";
        hotSpotDiv.style.width = nadir_size;
        hotSpotDiv.style.height = nadir_size;
        if(round==1) {
            hotSpotDiv.style.aspectRatio = 1;
            hotSpotDiv.style.borderRadius = '50%';
        }
    }

    function getYoutubeId(url) {
        const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
        const match = url.match(regExp);
        return (match && match[2].length === 11) ? match[2] : null;
    }

    function getVimeoId(url) {
        var m = url.match(/^.+vimeo.com\/(.*\/)?([^#\?]*)/);
        return m ? m[2] || m[1] : null;
    }

    var start_drag, end_drag, drag_p;

    function hotspot_visitor(hotSpotDiv, args) {
        if(!live_session_connected) {
            hotSpotDiv.setAttribute('data-id', args.id);
            hotSpotDiv.setAttribute('draggable',false);
            hotSpotDiv.classList.add('poi_not_selectable');
            hotSpotDiv.classList.add('noselect');
            var div_wrapper = document.createElement('div');
            div_wrapper.classList.add('div_visitor_wrapper');
            div_wrapper.style.backgroundColor = args.color;
            var i = document.createElement('i');
            i.className = 'fas fa-user';
            div_wrapper.appendChild(i);
            hotSpotDiv.appendChild(div_wrapper);
        }
    }

    function initialize_poi_staging() {
        if(worker==null) {
            worker = new Worker('worker_staging.js?v='+Date.now());
            worker_image = new Worker('worker_image.js?v'+Date.now());
            worker_image.onmessage = (event) => {
                const { id, bitmap, error } = event.data;
                if (error) {
                    console.error(`Error for id ${id}:`, error);
                } else {
                    if(id==0) {
                        currentBitmapImage = bitmap;
                    } else {
                        array_staging_bitmap[id] = bitmap;
                    }
                }
            };
            (async () => {
                const data = { id: 0, image: currentBaseImage };
                worker_image.postMessage(data);
            })();
        }
    }

    function hotspot_staging(hotSpotDiv, args) {
        initialize_poi_staging();
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        switch(args.tooltip_type) {
            case 'text':
                if(window.is_mobile && (args.tooltip_text_mobile !== null && args.tooltip_text_mobile !== '' && args.tooltip_text_mobile !== '<p><br></p>')) {
                    args.tooltip_text = args.tooltip_text_mobile;
                }
                if(args.tooltip_text !== null && args.tooltip_text !== '' && args.tooltip_text !== '<p><br></p>') {
                    var tooltip = document.createElement('div');
                    tooltip.classList.add('tooltip_poi_'+args.id);
                    tooltip.classList.add('tooltip_text');
                    tooltip.classList.add('tooltip_poi');
                    tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                    tooltip.innerHTML = args.tooltip_text;
                    hotSpotDiv.parentNode.appendChild(tooltip);
                }
                break;
        }
        try {
            if(controls_status['icons_content']==false) tooltip.classList.add('hidden_icons');
        } catch (e) {}
        switch(args.tooltip_visibility) {
            case 'hover':
                hotSpotDiv.addEventListener("mouseover", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'hotspot_t');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip(id,e);
                                $('.tooltip_poi_'+id).css('opacity',1);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            position_tooltip(id,e);
                            $('.tooltip_poi_'+id).css('opacity',1);
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('.tooltip_poi_'+id).css('opacity',0);
                        }
                    }
                });
                hotSpotDiv.addEventListener("mousemove", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'hotspot_t');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip(id,e);
                            }
                        }
                    }
                });
                break;
            case 'visible':
                $('.tooltip_poi_'+args.id).css('opacity',1);
                break;
            case 'visible_mobile':
                if(window.is_mobile) {
                    $('.tooltip_poi_'+args.id).css('opacity',1);
                } else {
                    hotSpotDiv.addEventListener("mouseover", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'hotspot_t');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_tooltip(id,e);
                                    $('.tooltip_poi_'+id).css('opacity',1);
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseenter", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip(id,e);
                                $('.tooltip_poi_'+id).css('opacity',1);
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseleave", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                $('.tooltip_poi_'+id).css('opacity',0);
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mousemove", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'hotspot_t');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_tooltip(id,e);
                                }
                            }
                        }
                    });
                }
                break;
        }
        var id = args.id;
        if(virtual_staging) {
            if (hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                id = "alt"+id;
            }
        }
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('custom-tooltip');
        hotSpotDiv.classList.add('hotspot_t');
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('hotspot_'+id);
        if(parseInt(args.is_grouped)==1) {
            hotSpotDiv.classList.add('hidden_grouped');
            hotSpotDiv.classList.add('grouped_poi');
        }
        if(virtual_staging) {
            hotSpotDiv.style.zIndex = parseInt(args.zIndex)+10;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.zIndex = args.zIndex;
        }
        if(args.css_class!='') {
            var array_css_class = args.css_class.split(" ");
            jQuery.each(array_css_class, function(index_c, css_class) {
                hotSpotDiv.classList.add(css_class);
            });
        }
        hotSpotDiv.setAttribute('data-id', id);
        var div = document.createElement('div');
        div.classList.add('staging_icon');
        div.id = "staging_icon_"+id;
        var main_elem = document.createElement('div');
        main_elem.classList.add('wcircle-icon');
        main_elem.style.pointerEvents = "none";
        div.appendChild(main_elem);
        var main_container = document.createElement('div');
        main_container.classList.add('wcircle-menu');
        main_container.style.display = "none";
        var count_elems = 0;
        args.content.forEach(function(item) {
            if(!window.is_mobile) {
                (async () => {
                    var image = ((window.s3_enabled) ? window.s3_url : '') + "staging/" + item.image + ((window.s3_enabled) ? '?s3=' + s3_version : '');
                    const data = {id: item.id, image: image};
                    worker_image.postMessage(data);
                })();
            }
            var staging_elem = document.createElement('div');
            staging_elem.classList.add('wcircle-menu-item');
            staging_elem.setAttribute('data-poi-id',id);
            staging_elem.setAttribute('data-id',item.id);
            staging_elem.setAttribute('title',item.tooltip);
            if(parseInt(item.default)==1) {
                staging_elem.classList.add('selected');
                staging_elem.classList.add('active');
            }
            var icon = ((window.s3_enabled) ? window.s3_url : '')+"staging/"+item.icon+((window.s3_enabled) ? '?s3='+s3_version : '');
            staging_elem.style.backgroundImage = `url(${icon})`;
            staging_elem.onclick = function(evt) {
                evt.stopPropagation();
                if($('.wcircle-menu-item[data-id="'+item.id+'"]').hasClass('active')) {
                    return;
                }
                staging_item_id_sel = item.id;
                $('.wcircle-menu-item[data-poi-id="'+id+'"]').removeClass('loading');
                $('.wcircle-menu-item[data-poi-id="'+id+'"]').removeClass('selected');
                $('.wcircle-menu-item[data-poi-id="'+id+'"]').removeClass('active');
                $('.wcircle-menu-item').addClass('inactive');
                $('.wcircle-menu-item[data-id="'+item.id+'"]').addClass('loading');
                $('.wcircle-menu-item[data-id="'+item.id+'"]').addClass('selected');
                swap_staging(id,item.id,item.image);
            }
            main_container.appendChild(staging_elem);
            count_elems++;
        });
        div.appendChild(main_container);
        var i = document.createElement('i');
        i.style = "color:"+args.color;
        i.className = 'icon_s '+args.icon;
        div.appendChild(i);
        hotSpotDiv.appendChild(div);
        if(count_elems<=6) {
            var angle_interval = Math.PI/3;
            var distance = 120;
        } else if(count_elems<=8) {
            var angle_interval = Math.PI/4;
            var distance = 150;
        } else if(count_elems<=10) {
            var angle_interval = Math.PI/5;
            var distance = 180;
        } else if(count_elems<=12) {
            var angle_interval = Math.PI/6;
            var distance = 210;
        }
        $(div).WCircleMenu({
            width: '64px',
            height: '64px',
            angle_start : -Math.PI/2,
            delay: 20,
            distance: distance,
            angle_interval: angle_interval,
            easingFuncShow:"easeOutBack",
            easingFuncHide:"easeInBack",
            step: 20,
            openCallback:false,
            closeCallback:false,
            itemRotation:360,
            iconRotation:90,
        });
        if(!window.is_mobile) {
            $(div).find('.wcircle-menu-item').tooltipster({
                theme: 'tooltipster-borderless',
                animation: 'grow',
                delay: 25,
                arrow: false
            });
        }
    }

    function toggle_staging(hotspotDiv, id) {
        if(leave_poi_open==0) close_all_pois();
        $('#staging_icon_'+id).WCircleMenu('open');
        if(!$('#staging_icon_'+id).hasClass('wcircle-open')) {
            set_poi_statistics('',id);
            $('.tooltip_poi_'+id).addClass('hidden');
        } else {
            setTimeout(function() {
                $('.tooltip_poi_'+id).removeClass('hidden');
            },300);
        }
    }

    function swap_staging(id_poi,id,image) {
        var id_array_staging = '';
        $('.wcircle-menu-item.selected').each(function() {
            var id = $(this).attr('data-id');
            id_array_staging = id_array_staging + id;
        });
        if(array_staging_bitmap[id]!==undefined) {
            var image_w = array_staging_bitmap[id];
        } else {
            var image_w = ((window.s3_enabled) ? window.s3_url : '')+"staging/"+image+((window.s3_enabled) ? '?s3='+s3_version : '')
        }
        if(currentBitmapImage!==null) {
            var base_w = currentBitmapImage;
        } else {
            var base_w = currentBaseImage;
        }
        currentBitmapImage = null;
        overlayImagesWithWorker(base_w, image_w, id_array_staging)
            .then(resultImage => {
                currentBaseImage = resultImage.src;
                (async () => {
                    const data = { id: 0, image: currentBaseImage };
                    worker_image.postMessage(data);
                })();
                $('.wcircle-menu-item[data-id="'+staging_item_id_sel+'"]').removeClass('loading');
                $('.wcircle-menu-item[data-id="'+staging_item_id_sel+'"]').addClass('active');
                $('.wcircle-menu-item').removeClass('inactive');
                pano_viewer.setPanorama(resultImage);
            })
            .catch(err => console.error("Overlay failed:", err));
    }

    function overlayImagesWithWorker(baseImageSrc, overlayImageSrc, id) {
        return new Promise((resolve, reject) => {
            worker.postMessage({ baseImageSrc: baseImageSrc, overlayImageSrc: overlayImageSrc, id:id });
            worker.onmessage = function (e) {
                if (e.data.error) {
                    reject(new Error(e.data.error));
                } else {
                    const img = new Image();
                    img.onload = () => resolve(img);
                    img.onerror = () => reject(new Error("Failed to create Image object."));
                    img.crossOrigin = 'anonymous';
                    img.src = e.data.base64Image;
                }
            };
            worker.onerror = function (err) {
                reject(new Error("Web Worker error: " + err.message));
            };
        });
    }

    function hotspot_callout(hotSpotDiv, args) {
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        var id = args.id;
        if(virtual_staging) {
            if (hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                id = "alt"+id;
            }
        }
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('hotspot_'+id);
        if(parseInt(args.is_grouped)==1) {
            hotSpotDiv.classList.add('hidden_grouped');
            hotSpotDiv.classList.add('grouped_poi');
        }
        if(virtual_staging) {
            hotSpotDiv.style.zIndex = parseInt(args.zIndex)+10;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.zIndex = args.zIndex;
        }
        if(args.css_class!='') {
            var array_css_class = args.css_class.split(" ");
            jQuery.each(array_css_class, function(index_c, css_class) {
                hotSpotDiv.classList.add(css_class);
            });
        }
        hotSpotDiv.setAttribute('data-id', id);
        var json_callout = args.params;
        if(args_callout[id] === undefined) {
            try {
                args_callout[id] = JSON.parse(json_callout);
            } catch (e) {
                return;
            }
        }
        if(args_callout[id].open=='hover' && window.is_mobile) args_callout[id].open='click';
        hotSpotDiv.setAttribute('data-open', args_callout[id].open);
        var tmp = args_callout[id].title_bg_color;
        tmp = tmp.replace('rgba(','').replace(')','');
        tmp = tmp.split(',');
        if(tmp[3]==0) {
            var title_margin = args_callout[id].title_margin+'px 0px';
        } else {
            var title_margin = args_callout[id].title_margin+'px';
        }
        switch(args_callout[id].dir) {
            case 'left':
                if(args_callout[id].rotate_fix===undefined) {
                    args_callout[id].rotate = args_callout[id].rotate + 180;
                    args_callout[id].rotate_fix=1;
                }
                var callout_html = '<div id="callout_'+id+'" class="callout" style="position: absolute; z-index: 2002; overflow: visible; background-color: '+args_callout[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 data-id="'+id+'" id="callout_pointer_'+id+'" class="callout_pointer callout_blink" style="position: absolute; z-index: 3001; overflow: visible; opacity: 0; cursor: default; pointer-events: none; background-image: none; border: 2px solid '+args_callout[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_'+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[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_'+id+'" class="callout_content" style="position: absolute; z-index: 3001; overflow: hidden; opacity: 1; cursor: default; pointer-events: none; background-color: '+args_callout[id].content_bg_color+'; background-image: none; border-style: solid; border-color: '+args_callout[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_'+id+'" class="callout_title" style="margin-top: 5px;font-size: '+args_callout[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[id].title_bg_color+';line-height: '+args_callout[id].title_font_size+'px;">\n' +
                    '                            <div class="callout_title_text" style="margin: '+title_margin+';color:'+args_callout[id].title_font_color+';text-align:right">'+args_callout[id].title+'<span style="width:0;height:0;"></span></div>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '                <div id="callout_description_'+id+'" class="callout_description" style="font-size: '+args_callout[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[id].description_font_color+';text-align:right">'+args_callout[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_'+id+'" class="callout" style="position: absolute; z-index: 3001; overflow: visible; background-color: '+args_callout[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 data-id="'+id+'" id="callout_pointer_'+id+'" class="callout_pointer callout_blink" style="position: absolute; z-index: 3001; overflow: visible; opacity: 0; cursor: default; pointer-events: none; background-image: none; border: 2px solid '+args_callout[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_'+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[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_'+id+'" class="callout_content" style="position: absolute; z-index: 3001; overflow: hidden; opacity: 1; cursor: default; pointer-events: none; background-color: '+args_callout[id].content_bg_color+'; background-image: none; border-style: solid; border-color: '+args_callout[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_'+id+'" class="callout_title" style="margin-top: 5px;font-size: '+args_callout[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[id].title_bg_color+';line-height: '+args_callout[id].title_font_size+'px;">\n' +
                    '                            <div class="callout_title_text" style="margin: '+title_margin+';color:'+args_callout[id].title_font_color+';">'+args_callout[id].title+'<span style="width:0;height:0;"></span></div>\n' +
                    '                        </div>\n' +
                    '                    </div>\n' +
                    '                </div>\n' +
                    '                <div id="callout_description_'+id+'" class="callout_description" style="font-size: '+args_callout[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[id].description_font_color+';">'+args_callout[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;
        switch(args_callout[id].open) {
            case 'hover':
                hotSpotDiv.addEventListener("mouseover", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('#callout_'+id).css('pointer-events','none');
                            open_callout(id);
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('#callout_'+id).css('pointer-events','none');
                            open_callout(id);
                        }
                    }
                });
                break;
            case 'always_open':
                if(controls_status['icons_content']==true) {
                    if(id !== null) {
                        $('#callout_'+id).css('pointer-events','none');
                        setTimeout(function() {
                            open_callout(id);
                        },50);
                    }
                }
                break;
        }
        if(window.learning_mode>0) {
            var div = document.createElement('div');
            var i = document.createElement('i');
            div.id = 'learning_check_'+args.id;
            div.classList.add('learning_check');
            div.classList.add('learning_check_callout');
            i.classList = window.learning_check_icon;
            if(learning_poi_visited.includes(args.id)) {
                div.classList.add('visited');
            }
            div.appendChild(i);
            hotSpotDiv.appendChild(div);
            if(window.learning_poi_progressive) {
                if(check_learning_poi_progressive_disabled(args.id,args.id_room)) {
                    if(args.type!=null && args.type!='' && args.type!='grouped' && parseInt(args.learning)==1) hotSpotDiv.classList.add('disabled_l');
                }
            }
        }
    }

    function toggle_callout(hotSpotDiv,id) {
        var callout = document.getElementById('callout_'+id);
        switch($('#callout_'+id).parent().attr('data-open')) {
            case 'click':
                if(callout.classList.contains('callout_open')) {
                    close_callout(id);
                } else {
                    open_callout(id);
                }
                break;
        }
    }

    function open_callout(id) {
        if(leave_poi_open==0) close_all_pois();
        var callout = document.getElementById('callout_'+id);
        if(callout!==null && callout!==undefined) {
            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);
            if(!callout.classList.contains('callout_open')) {
                set_poi_statistics('',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;
            }
            if(window.learning_mode>0) {
                unlock_poi_learning(id,current_id_panorama);
                calculate_learning_score(0);
                calculate_learning_score(current_id_panorama);
                save_learning_log(0);
            }
        }
    }

    function close_callout(id) {
        var callout = document.getElementById('callout_'+id);
        if(callout!==null && callout!==undefined) {
            callout.style.pointerEvents = 'initial';
            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)';
        }
    }

    function position_tooltip(id,e) {
        var hs_width = $('.tooltip_poi_'+id).outerWidth();
        var hs_height = $('.tooltip_poi_'+id).outerHeight();
        var x = (e.x - $('#vt_container').offset().left) - (hs_width/2);
        var y = (e.y - $('#vt_container').offset().top) - (hs_height)-30;
        if(y<0) y=0;
        if(x<0) x=0;
        if((x+hs_width)>window.c_width) x=window.c_width-hs_width;
        $('.tooltip_poi_'+id).css({'left':x+'px','top':y+'px'});
    }

    function hotspot_content(hotSpotDiv, args) {
        if(args.type=='form' && window.export_mode==1) {
            return;
        }
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('hotspot_t');
        hotSpotDiv.classList.add('hotspot_'+args.id);
        if(parseInt(args.is_grouped)==1) {
            hotSpotDiv.classList.add('hidden_grouped');
            hotSpotDiv.classList.add('grouped_poi');
        }
        if(virtual_staging) {
            hotSpotDiv.style.zIndex = parseInt(args.zIndex)+10;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.zIndex = args.zIndex;
        }
        if(args.css_class!='') {
            var array_css_class = args.css_class.split(" ");
            jQuery.each(array_css_class, function(index_c, css_class) {
                hotSpotDiv.classList.add(css_class);
            });
        }
        if((args.type=='' || args.type==null) && args.sound=='') {
            hotSpotDiv.classList.add('poi_not_selectable');
        }
        hotSpotDiv.setAttribute('data-id', args.id);
        hotSpotDiv.classList.add('hs_p'+args.id);
        hotSpotDiv.setAttribute('data-sticky', parseInt(args.sticky));
        if(args.title==null) args.title = '';
        if(args.description==null) args.description = '';
        if((args.title!='') && (args.description!='')) {
            var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
        } else if((args.title!='') && (args.description=='')) {
            var caption = '<b>'+args.title+'</b>';
        } else if((args.title=='') && (args.description!='')) {
            var caption = '<i>'+args.description+'</i>';
        } else {
            var caption = '';
        }
        if(args.view_type==2) {
            hotSpotDiv.addEventListener("mouseenter", function (e) {
                if(controls_status['icons_content']==true && !window.is_mobile) {
                    var id = e.target.getAttribute('data-id');
                    if(id !== null) {
                        if(leave_poi_open==0) close_all_pois();
                        view_poi_box(id,true);
                    }
                }
            });
        } else {
            switch(args.tooltip_type) {
                case 'text':
                    if(window.is_mobile && (args.tooltip_text_mobile !== null && args.tooltip_text_mobile !== '' && args.tooltip_text_mobile !== '<p><br></p>')) {
                        args.tooltip_text = args.tooltip_text_mobile;
                    }
                    if(args.tooltip_text !== null && args.tooltip_text !== '' && args.tooltip_text !== '<p><br></p>') {
                        var tooltip = document.createElement('div');
                        tooltip.classList.add('tooltip_poi_'+args.id);
                        tooltip.classList.add('tooltip_text');
                        tooltip.classList.add('tooltip_poi');
                        tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                        tooltip.innerHTML = args.tooltip_text;
                        hotSpotDiv.parentNode.appendChild(tooltip);
                    }
                    break;
            }
        }
        try {
            if(controls_status['icons_content']==false) tooltip.classList.add('hidden_icons');
        } catch (e) {}
        switch(args.tooltip_visibility) {
            case 'hover':
                hotSpotDiv.addEventListener("mouseover", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'hotspot_t');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip(id,e);
                                $('.tooltip_poi_'+id).css('opacity',1);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            position_tooltip(id,e);
                            $('.tooltip_poi_'+id).css('opacity',1);
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('.tooltip_poi_'+id).css('opacity',0);
                        }
                    }
                });
                hotSpotDiv.addEventListener("mousemove", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'hotspot_t');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip(id,e);
                            }
                        }
                    }
                });
                break;
            case 'visible':
                $('.tooltip_poi_'+args.id).css('opacity',1);
                break;
            case 'visible_mobile':
                if(window.is_mobile) {
                    $('.tooltip_poi_'+args.id).css('opacity',1);
                } else {
                    hotSpotDiv.addEventListener("mouseover", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'hotspot_t');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_tooltip(id,e);
                                    $('.tooltip_poi_'+id).css('opacity',1);
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseenter", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip(id,e);
                                $('.tooltip_poi_'+id).css('opacity',1);
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseleave", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                $('.tooltip_poi_'+id).css('opacity',0);
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mousemove", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'hotspot_t');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_tooltip(id,e);
                                }
                            }
                        }
                    });
                }
                break;
        }
        if(args.type=='audio') {
            if(args.params=='minimal') {
                if(parseInt(args.style)==1 || parseInt(args.style)==4) {
                    args.style = 0;
                }
                args.icon = "fas fa-play";
            }
            var html_audio_poi = '<audio playsinline webkit-playsinline preload="auto" controls controlsList="nodownload">\n' +
                '<source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="audio/mpeg">\n' +
                'Your browser does not support the audio element.\n' +
                '</audio>';
            var audio_poi_player = document.createElement('div');
            audio_poi_player.setAttribute('data-id',args.id);
            audio_poi_player.setAttribute('data-playing',0);
            audio_poi_player.classList.add("audio_poi_"+args.id);
            audio_poi_player.classList.add('audio_poi');
            audio_poi_player.innerHTML = html_audio_poi;
            hotSpotDiv.parentNode.appendChild(audio_poi_player);
        }
        var style_t = parseInt(args.style);
        var view_type = parseInt(args.view_type);
        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');
        }
        if(style_t==1) args.icon_type='round';
        switch(args.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;
        switch (style_t) {
            case 0:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var i = document.createElement('i');
                i.className = args.icon;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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;
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        a.id = "link_"+args.id;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.id = "video_"+args.id;
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+args.id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+args.id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    default:
                        div_wrapper.appendChild(i);
                        break;
                }
                break;
            case 1:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_image');
                }
                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>';
                    switch (args.type) {
                        case 'download':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                    a.target = '_blank';
                                    a.download = '';
                                } else {
                                    a.removeAttribute('href');
                                    a.removeAttribute('download');
                                }
                            }, false);
                            a.appendChild(div);
                            hotSpotDiv.appendChild(a);
                            break;
                        case 'link':
                        case 'pdf':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.title = args.title;
                            a.id = "link_"+args.id;
                            if(view_type==0) {
                                a.addEventListener('mousedown', function(e) {
                                    start_drag = new Date().getTime();
                                    drag_p = false;
                                }, false);
                                a.addEventListener('mousemove', function(e) {
                                    end_drag = new Date().getTime();
                                    drag_p = true;
                                }, false);
                                a.addEventListener('mouseup', function(e) {
                                    var diff_drag = end_drag - start_drag;
                                    if(drag_p == false || diff_drag < 200) {
                                        if(args.content.includes('.pdf')) {
                                            if (args.content.startsWith('http')) {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                            } else {
                                                if(export_mode==1) {
                                                    a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                                } else {
                                                    a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                                }
                                            }
                                        } else {
                                            a.href = args.content;
                                        }
                                        a.setAttribute('data-fancybox','');
                                        a.setAttribute('data-caption',caption);
                                        a.setAttribute('data-type','iframe');
                                        a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                    } else {
                                        a.href = '#';
                                        a.removeAttribute('data-fancybox');
                                        a.removeAttribute('data-caption');
                                        a.removeAttribute('data-type');
                                        a.removeAttribute('data-options');
                                    }
                                }, false);
                                a.addEventListener('simulate_click', function (e) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                    a.click();
                                }, false);
                            }
                            a.appendChild(div);
                            hotSpotDiv.appendChild(a);
                            break;
                        case 'link_ext':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = args.content;
                                    a.target = args.target;
                                } else {
                                    a.removeAttribute('href');
                                    a.removeAttribute('target');
                                }
                            }, false);
                            a.appendChild(div);
                            hotSpotDiv.appendChild(a);
                            break;
                        case 'video':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.title = args.title;
                            if(view_type==0) {
                                a.id = "video_" + args.id;
                                a.addEventListener('mousedown', function(e) {
                                    start_drag = new Date().getTime();
                                    drag_p = false;
                                }, false);
                                a.addEventListener('mousemove', function(e) {
                                    end_drag = new Date().getTime();
                                    drag_p = true;
                                }, false);
                                a.addEventListener('mouseup', function(e) {
                                    var diff_drag = end_drag - start_drag;
                                    if(drag_p == false || diff_drag < 200) {
                                        a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                        a.onclick = function() {
                                            open_video("video_"+args.id);
                                        };
                                        a.setAttribute('data-fancybox', '');
                                        a.setAttribute('data-caption', caption);
                                    } else {
                                        a.href = '#';
                                        a.onclick = function() {};
                                        a.removeAttribute('data-fancybox');
                                        a.removeAttribute('data-caption');
                                        e.preventDefault();
                                        e.stopImmediatePropagation();
                                    }
                                }, false);
                                a.addEventListener('simulate_click', function (e) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+args.id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                    a.click();
                                }, false);
                            }
                            a.appendChild(div);
                            hotSpotDiv.appendChild(a);
                            break;
                        default:
                            hotSpotDiv.appendChild(div);
                            break;
                    }
                    bodymovin.loadAnimation({
                        container: document.getElementById('lottie_p_'+args.id),
                        renderer: 'svg',
                        loop: true,
                        autoplay: true,
                        path: ((window.s3_enabled) ? window.s3_url : '')+'icons/'+args.img_icon_library+((window.s3_enabled) ? '?s3='+s3_version : ''),
                        rendererSettings: {
                            progressiveLoad: true,
                        }
                    });
                } else {
                    var img = document.createElement('img');
                    if(array_base64[args.img_icon_library]!==undefined) {
                        if(isSVG(args.img_icon_library)) {
                            img.src = ((window.s3_enabled) ? window.s3_url : '')+'icons/'+args.img_icon_library+((window.s3_enabled) ? '?s3='+s3_version : '');
                        } else {
                            img.src = array_base64[args.img_icon_library];
                        }
                    } else {
                        img.src = ((window.s3_enabled) ? window.s3_url : '')+'icons/'+args.img_icon_library+((window.s3_enabled) ? '?s3='+s3_version : '');
                    }
                    img.style = "width:100px;margin: 0 auto;vertical-align:middle;opacity:1;";
                    switch (args.type) {
                        case 'download':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                    a.target = '_blank';
                                    a.download = '';
                                } else {
                                    a.removeAttribute('href');
                                    a.removeAttribute('download');
                                }
                            }, false);
                            a.appendChild(img);
                            div_wrapper.appendChild(a);
                            break;
                        case 'link':
                        case 'pdf':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.title = args.title;
                            a.id = "link_"+args.id;
                            if(view_type==0) {
                                a.addEventListener('mousedown', function(e) {
                                    start_drag = new Date().getTime();
                                    drag_p = false;
                                }, false);
                                a.addEventListener('mousemove', function(e) {
                                    end_drag = new Date().getTime();
                                    drag_p = true;
                                }, false);
                                a.addEventListener('mouseup', function(e) {
                                    var diff_drag = end_drag - start_drag;
                                    if(drag_p == false || diff_drag < 200) {
                                        if(args.content.includes('.pdf')) {
                                            if (args.content.startsWith('http')) {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                            } else {
                                                if(export_mode==1) {
                                                    a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                                } else {
                                                    a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                                }
                                            }
                                        } else {
                                            a.href = args.content;
                                        }
                                        a.setAttribute('data-fancybox','');
                                        a.setAttribute('data-caption',caption);
                                        a.setAttribute('data-type','iframe');
                                        a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                    } else {
                                        a.href = '#';
                                        a.removeAttribute('data-fancybox');
                                        a.removeAttribute('data-caption');
                                        a.removeAttribute('data-type');
                                        a.removeAttribute('data-options');
                                    }
                                }, false);
                                a.addEventListener('simulate_click', function (e) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                    a.click();
                                }, false);
                            }
                            a.appendChild(img);
                            div_wrapper.appendChild(a);
                            break;
                        case 'link_ext':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = args.content;
                                    a.target = args.target;
                                } else {
                                    a.removeAttribute('href');
                                    a.removeAttribute('target');
                                }
                            }, false);
                            a.appendChild(img);
                            div_wrapper.appendChild(a);
                            break;
                        case 'video':
                            var a = document.createElement('a');
                            a.style = 'text-decoration:none;';
                            a.title = args.title;
                            if(view_type==0) {
                                a.id = "video_" + args.id;
                                a.addEventListener('mousedown', function(e) {
                                    start_drag = new Date().getTime();
                                    drag_p = false;
                                }, false);
                                a.addEventListener('mousemove', function(e) {
                                    end_drag = new Date().getTime();
                                    drag_p = true;
                                }, false);
                                a.addEventListener('mouseup', function(e) {
                                    var diff_drag = end_drag - start_drag;
                                    if(drag_p == false || diff_drag < 200) {
                                        a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                        a.onclick = function() {
                                            open_video("video_"+args.id);
                                        };
                                        a.setAttribute('data-fancybox', '');
                                        a.setAttribute('data-caption', caption);
                                    } else {
                                        a.href = '#';
                                        a.onclick = function() {};
                                        a.removeAttribute('data-fancybox');
                                        a.removeAttribute('data-caption');
                                        e.preventDefault();
                                        e.stopImmediatePropagation();
                                    }
                                }, false);
                                a.addEventListener('simulate_click', function (e) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+args.id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                    a.click();
                                }, false);
                            }
                            a.appendChild(img);
                            div_wrapper.appendChild(a);
                            break;
                        default:
                            div_wrapper.appendChild(img);
                            break;
                    }
                }
                break;
            case 2:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var i = document.createElement('i');
                i.className = args.icon;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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;
                }
                var span = document.createElement('span');
                if(args.label != '') {
                    span.innerHTML = '&nbsp;'+args.label;
                }
                span.style = "vertical-align:middle;color:"+args.color;
                if(args.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;
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(i);
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        a.id = "link_"+args.id;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(i);
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(i);
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.id = "video_" + args.id;
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+args.id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+args.id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(i);
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    default:
                        div_wrapper.appendChild(i);
                        div_wrapper.appendChild(span);
                        break;
                }
                break;
            case 3:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var span = document.createElement('span');
                if(args.label != '') {
                    span.innerHTML = args.label+'&nbsp;';
                }
                span.style = "vertical-align:middle;color:"+args.color;
                if(args.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;
                }
                var i = document.createElement('i');
                i.className = args.icon;
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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;
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(span);
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+args.id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(span);
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(span);
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+args.id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+args.id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+args.id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(span);
                        a.appendChild(i);
                        div_wrapper.appendChild(a);
                        break;
                    default:
                        div_wrapper.appendChild(span);
                        div_wrapper.appendChild(i);
                        break;
                }
                break;
            case 4:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var span = document.createElement('span');
                if(args.label != '') {
                    span.innerHTML = args.label;
                }
                span.style = "font-size:32px;vertical-align:middle;color:"+args.color;
                if(args.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;
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+args.id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+args.id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+args.id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+args.id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(span);
                        div_wrapper.appendChild(a);
                        break;
                    default:
                        div_wrapper.appendChild(span);
                        break;
                }
                break;
        }
        if(lottie==false) hotSpotDiv.appendChild(div_wrapper);
        if(window.learning_mode>0) {
            var div = document.createElement('div');
            var i = document.createElement('i');
            div.id = 'learning_check_'+args.id;
            div.classList.add('learning_check');
            if(style_t==1) {
                div.classList.add('learning_check_image');
            }
            i.classList = window.learning_check_icon;
            if(learning_poi_visited.includes(args.id)) {
                div.classList.add('visited');
            }
            div.appendChild(i);
            hotSpotDiv.appendChild(div);
            if(window.learning_poi_progressive) {
                if(check_learning_poi_progressive_disabled(args.id,args.id_room)) {
                    if(args.type!=null && args.type!='' && args.type!='grouped' && parseInt(args.learning)==1) hotSpotDiv.classList.add('disabled_l');
                }
            }
        }
        embed_pois_contents(hotSpotDiv,view_type,args,caption,false);
    }

    var box_pois = [];
    window.enter_box_poi_fullscreen = function (id) {
        $('#box_poi_fullscreen_div').show();
        var video_current_time = 0;
        if ($('.box_poi_'+id+' video').length == 1) {
            var video = $('.box_poi_'+id+' video')[0];
            video_current_time = video.currentTime;
            video.currentTime = 0;
            video.pause();
        }
        embed_pois_contents(box_pois[id].hotSpotDiv,1,box_pois[id].args,box_pois[id].caption,true);
        $('.box_poi_'+id).show();
        $('.box_poi_'+id).css({'opacity':1,'pointer-events':'initial'});
        if ($('#box_poi_fullscreen_div .box_poi_'+id+' video').length == 1) {
            setTimeout(function() {
                var video = $('#box_poi_fullscreen_div .box_poi_'+id+' video')[0];
                video.currentTime = video_current_time;
                video.play();
            },500);
        }
    }

    window.exit_box_poi_fullscreen = function (id) {
        var video_current_time = 0;
        if ($('#box_poi_fullscreen_div .box_poi_'+id+' video').length == 1) {
            var video = $('#box_poi_fullscreen_div .box_poi_'+id+' video')[0];
            video_current_time = video.currentTime;
            video.currentTime = 0;
            video.pause();
        }
        $('#box_poi_fullscreen_div').hide();
        $('#box_poi_fullscreen_div').empty();
        if ($('.box_poi_'+id+' video').length == 1) {
            var video = $('.box_poi_'+id+' video')[0];
            video.currentTime = video_current_time;
            video.play();
        }
    }

    function embed_pois_contents(hotSpotDiv,view_type,args,caption,fullscreen) {
        switch (view_type) {
            case 1:
            case 2:
                var tmp = {};
                tmp['hotSpotDiv']=hotSpotDiv;
                tmp['args']=args;
                tmp['caption']=caption;
                box_pois[args.id]=tmp;
                var div = document.createElement('div');
                div.classList.add('box_poi');
                div.classList.add("box_poi_"+args.id);
                if(fullscreen) {
                    div.classList.add('box_poi_fullscreen');
                }
                div.style.maxWidth = args.box_max_width+'px';
                div.style.backgroundColor = args.box_background;
                div.style.color = args.box_color;
                var box_rgb_color = hexToRgb(args.box_color);
                div.setAttribute('data-id',args.id);
                div.setAttribute('data-box-pos',args.box_pos);
                div.setAttribute('data-scale',args.size_scale);
                var div_html = '<div style="border-bottom: 10px solid transparent;" class="box-arrow-border"><div style="border-bottom: 10px solid '+args.box_background+';" class="box-arrow-background"></div></div>';
                if(parseInt(args.box_maximize)==1) {
                    if(fullscreen) {
                        div_html += '<i onclick="exit_box_poi_fullscreen('+args.id+');" class="box_poi_full_btn fas fa-compress"></i>';
                    } else {
                        div_html += '<i onclick="enter_box_poi_fullscreen('+args.id+');" class="box_poi_full_btn fas fa-expand"></i>';
                    }
                } else {
                    div.style.padding = '10px';
                }
                if(fullscreen && (args.type=='image' || args.type=='link' || args.type=='pdf' || args.type=='video' || args.type=='video360' || args.type=='object360' || args.type=='object3d' || args.type=='lottie')) {
                    div_html += '<div class="box-content">';
                } else {
                    if(args.type=='pdf') {
                        div_html += '<div class="box-content">';
                    } else {
                        div_html += '<div data-simplebar class="box-content">';
                    }
                }
                var h_fix = 0;
                if(caption!='' && caption !== undefined && caption != null) {
                    div_html += '<p class="box-caption">'+caption+'</p><hr style="background-image: linear-gradient(to right, rgba('+box_rgb_color+',0.1), rgba('+box_rgb_color+',0.5), rgba('+box_rgb_color+',0.1));" class="box-hr">';
                    if(caption.includes('<br>')) {
                        h_fix = 60;
                    } else {
                        h_fix = 40;
                    }
                }
                switch (args.type) {
                    case 'image':
                        if(fullscreen) {
                            div_html += '<img style="width:100%;height:calc(100% - '+h_fix+'px);object-fit:contain;" src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" />';
                        } else {
                            div_html += '<img style="width:100%;" src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" />';
                        }
                        break;
                    case 'gallery':
                        div_html += '<div id="poi_gallery_container_'+args.id+'" class="poi_gallery_container"></div>';
                        break;
                    case 'link':
                    case 'pdf':
                        if(args.content.includes('.pdf')) {
                            if (args.content.startsWith('http')) {
                                var url_content = 'vendor/pdf_viewer/index.php?file='+args.content;
                            } else {
                                var url_content = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                            }
                        } else {
                            var url_content = args.content;
                        }
                        if(fullscreen) {
                            div_html += '<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" style="border:none;padding:0;margin:0;width:100%;height:100%;" src="'+url_content+'"></iframe>';
                        } else {
                            div_html += '<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" style="border:none;padding:0;margin:0;width:100%;height:300px;" src="'+url_content+'"></iframe>';
                        }
                        break;
                    case 'video':
                        if(args.content!='' && args.content!==undefined && args.content!=null) {
                            if (args.content.includes("youtu")) {
                                var id_y = getYoutubeId(args.content);
                                if (id_y != null) {
                                    if (fullscreen) {
                                        div_html += '<iframe style="width:100%;height:100%;" class="youtube_video" width="100%" src="//www.youtube.com/embed/' + id_y + '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
                                    } else {
                                        div_html += '<iframe class="youtube_video" width="100%" height="200px" src="//www.youtube.com/embed/' + id_y + '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
                                    }
                                }
                            } else if (args.content.includes("vimeo")) {
                                var id_v = getVimeoId(args.content);
                                if (id_v != null) {
                                    if (fullscreen) {
                                        div_html += '<iframe style="width:100%;height:100%;" class="vimeo_video" width="100%" height="200px" src="https://player.vimeo.com/video/' + id_v + '" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
                                    } else {
                                        div_html += '<iframe class="vimeo_video" width="100%" height="200px" src="https://player.vimeo.com/video/' + id_v + '" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
                                    }
                                }
                            } else if(args.content.startsWith('http')) {
                                if (fullscreen) {
                                    div_html += '<iframe style="width:100%;height:100%;" width="100%" height="200px" src="' + args.content + '" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
                                } else {
                                    div_html += '<iframe width="100%" height="200px" src="' + args.content + '" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
                                }
                            } else {
                                if (fullscreen) {
                                    div_html += '<video style="width:100%;height:calc(100% - ' + h_fix + 'px);object-fit:contain;" loop webkit-playsinline playsinline controls width="100%"><source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="video/mp4"></video>';
                                } else {
                                    div_html += '<video style="width:100%;" loop webkit-playsinline playsinline controls width="100%"><source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="video/mp4"></video>';
                                }
                            }
                        }
                        break;
                    case 'html':
                    case 'html_sc':
                        div_html += '<div style="border:none;padding:0;margin:0;width:100%;color:'+args.box_color+';">'+args.content+'</div>';
                        break;
                    case 'form':
                        try {
                            var content = JSON.parse(args.content);
                            var response = content[0].response;
                            var background = content[0].background;
                            if(background==null) background = 'rgba(255,255,255,1.0)';
                            var color = content[0].color;
                            if(color==null) color = '#000000';
                            var html_content = parse_form_content(content,args.id_room,args.id);
                            div_html += '<div style="border:none;padding:0;margin:0;width:100%;background:'+background+';color:'+color+';">'+html_content+'</div>';
                        } catch (e) {}
                        break;
                    case 'google_maps':
                        var gm_map = args.content.split('|')[0];
                        var gm_street = args.content.split('|')[1];
                        if (gm_map.startsWith('http')) {
                            gm_map = '<iframe src="'+gm_map+'" frameborder="0" width="100%" height="100%"></iframe>';
                        }
                        if (gm_street.startsWith('http')) {
                            gm_street = '<iframe src="'+gm_street+'" frameborder="0" width="100%" height="100%"></iframe>';
                        }
                        if(fullscreen) {
                            div_html += '<div style="height: calc(100% - '+h_fix+'px);" class="poi_google_maps_content_poi_box">'+gm_map+' '+gm_street+'</div>';
                        } else {
                            div_html += '<div class="poi_google_maps_content_poi_box">'+gm_map+' '+gm_street+'</div>';
                        }
                        break;
                    case 'video360':
                        if(fullscreen) {
                            div_html += '<video style="width:100%;height:calc(100% - '+h_fix+'px);" crossorigin="anonymous" controls playsinline webkit-playsinline class="video-js vjs-default-skin vjs-big-play-centered vjs-fluid" id="video360_f_'+args.id+'">' +
                                '<source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="video/mp4">' +
                                '</video>';
                        } else {
                            div_html += '<div style="width:100%;">' +
                                '<video style="width:100%;height:auto" crossorigin="anonymous" controls playsinline webkit-playsinline class="video-js vjs-default-skin vjs-big-play-centered vjs-fluid" id="video360_'+args.id+'">' +
                                '<source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="video/mp4">' +
                                '</video>' +
                                '</div>';
                        }
                        break;
                    case 'object360':
                        if(fullscreen) {
                            div_html += '<div style="width:100%;height:calc(100% - '+h_fix+'px);object-fit:contain;" class="poi_object360_content"><div' +
                                '   class="cloudimage-360"' +
                                '   data-folder="'+((window.s3_enabled) ? window.s3_url : '')+'objects360/"' +
                                '   data-filename="'+args.content.name_images+'?v='+time_version+'"' +
                                '   data-amount="'+args.content.count_images+'"' +
                                '   data-bottom-circle data-hide-360-logo data-spin-reverse data-autoplay data-autoplay-reverse data-play-once' +
                                '></div>';
                        } else {
                            div_html += '<div style="width:100%;" class="poi_object360_content"><div' +
                                '   class="cloudimage-360"' +
                                '   data-folder="'+((window.s3_enabled) ? window.s3_url : '')+'objects360/"' +
                                '   data-filename="'+args.content.name_images+'?v='+time_version+'"' +
                                '   data-amount="'+args.content.count_images+'"' +
                                '   data-bottom-circle data-hide-360-logo data-spin-reverse data-autoplay data-autoplay-reverse data-play-once' +
                                '></div>';
                        }
                        break;
                    case 'object3d':
                        var array_files = args.content.split(",");
                        var glb_file = '', usdz_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(file_s.split('.').pop().toLowerCase()=='usdz') {
                                usdz_file = file_s;
                            }
                        });
                        if(fullscreen) {
                            var h_3d = 'width:100%;height:calc(100% -'+h_fix+'px);';
                        } else {
                            var h_3d = 'height:250px';
                        }
                        if(args.params!='') {
                            var tmp = args.params.split(",");
                            var placement = tmp[0];
                            if(tmp[1]!==undefined) {
                                var interaction = parseInt(tmp[1]);
                            } else {
                                var interaction = 1;
                            }
                            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 animation = tmp[4];
                                if(animation=='none') {
                                    animation = '';
                                    var autoplay = '';
                                } else {
                                    var autoplay = 'autoplay';
                                }
                            } else {
                                var animation = '';
                                var autoplay = '';
                            }
                        } else {
                            var placement = '';
                            var interaction = 1;
                            var exposure = 1;
                            var environment = 'legacy';
                            var animation = '';
                            var autoplay = '';
                        }
                        switch(interaction) {
                            case 0: //disabled
                                var camera_controls = '';
                                var rotate_3d_object = '';
                                break;
                            case 1: //horizontal and vertical
                                var camera_controls = 'camera-controls';
                                var rotate_3d_object = '';
                                break;
                            case 2: //horizontal
                                var camera_controls = 'camera-controls';
                                var rotate_3d_object = 'camera-orbit="0deg 75deg" min-camera-orbit="auto 75deg auto" max-camera-orbit="auto 75deg auto"';
                                break;
                            case 3: //vertical
                                var camera_controls = 'camera-controls';
                                var rotate_3d_object = 'camera-orbit="0deg 75deg" min-camera-orbit="0deg 22.5deg auto" max-camera-orbit="0deg 157.5deg auto"';
                                break;
                        }
                        switch(placement) {
                            case 'floor':
                            case 'wall':
                                if(usdz_file!='') {
                                    div_html += '<div style="'+h_3d+'" class="poi_object3d_content"><model-viewer disable-tap disable-pan disable-zoom '+rotate_3d_object+' exposure="'+exposure+'" '+autoplay+' animation-name="'+animation+'" src="'+((window.s3_enabled) ? window.s3_url : '')+glb_file+'" ios-src="'+((window.s3_enabled) ? window.s3_url : '')+usdz_file+'" alt="" ar ar-modes="webxr scene-viewer quick-look" ar-placement="'+args.params+'" environment-image="'+environment+'" shadow-intensity="1" '+rotate_3d_object+' '+camera_controls+'>'+button_ar+'</model-viewer></div>';
                                } else {
                                    div_html += '<div style="'+h_3d+'" class="poi_object3d_content"><model-viewer disable-tap disable-pan disable-zoom '+rotate_3d_object+' exposure="'+exposure+'" '+autoplay+' animation-name="'+animation+'" src="'+((window.s3_enabled) ? window.s3_url : '')+glb_file+'" alt="" ar ar-modes="webxr scene-viewer quick-look" ar-placement="'+args.params+'" environment-image="'+environment+'" shadow-intensity="1" '+rotate_3d_object+' '+camera_controls+'>'+button_ar+'</model-viewer></div>';
                                }
                                break;
                            default:
                                div_html += '<div style="'+h_3d+'" class="poi_object3d_content"><model-viewer disable-tap disable-pan disable-zoom '+rotate_3d_object+' exposure="'+exposure+'" '+autoplay+' animation-name="'+animation+'" src="'+((window.s3_enabled) ? window.s3_url : '')+glb_file+'" alt="" environment-image="'+environment+'" shadow-intensity="1" auto-rotate '+rotate_3d_object+' '+camera_controls+'></model-viewer></div>';
                                break;
                        }
                        break;
                    case 'lottie':
                        if(fullscreen) {
                            div_html += '<div style="width:100%;height:calc(100% - '+h_fix+'px);object-fit:contain;" id="poi_lottie_'+args.id+'" class="poi_lottie_content"></div>';
                        } else {
                            div_html += '<div style="height: 250px" id="poi_lottie_'+args.id+'" class="poi_lottie_content"></div>';
                        }
                        break;
                    case 'product':
                        div_html += '<div style="border:none;padding:0;margin:0;width:100%;" id="poi_product_'+args.id+'" class="poi_product_content">'+get_product_html(args.product,args.product_images,args.id,args.box_color,args.product.button_background,args.product.button_color)+'</div>';
                        break;
                }
                div_html += '</div>';
                div.innerHTML = div_html;
                if(fullscreen) {
                    document.getElementById('box_poi_fullscreen_div').appendChild(div);
                } else {
                    hotSpotDiv.parentNode.appendChild(div);
                }
                switch(args.type) {
                    case 'google_maps':
                        if((gm_map=='') || (gm_street=='')) {
                            $('.poi_google_maps_content_poi_box iframe:nth-child(1)').addClass('poi_google_maps_full_width');
                        }
                        break;
                    case 'gallery':
                        var gallery_transition = 'swipe';
                        var gallery_thumbs = 'bottomOverMedia';
                        var gallery_autoplay = false;
                        var gallery_slide_duration = 4;
                        if(args.params!='') {
                            try {
                                var array_params = JSON.parse(args.params);
                                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_slide_duration' in array_params) {
                                    gallery_slide_duration = array_params.gallery_slide_duration;
                                }
                            } catch (e) {}
                        }
                        poi_gallery = $('#poi_gallery_container_'+args.id).nanogallery2({
                            imageTransition: gallery_transition,
                            slideshowAutoStart: (parseInt(gallery_autoplay)==1) ? true : false,
                            slideshowDelay: parseFloat(gallery_slide_duration)*1000,
                            viewerGallery: gallery_thumbs,
                            thumbnailHeight: 150,
                            thumbnailWidth: 'auto',
                            items: args.content,
                            allowHTMLinData: true,
                            viewerHideToolsDelay: 30000,
                            viewerToolbar: {
                                display: true,
                                autoMinimize: false,
                                standard: 'label'
                            },
                            viewerTools: {
                                topLeft: 'pageCounter, playPauseButton',
                                topRight: 'zoomButton, closeButton'
                            }
                        });
                        break;
                    case 'video360':
                        if(fullscreen) {
                            try {
                                video360_f_poi.dispose();
                            } catch (e) {}
                            video360_f_poi = videojs('video360_f_'+args.id,{
                                controlBar: {
                                    pictureInPictureToggle: false
                                }
                            });
                            video360_f_poi.vr({projection: '360'});
                        } else {
                            video360_poi[args.id] = videojs('video360_'+args.id,{
                                controlBar: {
                                    pictureInPictureToggle: false
                                }
                            });
                            video360_poi[args.id].vr({projection: '360'});
                        }
                        break;
                    case 'object360':
                        window.CI360.init();
                        break;
                    case 'lottie':
                        bodymovin.loadAnimation({
                            container: document.getElementById('poi_lottie_'+args.id),
                            renderer: 'svg',
                            loop: true,
                            autoplay: true,
                            path: args.content+((window.s3_enabled) ? '?s3='+s3_version : ''),
                            rendererSettings: {
                                progressiveLoad: true,
                            }
                        });
                        break;
                    case 'product':
                        $("#product_"+args.id+" .carousel").swipe({
                            swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
                                if (direction == 'left') $(this).carousel('next');
                                if (direction == 'right') $(this).carousel('prev');
                            },
                            allowPageScroll: "vertical"
                        });
                        break;
                }
                break;
        }
    }

    function initialize_panorama_preview_marker(id,image,min_yaw,max_yaw,haov,vaov,hfov) {
        if(hfov==0) { hfov=55; } else { hfov=hfov*0.5; }
        try {
            panorama_preview_marker.destroy();
        } catch (e) {}
        if(image===undefined) return;
        panorama_preview_marker = pannellum.viewer('panorama_preview_marker_'+id, {
            "type": "equirectangular",
            "autoLoad": true,
            "avoidShowingBackground": true,
            "autoRotate": -20,
            "showControls": false,
            "compass": false,
            "minYaw": parseInt(min_yaw),
            "maxYaw": parseInt(max_yaw),
            "haov": parseInt(haov),
            "vaov": parseInt(vaov),
            "hfov": parseInt(hfov),
            "panorama": ((window.s3_enabled) ? window.s3_url : '')+"panoramas/lowres/"+image+((window.s3_enabled) ? '?s3='+s3_version : '')
        });
        panorama_preview_marker.on('load',function () {
            setTimeout(function () {
                $('#panorama_preview_marker_'+id).css('opacity',1);
            },50);
        });
        $('.panorama_preview_marker').css('opacity',0);
    }

    function initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov) {
        if(hfov==0) { hfov=55; } else { hfov=hfov*0.5; }
        try {
            panorama_preview_tooltip.destroy();
        } catch (e) {}
        if(image===undefined) return;
        panorama_preview_tooltip = pannellum.viewer('panorama_preview_tooltip_'+id, {
            "type": "equirectangular",
            "autoLoad": true,
            "avoidShowingBackground": true,
            "autoRotate": -20,
            "showControls": false,
            "compass": false,
            "minYaw": parseInt(min_yaw),
            "maxYaw": parseInt(max_yaw),
            "haov": parseInt(haov),
            "vaov": parseInt(vaov),
            "hfov": parseInt(hfov),
            "panorama": ((window.s3_enabled) ? window.s3_url : '')+"panoramas/lowres/"+image+((window.s3_enabled) ? '?s3='+s3_version : '')
        });
        panorama_preview_tooltip.on('load',function () {
            setTimeout(function () {
                $('#panorama_preview_tooltip_'+id).css('opacity',1);
            },50);
        });
        $('.panorama_preview_tooltip').css('opacity',0);
        $('.panorama_preview_tooltip_square').css('opacity', 0);
        $('.panorama_preview_tooltip_rect').css('opacity', 0);
        $('.panorama_preview_tooltip_m').css('opacity',0);
        $('.panorama_preview_tooltip_square_m').css('opacity', 0);
        $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
    }

    function position_tooltip_m(id,e) {
        var hs_width = $('.tooltip_marker_'+id).outerWidth();
        var hs_height = $('.tooltip_marker_'+id).outerHeight();
        var x = (e.x - $('#vt_container').offset().left) - (hs_width/2);
        var y = (e.y - $('#vt_container').offset().top) - (hs_height)-30;
        if(y<0) y=0;
        if(x<0) x=0;
        if((x+hs_width)>window.c_width) x=window.c_width-hs_width;
        $('.tooltip_marker_'+id).css({'left':x+'px','top':y+'px'});
    }

    function learning_check_room_locked(id) {
        id = parseInt(id);
        var all_poi_visited = true;
        for (let key in learning_poi_room["r"+id]) {
            if (learning_poi_room["r"+id][key] === 0) {
                all_poi_visited = false;
                break;
            }
        }
        return !all_poi_visited;
    }

    function learning_check_marker_locked(id) {
        id = parseInt(id);
        const id_initial_room = parseInt(panoramas[index_initial].id);
        if (id_initial_room === id) {
            return false;
        }
        if(learning_room_enabled.includes(id)) {
            return false;
        } else {
            return true;
        }
    }

    function hotspot(hotSpotDiv, args) {
        if(vr_enabled) { var markers_show_room_t = 0; } else { var markers_show_room_t = parseInt(args.show_room); }
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('custom-tooltip');
        hotSpotDiv.classList.add('hotspot_t');
        hotSpotDiv.classList.add('noselect');
        if(hide_markers==1) {
            hotSpotDiv.classList.add('hidden_m');
        }
        hotSpotDiv.classList.add('marker_'+args.id);
        if(args.css_class!='') {
            var array_css_class = args.css_class.split(" ");
            jQuery.each(array_css_class, function(index_c, css_class) {
                hotSpotDiv.classList.add(css_class);
            });
        }
        hotSpotDiv.setAttribute('data-id', args.id);
        hotSpotDiv.classList.add('hs_m'+args.id);
        hotSpotDiv.setAttribute('data-sticky', parseInt(args.sticky));
        if(virtual_staging) {
            hotSpotDiv.style.zIndex = parseInt(args.zIndex)+10;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.zIndex = args.zIndex;
        }
        if(markers_show_room_t==5) {
            if(args.tooltip_type=='preview' || args.tooltip_type=='preview_square' || args.tooltip_type=='preview_rect') {
                args.tooltip_type = 'room_name';
            }
        }
        if(list_id_visited.includes(parseInt(args.id_room_target))) {
            var display_check = 'inline-block';
        } else {
            var display_check = 'none';
        }
        switch(args.tooltip_type) {
            case 'text':
                if(window.is_mobile && (args.tooltip_text_mobile !== null && args.tooltip_text_mobile !== '' && args.tooltip_text_mobile !== '<p><br></p>')) {
                    args.tooltip_text = args.tooltip_text_mobile;
                }
                if(args.tooltip_text !== null && args.tooltip_text !== '' && args.tooltip_text !== '<p><br></p>') {
                    var tooltip = document.createElement('div');
                    tooltip.classList.add('tooltip_marker_'+args.id);
                    tooltip.classList.add('tooltip_text');
                    tooltip.classList.add('tooltip_marker');
                    tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                    tooltip.innerHTML = args.tooltip_text+'<span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'">&nbsp;&nbsp;<i style="color:'+args.tooltip_color+'" class="fas fa-check"></i></span>';
                    hotSpotDiv.setAttribute('data-panorama','');
                    hotSpotDiv.parentNode.appendChild(tooltip);
                }
                break;
            case 'room_name':
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_text');
                tooltip.classList.add('tooltip_marker');
                tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                tooltip.innerHTML = args.name_room_target+'<span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'">&nbsp;&nbsp;<i style="color:'+args.tooltip_color+'" class="fas fa-check"></i></span>';
                hotSpotDiv.setAttribute('data-panorama','');
                hotSpotDiv.parentNode.appendChild(tooltip);
                break;
            case 'preview':
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_preview');
                tooltip.classList.add('tooltip_marker');
                tooltip.innerHTML = '<div style="width:100%;height:100%;border-radius:50px;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;"><div id="panorama_preview_tooltip_'+args.id+'" class="panorama_preview_tooltip"></div><span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'"><i style="color:white" class="fas fa-check"></i></span></div>';
                hotSpotDiv.setAttribute('data-panorama',panorama_image);
                hotSpotDiv.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                hotSpotDiv.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                hotSpotDiv.setAttribute('data-haov',panoramas[index].haov);
                hotSpotDiv.setAttribute('data-vaov',panoramas[index].vaov);
                hotSpotDiv.setAttribute('data-hfov',panoramas[index].hfov);
                hotSpotDiv.parentNode.appendChild(tooltip);
                break;
            case 'preview_square':
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_preview_square');
                tooltip.classList.add('tooltip_marker');
                tooltip.innerHTML = '<div style="width:100%;height:100%;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;"><div id="panorama_preview_tooltip_'+args.id+'" class="panorama_preview_tooltip_square"></div><span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'"><i style="color:white" class="fas fa-check"></i></span></div>';
                hotSpotDiv.setAttribute('data-panorama',panorama_image);
                hotSpotDiv.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                hotSpotDiv.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                hotSpotDiv.setAttribute('data-haov',panoramas[index].haov);
                hotSpotDiv.setAttribute('data-vaov',panoramas[index].vaov);
                hotSpotDiv.setAttribute('data-hfov',panoramas[index].hfov);
                hotSpotDiv.parentNode.appendChild(tooltip);
                break;
            case 'preview_rect':
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_preview_rect');
                tooltip.classList.add('tooltip_marker');
                tooltip.innerHTML = '<div style="width:100%;height:100%;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;"><div id="panorama_preview_tooltip_'+args.id+'" class="panorama_preview_tooltip_rect"></div><span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'"><i style="color:white" class="fas fa-check"></i></span></div>';
                hotSpotDiv.setAttribute('data-panorama',panorama_image);
                hotSpotDiv.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                hotSpotDiv.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                hotSpotDiv.setAttribute('data-haov',panoramas[index].haov);
                hotSpotDiv.setAttribute('data-vaov',panoramas[index].vaov);
                hotSpotDiv.setAttribute('data-hfov',panoramas[index].hfov);
                hotSpotDiv.parentNode.appendChild(tooltip);
                break;
        }
        try {
            if(controls_status['icons_nav']==false) tooltip.classList.add('hidden_icons');
        } catch (e) {}
        switch(args.tooltip_visibility) {
            case 'hover':
                hotSpotDiv.addEventListener("mouseover", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'hotspot_t');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip_m(id,e);
                                $('.tooltip_marker_'+id).css('opacity',1);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            position_tooltip_m(id,e);
                            $('.tooltip_marker_'+id).css('opacity',1);
                            var image = $(this).attr('data-panorama');
                            if(image!='') {
                                var min_yaw = $(this).attr('data-min_yaw');
                                var max_yaw = $(this).attr('data-max_yaw');
                                var haov = $(this).attr('data-haov');
                                var vaov = $(this).attr('data-vaov');
                                var hfov = $(this).attr('data-hfov');
                                clearTimeout(timeout_destroy_tooltip);
                                initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mousemove", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'hotspot_t');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip_m(id,e);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('.tooltip_marker_'+id).css('opacity',0);
                            $('.panorama_preview_tooltip').css('opacity', 0);
                            $('.panorama_preview_tooltip_square').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect').css('opacity', 0);
                            $('.panorama_preview_tooltip_m').css('opacity',0);
                            $('.panorama_preview_tooltip_square_m').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
                            timeout_destroy_tooltip = setTimeout(function () {
                                try {
                                    panorama_preview_tooltip.destroy();
                                } catch (e) {}
                            }, 300);
                        }
                    }
                });
                break;
            case 'visible':
                $('.tooltip_marker_'+args.id).css('opacity',1);
                if(parseInt(args.show_room)==5) {
                    $('.tooltip_marker_'+args.id).addClass('tooltip_text5');
                }
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            if(parseInt(args.show_room)==5) {
                                $('.tooltip_marker_'+id).css('top','-40px');
                            }
                            var image = $(this).attr('data-panorama');
                            if(image!='') {
                                var min_yaw = $(this).attr('data-min_yaw');
                                var max_yaw = $(this).attr('data-max_yaw');
                                var haov = $(this).attr('data-haov');
                                var vaov = $(this).attr('data-vaov');
                                var hfov = $(this).attr('data-hfov');
                                clearTimeout(timeout_destroy_tooltip);
                                initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mousemove", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            if(parseInt(args.show_room)==5) {
                                $('.tooltip_marker_'+id).css('top','-40px');
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(ccontrols_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('.tooltip_marker_'+id).css('top','0px');
                            $('.panorama_preview_tooltip').css('opacity', 0);
                            $('.panorama_preview_tooltip_square').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect').css('opacity', 0);
                            $('.panorama_preview_tooltip_m').css('opacity',0);
                            $('.panorama_preview_tooltip_square_m').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
                            timeout_destroy_tooltip = setTimeout(function () {
                                try {
                                    panorama_preview_tooltip.destroy();
                                } catch (e) {}
                            }, 300);
                        }
                    }
                });
                break;
            case 'visible_mobile':
                if(window.is_mobile) {
                    $('.tooltip_marker_'+args.id).css('opacity',1);
                } else {
                    hotSpotDiv.addEventListener("mouseover", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'hotspot_t');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_tooltip_m(id,e);
                                    $('.tooltip_marker_'+id).css('opacity',1);
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseenter", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                position_tooltip_m(id,e);
                                $('.tooltip_marker_'+id).css('opacity',1);
                                var image = $(this).attr('data-panorama');
                                if(image!='') {
                                    var min_yaw = $(this).attr('data-min_yaw');
                                    var max_yaw = $(this).attr('data-max_yaw');
                                    var haov = $(this).attr('data-haov');
                                    var vaov = $(this).attr('data-vaov');
                                    var hfov = $(this).attr('data-hfov');
                                    clearTimeout(timeout_destroy_tooltip);
                                    initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mousemove", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'hotspot_t');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_tooltip_m(id,e);
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseleave", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                $('.tooltip_marker_'+id).css('opacity',0);
                                $('.panorama_preview_tooltip').css('opacity', 0);
                                $('.panorama_preview_tooltip_square').css('opacity', 0);
                                $('.panorama_preview_tooltip_rect').css('opacity', 0);
                                $('.panorama_preview_tooltip_m').css('opacity',0);
                                $('.panorama_preview_tooltip_square_m').css('opacity', 0);
                                $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
                                timeout_destroy_tooltip = setTimeout(function () {
                                    try {
                                        panorama_preview_tooltip.destroy();
                                    } catch (e) {}
                                }, 300);
                            }
                        }
                    });
                }
                break;
        }
        var div_wrapper = document.createElement('div');
        div_wrapper.classList.add('div_marker_wrapper');
        if(args.animation!='none' && !vr_enabled) {
            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');
        }
        if(markers_show_room_t==4 || markers_show_room_t==5) args.icon_type='round';
        switch(args.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;
        switch (markers_show_room_t) {
            case 0:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var i = document.createElement('i');
                i.setAttribute('data-icon', args.icon);
                if(imgs_loaded.indexOf(args.id_room_target) !== -1) {
                    i.className = args.icon+" marker_img_"+args.id_room_target;
                } else {
                    i.className = "fas fa-spin fa-circle-notch marker_img_"+args.id_room_target;
                }
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var i = document.createElement('i');
                i.setAttribute('data-icon', args.icon);
                if(imgs_loaded.indexOf(args.id_room_target) !== -1) {
                    i.className = args.icon+" marker_img_"+args.id_room_target;
                } else {
                    i.className = "fas fa-spin fa-circle-notch marker_img_"+args.id_room_target;
                }
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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;
                span.style = "vertical-align:middle;color:"+args.color;
                if(args.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:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var span = document.createElement('span');
                span.innerHTML = args.name_room_target+'&nbsp;';
                span.style = "vertical-align:middle;color:"+args.color;
                if(args.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.setAttribute('data-icon', args.icon);
                if(imgs_loaded.indexOf(args.id_room_target) !== -1) {
                    i.className = args.icon+" marker_img_"+args.id_room_target;
                } else {
                    i.className = "fas fa-spin fa-circle-notch marker_img_"+args.id_room_target;
                }
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var span = document.createElement('span');
                span.innerHTML = args.name_room_target;
                span.classList.add("marker_img_"+args.id_room_target);
                span.style = "font-size:32px;vertical-align:middle;color:"+args.color;
                if(args.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:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_image');
                }
                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.classList.add("marker_img_"+args.id_room_target);
                    div.innerHTML = '<div id="lottie_m_'+args.id+'" style="height:100px;width:100px;vertical-align:middle"></div>';
                    hotSpotDiv.appendChild(div);
                    bodymovin.loadAnimation({
                        container: document.getElementById('lottie_m_'+args.id),
                        renderer: 'svg',
                        loop: true,
                        autoplay: true,
                        path: ((window.s3_enabled) ? window.s3_url : '')+'icons/'+args.img_icon_library+((window.s3_enabled) ? '?s3='+s3_version : ''),
                        rendererSettings: {
                            progressiveLoad: true,
                        }
                    });
                } else {
                    var img = document.createElement('img');
                    if(array_base64[args.img_icon_library]!==undefined) {
                        if(isSVG(args.img_icon_library)) {
                            img.src = ((window.s3_enabled) ? window.s3_url : '')+'icons/'+args.img_icon_library+((window.s3_enabled) ? '?s3='+s3_version : '');
                        } else {
                            img.src = array_base64[args.img_icon_library];
                        }
                    } else {
                        img.src = ((window.s3_enabled) ? window.s3_url : '')+'icons/'+args.img_icon_library+((window.s3_enabled) ? '?s3='+s3_version : '');
                    }
                    img.classList.add("marker_img_"+args.id_room_target);
                    img.style = "width:100px;margin: 0 auto;;vertical-align:middle;";
                    div_wrapper.appendChild(img);
                }
                break;
            case 5:
                div_wrapper.classList.add('pulse_image');
                div_wrapper.classList.add('marker_preview');
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var div = document.createElement('div');
                div.classList.add('div_preview_rm');
                div.setAttribute('data-id',args.id);
                div.setAttribute('data-panorama',panorama_image);
                div.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                div.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                div.setAttribute('data-haov',panoramas[index].haov);
                div.setAttribute('data-vaov',panoramas[index].vaov);
                div.setAttribute('data-hfov',panoramas[index].hfov);
                div.classList.add("marker_img_"+args.id_room_target);
                div.style = 'width:240px;height:240px;border-radius:50%;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;';
                div.innerHTML = '<div id="panorama_preview_marker_'+args.id+'" class="panorama_preview_marker"></div>';
                div.addEventListener('mouseenter', function () {
                    if(!window.is_mobile) {
                        var id = $(this).attr('data-id');
                        var image = $(this).attr('data-panorama');
                        var min_yaw = $(this).attr('data-min_yaw');
                        var max_yaw = $(this).attr('data-max_yaw');
                        var haov = $(this).attr('data-haov');
                        var vaov = $(this).attr('data-vaov');
                        var hfov = $(this).attr('data-hfov');
                        if(image!='') {
                            clearTimeout(timeout_destroy_marker);
                            initialize_panorama_preview_marker(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                            div_wrapper.classList.add('no_animation');
                        }
                    }
                });
                div.addEventListener('mouseleave', function () {
                    if(!window.is_mobile) {
                        $('.panorama_preview_marker').css('opacity', 0);
                        div_wrapper.classList.remove('no_animation');
                        timeout_destroy_marker = setTimeout(function () {
                            try {
                                panorama_preview_marker.destroy();
                            } catch (e) {}
                        }, 300);
                    }
                });
                div_wrapper.appendChild(div);
                break;
            case 6:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var i = document.createElement('i');
                i.setAttribute('data-icon', args.icon);
                if(imgs_loaded.indexOf(args.id_room_target) !== -1) {
                    i.className = args.icon+" marker_img_"+args.id_room_target;
                } else {
                    i.className = "fas fa-spin fa-circle-notch marker_img_"+args.id_room_target;
                }
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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.label;
                span.style = "vertical-align:middle;color:"+args.color;
                if(args.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:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var span = document.createElement('span');
                span.innerHTML = args.label+'&nbsp;';
                span.style = "vertical-align:middle;color:"+args.color;
                if(args.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.setAttribute('data-icon', args.icon);
                if(imgs_loaded.indexOf(args.id_room_target) !== -1) {
                    i.className = args.icon+" marker_img_"+args.id_room_target;
                } else {
                    i.className = "fas fa-spin fa-circle-notch marker_img_"+args.id_room_target;
                }
                i.style = "margin: 0 auto;vertical-align:middle;font-size:48px;color:"+args.color;
                if(args.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:
                if(args.animation=='none') {
                    div_wrapper.classList.add('pulse_icon');
                }
                var span = document.createElement('span');
                span.innerHTML = args.label;
                span.classList.add("marker_img_"+args.id_room_target);
                span.style = "font-size:32px;vertical-align:middle;color:"+args.color;
                if(args.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);
        if(imgs_loaded.indexOf(args.id_room_target) == -1) {
            hotSpotDiv.classList.add('disabled');
        }
        if(window.learning_mode>0) {
            if(window.learning_unlock_marker) {
                if(learning_check_marker_locked(args.id_room_target)) {
                    hotSpotDiv.classList.add('disabled_l');
                }
            }
        }
    }

    window.goto_next_room = function () {
        var len = panoramas.length;
        var index = get_id_viewer(current_id_panorama);
        var next_panorama = panoramas[(index+1)%len];
        goto("",[next_panorama.id,null,null,null,null,null,null,null]);
    }

    window.goto_prev_room = function () {
        var len = panoramas.length;
        var index = get_id_viewer(current_id_panorama);
        var prev_panorama = panoramas[(index+len-1)%len];
        goto("",[prev_panorama.id,null,null,null,null,null,null,null]);
    }

    window.change_room_alt = function (id) {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'change_room_alt',args:id});
            } catch (e) {}
        }
        window.index_room_alt_sel = id;
        window.sync_virtual_staging_enabled=false;
        window.changed_room_alt = true;
        $('#loading_pano').show();
        $('#loading_pano').css('opacity',0.8);
        try { pano_viewer.stopAutoRotate(); } catch (e) {}
        pano_viewer.stopMovement();
        var yaw = parseFloat(pano_viewer.getYaw());
        var pitch = parseFloat(pano_viewer.getPitch());
        var hfov = parseFloat(pano_viewer.getHfov());
        var index = get_id_viewer(current_id_panorama);
        if(panoramas[index].virtual_staging==1) {
            virtual_staging = true;
        } else {
            virtual_staging = false;
        }
        if(virtual_staging) {
            if(pano_viewer_alt!=null && pano_viewer_alt!==undefined) {
                pano_viewer.setYaw(pano_viewer_alt.getYaw());
                pano_viewer.setPitch(pano_viewer_alt.getPitch());
                pano_viewer.setHfov(pano_viewer_alt.getHfov());
                var dataURL = pano_viewer_alt.getRenderer().render(pano_viewer.getPitch() / 180 * Math.PI,
                    pano_viewer.getYaw() / 180 * Math.PI,
                    pano_viewer.getHfov() / 180 * Math.PI,
                    {'returnImage': 'image/jpeg'});
            } else {
                var dataURL = pano_viewer.getRenderer().render(pano_viewer.getPitch() / 180 * Math.PI,
                    pano_viewer.getYaw() / 180 * Math.PI,
                    pano_viewer.getHfov() / 180 * Math.PI,
                    {'returnImage': 'image/jpeg'});
            }
        } else {
            var dataURL = pano_viewer.getRenderer().render(pano_viewer.getPitch() / 180 * Math.PI,
                pano_viewer.getYaw() / 180 * Math.PI,
                pano_viewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'image/jpeg'});
        }
        $('#background_pano').off('load');
        $('#background_pano').on('load',function () {
            $('#background_pano').show();
            $('#background_pano').css('z-index',11);
            setTimeout(function () {
                $('#panorama_viewer').css('opacity',0);
                $('#panorama_viewer_alt').css('opacity',0);
                $('#video_viewer').css('opacity',0);
                $('#vs_slider').fadeOut();
                $('#vs_grab').fadeOut();
                if(id==null) {
                    window.id_room_alt_sel = 0;
                    if(panoramas[index].multires) {
                        initialize_room(index,true,false,pitch,yaw,hfov,null,false);
                    } else {
                        var img = panoramas[index].panorama_image;
                        var tmp_image = new Image();
                        tmp_image.crossOrigin = 'anonymous';
                        $(tmp_image).on('load',function () {
                            initialize_room(index,true,false,pitch,yaw,hfov,null,false);
                        }).attr('src',((window.s3_enabled) ? window.s3_url : '')+img+((window.s3_enabled) ? '?s3='+s3_version : ''));
                    }
                } else {
                    window.id_room_alt_sel = panoramas[index].array_rooms_alt[id].id;
                    if(panoramas[index].array_rooms_alt[id].multires) {
                        initialize_room(index,true,false,pitch,yaw,hfov,id,false);
                    } else {
                        var img = panoramas[index].array_rooms_alt[id].panorama_image;
                        var tmp_image = new Image();
                        tmp_image.crossOrigin = 'anonymous';
                        $(tmp_image).on('load',function () {
                            initialize_room(index,true,false,pitch,yaw,hfov,id,false);
                        }).attr('src',((window.s3_enabled) ? window.s3_url : '')+img+((window.s3_enabled) ? '?s3='+s3_version : ''));
                    }
                }
            },50);
        }).attr('src',dataURL);
    }

    window.change_room_alt_poi = function (hotspotDiv,args) {
        window.sync_virtual_staging_enabled=false;
        window.changed_room_alt_poi = true;
        var id = parseInt(args.content);
        if(args.sound!='') {
            play_sound_hs(((window.s3_enabled) ? window.s3_url : '')+args.sound);
        }
        $('#loading_pano').hide();
        $('#loading_pano').css('opacity',0);
        try { pano_viewer.stopAutoRotate(); } catch (e) {}
        pano_viewer.stopMovement();
        var yaw = parseFloat(pano_viewer.getYaw());
        var pitch = parseFloat(pano_viewer.getPitch());
        var hfov = parseFloat(pano_viewer.getHfov());
        var index = get_id_viewer(current_id_panorama);
        var dataURL = pano_viewer.getRenderer().render(pano_viewer.getPitch() / 180 * Math.PI,
            pano_viewer.getYaw() / 180 * Math.PI,
            pano_viewer.getHfov() / 180 * Math.PI,
            {'returnImage': 'image/jpeg'});
        $('#background_pano').off('load');
        $('#background_pano').on('load',function () {
            $('#background_pano').show();
            $('#background_pano').css('z-index',11);
            setTimeout(function () {
                $('#panorama_viewer').css('opacity',0);
                $('#panorama_viewer_alt').css('opacity',0);
                $('#video_viewer').css('opacity',0);
                $('#vs_slider').fadeOut();
                $('#vs_grab').fadeOut();
                if(id==null || id==0) {
                    window.id_room_alt_sel = 0;
                    if(panoramas[index].multires) {
                        initialize_room(index,true,false,pitch,yaw,hfov,null,false);
                    } else {
                        var img = panoramas[index].panorama_image;
                        var tmp_image = new Image();
                        tmp_image.crossOrigin = 'anonymous';
                        $(tmp_image).on('load',function () {
                            initialize_room(index,true,false,pitch,yaw,hfov,null,false);
                        }).attr('src',((window.s3_enabled) ? window.s3_url : '')+img+((window.s3_enabled) ? '?s3='+s3_version : ''));
                    }
                } else {
                    var index_ara = null;
                    jQuery.each(panoramas[index].array_rooms_alt, function(index_alt, room_alt) {
                        if(room_alt.id==id) {
                            index_ara=index_alt;
                        }
                    });
                    if(index_ara!=null) {
                        window.id_room_alt_sel = id;
                        if(panoramas[index].array_rooms_alt[index_ara].multires) {
                            initialize_room(index,true,false,pitch,yaw,hfov,index_ara,false);
                        } else {
                            var img = panoramas[index].array_rooms_alt[index_ara].panorama_image;
                            var tmp_image = new Image();
                            tmp_image.crossOrigin = 'anonymous';
                            $(tmp_image).on('load',function () {
                                initialize_room(index,true,false,pitch,yaw,hfov,index_ara,false);
                            }).attr('src',((window.s3_enabled) ? window.s3_url : '')+img+((window.s3_enabled) ? '?s3='+s3_version : ''));
                        }
                    } else {
                        if(panoramas[index].multires) {
                            initialize_room(index,true,false,pitch,yaw,hfov,null,false);
                        } else {
                            var img = panoramas[index].panorama_image;
                            var tmp_image = new Image();
                            tmp_image.crossOrigin = 'anonymous';
                            $(tmp_image).on('load',function () {
                                initialize_room(index,true,false,pitch,yaw,hfov,null,false);
                            }).attr('src',((window.s3_enabled) ? window.s3_url : '')+img+((window.s3_enabled) ? '?s3='+s3_version : ''));
                        }
                    }
                }
            },50);
        }).attr('src',dataURL);
    }

    function fadeIn_live_p(elem,duration,fade) {
        elem.alpha = 0;
        ticker_mrv = PIXI.Ticker.shared;
        const onTick = (delta) => {
            if(mrv_initialized==1) {
                elem.alpha += delta / 0.03 / fade;
                if (elem.alpha > 1) {
                    elem.alpha = 1;
                    ticker_mrv.remove(onTick);
                    prev_current_mrv_panorama = index_current_mrv_panorama;
                    index_current_mrv_panorama++;
                    if(index_current_mrv_panorama>=mrv_count_panoramas) {
                        index_current_mrv_panorama = 0;
                    }
                    next_mrv_panorama(duration,fade);
                }
            } else {
                ticker_mrv.remove(onTick);
            }
        };
        ticker_mrv.add(onTick);
    }

    function next_mrv_panorama(duration,fade) {
        if(mrv_initialized==1) {
            mrv_next_timeout = setTimeout(function() {
                try {
                    mrv_panoramas[index_current_mrv_panorama].parent.addChild(mrv_panoramas[index_current_mrv_panorama]);
                    fadeIn_live_p(mrv_panoramas[index_current_mrv_panorama],duration,fade);
                } catch (e) {}
            },duration);
        }
    }

    function initialize_room(id,cb,click_m,pitch_m,yaw_m,hfov_m,id_room_alt,dh) {
        Pace.start();
        clearTimeout(timeout_initial_inactivity);
        setTimeout(function () {
            window.sync_poi_embed_enabled = false;
            window.sync_marker_embed_enabled = false;
            $('#draggable_container').empty();
            array_id_room_nav.push(panoramas[id].id);
            if (window.self !== window.top) {
                var count_marker = 0;
                var count_poi = 0;
                var count_measure = 0;
                $.each(panoramas[id].hotSpots,function(index,hs) {
                    switch(hs.object) {
                        case 'poi':
                        case 'poi_embed':
                            count_poi++;
                            break;
                        case 'marker':
                        case 'marker_embed':
                            count_marker++;
                            break;
                        case 'measure':
                            count_measure++;
                            break;
                    }
                });
                if(count_measure>0) count_measure=count_measure/2;
                window.parent.postMessage({payload:'change_room',id_room:panoramas[id].id,name_room:panoramas[id].name,image_room:panoramas[id].panorama_image,count_marker:count_marker,count_poi:count_poi,count_measure:count_measure}, "*");
            }
            var len = panoramas.length;
            var prev_panorama = panoramas[(id+len-1)%len];
            var next_panorama = panoramas[(id+1)%len];
            $('.prev_arrow').attr('onclick','goto("",['+prev_panorama.id+',null,null,null,null,null,null,null]);');
            $('.prev_arrow').attr('data-roomtarget',prev_panorama.id);
            $('.prev_arrow').attr('title',prev_panorama.name);
            $('.next_arrow').attr('onclick','goto("",['+next_panorama.id+',null,null,null,null,null,null,null]);');
            $('.next_arrow').attr('data-roomtarget',next_panorama.id);
            $('.next_arrow').attr('title',next_panorama.name);
            $(".arrows").addClass('disabled');
            if(imgs_loaded.indexOf(prev_panorama.id) !== -1) {
                $(".arrows_nav").find("[data-roomtarget='" + prev_panorama.id + "']").removeClass('disabled');
                $(".controls_arrows").find("[data-roomtarget='" + prev_panorama.id + "']").removeClass('disabled');
            }
            if(imgs_loaded.indexOf(next_panorama.id) !== -1) {
                $(".arrows_nav").find("[data-roomtarget='" + next_panorama.id + "']").removeClass('disabled');
                $(".controls_arrows").find("[data-roomtarget='" + prev_panorama.id + "']").removeClass('disabled');
            }
            if(window.icon_tooltips==1) {
                try {
                    $('.prev_arrow').tooltipster('destroy');
                } catch (e) {}
                $('.arrows_nav .prev_arrow').tooltipster({
                    theme: 'tooltipster-borderless',
                    side: 'right',
                    animation: 'grow',
                    delay: 0,
                    arrow: false
                });
                $('.controls_arrows .prev_arrow').tooltipster({
                    theme: 'tooltipster-borderless',
                    side: 'top',
                    animation: 'grow',
                    delay: 0,
                    arrow: false
                });
                try {
                    $('.next_arrow').tooltipster('destroy');
                } catch (e) {}
                $('.arrows_nav .next_arrow').tooltipster({
                    theme: 'tooltipster-borderless',
                    side: 'left',
                    animation: 'grow',
                    delay: 0,
                    arrow: false
                });
                $('.controls_arrows .next_arrow').tooltipster({
                    theme: 'tooltipster-borderless',
                    side: 'top',
                    animation: 'grow',
                    delay: 0,
                    arrow: false
                });
            } else {
                $('.arrows_nav .prev_arrow').removeAttr('title');
                $('.controls_arrows .prev_arrow').removeAttr('title');
                $('.arrows_nav .next_arrow').removeAttr('title');
                $('.controls_arrows .next_arrow').removeAttr('title');
            }
            var view_name = '';
            if(id_room_alt==null) {
                if(panoramas[id].main_view_tooltip!='') {
                    view_name = " ("+panoramas[id].main_view_tooltip+")";
                }
            } else {
                if(panoramas[id].array_rooms_alt[id_room_alt].view_tooltip!='') {
                    view_name = " ("+panoramas[id].array_rooms_alt[id_room_alt].view_tooltip+")";
                }
            }
            $('.name_vt').html(name_virtual_tour);
            if(panoramas[id].logo!='') {
                $('.room_vt').css('height',panoramas[id].logo_height+'px');
                $('.room_vt').html("<img style='height:"+panoramas[id].logo_height+"px' class='logo_room_vt' src='"+((window.s3_enabled) ? window.s3_url : '')+"content/"+panoramas[id].logo+"' />&nbsp;&nbsp;"+view_name);
            } else {
                $('.room_vt').css('height','auto');
                $('.room_vt').html(panoramas[id].name+view_name);
            }
            if(array_panoramas_category["r_"+panoramas[id].id]!==undefined) {
                var name_category = array_panoramas_category["r_"+panoramas[id].id][1];
                if(name_category=='') {
                    $('.category_room_vt').html('');
                    $('.category_room_vt').hide();
                } else {
                    $('.category_room_vt').html('<i class="fas fa-layer-group"></i> '+name_category);
                    $('.category_room_vt').show();
                }
            } else {
                $('.category_room_vt').html('');
                $('.category_room_vt').hide();
            }
            $('.rooms_alt').removeClass("disabled");
            if(panoramas[id].virtual_staging==0 || panoramas[id].virtual_staging==1) {
                if(ObjectLength(panoramas[id].array_rooms_alt)>0) {
                    var main_img = panoramas[id].thumb_image;
                    var main_view_tooltip = panoramas[id].main_view_tooltip;
                    var class_tooltip = 'tooltip_view';
                    if(main_view_tooltip=='') class_tooltip='';
                    if(window.index_room_alt_sel==null) {
                        var html = "<img title=\""+main_view_tooltip+"\" class='active rooms_alt "+class_tooltip+"' onclick='change_room_alt(null);' src='"+((window.s3_enabled) ? window.s3_url : '')+main_img+"' />";
                    } else {
                        var html = "<img title=\""+main_view_tooltip+"\" class='rooms_alt "+class_tooltip+"' onclick='change_room_alt(null);' src='"+((window.s3_enabled) ? window.s3_url : '')+main_img+"' />";
                    }
                    var num_rooms_alt = 0;
                    jQuery.each(panoramas[id].array_rooms_alt, function(index_alt, room_alt) {
                        if(room_alt.poi==0) {
                            num_rooms_alt++;
                            class_tooltip = 'tooltip_view';
                            if(room_alt.view_tooltip=='') class_tooltip='';
                            if(window.index_room_alt_sel==index_alt) {
                                html += "<img title=\""+room_alt.view_tooltip+"\" class='active rooms_alt "+class_tooltip+" rooms_alt_"+index_alt+"' onclick='change_room_alt("+index_alt+");' src='"+((window.s3_enabled) ? window.s3_url : '')+room_alt.thumb_image+"' />";
                            } else {
                                html += "<img title=\""+room_alt.view_tooltip+"\" class='rooms_alt "+class_tooltip+" rooms_alt_"+index_alt+"' onclick='change_room_alt("+index_alt+");' src='"+((window.s3_enabled) ? window.s3_url : '')+room_alt.thumb_image+"' />";
                            }
                        }
                    });
                    if(num_rooms_alt>0) {
                        $('.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();
                }
            } else {
                $('.rooms_alt').removeClass("active");
                $('.rooms_alt_'+id_room_alt).addClass("active");
            }
            if(panoramas[id].allow_pitch==1) {
                var minPitch = parseInt(panoramas[id].min_pitch);
                var maxPitch = parseInt(panoramas[id].max_pitch);
                if(pitch_m!=null) {
                    var pitch = parseInt(pitch_m);
                } else {
                    var pitch = parseInt(panoramas[id].pitch);
                }
            } else {
                if(parseInt(panoramas[id].vaov)<180) {
                    var minPitch = (parseInt(panoramas[id].vaov)/2)*-1;
                    var maxPitch = parseInt(panoramas[id].vaov)/2;
                    var pitch = 0;
                } else {
                    var minPitch = 0;
                    var maxPitch = 0;
                    var pitch = 0;
                }
            }
            if(panoramas[id].autorotate_override==1) {
                var autorotate_speed_h = panoramas[id].autorotate_speed;
                var autorotate_inactivity_h = panoramas[id].autorotate_inactivity;
            } else {
                var autorotate_speed_h = autorotate_speed;
                var autorotate_inactivity_h = autorotate_inactivity;
            }
            if(autorotate_speed_h==0) {
                $('.autorotate_control').addClass('disabled');
            } else {
                $('.autorotate_control').removeClass('disabled');
            }
            if(vr_enabled) {
                var orientationOnByDefault = false;
                var min_hfov_f = 110;
                var max_hfov_f = 110;
                var hfov_f = 110;
                var draggable = false;
                var autorotate_speed_f = 0;
                if(yaw_m!=null) {
                    var workingYaw = parseInt(yaw_m);
                } else {
                    var workingYaw = parseInt(panoramas[id].yaw);
                }
            } else {
                if(controls_status['orient']) {
                    var orientationOnByDefault = true;
                } else {
                    var orientationOnByDefault = false;
                }
                var draggable = true;
                var min_hfov_f = min_hfov;
                var max_hfov_f = max_hfov;
                var hfov_f = parseInt(panoramas[id].hfov);
                var autorotate_speed_f = autorotate_speed_h;
            }
            if(controls_status['presentation'] && !presentation_type=='automatic') {
                autorotate_speed_f = 0;
            }
            if(sameAzimuth && click_m) {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile)  || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var current_yaw = parseFloat(pano_viewer.getYaw());
                    var current_north = parseFloat(pano_viewer.getNorthOffset());
                } else {
                    var current_yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var current_north = parseFloat(video_viewer.pnlmViewer.getNorthOffset());
                }
                var workingYaw = current_yaw + (current_north || 0) - (parseInt(panoramas[id].northOffset) || 0);
                pitch = 0;
            } else {
                if(yaw_m!=null) {
                    var workingYaw = parseInt(yaw_m);
                } else {
                    var workingYaw = parseInt(panoramas[id].yaw);
                }
            }
            if((controls_status['presentation']) && (presentation_type=='automatic')) {
                pitch = 0;
                hfov_f = hfov;
                autorotate_speed_f = auto_presentation_speed;
            } else if((controls_status['presentation']) && (presentation_type=='manual')) {
                pitch = 0;
                hfov_f = hfov;
                autorotate_speed_f = 0;
            }
            var orig_hfov = hfov_f;
            if(hfov_m!=null) {
                hfov_f=hfov_m;
                workingYaw=yaw_m;
                pitch=pitch_m;
            }
            if((panoramas[id].allow_hfov==0) && (!vr_enabled)) {
                min_hfov_f = hfov_f;
                max_hfov_f = hfov_f;
            }
            if(window.flyin!=0 && !cb && autorotate_speed_h>0 || !controls_status['auto_rotate']) {
                var autorotate_inactivity_f = -1;
            } else {
                var autorotate_inactivity_f = autorotate_inactivity_h;
            }
            if(window.flyin!=0 && !cb && autorotate_speed_h>0 && (show_autorotation_toggle==1 || show_autorotation_toggle==3)) {
                controls_status['auto_rotate']=true;
            }
            if(live_session_connected) {
                controls_status['auto_rotate']=false;
                autorotate_inactivity_f = -1;
                autorotate_speed_f = 0;
            }
            try {
                pano_viewer.destroy();
            } catch (e) {}
            pano_viewer = null;
            try {
                pano_viewer_alt.destroy();
            } catch (e) {}
            pano_viewer_alt = null;
            try {
                video_viewer.pnlmViewer.destroy();
                video_viewer.dispose();
            } catch (e) {}
            video_viewer = null;
            try {
                app_p.destroy(true);
            } catch (e) {}
            app_p = null;
            if(vr_enabled) {
                try {
                    pano_viewer_vr.destroy();
                } catch (e) {}
                try {
                    video_viewer_vr.pnlmViewer.destroy();
                    video_viewer_vr.dispose();
                    video_viewer_vr = null;
                } catch (e) {}
                try {
                    app_p_vr.destroy(true);
                } catch (e) {}
                app_p_vr = null;
            }
            if(window.innerHeight > window.innerWidth){
                if(window.innerWidth<500) {
                    var touchPanSpeedCoeffFactor = pan_speed_mobile_vt;
                    var friction = friction_mobile_vt;
                } else {
                    var touchPanSpeedCoeffFactor = pan_speed_mobile_vt/2;
                    var friction = friction_mobile_vt/2;
                }
                var zoom_friction = zoom_friction_mobile_vt;
            } else {
                var touchPanSpeedCoeffFactor = pan_speed_vt;
                var friction = friction_vt;
                var zoom_friction = zoom_friction_vt;
            }
            if(window.s3_enabled==1) {
                currentBaseImage = window.s3_url + panoramas[id].panorama_image + '?s3='+s3_version;
            } else {
                currentBaseImage = panoramas[id].panorama_image;
            }
            worker = null;
            switch(panoramas[id].type) {
                case 'image':
                    current_panorama_type = 'image';
                    $('#video_viewer').css('opacity', 0);
                    $('#video_viewer').css('z-index', 0);
                    if (id_room_alt != null) {
                        var multires = panoramas[id].array_rooms_alt[id_room_alt].multires;
                        var multires_config = panoramas[id].array_rooms_alt[id_room_alt].multires_config;
                        if (panoramas[id].array_rooms_alt[id_room_alt].panorama_blob != '') {
                            var panorama_image = panoramas[id].array_rooms_alt[id_room_alt].panorama_blob;
                        } else {
                            if(window.s3_enabled==1) {
                                var panorama_image = window.s3_url + panoramas[id].array_rooms_alt[id_room_alt].panorama_image + '?s3='+s3_version;
                            } else {
                                var panorama_image = panoramas[id].array_rooms_alt[id_room_alt].panorama_image;
                            }
                        }
                        var stats = false;
                    } else {
                        if(panoramas[id].virtual_staging==3) {
                            jQuery.each(panoramas[id].array_rooms_alt,function(index_ra,room_alt) {
                                if(room_alt.from_hour!==null && room_alt.to_hour!==null) {
                                    var start_time = moment(room_alt.from_hour, "HH:mm:ss");
                                    var end_time = moment(room_alt.to_hour, "HH:mm:ss");
                                    if (start_time.isAfter(end_time)){
                                        end_time.add(1, 'days');
                                    }
                                    if(moment().isBetween(start_time, end_time, 'time', true)) {
                                        id_room_alt = index_ra;
                                        window.id_room_alt_sel = room_alt.id;
                                        return false;
                                    }
                                }
                            });
                            if (id_room_alt != null) {
                                var multires = panoramas[id].array_rooms_alt[id_room_alt].multires;
                                var multires_config = panoramas[id].array_rooms_alt[id_room_alt].multires_config;
                                if (panoramas[id].array_rooms_alt[id_room_alt].panorama_blob != '') {
                                    var panorama_image = panoramas[id].array_rooms_alt[id_room_alt].panorama_blob;
                                } else {
                                    if(window.s3_enabled==1) {
                                        var panorama_image = window.s3_url + panoramas[id].array_rooms_alt[id_room_alt].panorama_image + '?s3='+s3_version;
                                    } else {
                                        var panorama_image = panoramas[id].array_rooms_alt[id_room_alt].panorama_image;
                                    }
                                }
                                var stats = true;
                                if(panoramas[id].array_rooms_alt[id_room_alt].view_tooltip!='') {
                                    view_name = " ("+panoramas[id].array_rooms_alt[id_room_alt].view_tooltip+")";
                                }
                                $('.name_vt').html(name_virtual_tour);
                                if(panoramas[id].logo!='') {
                                    $('.room_vt').css('height',panoramas[id].logo_height+'px');
                                    $('.room_vt').html("<img style='height:"+panoramas[id].logo_height+"px' class='logo_room_vt' src='"+((window.s3_enabled) ? window.s3_url : '')+"content/"+panoramas[id].logo+"' />&nbsp;&nbsp;"+view_name);
                                } else {
                                    $('.room_vt').css('height','auto');
                                    $('.room_vt').html(panoramas[id].name+view_name);
                                }
                                if(array_panoramas_category["r_"+panoramas[id].id]!==undefined) {
                                    var name_category = array_panoramas_category["r_"+panoramas[id].id][1];
                                    if(name_category=='') {
                                        $('.category_room_vt').html('');
                                        $('.category_room_vt').hide();
                                    } else {
                                        $('.category_room_vt').html('<i class="fas fa-layer-group"></i> '+name_category);
                                        $('.category_room_vt').show();
                                    }
                                } else {
                                    $('.category_room_vt').html('');
                                    $('.category_room_vt').hide();
                                }
                            } else {
                                var multires = panoramas[id].multires;
                                var multires_config = panoramas[id].multires_config;
                                if (panoramas[id].panorama_blob != '') {
                                    var panorama_image = panoramas[id].panorama_blob;
                                } else {
                                    if(window.s3_enabled==1) {
                                        var panorama_image = window.s3_url + panoramas[id].panorama_image + '?s3='+s3_version;
                                    } else {
                                        var panorama_image = panoramas[id].panorama_image;
                                    }
                                }
                                var stats = true;
                            }
                        } else {
                            var multires = panoramas[id].multires;
                            var multires_config = panoramas[id].multires_config;
                            if (panoramas[id].panorama_blob != '') {
                                var panorama_image = panoramas[id].panorama_blob;
                            } else {
                                if(window.s3_enabled==1) {
                                    var panorama_image = window.s3_url + panoramas[id].panorama_image + '?s3='+s3_version;
                                } else {
                                    var panorama_image = panoramas[id].panorama_image;
                                }
                            }
                            var stats = true;
                        }
                    }
                    if (panoramas[id].virtual_staging==2) {
                        try {
                            PIXI.assets.reset();
                        } catch (e) {}
                        list_mrv_panoramas.push(panoramas[id].panorama_image);
                        jQuery.each(panoramas[id].array_rooms_alt, function(id_room_alt, room_alt) {
                            list_mrv_panoramas.push(room_alt.panorama_image);
                        });
                        var setup_live_panorama = (loader, resources) => {
                            $("#canvas_p").empty();
                            PIXI.utils.sayHello("WebGL");
                            var index_first_mrv_panorama = Object.keys(resources)[0];
                            app_p = new PIXI.Application({
                                antialias: false,
                                transparent: false,
                                resolution: (window.is_mobile) ? 0.6 : 0.8,
                                width: resources[index_first_mrv_panorama].baseTexture.width,
                                height: resources[index_first_mrv_panorama].baseTexture.height,
                            });
                            $("#canvas_p").append(app_p.view);
                            mrv_panoramas[0] = PIXI.Sprite.from(resources[index_first_mrv_panorama]);
                            mrv_panoramas[0].alpha = 1;
                            mrv_panoramas[0].position.x = 0;
                            mrv_panoramas[0].position.y = 0;
                            app_p.stage.addChild(mrv_panoramas[0]);
                            mrv_count_panoramas = Object.keys(resources).length;
                            for (var i=1;i<mrv_count_panoramas;i++) {
                                var index_mrv_panorama = Object.keys(resources)[i];
                                mrv_panoramas[i] = PIXI.Sprite.from(resources[index_mrv_panorama]);
                                mrv_panoramas[i].alpha = 0;
                                mrv_panoramas[i].position.x = 0;
                                mrv_panoramas[i].position.y = 0;
                                app_p.stage.addChild(mrv_panoramas[i]);
                            }
                            let canvas = $('#canvas_p canvas')[0];
                            pano_viewer = pannellum.viewer('panorama_viewer', {
                                "id_room": panoramas[id].id,
                                "type": "equirectangular",
                                "panorama": canvas,
                                "backgroundColor": panoramas[id].background_color,
                                "avoidShowingBackground": true,
                                "dynamic": true,
                                "dynamicUpdate": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "friction": friction,
                                "zoom_friction": zoom_friction,
                                "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                "compass": true,
                                "northOffset": parseInt(panoramas[id].northOffset),
                                "map_north": parseInt(panoramas[id].map_north),
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "multiResMinHfov": true,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov": max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch": maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw": parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots,
                            });
                            setTimeout(function () {
                                if(vr_enabled) {
                                    pano_viewer = pannellum.viewer('panorama_viewer_vr', {
                                        "id_room": panoramas[id].id,
                                        "type": "equirectangular",
                                        "panorama": canvas,
                                        "backgroundColor": panoramas[id].background_color,
                                        "avoidShowingBackground": true,
                                        "dynamic": true,
                                        "dynamicUpdate": true,
                                        "autoLoad": true,
                                        "disableKeyboardCtrl": keyboard_mode,
                                        "mouseZoom": window.mouse_zoom,
                                        "showZoomCtrl": false,
                                        "showFullscreenCtrl": false,
                                        "orientationOnByDefault": orientationOnByDefault,
                                        "draggable": draggable,
                                        "autoRotate": autorotate_speed_f,
                                        "autoRotateStopDelay": 10,
                                        "autoRotateInactivityDelay": autorotate_inactivity_f,
                                        "friction": friction,
                                        "zoom_friction": zoom_friction,
                                        "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                        "compass": true,
                                        "northOffset": parseInt(panoramas[id].northOffset),
                                        "map_north": parseInt(panoramas[id].map_north),
                                        "horizonPitch": parseInt(panoramas[id].h_pitch),
                                        "horizonRoll": parseInt(panoramas[id].h_roll),
                                        "pitch": pitch,
                                        "yaw": workingYaw,
                                        "multiResMinHfov": true,
                                        "hfov": hfov_f,
                                        "origHfov": orig_hfov,
                                        "minHfov": min_hfov_f,
                                        "maxHfov": max_hfov_f,
                                        "minPitch": minPitch,
                                        "maxPitch": maxPitch,
                                        "minYaw": parseInt(panoramas[id].min_yaw),
                                        "maxYaw": parseInt(panoramas[id].max_yaw),
                                        "haov": parseInt(panoramas[id].haov),
                                        "vaov": parseInt(panoramas[id].vaov),
                                        "hotSpots": panoramas[id].hotSpots,
                                    });
                                    setTimeout(function() {
                                        player_initialized(cb, id, stats, id_room_alt, dh, click_m);
                                        register_viewer_listeners(pano_viewer,false);
                                    },250);
                                } else {
                                    player_initialized(cb, id, stats, id_room_alt, dh, click_m);
                                    register_viewer_listeners(pano_viewer,false);
                                }
                            },250);
                        };
                        var list_assets = [];
                        for(var i=0;i<list_mrv_panoramas.length;i++) {
                            list_assets.push("panorama_"+panoramas[id].id+"_"+(i+1));
                            PIXI.Assets.add("panorama_"+panoramas[id].id+"_"+(i+1),((window.s3_enabled) ? window.s3_url : '')+list_mrv_panoramas[i]);
                        }
                        PIXI.Assets.load(list_assets).then((textures) => {
                            setup_live_panorama(null,textures);
                        });
                    } else {
                        if (multires) {
                            pano_viewer = pannellum.viewer('panorama_viewer', {
                                "id_room": panoramas[id].id,
                                "type": "multires",
                                "multiRes": multires_config,
                                "backgroundColor": panoramas[id].background_color,
                                "avoidShowingBackground": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "friction": friction,
                                "zoom_friction": zoom_friction,
                                "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                "compass": true,
                                "northOffset": parseInt(panoramas[id].northOffset),
                                "map_north": parseInt(panoramas[id].map_north),
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "multiResMinHfov": true,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov": max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch": maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw": parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots,
                            });
                            setTimeout(function () {
                                player_initialized(cb, id, stats, id_room_alt, dh, click_m);
                                register_viewer_listeners(pano_viewer,true);
                            }, 100);
                        } else {
                            pano_viewer = pannellum.viewer('panorama_viewer', {
                                "id_room": panoramas[id].id,
                                "type": "equirectangular",
                                "panorama": panorama_image,
                                "backgroundColor": panoramas[id].background_color,
                                "avoidShowingBackground": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "friction": friction,
                                "zoom_friction": zoom_friction,
                                "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                "compass": true,
                                "northOffset": parseInt(panoramas[id].northOffset),
                                "map_north": parseInt(panoramas[id].map_north),
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "multiResMinHfov": true,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov": max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch": maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw": parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots,
                            });
                            pano_viewer.on('load', function () {
                                setTimeout(function () {
                                    player_initialized(cb, id, stats, id_room_alt, dh, click_m);
                                    register_viewer_listeners(pano_viewer,true);
                                }, 50);
                            });
                        }
                        if (virtual_staging) {
                            var multires = panoramas[id].multires;
                            var multires_config = panoramas[id].multires_config;
                            if (panoramas[id].panorama_blob != '') {
                                var panorama_image = panoramas[id].panorama_blob;
                            } else {
                                var panorama_image = ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_image;
                            }
                            if (multires) {
                                config_alt = {
                                    "id_room": panoramas[id].id,
                                    "type": "multires",
                                    "multiRes": multires_config,
                                    "backgroundColor": panoramas[id].background_color,
                                    "avoidShowingBackground": true,
                                    "autoLoad": true,
                                    "disableKeyboardCtrl": keyboard_mode,
                                    "mouseZoom": window.mouse_zoom,
                                    "showZoomCtrl": false,
                                    "showFullscreenCtrl": false,
                                    "orientationOnByDefault": orientationOnByDefault,
                                    "draggable": draggable,
                                    "autoRotate": autorotate_speed_f,
                                    "autoRotateStopDelay": 10,
                                    "autoRotateInactivityDelay": autorotate_inactivity_f,
                                    "friction": friction,
                                    "zoom_friction": zoom_friction,
                                    "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                    "compass": true,
                                    "northOffset": parseInt(panoramas[id].northOffset),
                                    "map_north": parseInt(panoramas[id].map_north),
                                    "horizonPitch": parseInt(panoramas[id].h_pitch),
                                    "horizonRoll": parseInt(panoramas[id].h_roll),
                                    "pitch": pitch,
                                    "yaw": workingYaw,
                                    "multiResMinHfov": true,
                                    "hfov": hfov_f,
                                    "origHfov": orig_hfov,
                                    "minHfov": min_hfov_f,
                                    "maxHfov": max_hfov_f,
                                    "minPitch": minPitch,
                                    "maxPitch": maxPitch,
                                    "minYaw": parseInt(panoramas[id].min_yaw),
                                    "maxYaw": parseInt(panoramas[id].max_yaw),
                                    "haov": parseInt(panoramas[id].haov),
                                    "vaov": parseInt(panoramas[id].vaov),
                                    "hotSpots": panoramas[id].hotSpots_alt,
                                };
                            } else {
                                config_alt = {
                                    "id_room": panoramas[id].id,
                                    "type": "equirectangular",
                                    "panorama": panorama_image,
                                    "backgroundColor": panoramas[id].background_color,
                                    "avoidShowingBackground": true,
                                    "autoLoad": true,
                                    "disableKeyboardCtrl": keyboard_mode,
                                    "mouseZoom": window.mouse_zoom,
                                    "showZoomCtrl": false,
                                    "showFullscreenCtrl": false,
                                    "orientationOnByDefault": orientationOnByDefault,
                                    "draggable": draggable,
                                    "autoRotate": autorotate_speed_f,
                                    "autoRotateStopDelay": 10,
                                    "autoRotateInactivityDelay": autorotate_inactivity_f,
                                    "friction": friction,
                                    "zoom_friction": zoom_friction,
                                    "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                    "compass": true,
                                    "northOffset": parseInt(panoramas[id].northOffset),
                                    "map_north": parseInt(panoramas[id].map_north),
                                    "horizonPitch": parseInt(panoramas[id].h_pitch),
                                    "horizonRoll": parseInt(panoramas[id].h_roll),
                                    "pitch": pitch,
                                    "yaw": workingYaw,
                                    "multiResMinHfov": true,
                                    "hfov": hfov_f,
                                    "origHfov": orig_hfov,
                                    "minHfov": min_hfov_f,
                                    "maxHfov": max_hfov_f,
                                    "minPitch": minPitch,
                                    "maxPitch": maxPitch,
                                    "minYaw": parseInt(panoramas[id].min_yaw),
                                    "maxYaw": parseInt(panoramas[id].max_yaw),
                                    "haov": parseInt(panoramas[id].haov),
                                    "vaov": parseInt(panoramas[id].vaov),
                                    "hotSpots": panoramas[id].hotSpots_alt,
                                };
                            }
                        }
                    }
                    break;
                case 'video':
                    if(window.is_mobile) {
                        try {
                            PIXI.assets.reset();
                        } catch (e) {}
                        try {
                            video_p.remove();
                        } catch (e) {}
                        $("#canvas_p").empty();
                        current_panorama_type = 'video';
                        $('#video_viewer').css('opacity',0);
                        $('#video_viewer').css('z-index',0);
                        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: (window.is_mobile) ? 0.6 : 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;*/
                            if(controls_status['presentation']) {
                                if(presentation_video_wait_end==1) {
                                    var loop_vj = false;
                                } else {
                                    var loop_vj = true;
                                }
                            } else {
                                if(panoramas[id].video_end_goto==0) {
                                    var loop_vj = true;
                                } else {
                                    var loop_vj = false;
                                }
                            }
                            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 = (panoramas[id].audio_track_enable) ? false : true;
                            video_p.loop = loop_vj;
                            video_p.setAttribute('playsinline','');
                            video_p.setAttribute('webkit-playsinline','');
                            video_p.oncanplay = function() {
                                video_p.play().catch(function() {
                                    video_p.muted = true;
                                    video_p.play();
                                });
                            };
                            video_p.src = ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_video;
                            const sprite = PIXI.Sprite.from(video_p);
                            video_p.addEventListener('loadedmetadata', function() {
                                const videoWidth = video_p.videoWidth;
                                const videoHeight = video_p.videoHeight;
                                const maxTextureSize = 4096;
                                if (videoWidth > maxTextureSize || videoHeight > maxTextureSize) {
                                    const scaleFactor = maxTextureSize / Math.max(videoWidth, videoHeight);
                                    sprite.scale.set(scaleFactor, scaleFactor);
                                }
                            });
                            /*sprite.anchor.y = 1;
                            sprite.scale.y = -1;*/
                            app_p.stage.addChild(sprite);
                            let canvas = $('#canvas_p canvas')[0];
                            pano_viewer = pannellum.viewer('panorama_viewer', {
                                "id_room": panoramas[id].id,
                                "type": "equirectangular",
                                "panorama": canvas,
                                "backgroundColor": panoramas[id].background_color,
                                "dynamic": true,
                                "dynamicUpdate": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "friction": friction,
                                "zoom_friction": zoom_friction,
                                "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                "compass": true,
                                "northOffset": parseInt(panoramas[id].northOffset),
                                "map_north": parseInt(panoramas[id].map_north),
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "multiResMinHfov": true,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov" : max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch" : maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw" : parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots,
                            });
                            setTimeout(function () {
                                player_initialized(cb,id,stats,null,dh,click_m);
                                pano_viewer.on('touchend',function() {
                                    if(panoramas[id].audio_track_enable) {
                                        video_p.muted = false;
                                    }
                                });
                                register_viewer_listeners(pano_viewer,false);
                                if(vr_enabled) {
                                    $("#canvas_p_vr").empty();
                                    $('#video_viewer_vr').show();
                                    PIXI.utils.sayHello("WebGL");
                                    app_p_vr = new PIXI.Application({
                                        antialias: false,
                                        transparent: false,
                                        resolution: (window.is_mobile) ? 0.6 : 1,
                                        width: resources[index_bg].baseTexture.width,
                                        height: resources[index_bg].baseTexture.height
                                    });
                                    $("#canvas_p_vr").append(app_p_vr.view);
                                    let bg = PIXI.Sprite.from(resources[index_bg]);
                                    app_p_vr.stage.addChild(bg);
                                    const sprite = PIXI.Sprite.from(video_p);
                                    app_p_vr.stage.addChild(sprite);
                                    let canvas = $('#canvas_p canvas')[0];
                                    pano_viewer_vr = pannellum.viewer('panorama_viewer_vr', {
                                        "id_room": panoramas[id].id,
                                        "type": "equirectangular",
                                        "panorama": canvas,
                                        "dynamic": true,
                                        "dynamicUpdate": true,
                                        "autoLoad": true,
                                        "disableKeyboardCtrl": keyboard_mode,
                                        "mouseZoom": window.mouse_zoom,
                                        "showZoomCtrl": false,
                                        "showFullscreenCtrl": false,
                                        "orientationOnByDefault": orientationOnByDefault,
                                        "draggable": draggable,
                                        "autoRotate": autorotate_speed_f,
                                        "autoRotateStopDelay": 10,
                                        "autoRotateInactivityDelay": autorotate_inactivity_f,
                                        "friction": friction,
                                        "zoom_friction": zoom_friction,
                                        "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                        "compass": true,
                                        "northOffset": parseInt(panoramas[id].northOffset),
                                        "horizonPitch": parseInt(panoramas[id].h_pitch),
                                        "horizonRoll": parseInt(panoramas[id].h_roll),
                                        "pitch": pitch,
                                        "yaw": workingYaw,
                                        "hfov": hfov_f,
                                        "origHfov": orig_hfov,
                                        "minHfov": min_hfov_f,
                                        "maxHfov" : max_hfov_f,
                                        "minPitch": minPitch,
                                        "maxPitch" : maxPitch,
                                        "minYaw": parseInt(panoramas[id].min_yaw),
                                        "maxYaw" : parseInt(panoramas[id].max_yaw),
                                        "haov": parseInt(panoramas[id].haov),
                                        "vaov": parseInt(panoramas[id].vaov),
                                        "hotSpots": panoramas[id].hotSpots_vr,
                                    });
                                    setTimeout(function () {
                                        $('#video_viewer_vr').animate({
                                            opacity: 1
                                        }, { duration: 250, queue: false });
                                        $('#video_viewer_vr').css('z-index',10);
                                        $('#panorama_viewer_vr').css('opacity',1);
                                        $('#background_pano').fadeOut();
                                        $('#background_pano_vr').fadeOut();
                                        $('.pnlm-controls-container').hide();
                                        $('.map').hide();
                                        $('.share_popup').removeClass('show');
                                        $('.custom-hotspot-content').css('opacity',0);
                                        $('.custom-hotspot-content').css('pointer-events','none');
                                        $('.leader-line').css('opacity',0);
                                        $('.leader-line').css('pointer-events','none');
                                        $('.pnlm-orientation-button').hide();
                                        $('.compass_control').hide();
                                        clearInterval(interval_position);
                                        interval_position = setInterval(function () {
                                            check_vr_pos();
                                        },250);
                                        setTimeout(function () {
                                            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                                pano_viewer.startOrientation();
                                                pano_viewer_vr.startOrientation();
                                            } else {
                                                video_viewer.pnlmViewer.startOrientation();
                                                video_viewer_vr.pnlmViewer.startOrientation();
                                            }
                                            $('.loading_vr').fadeOut();
                                        },500);
                                    },200);
                                }
                            },200);
                        };
                        var list_assets = ["background_"+panoramas[id].id];
                        PIXI.Assets.add("background_"+panoramas[id].id, ((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+panoramas[id].panorama_image);
                        PIXI.Assets.load(list_assets).then((textures) => {
                            setup_video_p(null,textures);
                        });
                    } else {
                        var vh = window.innerHeight * 0.01;
                        document.documentElement.style.setProperty('--vh', `${vh}px`);
                        var fileExt = panoramas[id].panorama_video.split('.').pop().toLowerCase();
                        switch(fileExt) {
                            case 'webm':
                                var type_video = 'video/webm';
                                break;
                            default:
                                var type_video = 'video/mp4';
                                break;
                        }
                        if(vr_enabled) {
                            $('#div_panoramas').append('<video playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="display: none;position: absolute;top: 0;left: 0;width: 50%;height: calc(var(--vh, 1vh) * 100);opacity: 0" preload="none" crossorigin="anonymous"><source src="'+((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_video+'" type="'+type_video+'"/></video>');
                        } else {
                            $('#div_panoramas').append('<video playsinline webkit-playsinline id="video_viewer" class="video-js vjs-default-skin vjs-big-play-centered" style="display: none;position: absolute;top: 0;left: 0;width: 100%;height: calc(var(--vh, 1vh) * 100);opacity: 0" preload="none" crossorigin="anonymous"><source src="'+((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_video+'" type="'+type_video+'"/></video>');
                        }
                        current_panorama_type = 'video';
                        $('#video_viewer').show();
                        $('#panorama_viewer').css('opacity',0);
                        $('#panorama_viewer').css('z-index',0);
                        if(window.flyin!=0) {
                            $('#panorama_viewer_alt').css('opacity',0);
                            $('#panorama_viewer_alt').css('z-index',0);
                        }
                        if(vr_enabled) {
                            var controls_video = false;
                        } else {
                            var controls_video = true;
                        }
                        if(controls_status['presentation']) {
                            if(presentation_video_wait_end==1) {
                                var loop_vj = false;
                            } else {
                                var loop_vj = true;
                            }
                        } else {
                            if(panoramas[id].video_end_goto==0) {
                                var loop_vj = true;
                            } else {
                                var loop_vj = false;
                            }
                        }
                        video_viewer = videojs('video_viewer', {
                            loop: loop_vj,
                            autoload: true,
                            autoplay: true,
                            muted: true,
                            controls: controls_video,
                            inactivityTimeout: 0,
                            controlBar: {
                                fullscreenToggle: false,
                                pictureInPictureToggle: false
                            },
                            plugins: {
                                pannellum: {
                                    "id_room": panoramas[id].id,
                                    "autoLoad": true,
                                    "disableKeyboardCtrl": keyboard_mode,
                                    "mouseZoom": window.mouse_zoom,
                                    "showZoomCtrl": false,
                                    "showFullscreenCtrl": false,
                                    "orientationOnByDefault": orientationOnByDefault,
                                    "draggable": draggable,
                                    "autoRotate": autorotate_speed_f,
                                    "autoRotateStopDelay": 10,
                                    "autoRotateInactivityDelay": autorotate_inactivity_f,
                                    "friction": friction,
                                    "zoom_friction": zoom_friction,
                                    "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                    "compass": true,
                                    "northOffset": parseInt(panoramas[id].northOffset),
                                    "map_north": parseInt(panoramas[id].map_north),
                                    "horizonPitch": parseInt(panoramas[id].h_pitch),
                                    "horizonRoll": parseInt(panoramas[id].h_roll),
                                    "pitch": pitch,
                                    "yaw": workingYaw,
                                    "hfov": hfov_f,
                                    "origHfov": orig_hfov,
                                    "minHfov": min_hfov_f,
                                    "maxHfov" : max_hfov_f,
                                    "minPitch": minPitch,
                                    "maxPitch" : maxPitch,
                                    "minYaw": parseInt(panoramas[id].min_yaw),
                                    "maxYaw" : parseInt(panoramas[id].max_yaw),
                                    "haov": parseInt(panoramas[id].haov),
                                    "vaov": parseInt(panoramas[id].vaov),
                                    "hotSpots": panoramas[id].hotSpots,
                                }
                            }
                        });
                        video_viewer.load();
                        video_viewer.on('loadeddata', function() {
                            video_viewer.play();
                            var video_is_playing = false;
                            $(document).one("mousedown touchstart",function(e){
                                if(!video_is_playing) {
                                    var video_elem = document.getElementById('video_viewer_html5_api');
                                    video_elem.play();
                                    video_is_playing = true;
                                }
                            });
                            video_viewer.pnlmViewer.on('load',function () {
                                setTimeout(function () {
                                    player_initialized(cb, id, true, null, dh, click_m);
                                    register_viewer_listeners(video_viewer.pnlmViewer, false);
                                    if(vr_enabled) {
                                        var vh = window.innerHeight * 0.01;
                                        document.documentElement.style.setProperty('--vh', `${vh}px`);
                                        var fileExt = panoramas[id].panorama_video.split('.').pop().toLowerCase();
                                        switch(fileExt) {
                                            case 'webm':
                                                var type_video = 'video/webm';
                                                break;
                                            default:
                                                var type_video = 'video/mp4';
                                                break;
                                        }
                                        $('#div_panoramas').append('<video id="video_viewer_vr" class="video-js vjs-default-skin vjs-big-play-centered" style="display: none;position: absolute;width: 50%;top: 0;left: 50%;height: calc(var(--vh, 1vh) * 100);opacity: 0" muted preload="none" crossorigin="anonymous"><source src="'+((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_video+'" type="'+type_video+'"/></video>');
                                        $('#video_viewer_vr').show();
                                        video_viewer_vr = videojs('video_viewer_vr', {
                                            loop: true,
                                            autoload: true,
                                            plugins: {
                                                pannellum: {
                                                    "id_room": panoramas[id].id,
                                                    "autoLoad": true,
                                                    "disableKeyboardCtrl": keyboard_mode,
                                                    "mouseZoom": window.mouse_zoom,
                                                    "showZoomCtrl": false,
                                                    "showFullscreenCtrl": false,
                                                    "orientationOnByDefault": orientationOnByDefault,
                                                    "draggable": draggable,
                                                    "autoRotate": autorotate_speed_f,
                                                    "autoRotateStopDelay": 10,
                                                    "autoRotateInactivityDelay": autorotate_inactivity_f,
                                                    "friction": friction,
                                                    "zoom_friction": zoom_friction,
                                                    "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                                    "compass": true,
                                                    "northOffset": parseInt(panoramas[id].northOffset),
                                                    "horizonPitch": parseInt(panoramas[id].h_pitch),
                                                    "horizonRoll": parseInt(panoramas[id].h_roll),
                                                    "pitch": pitch,
                                                    "yaw": workingYaw,
                                                    "hfov": hfov_f,
                                                    "origHfov": orig_hfov,
                                                    "minHfov": min_hfov_f,
                                                    "maxHfov" : max_hfov_f,
                                                    "minPitch": minPitch,
                                                    "maxPitch" : maxPitch,
                                                    "minYaw": parseInt(panoramas[id].min_yaw),
                                                    "maxYaw" : parseInt(panoramas[id].max_yaw),
                                                    "haov": parseInt(panoramas[id].haov),
                                                    "vaov": parseInt(panoramas[id].vaov),
                                                    "hotSpots": panoramas[id].hotSpots_vr,
                                                }
                                            }
                                        });
                                        video_viewer_vr.load();
                                        video_viewer_vr.on('ready', function() {
                                            video_viewer.currentTime(0);
                                            video_viewer_vr.play();
                                            video_viewer.play();
                                            video_viewer_vr.pnlmViewer.on('load',function () {
                                                $('#video_viewer_vr').animate({
                                                    opacity: 1
                                                }, { duration: 250, queue: false });
                                                $('#video_viewer_vr').css('z-index',10);
                                                $('#background_pano').fadeOut();
                                                $('#background_pano_vr').fadeOut();
                                                $('.pnlm-controls-container').hide();
                                                $('.map').hide();
                                                $('.share_popup').removeClass('show');
                                                $('.custom-hotspot-content').css('opacity',0);
                                                $('.custom-hotspot-content').css('pointer-events','none');
                                                $('.leader-line').css('opacity',0);
                                                $('.leader-line').css('pointer-events','none');
                                                $('.pnlm-orientation-button').hide();
                                                $('.compass_control').hide();
                                                clearInterval(interval_position);
                                                interval_position = setInterval(function () {
                                                    check_vr_pos();
                                                },250);
                                                setTimeout(function () {
                                                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                                        pano_viewer.startOrientation();
                                                        pano_viewer_vr.startOrientation();
                                                    } else {
                                                        video_viewer.pnlmViewer.startOrientation();
                                                        video_viewer_vr.pnlmViewer.startOrientation();
                                                    }
                                                    $('.loading_vr').fadeOut();
                                                },500);
                                            });
                                        });
                                    }
                                },200);
                            });
                        });
                    }
                    break;
                case 'hls':
                    try {
                        video_p.remove();
                    } catch (e) {}
                    $("#canvas_p").empty();
                    current_panorama_type = 'hls';
                    $('#video_viewer').css('opacity',0);
                    $('#video_viewer').css('z-index',0);
                    var setup_video_p_hls = (loader, resources) => {
                        PIXI.utils.sayHello("WebGL");
                        var index_bg = Object.keys(resources)[0];
                        app_p = new PIXI.Application({
                            antialias: false,
                            transparent: false,
                            resolution: (window.is_mobile) ? 0.6 : 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]);
                        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','');
                        if (Hls.isSupported()) {
                            var hls = new Hls();
                            hls.loadSource(panoramas[id].panorama_url);
                            hls.attachMedia(video_p);
                            hls.on(Hls.Events.MANIFEST_PARSED,function() {
                                video_p.play();
                            });
                        } else if (video_p.canPlayType("application/vnd.apple.mpegurl")) {
                            video_p.src = panoramas[id].panorama_url;
                            video_p.addEventListener('loadedmetadata',function() {
                                video_p.play();
                            });
                        }
                        const sprite = PIXI.Sprite.from(video_p);
                        app_p.stage.addChild(sprite);
                        let canvas = $('#canvas_p canvas')[0];
                        pano_viewer = pannellum.viewer('panorama_viewer', {
                            "id_room": panoramas[id].id,
                            "type": "equirectangular",
                            "panorama": canvas,
                            "backgroundColor": panoramas[id].background_color,
                            "dynamic": true,
                            "dynamicUpdate": true,
                            "autoLoad": true,
                            "disableKeyboardCtrl": keyboard_mode,
                            "mouseZoom": window.mouse_zoom,
                            "showZoomCtrl": false,
                            "showFullscreenCtrl": false,
                            "orientationOnByDefault": orientationOnByDefault,
                            "draggable": draggable,
                            "autoRotate": autorotate_speed_f,
                            "autoRotateStopDelay": 10,
                            "autoRotateInactivityDelay": autorotate_inactivity_f,
                            "friction": friction,
                            "zoom_friction": zoom_friction,
                            "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                            "compass": true,
                            "northOffset": parseInt(panoramas[id].northOffset),
                            "map_north": parseInt(panoramas[id].map_north),
                            "horizonPitch": parseInt(panoramas[id].h_pitch),
                            "horizonRoll": parseInt(panoramas[id].h_roll),
                            "pitch": pitch,
                            "yaw": workingYaw,
                            "multiResMinHfov": true,
                            "hfov": hfov_f,
                            "origHfov": orig_hfov,
                            "minHfov": min_hfov_f,
                            "maxHfov" : max_hfov_f,
                            "minPitch": minPitch,
                            "maxPitch" : maxPitch,
                            "minYaw": parseInt(panoramas[id].min_yaw),
                            "maxYaw" : parseInt(panoramas[id].max_yaw),
                            "haov": parseInt(panoramas[id].haov),
                            "vaov": parseInt(panoramas[id].vaov),
                            "hotSpots": panoramas[id].hotSpots,
                        });
                        setTimeout(function () {
                            player_initialized(cb,id,stats,null,dh,click_m);
                            pano_viewer.on('touchend',function() {
                                if(panoramas[id].audio_track_enable) {
                                    video_p.muted = false;
                                }
                            });
                            register_viewer_listeners(pano_viewer,false);
                            if(vr_enabled) {
                                $("#canvas_p_vr").empty();
                                $('#video_viewer_vr').show();
                                PIXI.utils.sayHello("WebGL");
                                app_p_vr = new PIXI.Application({
                                    antialias: false,
                                    transparent: false,
                                    resolution: (window.is_mobile) ? 0.6 : 1,
                                    width: resources[index_bg].baseTexture.width,
                                    height: resources[index_bg].baseTexture.height
                                });
                                $("#canvas_p_vr").append(app_p_vr.view);
                                let bg = PIXI.Sprite.from(resources[index_bg]);
                                app_p_vr.stage.addChild(bg);
                                const sprite = PIXI.Sprite.from(video_p);
                                app_p_vr.stage.addChild(sprite);
                                let canvas = $('#canvas_p canvas')[0];
                                pano_viewer_vr = pannellum.viewer('panorama_viewer_vr', {
                                    "id_room": panoramas[id].id,
                                    "type": "equirectangular",
                                    "panorama": canvas,
                                    "dynamic": true,
                                    "dynamicUpdate": true,
                                    "autoLoad": true,
                                    "disableKeyboardCtrl": keyboard_mode,
                                    "mouseZoom": window.mouse_zoom,
                                    "showZoomCtrl": false,
                                    "showFullscreenCtrl": false,
                                    "orientationOnByDefault": orientationOnByDefault,
                                    "draggable": draggable,
                                    "autoRotate": autorotate_speed_f,
                                    "autoRotateStopDelay": 10,
                                    "autoRotateInactivityDelay": autorotate_inactivity_f,
                                    "friction": friction,
                                    "zoom_friction": zoom_friction,
                                    "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                    "compass": true,
                                    "northOffset": parseInt(panoramas[id].northOffset),
                                    "horizonPitch": parseInt(panoramas[id].h_pitch),
                                    "horizonRoll": parseInt(panoramas[id].h_roll),
                                    "pitch": pitch,
                                    "yaw": workingYaw,
                                    "hfov": hfov_f,
                                    "origHfov": orig_hfov,
                                    "minHfov": min_hfov_f,
                                    "maxHfov" : max_hfov_f,
                                    "minPitch": minPitch,
                                    "maxPitch" : maxPitch,
                                    "minYaw": parseInt(panoramas[id].min_yaw),
                                    "maxYaw" : parseInt(panoramas[id].max_yaw),
                                    "haov": parseInt(panoramas[id].haov),
                                    "vaov": parseInt(panoramas[id].vaov),
                                    "hotSpots": panoramas[id].hotSpots_vr,
                                });
                                setTimeout(function () {
                                    $('#video_viewer_vr').animate({
                                        opacity: 1
                                    }, { duration: 250, queue: false });
                                    $('#video_viewer_vr').css('z-index',10);
                                    $('#panorama_viewer_vr').css('opacity',1);
                                    $('#background_pano').fadeOut();
                                    $('#background_pano_vr').fadeOut();
                                    $('.pnlm-controls-container').hide();
                                    $('.map').hide();
                                    $('.share_popup').removeClass('show');
                                    $('.custom-hotspot-content').css('opacity',0);
                                    $('.custom-hotspot-content').css('pointer-events','none');
                                    $('.leader-line').css('opacity',0);
                                    $('.leader-line').css('pointer-events','none');
                                    $('.pnlm-orientation-button').hide();
                                    $('.compass_control').hide();
                                    clearInterval(interval_position);
                                    interval_position = setInterval(function () {
                                        check_vr_pos();
                                    },250);
                                    setTimeout(function () {
                                        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                            pano_viewer.startOrientation();
                                            pano_viewer_vr.startOrientation();
                                        } else {
                                            video_viewer.pnlmViewer.startOrientation();
                                            video_viewer_vr.pnlmViewer.startOrientation();
                                        }
                                        $('.loading_vr').fadeOut();
                                    },500);
                                },200);
                            }
                        },200);
                    };
                    var list_assets = ["background_"+panoramas[id].id];
                    PIXI.Assets.add("background_"+panoramas[id].id, ((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+panoramas[id].panorama_image);
                    PIXI.Assets.load(list_assets).then((textures) => {
                        setup_video_p_hls(null,textures);
                    });
                    break;
                case 'lottie':
                    current_panorama_type = 'lottie';
                    var img_lottie = new Image();
                    img_lottie.crossOrigin = 'anonymous';
                    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: ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_json+((window.s3_enabled) ? '?s3='+s3_version : ''),
                            rendererSettings: {
                                context: lottie_context,
                                progressiveLoad: true,
                            }
                        });
                        pano_viewer = pannellum.viewer('panorama_viewer', {
                            "id_room": panoramas[id].id,
                            "type": "equirectangular",
                            "panorama": canvas,
                            "backgroundColor": panoramas[id].background_color,
                            "avoidShowingBackground": true,
                            "dynamic": true,
                            "dynamicUpdate": true,
                            "autoLoad": true,
                            "disableKeyboardCtrl": keyboard_mode,
                            "mouseZoom": window.mouse_zoom,
                            "showZoomCtrl": false,
                            "showFullscreenCtrl": false,
                            "orientationOnByDefault": orientationOnByDefault,
                            "draggable": draggable,
                            "autoRotate": autorotate_speed_f,
                            "autoRotateStopDelay": 10,
                            "autoRotateInactivityDelay": autorotate_inactivity_f,
                            "friction": friction,
                            "zoom_friction": zoom_friction,
                            "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                            "compass": true,
                            "northOffset": parseInt(panoramas[id].northOffset),
                            "map_north": parseInt(panoramas[id].map_north),
                            "horizonPitch": parseInt(panoramas[id].h_pitch),
                            "horizonRoll": parseInt(panoramas[id].h_roll),
                            "pitch": pitch,
                            "yaw": workingYaw,
                            "multiResMinHfov": true,
                            "hfov": hfov_f,
                            "origHfov": orig_hfov,
                            "minHfov": min_hfov_f,
                            "maxHfov" : max_hfov_f,
                            "minPitch": minPitch,
                            "maxPitch" : maxPitch,
                            "minYaw": parseInt(panoramas[id].min_yaw),
                            "maxYaw" : parseInt(panoramas[id].max_yaw),
                            "haov": parseInt(panoramas[id].haov),
                            "vaov": parseInt(panoramas[id].vaov),
                            "hotSpots": panoramas[id].hotSpots,
                        });
                        setTimeout(function () {
                            player_initialized(cb,id,stats,null,dh,click_m);
                            register_viewer_listeners(pano_viewer,false);
                        },200);
                    }
                    img_lottie.crossOrigin = false;
                    img_lottie.src = ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_image;
                    break;
            }

            if(vr_enabled) {
                switch(panoramas[id].type) {
                    case 'image':
                        if(panoramas[id].multires) {
                            pano_viewer_vr = pannellum.viewer('panorama_viewer_vr', {
                                "id_room": panoramas[id].id,
                                "type": "multires",
                                "multiRes": panoramas[id].multires_config,
                                "backgroundColor": panoramas[id].background_color,
                                "avoidShowingBackground": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "compass": true,
                                "northOffset": panoramas[id].northOffset,
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "multiResMinHfov": true,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov" : max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch" : maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw" : parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots_vr,
                            });
                            setTimeout(function () {
                                apply_room_filters(panoramas[id].filters,'vr');
                                $('#panorama_viewer_vr').animate({
                                    opacity: 1
                                }, { duration: 250, queue: false });
                                $('#panorama_viewer_vr').css('z-index',10);
                                $('#background_pano').fadeOut();
                                $('#background_pano_vr').fadeOut();
                                $('.pnlm-controls-container').hide();
                                $('.map').hide();
                                $('.share_popup').removeClass('show');
                                $('.custom-hotspot-content').css('opacity',0);
                                $('.custom-hotspot-content').css('pointer-events','none');
                                $('.leader-line').css('opacity',0);
                                $('.leader-line').css('pointer-events','none');
                                $('.pnlm-orientation-button').hide();
                                $('.compass_control').hide();
                                clearInterval(interval_position);
                                interval_position = setInterval(function () {
                                    check_vr_pos();
                                },250);
                                setTimeout(function () {
                                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                        pano_viewer.startOrientation();
                                        pano_viewer_vr.startOrientation();
                                    } else {
                                        video_viewer.pnlmViewer.startOrientation();
                                        video_viewer_vr.pnlmViewer.startOrientation();
                                    }
                                    $('.loading_vr').fadeOut();
                                },500);
                            },200);
                        } else {
                            pano_viewer_vr = pannellum.viewer('panorama_viewer_vr', {
                                "id_room": panoramas[id].id,
                                "type": "equirectangular",
                                "panorama": ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_image+((window.s3_enabled) ? '?s3='+s3_version : ''),
                                "backgroundColor": panoramas[id].background_color,
                                "avoidShowingBackground": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "compass": true,
                                "northOffset": panoramas[id].northOffset,
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "multiResMinHfov": true,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov" : max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch" : maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw" : parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots_vr,
                            });
                            pano_viewer_vr.on('load',function () {
                                apply_room_filters(panoramas[id].filters,'vr');
                                $('#panorama_viewer_vr').animate({
                                    opacity: 1
                                }, { duration: 250, queue: false });
                                $('#panorama_viewer_vr').css('z-index',10);
                                $('#background_pano').fadeOut();
                                $('#background_pano_vr').fadeOut();
                                $('.pnlm-controls-container').hide();
                                $('.map').hide();
                                $('.share_popup').removeClass('show');
                                $('.custom-hotspot-content').css('opacity',0);
                                $('.custom-hotspot-content').css('pointer-events','none');
                                $('.leader-line').css('opacity',0);
                                $('.leader-line').css('pointer-events','none');
                                $('.pnlm-orientation-button').hide();
                                $('.compass_control').hide();
                                clearInterval(interval_position);
                                interval_position = setInterval(function () {
                                    check_vr_pos();
                                },250);
                                setTimeout(function () {
                                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                        pano_viewer.startOrientation();
                                        pano_viewer_vr.startOrientation();
                                    } else {
                                        video_viewer.pnlmViewer.startOrientation();
                                        video_viewer_vr.pnlmViewer.startOrientation();
                                    }
                                    $('.loading_vr').fadeOut();
                                },500);
                            });
                        }
                        break;
                    case 'lottie':
                        var img_lottie = new Image();
                        img_lottie.crossOrigin = 'anonymous';
                        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: ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_json+((window.s3_enabled) ? '?s3='+s3_version : ''),
                                rendererSettings: {
                                    context: lottie_context,
                                    progressiveLoad: true,
                                }
                            });
                            pano_viewer_vr = pannellum.viewer('panorama_viewer_vr', {
                                "id_room": panoramas[id].id,
                                "type": "equirectangular",
                                "panorama": canvas,
                                "avoidShowingBackground": true,
                                "dynamic": true,
                                "dynamicUpdate": true,
                                "autoLoad": true,
                                "disableKeyboardCtrl": keyboard_mode,
                                "mouseZoom": window.mouse_zoom,
                                "showZoomCtrl": false,
                                "showFullscreenCtrl": false,
                                "orientationOnByDefault": orientationOnByDefault,
                                "draggable": draggable,
                                "autoRotate": autorotate_speed_f,
                                "autoRotateStopDelay": 10,
                                "autoRotateInactivityDelay": autorotate_inactivity_f,
                                "friction": friction,
                                "zoom_friction": zoom_friction,
                                "touchPanSpeedCoeffFactor": touchPanSpeedCoeffFactor,
                                "compass": true,
                                "northOffset": parseInt(panoramas[id].northOffset),
                                "horizonPitch": parseInt(panoramas[id].h_pitch),
                                "horizonRoll": parseInt(panoramas[id].h_roll),
                                "pitch": pitch,
                                "yaw": workingYaw,
                                "hfov": hfov_f,
                                "origHfov": orig_hfov,
                                "minHfov": min_hfov_f,
                                "maxHfov" : max_hfov_f,
                                "minPitch": minPitch,
                                "maxPitch" : maxPitch,
                                "minYaw": parseInt(panoramas[id].min_yaw),
                                "maxYaw" : parseInt(panoramas[id].max_yaw),
                                "haov": parseInt(panoramas[id].haov),
                                "vaov": parseInt(panoramas[id].vaov),
                                "hotSpots": panoramas[id].hotSpots_vr,
                            });
                            setTimeout(function () {
                                $('#panorama_viewer_vr').animate({
                                    opacity: 1
                                }, { duration: 250, queue: false });
                                $('#panorama_viewer_vr').css('z-index',10);
                                $('#background_pano').fadeOut();
                                $('#background_pano_vr').fadeOut();
                                $('.pnlm-controls-container').hide();
                                $('.map').hide();
                                $('.share_popup').removeClass('show');
                                $('.custom-hotspot-content').css('opacity',0);
                                $('.custom-hotspot-content').css('pointer-events','none');
                                $('.leader-line').css('opacity',0);
                                $('.leader-line').css('pointer-events','none');
                                $('.pnlm-orientation-button').hide();
                                $('.compass_control').hide();
                                clearInterval(interval_position);
                                interval_position = setInterval(function () {
                                    check_vr_pos();
                                },250);
                                setTimeout(function () {
                                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                        pano_viewer.startOrientation();
                                        pano_viewer_vr.startOrientation();
                                    } else {
                                        video_viewer.pnlmViewer.startOrientation();
                                        video_viewer_vr.pnlmViewer.startOrientation();
                                    }
                                    $('.loading_vr').fadeOut();
                                },500);
                            },200);
                        };
                        img_lottie.crossOrigin = false;
                        img_lottie.src = ((window.s3_enabled) ? window.s3_url : '')+panoramas[id].panorama_image;
                        break;
                }
            }
        },0);
    }

    var current_viewer, drag_v = false, start_drag_v, end_drag_v, first_mov_follow_mouse = true, timeout_mov_follow_mouse, timeout_clear_mov_pos_change;
    var current_viewer_pitch=0, current_viewer_yaw=0, x_mouseup=0, y_mouseup=0;
    function register_viewer_listeners(viewer,mfm) {
        current_viewer=viewer;
        window.viewer_mov_follow_mouse = false;
        setTimeout(function() {
            if(!first_mov_follow_mouse && mfm) {
                if(mouse_follow_feedback!=0) {
                    window.viewer_mov_follow_mouse = true;
                }
            }
            document.removeEventListener('mousedown', mouse_down_el);
            document.removeEventListener('mousemove', mouse_move_el);
            document.removeEventListener('mouseup', mouse_up_el_alt);
            document.removeEventListener('mousedown', mouse_down_el_alt);
            if(mfm) {
                document.addEventListener('mousedown', mouse_down_el);
                document.addEventListener('mousemove', mouse_move_el);
            } else {
                document.addEventListener('mousedown', mouse_down_el_alt);
                document.addEventListener('mouseup', mouse_up_el_alt);
                mouse_up_el_alt();
            }
            current_viewer_pitch = parseFloat(viewer.getPitch());
            current_viewer_yaw = parseFloat(viewer.getYaw());
            viewer.on('mousedown',function() {
                window.viewer_mov_follow_mouse = false;
                window.viewer_mov_pos_change = false;
                if(look_target_animating) {
                    look_target_animating = false;
                    current_viewer_pitch = parseFloat(viewer.getPitch());
                    current_viewer_yaw = parseFloat(viewer.getYaw());
                }
            });
            viewer.on('animatefinished', function(event) {
                if(!window.viewer_mov_pos_change) {
                    clearTimeout(timeout_mov_follow_mouse);
                    current_viewer_pitch = parseFloat(event.pitch);
                    current_viewer_yaw = parseFloat(event.yaw);
                    timeout_mov_follow_mouse = setTimeout(function() {
                        if(!first_mov_follow_mouse) {
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        }
                    },15);
                }
            });
            viewer.on('mouseup', viewer_click_listener);
        },250);
    }

    var timout_rotate_alt = null;
    function mouse_down_el_alt() {
        clearTimeout(timout_rotate_alt);
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            var viewer = pano_viewer;
        } else {
            var viewer = video_viewer.pnlmViewer;
        }
        try {
            viewer.stopAutoRotate();
        } catch (e) {}
    }

    function mouse_up_el_alt() {
        var index_current = get_id_viewer(current_id_panorama);
        if(panoramas[index_current].autorotate_override==1) {
            var autorotate_speed_h = panoramas[index_current].autorotate_speed;
            var autorotate_inactivity_h = panoramas[index_current].autorotate_inactivity;
        } else {
            var autorotate_speed_h = autorotate_speed;
            var autorotate_inactivity_h = autorotate_inactivity;
        }
        setTimeout(function() {
            if(controls_status['auto_rotate'] && autorotate_speed_h!=0) {
                clearTimeout(timout_rotate_alt);
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var viewer = pano_viewer;
                } else {
                    var viewer = video_viewer.pnlmViewer;
                }
                viewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                timout_rotate_alt = setTimeout(function () {
                    viewer.startAutoRotate(autorotate_speed_h);
                },autorotate_inactivity_h);
            }
        },100);
    }

    function mouse_down_el() {
        start_drag_v = new Date().getTime();
        drag_v = false;
    }

    function mouse_move_el(event) {
        var viewer=current_viewer;
        end_drag_v = new Date().getTime();
        drag_v = true;
        if(window.viewer_mov_follow_mouse && $('.potree_iframe').length===0 && !live_session_connected && !vr_enabled && !controls_status['presentation'] && !viewer.is_autorotating()) viewer_move_pos_listener(event);
        if(click_anywhere==1 && hide_markers==1 && hover_markers==1) {
            viewer_move_listener(event);
        }
    }

    function viewer_click_listener(event) {
        x_mouseup = event.x;
        y_mouseup = event.y;
        var diff_drag_v = end_drag_v - start_drag_v;
        if(drag_v == false || diff_drag_v < 200) {
            if(click_anywhere==1) {
                if(event.target.className!='pnlm-dragfix' || event.which!=1) return;
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var coords = pano_viewer.mouseEventToCoords(event);
                } else {
                    var coords = video_viewer.pnlmViewer.mouseEventToCoords(event);
                }
                try {
                    var pitch = parseFloat(coords[0]);
                    var yaw = parseFloat(coords[1]);
                    find_nearest_marker(yaw,pitch);
                } catch (e) {}
            }
            if(window.poi_box_open) {
                restart_autorotate();
            }
            if(close_poi_click_outside==1 && event.target.classList.contains('pnlm-dragfix')) {
                close_all_pois();
            }
        } else {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                current_viewer_pitch = parseFloat(pano_viewer.getPitch());
                current_viewer_yaw = parseFloat(pano_viewer.getYaw());
            } else {
                current_viewer_pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
                current_viewer_yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
            }
        }
    }

    function close_all_pois() {
        close_all_poi_box();
        close_all_poi_callout();
        close_all_poi_staging();
    }

    function viewer_move_listener(event) {
        if(click_anywhere==1) {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                var coords = pano_viewer.mouseEventToCoords(event);
            } else {
                var coords = video_viewer.pnlmViewer.mouseEventToCoords(event);
            }
            try {
                var pitch = parseFloat(coords[0]);
                var yaw = parseFloat(coords[1]);
                view_nearest_marker(yaw,pitch);
            } catch (e) {}
        }
    }

    function hasParentWithClass(element, className) {
        let parent = element.parentNode;
        while (parent) {
            if (parent.classList && parent.classList.contains(className)) {
                return true;
            }
            parent = parent.parentNode;
        }
        return false;
    }

    function viewer_move_pos_listener(event) {
        if($('#comments_div').is(':visible')) return;
        if(hasParentWithClass(event.target, 'video-js')) return;
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            var hfov = parseFloat(pano_viewer.getHfov());
        } else {
            var hfov = parseFloat(video_viewer.pnlmViewer.getHfov());
        }
        var w = document.getElementById('vt_container').offsetWidth;
        var h = document.getElementById('vt_container').offsetHeight;
        var x = event.clientX;
        var y = event.clientY;
        if(x_mouseup==0) x_mouseup = x;
        if(y_mouseup==0) y_mouseup = y;
        var diff_x = (x-x_mouseup)/(w/2);
        var diff_y = (y-y_mouseup)/(h/2);
        var x_c = diff_x*(mouse_follow_feedback/1.5)*(hfov/100);
        var y_c = diff_y*(mouse_follow_feedback/2)*(hfov/100);
        var look_yaw = current_viewer_yaw+(x_c);
        var look_pitch = current_viewer_pitch-(y_c);
        window.viewer_mov_pos_change = true;
        clearTimeout(timeout_clear_mov_pos_change);
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.lookAt(look_pitch,look_yaw,hfov,false,function() {
                timeout_clear_mov_pos_change = setTimeout(function() {
                    window.viewer_mov_pos_change = false;
                },100);
            });
        } else {
            video_viewer.pnlmViewer.lookAt(look_pitch,look_yaw,hfov,false,function() {
                timeout_clear_mov_pos_change = setTimeout(function() {
                    window.viewer_mov_pos_change = false;
                },100);
            });
        }
        if(pano_viewer_alt!=null && pano_viewer_alt!==undefined) {
            pano_viewer_alt.lookAt(look_pitch,look_yaw,hfov,false);
        }
        adjust_poi_embed_helpers_all();
        adjust_marker_embed_helpers_all();
        adjust_measurements();
    }

    function close_all_poi_box() {
        $('.box_poi').css({'opacity':0,'pointer-events':'none'});
        window.poi_box_open = false;
        $('.tooltip_text').removeClass('hidden_pb');
        $('.box_poi video').each(function () {
            $(this).trigger('pause');
        });
        $('.box_poi .youtube_video, .box_poi .vimeo_video').each(function () {
            var src = $(this).attr('src');
            $(this).attr('src',src);
        });
    }

    function close_all_poi_callout() {
        $('.callout').each(function () {
            var id = $(this).parent().attr('data-id');
            var open = $(this).parent().attr('data-open');
            if(open!='lookat' && open!='always_open') {
                close_callout(id);
            }
        });
    }

    function close_all_poi_staging() {
        $('.staging_icon').each(function() {
            $(this).WCircleMenu('close');
        });
    }

    function find_nearest_marker(yaw,pitch) {
        var index = get_id_viewer(current_id_panorama);
        var array_coord = [];
        jQuery.each(panoramas[index].hotSpots, function(index, hotspot) {
            if(hotspot.object=='marker' || hotspot.object=='marker_embed') {
                var h_yaw = parseFloat(hotspot.yaw);
                var h_pitch = parseFloat(hotspot.pitch);
                var dist = Math.abs(yaw % 360 - h_yaw % 360);
                dist = Math.min(dist, 360 - dist);
                var dist_coord = Math.sqrt(Math.pow(h_yaw - yaw, 2) + Math.pow(h_pitch - pitch, 2));
                if(dist<=20) {
                    array_coord.push({x:h_yaw,y:h_pitch,dist_coord:dist_coord,hotspot:hotspot});
                }
            }
        });
        if(array_coord.length>0) {
            array_coord.sort((a, b) => a.dist_coord - b.dist_coord);
            goto('',array_coord[0].hotspot.clickHandlerArgs)
        }
    }

    function view_nearest_marker(yaw,pitch) {
        var index = get_id_viewer(current_id_panorama);
        var array_coord = [];
        jQuery.each(panoramas[index].hotSpots, function(index, hotspot) {
            if(hotspot.object=='marker' || hotspot.object=='marker_embed') {
                var h_yaw = parseFloat(hotspot.yaw);
                var h_pitch = parseFloat(hotspot.pitch);
                var id = hotspot.id;
                $('.marker_embed_'+id).addClass('hidden_m');
                $('.marker_'+id).addClass('hidden_m');
                var dist = Math.abs(yaw % 360 - h_yaw % 360);
                dist = Math.min(dist, 360 - dist);
                var dist_coord = Math.sqrt(Math.pow(h_yaw - yaw, 2) + Math.pow(h_pitch - pitch, 2));
                if(dist<=20) {
                    array_coord.push({x:h_yaw,y:h_pitch,dist_coord:dist_coord,id:id});
                }
            }
        });
        if(array_coord.length>0) {
            array_coord.sort((a, b) => a.dist_coord - b.dist_coord);
            $('.marker_'+array_coord[0].id).removeClass('hidden_m');
            $('.marker_embed_'+array_coord[0].id).removeClass('hidden_m');
        }
    }

    window.apply_room_filters = function(filters,w) {
        $('#background_pano').css('filter','none');
        if(filters!='') {
            filters = JSON.parse(filters);
            var filter = '';
            if(filters.brightness!=100) {
                filter += 'brightness('+filters.brightness+'%) ';
            }
            if(filters.contrast!=100) {
                filter += 'contrast('+filters.contrast+'%) ';
            }
            if(filters.saturate!=100) {
                filter += 'saturate('+filters.saturate+'%) ';
            }
            if(filters.grayscale!=0) {
                filter += 'grayscale('+filters.grayscale+'%) ';
            }
            switch(w) {
                case 'pano':
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var canvas = pano_viewer.getRenderer().getCanvas();
                    } else {
                        var canvas = video_viewer.pnlmViewer.getRenderer().getCanvas();
                    }
                    canvas.style.filter = filter;
                    break;
                case 'vr':
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var canvas_vr = pano_viewer_vr.getRenderer().getCanvas();
                    } else {
                        var canvas_vr = video_viewer_vr.pnlmViewer.getRenderer().getCanvas();
                    }
                    canvas_vr.style.filter = filter;
                    break;
            }
            $('#background_pano').css('filter',filter);
        }
    }

    function init_vs_drag() {
        $("#vs_grab").draggable({
            axis: "x",
            drag: function( event, ui ) {
                var width = $("#vt_container").width();
                var margin_left = width*0.05;
                var margin_right = width*0.95;
                if(ui.position.left<=margin_left) ui.position.left=margin_left;
                if(ui.position.left>=margin_right) ui.position.left=margin_right;
                var grab_width = $('#vs_grab').width();
                var slider_width = $('#vs_slider').width();
                var pos_left = ui.position.left+(grab_width/2)-(slider_width/2);
                var perc_left = 100 - (((width - pos_left) / width) * 100);
                $('#vs_slider').css('left',perc_left+'%');
                $('#vs_before').css('width',perc_left+'%');
                if(live_session_connected) {
                    try {
                        peer_conn.send({type:'drag_vs',args:perc_left});
                    } catch (e) {}
                }
            }
        });
    }

    function initialize_virtual_staging(id,id_room_alt,click_m) {
        window.sync_virtual_staging_enabled=false;
        if(id_room_alt!=null && virtual_staging) {
            $('#vs_before').show();
            $('#vs_slider').fadeIn();
            $('#vs_grab').fadeIn();
            init_vs_drag();
            $('#panorama_viewer_alt').css('z-index',0);
            $('#panorama_viewer_alt').css('opacity',0);
            pano_viewer_alt = pannellum.viewer('panorama_viewer_alt', config_alt);
            var multires = panoramas[id].multires;
            if(multires) {
                setTimeout(function () {
                    sync_virtual_staging(id,click_m);
                    setTimeout(function() {
                        initialize_measures_alt(id);
                        var poi_embed_count = $('.poi_embed').length;
                        if(poi_embed_count>0) {
                            init_poi_embed();
                        }
                    },250);
                },200)
            } else {
                pano_viewer_alt.on('load',function () {
                    sync_virtual_staging(id,click_m);
                    setTimeout(function() {
                        initialize_measures_alt(id);
                        var poi_embed_count = $('.poi_embed').length;
                        if(poi_embed_count>0) {
                            init_poi_embed();
                        }
                    },250);
                });
            }
        } else {
            $('#vs_before').hide();
            $('#vs_slider').fadeOut();
            $('#vs_grab').fadeOut();
        }
    }

    function sync_virtual_staging(id,click_m) {
        $('.pnlm-controls-container').hide();
        if(window.flyin==0) {
            $('#panorama_viewer').css('z-index',10);
            $('#panorama_viewer').css('opacity',1);
            $('#panorama_viewer_alt').css('z-index',10);
            $('#panorama_viewer_alt').css('opacity',1);
        }
        if(panoramas[id].transition_override==1) {
            var transition_fadeout_r = panoramas[id].transition_fadeout;
            var transition_effect_r = panoramas[id].transition_effect;
            var transition_hfov_r = panoramas[id].transition_hfov;
            var transition_hfov_time_r = panoramas[id].transition_hfov_time;
        } else {
            var transition_fadeout_r = transition_fadeout;
            var transition_effect_r = transition_effect;
            var transition_hfov_r = transition_hfov;
            var transition_hfov_time_r = transition_hfov_time;
        }
        if(!click_m) {
            transition_effect_r = 'fade';
            transition_fadeout_r = 0;
            transition_hfov_r = 0;
            transition_hfov_time_r = 0;
        }
        switch (transition_effect_r) {
            case 'drop':
                var effect_options = {direction: "down"};
                break;
            case 'blind':
                var effect_options = {direction: "down"};
                break;
            case 'scale':
                var effect_options = {percent: 10};
                break;
            default:
                var effect_options = {};
                break;
        }
        $('#background_pano').effect(transition_effect_r, effect_options, transition_fadeout_r,function () {
            var filters = $('#background_pano').css('filter');
            $('#background_pano').removeAttr('style');
            $('#background_pano').css('filter',filters);
            $('#background_pano').css('z-index',0);
            if(!panoramas[id].protected) {
                var filters = $('#background_pano').css('filter');
                filters = filters.replace('blur(16px)','');
                $('#background_pano').css('filter',filters);
            }
        });
        if(transition_hfov_r!=0 && transition_hfov_time_r>0) {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                try {
                    var hfov_r = parseInt(pano_viewer.getHfov());
                    var yaw_r = parseFloat(pano_viewer.getYaw());
                    var pitch_r = parseFloat(pano_viewer.getPitch());
                    transition_hfov_r = hfov_r + (hfov_r*(transition_hfov_r/100));
                    var hfov_bounds_o = pano_viewer.getHfovBounds();
                    var min_hfov_o = hfov_bounds_o[0];
                    var max_hfov_o = hfov_bounds_o[1];
                    var min_hfov_r = min_hfov_o;
                    var max_hfov_r = max_hfov_o;
                    if(transition_hfov_r>max_hfov_o) {
                        max_hfov_r=transition_hfov_r;
                    }
                    if(transition_hfov_r<min_hfov_o) {
                        min_hfov_r=transition_hfov_r;
                    }
                    if(max_hfov_r>160) max_hfov_r=160;
                    if(min_hfov_r<20) min_hfov_r=20;
                    pano_viewer.setHfovBounds([min_hfov_r,max_hfov_r]);
                    pano_viewer.setHfov(transition_hfov_r,false);
                    pano_viewer.lookAt(pitch_r,yaw_r,hfov_r,transition_hfov_time_r,function() {
                        pano_viewer.setHfovBounds([min_hfov_o,max_hfov_o]);
                    });
                } catch (e) {}
            } else {
                try {
                    var hfov_r = parseInt(video_viewer.pnlmViewer.getHfov());
                    var yaw_r = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var pitch_r = parseFloat(video_viewer.pnlmViewer.getPitch());
                    transition_hfov_r = hfov_r + (hfov_r*(transition_hfov_r/100));
                    var hfov_bounds_o = video_viewer.pnlmViewer.getHfovBounds();
                    var min_hfov_o = hfov_bounds_o[0];
                    var max_hfov_o = hfov_bounds_o[1];
                    var min_hfov_r = min_hfov_o;
                    var max_hfov_r = max_hfov_o;
                    if(transition_hfov_r>max_hfov_o) {
                        max_hfov_r=transition_hfov_r;
                    }
                    if(transition_hfov_r<min_hfov_o) {
                        min_hfov_r=transition_hfov_r;
                    }
                    if(max_hfov_r>160) max_hfov_r=160;
                    if(min_hfov_r<20) min_hfov_r=20;
                    video_viewer.pnlmViewer.setHfovBounds([min_hfov_r,max_hfov_r]);
                    video_viewer.pnlmViewer.setHfov(hfov_r+transition_hfov_r,false);
                    video_viewer.pnlmViewer.lookAt(pitch_r,yaw_r,hfov_r,transition_hfov_time_r,function() {
                        video_viewer.pnlmViewer.setHfovBounds([min_hfov_o,max_hfov_o]);
                    });
                } catch (e) {}
            }
        }
        if (!controls_status['measures']) {
            $('.leader-line').addClass('hidden_icons');
        } else {
            $('.leader-line').removeClass('hidden_icons');
        }
        if (!controls_status['icons_content']) {
            $('.custom-hotspot-content').addClass('hidden_icons');
            $('.poi_embed').addClass('hidden_icons');
        } else {
            $('.custom-hotspot-content').removeClass('hidden_icons');
            $('.poi_embed').removeClass('hidden_icons');
        }
        if (!controls_status['icons_nav']) {
            $('.custom-hotspot').addClass('hidden_icons');
            $('.custom-hotspot img').addClass('hidden_icons');
            $('.marker_embed').addClass('hidden_icons');
        } else {
            $('.custom-hotspot').removeClass('hidden_icons');
            $('.custom-hotspot img').removeClass('hidden_icons');
            $('.marker_embed').removeClass('hidden_icons');
        }
        window.sync_virtual_staging_enabled=true;
    }

    window.sync_virtual_staging_view = function () {
        var width = $("#vt_container").width();
        $('#panorama_viewer_alt').css('width',width+'px');
        var yaw = parseFloat(pano_viewer.getYaw());
        var pitch = parseFloat(pano_viewer.getPitch());
        var hfov = parseFloat(pano_viewer.getHfov());
        try {
            pano_viewer_alt.lookAt(pitch,yaw,hfov,false);
        } catch (e) {}
    }

    function player_initialized(cb,id,stats,id_room_alt,dh,click_m) {
        look_target_animating = false;
        x_mouseup=0;
        y_mouseup=0;
        if(!controls_status['auto_rotate']) {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                try { pano_viewer.stopAutoRotate(); } catch (e) {}
            } else {
                try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
            }
        }
        $('.leader-line').remove();
        initialize_measures(id);
        var index_room_alt_auto_open = null;
        if(!controls_status['presentation'] && !live_session_connected && !vr_enabled && !first_change_rooms_alt) {
            if(ObjectLength(panoramas[id].array_rooms_alt)>0) {
                jQuery.each(panoramas[id].array_rooms_alt, function (index_alt, room_alt) {
                    if (room_alt.auto_open==1) {
                        first_change_rooms_alt = true;
                        index_room_alt_auto_open = index_alt;
                    }
                });
            }
        }
        if(index_room_alt_auto_open===null) initialize_virtual_staging(id,id_room_alt,click_m);
        if(schedule_enabled) {
            check_pois_schedule(panoramas[id].id);
            clearInterval(interval_check_pois_schedule);
            interval_check_pois_schedule = setInterval(function () {
                check_pois_schedule(panoramas[id].id);
            },15000);
        }
        view_protect_form(cb,id);
        if(map_tour_l!=null) {
            select_map_tour_point();
        }
        if(cb) {
            if(!window.changed_room_alt && !window.changed_room_alt_poi) adjust_ratio_hfov();
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                if(id_room_alt==null || virtual_staging==false) {
                    if(window.flyin==0) {
                        $('#panorama_viewer').css('z-index',10);
                        $('#panorama_viewer').css('opacity',1);
                    }
                }
            } else {
                $('#video_viewer').css('z-index',10);
                $('#video_viewer').css('opacity',1);
            }
            if(!vr_enabled) {
                if(id_room_alt==null || virtual_staging==false) {
                    if(panoramas[id].transition_override==1) {
                        var transition_fadeout_r = panoramas[id].transition_fadeout;
                        var transition_effect_r = panoramas[id].transition_effect;
                        var transition_hfov_r = panoramas[id].transition_hfov;
                        var transition_hfov_time_r = panoramas[id].transition_hfov_time;
                    } else {
                        var transition_fadeout_r = transition_fadeout;
                        var transition_effect_r = transition_effect;
                        var transition_hfov_r = transition_hfov;
                        var transition_hfov_time_r = transition_hfov_time;
                    }
                    switch (transition_effect_r) {
                        case 'drop':
                            var effect_options = {direction: "down"};
                            break;
                        case 'scale':
                            var effect_options = {percent: 10};
                            break;
                        default:
                            var effect_options = {};
                            break;
                    }
                    if(dh || window.changed_room_alt_poi || window.changed_room_alt) {
                        transition_effect_r = 'fade';
                        transition_fadeout_r = 0;
                        transition_hfov_r = 0;
                        transition_hfov_time_r = 0;
                    }
                    if(!click_m || controls_status['orient']) {
                        transition_hfov_r = 0;
                        transition_hfov_time_r = 0;
                    }
                    $('#background_pano').effect(transition_effect_r, effect_options, transition_fadeout_r,function () {
                        var filters = $('#background_pano').css('filter');
                        $('#background_pano').removeAttr('style');
                        $('#background_pano').css('filter',filters);
                        $('#background_pano').css('z-index',0);
                        if(!panoramas[id].protected) {
                            var filters = $('#background_pano').css('filter');
                            filters = filters.replace('blur(16px)','');
                            $('#background_pano').css('filter',filters);
                        }
                    });
                    window.viewer_mov_pos_change = false;
                    window.viewer_mov_follow_mouse = false;
                    $('#div_panoramas').css('pointer-events','none');
                    $('.pnlm-dragfix').css('pointer-events','none');
                    if(transition_hfov_r!=0 && transition_hfov_time_r>0) {
                        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                            try {
                                var hfov_r = parseInt(pano_viewer.getHfov());
                                var yaw_r = parseFloat(pano_viewer.getYaw());
                                var pitch_r = parseFloat(pano_viewer.getPitch());
                                transition_hfov_r = hfov_r + (hfov_r*(transition_hfov_r/100));
                                var hfov_bounds_o = pano_viewer.getHfovBounds();
                                var min_hfov_o = hfov_bounds_o[0];
                                var max_hfov_o = hfov_bounds_o[1];
                                var min_hfov_r = min_hfov_o;
                                var max_hfov_r = max_hfov_o;
                                if(transition_hfov_r>max_hfov_o) {
                                    max_hfov_r=transition_hfov_r;
                                }
                                if(transition_hfov_r<min_hfov_o) {
                                    min_hfov_r=transition_hfov_r;
                                }
                                if(max_hfov_r>160) max_hfov_r=160;
                                if(min_hfov_r<20) min_hfov_r=20;
                                pano_viewer.setHfovBounds([min_hfov_r,max_hfov_r]);
                                pano_viewer.setHfov(transition_hfov_r,false);
                                pano_viewer.lookAt(pitch_r,yaw_r,hfov_r,transition_hfov_time_r,function() {
                                    window.viewer_mov_pos_change = false;
                                    window.viewer_mov_follow_mouse = false;
                                    $('#div_panoramas').css('pointer-events','initial');
                                    $('.pnlm-dragfix').css('pointer-events','initial');
                                    pano_viewer.setHfovBounds([min_hfov_o,max_hfov_o]);
                                    if(look_room_target['yaw']!==undefined) {
                                        look_target_animating = true;
                                        pano_viewer.lookAt(look_room_target['pitch'],look_room_target['yaw'],hfov_r,look_room_target['duration'],function() {
                                            if(look_target_animating) {
                                                current_viewer_pitch = parseFloat(look_room_target['pitch']);
                                                current_viewer_yaw = parseFloat(look_room_target['yaw']);
                                            }
                                            look_target_animating = false;
                                            window.viewer_mov_pos_change = true;
                                            if(mouse_follow_feedback!=0) {
                                                window.viewer_mov_follow_mouse = true;
                                            }
                                        });
                                    } else {
                                        window.viewer_mov_pos_change = true;
                                        current_viewer_pitch = parseFloat(look_room_target['pitch']);
                                        current_viewer_yaw = parseFloat(look_room_target['yaw']);
                                        if(mouse_follow_feedback!=0) {
                                            window.viewer_mov_follow_mouse = true;
                                        }
                                    }
                                });
                            } catch (e) {}
                        } else {
                            try {
                                var hfov_r = parseInt(video_viewer.pnlmViewer.getHfov());
                                var yaw_r = parseFloat(video_viewer.pnlmViewer.getYaw());
                                var pitch_r = parseFloat(video_viewer.pnlmViewer.getPitch());
                                transition_hfov_r = hfov_r + (hfov_r*(transition_hfov_r/100));
                                var hfov_bounds_o = video_viewer.pnlmViewer.getHfovBounds();
                                var min_hfov_o = hfov_bounds_o[0];
                                var max_hfov_o = hfov_bounds_o[1];
                                var min_hfov_r = min_hfov_o;
                                var max_hfov_r = max_hfov_o;
                                if(transition_hfov_r>max_hfov_o) {
                                    max_hfov_r=transition_hfov_r;
                                }
                                if(transition_hfov_r<min_hfov_o) {
                                    min_hfov_r=transition_hfov_r;
                                }
                                if(max_hfov_r>160) max_hfov_r=160;
                                if(min_hfov_r<20) min_hfov_r=20;
                                video_viewer.pnlmViewer.setHfovBounds([min_hfov_r,max_hfov_r]);
                                video_viewer.pnlmViewer.setHfov(hfov_r+transition_hfov_r,false);
                                video_viewer.pnlmViewer.lookAt(pitch_r,yaw_r,hfov_r,transition_hfov_time_r,function() {
                                    window.viewer_mov_pos_change = false;
                                    window.viewer_mov_follow_mouse = false;
                                    $('#div_panoramas').css('pointer-events','initial');
                                    $('.pnlm-dragfix').css('pointer-events','initial');
                                    video_viewer.pnlmViewer.setHfovBounds([min_hfov_o,max_hfov_o]);
                                    if(look_room_target['yaw']!==undefined) {
                                        look_target_animating = true;
                                        video_viewer.pnlmViewer.lookAt(look_room_target['pitch'],look_room_target['yaw'],hfov_r,look_room_target['duration'],function() {
                                            if(look_target_animating) {
                                                current_viewer_pitch = parseFloat(look_room_target['pitch']);
                                                current_viewer_yaw = parseFloat(look_room_target['yaw']);
                                            }
                                            look_target_animating = false;
                                            window.viewer_mov_pos_change = true;
                                            if(mouse_follow_feedback!=0) {
                                                window.viewer_mov_follow_mouse = true;
                                            }
                                        });
                                    } else {
                                        window.viewer_mov_pos_change = true;
                                        current_viewer_pitch = parseFloat(look_room_target['pitch']);
                                        current_viewer_yaw = parseFloat(look_room_target['yaw']);
                                        if(mouse_follow_feedback!=0) {
                                            window.viewer_mov_follow_mouse = true;
                                        }
                                    }
                                });
                            } catch (e) {}
                        }
                    } else {
                        if(look_room_target['yaw']!==undefined) {
                            look_target_animating = true;
                            pano_viewer.lookAt(look_room_target['pitch'],look_room_target['yaw'],hfov_r,look_room_target['duration'],function() {
                                if(look_target_animating) {
                                    current_viewer_pitch = parseFloat(look_room_target['pitch']);
                                    current_viewer_yaw = parseFloat(look_room_target['yaw']);
                                }
                                look_target_animating = false;
                                window.viewer_mov_pos_change = true;
                                if(mouse_follow_feedback!=0) {
                                    window.viewer_mov_follow_mouse = true;
                                }
                                $('#div_panoramas').css('pointer-events','initial');
                                $('.pnlm-dragfix').css('pointer-events','initial');
                            });
                        } else {
                            $('#div_panoramas').css('pointer-events','initial');
                            $('.pnlm-dragfix').css('pointer-events','initial');
                        }
                    }
                } else {
                    $('#div_panoramas').css('pointer-events','initial');
                    $('.pnlm-dragfix').css('pointer-events','initial');
                }
            } else {
                $('#div_panoramas').css('pointer-events','initial');
                $('.pnlm-dragfix').css('pointer-events','initial');
            }
            if(array_maps.length>0) {
                $('.all_maps').hide();
                $('.map_pointer_container').hide();
                var id_map_target = panoramas[id].id_map;
                if(!isNaN(id_map_target)) {
                    id_current_map = id_map_target;
                    $('.map_'+id_map_target).show();
                    $('.pointer_map_'+id_map_target).show();
                } else {
                    $('.map_'+id_current_map).show();
                    $('.pointer_map_'+id_current_map).show();
                }
                for(var k=0; k < array_maps.length; k++) {
                    if(array_maps[k].id==id_current_map) {
                        if(array_maps[k].info_link!='') {
                            var info_map = '&nbsp;&nbsp;<i onclick="open_info_map(\''+array_maps[k].info_link+'\',\''+array_maps[k].info_type+'\');" class="fas fa-info-circle info_map_btn"></i>';
                        } else {
                            var info_map = '';
                        }
                        $('.map_name').html(array_maps[k].name+info_map);
                    }
                }
                if(controls_status['map']) {
                    resize_maps();
                }
            }
            if(panoramas[id].visible_list) {
                var id_category = $('.pointer_list_'+panoramas[id].id).attr('data-id-category');
                slider_index = $('.pointer_list_'+panoramas[id].id).attr('data-index_id');
                if(id_category==0) {
                    try {
                        if(auto_show_slider!=2) sly.toCenter(slider_index);
                    } catch (e) {}
                } else {
                    var slider_index_cat = $('.pointer_list_cat_'+id_category).attr('data-index_id');
                    try {
                        if(auto_show_slider!=2) sly_cat[id_category].toCenter(slider_index);
                    } catch (e) {}
                    try {
                        if(auto_show_slider!=2) sly.toCenter(slider_index_cat);
                    } catch (e) {}
                }
            }
            var annotation_title = panoramas[id].annotation_title;
            var annotation_description = panoramas[id].annotation_description;
            if(((annotation_title!='') || (annotation_description!='')) && (show_annotations!=0)) {
                var a_both = 0;
                if(annotation_title!='') {
                    $('.annotation_title').html(annotation_title);
                    a_both++;
                }
                if(annotation_description!='') {
                    $('.annotation_description').html(annotation_description);
                    a_both++;
                }
                if(a_both==2) {
                    $('.annotation hr').show();
                } else {
                    $('.annotation hr').hide();
                }
                $('.annotation').show();
            } else {
                $('.annotation').hide();
            }
            audio_player_room.pause();
            if (typeof audio_player_room.loop == 'boolean') {
                if(parseInt(panoramas[id].song_loop)==1) {
                    audio_player_room.loop = true;
                } else {
                    audio_player_room.loop = false;
                }
            }
            song_bg_volume_sel = main_song_bg_volume;
            if(controls_status['song']) {
                //set_audio_volume(main_song_bg_volume,-1);
            } else {
                //mute_audio(true,true,0);
            }
            if(panoramas[id].audio_track_enable) {
                unmute_audio(true,true);
                set_audio_volume(panoramas[id].song_bg_volume,-1);
                song_bg_volume_sel = panoramas[id].song_bg_volume;
            }
            if(panoramas[id].song!='' && controls_status['song']) {
                if(panoramas[id].song_once==0 || (panoramas[id].song_once==1 && !panoramas[id].song_played)) {
                    //mute_audio(true,true);
                    audio_player_room.src = ((window.s3_enabled) ? window.s3_url : '')+"content/"+encodeURIComponent(panoramas[id].song);
                    audio_player_room.load();
                    audio_player_room.play().catch(function() {
                        $(document).one("mousedown touchstart",function(e){
                            audio_player_room.play();
                            panoramas[id].song_played = true;
                            if(is_iOS()) {
                                if(controls_status['song']) audio_player_room.muted = false;
                            }
                            //fadeVolume(audio_player_room, panoramas[id].song_volume, 500);
                            set_audio_volume(panoramas[id].song_bg_volume,panoramas[id].song_volume);
                            song_bg_volume_sel = panoramas[id].song_bg_volume;
                        });
                    }).then(function() {
                        if(is_iOS()) {
                            if(controls_status['song']) audio_player_room.muted = false;
                        }
                        //fadeVolume(audio_player_room, panoramas[id].song_volume, 500);
                        set_audio_volume(panoramas[id].song_bg_volume,panoramas[id].song_volume);
                        song_bg_volume_sel = panoramas[id].song_bg_volume;
                    });
                    if(panoramas[id].song_loop==0) {
                        audio_player_room.addEventListener('ended', function() {
                            song_bg_volume_sel = main_song_bg_volume;
                            if(controls_status['song']) fadeVolume(audio_player, main_song_bg_volume, 500);
                        }, false);
                    }
                }
            }
            if(!vr_enabled) {
                var poi_embed_count = $('.poi_embed').length;
                if(poi_embed_count>0) {
                    init_poi_embed();
                }
            }
            var marker_embed_count = $('.marker_embed').length;
            if(marker_embed_count>0) {
                init_marker_embed();
            }
        }
        $('.panorama').css('z-index','unset');
        poi_open = false;
        if (!controls_status['icons_content']) {
            if(!controls_status['presentation']) {
                $('.custom-hotspot-content').addClass('hidden_icons');
                $('.poi_embed').addClass('hidden_icons');
            } else {
                if(presentation_view_pois==0) {
                    $('.custom-hotspot-content').addClass('hidden_icons');
                    $('.poi_embed').addClass('hidden_icons');
                }
                $('.callout').css('pointer-events','none');
            }
        } else {
            $('.custom-hotspot-content').removeClass('hidden_icons');
            $('.poi_embed').removeClass('hidden_icons');
            if(vr_enabled) {
                $('.custom-hotspot-content').addClass('hidden_icons');
                $('.hotspot-visitor').css({'opacity':0});
                $('.hotspot-visitor-alt').css({'opacity':0});
            } else {
                $('.custom-hotspot-content').removeClass('hidden_icons');
            }
            setTimeout(function () {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    pano_viewer.resize();
                } else {
                    video_viewer.pnlmViewer.resize();
                }
            },50);
        }
        if (!controls_status['icons_nav']) {
            $('.custom-hotspot').addClass('hidden_icons');
            $('.custom-hotspot img').addClass('hidden_icons');
            $('.marker_embed').addClass('hidden_icons');
        } else {
            $('.custom-hotspot').removeClass('hidden_icons');
            $('.custom-hotspot img').removeClass('hidden_icons');
            $('.marker_embed').removeClass('hidden_icons');
            setTimeout(function () {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    pano_viewer.resize();
                } else {
                    video_viewer.pnlmViewer.resize();
                }
            },50);
        }
        if (!controls_status['measures']) {
            if(!controls_status['presentation']) {
                $('.leader-line').addClass('hidden_icons');
            } else {
                if(presentation_view_measures==0) {
                    $('.leader-line').addClass('hidden_icons');
                }
            }
        } else {
            $('.leader-line').removeClass('hidden_icons');
            if(vr_enabled) {
                $('.leader-line').addClass('hidden_icons');
            } else {
                $('.leader-line').removeClass('hidden_icons');
            }
        }
        if(show_compass && !vr_enabled) {
            $('.compass_control').css('display','inline-block');
        } else {
            $('.compass_control').hide();
        }
        if(controls_status['presentation']) {
            if(current_panorama_type=='video') {
                $('.vjs-control-bar').css({'opacity':0,'pointer-events':'none'});
            }
            if(presentation_type=='automatic') {
                automatic_presentation_steps(id);
            } else {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    try { pano_viewer.stopAutoRotate(); } catch (e) {}
                } else {
                    try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
                }
                if(presentation_goto_index!=null) {
                    if(current_panorama_type=='video' && presentation_video_wait_end==1 && !presentation_video_playing) {
                        presentation_video_playing = true;
                        setTimeout(function () {
                            presentation_steps(presentation_goto_index);
                        },presentation_goto_sleep_ms);
                        video_viewer.on("ended",function(){
                            presentation_video_playing = false;
                        });
                    } else {
                        setTimeout(function () {
                            presentation_steps(presentation_goto_index);
                        },presentation_goto_sleep_ms);
                    }
                }
            }
            $('.custom-hotspot').addClass('hidden_icons');
            $('.custom-hotspot img').addClass('hidden_icons');
            $('.marker_embed').addClass('hidden_icons');
            $('.compass_control').hide();
            $('.pnlm-dragfix').css('pointer-events','none');
        } else {
            if(panoramas[id].video_end_goto!=0) {
                try {
                    video_viewer.play();
                } catch (e) {}
                video_viewer.on("ended",function(){
                    var index = get_id_viewer(panoramas[id].video_end_goto);
                    goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                });
            }
        }
        if(!vr_enabled) {
            $('#loading_pano').css('opacity',0);
            $('#loading_pano').hide();
            $('.map_pointer_container').removeClass('active');
            $('#pointer_f_'+panoramas[id].id).addClass('active');
            if(!live_session_connected) {
                clearInterval(interval_position);
                interval_position = setInterval(function () {
                    check_pano_pos();
                },500);
            }
            var callout_exist = false;
            if(panoramas[id].hotSpots.length>0) {
                jQuery.each(panoramas[id].hotSpots, function(index_h, hotspot) {
                    if (hotspot.type == 'callout') {
                        callout_exist = true;
                    }
                });
            }
            clearInterval(interval_callout);
            if(callout_exist) {
                interval_callout = setInterval(function () {
                    check_callout_pos();
                },250);
            }
        }
        if(panoramas[id].virtual_staging==2 && cb) {
            mrv_initialized = 1;
            next_mrv_panorama(panoramas[id].lp_duration,panoramas[id].lp_fade);
        }
        init_effect(panoramas[id].effect);
        if($('.list_sliders').css('opacity')==1) {
            reposition_bottom_controls(true,false,0);
        } else {
            reposition_bottom_controls(false,false,0);
        }
        $('.pnlm-orientation-button').hide();
        $('#compass_icon').attr('onclick','set_initial_pos('+id+');');
        if(!controls_status['presentation'] && stats && !window.changed_room_alt && !window.changed_room_alt_poi) {
            if(window.export_mode==0 && window.preview==0 && window.nostat==0) {
                Pace.ignore(function(){
                    $.ajax({
                        url: "ajax/set_statistics.php",
                        type: "POST",
                        data: {
                            type: 'room',
                            id: panoramas[id].id,
                            ip_visitor: window.ip_visitor
                        },
                        async: true
                    });
                });
            }
        }
        window.changed_room_alt = false;
        window.changed_room_alt_poi = false;
        if(!live_session_connected && !vr_enabled && !controls_status['presentation']) {
            if(panoramas[id].id_poi_autoopen!=null) {
                setTimeout(function () {
                    $('.hotspot_'+panoramas[id].id_poi_autoopen).trigger('click');
                    $('.hotspot_alt'+panoramas[id].id_poi_autoopen).trigger('click');
                    $('.hotspot_'+panoramas[id].id_poi_autoopen+' a').trigger('click');
                    $('.hotspot_alt'+panoramas[id].id_poi_autoopen+' a').trigger('click');
                    try { $('.hotspot_'+panoramas[id].id_poi_autoopen)[0].dispatchEvent(event_simulate_click); } catch (e) {}
                    try { $('.hotspot_alt'+panoramas[id].id_poi_autoopen)[0].dispatchEvent(event_simulate_click); } catch (e) {}
                    try { $('.hotspot_'+panoramas[id].id_poi_autoopen+' a')[0].dispatchEvent(event_simulate_click); } catch (e) {}
                    try { $('.hotspot_alt'+panoramas[id].id_poi_autoopen+' a')[0].dispatchEvent(event_simulate_click); } catch (e) {}
                },1000);
            }
            setTimeout(function() {
                $.each(panoramas[id].hotSpots,function(index_h,hs) {
                    if(hs.type=='grouped' && hs.createTooltipArgs.params!='') {
                        var params = hs.createTooltipArgs.params.split(",");
                        var grouped_open = parseInt(params[0]);
                        if(grouped_open==1) {
                            $('.hotspot_'+hs.id).trigger('click');
                            $('.hotspot_alt'+hs.id).trigger('click');
                            try { $('.hotspot_'+hs.id)[0].dispatchEvent(event_simulate_click); } catch (e) {}
                            try { $('.hotspot_alt'+hs.id)[0].dispatchEvent(event_simulate_click); } catch (e) {}
                        }
                    }
                });
            },1000);
        }
        adjust_elements_positions();
        if(stats) {
            clearInterval(interval_access_time_avg);
            access_time_avg = 0;
            access_time_id = panoramas[id].id;
            interval_access_time_avg = setInterval(function () {
                access_time_avg = access_time_avg + 1;
            }, 1000);
        }
        try {
            var pointer_color_active = Number("0x"+array_dollhouse.settings.pointer_color_active);
            var pointer_color = Number("0x"+array_dollhouse.settings.pointer_color);
            for(var i=0; i<pointers_c_dollhouse.length; i++) {
                var id_dh = pointers_c_dollhouse[i].userData.id;
                if(panoramas[id].id==id_dh) {
                    pointers_c_dollhouse[i].material.color.setHex(pointer_color_active);
                    pointers_t_dollhouse[i].material.color.setHex(pointer_color_active);
                } else {
                    pointers_c_dollhouse[i].material.color.setHex(pointer_color);
                    pointers_t_dollhouse[i].material.color.setHex(pointer_color);
                }
            }
        } catch (e) {}
        if(!dollhouse_open) {
            set_dollhouse_position(panoramas[id].id);
        }
        $('.pnlm-container').trigger('click');
        if(live_session_connected) {
            clearInterval(interval_live_session);
            interval_live_session = setInterval(function () {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw = parseFloat(pano_viewer.getYaw());
                    var pitch = parseFloat(pano_viewer.getPitch());
                    var hfov = parseFloat(pano_viewer.getHfov());
                } else {
                    var yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
                    var hfov = parseFloat(video_viewer.pnlmViewer.getHfov());
                }
                try {
                    peer_conn.send({type:'lookAt',yaw:yaw,pitch:pitch,hfov:hfov});
                } catch (e) {}
            },1000);
        }
        if(!controls_status['presentation'] && !vr_enabled && window.preview_presentation==-1) {
            $('.rooms_view_sel').show();
        }
        if(cb && window.export_mode==0 && window.preview==0 && window.nostat==0 && window.ip_visitor!='') {
            exec_store_visitor(true);
        }
        if(index_room_alt_auto_open!==null) {
            setTimeout(function() {
                change_room_alt(index_room_alt_auto_open);
            },(cb) ? 250 : 1500);
        }
        if(live_session_connected) {
            if($('.live_status').is(':visible')) {
                var height_h = $('.name_vt').outerHeight()+$('.room_vt').outerHeight()+$('.category_room_vt').outerHeight()+$('.comments_vt').outerHeight()+$('.rooms_view_sel').outerHeight()+10;
                $('.live_status').css('top',height_h+'px');
            }
        }
        if(!cb && window.initial_hfov!=='') {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                try { pano_viewer.setHfov(window.initial_hfov,false); } catch (e) {}
            } else {
                try { video_viewer.pnlmViewer.setHfov(window.initial_hfov,false); } catch (e) {}
            }
        }
        if(cb && !main_avtar_video_playing) {
            try {
                var video = $('.avatar_video video')[0];
                video.currentTime = 0;
                video.pause();
            } catch (e) {}
            $('.avatar_video').hide();
            $('.avatar_video').css('opacity', 0);
            var room_avatar_video = '';
            if(panoramas[id].avatar_video!='') {
                room_avatar_video = panoramas[id].avatar_video;
            }
            if(!controls_status['presentation'] && !live_session_connected) {
                if(show_avatar_video && room_avatar_video!='') {
                    if((panoramas[id].avatar_video_play_once==1 && panoramas[id].avatar_video_played==0) || (panoramas[id].avatar_video_play_once==0)) {
                        initialize_avatar_video('room',id,room_avatar_video,panoramas[id].avatar_video_autoplay,panoramas[id].avatar_video_hide_end,panoramas[id].avatar_video_pause);
                    }
                }
            }
        }
        if(panoramas[id].autorotate_override==1) {
            var autorotate_speed_h = panoramas[id].autorotate_speed;
            var autorotate_inactivity_h = panoramas[id].autorotate_inactivity;
        } else {
            var autorotate_speed_h = autorotate_speed;
            var autorotate_inactivity_h = autorotate_inactivity;
        }
        if(controls_status['auto_rotate'] && window.flyin==0 && initial_feedback==0 && show_presentation!=2 && !live_session_connected && autorotate_inactivity_h>0 && autorotate_speed_h!=0 && !cb) {
            setTimeout(function () {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    try {
                        pano_viewer.stopAutoRotate();
                        pano_viewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                    } catch (e) {}
                } else {
                    try {
                        video_viewer.pnlmViewer.stopAutoRotate();
                        video_viewer.pnlmViewer.setAutoRotateInactivityDelay(autorotate_inactivity_h);
                    } catch (e) {}
                }
            },1000);
        }
        if(window.learning_mode>0 && cb) {
            calculate_learning_score(0);
            calculate_learning_score(panoramas[id].id);
            save_learning_log(0);
        }
        if(window.learning_mode>0) {
            if(window.learning_unlock_marker) {
                if(count_learning_poi_in_room(panoramas[id].id) == 0) {
                    $.each(learning_marker_room[panoramas[id].id],function(id_marker_room,id_room_target) {
                        id_room_target = parseInt(id_room_target);
                        if(!learning_room_enabled.includes(id_room_target)) learning_room_enabled.push(id_room_target);
                        $('.marker_'+id_marker_room).removeClass('disabled_l');
                        $('#pointer_f_'+id_room_target).removeClass('disabled_l');
                        $('.pointer_list_'+id_room_target).removeClass('disabled_l');
                        $('.list_alt_'+id_room_target).removeClass('disabled_l');
                        $('#pointer_m_'+id_room_target).removeClass('disabled_l');
                    })
                }
            }
        }
        setTimeout(function() {
            Pace.stop();
        },250);
    }

    function init_effect(type) {
        try {
            reset_effects();
            switch(type) {
                case 'snow':
                    $('.pnlm-dragfix').append('<canvas class="snow_effect"></canvas>');
                    init_snow();
                    $('.snow_effect').fadeIn();
                    break;
                case 'rain':
                    $('.pnlm-dragfix').append('<canvas class="rain_effect"></canvas>');
                    init_rain();
                    $('.rain_effect').fadeIn();
                    break;
                case 'fireworks':
                    $('.pnlm-dragfix').append('<canvas class="fireworks_effect"></canvas>');
                    init_fireworks();
                    $('.fireworks_effect').fadeIn();
                    break;
                case 'fog':
                    $('.pnlm-dragfix').append('<canvas class="fog_effect"></canvas>');
                    init_fog();
                    $('.fog_effect').fadeIn();
                    break;
                case 'confetti':
                    $('.pnlm-dragfix').append('<canvas class="confetti_effect"></canvas>');
                    init_confetti();
                    $('.confetti_effect').fadeIn();
                    break;
                case 'logo':
                    $('.pnlm-dragfix').append('<canvas class="logo_confetti_effect"></canvas>');
                    init_logo_confetti();
                    $('.logo_confetti_effect').fadeIn();
                    break;
                case 'sparkle':
                    $('.pnlm-dragfix').append('<canvas class="sparkle_effect"></canvas>');
                    $('.sparkle_effect').show();
                    init_sparkle();
                    break;
                default:
                    break;
            }
        } catch (e) {}
    }

    window.set_initial_pos = function(id) {
        if(peer_id=='') {
            if(!vr_enabled) {
                window.viewer_mov_pos_change = false;
                window.viewer_mov_follow_mouse = false;
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    pano_viewer.lookAt(parseFloat(panoramas[id].pitch),parseFloat(panoramas[id].yaw),parseInt(hfov),1000,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = parseFloat(panoramas[id].pitch);
                        current_viewer_yaw = parseFloat(panoramas[id].yaw);
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                } else {
                    video_viewer.pnlmViewer.lookAt(parseInt(panoramas[id].pitch),parseInt(panoramas[id].yaw),parseInt(hfov),1000,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = parseFloat(panoramas[id].pitch);
                        current_viewer_yaw = parseFloat(panoramas[id].yaw);
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                }
            }
        }
    }

    function check_vr_pos() {
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            var yaw = parseFloat(pano_viewer_vr.getYaw());
            var pitch = parseFloat(pano_viewer_vr.getPitch());
        } else {
            var yaw = parseFloat(video_viewer_vr.pnlmViewer.getYaw());
            var pitch = parseFloat(video_viewer_vr.pnlmViewer.getPitch());
        }
        var index = get_id_viewer(current_id_panorama);
        var in_marker = false;
        jQuery.each(panoramas[index].hotSpots_vr, function(index, hotspot_vr) {
            var h_yaw = hotspot_vr.yaw;
            var h_pitch = hotspot_vr.pitch;
            if(((yaw<=h_yaw+5) && (yaw>=h_yaw-5)) && ((pitch<=h_pitch+5) && (pitch>=h_pitch-5))) {
                in_marker = true;
                $('.cursor_vr').addClass('cursor_vr_active');
                $('.cursor_vr').addClass('fa-pulse');
                if(goto_timeout == null) {
                    goto_timeout = setTimeout(function () {
                        goto_timeout = null;
                        goto('',hotspot_vr.clickHandlerArgs)
                    },2000);
                }
            }
        });
        if(!in_marker) {
            clearTimeout(goto_timeout);
            goto_timeout = null;
            if(interval_position == null) {
                interval_position = setInterval(function () {
                    check_vr_pos();
                },250);
            }
            $('.cursor_vr').removeClass('cursor_vr_active');
            $('.cursor_vr').removeClass('fa-pulse');
        }
    }

    function check_pano_pos() {
        if(controls_status['icons_content'] || controls_status['icons_nav']) {
            try {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw = parseFloat(pano_viewer.getYaw());
                    var pitch = parseFloat(pano_viewer.getPitch());
                } else {
                    var yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
                }
            } catch (e) {
                return;
            }
            var index = get_id_viewer(current_id_panorama);
            if(controls_status['icons_content']) {
                $('.div_poi_wrapper').removeClass('pulse_icon_hover');
                $('.div_poi_wrapper').removeClass('pulse_image_hover');
            }
            if(controls_status['icons_nav']) {
                $('.div_marker_wrapper').removeClass('pulse_icon_hover');
                $('.div_marker_wrapper').removeClass('pulse_image_hover');
            }
            $('.pnlm-pointer').removeClass('hotspot_hover');
            var array_coord = [];
            jQuery.each(panoramas[index].hotSpots, function(index, hotspot) {
                if(hotspot.object!='poi_embed' && hotspot.type!='callout' && hotspot.type!='grouped' && hotspot.type!=null) {
                    var h_yaw = hotspot.yaw;
                    var h_pitch = hotspot.pitch;
                    var dist_yaw = Math.abs(yaw % 360 - h_yaw % 360);
                    dist_yaw = Math.min(dist_yaw, 360 - dist_yaw);
                    var dist_pitch = Math.abs(pitch % 360 - h_pitch % 360);
                    dist_pitch = Math.min(dist_pitch, 360 - dist_pitch);
                    if((dist_yaw<=20) && (dist_pitch<=20)) {
                        array_coord.push({x:h_yaw,y:h_pitch,hotspot:hotspot});
                    }
                }
            });
            if(array_coord.length>0) {
                sortByDistance(array_coord, {x: yaw, y: pitch});
                if(controls_status['icons_content']) {
                    if(array_coord[0].hotspot.type=='poi') {
                        if(array_coord[0].hotspot.animation=='none') {
                            if ($('.hotspot_' + array_coord[0].hotspot.id + ' .div_poi_wrapper').hasClass('pulse_icon')) {
                                $('.hotspot_' + array_coord[0].hotspot.id + ' .div_poi_wrapper').addClass('pulse_icon_hover');
                            } else {
                                $('.hotspot_' + array_coord[0].hotspot.id + ' .div_poi_wrapper').addClass('pulse_image_hover');
                            }
                        }
                        $('.hotspot_'+array_coord[0].hotspot.id).addClass('hotspot_hover');
                    }
                }
                if(controls_status['icons_nav']) {
                    if(array_coord[0].hotspot.type=='marker') {
                        if(array_coord[0].hotspot.animation=='none') {
                            if($('.marker_'+array_coord[0].hotspot.id+' .div_marker_wrapper').hasClass('pulse_icon')) {
                                $('.marker_'+array_coord[0].hotspot.id+' .div_marker_wrapper').addClass('pulse_icon_hover');
                            } else {
                                $('.marker_'+array_coord[0].hotspot.id+' .div_marker_wrapper').addClass('pulse_image_hover');
                            }
                        }
                        $('.marker_'+array_coord[0].hotspot.id).addClass('hotspot_hover');
                    }
                }
            }
        }
    }

    function check_callout_pos() {
        if(controls_status['icons_content']) {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                var yaw = parseFloat(pano_viewer.getYaw());
                var pitch = parseFloat(pano_viewer.getPitch());
            } else {
                var yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                var pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
            }
            var index = get_id_viewer(current_id_panorama);
            var array_coord = [], array_callout = [];
            jQuery.each(panoramas[index].hotSpots, function(index, hotspot) {
                if(hotspot.type=='callout') {
                    var params = hotspot.createTooltipArgs.params;
                    var json = JSON.parse(params);
                    if(json.open=='lookat' || controls_status['presentation']) {
                        array_callout.push(hotspot);
                        var h_yaw = hotspot.yaw;
                        var h_pitch = hotspot.pitch;
                        var dist_yaw = Math.abs(yaw % 360 - h_yaw % 360);
                        dist_yaw = Math.min(dist_yaw, 360 - dist_yaw);
                        var dist_pitch = Math.abs(pitch % 360 - h_pitch % 360);
                        dist_pitch = Math.min(dist_pitch, 360 - dist_pitch);
                        if((dist_yaw<=20) && (dist_pitch<=20)) {
                            array_coord.push({x:h_yaw,y:h_pitch,hotspot:hotspot});
                        }
                    }
                }
            });
            for(var i=0; i<array_callout.length; i++) {
                var array_id_exclude = [];
                for(var k=0; k<array_coord.length; k++) {
                    var id_exclude = array_coord[k].hotspot.createTooltipArgs.id;
                    array_id_exclude.push(id_exclude);
                }
                if(!array_id_exclude.includes(array_callout[i].createTooltipArgs.id)) {
                    close_callout(array_callout[i].createTooltipArgs.id);
                }
            }
            if(array_coord.length>0) {
                for(var i=0; i<array_coord.length; i++) {
                    open_callout(array_coord[i].hotspot.createTooltipArgs.id);
                }
            }
        }
    }

    const distance = (coor1, coor2) => {
        var dist = Math.abs(coor1 % 360 - coor2 % 360);
        return Math.min(dist, 360 - dist);
    };
    const sortByDistance = (coordinates, point) => {
        const sorter = (a, b) => distance(a, point) - distance(b, point);
        coordinates.sort(sorter);
    };

    var goto_check = false;
    var look_room_target = [];
    window.goto = function(hotSpotDiv, args, dh=false) {
        if(window.learning_mode>0) {
            if(window.learning_unlock_marker) {
                if(learning_check_marker_locked(args[0])) {
                    return;
                }
            }
        }
        if(hotSpotDiv!='') {
            if(check_click_outbound_hs("m"+args[8],args[2],args[1])) return;
        }
        $('#div_panoramas').css('pointer-events','none');
        $('.pnlm-dragfix').css('pointer-events','none');
        if(window.comments!=0) {
            $('#comments_div').hide();
            $('#comments_control').removeClass('active');
        }
        window.viewer_mov_pos_change = false;
        first_change_rooms_alt = false;
        list_mrv_panoramas = [], index_current_mrv_panorama = 1, prev_current_mrv_panorama = 0, mrv_initialized = 0;
        try {
            ticker_mrv.destroy();
        } catch (e) {}
        clearTimeout(mrv_next_timeout);
        document.removeEventListener('mousedown', mouse_down_el);
        document.removeEventListener('mousemove', mouse_move_el);
        if(!goto_check) {
            goto_check = true;
        } else {
            return;
        }
        $('.tooltip_text').hide();
        $('.tooltip_preview').hide();
        $('.tooltip_preview_square').hide();
        $('.tooltip_preview_rect').hide();
        $('.passcode_div').hide();
        $('.leads_div').hide();
        $('.mailchimp_form_div').hide();
        $('.rooms_view_sel').hide();
        if(live_session_connected) {
            clearInterval(interval_live_session);
            try {
                peer_conn.send({type:'goto',args:args});
            } catch (e) {}
        }
        var id_prev = get_id_viewer(current_id_panorama);
        current_id_panorama = args[0];
        if(!list_id_visited.includes(parseInt(current_id_panorama))) list_id_visited.push(parseInt(current_id_panorama));
        $('.room_visited_'+current_id_panorama).show();
        check_list_sliders_visited();
        var id = get_id_viewer(current_id_panorama);
        if(window.comments==2) change_disqus(id);
        if(panoramas[id].transition_override==1) {
            var transition_time_r = panoramas[id].transition_time;
            var transition_zoom_r = panoramas[id].transition_zoom;
        } else {
            var transition_time_r = transition_time;
            var transition_zoom_r = transition_zoom;
        }
        if(dh || controls_status['orient']) {
            transition_time_r=0;
            transition_zoom_r=0;
        }
        var pitch_m = args[3];
        var yaw_m = args[4];
        var hfov_m = args[5];
        if(args[6] === undefined) {
            var lookat = 0;
        } else {
            var lookat = args[6];
            if(lookat==null) lookat=0;
        }
        if(args[7] === undefined) {
            var sound = '';
        } else {
            var sound = args[7];
        }
        look_room_target = [];
        if(args[9] !== undefined) {
            if(args[9] !== null) {
                look_room_target['pitch'] = parseFloat(args[9]);
            }
        }
        if(args[10] !== undefined) {
            if(args[10] !== null) {
                look_room_target['yaw'] = parseFloat(args[10]);
            }
        }
        if(args[11] !== undefined) {
            if(args[11] !== null) {
                look_room_target['duration'] = parseInt(args[11]);
            }
        }
        if(look_room_target['yaw']!==undefined) {
            if(parseFloat(yaw_m)==parseFloat(look_room_target['yaw']) && parseFloat(pitch_m)==parseFloat(look_room_target['pitch'])) {
                look_room_target = [];
            }
        }
        if(sound!='') {
            play_sound_hs(sound);
        }
        if(pitch_m=='') {
            pitch_m = null;
        }
        if(yaw_m=='') {
            yaw_m = null;
        }
        if(hfov_m=='') {
            hfov_m = null;
        }
        if(args[1]!=null) {
            switch(lookat) {
                case 0:
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var pitch_t = parseFloat(pano_viewer.getPitch());
                        var yaw_t = parseFloat(pano_viewer.getYaw());
                    } else {
                        var pitch_t = parseFloat(video_viewer.pnlmViewer.getPitch());
                        var yaw_t = parseFloat(video_viewer.pnlmViewer.getYaw());
                    }
                    break;
                case 1:
                    var pitch_t = 0;
                    if(parseInt(panoramas[id_prev].min_yaw)>-50 || parseInt(panoramas[id_prev].max_yaw)<50) {
                        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                            var yaw_t = parseFloat(pano_viewer.getYaw());
                        } else {
                            var yaw_t = parseFloat(video_viewer.pnlmViewer.getYaw());
                        }
                    } else {
                        var yaw_t = args[2];
                    }
                    break;
                case 2:
                    if(parseInt(panoramas[id_prev].allow_pitch)==0 || (parseInt(panoramas[id_prev].min_pitch)>-25 || parseInt(panoramas[id_prev].max_pitch)<25)) {
                        var pitch_t = 0;
                    } else {
                        var pitch_t = args[1];
                    }
                    if(parseInt(panoramas[id_prev].min_yaw)>-50 || parseInt(panoramas[id_prev].max_yaw)<50) {
                        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                            var yaw_t = parseFloat(pano_viewer.getYaw());
                        } else {
                            var yaw_t = parseFloat(video_viewer.pnlmViewer.getYaw());
                        }
                    } else {
                        var yaw_t = args[2];
                    }
                    break;
            }
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                if(transition_time_r>0) {
                    var c_hfov = parseInt(pano_viewer.getHfov());
                    var c_transition_zoom = c_hfov - (c_hfov*(transition_zoom_r/100));
                    pano_viewer.lookAt(pitch_t,yaw_t,c_transition_zoom,transition_time_r,function () {
                        fade_background(current_id_panorama,true,pitch_m,yaw_m,hfov_m,dh);
                    });
                } else {
                    fade_background(current_id_panorama,true,pitch_m,yaw_m,hfov_m,dh);
                }
            } else {
                if(transition_time_r>0) {
                    var c_hfov = parseInt(video_viewer.pnlmViewer.getHfov());
                    var c_transition_zoom = c_hfov - (c_hfov*(transition_zoom_r/100));
                    video_viewer.pnlmViewer.lookAt(pitch_t, yaw_t, c_transition_zoom, transition_time_r, function () {
                        try {
                            video_viewer.pause();
                        } catch (e) {}
                        fade_background(current_id_panorama, true,pitch_m,yaw_m,hfov_m,dh);
                    });
                } else {
                    try {
                        video_viewer.pause();
                    } catch (e) {}
                    fade_background(current_id_panorama, true,pitch_m,yaw_m,hfov_m,dh);
                }
            }
        } else {
            try {
                video_viewer.pause();
            } catch (e) {}
            fade_background(current_id_panorama,false,pitch_m,yaw_m,hfov_m,dh);
        }
        if($('.list_sliders').css('opacity')==1) {
            reposition_bottom_controls(true,true,0);
        } else {
            reposition_bottom_controls(false,true,0);
        }
        if(access_time_id!=0) {
            clearInterval(interval_access_time_avg);
            if(!controls_status['presentation']) {
                if(window.export_mode==0 && window.preview==0 && window.nostat==0) {
                    Pace.ignore(function(){
                        $.ajax({
                            url: "ajax/set_statistics.php",
                            type: "POST",
                            data: {
                                type: 'room_time',
                                id: access_time_id,
                                access_time_avg: access_time_avg,
                                ip_visitor: window.ip_visitor
                            },
                            async: true
                        });
                    });
                }
            }
            access_time_avg = 0;
        }
    }

    function ObjectLength( object ) {
        var length = 0;
        for( var key in object ) {
            if( object.hasOwnProperty(key) ) {
                ++length;
            }
        }
        return length;
    };

    function fade_background(current_id_panorama,click_m,pitch_m,yaw_m,hfov_m,dh) {
        var id = get_id_viewer(current_id_panorama);
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            var dataURL = pano_viewer.getRenderer().render(pano_viewer.getPitch() / 180 * Math.PI,
                pano_viewer.getYaw() / 180 * Math.PI,
                pano_viewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'image/jpeg'});
        } else {
            var dataURL = video_viewer.pnlmViewer.getRenderer().render(video_viewer.pnlmViewer.getPitch() / 180 * Math.PI,
                video_viewer.pnlmViewer.getYaw() / 180 * Math.PI,
                video_viewer.pnlmViewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'image/jpeg'});
        }
        if(vr_enabled) {
            $('#background_pano_vr').off('load');
            $('#background_pano_vr').on('load',function () {
                $('#background_pano_vr').show();
                setTimeout(function () {
                    $('#panorama_viewer_vr').css('opacity',0);
                    $('#video_viewer_vr').css('opacity',0);
                },50);
            }).attr('src',dataURL);
        }
        $('#background_pano').off('load');
        $('#background_pano').on('load',function () {
            $('#background_pano').show();
            $('#background_pano').css('z-index',11);
            if(!vr_enabled) {
                $('#loading_pano').show();
                $('#loading_pano').css('opacity',0.8);
            }
            setTimeout(function () {
                $('#panorama_viewer').css('opacity',0);
                $('#video_viewer').css('opacity',0);
                if(window.index_room_alt_sel!=null && panoramas[id].array_rooms_alt[window.index_room_alt_sel]!==undefined) {
                    window.id_room_alt_sel = panoramas[id].array_rooms_alt[window.index_room_alt_sel].id;
                    window.sync_virtual_staging_enabled=false;
                    window.changed_room_alt = false;
                    if(panoramas[id].virtual_staging==1) {
                        virtual_staging = true;
                    } else {
                        virtual_staging = false;
                    }
                    $('#panorama_viewer_alt').css('opacity',0);
                    $('#vs_slider').fadeOut();
                    $('#vs_grab').fadeOut();
                    initialize_room(id,true,click_m,pitch_m,yaw_m,hfov_m,window.index_room_alt_sel,dh);
                } else {
                    window.id_room_alt_sel = 0;
                    initialize_room(id,true,click_m,pitch_m,yaw_m,hfov_m,null,dh);
                }
                goto_check = false;
                $('.map_pointer_container').removeClass('active');
                $('#pointer_f_'+current_id_panorama).addClass('active');
                try {
                    if(!isNaN(panoramas[id].id_map)) {
                        var map_left = parseFloat(panoramas[id].map_left);
                        var map_top = parseFloat(panoramas[id].map_top);
                        var map_w = $('.map_'+panoramas[id].id_map).width();
                        var map_h = $('.map_'+panoramas[id].id_map).height();
                        var orig_w =  $('.map_'+panoramas[id].id_map+' .map_image').attr('data-map_width_d');
                        var ratio = map_w / orig_w;
                        var point_size = 20;
                        for(var k=0; k < array_maps.length; k++) {
                            if(panoramas[id].id_map==array_maps[k].id) {
                                point_size = array_maps[k].point_size;
                            }
                        }
                        map_left = map_left + (point_size/2);
                        map_top = map_top + (point_size/3);
                        map_left = (map_w/2) - (map_left*ratio);
                        map_top = (map_h/2) - (map_top*ratio);
                        panzoom_map[panoramas[id].id_map].pan(map_left, map_top);
                    }
                } catch (e) {}
                $('.pointer_list').removeClass('active');
                $('.pointer_list_cat').removeClass('active');
                $('.pointer_list_'+current_id_panorama).addClass('active');
                $('#list_slider_main .cat_image_grid img').each(function() {
                    var id_room_sg = $(this).attr('data-id-room');
                    if(parseInt(id_room_sg) == parseInt(current_id_panorama)) {
                        $(this).parent().parent().addClass('active');
                        return;
                    }
                });
                $('#list_slider_main .cat_image_grid img').each(function() {
                    var id_room_sg = $(this).attr('data-id-room');
                    if(parseInt(id_room_sg) == parseInt(current_id_panorama)) {
                        $(this).parent().parent().addClass('active');
                        return;
                    }
                });
                $('.list_slider_cat .cat_image_grid img').each(function() {
                    var id_room_sg = $(this).attr('data-id-room');
                    if(parseInt(id_room_sg) == parseInt(current_id_panorama)) {
                        $(this).parent().parent().addClass('active');
                        return;
                    }
                });
                if($('#list_slider_main').hasClass('hidden_slider')) {
                    var one_slide_active = false;
                    $('.list_slider_cat:not(.hidden_slider) .slidee_cat .pointer_list').each(function() {
                        if($(this).hasClass('active')) {
                            one_slide_active = true;
                        }
                    });
                    if(!one_slide_active) {
                        $('.list_slider').addClass('hidden_slider');
                        $('#list_slider_main').removeClass('hidden_slider');
                        sliders_reload();
                    }
                }
                close_all_categories();
                $('.list_alt_menu .dropdown p:not(.cat) i').each(function () {
                    if($(this).hasClass('fas fa-dot-circle')) {
                        $(this).removeClass('fas fa-dot-circle').addClass('fas fa-circle');
                    }
                });
                const $currentItemElement = $('.list_alt_'+current_id_panorama);
                if ($currentItemElement.length > 0) {
                    $currentItemElement.find('i').removeClass('fas fa-circle').removeClass('far fa-circle').addClass('fas fa-dot-circle');
                    if ($currentItemElement.is('[class*="cat_parent_"]')) {
                        const immediateParentId = $currentItemElement.data('cat');
                        const mainAncestorId = getMainAncestorId(immediateParentId);
                        if (mainAncestorId) {
                            $('.list_alt_menu .cat_parent_root').each(function() {
                                const $otherMainCat = $(this);
                                const otherMainCatMatch = $otherMainCat.attr('class').match(/cat_(c\d+)/);
                                if (otherMainCatMatch && otherMainCatMatch[1]) {
                                    const otherMainCatId = otherMainCatMatch[1];
                                    if (otherMainCatId !== mainAncestorId) {
                                        $otherMainCat.find('i.fas').removeClass('fa-chevron-down').addClass('fa-chevron-right');
                                        $otherMainCat.find('i.fas').parent().removeClass('open');
                                        hideAllDescendants(otherMainCatId);
                                    }
                                }
                            });
                            ensureCategoryOpen(immediateParentId);
                        }
                    }
                }
            },50);
        }).attr('src',dataURL);
    }

    function check_list_sliders_visited() {
        $('#list_slider_main .pointer_list_cat').each(function() {
            var all_visited = true;
            $(this).find('.cat_image_grid img').each(function() {
                var id_room = parseInt($(this).attr('data-id-room'));
                if(!list_id_visited.includes(id_room)) {
                    all_visited = false;
                }
            });
            if(all_visited) {
                $(this).find('.room_visited').show();
            }
        });
        $('.list_slider_cat').each(function() {
            $(this).find('.pointer_list_cat').each(function() {
                var all_visited = true;
                $(this).find('.cat_image_grid img').each(function() {
                    var id_room = parseInt($(this).attr('data-id-room'));
                    if(!list_id_visited.includes(id_room)) {
                        all_visited = false;
                    }
                });
                if(all_visited) {
                    $(this).find('.room_visited').show();
                }
            });
        });
    }

    function adjust_ratio_hfov() {
        if(!live_session_connected) {
            if(!vr_enabled) {
                var c_w = document.querySelector("#vt_container").offsetWidth;
                var c_h = document.querySelector("#vt_container").offsetHeight;
                var ratio_panorama = c_w / c_h;
                if(c_w <= 500) {
                    var ratio_hfov = window.hfov_mobile_ratio / ratio_panorama;
                } else {
                    var ratio_hfov = 1;
                }
                if(ratio_hfov<1) ratio_hfov=1;
                var min_hfov_t = min_hfov / ratio_hfov;
                var max_hfov_t = max_hfov / ratio_hfov;
                var id = get_id_viewer(current_id_panorama);
                if(window.is_mobile) {
                    try {
                        var hfov_c = panoramas[id].hfov;
                        var hfov_t = hfov_c / ratio_hfov;
                    } catch (e) {}
                } else {
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        try {
                            hfov_c = pano_viewer.getHfov();
                        } catch (e) {}
                    } else {
                        try {
                            hfov_c = video_viewer.pnlmViewer.getHfov();
                        } catch (e) {}
                    }
                }
                hfov_t = hfov_c / ratio_hfov;
                try {
                    if(panoramas[id].allow_hfov==0) {
                        min_hfov_t = hfov_t;
                        max_hfov_t = hfov_t;
                    }
                } catch (e) {}
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    try {
                        pano_viewer.setHfovBounds([min_hfov_t,max_hfov_t]);
                        if(!window.poi_box_open) {
                            pano_viewer.setHfov(hfov_t,false);
                        }
                    } catch (e) {}
                    try {
                        pano_viewer_alt.setHfovBounds([min_hfov_t,max_hfov_t]);
                        if(!window.poi_box_open) {
                            pano_viewer_alt.setHfov(hfov_t,false);
                        }
                    } catch (e) {}
                } else {
                    try {
                        video_viewer.pnlmViewer.setHfovBounds([min_hfov_t,max_hfov_t]);
                        if(!window.poi_box_open) {
                            video_viewer.pnlmViewer.setHfov(hfov_t, false);
                        }
                    } catch (e) {}
                }
            }
        }
    }

    $(window).resize(function () {
        window.c_width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        window.c_height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
        adjust_ratio_hfov();
        sliders_reload();
        if(window.innerHeight > window.innerWidth){
            if(window.innerWidth<500) {
                var touchPanSpeedCoeffFactor = pan_speed_mobile_vt;
                var friction = friction_mobile_vt;
            } else {
                var touchPanSpeedCoeffFactor = pan_speed_mobile_vt/2;
                var friction = friction_mobile_vt/2;
            }
            var zoom_friction = zoom_friction_mobile_vt;
        } else {
            var touchPanSpeedCoeffFactor = pan_speed_vt;
            var friction = friction_vt;
            var zoom_friction = zoom_friction_vt;
        }
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try {
                pano_viewer.setFriction(friction);
                pano_viewer.setZoomFriction(zoom_friction);
                pano_viewer.setTouchPanSpeedCoeffFactor(touchPanSpeedCoeffFactor);
            } catch (e) {}
        } else {
            try {
                video_viewer.pnlmViewer.setFriction(friction);
                video_viewer.pnlmViewer.setZoomFriction(zoom_friction);
                video_viewer.pnlmViewer.setTouchPanSpeedCoeffFactor(touchPanSpeedCoeffFactor);
            } catch (e) {}
        }
        if(window.innerWidth<540) {
            var info_control = false;
            var voice_control = false;
            var gallery_control = false;
            if(show_info>0) {
                info_control = true;
            }
            if(voice_commands_enable>0) {
                voice_control = true;
            }
            if(gallery_images.length>0 && gallery_mode=='images') {
                if(show_gallery>0) {
                    gallery_control = true;
                }
            } else if(gallery_mode=='slideshow') {
                if(show_gallery>0) {
                    gallery_control = true;
                }
            }
        }
        if(window.flyin!=0) {
            try {
                var width = document.querySelector("#vt_container").offsetWidth;
                var height = document.querySelector("#vt_container").offsetHeight;
                flyin_renderer.setSize(width, height);
                flyin_camera.aspect = width / height;
                flyin_camera.updateProjectionMatrix();
            } catch (e) {}
        }
        try {
            $('#vs_grab').css('top','calc(50% - 15px)');
            var width = $("#vt_container").width();
            $('#panorama_viewer_alt').css('width',width+'px');
            var perc_left = $('#vs_slider')[0].style.left.replace('%','');
            if(perc_left!='') {
                perc_left = parseFloat(perc_left) / 100;
                var grab_width = $('#vs_grab').width();
                var slider_width = $('#vs_slider').width();
                var new_pos_left = (width * perc_left)-(grab_width/2)+(slider_width/2);
                $('#vs_grab').css('left',new_pos_left+'px');
            }
            init_vs_drag();
        } catch (e) {}
        if(map_tour_l!=null) {
            setTimeout(function () {
                map_tour_l.invalidateSize();
            },100);
        }
        var poi_embed_count = $('.poi_embed').length;
        if(poi_embed_count>0) {
            setTimeout(function () {
                adjust_poi_embed_helpers_all();
            },50);
        }
        var marker_embed_count = $('.marker_embed').length;
        if(marker_embed_count>0) {
            setTimeout(function () {
                adjust_marker_embed_helpers_all();
            },50);
        }
        setTimeout(function () {
            adjust_measurements();
        },50);
        resize_maps();
        if(voice_commands_enable>0) {
            reposition_voice_control();
        }
        if($('.list_sliders').css('opacity')==1) {
            reposition_bottom_controls(true, false,0);
        } else {
            reposition_bottom_controls(false, false,0);
        }
        adjustCenterDiv();
        adjust_elements_positions();
    });

    window.resize_maps = function () {
        $('.map').css({'width':'','height':''});
        $('.map_zoomed').css({'width':'','height':''});
        $('.map_image').each(function () {
            if($(this).parent().parent().is(':visible')) {
                var width = $(this).css('width');
                var height = $(this).css('height');
                var width_f = $(this).width()-1;
                var height_f = $(this).height()-2;
                if($(this).parent().parent().parent().hasClass('map_zoomed')) {
                    $(this).parent().parent().parent().css({'width':width_f,'height':height_f});
                } else {
                    var map_width_d = $(this).attr('data-map_width_d');
                    var map_width_m = $(this).attr('data-map_width_m');
                    if((window.innerWidth<540) || (window.innerHeight<540)) {
                        $(this).css('width',map_width_m+'px');
                    } else {
                        $(this).css('width',map_width_d+'px');
                    }
                    $(this).parent().parent().parent().css({'width':width,'height':height});
                }
                var id_map = $(this).parent().parent().attr('data-id');
                var point_size = 20;
                for(var k=0; k < array_maps.length; k++) {
                    if(id_map==array_maps[k].id) {
                        point_size = array_maps[k].point_size;
                    }
                }
                var scale = (point_size/20)*(parseInt($(this).css('width'))/300);
                $('.pointer_map_'+id_map).attr('data-scale',scale);
                change_pointer_map_scale(scale,id_map);
            }
        });
    }

    function change_pointer_map_scale(newScale,id_map){
        Array.from(document.getElementsByClassName('pointer_map_'+id_map)).forEach(
            function(element, index, array) {
                element.style.transform = element.style.transform.replace(/scale\([0-9|\.]*\)/, 'scale(' + newScale + ')');
            }
        );
    }

    $(document).bind('webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange', function() {
        var isFullScreen = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen || (document.msFullscreenElement != null);
        setTimeout(function () {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.resize();
            } else {
                video_viewer.pnlmViewer.resize();
            }
        },100);
        if (isFullScreen) {
            $('.fullscreen_control').addClass('active_control');
            $('.fullscreen_control i').removeClass('fa-expand').addClass('fa-compress');
            $('.fullscreen_alt_control i').removeClass('fa-expand').addClass('fa-compress');
            controls_status['fullscreen']=true;
        } else {
            $('.fullscreen_control').removeClass('active_control');
            $('.fullscreen_control i').removeClass('fa-compress').addClass('fa-expand');
            $('.fullscreen_alt_control i').removeClass('fa-compress').addClass('fa-expand');
            controls_status['fullscreen']=false;
        }
    });

    function get_gallery() {
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.gallery_json,function(rsp) {
                if(rsp.length>0 && gallery_mode=='images') {
                    initialize_gallery(rsp);
                }
                loading_config();
            });
        } else {
            $.ajax({
                url: "ajax/get_gallery.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    language: window.language,
                    count_languages_enabled: window.count_languages_enabled
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if(rsp.length>0 && gallery_mode=='images') {
                        initialize_gallery(rsp);
                    }
                    loading_config();
                },
                error: function () {
                    loading_config();
                }
            });
        }
    }

    function get_info_box() {
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.info_box_json,function(rsp) {
                info_box = rsp.info_box;
                info_box_type = rsp.info_box_type;
                if(info_box!='') {
                    $('.info_control').removeClass("loading_spinner_icon");
                    if(show_info==2) {
                        view_info_box();
                    }
                }
            });
        } else {
            $.ajax({
                url: "ajax/get_info_box.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    language: window.language,
                    count_languages_enabled: window.count_languages_enabled
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    info_box = rsp.info_box;
                    info_box_type = rsp.info_box_type;
                    if(info_box!='') {
                        $('.info_control').removeClass("loading_spinner_icon");
                        if(show_info==2) {
                            view_info_box();
                        }
                    }
                }
            });
        }
    }

    function get_custom_box() {
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.custom_box_json,function(rsp) {
                custom_box = rsp.custom_box;
                custom2_box = rsp.custom2_box;
                custom3_box = rsp.custom3_box;
                custom4_box = rsp.custom4_box;
                custom5_box = rsp.custom5_box;
                location_box = rsp.location_box;
                if(custom_box!='') {
                    $('.custom_control').removeClass("loading_spinner_icon");
                    if(show_custom==2) {
                        view_custom_box();
                    }
                }
                if(custom2_box!='') {
                    $('.custom2_control').removeClass("loading_spinner_icon");
                    if(show_custom2==2) {
                        view_custom2_box();
                    }
                }
                if(custom3_box!='') {
                    $('.custom3_control').removeClass("loading_spinner_icon");
                    if(show_custom3==2) {
                        view_custom3_box();
                    }
                }
                if(custom4_box!='') {
                    $('.custom4_control').removeClass("loading_spinner_icon");
                    if(show_custom4==2) {
                        view_custom4_box();
                    }
                }
                if(custom5_box!='') {
                    $('.custom5_control').removeClass("loading_spinner_icon");
                    if(show_custom5==2) {
                        view_custom5_box();
                    }
                }
                if(location_box!='') {
                    $('.location_control').removeClass("loading_spinner_icon");
                    if(show_location==2) {
                        view_location_box();
                    }
                }
            });
        } else {
            $.ajax({
                url: "ajax/get_custom_box.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    language: window.language,
                    count_languages_enabled: window.count_languages_enabled
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    custom_box = rsp.custom_box;
                    custom2_box = rsp.custom2_box;
                    custom3_box = rsp.custom3_box;
                    custom4_box = rsp.custom4_box;
                    custom5_box = rsp.custom5_box;
                    location_box = rsp.location_box;
                    if(custom_box!='') {
                        $('.custom_control').removeClass("loading_spinner_icon");
                        if(show_custom==2) {
                            view_custom_box();
                        }
                    }
                    if(custom2_box!='') {
                        $('.custom2_control').removeClass("loading_spinner_icon");
                        if(show_custom2==2) {
                            view_custom2_box();
                        }
                    }
                    if(custom3_box!='') {
                        $('.custom3_control').removeClass("loading_spinner_icon");
                        if(show_custom3==2) {
                            view_custom3_box();
                        }
                    }
                    if(custom4_box!='') {
                        $('.custom4_control').removeClass("loading_spinner_icon");
                        if(show_custom4==2) {
                            view_custom4_box();
                        }
                    }
                    if(custom5_box!='') {
                        $('.custom5_control').removeClass("loading_spinner_icon");
                        if(show_custom5==2) {
                            view_custom5_box();
                        }
                    }
                    if(location_box!='') {
                        $('.location_control').removeClass("loading_spinner_icon");
                        if(show_location==2) {
                            view_location_box();
                        }
                    }
                }
            });
        }
    }

    function initialize_gallery(array_images) {
        jQuery.each(array_images, function(index, image) {
            if((image.title!='') || (image.description!='')) {
                gallery_images.push({
                    "ID":(index+1),
                    "kind":'image',
                    "src":((window.s3_enabled) ? window.s3_url : '')+"gallery/"+image.image,
                    "srct":((window.s3_enabled) ? window.s3_url : '')+"gallery/thumb/"+image.image,
                    "title":"<div><h4>"+image.title+"</h4><p>"+image.description+"</p></div>",
                });
            } else {
                gallery_images.push({
                    "ID":(index+1),
                    "kind":'image',
                    "src":((window.s3_enabled) ? window.s3_url : '')+"gallery/"+image.image,
                    "srct":((window.s3_enabled) ? window.s3_url : '')+"gallery/thumb/"+image.image,
                });
            }
        });
    }

    function get_maps() {
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.maps_json,function(rsp) {
                if (rsp.status == 'ok') {
                    array_maps = rsp.maps;
                    map_tour = rsp.map_tour;
                    map_tour_points = rsp.map_tour_points;
                }
                get_presentation();
            });
        } else {
            $.ajax({
                url: "ajax/get_maps.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    language: window.language,
                    count_languages_enabled: window.count_languages_enabled
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == 'ok') {
                        array_maps = rsp.maps;
                        map_tour = rsp.map_tour;
                        map_tour_points = rsp.map_tour_points;
                    }
                    get_presentation();
                },
                error: function () {
                    get_presentation();
                }
            });
        }
    }

    function get_presentation() {
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.presentation_json,function(rsp) {
                if (rsp.status == 'ok') {
                    array_presentation = rsp.presentation;
                }
                get_advertisement();
            });
        } else {
            $.ajax({
                url: "ajax/get_presentation.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                    language: window.language,
                    count_languages_enabled: window.count_languages_enabled
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == 'ok') {
                        array_presentation = rsp.presentation;
                    }
                    get_advertisement();
                },
                error: function () {
                    get_advertisement();
                }
            });
        }
    }

    function get_advertisement() {
        if(window.export_mode==1) {
            $.getJSON('ajax/'+window.advertisement_json,function(rsp) {
                if (rsp.status == 'ok') {
                    announce = rsp.announce;
                }
                get_gallery();
            });
        } else {
            $.ajax({
                url: "ajax/get_announce.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    if (rsp.status == 'ok') {
                        announce = rsp.announce;
                    }
                    get_gallery();
                },
                error: function () {
                    get_gallery();
                }
            });
        }
    }

    window.play_ad_video = function () {
        var video = document.getElementById('ad_video');
        video.play();
        if(announce.countdown==-1) {
            $('#announce_close_ad').html(window.viewer_labels.wait_video);
            $('#announce_close_ad').attr('onclick','');
            $('#announce_close_ad').css({'cursor':'default','pointer-events':'none'});
        } else if(announce.countdown==0) {
            $('#announce_close_ad').html(window.viewer_labels.close_ad+' <i class="fas fa-angle-double-right"></i>');
            $('#announce_close_ad').css({'cursor':'pointer','pointer-events':'initial'});
            $('#announce_close_ad').on('click',function () {
                announce_open = false;
                $.fancybox.close();
            });
        } else {
            $('#announce_close_ad').html(window.viewer_labels.close_ad+' <span id="announce_time_left">'+announce.countdown+'</span>').promise().done(function () {
                announce_interval = setInterval(function () {
                    announce.countdown = parseInt(announce.countdown)-1;
                    $('#announce_time_left').html(announce.countdown);
                    if(parseInt(announce.countdown)<=0) {
                        clearInterval(announce_interval);
                        $('#announce_close_ad').css('cursor','pointer');
                        $('#announce_time_left').html('<i class="fas fa-angle-double-right"></i>');
                        $('#announce_close_ad').on('click',function () {
                            announce_open = false;
                            $.fancybox.close();
                        });
                    }
                },1000);
            });
        }
    }

    function view_announce() {
        var close_ad_html = '<div class="noselect" id="announce_close_ad">'+window.viewer_labels.close_ad+' <span id="announce_time_left">'+announce.countdown+'</span></div>';
        var play_video_html = '<div onclick="play_ad_video();" style="cursor:pointer;pointer-events:initial;" class="noselect" id="announce_close_ad"><i class="fas fa-play"></i> '+window.viewer_labels.play_video+'</div>';
        if(announce.link=='') {
            switch(announce.type) {
                case 'image':
                    var announce_html = '<div class="noselect" id="announce_div"><img src="content/'+announce.image+'" /><br>'+close_ad_html+'</div>';
                    break;
                case 'video':
                    var announce_html = '<div class="noselect" id="announce_div"><video id="ad_video" playsinline ><source src="content/'+announce.video+'" type="video/mp4" /></video><br>'+play_video_html+'</div>';
                    break;
                case 'iframe':
                    var announce_html = '<div class="noselect" id="announce_div"><div class="blocker"></div><iframe scrolling="no" src="'+announce.iframe_link+'"></iframe><br>'+close_ad_html+'</div>';
                    break;
                case 'html':
                    var announce_html = '<div class="noselect" id="announce_div"><div class="ad_custom_html">'+announce.custom_html+'</div><br>'+close_ad_html+'</div>';
                    break;
            }
        } else {
            switch(announce.type) {
                case 'image':
                    var announce_html = '<div class="noselect" id="announce_div"><a href="'+announce.link+'" target="_blank"><img src="content/'+announce.image+'" /></a><br>'+close_ad_html+'</div>';
                    break;
                case 'video':
                    var announce_html = '<div class="noselect" id="announce_div"><a href="'+announce.link+'" target="_blank"><video id="ad_video" playsinline ><source src="content/'+announce.video+'" type="video/mp4" /></video></a><br>'+play_video_html+'</div>';
                    break;
                case 'iframe':
                    var announce_html = '<div class="noselect" id="announce_div"><a class="linkwrap" href="'+announce.link+'" target="_blank"><div class="blocker"></div><iframe scrolling="no" src="'+announce.iframe_link+'"></iframe></a><br>'+close_ad_html+'</div>';
                    break;
                case 'html':
                    var announce_html = '<div class="noselect" id="announce_div"><a href="'+announce.link+'" target="_blank"><div class="ad_custom_html">'+announce.custom_html+'</div></a><br>'+close_ad_html+'</div>';
                    break;
            }
        }
        announce_open = true;
        $.fancybox.open({
            src  : announce_html,
            type : 'html',
            touch: false,
            modal: true,
            clickSlide: false,
            clickOutside: false,
            afterShow: function () {
                switch(announce.type) {
                    case 'image':
                    case 'iframe':
                    case 'html':
                        if(parseInt(announce.countdown)==0) {
                            $('#announce_close_ad').css('cursor','pointer');
                            $('#announce_time_left').html('<i class="fas fa-angle-double-right"></i>');
                            $('#announce_close_ad').on('click',function () {
                                announce_open = false;
                                $.fancybox.close();
                            });
                        } else {
                            announce_interval = setInterval(function () {
                                announce.countdown = parseInt(announce.countdown)-1;
                                $('#announce_time_left').html(announce.countdown);
                                if(parseInt(announce.countdown)<=0) {
                                    clearInterval(announce_interval);
                                    $('#announce_close_ad').css('cursor','pointer');
                                    $('#announce_time_left').html('<i class="fas fa-angle-double-right"></i>');
                                    $('#announce_close_ad').on('click',function () {
                                        announce_open = false;
                                        $.fancybox.close();
                                    });
                                }
                            },1000);
                        }
                        break;
                    case 'video':
                        var video = document.getElementById('ad_video');
                        if(announce.countdown!=-1) {
                            video.loop = true;
                        }
                        var promise = video.play();
                        if (promise !== undefined) {
                            promise.then(_ => {
                                if(announce.countdown==-1) {
                                    $('#announce_close_ad').html(window.viewer_labels.wait_video);
                                    $('#announce_close_ad').attr('onclick','');
                                    $('#announce_close_ad').css({'cursor':'default','pointer-events':'none'});
                                } else if(announce.countdown==0) {
                                    $('#announce_close_ad').html(window.viewer_labels.close_ad+' <i class="fas fa-angle-double-right"></i>');
                                    $('#announce_close_ad').css({'cursor':'pointer','pointer-events':'initial'});
                                    $('#announce_close_ad').on('click',function () {
                                        announce_open = false;
                                        $.fancybox.close();
                                    });
                                } else {
                                    $('#announce_close_ad').html(window.viewer_labels.close_ad+' <span id="announce_time_left">'+announce.countdown+'</span>').promise().done(function () {
                                        announce_interval = setInterval(function () {
                                            announce.countdown = parseInt(announce.countdown)-1;
                                            $('#announce_time_left').html(announce.countdown);
                                            if(parseInt(announce.countdown)<=0) {
                                                clearInterval(announce_interval);
                                                $('#announce_close_ad').css('cursor','pointer');
                                                $('#announce_time_left').html('<i class="fas fa-angle-double-right"></i>');
                                                $('#announce_close_ad').on('click',function () {
                                                    announce_open = false;
                                                    $.fancybox.close();
                                                });
                                            }
                                        },1000);
                                    });
                                }
                            }).catch(error => {

                            });
                        }
                        video.addEventListener("ended", function() {
                            if(announce.countdown==-1) {
                                $('#announce_close_ad').html(window.viewer_labels.close_ad+' <i class="fas fa-angle-double-right"></i>');
                                $('#announce_close_ad').css({'cursor':'pointer','pointer-events':'initial'});
                                $('#announce_close_ad').on('click',function () {
                                    announce_open = false;
                                    $.fancybox.close();
                                });
                            }
                        }, true);
                        break;
                }
            }
        });
    }

    window.start_presentation_l = function () {
        if(controls_status['song']) {
            song_is_playng = true;
        } else {
            song_is_playng = false;
        }
        if(controls_status['map']) {
            map_opened = true;
        } else {
            map_opened = false;
        }
        if(controls_status['icons_content']) {
            icons_active = 1;
        } else {
            icons_active = 0;
        }
        if(controls_status['measures']) {
            measures_active = 1;
        } else {
            measures_active = 0;
        }
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try { pano_viewer.stopAutoRotate(); } catch (e) {}
        } else {
            try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
        }
        controls_status['presentation']=true;
        $('.panorama').css('pointer-events','none');
        $('.intro_img').css('display','none');
        if(presentation_view_pois==0) {
            $('.custom-hotspot-content').addClass('hidden_icons');
            controls_status['icons_content']=false;
        }
        if(presentation_view_measures==0) {
            $('.leader-line').addClass('hidden_icons');
            controls_status['measures']=false;
        }
        $('.custom-hotspot').addClass('hidden_icons');
        $('.custom-hotspot img').addClass('hidden_icons');
        $('.marker_embed').addClass('hidden_icons');
        $('.share_popup').removeClass('show');
        $('.list_sliders').css('z-index',0);
        $('.list_sliders').css('opacity',0);
        $('.list_control').removeClass('active_control');
        $('.list_control i, .list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
        reposition_bottom_controls(false,false,0);
        $('.map').hide();
        $('.pnlm-controls').hide();
        $('#dialog').show();
        $('#dialog').css('z-index',999);
        $('.pnlm-dragfix').css('pointer-events','none');
        $('.controls_control').css('pointer-events','none');
        $('.arrows_nav').hide();
        $('.vr_control_right').hide();
        $('.fullscreen_control').css({'opacity':0,'pointer-events':'none'});
        $('.list_control').css({'opacity':0,'pointer-events':'none'});
        $('.map_control').css({'opacity':0,'pointer-events':'none'});
        $('.map_tour_control').css({'opacity':0,'pointer-events':'none'});
        $('.song_control').css({'opacity':0,'pointer-events':'none'});
        $('.nav_control').css({'opacity':0,'pointer-events':'none'});
        $('#controls_bottom_left').css({'opacity':0,'pointer-events':'none'});
        $('#controls_bottom_center').css({'opacity':0,'pointer-events':'none'});
        $('#controls_bottom_right').css({'opacity':0,'pointer-events':'none'});
        $('.logo a').css('pointer-events','none');
        $('.poweredby a').css('pointer-events','none');
        if(window.preview_presentation==-1) {
            $('#btn_stop_presentation').show();
        }
        $('.menu_controls').hide();
        $('.list_alt_menu').hide();
        $('#menu_sidebar').hide();
        $('.rooms_view_sel').hide();
        $('.comments_vt').hide();
        $('.snipcart-checkout').hide();
        $('.woocommerce-checkout').hide();
        if(voice_commands_enable>0) {
            try {
                SpeechKITT.hide();
                if (annyang) { annyang.pause(); }
            } catch (e) {}
        }
        controls_status['orient']=false;
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.stopOrientation();
        } else {
            video_viewer.pnlmViewer.stopOrientation();
        }
        var af = $.fancybox.getInstance();
        if(af!=false) {
            controls_status['song']=false;
            if((af.current.type!='video' && af.current.contentType!='video')) {
                unmute_audio(true,false);
                audio_player.currentTime = 0;
                if(!audio_isPlaying()) audio_player.play();
                controls_status['song']=true;
            }
        } else {
            unmute_audio(true,false);
            audio_player.currentTime = 0;
            if(!audio_isPlaying()) audio_player.play();
            controls_status['song']=true;
        }
        controls_status['map']=false;
        controls_status['list']=false;
        controls_status['share']=false;
        $('.map_tour_control i').removeClass('fas').addClass('far');
        $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
        $('.map_tour_control').removeClass('active_control');
        $('.map_alt_control').removeClass('active_control');
        close_map_tour();
        if((presentation_type=='manual' || presentation_type=='automatic') && presentation_stop_click) {
            setTimeout(function() {
                document.addEventListener('click', presentation_stop_click_listener, false);
            },(presentation_type=='automatic') ? 2000 : 400);
        }
        if(presentation_type=='automatic') {
            var index = get_id_viewer(current_id_panorama);
            goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
        } else {
            if(window.preview_presentation!=-1) {
                presentation_steps(window.preview_presentation);
            } else {
                presentation_steps(0);
            }
        }
        if(live_session_connected) {
            if($('.live_status').is(':visible')) {
                var height_h = $('.name_vt').outerHeight()+$('.room_vt').outerHeight()+$('.category_room_vt').outerHeight()+$('.comments_vt').outerHeight()+$('.rooms_view_sel').outerHeight()+10;
                $('.live_status').css('top',height_h+'px');
            }
        }
    }

    window.start_presentation = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'start_presentation'});
            } catch (e) {}
        }
        start_presentation_l();
    }

    window.stop_presentation = function () {
        if(live_session_connected) {
            try {
                peer_conn.send({type:'stop_presentation'});
            } catch (e) {}
        }
        stop_presentation_l();
    }

    function presentation_stop_click_listener(e) {
        if(controls_status['presentation']) {
            if(e.screenX && e.screenX != 0 && e.screenY && e.screenY != 0){
                stop_presentation();
            }
        }
    }

    function automatic_presentation_steps(index) {
        if(controls_status['presentation']) {
            $('#btn_stop_presentation').addClass('disabled');
            if(!presentation_loop) {
                if(automatic_presentation_first_index === null) {
                    automatic_presentation_first_index = index;
                }
            }
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                var yaw = parseInt(pano_viewer.getYaw());
                pano_viewer.startAutoRotate(auto_presentation_speed);
                setTimeout(function () {
                    $('#btn_stop_presentation').removeClass('disabled');
                    interval_automatic_presentation = setInterval(function () {
                        var c_yaw = parseInt(pano_viewer.getYaw());
                        if(yaw==c_yaw) {
                            try { pano_viewer.stopAutoRotate(); } catch (e) {}
                            clearInterval(interval_automatic_presentation);
                            var len = panoramas.length;
                            index = (index+1)%len;
                            if(window.learning_mode>0) {
                                if(window.learning_unlock_marker) {
                                    if(learning_check_marker_locked(panoramas[index].id)) {
                                        try { pano_viewer.stopAutoRotate(); } catch (e) {}
                                        clearInterval(interval_automatic_presentation);
                                        stop_presentation();
                                        return;
                                    }
                                }
                            }
                            if(!presentation_loop) {
                                if(index == automatic_presentation_first_index) {
                                    stop_presentation();
                                    if(presentation_stop_id_room==0) {
                                        goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                                    }
                                } else {
                                    goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                                }
                            } else {
                                goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                            }
                        }
                    },50);
                },3000);
            } else {
                var yaw = parseInt(video_viewer.pnlmViewer.getYaw());
                video_viewer.pnlmViewer.startAutoRotate(auto_presentation_speed);
                setTimeout(function () {
                    $('#btn_stop_presentation').removeClass('disabled');
                    interval_automatic_presentation = setInterval(function () {
                        var c_yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                        if(yaw==c_yaw) {
                            try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
                            clearInterval(interval_automatic_presentation);
                            var len = panoramas.length;
                            index = (index+1)%len;
                            if(window.learning_mode>0) {
                                if(window.learning_unlock_marker) {
                                    if(learning_check_marker_locked(panoramas[index].id)) {
                                        try { pano_viewer.stopAutoRotate(); } catch (e) {}
                                        clearInterval(interval_automatic_presentation);
                                        stop_presentation();
                                        return;
                                    }
                                }
                            }
                            if(!presentation_loop) {
                                if(index == automatic_presentation_first_index) {
                                    stop_presentation();
                                    if(presentation_stop_id_room==0) {
                                        goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                                    }
                                } else {
                                    goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                                }
                            } else {
                                goto('',[panoramas[index].id,null,null,null,null,null,null,null]);
                            }
                        }
                    },50);
                },3000);
            }
        }
    }

    window.stop_presentation_l = function () {
        controls_status['presentation']=false;
        try {
            clearInterval(interval_automatic_presentation);
        } catch (e) {}
        if((presentation_type=='manual' || presentation_type=='automatic') && presentation_stop_click) {
            document.removeEventListener('click', presentation_stop_click_listener, false);
        }
        automatic_presentation_first_index == null;
        try {
            typed.stop();
            typed.destroy();
        } catch (e) {}
        $('.panorama').css('pointer-events','initial');
        $('.custom-hotspot').removeClass('hidden_icons');
        $('.custom-hotspot img').removeClass('hidden_icons');
        $('.custom-hotspot-content').removeClass('hidden_icons');
        $('.callout').css('pointer-events','none');
        $('.leader-line').removeClass('hidden_icons');
        $('.poi_embed').removeClass('hidden_icons');
        $('.marker_embed').removeClass('hidden_icons');
        $('.controls_control').show();
        $('.presentation_control').show();
        $('.compass_control').css('display','inline-block');
        $('#dialog').hide();
        $('#dialog').css('z-index',0);
        $('.fullscreen_control').css({'opacity':1,'pointer-events':'initial'});
        $('.list_control').css({'opacity':1,'pointer-events':'initial'});
        $('.map_control').css({'opacity':1,'pointer-events':'initial'});
        $('.map_tour_control').css({'opacity':1,'pointer-events':'initial'});
        $('.song_control').css({'opacity':1,'pointer-events':'initial'});
        $('.nav_control').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_left').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_center').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_right').css({'opacity':1,'pointer-events':'initial'});
        $('.logo a').css('pointer-events','initial');
        $('.poweredby a').css('pointer-events','initial');
        $('.pnlm-dragfix').css('pointer-events','initial');
        $('.nav_control').css('pointer-events','initial');
        $('.rooms_view_sel').show();
        if(window.comments!=0) {
            $('.comments_vt').show();
        }
        $('.snipcart-checkout').show();
        $('.woocommerce-checkout').show();
        switch(arrows_nav) {
            case 0:
                $('.arrows_nav').hide();
                break;
            case 1:
                $('.arrows_nav').show();
                break;
            case 2:
                if(window.is_mobile) {
                    $('.arrows_nav').hide();
                } else {
                    $('.arrows_nav').show();
                }
                break;
        }
        if(voice_commands_enable>0) {
            try {
                SpeechKITT.show();
            } catch (e) {}
            if(voice_commands_enable==2) {
                try {
                    if (annyang) { annyang.resume(); }
                } catch (e) {}
            }
        }
        controls_status['orient']=false;
        if(show_map!=0) {
            if(map_opened) {
                $('.map').show();
                $('.map_control').addClass('active_control');
                $('.floorplan_alt_control').addClass('active_control');
                $('.map_control i').removeClass('icon-map_off').addClass('icon-map_on');
                $('.floorplan_alt_control .fa-circle').removeClass('not_active').addClass('active');
                controls_status['map']=true;
            }
        }
        if(icons_active==1) {
            controls_status['icons_content']=true;
            $('.icons_control').addClass('active_control');
            $('.icons_control .fa-circle').removeClass('not_active').addClass('active');
        } else {
            controls_status['icons_content']=false;
            $('.icons_control').removeClass('active_control');
            $('.icons_control .fa-circle').removeClass('active').addClass('not_active');
        }
        if(measures_active==1) {
            controls_status['measures']=true;
            $('.measures_control').addClass('active_control');
            $('.measures_control .fa-circle').removeClass('not_active').addClass('active');
        } else {
            controls_status['measures']=false;
            $('.measures_control').removeClass('active_control');
            $('.measures_control .fa-circle').removeClass('active').addClass('not_active');
        }
        controls_status['list']=false;
        controls_status['share']=false;
        if(song_is_playng) {
            controls_status['song']=true;
            $('.song_control').addClass('active_control');
            $('.song_alt_control').addClass('active_control');
            $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
            $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
            unmute_audio(true,false);
        } else {
            controls_status['song']=false;
            $('.song_control').removeClass('active_control');
            $('.song_alt_control').removeClass('active_control');
            $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
            $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
            mute_audio(true,false);
        }
        $('#btn_stop_presentation').hide();
        $('.menu_controls').show();
        $('.list_alt_menu').show();
        $('#menu_sidebar').show();
        $('.tooltip_text').removeClass('hidden_icons');
        $('.tooltip_text_embed').removeClass('hidden_icons');
        $('.tooltip_text_embed_m').removeClass('hidden_icons');
        $('.tooltip_preview').removeClass('hidden_icons');
        $('.tooltip_preview_m').removeClass('hidden_icons');
        $('.tooltip_preview_rect_m').removeClass('hidden_icons');
        $('.tooltip_preview_square_m').removeClass('hidden_icons');
        if(presentation_type=='automatic') {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                try { pano_viewer.stopAutoRotate(); } catch (e) {}
            } else {
                try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
            }
        }
        if(presentation_stop_id_room!=0) {
            goto("",[presentation_stop_id_room,null,null,null,null,null,null,null]);
        }
        resize_maps();
        if(live_session_connected) {
            if($('.live_status').is(':visible')) {
                var height_h = $('.name_vt').outerHeight()+$('.room_vt').outerHeight()+$('.category_room_vt').outerHeight()+$('.comments_vt').outerHeight()+$('.rooms_view_sel').outerHeight()+10;
                $('.live_status').css('top',height_h+'px');
            }
        }
    }

    function get_id_viewer(id) {
        for(var i=0; i<panoramas.length; i++) {
            if(id==panoramas[i].id) {
                return i;
            }
        }
        return null;
    }

    function presentation_steps(index) {
        if(controls_status['presentation']) {
            if(typeof array_presentation[index] === 'undefined') {
                if(presentation_loop) {
                    index = 0;
                } else {
                    stop_presentation();
                    return;
                }
            }
            if(window.learning_mode>0) {
                if(window.learning_unlock_marker) {
                    if(learning_check_marker_locked(array_presentation[index].id_room)) {
                        presentation_steps(index+1);
                    }
                }
            }
            var action = array_presentation[index].action;
            var params = array_presentation[index].params;
            var sleep_ms = array_presentation[index].sleep;
            var video_wait_end = parseInt(array_presentation[index].video_wait_end);
            var pos = array_presentation[index].pos;
            switch (action) {
                case 'goto':
                    presentation_goto_sleep_ms = sleep_ms;
                    presentation_goto_index = index+1;
                    presentation_goto_params = params;
                    presentation_video_wait_end = video_wait_end;
                    if(pos!='') {
                        var tmp = pos.split(",");
                        var yaw = parseFloat(tmp[0]);
                        var pitch = parseFloat(tmp[1]);
                        var hfov = parseInt(tmp[2]);
                    } else {
                        var yaw = null;
                        var pitch = null;
                        var hfov = null;
                    }
                    if(video_wait_end==1 && !presentation_video_playing) {
                        goto('',[params,null,null,pitch,yaw,null,null,null]);
                    } else {
                        if(presentation_video_playing) {
                            presentation_video_playing_interval = setInterval(function() {
                                if(!presentation_video_playing) {
                                    clearInterval(presentation_video_playing_interval);
                                    goto('',[params,null,null,pitch,yaw,hfov,null,null]);
                                }
                            },1000);
                        } else {
                            goto('',[params,null,null,pitch,yaw,hfov,null,null]);
                        }
                    }
                    break;
                case 'type':
                    type(params,function () {
                        setTimeout(function () {
                            presentation_steps(index+1);
                        },sleep_ms);
                    });
                    break;
                case 'lookAt':
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        pano_viewer.lookAt(parseInt(params[0]),parseInt(params[1]),parseInt(params[2]),parseInt(params[3]),function () {
                            setTimeout(function () {
                                presentation_steps(index+1);
                            },sleep_ms);
                        });
                    } else {
                        video_viewer.pnlmViewer.lookAt(parseInt(params[0]),parseInt(params[1]),parseInt(params[2]),parseInt(params[3]),function () {
                            setTimeout(function () {
                                presentation_steps(index+1);
                            },sleep_ms);
                        });
                    }
                    break;
            }
        }
    }

    var typed;
    function type ( stringArray, onComplete ) {
        onComplete = onComplete || function(){};
        typed = new Typed( "#typed", {
            strings: stringArray,
            typeSpeed: 50,
            showCursor: false,
            startDelay: 0,
            onComplete: onComplete
        });
    }

    function lock (orientation) {
        if (document.documentElement.requestFullscreen) {
            document.documentElement.requestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
            document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
            document.documentElement.webkitRequestFullscreen();
        } else if (document.documentElement.msRequestFullscreen) {
            document.documentElement.msRequestFullscreen();
        }
        try {
            screen.orientation.lock(orientation).then(function() {}).catch(function(error) {});
        } catch (e) {}
    }

    function unlock () {
        try {
            screen.orientation.unlock();
        } catch (e) {}
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }

    window.enable_vr = function () {
        if(window.vr_button==1 && running_in=='web') {
            $.confirm({
                lazyOpen: false,
                theme: 'modern,deivce_motion_prompt',
                useBootstrap: false,
                closeIcon: false,
                typeAnimated: true,
                title: window.viewer_labels.open_vr_msg,
                content: '',
                boxWidth: '250px',
                buttons: {
                    yes: {
                        text: window.viewer_labels.yes,
                        btnClass: 'btn-green',
                        action: function(){
                            let urlParts = window.location.href.split("/");
                            var url = window.location.href.replace('/'+urlParts[urlParts.length-2]+'/','/vr/');
                            if(webvr_new_window==1) {
                                window.open('../vr/redirect_vr.php?n=1&url='+url,'_blank');
                            } else {
                                window.location.href = '../vr/redirect_vr.php?url='+url;
                            }
                        }
                    },
                    cancel: {
                        text: window.viewer_labels.no,
                        action: function(){}
                    },
                }
            });
        } else {
            if(controls_status['map']) {
                map_opened = true;
            } else {
                map_opened = false;
            }
            $('.loading_vr').css('display','flex');
            $('.arrows_nav').hide();
            $('#panorama_viewer').css('width','50%');
            $('#panorama_viewer_vr').show();
            $('#video_viewer').css('width','50%');
            $('#video_viewer_vr').show();
            $('#background_pano').css('width','50%');
            $('.fullscreen_control').css({'opacity':0,'pointer-events':'none'});
            $('.list_control').css({'opacity':0,'pointer-events':'none'});
            $('.map_control').css({'opacity':0,'pointer-events':'none'});
            $('.map_tour_control').css({'opacity':0,'pointer-events':'none'});
            $('.song_control').css({'opacity':0,'pointer-events':'none'});
            $('.nav_control').css({'opacity':0,'pointer-events':'none'});
            $('#controls_bottom_left').css({'opacity':0,'pointer-events':'none'});
            $('#controls_bottom_center').css({'opacity':0,'pointer-events':'none'});
            $('#controls_bottom_right').css({'opacity':0,'pointer-events':'none'});
            $('.annotation').css({'opacity':0,'pointer-events':'none'});
            $('.logo a').css('pointer-events','none');
            $('.logo').hide();
            $('.poweredby a').css('pointer-events','none');
            $('.poweredby').hide();
            $('.cursor_vr').show();
            $('.rooms_view_sel').hide();
            $('.comments_vt').hide();
            $('.snipcart-checkout').hide();
            $('.woocommerce-checkout').hide();
            $('.visitors_rt_stats').hide();
            $('.hotspot-visitor').css({'opacity':0});
            $('.hotspot-visitor-alt').css({'opacity':0});
            $('.stat_visitors_rt_rooms').hide();
            if(voice_commands_enable>0) {
                try {
                    SpeechKITT.hide();
                    if (annyang) { annyang.pause(); }
                } catch (e) {}
            }
            vr_enabled = true;
            $('.menu_controls').hide();
            $('.list_alt_menu').hide();
            $('#menu_sidebar').hide();
            $('.header_vt').css('width','50%');
            $('.header_vt_vr').show();
            $('#btn_stop_vr').show();
            $('#btn_stop_vr_2').show();
            $('.map_tour_control i').removeClass('fas').addClass('far');
            $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
            $('.map_tour_control').removeClass('active_control');
            $('.map_alt_control').removeClass('active_control');
            $('.list_sliders').css('z-index',0);
            $('.list_sliders').css('opacity',0);
            $('.list_control').removeClass('active_control');
            reposition_bottom_controls(false,false,0);
            $('.list_control i, .list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
            close_map_tour();
            $('.orient_control').addClass('active_control');
            $('.orient_control .fa-circle').removeClass('not_active').addClass('active');
            controls_status['orient']=true;
            jQuery.each(panoramas, function(index_p, panorama) {
                jQuery.each(panorama.hotSpots, function(index_h, hotspot) {
                    if(hotspot.object=='marker_embed') {
                        var tmp = [];
                        tmp['index_p'] = index_p;
                        tmp['index_h'] = index_h;
                        tmp['hotspot'] = Object.assign({}, panoramas[index_p].hotSpots[index_h]);
                        tmp['hotspot'].createTooltipArgs = Object.assign({}, panoramas[index_p].hotSpots[index_h].createTooltipArgs);
                        panoramas_tmp.push(tmp);
                        panoramas[index_p].hotSpots[index_h].object = 'marker';
                        panoramas[index_p].hotSpots[index_h].cssClass = 'custom-hotspot custom-hotspot_vr';
                        panoramas[index_p].hotSpots[index_h].createTooltipArgs.background = 'rgba(255,255,255,0.7)';
                        panoramas[index_p].hotSpots[index_h].createTooltipArgs.color = '#000000';
                    }
                });
            });
            controls_status['orient']=true;
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.startOrientation();
            } else {
                video_viewer.pnlmViewer.startOrientation();
            }
            setTimeout(function () {
                lock('landscape-primary');
                goto('',[current_id_panorama,null,null,null,null,null,null,null]);
            },250);
        }
    }

    function show_visitors_stat() {
        if(enable_visitor_rt==1 && enable_views_stat==0) {
            $('.visitors_rt_stats').show();
            $('.views_block').hide();
            $('.visitors_block').css('display','inline-block');
            $('.separator_block').hide();
            $('.stat_visitors_rt_rooms').removeClass('hidden');
        } else if(enable_visitor_rt==0 && enable_views_stat==1) {
            $('.visitors_rt_stats').show();
            $('.views_block').css('display','inline-block');
            $('.visitors_block').hide();
            $('.separator_block').hide();
            $('.stat_visitors_rt_rooms').addClass('hidden');
        } else if(enable_visitor_rt==1 && enable_views_stat==1) {
            $('.visitors_rt_stats').show();
            $('.views_block').css('display','inline-block');
            $('.visitors_block').css('display','inline-block');
            $('.separator_block').css('display','inline-block');
            $('.stat_visitors_rt_rooms').removeClass('hidden');
            if(window.is_mobile) {
                $('.separator_block').html('<br>');
                $('.separator_block').css('display','block');
                $('.visitors_rt_stats').css('line-height','2px');
                $('.visitors_rt_stats').css('padding','2px 10px');
                $('.visitors_rt_stats').css('font-size','10px');
            }
        }
    }

    window.disable_vr = function () {
        if ('orientation' in screen) {
            try {
                screen.orientation.unlock();
            } catch (e) {}
        }
        $('.loading_vr').css('display','flex');
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            $('#panorama_viewer').css('width','100%');
            $('#panorama_viewer_vr').hide();
        } else {
            $('#video_viewer').css('width','100%');
            $('#video_viewer_vr').hide();
        }
        $('#background_pano').css('width','100%');
        $('.cursor_vr').hide();
        $('.fullscreen_control').css({'opacity':1,'pointer-events':'initial'});
        $('.list_control').css({'opacity':1,'pointer-events':'initial'});
        $('.map_control').css({'opacity':1,'pointer-events':'initial'});
        $('.map_tour_control').css({'opacity':1,'pointer-events':'initial'});
        $('.song_control').css({'opacity':1,'pointer-events':'initial'});
        $('.nav_control').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_left').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_center').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_right').css({'opacity':1,'pointer-events':'initial'});
        $('.annotation').css({'opacity':1,'pointer-events':'initial'});
        $('.logo a').css('pointer-events','initial');
        $('.logo').show();
        $('.poweredby a').css('pointer-events','initial');
        $('.poweredby').show();
        $('.pnlm-controls-container').show();
        $('.rooms_view_sel').show();
        $('.hotspot-visitor').css({'opacity':1});
        $('.hotspot-visitor-alt').css({'opacity':1});
        $('.snipcart-checkout').show();
        $('.woocommerce-checkout').show();
        show_visitors_stat();
        if(voice_commands_enable>0) {
            try {
                SpeechKITT.show();
            } catch (e) {}
            if(voice_commands_enable==2) {
                try {
                    if (annyang) { annyang.resume(); }
                } catch (e) {}
            }
        }
        if(show_map!=0) {
            if(map_opened) {
                $('.map').show();
                $('.map_control').addClass('active_control');
                $('.floorplan_alt_control').addClass('active_control');
                $('.map_control i').removeClass('icon-map_off').addClass('icon-map_on');
                $('.floorplan_alt_control .fa-circle').removeClass('not_active').addClass('active');
                controls_status['map']=true;
            }
        }
        controls_status['icons_content']=true;
        controls_status['icons_nav']=true;
        controls_status['measures']=true;
        controls_status['list']=false;
        controls_status['share']=false;
        if(arrows_nav) {
            $('.arrows_nav').show();
        }
        if(show_info>0) {
            $('.info_control').show();
        } else {
            $('.info_control').hide();
        }
        if(show_custom>0) {
            $('.custom_control').show();
        } else {
            $('.custom_control').hide();
        }
        if(show_dollhouse>0) {
            $('.dollhouse_control').show();
        } else {
            $('.dollhouse_control').hide();
        }
        clearInterval(interval_position);
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try {
                pano_viewer_vr.off('load');
                pano_viewer_vr.destroy();
            } catch (e) {}
        } else {
            try {
                video_viewer_vr.pnlmViewer.destroy();
                video_viewer_vr.dispose();
            } catch (e) {}
        }
        vr_enabled = false;
        $('.menu_controls').show();
        $('.list_alt_menu').show();
        $('#menu_sidebar').show();
        $('.header_vt').css('width','100%');
        $('.header_vt_vr').hide();
        if(window.comments!=0) {
            $('.comments_vt').show();
        }
        $('#btn_stop_vr').hide();
        $('#btn_stop_vr_2').hide();
        $('.orient_control').removeClass('active_control');
        $('.orient_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['orient']=false;
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.stopOrientation();
            pano_viewer_vr.stopOrientation();
        } else {
            video_viewer.pnlmViewer.stopOrientation();
            video_viewer_vr.pnlmViewer.stopOrientation();
        }
        jQuery.each(panoramas_tmp, function(index_tmp, panorama_tmp) {
            var index_p = panorama_tmp['index_p'];
            var index_h = panorama_tmp['index_h'];
            var hotspot_tmp = panorama_tmp['hotspot'];
            panoramas[index_p].hotSpots[index_h] = Object.assign({}, hotspot_tmp);
            panoramas[index_p].hotSpots[index_h].createTooltipArgs = Object.assign({}, hotspot_tmp.createTooltipArgs);
        });
        goto('',[current_id_panorama,null,null,null,null,null,null,null]);
        setTimeout(function () {
            $('.loading_vr').hide();
            unlock();
        },1000);
    }

    window.initialize_speech = function () {
        if (annyang) {
            if(window.export_mode==1) {
                $.getJSON('ajax/'+window.voice_commands_json,function(rsp) {
                    initialize_voice_commands(rsp);
                });
            } else {
                $.ajax({
                    url: "ajax/get_voice_commands.php",
                    type: "POST",
                    data: {
                        id_virtualtour: window.id_virtualtour
                    },
                    async: false,
                    success: function (json) {
                        var rsp = JSON.parse(json);
                        initialize_voice_commands(rsp);
                    }
                });
            }
        }
    }

    function initialize_voice_commands(rsp) {
        if(rsp.status=='ok') {
            var commands = [];
            var voice_commands = rsp.voice_commands[0];
            annyang.setLanguage(voice_commands.language);
            commands.push({
                phrase : voice_commands.help_cmd,
                callback : function() {
                    annyang.pause();
                    SpeechKITT.setInstructionsText(voice_commands.help_msg_1);
                    setTimeout(function () {
                        SpeechKITT.setInstructionsText(voice_commands.help_msg_2);
                        setTimeout(function () {
                            SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                            annyang.resume();
                        },4000);
                    },4000);
                }
            });
            commands.push({
                phrase : voice_commands.next_cmd,
                callback : function() {
                    annyang.pause();
                    $('#skitt-ui').addClass('ok');
                    $('#skitt-toggle-button').addClass('ok');
                    SpeechKITT.setInstructionsText(voice_commands.next_msg);
                    var len = panoramas.length;
                    var index = get_id_viewer(current_id_panorama);
                    var next_panorama = panoramas[(index+1)%len];
                    goto('',[next_panorama.id,null,null,null,null,null,null,null]);
                    setTimeout(function () {
                        $('#skitt-ui').removeClass('ok');
                        $('#skitt-toggle-button').removeClass('ok');
                        SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                        annyang.resume();
                    },1500);
                }
            });
            commands.push({
                phrase : voice_commands.prev_cmd,
                callback : function() {
                    annyang.pause();
                    $('#skitt-ui').addClass('ok');
                    $('#skitt-toggle-button').addClass('ok');
                    SpeechKITT.setInstructionsText(voice_commands.prev_msg);
                    var len = panoramas.length;
                    var index = get_id_viewer(current_id_panorama);
                    var prev_panorama = panoramas[(index+len-1)%len];
                    goto('',[prev_panorama.id,null,null,null,null,null,null,null]);
                    setTimeout(function () {
                        $('#skitt-ui').removeClass('ok');
                        $('#skitt-toggle-button').removeClass('ok');
                        SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                        annyang.resume();
                    },1500);
                }
            });
            commands.push({
                phrase : voice_commands.left_cmd,
                callback : function() {
                    annyang.pause();
                    $('#skitt-ui').addClass('ok');
                    $('#skitt-toggle-button').addClass('ok');
                    SpeechKITT.setInstructionsText(voice_commands.left_msg);
                    window.viewer_mov_pos_change = false;
                    window.viewer_mov_follow_mouse = false;
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var yaw_s = pano_viewer.getYaw();
                        var pitch_s = pano_viewer.getPitch();
                        var hfov_s = pano_viewer.getHfov();
                        yaw_s = yaw_s - 90;
                        pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    } else {
                        var yaw_s = video_viewer.pnlmViewer.getYaw();
                        var pitch_s = video_viewer.pnlmViewer.getPitch();
                        var hfov_s = video_viewer.pnlmViewer.getHfov();
                        yaw_s = yaw_s - 90;
                        video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    }
                    setTimeout(function () {
                        $('#skitt-ui').removeClass('ok');
                        $('#skitt-toggle-button').removeClass('ok');
                        SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                        annyang.resume();
                    },1500);
                }
            });
            commands.push({
                phrase : voice_commands.right_cmd,
                callback : function() {
                    annyang.pause();
                    $('#skitt-ui').addClass('ok');
                    $('#skitt-toggle-button').addClass('ok');
                    SpeechKITT.setInstructionsText(voice_commands.right_msg);
                    window.viewer_mov_pos_change = false;
                    window.viewer_mov_follow_mouse = false;
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var yaw_s = pano_viewer.getYaw();
                        var pitch_s = pano_viewer.getPitch();
                        var hfov_s = pano_viewer.getHfov();
                        yaw_s = yaw_s + 90;
                        pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    } else {
                        var yaw_s = video_viewer.pnlmViewer.getYaw();
                        var pitch_s = video_viewer.pnlmViewer.getPitch();
                        var hfov_s = video_viewer.pnlmViewer.getHfov();
                        yaw_s = yaw_s + 90;
                        video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    }
                    setTimeout(function () {
                        $('#skitt-ui').removeClass('ok');
                        $('#skitt-toggle-button').removeClass('ok');
                        SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                        annyang.resume();
                    },1500);
                }
            });
            commands.push({
                phrase : voice_commands.up_cmd,
                callback : function() {
                    annyang.pause();
                    $('#skitt-ui').addClass('ok');
                    $('#skitt-toggle-button').addClass('ok');
                    SpeechKITT.setInstructionsText(voice_commands.up_msg);
                    window.viewer_mov_pos_change = false;
                    window.viewer_mov_follow_mouse = false;
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var yaw_s = pano_viewer.getYaw();
                        var pitch_s = pano_viewer.getPitch();
                        var hfov_s = pano_viewer.getHfov();
                        pitch_s = pitch_s + 45;
                        pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    } else {
                        var yaw_s = video_viewer.pnlmViewer.getYaw();
                        var pitch_s = video_viewer.pnlmViewer.getPitch();
                        var hfov_s = video_viewer.pnlmViewer.getHfov();
                        pitch_s = pitch_s + 45;
                        video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    }
                    setTimeout(function () {
                        $('#skitt-ui').removeClass('ok');
                        $('#skitt-toggle-button').removeClass('ok');
                        SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                        annyang.resume();
                    },1500);
                }
            });
            commands.push({
                phrase : voice_commands.down_cmd,
                callback : function() {
                    annyang.pause();
                    $('#skitt-ui').addClass('ok');
                    $('#skitt-toggle-button').addClass('ok');
                    SpeechKITT.setInstructionsText(voice_commands.down_msg);
                    window.viewer_mov_pos_change = false;
                    window.viewer_mov_follow_mouse = false;
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        var yaw_s = pano_viewer.getYaw();
                        var pitch_s = pano_viewer.getPitch();
                        var hfov_s = pano_viewer.getHfov();
                        pitch_s = pitch_s - 45;
                        pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    } else {
                        var yaw_s = video_viewer.pnlmViewer.getYaw();
                        var pitch_s = video_viewer.pnlmViewer.getPitch();
                        var hfov_s = video_viewer.pnlmViewer.getHfov();
                        pitch_s = pitch_s - 45;
                        video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,2000,function() {
                            window.viewer_mov_pos_change = true;
                            current_viewer_pitch = pitch_s;
                            current_viewer_yaw = yaw_s;
                            if(mouse_follow_feedback!=0) {
                                window.viewer_mov_follow_mouse = true;
                            }
                        });
                    }
                    setTimeout(function () {
                        $('#skitt-ui').removeClass('ok');
                        $('#skitt-toggle-button').removeClass('ok');
                        SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                        annyang.resume();
                    },1500);
                }
            });
            annyang.addCommandsWithDynamicText(commands);
            annyang.addCallback('start', function() {
                controls_status['song']=false;
                $('.controls_bottom.bar-btn #controls_bottom_left').css('overflow','initial');
                $('.song_control').removeClass('active_control');
                $('.song_alt_control').removeClass('active_control');
                $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
                $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
                mute_audio(true,true);
            });
            annyang.addCallback('end', function() {
                controls_status['song']=true;
                SpeechKITT.abortRecognition();
                $('.controls_bottom.bar-btn #controls_bottom_left').css('overflow','hidden');
                $('.song_control').addClass('active_control');
                $('.song_alt_control').addClass('active_control');
                $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                unmute_audio(true,false);
            });
            annyang.addCallback('resultNoMatch', function(userSaid, commandText, phrases) {
                annyang.pause();
                $('#skitt-ui').addClass('error');
                $('#skitt-toggle-button').addClass('error');
                SpeechKITT.setInstructionsText(voice_commands.error_msg);
                setTimeout(function () {
                    $('#skitt-ui').removeClass('error');
                    $('#skitt-toggle-button').removeClass('error');
                    SpeechKITT.setInstructionsText(voice_commands.listening_msg);
                    annyang.resume();
                },3000);
            });
            SpeechKITT.annyang();
            SpeechKITT.setStartCommand(function() {
                annyang.start({ autoRestart: true, continuous: true, paused: false });
            });
            if(window.export_mode==1) {
                SpeechKITT.setStylesheet('css/skflat.css?v=15');
            } else {
                SpeechKITT.setStylesheet('vendor/SpeechKITT/themes/flat.css?v=15');
            }
            SpeechKITT.setInstructionsText(voice_commands.initial_msg);
            $('.voice_control').show();
            reposition_voice_control();
            SpeechKITT.render();
            $("#skitt-ui").appendTo(".voice_control");
            if(voice_commands_enable==2) {
                annyang.resume();
            }
        }
    }

    window.click_menu_controls = function () {
        if(window.sidebar_enable) {
            $('#menu_sidebar').addClass('open');
        } else {
            $('.menu_controls .dropdown')[0].classList.toggle('down');
            $('.menu_controls .arrow')[0].classList.toggle('gone');
            if ($('.menu_controls .dropdown')[0].classList.contains('down')) {
                close_list_alt_menu();
            }
        }
    }

    window.close_menu_sidebar = function () {
        $('#menu_sidebar').removeClass('open');
    }

    window.click_list_alt_menu = function () {
        $('.list_alt_menu .dropdown')[0].classList.toggle('down');
        $('.list_alt_menu .arrow')[0].classList.toggle('gone');
        if ($('.list_alt_menu .dropdown')[0].classList.contains('down')) {
            close_menu_controls();
        }
    }

    window.click_language_menu = function() {
        $('.language_menu .dropdown')[0].classList.toggle('down');
        $('.language_menu .arrow')[0].classList.toggle('gone');
    }

    window.close_menu_controls = function () {
        $('.menu_controls .dropdown')[0].classList.remove('down');
        $('.menu_controls .arrow')[0].classList.remove('gone');
    }

    window.close_list_alt_menu = function () {
        $('.list_alt_menu .dropdown')[0].classList.remove('down');
        $('.list_alt_menu .arrow')[0].classList.remove('gone');
    }

    window.close_language_menu = function () {
        $('.language_menu .dropdown')[0].classList.remove('down');
        $('.language_menu .arrow')[0].classList.remove('gone');
    }

    window.init_peer = function() {
        if(peer_id=='') {
            init_sender_viewer();
            $('.live_status span').html(window.viewer_labels.ls_initializing);
            $('#btn_live_end').hide();
            $('#btn_link_session').hide();
            $('#btn_lock_session').hide();
            $('#btn_live_status').css('color','black');
            var height_h = $('.name_vt').outerHeight()+$('.room_vt').outerHeight()+$('.category_room_vt').outerHeight()+$('.comments_vt').outerHeight()+$('.rooms_view_sel').outerHeight()+10;
            $('.live_status').css('top',height_h+'px');
            $('.live_call').show();
            $(".video_my_wrapper").draggable({ containment: "#vt_container" });
            $(".video_remote_wrapper").draggable({ containment: "#vt_container" });
            if(peer_turn_host!='') {
                if(peer_turn_u!='' && peer_turn_p!='') {
                    window.peer = new Peer(null,{
                        config: {'iceServers': [
                                {url: 'stun:'+peer_turn_host+':'+peer_turn_port},
                                {url: 'turn:'+peer_turn_host+':'+peer_turn_port, username:peer_turn_u, credential:peer_turn_p},
                            ]},
                        host: peer_server_host,
                        port: peer_server_port,
                        path: peer_server_path,
                        secure: true,
                        debug: 2
                    });
                } else {
                    window.peer = new Peer(null,{
                        config: {'iceServers': [
                                {url: 'stun:'+peer_turn_host+':'+peer_turn_port},
                                {url: 'turn:'+peer_turn_host+':'+peer_turn_port},
                            ]},
                        host: peer_server_host,
                        port: peer_server_port,
                        path: peer_server_path,
                        secure: true,
                        debug: 2
                    });
                }
            } else {
                window.peer = new Peer(null,{
                    host: peer_server_host,
                    port: peer_server_port,
                    path: peer_server_path,
                    secure: true,
                    debug: 2
                });
            }
            peer.on('open', function(id) {
                id_live_session = id;
                $.confirm({
                    useBootstrap: false,
                    closeIcon: false,
                    type: 'blue',
                    theme: 'modern',
                    typeAnimated: true,
                    title: window.viewer_labels.lsc_title,
                    content: window.viewer_labels.ls_webcam_msg,
                    buttons: {
                        video: {
                            text: '<i class="fas fa-video"></i> '+window.viewer_labels.ls_video_audio,
                            action: function(){
                                webcam_audio = true;
                                webcam_video = true;
                                init_sender();
                                $('.live_status span').html(window.viewer_labels.ls_awaiting);
                                $('#btn_live_end').show();
                                $('#btn_link_session').show();
                                $('#btn_live_status').css('color','orange');
                                open_live_link_modal();
                            }
                        },
                        audio : {
                            text: '<i class="fas fa-microphone"></i> '+window.viewer_labels.ls_audio,
                            action: function(){
                                webcam_audio = true;
                                webcam_video = false;
                                init_sender();
                                $('.live_status span').html(window.viewer_labels.ls_awaiting);
                                $('#btn_live_end').show();
                                $('#btn_link_session').show();
                                $('#btn_live_status').css('color','orange');
                                open_live_link_modal();
                            }
                        },
                    }
                });
            });
            peer.on('error', function (err) {
                if(err.toString().indexOf('concurrent') !== -1) {
                    setTimeout(function () {
                        init_peer();
                    },2000);
                } else if(err.toString().indexOf('not get an ID') !== -1) {
                    setTimeout(function () {
                        init_peer();
                    },2000);
                } else {
                    alert(err);
                    try {
                        window.stream_sender.getTracks().forEach(function(track) { track.stop(); })
                    } catch (e) {}
                    try {
                        call_session.close();
                    } catch (e) {}
                    $('#webcam_my').hide();
                    peer.destroy();
                    live_session_connected = false;
                    clearInterval(interval_live_session);
                    $('.live_call').hide();
                    $('.live_control').removeClass('active_control');
                    $('.live_control').removeClass('disabled');
                    $('.meeting_control').removeClass('disabled');
                    exit_sender_viewer();
                }
            });
        } else {
            init_receiver_viewer();
            $('.live_status').css('width','180px');
            $('.live_status').css('left','calc(50% - 90px)');
            var height_h = $('.name_vt').outerHeight()+$('.room_vt').outerHeight()+$('.category_room_vt').outerHeight()+$('.comments_vt').outerHeight()+$('.rooms_view_sel').outerHeight()+10;
            $('.live_status').css('top',height_h+'px');
            $('.live_call').show();
            $(".video_my_wrapper").draggable({ containment: "#vt_container" });
            $(".video_remote_wrapper").draggable({ containment: "#vt_container" });
            if(peer_turn_host!='') {
                if(peer_turn_u!='' && peer_turn_p!='') {
                    window.peer = new Peer(null,{
                        config: {'iceServers': [
                                {url: 'stun:'+peer_turn_host+':'+peer_turn_port},
                                {url: 'turn:'+peer_turn_host+':'+peer_turn_port, username:peer_turn_u, credential:peer_turn_p},
                            ]},
                        host: peer_server_host,
                        port: peer_server_port,
                        path: peer_server_path,
                        secure: true,
                        debug: 2
                    });
                } else {
                    window.peer = new Peer(null,{
                        config: {'iceServers': [
                                {url: 'stun:'+peer_turn_host+':'+peer_turn_port},
                                {url: 'turn:'+peer_turn_host+':'+peer_turn_port},
                            ]},
                        host: peer_server_host,
                        port: peer_server_port,
                        path: peer_server_path,
                        secure: true,
                        debug: 2
                    });
                }
            } else {
                window.peer = new Peer(null,{
                    host: peer_server_host,
                    port: peer_server_port,
                    path: peer_server_path,
                    secure: true,
                    debug: 2
                });
            }
            peer.on('open', function(id) {
                $.confirm({
                    useBootstrap: false,
                    closeIcon: false,
                    type: 'blue',
                    theme: 'modern',
                    typeAnimated: true,
                    title: window.viewer_labels.lsc_title,
                    content: window.viewer_labels.ls_webcam_msg,
                    buttons: {
                        video: {
                            text: '<i class="fas fa-video"></i> '+window.viewer_labels.ls_video_audio,
                            action: function(){
                                webcam_audio = true;
                                webcam_video = true;
                                $('.live_status span').html(window.viewer_labels.ls_connecting);
                                $('#btn_live_status').css('color','orange');
                                init_receiver();
                            }
                        },
                        audio : {
                            text: '<i class="fas fa-microphone"></i> '+window.viewer_labels.ls_audio,
                            action: function(){
                                webcam_audio = true;
                                webcam_video = false;
                                $('.live_status span').html(window.viewer_labels.ls_connecting);
                                $('#btn_live_status').css('color','orange');
                                init_receiver();
                            }
                        },
                    }
                });
            });
            peer.on('error', function (err) {
                if(err.toString().indexOf('concurrent') !== -1) {
                    setTimeout(function () {
                        init_peer();
                    },2000);
                } else if(err.toString().indexOf('not get an ID') !== -1) {
                    setTimeout(function () {
                        init_peer();
                    },2000);
                } else if(err.toString().indexOf('Lost connection') !== -1) {
                    setTimeout(function () {
                        init_peer();
                    },2000);
                } else if(err.toString().indexOf('not connect to peer') !== -1) {
                    $('.live_status span').html(window.viewer_labels.ls_invalid);
                    $('#btn_live_status').css('color','red');
                    setTimeout(function () {
                        try {
                            window.stream_sender.getTracks().forEach(function(track) { track.stop(); })
                        } catch (e) {}
                        try {
                            call_session.close();
                        } catch (e) {}
                        $('#webcam_my').hide();
                        peer.destroy();
                        $('.live_call').hide();
                        exit_receiver_viewer();
                    },5000);
                }
            });
        }
    }

    window.open_live_link_modal = function () {
        var link_live = window.url_vt+"index.php?code="+window.code+"&peer_id="+id_live_session;
        var link_live_share = link_live.replace("&","%26");
        var html_live = '<div class="modal_live_link">' +
            '<span style="margin: 0 auto;">'+window.viewer_labels.ls_link_msg+'</span><br><br>' +
            '<textarea id="live_link" rows="3" style="width:100%;padding:5px;" readonly>'+link_live+'</textarea><br>'+
            '<i data-clipboard-target="#live_link" class="fas fa-clipboard"></i> <a target="_blank" href="mailto:?body='+link_live_share+'"><i class="fas fa-envelope"></i></a> <a target="_blank" href="https://wa.me/?text='+link_live_share+'"><i class="fab fa-whatsapp"></i></a>'+
            '</div>';
        $.fancybox.open({
            clickSlide: false,
            clickOutside: false,
            smallBtn: false,
            touch: false,
            src  : html_live,
            type : 'html',
            afterShow : function () {
                new ClipboardJS('.modal_live_link i');
            }
        });
    }

    function check_getUserMedia() {
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function(constraints) {
                var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
                if (!getUserMedia) {
                    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                }
                return new Promise(function(resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                });
            }
        }
    }

    function init_sender() {
        check_getUserMedia();
        navigator.mediaDevices.getUserMedia({
            video: webcam_video,
            audio: webcam_audio
        }).then(function(stream) {
            $('#webcam_my').show();
            if ("srcObject" in window.webcam_my) {
                window.webcam_my.srcObject = stream;
            } else {
                window.webcam_my.src = window.URL.createObjectURL(stream);
            }
            window.webcam_my.volume = 0;
            window.webcam_my.onloadedmetadata = function(e) {
                window.webcam_my.play();
            };
            window.stream_sender = stream;
            peer.on('call', function(call) {
                call_session = call;
                call.answer(stream);
                call.on('stream', function(remoteStream) {
                    $('#webcam_remote').show();
                    if ("srcObject" in window.webcam_remote) {
                        window.webcam_remote.srcObject = remoteStream;
                    } else {
                        window.webcam_remote.src = window.URL.createObjectURL(remoteStream);
                    }
                    window.webcam_remote.onloadedmetadata = function(e) {
                        window.webcam_remote.play();
                    };
                });
            });
        }).catch((err) => {
            console.log('Failed to get local stream:' + err);
        });
        window.peer.on('connection', function(conn) {
            if (window.peer_conn && window.peer_conn.open) {
                conn.on('open', function() {
                    setTimeout(function() { conn.close(); }, 500);
                });
                return;
            }
            window.peer_conn = conn;
            window.peer_conn.on('data', function(data) {
                switch(data.type) {
                    case 'chat':
                        if(!$('.floating-chat').hasClass('expand')) {
                            $('.floating-chat').addClass('blink');
                        }
                        receiveMessage(data.message);
                        break;
                }
            });
            window.peer_conn.on('close', function() {
                live_session_connected = false;
                clearInterval(interval_live_session);
                $('.live_status span').html(window.viewer_labels.ls_awaiting);
                $('#webcam_remote').hide();
                $('#btn_live_status').css('color','orange');
                window.peer_conn = null;
            });
            $.fancybox.close(true);
            setTimeout(function() {
                live_chat.addClass('enter');
                live_chat.click(openLiveChat);
                $('#webcam_remote').show();
                $('.live_status span').html(window.viewer_labels.ls_connected);
                $('#btn_live_status').css('color','green');
                $('#btn_lock_session').show();
                live_session_connected = true;
                controls_status['auto_rotate'] = false;
                goto('',[panoramas[0].id,null,null,null,null,null,null,null]);
            }, 1000);
        });
    }

    function createEmptyVideoTrack({ width, height }) {
        const canvas = Object.assign(document.createElement('canvas'), { width, height });
        canvas.getContext('2d').fillRect(0, 0, width, height);
        const stream = canvas.captureStream();
        const track = stream.getVideoTracks()[0];
        return Object.assign(track, { enabled: false });
    };

    function init_receiver() {
        check_getUserMedia();
        window.peer_conn = window.peer.connect(peer_id, {
            reliable: true
        });
        window.peer_conn.on('open', function() {
            navigator.mediaDevices.getUserMedia({
                video: webcam_video,
                audio: webcam_audio
            }).then(function(stream) {
                if ("srcObject" in window.webcam_remote) {
                    window.webcam_remote.srcObject = stream;
                } else {
                    window.webcam_remote.src = window.URL.createObjectURL(stream);
                }
                window.webcam_remote.volume = 0;
                window.webcam_remote.onloadedmetadata = function(e) {
                    window.webcam_remote.play();
                };
                if(!webcam_video) {
                    let w = 640;
                    let h = 480;
                    let canvas = Object.assign(document.createElement("canvas"), { w, h });
                    canvas.getContext('2d').fillRect(0, 0, w, h);
                    let blackStream = canvas.captureStream();
                    stream.addTrack(blackStream.getVideoTracks()[0]);
                    $('#webcam_my').hide();
                } else {
                    $('#webcam_my').show();
                }
                window.stream_sender = stream;
                var call = peer.call(peer_id, window.stream_sender);
                call_session = call;
                call.on('stream', function(remoteStream) {
                    $('#webcam_remote').show();
                    if ("srcObject" in window.webcam_my) {
                        window.webcam_my.srcObject = remoteStream;
                    } else {
                        window.webcam_my.src = window.URL.createObjectURL(remoteStream);
                    }
                    window.webcam_my.onloadedmetadata = function(e) {
                        window.webcam_my.play();
                    };
                });
            }).catch(() => {
                console.log('Failed to get local stream');
                var videoTrack = createEmptyVideoTrack({ width: 500, height: 500 })
                var empty_stream = new MediaStream([ videoTrack]);
                var call = peer.call(peer_id, empty_stream);
                call_session = call;
                call.on('stream', function(remoteStream) {
                    $('#webcam_remote').show();
                    window.webcam_my.srcObject = remoteStream;
                });
            });
            setTimeout(function() {
                live_chat.addClass('enter');
                live_chat.click(openLiveChat);
                $('.live_status span').html(window.viewer_labels.ls_connected);
                $('#btn_live_status').css('color','green');
                $('#btn_live_end').attr('onclick','close_live_receiver()');
                $('#btn_live_end').show();
                controls_status['auto_rotate'] = false;
                live_session_connected = true;
            }, 1000);
        });
        window.peer_conn.on('data', function(data) {
            switch(data.type) {
                case 'lock':
                    $.fancybox.close(true);
                    try {
                        gallery.nanogallery2('closeViewer');
                    } catch (e) {}
                    try {
                        poi_gallery.nanogallery2('closeViewer');
                    } catch (e) {}
                    lock_receiver_viewer();
                    break;
                case 'unlock':
                    unlock_receiver_viewer();
                    break;
                case 'chat':
                    if(!$('.floating-chat').hasClass('expand')) {
                        $('.floating-chat').addClass('blink');
                    }
                    receiveMessage(data.message);
                    break;
                case 'goto':
                    if(lock_viewer) {
                        if(!controls_status['presentation']) {
                            controls_status['auto_rotate'] = false;
                            goto('',data.args);
                        }
                    }
                    break;
                case 'change_room_alt':
                    if(lock_viewer) {
                        change_room_alt(data.args);
                    }
                    break;
                case'lookAt':
                    if(!controls_status['presentation']) {
                        if(lock_viewer) {
                            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                pano_viewer.lookAt(parseInt(data.pitch),parseInt(data.yaw),parseInt(data.hfov));
                            } else {
                                video_viewer.pnlmViewer.lookAt(parseInt(data.pitch),parseInt(data.yaw),parseInt(data.hfov));
                            }
                        }
                    }
                    break;
                case 'view_content':
                    if(lock_viewer) {
                        switch(data.args.type) {
                            case 'link':
                            case 'pdf':
                            case 'video':
                                try { $('.hotspot_'+data.args.id)[0].dispatchEvent(event_simulate_click); } catch (e) {}
                                try { $('.hotspot_'+data.args.id+' a')[0].dispatchEvent(event_simulate_click); } catch (e) {}
                                break;
                            default:
                                view_content('',data.args);
                                break;
                        }
                    }
                    break;
                case 'close_content':
                    if(lock_viewer) {
                        $.fancybox.close(true);
                    }
                    break;
                case 'view_video':
                    if(lock_viewer) {
                        $('#'+data.id).trigger('click');
                    }
                    break;
                case 'open_gallery':
                    if(lock_viewer) {
                        open_gallery();
                    }
                    break;
                case 'close_gallery':
                    if(lock_viewer) {
                        try {
                            gallery.nanogallery2('closeViewer');
                        } catch (e) {}
                        try {
                            poi_gallery.nanogallery2('closeViewer');
                        } catch (e) {}
                    }
                    break;
                case 'open_map_tour':
                    if(lock_viewer) {
                        $('.map_tour_control i').removeClass('far').addClass('fas');
                        $('.map_alt_control .fa-circle').removeClass('not_active').addClass('active');
                        $('.map_tour_control').addClass('active_control');
                        $('.map_alt_control').addClass('active_control');
                        open_map_tour();
                    }
                    break;
                case 'close_map_tour':
                    if(lock_viewer) {
                        $('.map_tour_control i').removeClass('fas').addClass('far');
                        $('.map_alt_control .fa-circle').removeClass('active').addClass('not_active');
                        $('.map_tour_control').removeClass('active_control');
                        $('.map_alt_control').removeClass('active_control');
                        close_map_tour();
                    }
                    break;
                case 'drag_vs':
                    if(lock_viewer) {
                        var perc_left = data.args;
                        $('#vs_slider').css('left',perc_left+'%');
                        $('#vs_before').css('width',perc_left+'%');
                        $('#vs_grab').css('left','calc('+perc_left+'% - 15px)');
                    }
                    break;
                case 'open_map':
                    if(lock_viewer) {
                        open_map();
                    }
                    break;
                case 'close_map':
                    if(lock_viewer) {
                        close_map();
                    }
                    break;
                case 'open_annotations':
                    if(lock_viewer) {
                        open_annotations();
                    }
                    break;
                case 'close_annotations':
                    if(lock_viewer) {
                        close_annotations();
                    }
                    break;
                case 'start_presentation':
                    if(lock_viewer) {
                        start_presentation_l();
                    }
                    break;
                case 'stop_presentation':
                    if(lock_viewer) {
                        stop_presentation_l();
                    }
                    break;
                case 'open_info':
                    if(lock_viewer) {
                        view_info_box();
                    }
                    break;
                case 'view_dollhouse':
                    if(lock_viewer) {
                        view_dollhouse();
                    }
                    break;
                case 'close_dollhouse':
                    if(lock_viewer) {
                        close_dollhouse();
                    }
                    break;
                case 'view_location_box':
                    if(lock_viewer) {
                        view_location_box();
                    }
                    break;
                case 'view_custom_box':
                    if(lock_viewer) {
                        view_custom_box();
                    }
                    break;
                case 'view_custom2_box':
                    if(lock_viewer) {
                        view_custom2_box();
                    }
                    break;
                case 'view_custom3_box':
                    if(lock_viewer) {
                        view_custom3_box();
                    }
                    break;
            }
        });
        window.peer_conn.on('disconnected', function () {
            console.log('Connection lost. Please reconnect');
        });
        window.peer_conn.on('close', function() {
            console.log('Connection closed');
            $('#btn_live_end').hide();
            $('.live_status span').html(window.viewer_labels.ls_connection_closed);
            $('#btn_live_status').css('color','red');
            setTimeout(function () {
                try {
                    window.stream_sender.getTracks().forEach(function(track) { track.stop(); })
                } catch (e) {}
                try {
                    call_session.close();
                } catch (e) {}
                $('#webcam_my').hide();
                peer.destroy();
                $('.live_call').hide();
                exit_receiver_viewer();
            },2000);
        });
        window.peer_conn.on('error', function (err) {
            console.log(err);
        });
    }

    window.lock_receiver = function() {
        peer_conn.send({type:'lock'});
        goto('',[current_id_panorama,null,null,null,null,null,null,null]);
        $('#btn_lock_session').addClass('disabled');
        $('#btn_lock_session').attr('onclick','unlock_receiver()');
        $('#btn_lock_session').addClass('fa-lock').removeClass('fa-unlock-alt');
        setTimeout(function() {
            $('#btn_lock_session').removeClass('disabled');
        },2000);
    }

    window.unlock_receiver = function() {
        peer_conn.send({type:'unlock'});
        $('#btn_lock_session').addClass('disabled');
        $('#btn_lock_session').attr('onclick','lock_receiver()');
        $('#btn_lock_session').addClass('fa-unlock-alt').removeClass('fa-lock');
        setTimeout(function() {
            $('#btn_lock_session').removeClass('disabled');
        },2000);
    }

    function lock_receiver_viewer() {
        lock_viewer = true;
        $('.msg_lock').show();
        $('#div_panoramas').addClass('locked');
        $('.arrows_nav').addClass('hidden_lc');
    }

    function unlock_receiver_viewer() {
        lock_viewer = false;
        $('#div_panoramas').removeClass('locked');
        $('.arrows_nav').removeClass('hidden_lc');
        $('.msg_lock').hide();
    }

    function init_receiver_viewer() {
        lock_receiver_viewer();
        $('.song_control').addClass('hidden_lc');
        $('.song_alt_control').addClass('hidden_lc');
        $('.comments_vt').addClass('hidden_lc');
        $('.visitors_rt_stats').addClass('hidden_lc');
        $('.div_visitor_wrapper').addClass('hidden_lc');
        $('.meeting_control').addClass('hidden_lc');
        $('.live_control').addClass('hidden_lc');
        $('.list_sliders').css('pointer-events','none');
        $('#controls_bottom_left').addClass('hidden_lc');
        $('#controls_bottom_center').addClass('hidden_lc');
        $('#controls_bottom_right').addClass('hidden_lc');
        $('.list_control').addClass('hidden_lc');
        mute_audio(true,true);
        try {
            audio_player.pause();
        } catch (e) {}
        controls_status['song']=false;
        $('.song_control').removeClass('active_control');
        $('.song_alt_control').removeClass('active_control');
        $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
        $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try { pano_viewer.stopAutoRotate(); } catch (e) {}
        } else {
            try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
        }
        $('.nav_rotate').removeClass('active_rotate');
        $('.autorotate_control').removeClass('active_control');
        $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['auto_rotate']=false;
    }

    function exit_receiver_viewer() {
        unlock_receiver_viewer();
        $('.song_control').removeClass('hidden_lc');
        $('.song_alt_control').removeClass('hidden_lc');
        $('.visitors_rt_stats').removeClass('hidden_lc');
        $('.div_visitor_wrapper').removeClass('hidden_lc');
        $('.meeting_control').removeClass('hidden_lc');
        $('.live_control').removeClass('hidden_lc');
        $('.list_sliders').css('pointer-events','initial');
        $('#controls_bottom_left').removeClass('hidden_lc');
        $('#controls_bottom_center').removeClass('hidden_lc');
        $('#controls_bottom_right').removeClass('hidden_lc');
        $('.list_control').removeClass('hidden_lc');
    }

    function init_sender_viewer() {
        $('.menu_controls').css('pointer-events','none');
        $('.visitors_rt_stats').addClass('hidden_lc');
        //$('#controls_bottom_left').css({'opacity':0,'pointer-events':'none'});
        //$('#controls_bottom_center').css({'opacity':0,'pointer-events':'none'});
        //$('#controls_bottom_right').css({'opacity':0,'pointer-events':'none'});
        $('.list_control').addClass('hidden_lc');
        $('.list_sliders').css('z-index',0);
        $('.list_sliders').css('opacity',0);
        $('.list_control').removeClass('active_control');
        reposition_bottom_controls(false,false,0);
        $('.list_control i, .list_control_alt').removeClass('fa-chevron-down').addClass('fa-chevron-up');
        controls_status['list']=false;
        $('.share_popup').removeClass('show');
        $('.share_control').removeClass('active_control');
        $('.share_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['share']=false;
        $('.song_control').addClass('hidden_lc');
        $('.song_alt_control').addClass('hidden_lc');
        mute_audio(true,true);
        try {
            audio_player.pause();
        } catch (e) {}
        $('.song_control').removeClass('active_control');
        $('.song_alt_control').removeClass('active_control');
        $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
        $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['song']=false;
        if(voice_commands_enable>0) {
            try {
                SpeechKITT.hide();
                if (annyang) { annyang.pause(); }
            } catch (e) {}
        }
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try { pano_viewer.stopAutoRotate(); } catch (e) {}
        } else {
            try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
        }
        $('.nav_rotate').removeClass('active_rotate');
        $('.autorotate_control').removeClass('active_control');
        $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
        controls_status['auto_rotate']=false;
    }

    function exit_sender_viewer() {
        $('.menu_controls').css('pointer-events','initial');
        $('#controls_bottom_left').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_center').css({'opacity':1,'pointer-events':'initial'});
        $('#controls_bottom_right').css({'opacity':1,'pointer-events':'initial'});
        $('.list_control').removeClass('hidden_lc');
        $('.song_control').removeClass('hidden_lc');
        $('.song_alt_control').removeClass('hidden_lc');
        $('.visitors_rt_stats').removeClass('hidden_lc');
        if(voice_commands_enable>0) {
            try {
                SpeechKITT.show();
            } catch (e) {}
            if(voice_commands_enable==2) {
                try {
                    if (annyang) { annyang.resume(); }
                } catch (e) {}
            }
        }
    }

    function openLiveChat() {
        $('.floating-chat').removeClass('blink');
        var messages = live_chat.find('.messages');
        var textInput = live_chat.find('.text-box');
        live_chat.find('>i').hide();
        live_chat.addClass('expand');
        live_chat.find('.chat').addClass('enter');
        textInput.keydown(onChatEnter).prop("disabled", false).focus();
        live_chat.off('click', openLiveChat);
        live_chat.find('.header button').click(closeLiveChat);
        live_chat.find('#sendMessage').click(sendNewMessage);
        messages.scrollTop(messages.prop("scrollHeight"));
    }

    function closeLiveChat() {
        live_chat.find('.chat').removeClass('enter').hide();
        live_chat.find('>i').show();
        live_chat.removeClass('expand');
        live_chat.find('.header button').off('click', closeLiveChat);
        live_chat.find('#sendMessage').off('click', sendNewMessage);
        live_chat.find('.text-box').off('keydown', onChatEnter).prop("disabled", true).blur();
        setTimeout(function() {
            live_chat.find('.chat').removeClass('enter').show()
            live_chat.click(openLiveChat);
        }, 500);
    }

    function sendNewMessage() {
        var userInput = $('.text-box');
        var newMessage = userInput.html().replace(/\<div\>|\<br.*?\>/ig, '\n').replace(/\<\/div\>/g, '').trim().replace(/\n/g, '<br>');
        if (!newMessage) return;
        var newMessage_s = urlify(newMessage);
        var messagesContainer = $('.messages');
        messagesContainer.append([
            '<li class="self">',
            newMessage_s,
            '</li>'
        ].join(''));
        userInput.html('');
        userInput.focus();
        messagesContainer.finish().animate({
            scrollTop: messagesContainer.prop("scrollHeight")
        }, 250);
        try {
            peer_conn.send({type:'chat',message:newMessage});
        } catch (e) {}
    }

    function receiveMessage(message) {
        var message = message.replace(/\<div\>|\<br.*?\>/ig, '\n').replace(/\<\/div\>/g, '').trim().replace(/\n/g, '<br>');
        var message_s = urlify(message);
        var messagesContainer = $('.messages');
        messagesContainer.append([
            '<li class="other">',
            message_s,
            '</li>'
        ].join(''));
        messagesContainer.finish().animate({
            scrollTop: messagesContainer.prop("scrollHeight")
        }, 250);
    }

    function onChatEnter(event) {
        if (event.keyCode == 13) {
            sendNewMessage();
            event.preventDefault();
        }
    }

    function urlify(text) {
        var urlRegex = /(https?:\/\/[^\s]+)/g;
        return text.replace(urlRegex, function(url) {
            return '<a style="color: white;text-decoration: underline;" target="_blank" href="' + url + '">' + url + '</a>';
        })
    }

    function interpolateZoom(width) {
        if(width<=450) {
            var breakpoints = [
                { width: 300, zoom: 10 },
                { width: 450, zoom: 15 }
            ];
        } else {
            var breakpoints = [
                { width: 450, zoom: 0 },
                { width: 1600, zoom: 60 }
            ];
        }
        for (var i = 0; i < breakpoints.length - 1; i++) {
            if (width >= breakpoints[i].width && width < breakpoints[i + 1].width) {
                var x0 = breakpoints[i].width;
                var y0 = breakpoints[i].zoom;
                var x1 = breakpoints[i + 1].width;
                var y1 = breakpoints[i + 1].zoom;
                return y0 + (y1 - y0) * (width - x0) / (x1 - x0);
            }
        }
        return breakpoints[breakpoints.length - 1].zoom;
    }

    function init_flyin_lp(pano,yaw,pitch,hfov) {
        try {
            $('#flyin').show();
            $('#flyin').css({'width':'100%','height':'100vh','top':0});
            var c_w = $(window).width();
            var end_zoom = interpolateZoom(c_w);
            var hfov_end = hfov;
            animatedValues_flyin_lp = {
                pitch: { start: degreesToRadians(-90), end: degreesToRadians(pitch) },
                yaw: { start: degreesToRadians(yaw), end: degreesToRadians(yaw) },
                zoom: { start: 0, end: end_zoom },
                maxFov: { start: 140, end: hfov_end },
                fisheye: { start: 2, end: 0 },
            };
            viewer_flyin_lp = new PhotoSphereViewer.Viewer({
                container: document.querySelector('#flyin'),
                navbar: false,
                defaultPitch: animatedValues_flyin_lp.pitch.start,
                defaultYaw: animatedValues_flyin_lp.yaw.start,
                defaultZoomLvl: animatedValues_flyin_lp.zoom.start,
                maxFov: animatedValues_flyin_lp.maxFov.start,
                fisheye: animatedValues_flyin_lp.fisheye.start,
                mousemove: false,
                mousewheel: false,
                panorama: first_image.src,
            });
            viewer_flyin_lp.addEventListener('ready', () => {
                setTimeout(() => {
                    animate_flyin_lp(animatedValues_flyin_lp.pitch.end, animatedValues_flyin_lp.yaw.end);
                }, 500);
            }, { once: true });
        } catch (e) {
            window.flyin = 0;
            complete_init();
            $('#flyin').remove();
        }
    }

    function animate_flyin_lp(pitch, yaw) {
        setTimeout(function() {
            $('#flyin').animate({
                opacity: 1.0
            }, { duration: 500, queue: true });
            $('.loading').fadeOut(500);
            new PhotoSphereViewer.utils.Animation({
                properties: {
                    ...animatedValues_flyin_lp,
                    pitch: { start: animatedValues_flyin_lp.pitch.start, end: pitch },
                    yaw: { start: animatedValues_flyin_lp.yaw.start, end: yaw },
                },
                duration: flyin_duration,
                easing: 'inOutQuad',
                onTick: (properties) => {
                    viewer_flyin_lp.setOptions({
                        fisheye: properties.fisheye,
                        maxFov: properties.maxFov,
                    });
                    viewer_flyin_lp.rotate({ yaw: properties.yaw, pitch: properties.pitch });
                    viewer_flyin_lp.zoom(properties.zoom);
                },
            }).then(() => {
                window.flyin = 0;
                complete_init();
                setTimeout(function () {
                    $('#flyin').fadeOut(500,function() {
                        $('#flyin').remove();
                    });
                },500);
            });
        },250);
    }

    function init_flyin(pano,yaw,pitch) {
        try {
            $('#flyin').show();
            flyin_renderer = new THREE.WebGLRenderer({ antialiasing: true, alpha: true });
            THREE.Cache.enabled = true;
            flyin_renderer.setSize(document.querySelector("#vt_container").offsetWidth, document.querySelector("#vt_container").offsetHeight);
            flyin_renderer.setClearColor( 0x000000, 0 );
            document.getElementById('flyin').appendChild(flyin_renderer.domElement);
            flyin_scene = new THREE.Scene();
            flyin_camera = new THREE.PerspectiveCamera(50, document.querySelector("#vt_container").offsetWidth / document.querySelector("#vt_container").offsetHeight, 1, 1000);
            flyin_camera.position.set(0, 550, -15);
            flyin_camera.lookAt(new THREE.Vector3(0,0,-15));
            flyin_scene.add( flyin_camera );
            flyin_scene.add( new THREE.AmbientLight(0x444444));
            var light = new THREE.PointLight(0xffffff, 0.8);
            flyin_camera.add( light );
            flyin_geometry = new THREE.SphereGeometry(50, 256, 256);
            flyin_loader = new THREE.TextureLoader();
            flyin_renderer.setAnimationLoop(animate_flyin);
            flyin_texture = new THREE.Texture(first_image);
            flyin_texture.needsUpdate = true;
            flyin_texture.wrapS = THREE.RepeatWrapping;
            flyin_texture.repeat.x = - 1;
            flyin_material = new THREE.MeshBasicMaterial({
                map: flyin_texture,
                color: 0xffffff,
                side: THREE.BackSide
            });
            flyin_mesh = new THREE.Mesh( flyin_geometry, flyin_material );
            flyin_mesh.position.set(0, 0, -15);
            rotateObject(flyin_mesh,-pitch,(yaw+90),0);
            flyin_scene.add( flyin_mesh );
            setTimeout(function() {
                $('.loading').fadeOut(500);
                $('#flyin').animate({
                    opacity: 1.0
                }, { duration: 250, queue: false });
                setTimeout(function () {
                    var targetPosition = new THREE.Vector3(0, 0, 0);
                    var duration = flyin_duration;
                    tweenCamera(targetPosition, duration);
                },(flyin_duration*0.09));
            },(flyin_duration*0.09));
            setTimeout(function () {
                $('#flyin').animate({
                    top: 0
                }, { duration: (flyin_duration*0.6), queue: false });
            },(flyin_duration*0.18));
        } catch (e) {
            flyin_renderer.setAnimationLoop(null);
            window.flyin = 0;
            complete_init();
            flyin_geometry.dispose();
            flyin_geometry=null;
            flyin_texture.dispose();
            flyin_texture=null;
            flyin_material.dispose();
            flyin_material=null;
            flyin_renderer.setSize(0,0);
            flyin_renderer.renderLists.dispose();
            flyin_renderer.dispose();
            flyin_renderer=null;
            $('#flyin').remove();
        }
    }

    function animate_flyin() {
        TWEEN.update();
        flyin_renderer.render (flyin_scene, flyin_camera);
    }

    function rotateObject(object, degreeX=0, degreeY=0, degreeZ=0) {
        object.rotateX(THREE.Math.degToRad(degreeX));
        object.rotateY(THREE.Math.degToRad(degreeY));
        object.rotateZ(THREE.Math.degToRad(degreeZ));
    }

    function tweenCamera( targetPosition, duration ) {
        var position = new THREE.Vector3().copy(flyin_camera.position);
        var flyin_tween = new TWEEN.Tween(position)
            .to(targetPosition, duration)
            .easing(TWEEN.Easing.Quadratic.InOut)
            .onUpdate( function () {
                flyin_camera.position.copy(position);
                flyin_camera.lookAt(new THREE.Vector3(0,0,-15));
            } )
            .onComplete( function () {
                flyin_camera.position.copy(targetPosition);
                flyin_camera.lookAt(new THREE.Vector3(0,0,-15));
                flyin_renderer.setAnimationLoop(null);
                window.flyin = 0;
                complete_init();
                setTimeout(function () {
                    $('#flyin').fadeOut(500,function() {
                        flyin_geometry.dispose();
                        flyin_geometry=null;
                        flyin_texture.dispose();
                        flyin_texture=null;
                        flyin_material.dispose();
                        flyin_material=null;
                        flyin_renderer.setSize(0,0);
                        flyin_renderer.renderLists.dispose();
                        flyin_renderer.dispose();
                        flyin_renderer=null;
                        $('#flyin').remove();
                    });
                },500);
            } )
            .start();
    }

    window.check_pois_schedule = function (id_room) {
        if(window.export_mode==0) {
            $.ajax({
                url: "ajax/check_pois_schedule.php",
                type: "POST",
                data: {
                    id_room: id_room
                },
                async: false,
                success: function (json) {
                    var pois = JSON.parse(json);
                    jQuery.each(pois, function(id, visible) {
                        if(parseInt(visible)==0) {
                            $('.hotspot_'+id).addClass("hidden_s");
                        } else {
                            $('.hotspot_'+id).removeClass("hidden_s");
                        }
                        if(id in video_embeds) {
                            video_embeds[id].pause();
                        }
                    });
                }
            });
        }
    }

    window.is_iOS = function() {
        return ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
    }

    window.open_jitsi_meet = function () {
        if($('#vt_container').hasClass('open_map_tour')) {
            $('#vt_container').addClass('open_jitsi_meet_map_tour');
            $('#vt_container').removeClass('open_map_tour');
        } else {
            $('#vt_container').addClass('open_jitsi_meet');
        }
        $('#jitsi_div').addClass('visible_jitsi_meet');
        var options = {
            roomName: window.name_app_vt,
            width: '100%',
            height: '100%',
            parentNode: document.querySelector('#jitsi_div'),
            configOverwrite: {
                disableDeepLinking: true,
                enableWelcomePage: false,
                disableInviteFunctions: true,
                apiLogLevels: ['warn', 'error'],
                hideConferenceSubject: true,
                prejoinPageEnabled: true
            },
            interfaceConfigOverwrite: {
                MOBILE_APP_PROMO: false,
                DEFAULT_LOGO_URL: '',
                DEFAULT_WELCOME_PAGE_LOGO_URL: '',
                JITSI_WATERMARK_LINK: '',
                BRAND_WATERMARK_LINK: '',
                SHOW_CHROME_EXTENSION_BANNER: false,
                SHOW_BRAND_WATERMARK: false,
                SHOW_JITSI_WATERMARK: false,
                SHOW_POWERED_BY: false,
                SHOW_PROMOTIONAL_CLOSE_PAGE: false,
                TOOLBAR_BUTTONS: [
                    'microphone', 'camera', 'desktop' , 'closedcaptions', 'fullscreen',
                    'fodeviceselection', 'hangup', 'chat', 'etherpad', 'settings', 'raisehand',
                    'videoquality', 'filmstrip', 'tileview', 'videobackgroundblur', 'mute-everyone',
                ],
            },
        }
        api_jitsi = new JitsiMeetExternalAPI(jitsi_domain, options);
        api_jitsi.addListener('videoConferenceLeft', function() {
            close_jitsi_meet();
        });
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.open_map_tour = function () {
        if($('#vt_container').hasClass('open_jitsi_meet')) {
            $('#vt_container').addClass('open_jitsi_meet_map_tour');
            $('#vt_container').removeClass('open_jitsi_meet');
        } else {
            $('#vt_container').addClass('open_map_tour');
        }
        $('#map_tour_div').addClass('visible_map_tour');
        $('#map_tour_div').show();
        $('#map_tour_div').css('opacity',1);
        if(map_tour_l==null) {
            initialize_map_tour();
        }
        setTimeout(function () {
            $(document).trigger('resize');
        },100);
        if(live_session_connected) {
            try {
                peer_conn.send({type:'open_map_tour'});
            } catch (e) {}
        }
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.close_map_tour = function () {
        if($('#vt_container').hasClass('open_jitsi_meet_map_tour')) {
            $('#vt_container').removeClass('open_jitsi_meet_map_tour');
            $('#vt_container').addClass('open_jitsi_meet');
        } else {
            $('#vt_container').removeClass('open_map_tour');
        }
        $('#map_tour_div').removeClass('visible_map_tour');
        setTimeout(function() {
            $('#map_tour_div').css('opacity',0);
            $('#map_tour_div').hide();
        },300);
        setTimeout(function () {
            $(document).trigger('resize');
        },100);
        if(live_session_connected) {
            try {
                peer_conn.send({type:'close_map_tour'});
            } catch (e) {}
        }
        interval_adjust_embed_helpers_all = setInterval(function () {
            adjust_poi_embed_helpers_all();
            adjust_marker_embed_helpers_all();
            adjust_measurements();
            count_adjust_embed_helpers_all++;
            if(count_adjust_embed_helpers_all>=2000) {
                clearInterval(interval_adjust_embed_helpers_all);
                count_adjust_embed_helpers_all=0;
            }
        },1);
    }

    window.close_map_fullscreen = function() {
        $('#map_tour_div').removeClass('fullscreen');
        setTimeout(function(){ map_tour_l.invalidateSize()}, 10);
    }

    function initialize_map_tour() {
        var street_subdomain_t = street_subdomain.split(",");
        var street_maxzoom_t = parseInt(street_maxzoom);
        if(street_subdomain!='') {
            var street_basemap = L.tileLayer(street_basemap_url,{
                maxZoom: street_maxzoom_t,
                subdomains: street_subdomain_t
            });
        } else {
            var street_basemap = L.tileLayer(street_basemap_url,{
                maxZoom: street_maxzoom_t
            });
        }
        var satellite_subdomain_t = satellite_subdomain.split(",");
        var satellite_maxzoom_t = parseInt(satellite_maxzoom);
        if(satellite_subdomain!='') {
            var satellite_basemap = L.tileLayer(satellite_basemap_url,{
                maxZoom: satellite_maxzoom_t,
                subdomains: satellite_subdomain_t
            });
        } else {
            var satellite_basemap = L.tileLayer(satellite_basemap_url,{
                maxZoom: satellite_maxzoom_t
            });
        }
        map_tour_l = L.map('map_tour_div', {
            layers: [street_basemap]
        });
        var baseMaps = {
            "Street": street_basemap,
            "Satellite": satellite_basemap
        };
        L.control.layers(baseMaps, {}, {position: 'bottomleft'}).addTo(map_tour_l);
        switch(map_tour.default_view) {
            case 'street':
                baseMaps["Street"].addTo(map_tour_l);
                break;
            case 'satellite':
                baseMaps["Satellite"].addTo(map_tour_l);
                break;
        }
        L.control.locate({
            setView: 'once',
            flyTo: true,
            keepCurrentZoomLevel: true,
            icon: 'fas fa-map-marker-alt',
            strings: {
                title: ""
            }
        }).addTo(map_tour_l);
        L.Control.Button = L.Control.extend({
            options: {
                position: 'topright'
            },
            onAdd: function (map) {
                var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
                var button = L.DomUtil.create('a', 'leaflet-control-button', container);
                button.innerHTML = '<i class="fa-solid fa-expand"></i>';
                button.style.cursor = 'pointer';
                L.DomEvent.disableClickPropagation(button);
                L.DomEvent.on(button, 'click', function(){
                    if($('#map_tour_div').hasClass('fullscreen')) {
                        $('#map_tour_div').removeClass('fullscreen');
                    } else {
                        $('#map_tour_div').addClass('fullscreen');
                    }
                    setTimeout(function(){ map.invalidateSize()}, 10);
                });
                container.title = "Fullscreen";
                return container;
            },
            onRemove: function(map) {},
        });
        var control = new L.Control.Button();
        control.addTo(map_tour_l);
        var point_size = parseInt(map_tour.point_size);
        if(window.is_mobile) {
            point_size = point_size / 1.5;
        }
        var bounds = new L.LatLngBounds();
        var point_na = true,first_lat=0,first_lon=0;
        jQuery.each(map_tour_points, function(index, map_tour_point) {
            var id = parseInt(map_tour_point.id);
            var name = map_tour_point.name;
            var lat = parseFloat(map_tour_point.lat);
            var lon = parseFloat(map_tour_point.lon);
            var class_active = '';
            if(first_lat==0) first_lat=lat;
            if(first_lon==0) first_lon=lon;
            if(current_id_panorama==id) {
                map_tour_l.setView([lat, lon], parseInt(map_tour.zoom_level));
                class_active = 'active';
                point_na = false;
            }
            var learning_disabled = "";
            if(window.learning_mode>0) {
                if(window.learning_unlock_marker) {
                    if(learning_check_marker_locked(id)) {
                        learning_disabled = 'disabled_l';
                    }
                }
            }
            var view_size = parseInt(map_tour.point_view_size)*2;
            if(parseInt(map_tour.map_thumb)==1) {
                var html_map_point = "<div id='pointer_m_"+id+"' class='map_pointer_container_m "+learning_disabled+" "+class_active+"'><div style='width:"+(view_size*2)+"px;height:"+(view_size*2)+"px;' data-view-size='"+view_size+"' data-view-color='"+map_tour.point_view_color+"' class='map_pointer_view'></div><div style='width:"+point_size+"px;height:"+point_size+"px;border-color:"+map_tour.point_color+";background-image:url("+((window.s3_enabled) ? window.s3_url : '')+map_tour_point.icon+");' onclick='close_map_fullscreen();goto(\"\",["+id+",null,null,null,null,null,null,null]);' title=\""+name+"\" class='map_pointer_circle tooltip_map_tour'></div></div>";
            } else {
                var html_map_point = "<div id='pointer_m_"+id+"' class='map_pointer_container_m "+learning_disabled+" "+class_active+"'><div style='width:"+(view_size*2)+"px;height:"+(view_size*2)+"px;' data-view-size='"+view_size+"' data-view-color='"+map_tour.point_view_color+"' class='map_pointer_view'></div><div style='width:"+point_size+"px;height:"+point_size+"px;background-color:"+map_tour.point_color+";' onclick='close_map_fullscreen();goto(\"\",["+id+",null,null,null,null,null,null,null]);' title=\""+name+"\" class='map_pointer_circle tooltip_map_tour'></div></div>";
            }
            var icon = new L.DivIcon({
                html: html_map_point,
                iconSize: [point_size, point_size],
                iconAnchor: [(point_size/2), (point_size/2)]
            });
            L.marker([lat, lon], {icon: icon}).addTo(map_tour_l);
            bounds.extend([lat, lon]);
        });
        $('.map_container_m .map_pointer_circle').css({'top':(point_size/2)+'px','left':(point_size/2)+'px'});
        $('.map_container_m .map_pointer_view').css({'top':(point_size/2)+'px','left':(point_size/2)+'px'});
        if(point_na) {
            var first_zoom=parseInt(map_tour.zoom_level);
            if(parseInt(map_tour.zoom_level)==0) first_zoom=4;
            map_tour_l.setView([first_lat,first_lon],first_zoom);
        }
        if(parseInt(map_tour.zoom_level)==0) {
            map_tour_l.fitBounds(bounds, {padding: [50,50]});
        }
        $('.map_pointer_container_m').parent().removeClass('map_tour_icon_top');
        $('#pointer_m_'+current_id_panorama).parent().addClass('map_tour_icon_top');
        $('.map_pointer_container_m').removeClass('active');
        $('#pointer_m_'+current_id_panorama).addClass('active');
        $('.tooltip_map_tour').tooltipster({
            theme: 'tooltipster-borderless',
            animation: 'grow',
            delay: 0,
            arrow: false
        });
    }

    function select_map_tour_point() {
        $('.map_pointer_container_m').removeClass('active');
        $('.map_pointer_container_m').parent().removeClass('map_tour_icon_top');
        jQuery.each(map_tour_points, function(index, map_tour_point) {
            var id = parseInt(map_tour_point.id);
            var lat = parseFloat(map_tour_point.lat);
            var lon = parseFloat(map_tour_point.lon);
            if(current_id_panorama==id) {
                if(parseInt(map_tour.zoom_to_point) && parseInt(map_tour.zoom_level)>0) {
                    map_tour_l.setView([lat, lon], parseInt(map_tour.zoom_level));
                } else {
                    map_tour_l.setView([lat, lon]);
                }
                $('#pointer_m_'+id).addClass('active');
                $('#pointer_m_'+id).parent().addClass('map_tour_icon_top');
            }
        });
    }

    window.store_visitor_init = function() {
        store_visitor(true);
        if(enable_views_stat==1) {
            get_views_stats();
            setInterval(function () {
                get_views_stats();
            },10000);
        }
        show_visitors_stat();
    }

    function get_views_stats() {
        Pace.ignore(function(){
            $.ajax({
                url: "ajax/get_views_stats.php",
                type: "POST",
                data: {
                    id_virtualtour: window.id_virtualtour,
                },
                async: true,
                success: function (json) {
                    var rsp = JSON.parse(json);
                    $('#views_total_count').html(rsp.views);
                }
            });
        });
    }

    function store_visitor(first_exec) {
        if(first_exec) {
            var interval = 0;
        } else {
            var interval = interval_visitor_rt;
        }
        setTimeout(function() {
            exec_store_visitor(false);
        },interval);
    }

    function exec_store_visitor(force) {
        var id = get_id_viewer(current_id_panorama);
        var id_room = panoramas[id].id;
        if(enable_visitor_rt==1) {
            try {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw = pano_viewer.getYaw();
                    var pitch = pano_viewer.getPitch();
                } else {
                    var yaw = video_viewer.pnlmViewer.getYaw();
                    var pitch = video_viewer.pnlmViewer.getPitch();
                }
            } catch (e) {
                var yaw = 0;
                var pitch = 0;
            }
        } else {
            var yaw = 0;
            var pitch = 0;
        }
        if(!in_idle) {
            Pace.ignore(function(){
                $.ajax({
                    url: "ajax/store_visitor.php",
                    type: "POST",
                    data: {
                        id_virtualtour: window.id_virtualtour,
                        ip_visitor: window.ip_visitor,
                        id_visitor: window.id_visitor,
                        id_room: id_room,
                        yaw: yaw,
                        pitch: pitch,
                        enable_visitor_rt: enable_visitor_rt,
                        interval_visitor_rt: interval_visitor_rt
                    },
                    async: true,
                    success: function (json) {
                        if(enable_visitor_rt==1 && !vr_enabled && !live_session_connected) {
                            var rsp = JSON.parse(json);
                            $('#visitors_here').html(rsp.here);
                            $('#visitors_total').html(rsp.total);
                            $('.stat_visitors_rt_rooms span').html(0);
                            $('.stat_visitors_rt_rooms').hide();
                            jQuery.each(rsp.visitors_count, function(id_room, count) {
                                $('#count_visitors_rt_room_'+id_room).html(count);
                                if(count>0) {
                                    $('#count_visitors_rt_room_'+id_room).parent().show();
                                }
                            });
                            $('#list_slider_main .pointer_list_cat').each(function() {
                                var total_count = 0;
                                $(this).find('.cat_image_grid img').each(function() {
                                    var id_room = parseInt($(this).attr('data-id-room'));
                                    var count = parseInt($('#count_visitors_rt_room_'+id_room).html());
                                    total_count = total_count + count;
                                });
                                if(total_count>0) {
                                    $(this).find('.stat_visitors_rt_rooms span').html(total_count);
                                    $(this).find('.stat_visitors_rt_rooms').show();
                                }
                            });
                            $('.list_slider_cat').each(function() {
                                $(this).find('.pointer_list_cat').each(function() {
                                    var total_count = 0;
                                    $(this).find('.cat_image_grid img').each(function() {
                                        var id_room = parseInt($(this).attr('data-id-room'));
                                        var count = parseInt($('#count_visitors_rt_room_'+id_room).html());
                                        total_count = total_count + count;
                                    });
                                    if(total_count>0) {
                                        $(this).find('.stat_visitors_rt_rooms span').html(total_count);
                                        $(this).find('.stat_visitors_rt_rooms').show();
                                    }
                                });
                            });
                            handle_visitor_rt(rsp.visitors);
                            if(pano_viewer_alt!=null && pano_viewer_alt!==undefined) {
                                handle_visitor_rt_alt(rsp.visitors);
                            }
                        }
                        if(!force) store_visitor(false);
                    },
                    error: function () {
                        if(!force) store_visitor(false);
                    }
                });
            });
        } else {
            if(!force) store_visitor(false);
        }
    }

    function handle_visitor_rt(visitors) {
        var array_exist_visitors = [];
        $('.hotspot-visitor').each(function () {
            var id = $(this).attr('data-id');
            array_exist_visitors.push(id);
        });
        if(!window.vr_enabled) {
            var array_current_visitors = [];
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                var pano_visitors = pano_viewer;
            } else {
                var pano_visitors = video_viewer.pnlmViewer;
            }
            jQuery.each(visitors, function(index, visitor) {
                var id = visitor.id;
                array_current_visitors.push(id);
                var yaw = parseFloat(visitor.yaw);
                var pitch = parseFloat(visitor.pitch);
                if(array_exist_visitors.includes(id)) {
                    pano_visitors.modifyHotSpot("visitor_"+id,yaw,pitch);
                } else {
                    pano_visitors.addHotSpot({
                        "id": "visitor_"+id,
                        "type": 'visitor',
                        "object": "visitor",
                        "transform3d": false,
                        "pitch": pitch,
                        "yaw": yaw,
                        "size_scale": 1,
                        "rotateX": 0,
                        "rotateZ": 0,
                        "draggable": false,
                        "cssClass": "hotspot-visitor",
                        "createTooltipFunc": hotspot_visitor,
                        "createTooltipArgs": visitor,
                    });
                }
            });
            jQuery.each(array_exist_visitors, function(index, exist_visitor) {
                if(!array_current_visitors.includes(exist_visitor)) {
                    try { pano_visitors.removeHotSpot("visitor_"+exist_visitor); } catch (e) {}
                }
            });
            pano_visitors.resize();
        } else {
            jQuery.each(array_exist_visitors, function(index, exist_visitor) {
                try { pano_visitors.removeHotSpot("visitor_"+exist_visitor); } catch (e) {}
            });
            $('.hotspot-visitor').css({'opacity':0});
        }
    }

    function handle_visitor_rt_alt(visitors) {
        var array_exist_visitors = [];
        $('.hotspot-visitor-alt').each(function () {
            var id = $(this).attr('data-id');
            array_exist_visitors.push(id);
        });
        if(!window.vr_enabled) {
            var array_current_visitors = [];
            jQuery.each(visitors, function(index, visitor) {
                var id = visitor.id;
                array_current_visitors.push(id);
                var yaw = parseFloat(visitor.yaw);
                var pitch = parseFloat(visitor.pitch);
                if(array_exist_visitors.includes(id)) {
                    pano_viewer_alt.modifyHotSpot("visitor_alt_"+id,yaw,pitch);
                } else {
                    pano_viewer_alt.addHotSpot({
                        "id": "visitor_alt_"+id,
                        "type": 'visitor',
                        "object": "visitor",
                        "transform3d": false,
                        "pitch": pitch,
                        "yaw": yaw,
                        "size_scale": 1,
                        "rotateX": 0,
                        "rotateZ": 0,
                        "draggable": false,
                        "cssClass": "hotspot-visitor-alt",
                        "createTooltipFunc": hotspot_visitor,
                        "createTooltipArgs": visitor,
                    });
                }
            });
            jQuery.each(array_exist_visitors, function(index, exist_visitor) {
                if(!array_current_visitors.includes(exist_visitor)) {
                    try { pano_viewer_alt.removeHotSpot("visitor_alt_"+exist_visitor); } catch (e) {}
                }
            });
            pano_viewer_alt.resize();
        } else {
            jQuery.each(array_exist_visitors, function(index, exist_visitor) {
                try { pano_viewer_alt.removeHotSpot("visitor_alt_"+exist_visitor); } catch (e) {}
            });
            $('.hotspot-visitor-alt').css({'opacity':0});
        }
    }

    function init_poi_embed() {
        window.sync_poi_embed_enabled = true;
        poi_embed_ids = [];
        $('.poi_embed').each(function () {
            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 && transform3d==1) {
                $(this).attr('data-initialized',1);
                $(this).css('visibility','visible');
                poi_embed_make_transformable('.poi_embed_'+id, id, function(element, H) {});
            }
        });
        adjust_poi_embed_helpers_all();
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.setUpdate(true);
        } else {
            video_viewer.pnlmViewer.setUpdate(true);
        }
        setTimeout(function () {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.setUpdate(false);
            } else {
                video_viewer.pnlmViewer.setUpdate(false);
            }
        },1000);
    }

    function init_marker_embed() {
        window.sync_marker_embed_enabled = true;
        marker_embed_ids = [];
        $('.marker_embed').each(function () {
            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 && transform3d==1) {
                $(this).attr('data-initialized',1);
                $(this).css('visibility','visible');
                marker_embed_make_transformable('.marker_embed_'+id, id, function(element, H) {});
            }
        });
        adjust_marker_embed_helpers_all();
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.setUpdate(true);
        } else {
            video_viewer.pnlmViewer.setUpdate(true);
        }
        setTimeout(function () {
            if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                pano_viewer.setUpdate(false);
            } else {
                video_viewer.pnlmViewer.setUpdate(false);
            }
        },1000);
    }

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

    function isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }

    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 tooltip_visibility = $('.poi_embed_'+id).attr('data-tooltip_visibility');
            var type = $('.poi_embed_'+id).attr('data-type');
            if(transform3d==0) {
                $('.poi_embed_'+id).css({'top':0,'left':0});
                if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                    $('.tooltip_poi_embed_'+id).css('opacity',1);
                }
                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 'gallery':
                        $('.poi_embed_'+id+' .poi_embed_gallery').css('opacity',1);
                        break;
                    case 'link':
                        $('.poi_embed_'+id+' .poi_embed_link').css('opacity',1);
                        $('.poi_embed_'+id+' iframe').css('opacity',1);
                        break;
                    case 'text':
                    case 'html':
                        $('.poi_embed_'+id+' div:not(.tooltip_text_embed)').css('opacity',1);
                        break;
                    case 'selection':
                        $('.poi_embed_'+id+' .poi_embed_selection').css('opacity',1);
                        break;
                    case 'object3d':
                        $('.poi_embed_'+id+' .poi_embed_object3d').css('opacity',1);
                        break;
                }
            } else if(initialized==1) {
                var pos_1 = ($('#poi_embded_helper_'+id.replace('alt','')+'_1').position());
                pos_1.top=pos_1.top+8;
                pos_1.left=pos_1.left+8;
                $('#draggable_'+id+'_1').css({'top':pos_1.top+'px','left':pos_1.left+'px'});
                var pos_2 = ($('#poi_embded_helper_'+id.replace('alt','')+'_2').position());
                pos_2.top=pos_2.top+8;
                pos_2.left=pos_2.left+8;
                $('#draggable_'+id+'_2').css({'top':pos_2.top+'px','left':pos_2.left+'px'});
                var pos_3 = ($('#poi_embded_helper_'+id.replace('alt','')+'_3').position());
                pos_3.top=pos_3.top+8;
                pos_3.left=pos_3.left+8;
                $('#draggable_'+id+'_3').css({'top':pos_3.top+'px','left':pos_3.left+'px'});
                var pos_4 = ($('#poi_embded_helper_'+id.replace('alt','')+'_4').position());
                pos_4.top=pos_4.top+8;
                pos_4.left=pos_4.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) {
                    if($('.poi_embed_'+id).css('visibility')=='visible' && count_offscreen<=2) {
                        poi_embed_apply_transform(id, $('.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');
                        if(current_transform!="none" && $('#poi_embded_helper_'+id.replace('alt','')+'_1').position().top!=0 && $('#poi_embded_helper_'+id.replace('alt','')+'_2').position().top!=0 && $('#poi_embded_helper_'+id.replace('alt','')+'_3').position().top!=0 && $('#poi_embded_helper_'+id.replace('alt','')+'_4').position().top!=0) {
                            if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                                const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
                                if(pos_1.left>width) {
                                    $('.tooltip_poi_embed_'+id).css('opacity',0);
                                } else {
                                    $('.tooltip_poi_embed_'+id).css('opacity',1);
                                }
                            }
                            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 'gallery':
                                    $('.poi_embed_'+id+' .poi_embed_gallery').css('opacity',1);
                                    break;
                                case 'link':
                                    $('.poi_embed_'+id+' .poi_embed_link').css('opacity',1);
                                    $('.poi_embed_'+id+' iframe').css('opacity',1);
                                    break;
                                case 'text':
                                case 'html':
                                    $('.poi_embed_'+id+' div:not(.tooltip_text_embed)').css('opacity',1);
                                    break;
                                case 'selection':
                                    $('.poi_embed_'+id+' .poi_embed_selection').css('opacity',1);
                                    break;
                                case 'object3d':
                                    $('.poi_embed_'+id+' .poi_embed_object3d').css('opacity',1);
                                    break;
                            }
                        } else {
                            if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                                $('.tooltip_poi_embed_'+id).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+' .poi_embed_link').css('opacity',0);
                                    $('.poi_embed_'+id+' iframe').css('opacity',0);
                                    break;
                                case 'text':
                                case 'html':
                                    $('.poi_embed_'+id+' div:not(.tooltip_text_embed)').css('opacity',0);
                                    break;
                                case 'selection':
                                    $('.poi_embed_'+id+' .poi_embed_selection').css('opacity',0);
                                    break;
                                case 'object3d':
                                    $('.poi_embed_'+id+' .poi_embed_object3d').css('opacity',0);
                                    break;
                            }
                        }
                    } else {
                        if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                            $('.tooltip_poi_embed_'+id).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+' .poi_embed_link').css('opacity',0);
                                $('.poi_embed_'+id+' iframe').css('opacity',0);
                                break;
                            case 'text':
                            case 'html':
                                $('.poi_embed_'+id+' div:not(.tooltip_text_embed)').css('opacity',0);
                                break;
                            case 'selection':
                                $('.poi_embed_'+id+' .poi_embed_selection').css('opacity',0);
                                break;
                            case 'object3d':
                                $('.poi_embed_'+id+' .poi_embed_object3d').css('opacity',0);
                                break;
                        }
                    }
                }
            }
            if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                position_embed_tooltip_fixed(id);
            }
        }
    }

    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 tooltip_visibility = $('.marker_embed_'+id).attr('data-tooltip_visibility');
            var type = $('.marker_embed_'+id).attr('data-type');
            if(transform3d==0) {
                $('.marker_embed_'+id).css({'top':0,'left':0});
                if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                    $('.tooltip_marker_'+id).css('opacity',1);
                }
                switch(type) {
                    case 'selection':
                        $('.marker_embed_'+id+' .marker_embed_selection').css('opacity',1);
                        break;
                }
            } else if(initialized==1) {
                var pos_1 = ($('#marker_embded_helper_'+id.replace('alt','')+'_1').position());
                pos_1.top=pos_1.top+8;
                pos_1.left=pos_1.left+8;
                $('#draggable_'+id+'_1').css({'top':pos_1.top+'px','left':pos_1.left+'px'});
                var pos_2 = ($('#marker_embded_helper_'+id.replace('alt','')+'_2').position());
                pos_2.top=pos_2.top+8;
                pos_2.left=pos_2.left+8;
                $('#draggable_'+id+'_2').css({'top':pos_2.top+'px','left':pos_2.left+'px'});
                var pos_3 = ($('#marker_embded_helper_'+id.replace('alt','')+'_3').position());
                pos_3.top=pos_3.top+8;
                pos_3.left=pos_3.left+8;
                $('#draggable_'+id+'_3').css({'top':pos_3.top+'px','left':pos_3.left+'px'});
                var pos_4 = ($('#marker_embded_helper_'+id.replace('alt','')+'_4').position());
                pos_4.top=pos_4.top+8;
                pos_4.left=pos_4.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) {
                    if($('.marker_embed_'+id).css('visibility')=='visible' && count_offscreen<=2) {
                        marker_embed_apply_transform(id, $('.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');
                        if(current_transform!="none" && $('#marker_embded_helper_'+id.replace('alt','')+'_1').position().top!=0 && $('#marker_embded_helper_'+id.replace('alt','')+'_2').position().top!=0 && $('#marker_embded_helper_'+id.replace('alt','')+'_3').position().top!=0 && $('#marker_embded_helper_'+id.replace('alt','')+'_4').position().top!=0) {
                            if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                                const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
                                if(pos_1.left>width) {
                                    $('.tooltip_marker_'+id).css('opacity',0);
                                } else {
                                    $('.tooltip_marker_'+id).css('opacity',1);
                                }
                            }
                            switch(type) {
                                case 'selection':
                                    $('.marker_embed_'+id+' .marker_embed_selection').css('opacity',1);
                                    break;
                            }
                        }
                    } else {
                        if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                            $('.tooltip_marker_'+id).css('opacity',0);
                        }
                        switch(type) {
                            case 'selection':
                                $('.marker_embed_'+id+' .marker_embed_selection').css('opacity',0);
                                break;
                        }
                    }
                }
            }
            if(tooltip_visibility=='visible' || (tooltip_visibility=='visible_mobile' && window.is_mobile)) {
                position_embed_tooltip_fixed_m(id);
            }
        }
    }

    function position_embed_tooltip(id,e) {
        var hs_width = $('.tooltip_poi_embed_'+id).outerWidth();
        var hs_height = $('.tooltip_poi_embed_'+id).outerHeight();
        var x = (e.x - $('#vt_container').offset().left) - (hs_width/2);
        var y = (e.y - $('#vt_container').offset().top) - (hs_height)-30;
        if(y<0) y=0;
        if(x<0) x=0;
        if((x+hs_width)>window.c_width) x=window.c_width-hs_width;
        if(!($('.tooltip_poi_embed_'+id).parent().hasClass('pnlm-ui'))) {
            $('.tooltip_poi_embed_'+id).detach().appendTo('.pnlm-ui');
        }
        $('.tooltip_poi_embed_'+id).css({'left':x+'px','top':y+'px','transform':'none'});
    }

    function position_embed_tooltip_fixed(id) {
        var hs_width = $('.tooltip_poi_embed_'+id).outerWidth();
        var hs_height = $('.tooltip_poi_embed_'+id).outerHeight();
        var x1 = $('#poi_embded_helper_'+id+'_1').position().left;
        var y1 = $('#poi_embded_helper_'+id+'_1').position().top;
        var x3 = $('#poi_embded_helper_'+id+'_3').position().left;
        var y3 = $('#poi_embded_helper_'+id+'_3').position().top;
        var x = ((x3+x1)/2) - (hs_width/2);
        var y = ((y3+y1)/2) - (hs_height/2) - 20;
        if(!($('.tooltip_poi_embed_'+id).parent().hasClass('pnlm-ui'))) {
            $('.tooltip_poi_embed_'+id).detach().appendTo('.pnlm-ui');
        }
        $('.tooltip_poi_embed_'+id).css({'left':x+'px','top':y+'px','transform':'none'});
    }

    function hotspot_embed(hotSpotDiv, args) {
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        var id = args.id;
        if(virtual_staging) {
            if (hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                id = "alt"+id;
            }
        }
        var type = args.embed_type;
        var view_type = parseInt(args.view_type);
        var size = args.embed_size.split(",");
        if(args.transform3d==1) {
            var width = size[0]+'px';
            var height = size[1]+'px';
        } else {
            var width = '100%';
            var height = '100%';
            hotSpotDiv.style = 'width:'+size[0]+'px;height:'+size[1]+'px;';
        }
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('poi_embed');
        hotSpotDiv.classList.add('poi_embed_'+id);
        hotSpotDiv.classList.add('hotspot_'+id);
        if(parseInt(args.is_grouped)==1) {
            hotSpotDiv.classList.add('hidden_grouped');
            hotSpotDiv.classList.add('grouped_poi');
        }
        if(virtual_staging) {
            hotSpotDiv.style.zIndex = parseInt(args.zIndex)+10;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.zIndex = args.zIndex;
        }
        if(args.css_class!='') {
            var array_css_class = args.css_class.split(" ");
            jQuery.each(array_css_class, function(index_c, css_class) {
                hotSpotDiv.classList.add(css_class);
            });
        }
        hotSpotDiv.setAttribute('data-id',id);
        hotSpotDiv.setAttribute('data-type',type);
        hotSpotDiv.setAttribute('data-transform3d',args.transform3d);
        hotSpotDiv.setAttribute('data-initialized',0);
        hotSpotDiv.setAttribute('data-tooltip_visibility',args.tooltip_visibility);
        if(args.view_type==2) {
            hotSpotDiv.addEventListener("mouseover", function (e) {
                if(controls_status['icons_content']==true && !window.is_mobile) {
                    var id = e.target.getAttribute('data-id');
                    if(id !== null) {
                        view_poi_box(id,true);
                    }
                }
            });
            hotSpotDiv.addEventListener("mouseenter", function (e) {
                if(controls_status['icons_content']==true && !window.is_mobile) {
                    var id = e.target.getAttribute('data-id');
                    if(id !== null) {
                        if(leave_poi_open==0) close_all_pois();
                        view_poi_box(id,true);
                    }
                }
            });
        } else {
            switch(args.tooltip_type) {
                case 'text':
                    if(window.is_mobile && (args.tooltip_text_mobile !== null && args.tooltip_text_mobile !== '' && args.tooltip_text_mobile !== '<p><br></p>')) {
                        args.tooltip_text = args.tooltip_text_mobile;
                    }
                    if(args.tooltip_text !== null && args.tooltip_text !== '' && args.tooltip_text !== '<p><br></p>') {
                        var tooltip = document.createElement('div');
                        tooltip.classList.add('tooltip_poi_embed_'+id);
                        tooltip.classList.add('tooltip_text_embed');
                        tooltip.classList.add('tooltip_poi');
                        tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                        tooltip.innerHTML = args.tooltip_text;
                        hotSpotDiv.appendChild(tooltip);
                    }
                    break;
            }
        }
        try {
            if(controls_status['icons_content']==false) tooltip.classList.add('hidden_icons');
        } catch (e) {}
        switch(args.tooltip_visibility) {
            case 'hover':
                hotSpotDiv.addEventListener("mouseover", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'poi_embed');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                switch(args.embed_type) {
                                    case 'link':
                                        position_embed_tooltip_fixed(id);
                                        break;
                                    default:
                                        position_embed_tooltip(id,e);
                                        break;
                                }
                                switch(args.embed_type) {
                                    case 'video':
                                        if(video_embeds[id].paused() && !$('.vjs-control-bar').is(':visible')) {
                                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        }
                                        break;
                                    case 'selection':
                                        if(args.embed_params=='') {
                                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        }
                                        break;
                                    case 'link':
                                        $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        break;
                                    default:
                                        $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        break;
                                }
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            switch(args.embed_type) {
                                case 'video':
                                    if(video_embeds[id].paused() && !$('.vjs-control-bar').is(':visible')) {
                                        $('.tooltip_poi_embed_'+id).css('opacity',1);
                                    }
                                    break;
                                case 'selection':
                                    if(args.embed_params=='') {
                                        $('.tooltip_poi_embed_'+id).css('opacity',1);
                                    }
                                    break;
                                case 'link':
                                    $('.tooltip_poi_embed_'+id).css('opacity',1);
                                    break;
                                default:
                                    $('.tooltip_poi_embed_'+id).css('opacity',1);
                                    break;
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            switch(args.embed_type) {
                                case 'video':
                                    $('.tooltip_poi_embed_'+id).css('opacity',0);
                                    break;
                                case 'selection':
                                    if(args.embed_params=='') {
                                        $('.tooltip_poi_embed_'+id).css('opacity',0);
                                    }
                                    break;
                                case 'link':
                                    $('.tooltip_poi_embed_'+id).css('opacity',0);
                                    break;
                                default:
                                    $('.tooltip_poi_embed_'+id).css('opacity',0);
                                    break;
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mousemove", function (e) {
                    if(controls_status['icons_content']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'poi_embed');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                switch(args.embed_type) {
                                    case 'link':
                                        position_embed_tooltip_fixed(id);
                                        break;
                                    default:
                                        position_embed_tooltip(id,e);
                                        break;
                                }
                            }
                        }
                    }
                });
                break;
            case 'visible':
                $('.tooltip_poi_embed_'+id).css('opacity',1);
                break;
            case 'visible_mobile':
                if(window.is_mobile) {
                    $('.tooltip_poi_embed_'+id).css('opacity',1);
                } else {
                    hotSpotDiv.addEventListener("mouseover", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'poi_embed');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    switch(args.embed_type) {
                                        case 'link':
                                            position_embed_tooltip_fixed(id);
                                            break;
                                        default:
                                            position_embed_tooltip(id,e);
                                            break;
                                    }
                                    switch(args.embed_type) {
                                        case 'video':
                                            if(video_embeds[id].paused() && !$('.vjs-control-bar').is(':visible')) {
                                                $('.tooltip_poi_embed_'+id).css('opacity',1);
                                            }
                                            break;
                                        case 'selection':
                                            if(args.embed_params=='') {
                                                $('.tooltip_poi_embed_'+id).css('opacity',1);
                                            }
                                            break;
                                        case 'link':
                                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                                            break;
                                        default:
                                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                                            break;
                                    }
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseenter", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                switch(args.embed_type) {
                                    case 'video':
                                        if(video_embeds[id].paused() && !$('.vjs-control-bar').is(':visible')) {
                                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        }
                                        break;
                                    case 'selection':
                                        if(args.embed_params=='') {
                                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        }
                                        break;
                                    case 'link':
                                        $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        break;
                                    default:
                                        $('.tooltip_poi_embed_'+id).css('opacity',1);
                                        break;
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseleave", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                switch(args.embed_type) {
                                    case 'video':
                                        $('.tooltip_poi_embed_'+id).css('opacity',0);
                                        break;
                                    case 'selection':
                                        if(args.embed_params=='') {
                                            $('.tooltip_poi_embed_'+id).css('opacity',0);
                                        }
                                        break;
                                    case 'link':
                                        $('.tooltip_poi_embed_'+id).css('opacity',0);
                                        break;
                                    default:
                                        $('.tooltip_poi_embed_'+id).css('opacity',0);
                                        break;
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mousemove", function (e) {
                        if(controls_status['icons_content']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'poi_embed');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    switch(args.embed_type) {
                                        case 'link':
                                            position_embed_tooltip_fixed(id);
                                            break;
                                        default:
                                            position_embed_tooltip(id,e);
                                            break;
                                    }
                                }
                            }
                        }
                    });
                }
                break;
        }
        switch(type) {
            case 'image':
                var img = document.createElement('img');
                img.setAttribute('draggable',false);
                img.src = ((window.s3_enabled) ? window.s3_url : '')+args.embed_content;
                if(args.type!='' && args.type!=null) {
                    img.classList.add('highlight_poi_embed');
                } else {
                    if(args.sound=='') {
                        hotSpotDiv.classList.add('poi_not_selectable');
                    }
                }
                img.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                if(args.title==null) args.title = '';
                if(args.description==null) args.description = '';
                if((args.title!='') && (args.description!='')) {
                    var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
                } else if((args.title!='') && (args.description=='')) {
                    var caption = '<b>'+args.title+'</b>';
                } else if((args.title=='') && (args.description!='')) {
                    var caption = '<i>'+args.description+'</i>';
                } else {
                    var caption = '';
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(img);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(img);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(img);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(img);
                        hotSpotDiv.appendChild(a);
                        break;
                    default:
                        hotSpotDiv.appendChild(img);
                        break;
                }
                break;
            case 'text':
                var div = document.createElement('div');
                if(args.type=='' || args.type==null) {
                    if(args.sound=='') {
                        hotSpotDiv.classList.add('poi_not_selectable');
                    }
                }
                div.setAttribute('draggable',false);
                div.classList.add('poi_embed_text');
                var embed_content = args.embed_content.split(' border-width')[0];
                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;
                if(args.title==null) args.title = '';
                if(args.description==null) args.description = '';
                if((args.title!='') && (args.description!='')) {
                    var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
                } else if((args.title!='') && (args.description=='')) {
                    var caption = '<b>'+args.title+'</b>';
                } else if((args.title=='') && (args.description!='')) {
                    var caption = '<i>'+args.description+'</i>';
                } else {
                    var caption = '';
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    default:
                        hotSpotDiv.appendChild(div);
                        break;
                }
                break;
            case 'html':
                var div = document.createElement('div');
                if(args.type=='' || args.type==null) {
                    if(args.sound=='') {
                        hotSpotDiv.classList.add('poi_not_selectable');
                    }
                }
                div.setAttribute('draggable',false);
                div.classList.add('poi_embed_html');
                div.innerHTML = args.embed_content;
                div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                if(args.title==null) args.title = '';
                if(args.description==null) args.description = '';
                if((args.title!='') && (args.description!='')) {
                    var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
                } else if((args.title!='') && (args.description=='')) {
                    var caption = '<b>'+args.title+'</b>';
                } else if((args.title=='') && (args.description!='')) {
                    var caption = '<i>'+args.description+'</i>';
                } else {
                    var caption = '';
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    default:
                        hotSpotDiv.appendChild(div);
                        break;
                }
                break;
            case 'selection':
                var div = document.createElement('div');
                div.setAttribute('draggable',false);
                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:none;";
                } else {
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:"+bg_color+";border-color:"+color+";-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;"+args.embed_content;                }
                div.id = "poi_embed_selection_"+id;
                div.classList.add('poi_embed_selection');
                div.setAttribute('data-id',id);
                if(args.embed_params!='') {
                    var canvas = document.createElement('canvas');
                    canvas.id = 'canvas_selection_'+id;
                    canvas.width = width.replace('px','');
                    canvas.height = height.replace('px','');
                    div.appendChild(canvas);
                }
                if(args.type=='' || args.type==null) {
                    if(args.sound=='') {
                        hotSpotDiv.classList.add('poi_not_selectable');
                    }
                }
                if(args.embed_params!='') {
                    canvas.addEventListener("click", function (e) {
                        var diff_drag = end_drag - start_drag;
                        if(drag_p == false || diff_drag < 200) {
                            var points = JSON.parse(args.embed_params);
                            var pol = new Path2D();
                            for (const p of points) { pol.lineTo(p.x, p.y) }
                            pol.closePath();
                            var canvas = document.getElementById('canvas_selection_'+id);
                            var ctx = canvas.getContext('2d');
                            if (ctx.isPointInPath(pol, e.offsetX, e.offsetY)) {
                                switch(args.type) {
                                    case 'image':
                                    case 'gallery':
                                    case 'video360':
                                    case 'audio':
                                    case 'html':
                                    case 'html_sc':
                                    case 'form':
                                    case 'google_maps':
                                    case 'object360':
                                    case 'object3d':
                                    case 'download':
                                    case 'video':
                                    case 'link':
                                    case 'link_ext':
                                    case 'lottie':
                                    case 'product':
                                    case 'pdf':
                                        view_content('', args);
                                        break;
                                    case 'switch_pano':
                                        change_room_alt_poi('', args)
                                        break;
                                }
                            }
                        }
                    });
                    canvas.addEventListener("mousedown", function (e) {
                        start_drag = new Date().getTime();
                        drag_p = false;
                    });
                    canvas.addEventListener("mousemove", function (e) {
                        end_drag = new Date().getTime();
                        drag_p = true;
                        var points = JSON.parse(args.embed_params);
                        var pol = new Path2D();
                        for (const p of points) { pol.lineTo(p.x, p.y) }
                        pol.closePath();
                        var canvas = document.getElementById('canvas_selection_'+id);
                        var ctx = canvas.getContext('2d');
                        if (ctx.isPointInPath(pol, e.offsetX, e.offsetY)) {
                            if(args.type!='' && args.type!=null) {
                                $('#poi_embed_selection_'+id).css('cursor','pointer');
                                $('#canvas_selection_'+id).css('cursor','pointer');
                                $('.poi_embed_'+id).css('cursor','pointer');
                                draw_polygon(canvas,points,border,bg_color,color,true);
                            } else {
                                draw_polygon(canvas,points,border,bg_color,color,false);
                            }
                            $('.tooltip_poi_embed_'+id).css('opacity',1);
                        } else {
                            $('#poi_embed_selection_'+id).css('cursor','unset');
                            $('#canvas_selection_'+id).css('cursor','unset');
                            $('.poi_embed_'+id).css('cursor','unset');
                            $('.tooltip_poi_embed_'+id).css('opacity',0);
                            draw_polygon(canvas,points,border,bg_color,color,false);
                        }
                    });
                    canvas.addEventListener("mouseleave", function (e) {
                        var points = JSON.parse(args.embed_params);
                        var canvas = document.getElementById('canvas_selection_'+id);
                        $('#poi_embed_selection_'+id).css('cursor','unset');
                        $('#canvas_selection_'+id).css('cursor','unset');
                        $('.poi_embed_'+id).css('cursor','unset');
                        $('.tooltip_poi_embed_'+id).css('opacity',0);
                        draw_polygon(canvas,points,border,bg_color,color,false);
                    });
                } else {
                    div.addEventListener("mouseover", function (e) {
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('-webkit-box-shadow','0 0 10px 4px '+color);
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('-moz-box-shadow','0 0 10px 4px '+color);
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('box-shadow','0 0 10px 4px '+color);
                    });
                    div.addEventListener("mouseenter", function (e) {
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('-webkit-box-shadow','0 0 10px 4px '+color);
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('-moz-box-shadow','0 0 10px 4px '+color);
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('box-shadow','0 0 10px 4px '+color);
                    });
                    div.addEventListener("mouseleave", function (e) {
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('-webkit-box-shadow','none');
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('-moz-box-shadow','none');
                        $('#poi_embed_selection_'+e.target.getAttribute('data-id')).css('box-shadow','none');
                    });
                }
                if(args.title==null) args.title = '';
                if(args.description==null) args.description = '';
                if((args.title!='') && (args.description!='')) {
                    var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
                } else if((args.title!='') && (args.description=='')) {
                    var caption = '<b>'+args.title+'</b>';
                } else if((args.title=='') && (args.description!='')) {
                    var caption = '<i>'+args.description+'</i>';
                } else {
                    var caption = '';
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    default:
                        hotSpotDiv.appendChild(div);
                        break;
                }
                if(type=='selection' && 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,points,border,bg_color,color,false);
                    } 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_'+id);
                div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                var html = '<div class="glide__track" data-glide-el="track"><ul class="glide__slides">';
                jQuery.each(args.embed_content, function(index, image) {
                    html += '<li style="height:'+height+'px" class="glide__slide"><img style="object-fit: contain;width: 100%;height: 100%" src="'+((window.s3_enabled) ? window.s3_url : '')+image+'" /></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);
                new Glide('.poi_embed_gallery_'+id,{
                    type: 'carousel',
                    startAt: 0,
                    perView: 1,
                    hoverpause: true,
                    keyboard: false,
                    autoplay: parseInt(args.embed_gallery_autoplay)*1000
                }).mount();
                break;
            case 'video_chroma':
                var embed_video_muted = parseInt(args.embed_video_muted);
                var embed_video_autoplay = parseInt(args.embed_video_autoplay);
                var embed_video_loop = parseInt(args.embed_video_loop);
                var video = document.createElement('video');
                video.setAttribute('draggable',false);
                video.id = "video_embed_"+id;
                video.classList.add('noselect');
                video.setAttribute("preload", "auto");
                if(embed_video_loop==1) {
                    video.setAttribute("loop", "");
                }
                if(embed_video_muted==1) {
                    video.setAttribute("muted", "");
                }
                video.setAttribute('playsinline', '');
                video.setAttribute('webkit-playsinline','');
                video.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                video.crossOrigin = "anonymous";
                video.src = ((window.s3_enabled) ? window.s3_url : '')+args.embed_content+'#t=0.1';
                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');
                var c_chroma_tmp = document.createElement('canvas');
                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');
                video.addEventListener('play', (event) => {
                    $('.poi_embed_'+id+' .div_play_btn').hide();
                    $('.poi_embed_'+id).css('pointer-events','none');
                    remove_background_video_chroma(video,ctx_chroma_tmp,ctx_chroma,width.replace('px',''),height.replace('px',''),args.params,false);
                });
                video.addEventListener('loadeddata', function() {
                    remove_background_video_chroma(video,ctx_chroma_tmp,ctx_chroma,width.replace('px',''),height.replace('px',''),args.params,true);
                });
                video.addEventListener('loadedmetadata', function() {
                    remove_background_video_chroma(video,ctx_chroma_tmp,ctx_chroma,width.replace('px',''),height.replace('px',''),args.params,true);
                    if(embed_video_autoplay==1) {
                        _checkAutoPlay(video.play(),id);
                    } else {
                        _callback_onAutoplayBlocked(id);
                    }
                });
                hotSpotDiv.appendChild(video);
                var div = document.createElement('div');
                div.classList.add('div_play_btn');
                div.innerHTML = '<i onclick="play_video_transparent('+id+');" class="far fa-play-circle"></i>';
                hotSpotDiv.appendChild(div);
                break;
            case 'video_transparent':
                var embed_video_muted = parseInt(args.embed_video_muted);
                var embed_video_autoplay = parseInt(args.embed_video_autoplay);
                var embed_video_loop = parseInt(args.embed_video_loop);
                var video = document.createElement('video');
                video.setAttribute('draggable',false);
                video.id = "video_embed_"+id;
                video.classList.add('noselect');
                video.setAttribute("preload", "auto");
                if(embed_video_loop==1) {
                    video.setAttribute("loop", "");
                }
                if(embed_video_muted==1) {
                    video.setAttribute("muted", "");
                }
                if(embed_video_autoplay==1 && parseInt(args.is_grouped)==0) {
                    video.setAttribute("autoplay", "");
                } else if(parseInt(args.is_grouped)==1) {
                    video.setAttribute("data-autoplay", embed_video_autoplay);
                }
                video.setAttribute('playsinline', '');
                video.setAttribute('webkit-playsinline','');
                video.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                var array_videos = args.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()) {
                        video.src = ((window.s3_enabled) ? window.s3_url : '')+mov_source;
                    } else {
                        video.src = ((window.s3_enabled) ? window.s3_url : '')+webm_source;
                    }
                } else if(mov_source!='') {
                    video.src = ((window.s3_enabled) ? window.s3_url : '')+mov_source;
                } else if(webm_source!='') {
                    video.src = ((window.s3_enabled) ? window.s3_url : '')+webm_source;
                }
                video.addEventListener('play', (event) => {
                    $('.poi_embed_'+id+' .div_play_btn').hide();
                    $('.poi_embed_'+id).css('pointer-events','none');
                });
                hotSpotDiv.appendChild(video);
                var div = document.createElement('div');
                div.classList.add('div_play_btn');
                div.innerHTML = '<i onclick="play_video_transparent('+id+');" class="far fa-play-circle"></i>';
                hotSpotDiv.appendChild(div);
                if(embed_video_autoplay==1) {
                    _checkAutoPlay(video.play(),id);
                } else {
                    _callback_onAutoplayBlocked(id);
                }
                break;
            case 'video':
                var embed_video_muted = parseInt(args.embed_video_muted);
                var embed_video_autoplay = parseInt(args.embed_video_autoplay);
                var embed_video_loop = parseInt(args.embed_video_loop);
                var video = document.createElement('video');
                video.setAttribute('draggable',false);
                video.id = "video_embed_"+id;
                video.classList.add('video-js');
                if(parseInt(width.replace('px',''))<250) {
                    video.classList.add('small-video');
                }
                if(window.is_mobile) {
                    video.classList.add('vjs-theme-city');
                } else {
                    video.classList.add('vjs-default-skin');
                }
                video.classList.add('vjs-fill');
                video.classList.add('vjs-big-play-centered');
                video.classList.add('noselect');
                if(window.is_mobile) {
                    video.classList.add('control_bar_visible');
                }
                video.setAttribute("preload", "auto");
                if(embed_video_loop==1) {
                    video.setAttribute("loop", "");
                }
                if(embed_video_muted==1) {
                    video.setAttribute("muted", "");
                }
                if(embed_video_autoplay==1 && parseInt(args.is_grouped)==0) {
                    video.setAttribute("autoplay", "");
                } else if(parseInt(args.is_grouped)==1) {
                    video.setAttribute("data-autoplay", embed_video_autoplay);
                }
                video.setAttribute("controls", "");
                video.setAttribute('playsinline', '');
                video.setAttribute('webkit-playsinline','');
                video.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                if(args.embed_content!='' && args.embed_content!==undefined && args.embed_content!=null) {
                    if(args.embed_content.includes("youtu")) {
                        if(args.embed_content.includes("/shorts/")) {
                            args.embed_content = convertYouTubeShortsToWatchUrl(args.embed_content);
                        }
                        video.setAttribute('data-setup','{ "techOrder":["youtube"],"sources":[{"type":"video/youtube","src":"'+args.embed_content+'"}],"youtube":{"rel":0,"modestbranding":1,"controls":0,"iv_load_policy":3,"loop":1,"playsinline":1,"showinfo":0,"fs":0,"disablekb":1,"autoplay":'+embed_video_autoplay+',"muted":'+embed_video_muted+'}}');
                    } else {
                        var source = document.createElement('source');
                        source.src = ((window.s3_enabled) ? window.s3_url : '')+args.embed_content;
                        source.type = 'video/mp4';
                        video.appendChild(source);
                    }
                }
                hotSpotDiv.appendChild(video);
                try {
                    if (typeof video_embeds[id] !== 'undefined') {
                        video_embeds[id].dispose();
                    }
                } catch (e) {}
                if(window.is_mobile) {
                    video_embeds[id] = videojs('video_embed_'+id, {
                        controlBar: {
                            fullscreenToggle: true,
                            pictureInPictureToggle: false,
                            volumePanel: true
                        }
                    }, function() {
                        video_embeds[id].controlBar.progressControl.el().style.display = 'none';
                        $('.poi_embed_'+id+' video').css({'width':'100%','height':'100%'});
                    });
                } else {
                    video_embeds[id] = videojs('video_embed_'+id, {
                        controlBar: {
                            fullscreenToggle: true,
                            pictureInPictureToggle: false,
                            volumePanel: {
                                inline: false,
                                volumeControl: {
                                    vertical: true
                                }
                            }
                        }
                    }, function() {
                        $('.poi_embed_'+id+' video').css({'width':'100%','height':'100%'});
                    });
                }
                video_embeds[id].on('play', () => {
                    if(args.tooltip_visibility=='hover' || (args.tooltip_visibility=='visible_mobile' && !window.is_mobile)) {
                        $('.tooltip_poi_embed_' + id).css('opacity', 0);
                    }
                    if(video_embeds[id].volume()>0 && !video_embeds[id].muted()) {
                        try {
                            if(controls_status['song']) {
                                mute_audio(true,true);
                                $('.song_control').removeClass('active_control');
                                $('.song_alt_control').removeClass('active_control');
                                $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
                                $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
                                controls_status['song']=false;
                                force_audio_muted = true;
                                song_is_playng = true;
                            }
                        } catch (e) {}
                    }
                });
                video_embeds[id].on('volumechange', () => {
                    if(!video_embeds[id].paused() && video_embeds[id].volume()>0 && !video_embeds[id].muted()) {
                        try {
                            if(controls_status['song']) {
                                mute_audio(true,true);
                                $('.song_control').removeClass('active_control');
                                $('.song_alt_control').removeClass('active_control');
                                $('.song_control i').removeClass('fa-volume-down').addClass('fa-volume-mute');
                                $('.song_alt_control .fa-circle').removeClass('active').addClass('not_active');
                                controls_status['song']=false;
                                force_audio_muted = true;
                                song_is_playng = true;
                            }
                        } catch (e) {}
                    } else {
                        if(force_audio_muted) {
                            if(song_is_playng) {
                                unmute_audio(true,true);
                                $('.song_control').addClass('active_control');
                                $('.song_alt_control').addClass('active_control');
                                $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                                $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                                controls_status['song']=true;
                                force_audio_muted = false;
                            }
                        }
                    }
                });
                video_embeds[id].on('pause', () => {
                    if(force_audio_muted) {
                        if(song_is_playng) {
                            unmute_audio(true,true);
                            $('.song_control').addClass('active_control');
                            $('.song_alt_control').addClass('active_control');
                            $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                            $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                            controls_status['song']=true;
                            force_audio_muted = false;
                        }
                    }
                });
                video_embeds[id].on('end', () => {
                    if(force_audio_muted) {
                        if(song_is_playng) {
                            unmute_audio(true,true);
                            $('.song_control').addClass('active_control');
                            $('.song_alt_control').addClass('active_control');
                            $('.song_control i').addClass('fa-volume-down').removeClass('fa-volume-mute');
                            $('.song_alt_control .fa-circle').removeClass('not_active').addClass('active');
                            controls_status['song']=true;
                            force_audio_muted = false;
                        }
                    }
                });
                $('.poi_embed_'+id).on('touchstart click', function (e) {
                    if(e.target.className=='vjs-icon-placeholder') {
                        return;
                    }
                    if(video_embeds[id].paused()) {
                        video_embeds[id].play();
                    } else {
                        video_embeds[id].pause();
                    }
                });
                if(navigator.userAgent.toLowerCase().indexOf('mobi') >= 0) {
                    $('.poi_embed_'+id+' .vjs-control-bar').css('display','none');
                    $('.poi_embed_'+id+' .vjs-big-play-button').css('font-size','1em');
                } else {
                    video_embeds[id].one('play', function () {
                        if(!args.embed_content.includes("youtu")) {
                            this.currentTime(0);
                        }
                    });
                }
                if(parseInt(args.embed_video_autoplay)==1) {
                    video_embeds[id].oncanplay = function () {
                        video_embeds[id].play();
                    };
                }
                break;
            case 'link':
                var div = document.createElement('div');
                div.classList.add('poi_embed_link');
                div.classList.add('poi_embed_link_'+id);
                div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                var html = '<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" allow="accelerometer; camera; display-capture; fullscreen; geolocation; gyroscope; magnetometer; microphone; midi; xr-spatial-tracking;" frameborder="0" marginheight="0" marginwidth="0" style="border:none;" width="'+width+'px" height="'+height+'px" src="'+args.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_'+id);
                div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;";
                if(args.type!='' && args.type!=null) {
                    div.classList.add('highlight_poi_embed');
                } else {
                    if(args.sound=='') {
                        hotSpotDiv.classList.add('poi_not_selectable');
                    }
                }
                if(args.embed_params!='') {
                    var tmp = args.embed_params.split(",");
                    var camera_coord = tmp[0];
                    var interaction = parseInt(tmp[1]);
                    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 = '';
                    }
                    var coords_part = camera_coord.split(" ");
                    camera_coord = coords_part[0]+" "+coords_part[1]+" 100%";
                    switch(interaction) {
                        case 0: //disabled
                            interaction = '';
                            var camera_controls = '';
                            break;
                        case 1: //horizontal and vertical
                            div.classList.add('is_interactive');
                            var camera_controls = 'camera-controls';
                            var rotate_3d_object = '';
                            break;
                        case 2: //horizontal
                            div.classList.add('is_interactive');
                            var camera_controls = 'camera-controls';
                            var rotate_3d_object = 'min-camera-orbit="auto '+coords_part[1]+' auto" max-camera-orbit="auto '+coords_part[1]+' auto"';
                            break;
                        case 3: //vertical
                            div.classList.add('is_interactive');
                            var camera_controls = 'camera-controls';
                            var rotate_3d_object = 'min-camera-orbit="'+coords_part[0]+' 22.5deg auto" max-camera-orbit="'+coords_part[0]+' 157.5deg auto"';
                            break;
                    }
                } else {
                    var camera_coord = '';
                    var camera_controls = '';
                    var exposure = 1;
                    var rotate_3d_object = '';
                    var environment = 'legacy';
                    var shadow_intensity = 1;
                    var shadow_softness = 0.5;
                    var zoom_deg = 'auto';
                    var animation = '';
                    var autoplay = '';
                }
                var panorama_image_environment = '';
                if(environment=='panorama') {
                    var current_index_panorama = get_id_viewer(current_id_panorama);
                    panorama_image_environment = ((window.s3_enabled) ? window.s3_url : '')+panoramas[current_index_panorama].panorama_image.replace('mobile/','').replace('panoramas/','panoramas/lowres/');
                }
                var html = '<model-viewer disable-tap disable-pan disable-zoom min-field-of-view="'+zoom_deg+'" max-field-of-view="'+zoom_deg+'" environment-image="'+panorama_image_environment+'" shadow-intensity="'+shadow_intensity+'" shadow-softness="'+shadow_softness+'" exposure="'+exposure+'" '+camera_controls+' '+autoplay+' animation-name="'+animation+'" id="object3d_'+id+'" src="'+((window.s3_enabled) ? window.s3_url : '')+args.embed_content+'" alt="" disable-zoom bounds="tight" interaction-prompt="none" '+rotate_3d_object+' camera-orbit="'+camera_coord+'"><div class="object3d_loading" slot="progress-bar"><i class="fas fa-spin fa-circle-notch"></i></div></model-viewer>';
                div.innerHTML=html;
                if(args.title==null) args.title = '';
                if(args.description==null) args.description = '';
                if((args.title!='') && (args.description!='')) {
                    var caption = '<b>'+args.title+'</b><br><i>'+args.description+'</i>';
                } else if((args.title!='') && (args.description=='')) {
                    var caption = '<b>'+args.title+'</b>';
                } else if((args.title=='') && (args.description!='')) {
                    var caption = '<i>'+args.description+'</i>';
                } else {
                    var caption = '';
                }
                switch (args.type) {
                    case 'download':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = ((window.s3_enabled) ? window.s3_url : '')+args.content;
                                a.target = '_blank';
                                a.download = '';
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('download');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link':
                    case 'pdf':
                        var a = document.createElement('a');
                        a.id = "link_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    if(args.content.includes('.pdf')) {
                                        if (args.content.startsWith('http')) {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                        } else {
                                            if(export_mode==1) {
                                                a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                            } else {
                                                a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                            }
                                        }
                                    } else {
                                        a.href = args.content;
                                    }
                                    a.setAttribute('data-fancybox','');
                                    a.setAttribute('data-caption',caption);
                                    a.setAttribute('data-type','iframe');
                                    a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                } else {
                                    a.href = '#';
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    a.removeAttribute('data-type');
                                    a.removeAttribute('data-options');
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                if(args.content.includes('.pdf')) {
                                    if (args.content.startsWith('http')) {
                                        a.href = 'vendor/pdf_viewer/index.php?file='+args.content;
                                    } else {
                                        if(export_mode==1) {
                                            a.href = 'vendor/pdf_viewer/index.html?file='+args.content;
                                        } else {
                                            a.href = 'vendor/pdf_viewer/index.php?file='+((window.s3_enabled) ? window.s3_url : window.base_url+'viewer/')+args.content;
                                        }
                                    }
                                } else {
                                    a.href = args.content;
                                }
                                a.setAttribute('data-fancybox','');
                                a.setAttribute('data-caption',caption);
                                a.setAttribute('data-type','iframe');
                                a.setAttribute('data-options','{"type" : "iframe", "iframe" : {"preload" : false}}');
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'link_ext':
                        var a = document.createElement('a');
                        a.style = 'text-decoration:none;';
                        a.addEventListener('mousedown', function(e) {
                            start_drag = new Date().getTime();
                            drag_p = false;
                        }, false);
                        a.addEventListener('mousemove', function(e) {
                            end_drag = new Date().getTime();
                            drag_p = true;
                        }, false);
                        a.addEventListener('mouseup', function(e) {
                            var diff_drag = end_drag - start_drag;
                            if(drag_p == false || diff_drag < 200) {
                                a.href = args.content;
                                a.target = args.target;
                            } else {
                                a.removeAttribute('href');
                                a.removeAttribute('target');
                            }
                        }, false);
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    case 'video':
                        var a = document.createElement('a');
                        a.id = "video_"+id;
                        a.style = 'text-decoration:none;';
                        a.title = args.title;
                        if(view_type==0) {
                            a.addEventListener('mousedown', function(e) {
                                start_drag = new Date().getTime();
                                drag_p = false;
                            }, false);
                            a.addEventListener('mousemove', function(e) {
                                end_drag = new Date().getTime();
                                drag_p = true;
                            }, false);
                            a.addEventListener('mouseup', function(e) {
                                var diff_drag = end_drag - start_drag;
                                if(drag_p == false || diff_drag < 200) {
                                    a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                    a.onclick = function() {
                                        open_video("video_"+id);
                                    };
                                    a.setAttribute('data-fancybox', '');
                                    a.setAttribute('data-caption', caption);
                                } else {
                                    a.href = '#';
                                    a.onclick = function() {};
                                    a.removeAttribute('data-fancybox');
                                    a.removeAttribute('data-caption');
                                    e.preventDefault();
                                    e.stopImmediatePropagation();
                                }
                            }, false);
                            a.addEventListener('simulate_click', function (e) {
                                a.href = (args.content.startsWith('http')) ? args.content : ((window.s3_enabled) ? window.s3_url : '')+args.content+'#t=0';
                                a.onclick = function() {
                                    open_video("video_"+id);
                                };
                                a.setAttribute('data-fancybox', '');
                                a.setAttribute('data-caption', caption);
                                a.click();
                            }, false);
                        }
                        a.appendChild(div);
                        hotSpotDiv.appendChild(a);
                        break;
                    default:
                        hotSpotDiv.appendChild(div);
                        break;
                }
                break;
        }
        if(args.type=='audio') {
            var html_audio_poi = '<audio playsinline webkit-playsinline preload="auto" controls controlsList="nodownload">\n' +
                '<source src="'+((window.s3_enabled) ? window.s3_url : '')+args.content+'" type="audio/mpeg">\n' +
                'Your browser does not support the audio element.\n' +
                '</audio>';
            var audio_poi_player = document.createElement('div');
            audio_poi_player.setAttribute('data-id',id);
            audio_poi_player.setAttribute('data-playing',0);
            audio_poi_player.classList.add("audio_poi_"+id);
            audio_poi_player.classList.add('audio_poi_embed');
            audio_poi_player.innerHTML = html_audio_poi;
            hotSpotDiv.appendChild(audio_poi_player);
        }
        if(type=='object3d') {
            const onProgress_object = (event) => {
                const progressBar = event.target.querySelector('.object3d_loading');
                if (event.detail.totalProgress === 0) {
                    progressBar.style.opacity = 1;
                    progressBar.style.display = 'block';
                } else {
                    if (event.detail.totalProgress === 1) {
                        setTimeout(() => {
                            progressBar.style.opacity = 0;
                            setTimeout(() => {
                                progressBar.style.display = 'none';
                            }, 500);
                        }, 200);
                    }
                }
            };
            document.querySelector('model-viewer#object3d_'+id).addEventListener('progress', onProgress_object);
        }
        if(window.learning_mode>0) {
            var div = document.createElement('div');
            var i = document.createElement('i');
            div.id = 'learning_check_'+args.id;
            div.classList.add('learning_check');
            i.classList = window.learning_check_icon;
            if(learning_poi_visited.includes(args.id)) {
                div.classList.add('visited');
            }
            div.appendChild(i);
            hotSpotDiv.appendChild(div);
            if(window.learning_poi_progressive) {
                if(check_learning_poi_progressive_disabled(args.id,args.id_room)) {
                    if(args.type!=null && args.type!='' && args.type!='grouped' && parseInt(args.learning)==1) hotSpotDiv.classList.add('disabled_l');
                }
            }
        }
        embed_pois_contents(hotSpotDiv,view_type,args,caption,false);
    }

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

    function draw_polygon(canvas,points,border,background,color,highlight) {
        var ctx_selection = canvas.getContext("2d");
        ctx_selection.clearRect(0,0,canvas.width,canvas.height);
        if(highlight) {
            ctx_selection.shadowBlur= 10;
            ctx_selection.shadowOffsetX = 0;
            ctx_selection.shadowOffsetY = 0;
            ctx_selection.shadowColor=color;
        } else {
            ctx_selection.shadowBlur= 0;
        }
        ctx_selection.lineWidth = border;
        ctx_selection.strokeStyle = color;
        ctx_selection.fillStyle = background;
        ctx_selection.beginPath();
        for (const p of points) { ctx_selection.lineTo(p.x, p.y) }
        ctx_selection.closePath();
        ctx_selection.stroke();
        ctx_selection.fill();
    }

    function remove_background_video_chroma(video_chroma,ctx_chroma_tmp,ctx_chroma,width,height,params,force=false) {
        if (!force && (video_chroma.paused || video_chroma.ended)) { return;}
        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 position_embed_tooltip_m(id,e) {
        var hs_width = $('.tooltip_marker_'+id).outerWidth();
        var hs_height = $('.tooltip_marker_'+id).outerHeight();
        var x = (e.x - $('#vt_container').offset().left) - (hs_width/2);
        var y = (e.y - $('#vt_container').offset().top) - (hs_height)-30;
        if(y<0) y=0;
        if(x<0) x=0;
        if((x+hs_width)>window.c_width) x=window.c_width-hs_width;
        if(!($('.tooltip_marker_'+id).parent().hasClass('pnlm-ui'))) {
            $('.tooltip_marker_'+id).detach().appendTo('.pnlm-ui');
        }
        $('.tooltip_marker_'+id).css({'left':x+'px','top':y+'px','transform':'none'});
    }

    function position_embed_tooltip_fixed_m(id) {
        var hs_width = $('.tooltip_marker_'+id).outerWidth();
        var hs_height = $('.tooltip_marker_'+id).outerHeight();
        var x1 = $('#marker_embded_helper_'+id+'_1').position().left;
        var y1 = $('#marker_embded_helper_'+id+'_1').position().top;
        var x4 = $('#marker_embded_helper_'+id+'_4').position().left;
        var y4 = $('#marker_embded_helper_'+id+'_4').position().top;
        var x = ((x4+x1)/2) - (hs_width/2);
        var y = ((y4+y1)/2) - (hs_height/2);
        if(!($('.tooltip_marker_'+id).parent().hasClass('pnlm-ui'))) {
            $('.tooltip_marker_'+id).detach().appendTo('.pnlm-ui');
        }
        $('.tooltip_marker_'+id).css({'left':x+'px','top':y+'px','transform':'none'});
    }

    function hotspot_embed_m(hotSpotDiv, args) {
        if(vr_enabled && args.embed_type=='selection') {
            args.transform3d = 0;
            args.embed_type = '';
            hotspot(hotSpotDiv, args);
            return;
        }
        if(args.visible_multiview_ids!='') {
            var multiview_ids = args.visible_multiview_ids.split(",");
            multiview_ids = multiview_ids.map(str => parseInt(str));
            if(virtual_staging) {
                if (!hotSpotDiv.classList.contains('custom-hotspot_alt')) {
                    if(!multiview_ids.includes(window.id_room_alt_sel)) {
                        return;
                    }
                } else {
                    if(!multiview_ids.includes(0)) {
                        return;
                    }
                }
            }  else {
                if(!multiview_ids.includes(window.id_room_alt_sel)) {
                    return;
                }
            }
        }
        var id = args.id;
        var type = args.embed_type;
        var size = args.embed_size.split(",");
        var width = size[0]+'px';
        var height = size[1]+'px';
        hotSpotDiv.setAttribute('draggable',false);
        hotSpotDiv.classList.add('noselect');
        hotSpotDiv.classList.add('marker_embed');
        hotSpotDiv.classList.add('marker_embed_'+id);
        hotSpotDiv.classList.add('hotspot_'+id);
        if(virtual_staging) {
            hotSpotDiv.style.zIndex = parseInt(args.zIndex)+10;
            hotSpotDiv.style.pointerEvents = 'initial';
        } else {
            hotSpotDiv.style.zIndex = args.zIndex;
        }
        if(args.css_class!='') {
            var array_css_class = args.css_class.split(" ");
            jQuery.each(array_css_class, function(index_c, css_class) {
                hotSpotDiv.classList.add(css_class);
            });
        }
        hotSpotDiv.setAttribute('data-id',id);
        hotSpotDiv.setAttribute('data-type',type);
        hotSpotDiv.setAttribute('data-transform3d',args.transform3d);
        hotSpotDiv.setAttribute('data-initialized',0);
        hotSpotDiv.setAttribute('data-tooltip_visibility',args.tooltip_visibility);
        hotSpotDiv.classList.add('custom-tooltip');
        if(hide_markers==1) {
            hotSpotDiv.classList.add('hidden_m');
        }
        hotSpotDiv.classList.add('marker_'+args.id);
        hotSpotDiv.setAttribute('data-id', args.id);
        var markers_show_room_t = parseInt(args.show_room);
        if(vr_enabled) markers_show_room_t = 0;
        if(markers_show_room_t==5) {
            if(args.tooltip_type=='preview' || args.tooltip_type=='preview_square' || args.tooltip_type=='preview_rect') {
                args.tooltip_type = 'room_name';
            }
        }
        if(list_id_visited.includes(parseInt(args.id_room_target))) {
            var display_check = 'inline-block';
        } else {
            var display_check = 'none';
        }
        switch(args.tooltip_type) {
            case 'text':
                if(window.is_mobile && (args.tooltip_text_mobile !== null && args.tooltip_text_mobile !== '' && args.tooltip_text_mobile !== '<p><br></p>')) {
                    args.tooltip_text = args.tooltip_text_mobile;
                }
                if(args.tooltip_text !== null && args.tooltip_text !== '' && args.tooltip_text !== '<p><br></p>') {
                    var tooltip = document.createElement('div');
                    tooltip.classList.add('tooltip_marker_'+args.id);
                    tooltip.classList.add('tooltip_text_embed_m');
                    tooltip.classList.add('tooltip_marker');
                    tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                    tooltip.innerHTML = args.tooltip_text+'<span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'">&nbsp;&nbsp;<i style="color:'+args.tooltip_color+'" class="fas fa-check"></i></span>';
                    hotSpotDiv.setAttribute('data-panorama','');
                    hotSpotDiv.appendChild(tooltip);
                }
                break;
            case 'room_name':
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_text_embed_m');
                tooltip.classList.add('tooltip_marker');
                tooltip.style = "background-color:"+args.tooltip_background+";color:"+args.tooltip_color;
                tooltip.innerHTML = args.name_room_target+'<span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'">&nbsp;&nbsp;<i style="color:'+args.tooltip_color+'" class="fas fa-check"></i></span>';
                hotSpotDiv.setAttribute('data-panorama','');
                hotSpotDiv.appendChild(tooltip);
                break;
            case 'preview':
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_preview_m');
                tooltip.classList.add('tooltip_marker');
                tooltip.innerHTML = '<div style="width:100%;height:100%;border-radius:50px;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;"><div id="panorama_preview_tooltip_'+args.id+'" class="panorama_preview_tooltip_m"></div><span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'"><i style="color:white" class="fas fa-check"></i></span></div>';
                hotSpotDiv.setAttribute('data-panorama',panorama_image);
                hotSpotDiv.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                hotSpotDiv.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                hotSpotDiv.setAttribute('data-haov',panoramas[index].haov);
                hotSpotDiv.setAttribute('data-vaov',panoramas[index].vaov);
                hotSpotDiv.setAttribute('data-hfov',panoramas[index].hfov);
                hotSpotDiv.appendChild(tooltip);
                break;
            case 'preview_square':
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_preview_square_m');
                tooltip.classList.add('tooltip_marker');
                tooltip.innerHTML = '<div style="width:100%;height:100%;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;"><div id="panorama_preview_tooltip_'+args.id+'" class="panorama_preview_tooltip_square_m"></div><span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'"><i style="color:white" class="fas fa-check"></i></span></div>';
                hotSpotDiv.setAttribute('data-panorama',panorama_image);
                hotSpotDiv.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                hotSpotDiv.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                hotSpotDiv.setAttribute('data-haov',panoramas[index].haov);
                hotSpotDiv.setAttribute('data-vaov',panoramas[index].vaov);
                hotSpotDiv.setAttribute('data-hfov',panoramas[index].hfov);
                hotSpotDiv.appendChild(tooltip);
                break;
            case 'preview_rect':
                var index = get_id_viewer(args.id_room_target);
                var image = panoramas[index].thumb_image;
                var panorama_image = panoramas[index].panorama_image.replace('panoramas/','');
                var tooltip = document.createElement('div');
                tooltip.classList.add('tooltip_marker_'+args.id);
                tooltip.classList.add('tooltip_preview_rect_m');
                tooltip.classList.add('tooltip_marker');
                tooltip.innerHTML = '<div style="width:100%;height:100%;background-image: url('+((window.s3_enabled) ? window.s3_url : '')+image+');background-size: cover;background-position: center;"><div id="panorama_preview_tooltip_'+args.id+'" class="panorama_preview_tooltip_rect_m"></div><span style="display: '+display_check+'" class="tooltip_visited tooltip_visited_'+args.id+'"><i style="color:white" class="fas fa-check"></i></span></div>';
                hotSpotDiv.setAttribute('data-panorama',panorama_image);
                hotSpotDiv.setAttribute('data-min_yaw',panoramas[index].min_yaw);
                hotSpotDiv.setAttribute('data-max_yaw',panoramas[index].max_yaw);
                hotSpotDiv.setAttribute('data-haov',panoramas[index].haov);
                hotSpotDiv.setAttribute('data-vaov',panoramas[index].vaov);
                hotSpotDiv.setAttribute('data-hfov',panoramas[index].hfov);
                hotSpotDiv.appendChild(tooltip);
                break;
        }
        try {
            if(controls_status['icons_nav']==false) tooltip.classList.add('hidden_icons');
        } catch (e) {}
        switch(args.tooltip_visibility) {
            case 'hover':
                hotSpotDiv.addEventListener("mouseover", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'marker_embed');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_embed_tooltip_m(id,e);
                                switch(args.embed_type) {
                                    case 'selection':
                                        if(args.embed_params=='') {
                                            $('.tooltip_marker_'+id).css('opacity',1);
                                        }
                                        break;
                                    default:
                                        $('.tooltip_marker_'+id).css('opacity',1);
                                        break;
                                }
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            switch(args.embed_type) {
                                case 'selection':
                                    if(args.embed_params=='') {
                                        $('.tooltip_marker_'+id).css('opacity',1);
                                    }
                                    break;
                                default:
                                    $('.tooltip_marker_'+id).css('opacity',1);
                                    break;
                            }
                            position_embed_tooltip_m(id,e);
                            var image = $(this).attr('data-panorama');
                            if(image!='') {
                                var min_yaw = $(this).attr('data-min_yaw');
                                var max_yaw = $(this).attr('data-max_yaw');
                                var haov = $(this).attr('data-haov');
                                var vaov = $(this).attr('data-vaov');
                                var hfov = $(this).attr('data-hfov');
                                clearTimeout(timeout_destroy_tooltip);
                                initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            switch(args.embed_type) {
                                case 'selection':
                                    if(args.embed_params=='') {
                                        $('.tooltip_marker_'+id).css('opacity',0);
                                    }
                                    break;
                                default:
                                    $('.tooltip_marker_'+id).css('opacity',0);
                                    break;
                            }
                            $('.panorama_preview_tooltip').css('opacity', 0);
                            $('.panorama_preview_tooltip_square').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect').css('opacity', 0);
                            $('.panorama_preview_tooltip_m').css('opacity',0);
                            $('.panorama_preview_tooltip_square_m').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
                            timeout_destroy_tooltip = setTimeout(function () {
                                try {
                                    panorama_preview_tooltip.destroy();
                                } catch (e) {}
                            }, 300);
                        }
                    }
                });
                hotSpotDiv.addEventListener("mousemove", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var target = findAncestor(e.target,'marker_embed');
                        if(target!=null) {
                            var id = target.getAttribute('data-id');
                            if(id !== null) {
                                position_embed_tooltip_m(id,e);
                            }
                        }
                    }
                });
                break;
            case 'visible':
                $('.tooltip_marker_'+args.id).css('opacity',1);
                hotSpotDiv.addEventListener("mouseenter", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            var image = $(this).attr('data-panorama');
                            if(image!='') {
                                var min_yaw = $(this).attr('data-min_yaw');
                                var max_yaw = $(this).attr('data-max_yaw');
                                var haov = $(this).attr('data-haov');
                                var vaov = $(this).attr('data-vaov');
                                var hfov = $(this).attr('data-hfov');
                                clearTimeout(timeout_destroy_tooltip);
                                initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                            }
                        }
                    }
                });
                hotSpotDiv.addEventListener("mouseleave", function (e) {
                    if(controls_status['icons_nav']==true && !window.is_mobile) {
                        var id = e.target.getAttribute('data-id');
                        if(id !== null) {
                            $('.panorama_preview_tooltip').css('opacity', 0);
                            $('.panorama_preview_tooltip_square').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect').css('opacity', 0);
                            $('.panorama_preview_tooltip_m').css('opacity',0);
                            $('.panorama_preview_tooltip_square_m').css('opacity', 0);
                            $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
                            timeout_destroy_tooltip = setTimeout(function () {
                                try {
                                    panorama_preview_tooltip.destroy();
                                } catch (e) {}
                            }, 300);
                        }
                    }
                });
                break;
            case 'visible_mobile':
                if(window.is_mobile) {
                    $('.tooltip_marker_'+args.id).css('opacity',1);
                } else {
                    hotSpotDiv.addEventListener("mouseover", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'marker_embed');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_embed_tooltip_m(id,e);
                                    switch(args.embed_type) {
                                        case 'selection':
                                            if(args.embed_params=='') {
                                                $('.tooltip_marker_'+id).css('opacity',1);
                                            }
                                            break;
                                        default:
                                            $('.tooltip_marker_'+id).css('opacity',1);
                                            break;
                                    }
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseenter", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                switch(args.embed_type) {
                                    case 'selection':
                                        if(args.embed_params=='') {
                                            $('.tooltip_marker_'+id).css('opacity',1);
                                        }
                                        break;
                                    default:
                                        $('.tooltip_marker_'+id).css('opacity',1);
                                        break;
                                }
                                position_embed_tooltip_m(id,e);
                                var image = $(this).attr('data-panorama');
                                if(image!='') {
                                    var min_yaw = $(this).attr('data-min_yaw');
                                    var max_yaw = $(this).attr('data-max_yaw');
                                    var haov = $(this).attr('data-haov');
                                    var vaov = $(this).attr('data-vaov');
                                    var hfov = $(this).attr('data-hfov');
                                    clearTimeout(timeout_destroy_tooltip);
                                    initialize_panorama_preview_tooltip(id,image,min_yaw,max_yaw,haov,vaov,hfov);
                                }
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mouseleave", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var id = e.target.getAttribute('data-id');
                            if(id !== null) {
                                switch(args.embed_type) {
                                    case 'selection':
                                        if(args.embed_params=='') {
                                            $('.tooltip_marker_'+id).css('opacity',0);
                                        }
                                        break;
                                    default:
                                        $('.tooltip_marker_'+id).css('opacity',0);
                                        break;
                                }
                                $('.panorama_preview_tooltip').css('opacity', 0);
                                $('.panorama_preview_tooltip_square').css('opacity', 0);
                                $('.panorama_preview_tooltip_rect').css('opacity', 0);
                                $('.panorama_preview_tooltip_m').css('opacity',0);
                                $('.panorama_preview_tooltip_square_m').css('opacity', 0);
                                $('.panorama_preview_tooltip_rect_m').css('opacity', 0);
                                timeout_destroy_tooltip = setTimeout(function () {
                                    try {
                                        panorama_preview_tooltip.destroy();
                                    } catch (e) {}
                                }, 300);
                            }
                        }
                    });
                    hotSpotDiv.addEventListener("mousemove", function (e) {
                        if(controls_status['icons_nav']==true && !window.is_mobile) {
                            var target = findAncestor(e.target,'marker_embed');
                            if(target!=null) {
                                var id = target.getAttribute('data-id');
                                if(id !== null) {
                                    position_embed_tooltip_m(id,e);
                                }
                            }
                        }
                    });
                }
                break;
        }
        switch(type) {
            case 'selection':
                var div = document.createElement('div');
                div.setAttribute('draggable',false);
                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:none;";
                } else {
                    div.style = "width:"+width+";height:"+height+";margin: 0 auto;vertical-align:middle;opacity:0;background-color:"+bg_color+";border-color:"+color+";-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;"+args.embed_content;
                }
                div.id = "marker_embed_selection_"+args.id;
                div.classList.add('marker_embed_selection');
                div.setAttribute('data-id',args.id);
                if(args.embed_params!='') {
                    var canvas = document.createElement('canvas');
                    canvas.id = 'canvas_selection_'+args.id;
                    canvas.width = width.replace('px','');
                    canvas.height = height.replace('px','');
                    div.appendChild(canvas);
                }
                if(args.embed_params!='') {
                    canvas.addEventListener("click", function (e) {
                        var diff_drag = end_drag - start_drag;
                        if(drag_p == false || diff_drag < 200) {
                            var points = JSON.parse(args.embed_params);
                            var pol = new Path2D();
                            for (const p of points) { pol.lineTo(p.x, p.y) }
                            pol.closePath();
                            var canvas = document.getElementById('canvas_selection_'+id);
                            var ctx = canvas.getContext('2d');
                            if (ctx.isPointInPath(pol, e.offsetX, e.offsetY)) {
                                goto('',[args.id_room_target,parseInt(args.pitch),parseInt(args.yaw),args.pitch_room_target,args.yaw_room_target,null,parseInt(args.lookat),args.sound]);
                            }
                        }
                    });
                    canvas.addEventListener("mousedown", function (e) {
                        start_drag = new Date().getTime();
                        drag_p = false;
                    });
                    canvas.addEventListener("mousemove", function (e) {
                        end_drag = new Date().getTime();
                        drag_p = true;
                        var points = JSON.parse(args.embed_params);
                        var pol = new Path2D();
                        for (const p of points) { pol.lineTo(p.x, p.y) }
                        pol.closePath();
                        var canvas = document.getElementById('canvas_selection_'+id);
                        var ctx = canvas.getContext('2d');
                        if (ctx.isPointInPath(pol, e.offsetX, e.offsetY)) {
                            if(args.type!='' && args.type!=null) {
                                $('#marker_embed_selection_'+args.id).css('cursor','pointer');
                                $('#canvas_selection_'+args.id).css('cursor','pointer');
                                $('.marker_embed_'+args.id).css('cursor','pointer');
                            }
                            $('.tooltip_marker_'+args.id).css('opacity',1);
                            draw_polygon(canvas,points,border,bg_color,color,true);
                        } else {
                            $('#marker_embed_selection_'+args.id).css('cursor','unset');
                            $('#canvas_selection_'+args.id).css('cursor','unset');
                            $('.marker_embed_'+args.id).css('cursor','unset');
                            $('.tooltip_marker_'+args.id).css('opacity',0);
                            draw_polygon(canvas,points,border,bg_color,color,false);
                        }
                    });
                    canvas.addEventListener("mouseleave", function (e) {
                        var points = JSON.parse(args.embed_params);
                        var canvas = document.getElementById('canvas_selection_'+id);
                        $('#marker_embed_selection_'+args.id).css('cursor','unset');
                        $('#canvas_selection_'+args.id).css('cursor','unset');
                        $('.marker_embed_'+args.id).css('cursor','unset');
                        $('.tooltip_marker_'+args.id).css('opacity',0);
                        draw_polygon(canvas,points,border,bg_color,color,false);
                    });
                } else {
                    div.addEventListener("mouseover", function (e) {
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('-webkit-box-shadow','0 0 20px '+color);
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('-moz-box-shadow','0 0 20px '+color);
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('box-shadow','0 0 20px '+color);
                    });
                    div.addEventListener("mouseenter", function (e) {
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('-webkit-box-shadow','0 0 20px '+color);
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('-moz-box-shadow','0 0 20px '+color);
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('box-shadow','0 0 20px '+color);
                    });
                    div.addEventListener("mouseleave", function (e) {
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('-webkit-box-shadow','none');
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('-moz-box-shadow','none');
                        $('#marker_embed_selection_'+e.target.getAttribute('data-id')).css('box-shadow','none');
                    });
                }
                hotSpotDiv.appendChild(div);
                break;
        }
        if(type=='selection' && 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,points,border,bg_color,color,false);
            } catch (e) {}
        }
    }

    function supportsHEVCAlpha() {
        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 _checkAutoPlay(p,id) {
        var s = window['Promise'] ? window['Promise'].toString() : '';
        if (s.indexOf('function Promise()') !== -1 || s.indexOf('function ZoneAwarePromise()') !== -1) {
            p.catch(function() {
                _callback_onAutoplayBlocked(id);
                return;
            });
            if(id=='video_avatar') {
                avatar_video_playing = true;
                if(controls_status['song']) {
                    fadeVolume(audio_player, song_bg_volume_sel/3, 500);
                    var index_panorama = get_id_viewer(current_id_panorama);
                    fadeVolume(audio_player_room, panoramas[index_panorama].song_volume/3, 500);
                    try {
                        var video_elem = document.getElementById('video_viewer_html5_api');
                        fadeVolume(video_elem, 0.3, 500);
                    } catch (e) {}
                    try {
                        fadeVolume(video_p, 0.3, 500);
                    } catch (e) {}
                }
            }
        }
    }

    function _callback_onAutoplayBlocked(id) {
        if(id=='video_avatar') {
            $('.avatar_video .div_play_btn').show();
            $(document).one("mousedown touchstart",function(e){
                if($('.avatar_video').is(':visible')) {
                    var video = $('.avatar_video video')[0];
                    if (video.paused && !video.ended) {
                        var playPromise = video.play();
                        if (playPromise !== undefined) {
                            playPromise.then(() => {
                                $('.avatar_video .div_play_btn').hide();
                                avatar_video_playing = true;
                                if(controls_status['song']) {
                                    fadeVolume(audio_player, song_bg_volume_sel/3, 500);
                                    var index_panorama = get_id_viewer(current_id_panorama);
                                    fadeVolume(audio_player_room, panoramas[index_panorama].song_volume/3, 500);
                                    try {
                                        var video_elem = document.getElementById('video_viewer_html5_api');
                                        fadeVolume(video_elem, 0.3, 500);
                                    } catch (e) {}
                                    try {
                                        fadeVolume(video_p, 0.3, 500);
                                    } catch (e) {}
                                }
                            }).catch(error => {});
                        }
                    }
                }
            });
        } else {
            $('.poi_embed_'+id).css('pointer-events','none');
            $('#video_embed_'+id).css('pointer-events','none');
            $('#canvas_chroma_'+id).css('pointer-events','none');
            $('.poi_embed_'+id+' .div_play_btn').show();
        }
    }

    window.play_video_transparent = function (id) {
        if(id=='video_avatar') {
            var video = $('.avatar_video video')[0];
            video.play();
            $('.avatar_video .div_play_btn').hide();
            avatar_video_playing = true;
            if(controls_status['song']) {
                fadeVolume(audio_player, song_bg_volume_sel/3, 500);
                var index_panorama = get_id_viewer(current_id_panorama);
                fadeVolume(audio_player_room, panoramas[index_panorama].song_volume/3, 500);
                try {
                    var video_elem = document.getElementById('video_viewer_html5_api');
                    fadeVolume(video_elem, 0.3, 500);
                } catch (e) {}
                try {
                    fadeVolume(video_p, 0.3, 500);
                } catch (e) {}
            }
        } else {
            var video = $('.poi_embed_'+id+' video')[0];
            video.play();
            $('.poi_embed_'+id+' .div_play_btn').hide();
            var tooltip_visibility = $('.poi_embed_'+id).attr('data-tooltip_visibility');
            if(tooltip_visibility=='hover') {
                $('.tooltip_poi_embed_'+id).css('opacity',0);
            }
        }
    }

    window.pause_avatar_video = function () {
        var video = $('.avatar_video video')[0];
        video.pause();
        avatar_video_playing = false;
        if(controls_status['song']) {
            fadeVolume(audio_player, song_bg_volume_sel, 500);
            var index_panorama = get_id_viewer(current_id_panorama);
            fadeVolume(audio_player_room, panoramas[index_panorama].song_volume, 500);
            try {
                var video_elem = document.getElementById('video_viewer_html5_api');
                fadeVolume(video_elem, 1, 500);
            } catch (e) {}
            try {
                fadeVolume(video_p, 1, 500);
            } catch (e) {}
        }
        $('.avatar_video .div_pause_btn').hide();
        $('.avatar_video .div_play_btn').show();
    }

    function hotspot_embed_helper(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_helper_m(hotSpotDiv, args) {
        if(vr_enabled) {
            return;
        }
        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.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(id_p, 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.marker_embed_apply_transform = function(id_m, 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) {
        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('#draggable_container').position({
                        at: position,
                        of: element,
                        collision: 'none'
                    }));
                }
                return results;
            })();
            if(window.is_mobile) {
                var offset_fix = 3;
            } else {
                var offset_fix = 0;
            }
            originalPos = (function() {
                var k, len, results;
                results = [];
                for (k = 0, len = controlPoints.length; k < len; k++) {
                    p = controlPoints[k];
                    results.push([p.position().left+offset_fix, p.position().top+offset_fix]);
                }
                return results;
            })();
            poi_embed_originals_pos[id] = originalPos;
            return element;
        });
    };

    window.marker_embed_make_transformable = function(selector, id, callback) {
        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('#draggable_container').position({
                        at: position,
                        of: element,
                        collision: 'none'
                    }));
                }
                return results;
            })();
            if(window.is_mobile) {
                var offset_fix = 3;
            } else {
                var offset_fix = 0;
            }
            originalPos = (function() {
                var k, len, results;
                results = [];
                for (k = 0, len = controlPoints.length; k < len; k++) {
                    p = controlPoints[k];
                    results.push([p.position().left+offset_fix, p.position().top+offset_fix]);
                }
                return results;
            })();
            marker_embed_originals_pos[id] = originalPos;
            return element;
        });
    };

    window.addEventListener("message", api_message, false);

    function api_message(evt) {
        switch(evt.data.payload) {
            case 'goto_room':
                var id = evt.data.id_room;
                goto('',[id,null,null,null,null,null,null,null]);
                break;
            case 'goto_next_room':
                goto_next_room();
                break;
            case 'goto_prev_room':
                goto_prev_room();
                break;
            case 'goto_room_coordinates':
                var coordinates = evt.data.coordinates;
                var lat = coordinates[0];
                var lon = coordinates[1];
                goto_room_coordinates(lat,lon,true);
                break;
        }
    }

    function goto_room_coordinates(lat,lon,api) {
        var min_distance = 99999999;
        var index_panorama = null;
        if(lat!=null && lat.length>0 && lon!=null && lon.length>0) {
            lat = lat.replace(/,/g, '.');
            lon = lon.replace(/,/g, '.');
            lat = parseFloat(lat);
            lon = parseFloat(lon);
            jQuery.each(panoramas, function(index, panorama) {
                var lat_p = panorama.lat;
                var lon_p = panorama.lon;
                if(lat_p!=null && lat_p.length>0 && lon_p!=null && lon_p.length>0) {
                    lat_p = parseFloat(lat_p);
                    lon_p = parseFloat(lon_p);
                    var distance = getDistanceFromLatLonInKm(lat,lon,lat_p,lon_p);
                    if(distance<=min_distance) {
                        min_distance = distance;
                        index_panorama = index;
                    }
                }
            });
        }
        if(index_panorama!=null) {
            if(api) {
                goto('',[panoramas[index_panorama].id,null,null,null,null,null,null,null]);
            } else {
                return index_panorama;
            }
        } else {
            if(api) {
                goto('',[panoramas[index_initial].id,null,null,null,null,null,null,null]);
            } else {
                return false;
            }
        }
    }

    function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
        var R = 6371;
        var dLat = deg2rad(lat2-lat1);
        var dLon = deg2rad(lon2-lon1);
        var a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
            Math.sin(dLon/2) * Math.sin(dLon/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        return d;
    }

    function deg2rad(deg) {
        return deg * (Math.PI/180);
    }

    window.nav_control_cmd = function (cmd) {
        window.viewer_mov_follow_mouse = false;
        window.viewer_mov_pos_change = false;
        switch (cmd) {
            case 'up':
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw_s = pano_viewer.getYaw();
                    var pitch_s = pano_viewer.getPitch();
                    var hfov_s = pano_viewer.getHfov();
                    pitch_s = pitch_s + 20;
                    pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                } else {
                    var yaw_s = video_viewer.pnlmViewer.getYaw();
                    var pitch_s = video_viewer.pnlmViewer.getPitch();
                    var hfov_s = video_viewer.pnlmViewer.getHfov();
                    pitch_s = pitch_s + 20;
                    video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                }
                break;
            case 'down':
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw_s = pano_viewer.getYaw();
                    var pitch_s = pano_viewer.getPitch();
                    var hfov_s = pano_viewer.getHfov();
                    pitch_s = pitch_s - 20;
                    pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                } else {
                    var yaw_s = video_viewer.pnlmViewer.getYaw();
                    var pitch_s = video_viewer.pnlmViewer.getPitch();
                    var hfov_s = video_viewer.pnlmViewer.getHfov();
                    pitch_s = pitch_s - 20;
                    video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                }
                break;
            case 'left':
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw_s = pano_viewer.getYaw();
                    var pitch_s = pano_viewer.getPitch();
                    var hfov_s = pano_viewer.getHfov();
                    yaw_s = yaw_s - 20;
                    pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                } else {
                    var yaw_s = video_viewer.pnlmViewer.getYaw();
                    var pitch_s = video_viewer.pnlmViewer.getPitch();
                    var hfov_s = video_viewer.pnlmViewer.getHfov();
                    yaw_s = yaw_s - 20;
                    video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                }
                break;
            case 'right':
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var yaw_s = pano_viewer.getYaw();
                    var pitch_s = pano_viewer.getPitch();
                    var hfov_s = pano_viewer.getHfov();
                    yaw_s = yaw_s + 20;
                    pano_viewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                } else {
                    var yaw_s = video_viewer.pnlmViewer.getYaw();
                    var pitch_s = video_viewer.pnlmViewer.getPitch();
                    var hfov_s = video_viewer.pnlmViewer.getHfov();
                    yaw_s = yaw_s + 20;
                    video_viewer.pnlmViewer.lookAt(pitch_s,yaw_s,hfov_s,500,function() {
                        window.viewer_mov_pos_change = true;
                        current_viewer_pitch = pitch_s;
                        current_viewer_yaw = yaw_s;
                        if(mouse_follow_feedback!=0) {
                            window.viewer_mov_follow_mouse = true;
                        }
                    });
                }
                break;
            case 'rotate':
                if($('.nav_rotate').hasClass('active_rotate')) {
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        try { pano_viewer.stopAutoRotate(); } catch (e) {}
                    } else {
                        try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
                    }
                    $('.nav_rotate').removeClass('active_rotate');
                    $('.autorotate_control').removeClass('active_control');
                    $('.autorotate_control .fa-circle').removeClass('active').addClass('not_active');
                    controls_status['auto_rotate']=false;
                } else {
                    if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                        pano_viewer.setAutoRotateInactivityDelay(autorotate_inactivity);
                        pano_viewer.startAutoRotate();
                    } else {
                        video_viewer.pnlmViewer.setAutoRotateInactivityDelay(autorotate_inactivity);
                        video_viewer.pnlmViewer.startAutoRotate();
                    }
                    $('.nav_rotate').addClass('active_rotate');
                    $('.autorotate_control').addClass('active_control');
                    $('.autorotate_control .fa-circle').removeClass('not_active').addClass('active');
                    controls_status['auto_rotate']=true;
                }
                break;
        }
    }

    function idleTimeout() {
        var t;
        window.onload = resetTimer;
        window.onmousemove = resetTimer;
        window.onmousedown = resetTimer;
        window.ontouchstart = resetTimer;
        window.ontouchmove = resetTimer;
        window.onclick = resetTimer;
        window.onkeydown = resetTimer;
        window.addEventListener('scroll', resetTimer, true);
        function timeout_elapsed() {
            in_idle=true;
        }
        function resetTimer() {
            in_idle=false;
            clearTimeout(t);
            t = setTimeout(timeout_elapsed, 300000);
        }
    }

    window.fix_colors_menu = function() {
        var first = null;
        var last = null;
        $('.menu_controls').find("p:not(.hidden)").sort(function(a, b) {
            return parseInt(a.style.order) > parseInt(b.style.order) ? 1 : -1;
        }).each(function () {
            if(first==null) {
                first=$(this);
            }
            last=$(this);
        });
        if(first!=null) {
            var bg_first = first.css('background-color');
            $('.menu_controls .arrow').css('border-bottom','10px solid '+bg_first);
            $('#menu_controls_mt').css('background-color',bg_first);
        }
        if(last!=null) {
            var bg_last = last.css('background-color');
            $('#menu_controls_md').css('background-color',bg_last);
        }
    }

    var computeGroupCenter_dollhouse;
    function init_dollhouse() {
        computeGroupCenter_dollhouse = (function () {
            var childBox = new THREE.Box3();
            var groupBox = new THREE.Box3();
            var invMatrixWorld = new THREE.Matrix4();
            return function (group, optionalTarget) {
                for(var i=0; i<group.length; i++) {
                    if (!optionalTarget) optionalTarget = new THREE.Vector3();
                    group[i].traverse(function (child) {
                        if (child instanceof THREE.Mesh) {
                            if (!child.geometry.boundingBox) {
                                child.geometry.computeBoundingBox();
                                childBox.copy(child.geometry.boundingBox);
                                child.updateMatrixWorld(true);
                                childBox.applyMatrix4(child.matrixWorld);
                                groupBox.min.min(childBox.min);
                                groupBox.max.max(childBox.max);
                            }
                        }
                    });
                    invMatrixWorld.copy(group[i].matrixWorld).invert();
                    groupBox.applyMatrix4(invMatrixWorld);
                    groupBox.getCenter(optionalTarget);
                }
                return optionalTarget;
            }
        })();
        array_dollhouse = JSON.parse(json_dollhouse);
        camera_pos_dollhouse = array_dollhouse.camera;
        if(dollhouse_glb!='') {
            rooms_dollhouse = [];
            levels_dollhouse = [];
        } else {
            rooms_dollhouse = array_dollhouse.rooms;
            levels_dollhouse = array_dollhouse.levels;
        }
        var array_levels_used = [], count_levels_used = 0;
        for(var i=0;i<rooms_dollhouse.length; i++) {
            var level = rooms_dollhouse[i].level;
            if(!array_levels_used.includes(level)) {
                array_levels_used.push(level);
                count_levels_used++;
            }
            if(rooms_dollhouse[i].pointer_visible === undefined) {
                rooms_dollhouse[i].pointer_visible=true;
            }
            if(rooms_dollhouse[i].cube_face_top === undefined) {
                rooms_dollhouse[i].cube_face_top=true;
            }
            if(rooms_dollhouse[i].cube_face_bottom === undefined) {
                rooms_dollhouse[i].cube_face_bottom=true;
            }
            if(rooms_dollhouse[i].cube_face_left === undefined) {
                rooms_dollhouse[i].cube_face_left=true;
            }
            if(rooms_dollhouse[i].cube_face_right === undefined) {
                rooms_dollhouse[i].cube_face_right=true;
            }
            if(rooms_dollhouse[i].cube_face_front === undefined) {
                rooms_dollhouse[i].cube_face_front=true;
            }
            if(rooms_dollhouse[i].cube_face_back === undefined) {
                rooms_dollhouse[i].cube_face_back=true;
            }
        }
        if(array_dollhouse.settings.level_measures === undefined) {
            array_dollhouse.settings.level_measures = 'm';
        }
        if(count_levels_used>0) {
            var level_measure_label = ['','','','','',''];
            if(array_dollhouse.settings.level_measures!='') {
                var total_measure = 0;
                var level_measure = [0,0,0,0,0,0];
                for(var i=0; i<rooms_dollhouse.length; i++) {
                    var level = rooms_dollhouse[i].level;
                    var cube_width = rooms_dollhouse[i].cube_width;
                    var cube_depth = rooms_dollhouse[i].cube_depth;
                    switch(array_dollhouse.settings.level_measures) {
                        case 'm':
                            var cube_m2 = (cube_width/100)*(cube_depth/100);
                            level_measure[level] = level_measure[level] + cube_m2;
                            total_measure = total_measure + cube_m2;
                            break;
                        case 'ft':
                            var cube_ft2 = ((cube_width/100)*3.2808)*((cube_depth/100)*3.2808);
                            level_measure[level] = level_measure[level] + cube_ft2;
                            total_measure = total_measure + cube_ft2;
                            break;
                    }
                }
                total_measure = total_measure.toFixed(2);
                level_measure[0] = level_measure[0].toFixed(2);
                level_measure[1] = level_measure[1].toFixed(2);
                level_measure[2] = level_measure[2].toFixed(2);
                level_measure[3] = level_measure[3].toFixed(2);
                level_measure[4] = level_measure[4].toFixed(2);
                level_measure[5] = level_measure[5].toFixed(2);
                switch(array_dollhouse.settings.level_measures) {
                    case 'm':
                        total_measure_label = '&nbsp;&nbsp;<span>'+total_measure+' m<sup>2</sup></span>';
                        level_measure_label[0] = '&nbsp;&nbsp;<span>'+level_measure[0]+' m<sup>2</sup></span>';
                        level_measure_label[1] = '&nbsp;&nbsp;<span>'+level_measure[1]+' m<sup>2</sup></span>';
                        level_measure_label[2] = '&nbsp;&nbsp;<span>'+level_measure[2]+' m<sup>2</sup></span>';
                        level_measure_label[3] = '&nbsp;&nbsp;<span>'+level_measure[3]+' m<sup>2</sup></span>';
                        level_measure_label[4] = '&nbsp;&nbsp;<span>'+level_measure[4]+' m<sup>2</sup></span>';
                        level_measure_label[5] = '&nbsp;&nbsp;<span>'+level_measure[5]+' m<sup>2</sup></span>';
                        break;
                    case 'ft':
                        total_measure_label = '&nbsp;&nbsp;<span>'+total_measure+' ft<sup>2</sup></span>';
                        level_measure_label[0] = '&nbsp;&nbsp;<span>'+level_measure[0]+' ft<sup>2</sup></span>';
                        level_measure_label[1] = '&nbsp;&nbsp;<span>'+level_measure[1]+' ft<sup>2</sup></span>';
                        level_measure_label[2] = '&nbsp;&nbsp;<span>'+level_measure[2]+' ft<sup>2</sup></span>';
                        level_measure_label[3] = '&nbsp;&nbsp;<span>'+level_measure[3]+' ft<sup>2</sup></span>';
                        level_measure_label[4] = '&nbsp;&nbsp;<span>'+level_measure[4]+' ft<sup>2</sup></span>';
                        level_measure_label[5] = '&nbsp;&nbsp;<span>'+level_measure[5]+' ft<sup>2</sup></span>';
                        break;
                }
            }
            var levels_html = '<ul>';
            if(count_levels_used==1) {
                $('#button_level_dollhouse').css('pointer-events','none');
                levels_html += '<li><a href="#">'+total_measure_label+'</a></li>';
            } else {
                levels_html += '<li><a onclick="select_level_dollhouse(\'all\',\''+window.viewer_labels.all+total_measure_label+'\','+count_levels_used+');return false;" href="#">'+window.viewer_labels.all+total_measure_label+'</a></li>';
            }
            if(count_levels_used>1) {
                for(var i=0;i<levels_dollhouse.length;i++) {
                    var id = levels_dollhouse[i].id;
                    if(array_levels_used.includes(id)) {
                        var name = levels_dollhouse[i].name;
                        levels_html += '<li><a onclick="select_level_dollhouse(\''+id+'\',\''+name+level_measure_label[i]+'\','+count_levels_used+');return false;" href="#">'+name+level_measure_label[i]+'</a></li>';
                    }
                }
            }
            levels_html += '</ul>';
            document.getElementById('select_level_dollhouse').innerHTML = levels_html;
        } else {
            $('#button_level_dollhouse').addClass('hidden');
        }
        dollhouse_div = document.getElementById('dollhouse');
        var container_dollhouse = document.getElementById('container_dollhouse');
        container_dollhouse.style.display = 'none';
        camera_dollhouse = new THREE.PerspectiveCamera( 75, dollhouse_div.offsetWidth / dollhouse_div.offsetHeight, 5, 100000 );
        camera_dollhouse.position.z = 500;
        camera_dollhouse.position.y = 1200;
        scene_dollhouse = new THREE.Scene();
        renderer_dollhouse = new THREE.WebGLRenderer({
            alpha: true,
            antialias: true
        });
        var background_color = Number("0x"+array_dollhouse.settings.background_color);
        var background_opacity = array_dollhouse.settings.background_opacity;
        if(array_dollhouse.settings.autorotate_speed === undefined) {
            array_dollhouse.settings.autorotate_speed = 0.5;
        }
        if(array_dollhouse.settings.autorotate_inactivity === undefined) {
            array_dollhouse.settings.autorotate_inactivity = 3000;
        }
        if(array_dollhouse.settings.measures === undefined) {
            array_dollhouse.settings.measures = 'm';
        }
        renderer_dollhouse.setClearColor(new THREE.Color(background_color));
        renderer_dollhouse.setClearAlpha(background_opacity);
        renderer_dollhouse.setPixelRatio(1);
        renderer_dollhouse.setSize( dollhouse_div.offsetWidth, dollhouse_div.offsetHeight );
        container_dollhouse.appendChild( renderer_dollhouse.domElement );
        controls_dollhouse = new THREE.OrbitControls(camera_dollhouse, renderer_dollhouse.domElement);
        controls_dollhouse.enableDamping = true;
        controls_dollhouse.dampingFactor = 0.1;
        controls_dollhouse.minDistance = 100;
        controls_dollhouse.maxDistance = 5000;
        controls_dollhouse.autoRotate = false;
        controls_dollhouse.autoRotateSpeed = array_dollhouse.settings.autorotate_speed;
        if(array_dollhouse.settings.autorotate_speed!=0) {
            controls_dollhouse.addEventListener('start', function(){
                clearTimeout(dollhouse_autorotate_timeout);
                controls_dollhouse.autoRotate = false;
            });
            controls_dollhouse.addEventListener('end', function(){
                clearTimeout(dollhouse_autorotate_timeout);
                dollhouse_autorotate_timeout = setTimeout(function(){
                    controls_dollhouse.autoRotate = true;
                }, array_dollhouse.settings.autorotate_inactivity);
            });
        }
        domEvents_dollhouse = new THREEx.DomEvents(camera_dollhouse, renderer_dollhouse.domElement);
        window.addEventListener( 'resize', onWindowResize_dollhouse, false );
        loading_dollhouse();
        animate_dollhouse();
    }

    window.toggle_dollhouse_help = function() {
        if(window.is_mobile) {
            if($('#info_dollhouse_mobile').is(':visible')) {
                $('#info_dollhouse_mobile').fadeOut();
            } else {
                $('#info_dollhouse_mobile').fadeIn();
            }
        } else {
            if($('#info_dollhouse_pc').is(':visible')) {
                $('#info_dollhouse_pc').fadeOut();
            } else {
                $('#info_dollhouse_pc').fadeIn();
            }
        }
    }

    function loading_dollhouse() {
        $('#progress_msg span').html(window.viewer_labels.progress_dollhouse);
        if(dollhouse_glb!='') {
            const ambientLight = new THREE.AmbientLight(0xFFFFFF);
            ambientLight.intensity = 2;
            scene_dollhouse.add( ambientLight );
            renderer_dollhouse.physicallyCorrectLights = true;
            renderer_dollhouse.gammaOutput = true;
            renderer_dollhouse.outputColorSpace = THREE.SRGBColorSpace;
            load_dollhouse_glb(((window.s3_enabled) ? window.s3_url : '')+'content/'+dollhouse_glb);
        } else {
            for(var i=0;i<rooms_dollhouse.length;i++) {
                var id_room = rooms_dollhouse[i].id;
                var index = get_id_viewer(id_room);
                if(index==null) {
                    if(step_progress>=1.0) {
                        step_progress=1.0;
                    }
                    progress_circle.animate(step_progress);
                    step_progress = step_progress + 0.01;
                    count_loaded_texture_dollhouse++;
                } else {
                    var panorama_image = panoramas[index].panorama_3d;
                    textures_dollhouse[i] = new THREE.TextureLoader().load( ((window.s3_enabled) ? window.s3_url : '')+panorama_image, function () {
                        if(step_progress>=1.0) {
                            step_progress=1.0;
                        }
                        progress_circle.animate(step_progress);
                        step_progress = step_progress + 0.01;
                        count_loaded_texture_dollhouse++;
                    });
                }
            }
            interval_load_texture_dollhouse = setInterval(function () {
                if(count_loaded_texture_dollhouse>=rooms_dollhouse.length) {
                    clearInterval(interval_load_texture_dollhouse);
                    setTimeout(function() {
                        finish_init_dollhouse();
                    },500);
                }
            },100);
        }
    }

    function load_dollhouse_glb(glb_file) {
        const loader = new THREE.GLTFLoader();

        const onLoad = (gltf) => {
            const model = gltf.scene;
            model.scale.set(100, 100, 100);
            gltf.scene.children.forEach((child) => {
                child.traverse((n) => {
                    if(n.userData.id_room!==undefined) {
                        var id_room = parseInt(n.userData.id_room);
                        var index_panorama = get_id_viewer(id_room);
                        if(index_panorama!==null) {
                            var room_tmp = [];
                            room_tmp.id = id_room;
                            room_tmp.level = 0;
                            room_tmp.cube_width = 0;
                            room_tmp.cube_height = 0;
                            room_tmp.cube_depth = 0;
                            var yaw = panoramas[index_panorama].yaw;
                            room_tmp.rotation = yaw + ((n.rotation.y*(180/Math.PI)) % 360) + 90;
                            room_tmp.x_pos = n.position.x*100;
                            room_tmp.y_pos = n.position.y*100;
                            room_tmp.z_pos = n.position.z*100;
                            room_tmp.pointer_offset_x = 0;
                            room_tmp.pointer_offset_y = 0;
                            room_tmp.yaw = 0;
                            rooms_dollhouse.push(room_tmp);
                            create_pointer_dollhouse(id_room,n.position.x*100,n.position.y*100,n.position.z*100,0,0,room_tmp.rotation,0,0,true);
                        }
                    }
                });
            });
            scene_dollhouse.add(model);
            setTimeout(function() {
                finish_init_dollhouse();
            },500);
        };

        const onProgress = progress => {};

        loader.load(
            glb_file,
            gltf => onLoad(gltf),
            onProgress
        );
    }

    function finish_init_dollhouse() {
        if(dollhouse_glb=='') {
            for(var i=0; i<=5; i++) {
                if( group_rooms_dollhouse[i] === undefined ) {
                    group_rooms_dollhouse[i] = new THREE.Group();
                }
            }
            for(var i=0;i<rooms_dollhouse.length;i++) {
                draw_room_dollhouse(i);
            }
        }
        for(var i=0; i<group_rooms_dollhouse.length; i++) {
            scene_dollhouse.add(group_rooms_dollhouse[i]);
        }
        if(camera_pos_dollhouse!='' && camera_pos_dollhouse!==undefined) {
            camera_dollhouse.position.copy(camera_pos_dollhouse.cameraPosition);
            controls_dollhouse.target.copy(camera_pos_dollhouse.targetPosition);
        } else {
            if(dollhouse_glb!='') {
                controls_dollhouse.target.set(0, 0, 0);
            } else {
                var center = computeGroupCenter_dollhouse(group_rooms_dollhouse);
                controls_dollhouse.target.set(center.x, center.y, center.z);
            }
        }
        var container_dollhouse = document.getElementById('container_dollhouse');
        container_dollhouse.addEventListener('mousemove', onDocumentMouseMove_pointer_dollhouse, false );
        document.getElementById('button_level_dollhouse').style.display = 'block';
        $('.dollhouse_control').removeClass('disabled');
        set_dollhouse_position(current_id_panorama);
        setTimeout(function () {
            dollhouse_loaded = true;
        },5000);
        initialize();
    }

    function setOpacity_group_dollhouse(group,level,opacity) {
        group[level].children.forEach(function(child){
            if(child.userData.type=='room') {
                if(rooms_dollhouse[child.userData.index].cube_face_front) {
                    child.material[0].opacity = opacity;
                } else {
                    child.material[0].opacity = 0;
                }
                if(rooms_dollhouse[child.userData.index].cube_face_back) {
                    child.material[1].opacity = opacity;
                } else {
                    child.material[1].opacity = 0;
                }
                if(rooms_dollhouse[child.userData.index].cube_face_top) {
                    child.material[2].opacity = opacity;
                } else {
                    child.material[2].opacity = 0;
                }
                if(rooms_dollhouse[child.userData.index].cube_face_bottom) {
                    child.material[3].opacity = opacity;
                } else {
                    child.material[3].opacity = 0;
                }
                if(rooms_dollhouse[child.userData.index].cube_face_left) {
                    child.material[4].opacity = opacity;
                } else {
                    child.material[4].opacity = 0;
                }
                if(rooms_dollhouse[child.userData.index].cube_face_right) {
                    child.material[5].opacity = opacity;
                } else {
                    child.material[5].opacity = 0;
                }
                if(opacity<1) {
                    child.material[0].depthWrite = false;
                    child.material[1].depthWrite = false;
                    child.material[2].depthWrite = false;
                    child.material[3].depthWrite = false;
                    child.material[4].depthWrite = false;
                    child.material[5].depthWrite = false;
                } else {
                    if(rooms_dollhouse[child.userData.index].cube_face_front) {
                        child.material[0].depthWrite = true;
                    } else {
                        child.material[0].depthWrite = false;
                    }
                    if(rooms_dollhouse[child.userData.index].cube_face_back) {
                        child.material[1].depthWrite = true;
                    } else {
                        child.material[1].depthWrite = false;
                    }
                    if(rooms_dollhouse[child.userData.index].cube_face_top) {
                        child.material[2].depthWrite = true;
                    } else {
                        child.material[2].depthWrite = false;
                    }
                    if(rooms_dollhouse[child.userData.index].cube_face_bottom) {
                        child.material[3].depthWrite = true;
                    } else {
                        child.material[3].depthWrite = false;
                    }
                    if(rooms_dollhouse[child.userData.index].cube_face_left) {
                        child.material[4].depthWrite = true;
                    } else {
                        child.material[4].depthWrite = false;
                    }
                    if(rooms_dollhouse[child.userData.index].cube_face_right) {
                        child.material[5].depthWrite = true;
                    } else {
                        child.material[5].depthWrite = false;
                    }
                }
            }
        });
        for(var i=0; i<pointers_c_dollhouse.length; i++) {
            if(pointers_c_dollhouse[i].userData.level==level) {
                if(opacity<1) {
                    pointers_c_dollhouse[i].visible = false;
                    pointers_t_dollhouse[i].visible = false;
                } else {
                    if(pointers_c_dollhouse[i].userData.visible) {
                        pointers_c_dollhouse[i].visible = true;
                        pointers_t_dollhouse[i].visible = true;
                    }
                }
            }
        }
    };

    function onWindowResize_dollhouse() {
        camera_dollhouse.aspect = dollhouse_div.offsetWidth / dollhouse_div.offsetHeight;
        camera_dollhouse.updateProjectionMatrix();
        renderer_dollhouse.setSize( dollhouse_div.offsetWidth, dollhouse_div.offsetHeight );
        if(css_renderer_dollhouse!=null) {
            css_renderer_dollhouse.setSize( dollhouse_div.offsetWidth, dollhouse_div.offsetHeight );
        }
    }

    function animate_dollhouse() {
        if(dollhouse_open || !dollhouse_loaded) {
            requestAnimationFrame( animate_dollhouse );
            update_dollhouse();
        }
    }

    function update_dollhouse() {
        controls_dollhouse.update();
        TWEEN.update();
        renderer_dollhouse.render( scene_dollhouse, camera_dollhouse );
        if(css_renderer_dollhouse!=null) {
            css_renderer_dollhouse.render(scene_dollhouse, camera_dollhouse);
        }
    }

    function adjust_camera_dollhouse_rotation(rotation, target) {
        var target_new = new THREE.Vector3().copy(target);
        rotation = rotation % 360;
        rotation = (rotation + 360) % 360;
        if(rotation>=0 && rotation<=90) {
            var ratio_x = rotation/90;
            var x = (ratio_x*100)*-1;
            var z = 100-(ratio_x*100);
            target_new.x += x;
            target_new.z += z;
        }
        if(rotation>90 && rotation<=180) {
            var ratio_x = (180-rotation)/90;
            var x = (ratio_x*100)*-1;
            var z = (100-(ratio_x*100))*-1;
            target_new.x += x;
            target_new.z += z;
        }
        if(rotation>180 && rotation<=270) {
            var ratio_x = (270-rotation)/90;
            var x = 100-(ratio_x*100);
            var z = (ratio_x*100)*-1;
            target_new.x += x;
            target_new.z += z;
        }
        if(rotation>270 && rotation<=360) {
            var ratio_x = (360-rotation)/90;
            var x = (ratio_x*100);
            var z = 100-(ratio_x*100);
            target_new.x += x;
            target_new.z += z;
        }
        return target_new;
    }

    function tweenCamera_dollhouse(targetPosition, duration, rotation, id) {
        var list_label_remove = [];
        scene_dollhouse.traverse(function(obj) {
            if (obj.name=="label_pointer_dollhouse") {
                list_label_remove.push(obj);
            }
        });
        for (var i=0; i<list_label_remove.length; i++) {
            scene_dollhouse.remove(list_label_remove[i]);
        }
        css_renderer_dollhouse = null;
        document.getElementById('css_container_dollhouse').innerHTML='';
        controls_dollhouse.enabled = false;
        is_animating_pointer_dollhouse = true;
        var position = new THREE.Vector3().copy(camera_dollhouse.position);
        var target = new THREE.Vector3().copy(targetPosition);
        target = adjust_camera_dollhouse_rotation(rotation,target);
        for(var i=0; i<pointers_c_dollhouse.length; i++) {
            pointers_c_dollhouse[i].visible = false;
            pointers_t_dollhouse[i].visible = false;
        }
        TWEEN.removeAll();
        new TWEEN.Tween(position).to(targetPosition, duration)
            .easing(TWEEN.Easing.Circular.Out)
            .onUpdate(function () {
                camera_dollhouse.position.copy(position);
            }).onComplete(function () {
            camera_dollhouse.position.copy(targetPosition);
            controls_dollhouse.enabled = true;
            is_animating_pointer_dollhouse = false;
        }).start();
        new TWEEN.Tween(controls_dollhouse.target).to(target, duration)
            .easing(TWEEN.Easing.Circular.Out)
            .onUpdate(function () {
                camera_dollhouse.lookAt(controls_dollhouse.target);
            }).onComplete(function () {
            camera_dollhouse.lookAt(target);
        }).start();
    }

    function tweenCamera_dollhouse_out(duration) {
        controls_dollhouse.enabled = false;
        is_animating_pointer_dollhouse = true;
        var position = new THREE.Vector3().copy(camera_dollhouse.position);
        var position_controls = new THREE.Vector3().copy(controls_dollhouse.target);
        if(camera_pos_dollhouse!='' && camera_pos_dollhouse!==undefined) {
            var target = new THREE.Vector3().copy(camera_pos_dollhouse.cameraPosition);
            var target_controls = new THREE.Vector3().copy(camera_pos_dollhouse.targetPosition);
        } else {
            var center = computeGroupCenter_dollhouse(group_rooms_dollhouse);
            var target = new THREE.Vector3(center.x-600, center.y+1200, center.z-600);
            var target_controls = new THREE.Vector3(center.x, center.y, center.z);
        }
        for(var i=0; i<pointers_c_dollhouse.length; i++) {
            pointers_c_dollhouse[i].visible = pointers_c_dollhouse[i].userData.visible;
            pointers_t_dollhouse[i].visible = pointers_t_dollhouse[i].userData.visible;
        }
        TWEEN.removeAll();
        new TWEEN.Tween(position).to(target, duration)
            .easing(TWEEN.Easing.Circular.In)
            .onUpdate(function () {
                camera_dollhouse.position.copy(position);
            }).onComplete(function () {
            camera_dollhouse.position.copy(target);
            controls_dollhouse.enabled = true;
            is_animating_pointer_dollhouse = false;
        }).start();
        new TWEEN.Tween(position_controls).to(target_controls, duration)
            .easing(TWEEN.Easing.Circular.In)
            .onUpdate(function () {
                controls_dollhouse.target.copy(position_controls);
            }).onComplete(function () {
            controls_dollhouse.target.copy(target_controls);
        }).start();
    }

    window.select_level_dollhouse = function(level,name,count_levels) {
        if(count_levels==1) {
            document.getElementById('button_level_dollhouse').innerHTML = name;
        } else {
            document.getElementById('button_level_dollhouse').innerHTML = '<i class="fas fa-layer-group"></i>&nbsp;&nbsp;'+name;
        }
        level_sel_dollhouse = level;
        if(level=='all') {
            for(var i=0; i<group_rooms_dollhouse.length; i++) {
                setOpacity_group_dollhouse(group_rooms_dollhouse,i,1);
            }
        } else {
            for(var i=0; i<group_rooms_dollhouse.length; i++) {
                if(i==level) {
                    setOpacity_group_dollhouse(group_rooms_dollhouse,i,1);
                } else {
                    setOpacity_group_dollhouse(group_rooms_dollhouse,i,0.1);
                }
            }
        }
    }

    function draw_room_dollhouse(index) {
        var id = rooms_dollhouse[index].id;
        var index_panorama = get_id_viewer(id);
        var level = rooms_dollhouse[index].level;
        var cube_width = rooms_dollhouse[index].cube_width;
        var cube_height = rooms_dollhouse[index].cube_height;
        var cube_depth = rooms_dollhouse[index].cube_depth;
        var rx_offset = rooms_dollhouse[index].rx_offset;
        var ry_offset = rooms_dollhouse[index].ry_offset;
        var rz_offset = rooms_dollhouse[index].rz_offset;
        var x_pos = rooms_dollhouse[index].x_pos;
        var y_pos = 0;
        for(var i=0; i<levels_dollhouse.length;i++) {
            if(level == levels_dollhouse[i].id) {
                y_pos = levels_dollhouse[i].y_pos;
            }
        }
        var z_pos = rooms_dollhouse[index].z_pos;
        var rotation = rooms_dollhouse[index].rotation;
        var center_x = rooms_dollhouse[index].center_x;
        var center_y = rooms_dollhouse[index].center_y;
        var center_z = rooms_dollhouse[index].center_z;
        var pointer_visible = rooms_dollhouse[index].pointer_visible;
        var pointer_offset_x = rooms_dollhouse[index].pointer_offset_x;
        var pointer_offset_z = rooms_dollhouse[index].pointer_offset_z;
        var cube_face_top = rooms_dollhouse[index].cube_face_top;
        var cube_face_bottom = rooms_dollhouse[index].cube_face_bottom;
        var cube_face_left = rooms_dollhouse[index].cube_face_left;
        var cube_face_right = rooms_dollhouse[index].cube_face_right;
        var cube_face_front = rooms_dollhouse[index].cube_face_front;
        var cube_face_back = rooms_dollhouse[index].cube_face_back;
        pointer_offset_x = pointer_offset_x * (cube_width/2);
        pointer_offset_z = pointer_offset_z * (cube_depth/2);
        var yaw = panoramas[index_panorama].yaw;
        if(rotation!=0) {
            var rotation_target = yaw-(rotation*360);
        } else {
            var rotation_target = yaw;
        }
        center_x = cube_width * center_x;
        center_y = cube_height * center_y;
        center_z = cube_depth * center_z;
        rx_offset = cube_width * rx_offset;
        ry_offset = cube_height * ry_offset;
        rz_offset = cube_depth * rz_offset;
        var x_pos_s = x_pos + (cube_width/2);
        var y_pos_s = y_pos + (cube_height/2);
        var z_pos_s = z_pos + (cube_depth/2);
        create_pointer_dollhouse(id,x_pos_s,y_pos,z_pos_s,level,cube_height,rotation_target,pointer_offset_x,pointer_offset_z,pointer_visible);
        textures_dollhouse[index].wrapS = THREE.RepeatWrapping;
        textures_dollhouse[index].magFilter = THREE.NearestFilter;
        textures_dollhouse[index].minFilter = THREE.NearestFilter;
        var MaxAnisotropy = renderer_dollhouse.capabilities.getMaxAnisotropy()/2;
        if(MaxAnisotropy<1) MaxAnisotropy=1;
        textures_dollhouse[index].anisotropy = MaxAnisotropy;
        textures_dollhouse[index].offset.x = rotation;
        geometries_dollhouse[index] = new THREE.BoxBufferGeometry(cube_width, cube_height, cube_depth, 600, 20, 20).toNonIndexed();
        geometries_dollhouse[index].scale(-1, 1, 1);
        var positions = geometries_dollhouse[index].attributes.position.array;
        var uvs = geometries_dollhouse[index].attributes.uv.array;
        var rx = (cube_width/2) + rx_offset;
        var ry = (cube_height/2) + ry_offset;
        var rz = (cube_depth/2) + rz_offset;
        for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
            var x = (positions[ i * 3 + 0 ]+center_x)/rx;
            var y = (positions[ i * 3 + 1 ]+center_y)/ry;
            var z = (positions[ i * 3 + 2 ]+center_z)/rz;
            var a = Math.sqrt(1.0 / (x * x + y * y + z * z));
            var phi, theta;
            phi = Math.asin(a * y);
            theta = Math.atan2(a * x, a * z);
            if((x==0) && (z<0)) {
                var p = Math.floor(i / 3);
                if ((positions[p * 3 * 3] < 0) || (positions[(p + 1) * 3 * 3] < 0) || (positions[(p + 2) * 3 * 3] < 0)) {
                    theta = -Math.PI;
                }
            }
            var uvx = 1 - (theta+Math.PI)/Math.PI/2;
            var uvy = (phi+Math.PI/2)/Math.PI;
            uvs[i * 2] = uvx;
            uvs[i * 2 + 1] = uvy;
        }
        if(cube_face_front) {
            var material1 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 1 } );
        } else {
            var material1 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 0, depthWrite: false } );
        }
        if(cube_face_back) {
            var material2 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 1 } );
        } else {
            var material2 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 0, depthWrite: false } );
        }
        if(cube_face_top) {
            var material3 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 1 } );
        } else {
            var material3 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 0, depthWrite: false } );
        }
        if(cube_face_bottom) {
            var material4 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 1 } );
        } else {
            var material4 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 0, depthWrite: false } );
        }
        if(cube_face_left) {
            var material5 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 1 } );
        } else {
            var material5 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 0, depthWrite: false } );
        }
        if(cube_face_right) {
            var material6 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 1 } );
        } else {
            var material6 = new THREE.MeshBasicMaterial( { map: textures_dollhouse[index], transparent: true, opacity: 0, depthWrite: false } );
        }
        meshes_dollhouse[index] = new THREE.Mesh( geometries_dollhouse[index], [material1,material2,material3,material4,material5, material6] );
        meshes_dollhouse[index].userData = { type:'room',level:level, index:index, id:id};
        meshes_dollhouse[index].position.set(x_pos_s, y_pos_s, z_pos_s);
        group_rooms_dollhouse[level].add(meshes_dollhouse[index]);
    }

    function onDocumentMouseMove_pointer_dollhouse(event) {
        var mouse = new THREE.Vector2();
        mouse.x = ( (event.clientX - dollhouse_div.offsetLeft) / dollhouse_div.clientWidth ) * 2 - 1;
        mouse.y = ( (event.clientY - dollhouse_div.offsetTop) / dollhouse_div.clientHeight ) * -2 + 1;
        var raycaster = new THREE.Raycaster();
        raycaster.setFromCamera( mouse, camera_dollhouse );
        var objects_raycast = [];
        for(var i=0; i<scene_dollhouse.children.length; i++) {
            if(dollhouse_glb!='') {
                objects_raycast.push(scene_dollhouse.children[i]);
            } else {
                if(scene_dollhouse.children[i].type=='Group') {
                    for(var k=0; k<scene_dollhouse.children[i].children.length; k++) {
                        if(level_sel_dollhouse=='all' || scene_dollhouse.children[i].children[k].userData.level==level_sel_dollhouse) {
                            objects_raycast.push(scene_dollhouse.children[i].children[k]);
                        }
                    }
                }
            }
        }
        var intersects = raycaster.intersectObjects( objects_raycast );
        for(var i=0; i<pointers_c_dollhouse.length; i++) {
            pointers_c_dollhouse[i].material.opacity=0.2;
            pointers_t_dollhouse[i].material.opacity=0.6;
        }
        var labels_pointer = document.getElementsByClassName('label_pointer_dollhouse');
        for(var i=0; i<labels_pointer.length; i++) {
            labels_pointer[i].classList.remove('label_pointer_dollhouse_active');
        }
        document.body.style.cursor = 'default';
        can_click_pointer_dollhouse = false;
        if(intersects.length > 0) {
            if(intersects[0].object.userData.type !== undefined) {
                if(intersects[0].object.userData.type == 'pointer') {
                    var id = intersects[0].object.userData.id;
                    var torus = scene_dollhouse.getObjectByName("pointer_t_"+id);
                    var circle = scene_dollhouse.getObjectByName("pointer_c_"+id);
                    if(circle.visible) {
                        torus.material.opacity=1;
                        circle.material.opacity=0.4;
                        try {
                            document.getElementById('label_pointer_dollhouse_'+id).classList.add('label_pointer_dollhouse_active');
                        } catch (e) {}
                        document.body.style.cursor = 'pointer';
                        can_click_pointer_dollhouse = true;
                    }
                }
            }
        }
        if(array_dollhouse.settings.autorotate_speed!=0) {
            if(can_click_pointer_dollhouse) {
                clearTimeout(dollhouse_autorotate_timeout);
                controls_dollhouse.autoRotate = false;
            } else {
                clearTimeout(dollhouse_autorotate_timeout);
                dollhouse_autorotate_timeout = setTimeout(function(){
                    controls_dollhouse.autoRotate = true;
                }, array_dollhouse.settings.autorotate_inactivity);
            }
        }
    }

    function create_pointer_dollhouse(id,pos_x,pos_y,pos_z,level,cube_height,rotation,pointer_offset_x,pointer_offset_z,visible) {
        var geometry = new THREE.TorusGeometry( 20, 2, 2, 32 );
        if(current_id_panorama==id) {
            var color = Number("0x"+array_dollhouse.settings.pointer_color_active);
        } else {
            var color = Number("0x"+array_dollhouse.settings.pointer_color);
        }
        var material = new THREE.MeshBasicMaterial( { color: color, transparent: false, opacity: 0.6 } );
        var torus = new THREE.Mesh(geometry, material);
        torus.position.set(pos_x+pointer_offset_x, pos_y+2, pos_z+pointer_offset_z);
        torus.rotation.x = Math.PI / 2;
        torus.userData = { type:'pointer',level:level, id:id, visible:visible};
        var geometry = new THREE.CircleGeometry( 20, 32 );
        var material = new THREE.MeshBasicMaterial( { color: color, transparent: true, opacity: 0.2, side: THREE.DoubleSide } );
        var circle = new THREE.Mesh(geometry, material);
        circle.renderOrder = 1;
        circle.position.set(pos_x+pointer_offset_x, pos_y+2, pos_z+pointer_offset_z);
        circle.rotation.x = -Math.PI / 2;
        circle.userData = { type:'pointer',level:level, id:id, visible:visible};
        torus.name = "pointer_t_"+id;
        circle.name = "pointer_c_"+id;
        if(visible) {
            var start_touch, end_touch, timer_touch;
            domEvents_dollhouse.addEventListener(torus, 'click', function(event){
                click_pointer_dollhouse(id,pos_x,pos_y+(cube_height/2),pos_z,rotation);
            }, false);
            domEvents_dollhouse.addEventListener(torus, 'touchstart', function(event){
                var labels_pointer = document.getElementsByClassName('label_pointer_dollhouse');
                for(var i=0; i<labels_pointer.length; i++) {
                    labels_pointer[i].classList.remove('label_pointer_dollhouse_active');
                }
                start_touch = new Date().getTime();
                timer_touch = setTimeout(function () {
                    try {
                        document.getElementById('label_pointer_dollhouse_'+id).classList.add('label_pointer_dollhouse_active');
                    } catch (e) {}
                },400);
            }, false);
            domEvents_dollhouse.addEventListener(torus, 'touchend', function(event){
                end_touch = new Date().getTime();
                var diff_touch = end_touch - start_touch;
                if(diff_touch<400) {
                    clearTimeout(timer_touch);
                    click_pointer_dollhouse(id,pos_x,pos_y+(cube_height/2),pos_z,rotation);
                }
            }, false);
            domEvents_dollhouse.addEventListener(circle, 'click', function(event){
                click_pointer_dollhouse(id,pos_x,pos_y+(cube_height/2),pos_z,rotation);
            }, false);
            domEvents_dollhouse.addEventListener(circle, 'touchstart', function(event){
                var labels_pointer = document.getElementsByClassName('label_pointer_dollhouse');
                for(var i=0; i<labels_pointer.length; i++) {
                    labels_pointer[i].classList.remove('label_pointer_dollhouse_active');
                }
                start_touch = new Date().getTime();
                timer_touch = setTimeout(function () {
                    try {
                        document.getElementById('label_pointer_dollhouse_'+id).classList.add('label_pointer_dollhouse_active');
                    } catch (e) {}
                },400);
            }, false);
            domEvents_dollhouse.addEventListener(circle, 'touchend', function(event){
                end_touch = new Date().getTime();
                var diff_touch = end_touch - start_touch;
                if(diff_touch<400) {
                    clearTimeout(timer_touch);
                    click_pointer_dollhouse(id,pos_x,pos_y+(cube_height/2),pos_z,rotation);
                }
            }, false);
        }
        torus.visible = visible;
        circle.visible = visible;
        pointers_t_dollhouse.push(torus);
        pointers_c_dollhouse.push(circle);
        if(dollhouse_glb!='') {
            scene_dollhouse.add(circle);
            scene_dollhouse.add(torus);
        } else {
            group_rooms_dollhouse[level].add(circle);
            group_rooms_dollhouse[level].add(torus);
        }
    }

    function render_labels_dollhouse() {
        var css_container = document.getElementById( 'css_container_dollhouse' );
        css_renderer_dollhouse = new THREE.CSS2DRenderer();
        css_renderer_dollhouse.setSize( dollhouse_div.offsetWidth, dollhouse_div.offsetHeight);
        css_renderer_dollhouse.domElement.style.position = 'absolute';
        css_renderer_dollhouse.domElement.style.top = '0px';
        css_renderer_dollhouse.domElement.style.pointerEvents = 'none';
        css_container.appendChild( css_renderer_dollhouse.domElement );
        for(var i=0; i<rooms_dollhouse.length; i++) {
            var id = parseInt(rooms_dollhouse[i].id);
            var index_panorama = get_id_viewer(id);
            if(index_panorama==null) continue;
            var name = panoramas[index_panorama].name;
            var level = rooms_dollhouse[i].level;
            var cube_width = rooms_dollhouse[i].cube_width;
            var cube_height = rooms_dollhouse[i].cube_height;
            var cube_depth = rooms_dollhouse[i].cube_depth;
            var rotation = rooms_dollhouse[i].rotation;
            var x_pos = rooms_dollhouse[i].x_pos;
            if(dollhouse_glb!='') {
                var y_pos = rooms_dollhouse[i].y_pos;
            } else {
                var y_pos = 0;
                for(var l=0; l<levels_dollhouse.length;l++) {
                    if(level == levels_dollhouse[l].id) {
                        y_pos = levels_dollhouse[l].y_pos;
                    }
                }
            }
            var z_pos = rooms_dollhouse[i].z_pos;
            if(dollhouse_glb!='') {
                var pointer_offset_x = 0;
                var pointer_offset_z = 0;
                var x_pos_s = x_pos;
                var z_pos_s = z_pos;
                var y_pos_s = y_pos;
            } else {
                var pointer_offset_x = rooms_dollhouse[i].pointer_offset_x;
                var pointer_offset_z = rooms_dollhouse[i].pointer_offset_z;
                pointer_offset_x = pointer_offset_x * (cube_width/2);
                pointer_offset_z = pointer_offset_z * (cube_depth/2);
                var x_pos_s = x_pos + (cube_width/2);
                var z_pos_s = z_pos + (cube_depth/2);
                var y_pos_s = y_pos + (cube_height/2);
            }
            var yaw = panoramas[index_panorama].yaw;
            if(rotation!=0) {
                var rotation_target = yaw-(rotation*360);
            } else {
                var rotation_target = yaw;
            }
            var label_div = document.createElement( 'div' );
            label_div.id = 'label_pointer_dollhouse_'+id;
            label_div.id_room = id;
            label_div.x_pos = x_pos_s;
            label_div.y_pos = y_pos_s;
            label_div.z_pos = z_pos_s;
            label_div.rotation = rotation_target;
            label_div.className = 'label_pointer_dollhouse';
            if(dollhouse_glb!='') {
                array_dollhouse.settings.measures = '';
            }
            switch(array_dollhouse.settings.measures) {
                case 'm':
                    var cube_width_m = (cube_width/100).toFixed(2);
                    var cube_depth_m = (cube_depth/100).toFixed(2);
                    var cube_m2 = ((cube_width/100)*(cube_depth/100)).toFixed(2);
                    label_div.innerHTML = '<b>'+name+'</b><br><span>'+cube_width_m+' x '+cube_depth_m+' m = '+cube_m2+' m<sup>2</sup></span>';
                    break;
                case 'ft':
                    var cube_width_ft = ((cube_width/100)*3.2808).toFixed(2);
                    var cube_depth_ft = ((cube_depth/100)*3.2808).toFixed(2);
                    var cube_ft2 = (((cube_width/100)*3.2808)*(((cube_depth/100)*3.2808))).toFixed(2);
                    label_div.innerHTML = '<b>'+name+'</b><br><span>'+cube_width_ft+' x '+cube_depth_ft+' ft = '+cube_ft2+' ft<sup>2</sup></span>';
                    break;
                case '':
                    label_div.innerHTML = '<b>'+name+'</b>';
                    break;
            }
            label_div.addEventListener('click', function(evt){
                click_pointer_dollhouse(evt.currentTarget.id_room,evt.currentTarget.x_pos,evt.currentTarget.y_pos,evt.currentTarget.z_pos,evt.currentTarget.rotation);
            }, false);
            label_div.addEventListener('touchend', function(evt){
                click_pointer_dollhouse(evt.currentTarget.id_room,evt.currentTarget.x_pos,evt.currentTarget.y_pos,evt.currentTarget.z_pos,evt.currentTarget.rotation);
            }, false);
            var label = new THREE.CSS2DObject(label_div);
            label.name = 'label_pointer_dollhouse';
            label.position.set(x_pos_s+pointer_offset_x, y_pos+6, z_pos_s+pointer_offset_z);
            scene_dollhouse.add(label);
        }
    }

    window.view_dollhouse = function () {
        try {
            peer_conn.send({type:'view_dollhouse'});
        } catch (e) {}
        $('#container_dollhouse').show();
        renderer_dollhouse.setSize( dollhouse_div.offsetWidth, dollhouse_div.offsetHeight );
        dollhouse_open = true;
        animate_dollhouse();
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            try { pano_viewer.stopAutoRotate(); } catch (e) {}
        } else {
            try { video_viewer.pnlmViewer.stopAutoRotate(); } catch (e) {}
        }
        set_dollhouse_position(current_id_panorama);
        $('#dollhouse').css('z-index',99990);
        $('#dollhouse').animate({opacity: 1}, 400);
        for(var i=0; i<pointers_c_dollhouse.length; i++) {
            pointers_c_dollhouse[i].visible = pointers_c_dollhouse[i].userData.visible;
            pointers_t_dollhouse[i].visible = pointers_t_dollhouse[i].userData.visible;
        }
        var array_levels_used = [], count_levels_used = 0;
        for(var i=0;i<rooms_dollhouse.length; i++) {
            var level = rooms_dollhouse[i].level;
            if (!array_levels_used.includes(level)) {
                array_levels_used.push(level);
                count_levels_used++;
            }
        }
        if(count_levels_used>1) {
            select_level_dollhouse('all',window.viewer_labels.all+total_measure_label,count_levels_used);
        } else {
            select_level_dollhouse('all',total_measure_label,count_levels_used);
        }
        tweenCamera_dollhouse_out(array_dollhouse.settings.zoom_out);
        setTimeout(function () {
            render_labels_dollhouse();
            if(array_dollhouse.settings.autorotate_speed!=0) {
                dollhouse_autorotate_timeout = setTimeout(function(){
                    controls_dollhouse.autoRotate = true;
                }, array_dollhouse.settings.autorotate_inactivity);
            }
        },array_dollhouse.settings.zoom_out+100);
        $('.info_dollhouse').hide();
    }

    window.close_dollhouse = function () {
        try {
            peer_conn.send({type:'close_dollhouse'});
        } catch (e) {}
        var fadeout = 400;
        if(array_dollhouse.settings.zoom_out<800) {
            fadeout = array_dollhouse.settings.zoom_out - array_dollhouse.settings.zoom_out*0.5;
        }
        clearTimeout(dollhouse_autorotate_timeout);
        controls_dollhouse.autoRotate = false;
        dollhouse_open = false;
        $('#dollhouse').animate({opacity: 0}, fadeout);
        setTimeout(function () {
            $('#dollhouse').css('z-index',-100);
        },fadeout);
    }

    function click_pointer_dollhouse(id,x_pos,y_pos,z_pos,rotation) {
        if(window.learning_mode>0) {
            if(window.learning_unlock_marker) {
                var id_room_target = parseInt(id);
                if(learning_check_marker_locked(id_room_target)) {
                    return;
                }
            }
        }
        if(live_session_connected && peer_id!='') {
            return;
        }
        if(window.is_mobile) can_click_pointer_dollhouse=true;
        if(can_click_pointer_dollhouse && !is_animating_pointer_dollhouse) {
            var pointer_color_active = Number("0x"+array_dollhouse.settings.pointer_color_active);
            var pointer_color = Number("0x"+array_dollhouse.settings.pointer_color);
            try {
                for(var i=0; i<pointers_c_dollhouse.length; i++) {
                    var id_dh = pointers_c_dollhouse[i].userData.id;
                    if(id==id_dh) {
                        pointers_c_dollhouse[i].material.color.setHex(pointer_color_active);
                        pointers_t_dollhouse[i].material.color.setHex(pointer_color_active);
                    } else {
                        pointers_c_dollhouse[i].material.color.setHex(pointer_color);
                        pointers_t_dollhouse[i].material.color.setHex(pointer_color);
                    }
                }
            } catch (e) {}
            var targetPosition = new THREE.Vector3(x_pos,y_pos,z_pos);
            var duration = array_dollhouse.settings.zoom_in;
            var duration2 = duration - (duration*0.2);
            tweenCamera_dollhouse(targetPosition,duration,rotation,id);
            goto('',[id,null,null,null,null,null,null,null],true);
            setTimeout(function () {
                close_dollhouse();
            },duration2);
        }
    }

    function set_dollhouse_position(id_room) {
        for(var i=0; i<rooms_dollhouse.length; i++) {
            var id = rooms_dollhouse[i].id;
            if(id==id_room) {
                var x_pos = rooms_dollhouse[i].x_pos;
                var y_pos = rooms_dollhouse[i].y_pos;
                var z_pos = rooms_dollhouse[i].z_pos;
                var cube_width = rooms_dollhouse[i].cube_width;
                var cube_height = rooms_dollhouse[i].cube_height;
                var cube_depth = rooms_dollhouse[i].cube_depth;
                var rotation = rooms_dollhouse[i].rotation;
                if(dollhouse_glb!='') {
                    var x_pos_s = x_pos;
                    var z_pos_s = z_pos;
                    var y_pos_s = y_pos;
                } else {
                    var x_pos_s = x_pos + (cube_width/2);
                    var z_pos_s = z_pos + (cube_depth/2);
                    var y_pos_s = y_pos + (cube_height/2);
                }
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    var current_yaw = parseFloat(pano_viewer.getYaw());
                } else {
                    var current_yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                }
                if(rotation!=0) {
                    var rotation_target = current_yaw-(rotation*360);
                } else {
                    var rotation_target = current_yaw;
                }
                var targetPosition = new THREE.Vector3(x_pos_s,y_pos_s,z_pos_s);
                tweenCamera_dollhouse(targetPosition,0,rotation_target,id);
            }
        }
    }

    var popupCenter = ({url, title, w, h}) => {
        const dualScreenLeft = window.screenLeft !==  undefined ? window.screenLeft : window.screenX;
        const dualScreenTop = window.screenTop !==  undefined   ? window.screenTop  : window.screenY;
        const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
        const systemZoom = width / window.screen.availWidth;
        const left = (width - w) / 2 / systemZoom + dualScreenLeft
        const top = (height - h) / 2 / systemZoom + dualScreenTop
        const newWindow = window.open(url, title, `scrollbars=yes,width=${w / systemZoom}, height=${h / systemZoom}, top=${top}, left=${left}`)
        if (window.focus) newWindow.focus();
    }

    window.open_screencast_app = function() {
        $('#record_button').hide();
        popupCenter({url: window.url_screencast, title: 'screencast', w: 900, h: 600});
    }

    window.init_ar_simulator = function() {
        if (window.DeviceOrientationEvent && location.protocol == 'https:' && (navigator.userAgent.toLowerCase().indexOf('mobi') >= 0 || /Pacific Build.+OculusBrowser.+SamsungBrowser.+MobileVR/i.test(window.navigator.userAgent) || (navigator.userAgent.indexOf("Mac") >= 0 && navigator.maxTouchPoints && navigator.maxTouchPoints > 0))) {
            if(window.ar_camera_align==1) {
                $('#msg_camera_ar_simulator').show();
            } else {
                $('#container_ar_simulator').css('opacity',1);
                $('#container_ar_simulator').css('background','#343434');
                $('#container_ar_simulator').prependTo(".pnlm-render-container");
                $('.pnlm-ui').css('z-index',2);
            }
            $('#loading_ar').show();
            hide_icons();
            $('.pnlm-dragfix').css('pointer-events','none');
            check_getUserMedia();
            const constraints = {
                audio: false,
                video: { facingMode: (!window.is_mobile ? "user" : "environment") }
            };
            navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
                var video = document.getElementById('webcam_ar_simulator');
                if ("srcObject" in video) { video.srcObject = stream; } else { video.src = window.URL.createObjectURL(stream); }
                video.onloadedmetadata = function(e) {
                    video.play();
                    $('.pnlm-grab').css('cursor','default');
                    $('#msg_camera_ar_simulator').hide();
                    $('#container_ar_simulator').prependTo(".pnlm-render-container");
                    $('.pnlm-ui').css('z-index',2);
                    $('#btn_toggle_camera_ar_simulator').on('mousedown touchstart',function () {
                        $('#container_ar_simulator').css('opacity',0.8);
                        $('#btn_toggle_camera_ar_simulator').css('background-color','black');
                        $('#btn_toggle_camera_ar_simulator').css('color','white');
                    });
                    $('#btn_toggle_camera_ar_simulator').on('mouseup touchend',function () {
                        $('#container_ar_simulator').css('opacity',0.2);
                        $('#btn_toggle_camera_ar_simulator').css('background-color','white');
                        $('#btn_toggle_camera_ar_simulator').css('color','black');
                    });
                    if(window.ar_camera_align==1) {
                        $('#btn_toggle_camera_ar_simulator').show();
                        $('#btn_ar_simulator').show();
                        $('#activate_ar_simulator').show();
                    } else {
                        start_ar_simulator();
                    }
                    $('#loading_ar').fadeOut();
                };
            }).catch((err) => {
                console.log('Failed to get local stream:' + err);
                $('#activate_ar_simulator').hide();
                $('#btn_toggle_camera_ar_simulator').hide();
                $('#btn_ar_simulator').hide();
                $('#msg_camera_ar_simulator').show();
                show_icons();
                $('.pnlm-dragfix').css('pointer-events','initial');
            });
        } else {
            $('#unsupported_ar_simulator').show();
        }
    }

    window.start_ar_simulator = function() {
        if (typeof DeviceOrientationEvent !== 'undefined' && typeof DeviceOrientationEvent.requestPermission === 'function') {
            DeviceOrientationEvent.requestPermission().then(response => {
                if(response == "granted") {
                    toggle_orient();
                    $('#activate_ar_simulator').hide();
                    $('#btn_toggle_camera_ar_simulator').hide();
                    $('#btn_ar_simulator').hide();
                    show_icons();
                    $('#container_ar_simulator').css('opacity',1);
                }
            }).catch(function () {
                $.confirm({
                    lazyOpen: false,
                    theme: 'modern,deivce_motion_prompt',
                    useBootstrap: false,
                    closeIcon: false,
                    typeAnimated: true,
                    title: window.viewer_labels.enable_device_motion,
                    content: '',
                    boxWidth: '250px',
                    buttons: {
                        yes: {
                            text: window.viewer_labels.yes,
                            btnClass: 'btn-green',
                            action: function(){
                                controls_status['orient']=true;
                                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                    pano_viewer.startOrientation();
                                } else {
                                    video_viewer.pnlmViewer.startOrientation();
                                }
                                $('#activate_ar_simulator').hide();
                                $('#btn_toggle_camera_ar_simulator').hide();
                                $('#btn_ar_simulator').hide();
                                $('#container_ar_simulator').css('opacity',1);
                                show_icons();
                            }
                        },
                        cancel : {
                            text: window.viewer_labels.no,
                            action: function(){
                                controls_status['orient']=false;
                                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                                    pano_viewer.stopOrientation();
                                } else {
                                    video_viewer.pnlmViewer.stopOrientation();
                                }
                            }
                        },
                    }
                });
            });
        } else {
            toggle_orient();
            $('#activate_ar_simulator').hide();
            $('#btn_toggle_camera_ar_simulator').hide();
            $('#btn_ar_simulator').hide();
            show_icons();
            $('#container_ar_simulator').css('opacity',1);
        }
    }

    var timeoit_detect_vr = null;
    var redirect_to_vr_v = false;
    window.detectHeadsetVR = function() {
        if(!window.debug && navigator.xr !== undefined) {
            timeoit_detect_vr = setTimeout(function() {
                init_svt();
            },1000);
            if (navigator.xr.isSessionSupported) {
                navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
                    if(supported) {
                        if((isFirefoxReality() || isOculusBrowser()) && !isMobile() && window.webvr==1) {
                            clearTimeout(timeoit_detect_vr);
                            if(window.password_protected) {
                                redirect_to_vr_v = true;
                                init_svt();
                            } else {
                                redirect_to_vr();
                            }
                        } else {
                            clearTimeout(timeoit_detect_vr);
                            init_svt();
                        }
                    } else {
                        clearTimeout(timeoit_detect_vr);
                        init_svt();
                    }
                }).catch(function() {
                    clearTimeout(timeoit_detect_vr);
                    init_svt();
                });
            } else if (navigator.xr.supportsSession) {
                navigator.xr.supportsSession('immersive-vr').then(function () {
                    if((isFirefoxReality() || isOculusBrowser()) && !isMobile() && window.webvr==1) {
                        clearTimeout(timeoit_detect_vr);
                        if(window.password_protected) {
                            redirect_to_vr_v = true;
                            init_svt();
                        } else {
                            redirect_to_vr();
                        }
                    } else {
                        clearTimeout(timeoit_detect_vr);
                        init_svt();
                    }
                }).catch(function() {
                    clearTimeout(timeoit_detect_vr);
                    init_svt();
                });
            } else {
                clearTimeout(timeoit_detect_vr);
                init_svt();
            }
        } else {
            init_svt();
        }
    }

    function redirect_to_vr() {
        let urlParts = window.location.href.split("/");
        var url = window.location.href.replace('/'+urlParts[urlParts.length-2]+'/','/vr/');
        window.location.href = '../vr/redirect_vr.php?url='+url;
    }

    function findAncestor(el, cls) {
        while ((el = el.parentElement) && !el.classList.contains(cls));
        return el;
    }

    function isFirefoxReality() {
        return /(Mobile VR)/i.test(window.navigator.userAgent);
    }
    function isOculusBrowser() {
        return /(OculusBrowser)/i.test(window.navigator.userAgent);
    }
    function isIOS () {
        return /iPad|iPhone|iPod/.test(window.navigator.platform);
    }
    function isTablet () {
        return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(window.navigator.userAgent);
    }
    function isR7 () {
        return /R7 Build/.test(window.navigator.userAgent);
    }
    var isWebXRAvailable = window.navigator.xr !== undefined;
    function isAppleVisionPro () {
        var isMacintosh = navigator.userAgent.includes('Macintosh');
        var hasFiveTouchPoints = navigator.maxTouchPoints === 5;
        return isMacintosh && hasFiveTouchPoints && isWebXRAvailable;
    }
    function isMobileVR () {
        return isOculusBrowser() || isFirefoxReality() || isAppleVisionPro();
    }
    var isMobile = (function () {
        var _isMobile = false;
        (function (a) {
            if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
                _isMobile = true;
            }
            if (isIOS() || isTablet() || isR7()) {
                _isMobile = true;
            }
            if (isMobileVR()) {
                _isMobile = false;
            }
        })(window.navigator.userAgent || window.navigator.vendor || window.opera);
        return function () { return _isMobile; };
    })();

    function setCookie(name,value,days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }
    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    function eraseCookie(name) {
        document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    window.change_language_vt = function(lang) {
        $('.div_change_lang').show();
        $('#switching_lang').html($('#lang_item_'+lang).html()).promise().done(function() {
            setTimeout(function() {
                if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
                    try { pano_viewer.stopAutoRotate(); } catch (e) {}
                    var yaw = parseFloat(pano_viewer.getYaw());
                    var pitch = parseFloat(pano_viewer.getPitch());
                    var hfov = parseFloat(pano_viewer.getHfov());
                } else {
                    try {
                        video_viewer.pnlmViewer.stopAutoRotate();
                    } catch (e) {
                    }
                    var yaw = parseFloat(video_viewer.pnlmViewer.getYaw());
                    var pitch = parseFloat(video_viewer.pnlmViewer.getPitch());
                    var hfov = parseFloat(video_viewer.pnlmViewer.getHfov());
                }
                var id = get_id_viewer(current_id_panorama);
                var id_room = panoramas[id].id;
                var params_lang_t = {};
                params_lang_t['lang']=lang;
                params_lang_t['id_room']=id_room;
                params_lang_t['yaw']=yaw;
                params_lang_t['pitch']=pitch;
                params_lang_t['hfov']=hfov;
                var params_lang_json = JSON.stringify(params_lang_t);
                sessionStorage.setItem('params_lang',params_lang_json);
                if(window.export_mode==1) {
                    if(window.default_language==lang && window.browser_language==lang) {
                        var new_url = 'index.html';
                    } else {
                        var new_url = lang+'.html';
                    }
                } else {
                    var current_url = location.href;
                    if (current_url.indexOf('code=') !== -1 || current_url.indexOf('?') !== -1) {
                        if (current_url.indexOf('lang=') !== -1) {
                            if(window.default_language==lang && window.browser_language==lang) {
                                var new_url = current_url.replace(/&lang=[^&]+/,``);
                            } else {
                                var new_url = current_url.replace(/lang=[^&]+/, `lang=${lang}`);
                            }
                        } else {
                            if(window.default_language==lang && window.browser_language==lang) {
                                var new_url = current_url;
                            } else {
                                var new_url = current_url+`&lang=${lang}`;
                            }
                        }
                    } else {
                        if (current_url.indexOf('@') !== -1) {
                            if(window.default_language==lang && window.browser_language==lang) {
                                var new_url = current_url.replace(/@[^/]+/, ``);
                            } else {
                                var new_url = current_url.replace(/@[^/]+/, `@${lang}`);
                            }
                        } else {
                            if(window.default_language==lang && window.browser_language==lang) {
                                var new_url = current_url;
                            } else {
                                var new_url = current_url+`@${lang}`;
                            }
                        }
                    }
                }
                location.href=new_url;
            },100);
        });
    }

    function degreesToRadians(degrees) {
        return degrees * Math.PI / 180;
    }

    function isSVG(fileName) {
        return /\.svg$/i.test(fileName);
    }

    window.camera_currentAspectRatio = 16/9;
    window.snapshot_base64 = '';
    var camera_shutter_audio = new Howl({
        src: ['data:audio/mpeg;base64, ']
    });

    window.camera_setAspectRatio = function(ratio,animate,id) {
        window.camera_currentAspectRatio = ratio;
        const vtContainer = document.getElementById("vt_container");
        const cameraFrame = document.getElementById("cameraFrame");
        const overlayWrapper = document.querySelector(".camera-overlay-wrapper");
        $('.aspect-ratio-btn').removeClass('active');
        $('#aspectRatioBtn'+id).addClass('active');
        if(animate) cameraFrame.classList.add('camera-animation');
        const c_width = vtContainer.innerWidth || vtContainer.clientWidth;
        const c_height = vtContainer.innerHeight || vtContainer.clientHeight;
        let maxWidth = c_width - 90;
        let maxHeight = c_height - 90;
        let width = maxWidth;
        let height = maxHeight;
        if(ratio!=0) {
            maxWidth = c_width - 40;
            maxHeight = c_height - 40;
            width = maxWidth * 0.9;
            height = width / ratio;
            if (height > maxHeight * 0.9) {
                height = maxHeight * 0.9;
                width = height * ratio;
            }
        }
        cameraFrame.style.width = `${width}px`;
        cameraFrame.style.height = `${height}px`;
        camera_adjustOverlays(width, height, animate);
    }

    window.camera_triggerShutter = function() {
        const iconCamera_wrapper = document.getElementById("iconCamera");
        const iconCamera = iconCamera_wrapper.getElementsByTagName('i')[0];
        const shutterTop = document.getElementById('shutterTop');
        const shutterBottom = document.getElementById('shutterBottom');
        const cameraFlash = document.getElementById('cameraFlash');
        const cameraFrame = document.getElementById("cameraFrame");
        const screenshotOverlay = document.getElementById('screenshotOverlay');
        const aspectRatioBtns = document.getElementById('aspectRatioBtns');
        const closeSnapshotMode = document.getElementById("closeSnapshotMode");
        closeSnapshotMode.style.display = 'none';
        aspectRatioBtns.style.display = 'none';
        iconCamera_wrapper.classList.add('disabled');
        iconCamera.classList.remove('fa-camera');
        iconCamera.classList.add('fa-circle-notch');
        iconCamera.classList.add('fa-spin');
        camera_shutter_audio.currentTime=0;
        camera_shutter_audio.play();
        shutterTop.style.animation = 'closeShutter 0.6s ease-in-out';
        shutterBottom.style.animation = 'closeShutter 0.6s ease-in-out';
        cameraFlash.style.animation = 'flashEffect 0.6s ease-in-out';
        setTimeout(() => {
            shutterTop.style.animation = 'none';
            shutterBottom.style.animation = 'none';
            cameraFlash.style.animation = 'none';
            cameraFrame.classList.add('loading');
            captureAndOverlayScreenshot(cameraFrame, screenshotOverlay);
        }, 600);
    }

    function captureAndOverlayScreenshot() {
        let defaultParams = {
            logo: 'top_right',
            info: 'bottom_left',
            qrcode: 'bottom_right'
        };
        try {
            snapshot_params = JSON.parse(snapshot_params);
        } catch (e) {
            snapshot_params = {};
        }
        snapshot_params = Object.assign({}, defaultParams, snapshot_params);
        const cameraFrame = document.getElementById("cameraFrame");
        const rect = cameraFrame.getBoundingClientRect();
        const canvas = document.createElement('canvas');
        if(window.quality_viewer==1.1) {
            var pixelRatio = window.devicePixelRatio || 1;
        } else {
            var pixelRatio = window.quality_viewer;
        }
        var rect_width = rect.width * pixelRatio;
        var rect_height = rect.height * pixelRatio;
        var rect_left = rect.left * pixelRatio;
        var rect_top = rect.top * pixelRatio;
        canvas.width = rect_width-2;
        canvas.height = rect_height-2;
        const ctx = canvas.getContext('2d');
        let canvas_o;
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            if (pano_viewer?.getRenderer) {
                canvas_o = pano_viewer.getRenderer().getCanvas();
            }
        } else {
            if (video_viewer?.pnlmViewer?.getRenderer) {
                canvas_o = video_viewer.pnlmViewer.getRenderer().getCanvas();
            }
        }
        if (!canvas_o) {
            console.error("Canvas not found.");
            return;
        }
        let filters = canvas_o.style.filter;
        if(filters!=='') {
            ctx.filter = filters || "none";
        }
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            var dataURL = pano_viewer.getRenderer().render(pano_viewer.getPitch() / 180 * Math.PI,
                pano_viewer.getYaw() / 180 * Math.PI,
                pano_viewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'screenshot'});
        } else {
            var dataURL = video_viewer.pnlmViewer.getRenderer().render(video_viewer.pnlmViewer.getPitch() / 180 * Math.PI,
                video_viewer.pnlmViewer.getYaw() / 180 * Math.PI,
                video_viewer.pnlmViewer.getHfov() / 180 * Math.PI,
                {'returnImage': 'screenshot'});
        }
        var image = new Image();
        image.setAttribute('crossorigin', 'anonymous');
        image.onload = () => {
            ctx.drawImage(
                image,
                rect_left+2,
                rect_top+2,
                rect_width-2,
                rect_height-2,
                0,
                0,
                rect_width-2,
                rect_height-2
            );
            var index = get_id_viewer(current_id_panorama);
            if (snapshot_params.info!='none') {
                var name_room = panoramas[index].name;
                drawTitleSubtitleBox(ctx, canvas, name_virtual_tour, name_room, snapshot_params.info, rect_width);
            }
            if (snapshot_params.qrcode!='none') {
                var qrImage = new Image();
                qrImage.crossOrigin = "anonymous";
                qrImage.onload = function() {
                    drawQRCode(ctx, canvas, qrImage, snapshot_params.qrcode, rect_width);
                    continueAfterDraw(canvas, snapshot_params, rect_width);
                };
                qrImage.onerror = function() {
                    console.error("Failed to load QR code image.");
                    continueAfterDraw(canvas, snapshot_params, rect_width);
                };
                var url = window.url_vt+"/index.php?code="+window.code+'&room='+current_id_panorama;
                qrImage.src = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" + encodeURIComponent(url);
            } else {
                continueAfterDraw(canvas, snapshot_params, rect_width);
            }
        }
        image.src = dataURL;
    }

    function continueAfterDraw(canvas, snapshot_params, rect_width) {
        if(window.logo==='' || snapshot_params.logo=='none') {
            var base64Image = canvas.toDataURL('image/png',1.0);
            view_snapshot(base64Image);
        } else {
            var logo_s = new Image();
            logo_s.setAttribute('crossorigin', 'anonymous');
            logo_s.onload = function() {
                var maxWidth = (rect_width * 0.2 > 160) ? 160 : rect_width * 0.2;
                var maxHeight = (canvas.height * 0.1 > 160) ? 160 : canvas.height * 0.1;
                var base64Logo = watermark_camera_resizeImage(logo_s, maxWidth, maxHeight);
                var base64Image = canvas.toDataURL('image/png',1.0);
                apply_snapshot_watermark(base64Image, base64Logo, snapshot_params.logo);
            };
            logo_s.src = ((window.s3_enabled) ? window.s3_url : '') + "content/" + window.logo;
        }
    }

    function drawQRCode(ctx, canvas, qrImage, position, rect_width) {
        var qrSize = (rect_width * 0.2 > 80) ? 80 : rect_width * 0.2;
        var padding = 10;
        var x, y;
        switch (position) {
            case 'top_left':
                x = padding;
                y = padding;
                break;
            case 'top_right':
                x = canvas.width - qrSize - padding;
                y = padding;
                break;
            case 'bottom_left':
                x = padding;
                y = canvas.height - qrSize - padding;
                break;
            case 'bottom_right':
                x = canvas.width - qrSize - padding;
                y = canvas.height - qrSize - padding;
                break;
        }
        ctx.drawImage(qrImage, x, y, qrSize, qrSize);
    }

    function drawTitleSubtitleBox(ctx, canvas, title, subtitle, position ,rect_width) {
        const padding = 0;
        const boxPadding = 10;
        const title_box_height = 10 + ((rect_width * 0.03 > 18) ? 18 : rect_width * 0.03);
        const spaceBetween = 0;
        const title_font_size = (rect_width * 0.03 > 18) ? 18 : rect_width * 0.03;
        const subtitle_font_size = (rect_width * 0.02 > 14) ? 14 : rect_width * 0.02;
        ctx.textBaseline = "top";
        ctx.textAlign = "left";
        ctx.font = "bold "+title_font_size+"px Verdana";
        const titleWidth = ctx.measureText(title).width;
        ctx.font = "lighter "+subtitle_font_size+"px Verdana";
        const subtitleWidth = ctx.measureText(subtitle).width;
        const maxWidth = Math.max(titleWidth, subtitleWidth) + boxPadding * 2;
        let x, y;
        switch (position) {
            case 'top_left':
                x = padding;
                y = padding + 10;
                ctx.textAlign = "left";
                break;
            case 'top_right':
                x = canvas.width - padding - maxWidth;
                y = padding + 10;
                ctx.textAlign = "right";
                break;
            case 'bottom_left':
                x = padding;
                y = canvas.height - ((title_box_height*2) + padding);
                ctx.textAlign = "left";
                break;
            case 'bottom_right':
                x = canvas.width - padding - maxWidth;
                y = canvas.height - ((title_box_height*2) + padding);
                ctx.textAlign = "right";
                break;
        }

        ctx.fillStyle = "rgba(0,0,0,0.7)";
        ctx.fillRect(x, y, maxWidth, title_box_height);
        ctx.font = "bold "+title_font_size+"px Verdana";
        ctx.fillStyle = "rgba(255,255,255,0.9)";
        if (ctx.textAlign === "left") {
            ctx.fillText(title, x + boxPadding, y + 3);
        } else if (ctx.textAlign === "right") {
            ctx.fillText(title, x + maxWidth - boxPadding, y + 3);
        }
        ctx.font = "lighter "+subtitle_font_size+"px Verdana";
        ctx.fillStyle = "rgba(0,0,0,0.9)";
        ctx.strokeStyle = "rgba(255,255,255,0.5)";
        ctx.lineWidth = 4;
        if (ctx.textAlign === "left") {
            ctx.strokeText(subtitle, x + 5 + (boxPadding/2), y + title_box_height + spaceBetween + 4);
            ctx.fillText(subtitle, x + 5 + (boxPadding/2), y + title_box_height + spaceBetween + 4);
        } else if (ctx.textAlign === "right") {
            ctx.strokeText(subtitle, x - 5 + maxWidth - (boxPadding/2), y + title_box_height + spaceBetween + 4);
            ctx.fillText(subtitle, x - 5 + maxWidth - (boxPadding/2), y + title_box_height + spaceBetween + 4);
        }
    }

    function apply_snapshot_watermark(base64Image, base64Logo, position) {
        const positions = {
            top_left: watermark.image.upperLeft,
            top_right: watermark.image.upperRight,
            bottom_left: watermark.image.lowerLeft,
            bottom_right: watermark.image.lowerRight
        };
        const applyPosition = positions[position];
        if (applyPosition) {
            watermark([base64Image, base64Logo])
                .dataUrl(applyPosition(1.0))
                .then(function (watermarkedImage) {
                    view_snapshot(watermarkedImage);
                });
        }
    }

    function view_snapshot(base64Image) {
        window.snapshot_base64 = base64Image;
        const cameraFrame = document.getElementById("cameraFrame");
        const screenshotOverlay = document.getElementById('screenshotOverlay');
        const iconCloseSnaposhot = document.getElementById("iconCloseSnaposhot");
        const iconCamera_wrapper = document.getElementById("iconCamera");
        const iconCamera = iconCamera_wrapper.getElementsByTagName('i')[0];
        screenshotOverlay.style.backgroundImage = `url('${base64Image}')`;
        screenshotOverlay.style.opacity = 1;
        screenshotOverlay.style.pointerEvents = 'initial';
        iconCamera_wrapper.classList.remove('disabled');
        iconCamera.classList.add('fa-camera');
        iconCamera.classList.remove('fa-circle-notch');
        iconCamera.classList.remove('fa-spin');
        iconCamera_wrapper.style.display = 'none';
        iconCloseSnaposhot.style.display = 'flex';
        cameraFrame.classList.remove('loading');
    }

    window.download_snapshot = function() {
        const safeName = name_virtual_tour.toLowerCase().replace(/\s+/g, '_').replace(/[^\w\-]/g, '');
        const now = new Date();
        const timestamp = now.getTime();
        const fileName = `snapshot_${safeName}_${timestamp}.png`;
        const downloadLink = document.createElement("a");
        downloadLink.href = window.snapshot_base64;
        downloadLink.download = fileName;
        downloadLink.click();
    }

    function watermark_camera_resizeImage(image,maxWidth,maxHeight) {
        var canvas = document.createElement('canvas');
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxWidth) {
                height *= maxWidth / width;
                width = maxWidth;
            }
        } else {
            if (height > maxHeight) {
                width *= maxHeight / height;
                height = maxHeight;
            }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, width, height);
        var base64Image = canvas.toDataURL('image/png',1.0);
        return base64Image;
    }

    window.camera_closeSnaposhot = function() {
        const iconCloseSnaposhot = document.getElementById("iconCloseSnaposhot");
        const closeSnapshotMode = document.getElementById("closeSnapshotMode");
        const iconCamera_wrapper = document.getElementById("iconCamera");
        const screenshotOverlay = document.getElementById('screenshotOverlay');
        const aspectRatioBtns = document.getElementById('aspectRatioBtns');
        iconCamera_wrapper.style.display = 'flex';
        iconCloseSnaposhot.style.display = 'none';
        screenshotOverlay.style.opacity = 0;
        screenshotOverlay.style.pointerEvents = 'none';
        setTimeout(function() {
            screenshotOverlay.style.backgroundImage = `none`;
        },300);
        aspectRatioBtns.style.display = "block";
        closeSnapshotMode.style.display = "block";
        window.snapshot_base64 = '';
    }

    function camera_adjustOverlays(frameWidth, frameHeight, animate) {
        const frame = document.getElementById("cameraFrame");
        const overlayTop = document.getElementById("overlayTop");
        const overlayBottom = document.getElementById("overlayBottom");
        const overlayLeft = document.getElementById("overlayLeft");
        const overlayRight = document.getElementById("overlayRight");
        if(animate) {
            overlayTop.classList.add('camera-animation');
            overlayBottom.classList.add('camera-animation');
            overlayLeft.classList.add('camera-animation');
            overlayRight.classList.add('camera-animation');
        }
        var wrapperWidth = document.querySelector(".camera-overlay-wrapper").offsetWidth;
        const wrapperHeight = document.querySelector(".camera-overlay-wrapper").offsetHeight;
        const topHeight = (wrapperHeight - frameHeight) / 2;
        const bottomHeight = (wrapperHeight - frameHeight) / 2;
        const leftWidth = (wrapperWidth - frameWidth) / 2;
        const rightWidth = (wrapperWidth - frameWidth) / 2;
        wrapperWidth = wrapperWidth - (leftWidth + rightWidth);
        overlayTop.style.width = `${wrapperWidth}px`;
        overlayTop.style.height = `${topHeight}px`;
        overlayTop.style.top = "0";
        overlayBottom.style.width = `${wrapperWidth}px`;
        overlayBottom.style.height = `${bottomHeight}px`;
        overlayBottom.style.bottom = "0";
        overlayLeft.style.width = `${leftWidth}px`;
        overlayLeft.style.height = `${wrapperHeight}px`;
        overlayLeft.style.left = "0";
        overlayRight.style.width = `${rightWidth}px`;
        overlayRight.style.height = `${wrapperHeight}px`;
        overlayRight.style.right = "0";
        setTimeout(function() {
            frame.classList.remove('camera-animation');
            overlayTop.classList.remove('camera-animation');
            overlayBottom.classList.remove('camera-animation');
            overlayLeft.classList.remove('camera-animation');
            overlayRight.classList.remove('camera-animation');
        },300);
    }

    function init_snapshot() {
        camera_shutter_audio.preload = 'auto';
        camera_shutter_audio.autoplay = false;
        camera_shutter_audio.load();
    }

    window.open_snapshot = function() {
        addHiddenClassToDivs();
        clearTimeout(timeout_initial_inactivity);
        clearTimeout(autorotate_timeout);
        if(current_panorama_type=='image' || (current_panorama_type=='video' && window.is_mobile) || current_panorama_type=='hls' || current_panorama_type=='lottie') {
            pano_viewer.stopAutoRotate();
        } else {
            video_viewer.pnlmViewer.stopAutoRotate();
        }
        $('#snapshot_container').show();
        camera_setAspectRatio(window.camera_currentAspectRatio,false,'');
    }

    window.close_snapshot = function() {
        $('#snapshot_container').hide();
        restart_autorotate();
        removeHiddenSnapshotClass();
    }

    function addHiddenClassToDivs() {
        const container = document.getElementById('vt_container');
        function recurseDivs(element) {
            if (element.id === 'snapshot_container' || element.closest('#snapshot_container')) {
                return;
            }
            if (
                element.classList &&
                element.id !== 'vt_container' &&
                element.id !== 'div_panoramas' &&
                !element.classList.contains('pnlm-container') &&
                !element.classList.contains('pnlm-render-container') &&
                !element.classList.contains('pnlm-grab') &&
                !element.classList.contains('pnlm-dragfix')
            ) {
                element.classList.add('hidden_snapshot');
            }
            Array.from(element.children).forEach((child) => {
                if (child.tagName.toLowerCase() === 'div') {
                    recurseDivs(child);
                }
            });
        }
        recurseDivs(container);
    }

    function removeHiddenSnapshotClass() {
        const container = document.getElementById('vt_container');
        const hiddenDivs = container.querySelectorAll('.hidden_snapshot');
        hiddenDivs.forEach((div) => {
            div.classList.remove('hidden_snapshot');
        });
    }

    function isOverlapping(el1, el2, tolerance = 5) {
        const rect1 = el1.getBoundingClientRect();
        const rect2 = el2.getBoundingClientRect();
        return !(
            rect1.right < rect2.left - tolerance ||
            rect1.left > rect2.right + tolerance ||
            rect1.bottom < rect2.top - tolerance ||
            rect1.top > rect2.bottom + tolerance
        );
    }

    let isMoved = false;
    let wasMovedUp = false;
    function adjustCenterDiv() {
        const centerDiv = document.getElementById('controls_bottom_center');
        const leftDiv = document.getElementById('controls_bottom_left');
        const rightDiv = document.getElementById('controls_bottom_right');
        const overlapsLeft = isOverlapping(centerDiv, leftDiv);
        const overlapsRight = isOverlapping(centerDiv, rightDiv);
        const shouldMove = overlapsLeft || overlapsRight;
        if (shouldMove && !isMoved) {
            centerDiv.classList.add('moved');
            isMoved = true;
            wasMovedUp = true;
        }
        else if (!shouldMove && isMoved && wasMovedUp) {
            centerDiv.classList.remove('moved');
            isMoved = false;
        }
        adjustPoweredBy();
    }

    let isMoved_p = false;
    let wasMovedUp_p = false;
    function adjustPoweredBy() {
        const poweredbyDiv = document.querySelector('.poweredby:not(.hidden)');
        if(poweredbyDiv!==null && poweredbyDiv!==undefined) {
            const centerDiv = document.getElementById('controls_bottom_center');
            const overlaps = isOverlapping(poweredbyDiv, centerDiv);
            const shouldMove = overlaps;
            if (shouldMove && !isMoved_p) {
                poweredbyDiv.classList.add('moved');
                isMoved_p = true;
                wasMovedUp_p = true;
            }
            else if (!shouldMove && isMoved_p && wasMovedUp_p) {
                poweredbyDiv.classList.remove('moved');
                isMoved_p = false;
            }
        }
    }

    function reposition_voice_control() {
        if($('.controls_bottom').hasClass('small-btn') && $('.controls_bottom').hasClass('bar-btn')) {
            var pl = 25;
            if (window.c_width <= 480) {
                pl = 23;
            }
            if (window.c_width <= 360) {
                pl = 20;
            }
        } else if($('.controls_bottom').hasClass('small-btn') && !$('.controls_bottom').hasClass('bar-btn')) {
            var pl = 27;
            if (window.c_width <= 480) {
                pl = 25;
            }
            if (window.c_width <= 360) {
                pl = 22;
            }
        } else if($('.controls_bottom').hasClass('large-btn') && $('.controls_bottom').hasClass('bar-btn')) {
            var pl = 35;
            if (window.c_width <= 480) {
                pl = 32;
            }
            if (window.c_width <= 360) {
                pl = 29;
            }
        } else if($('.controls_bottom').hasClass('large-btn') && !$('.controls_bottom').hasClass('bar-btn')) {
            var pl = 37;
            if (window.c_width <= 480) {
                pl = 34;
            }
            if (window.c_width <= 360) {
                pl = 31;
            }
        } else if($('.controls_bottom').hasClass('bar-btn')) {
            var pl = 30;
            if (window.c_width <= 480) {
                pl = 27;
            }
            if (window.c_width <= 360) {
                pl = 25;
            }
        } else {
            var pl = 32;
            if (window.c_width <= 480) {
                pl = 29;
            }
            if (window.c_width <= 360) {
                pl = 27;
            }
        }
        $('#controls_bottom_left').css('padding-left',pl+'px');
    }

    window.onresize = () => {
        camera_setAspectRatio(window.camera_currentAspectRatio,false,'');
    };

    if($('#learning-email').length) {
        document.getElementById('learning-email').addEventListener('keydown', function(event) {
            if (event.key === "Enter") {
                event.preventDefault();
                start_learning();
            }
        });
    }

    window.start_learning = function() {
        if($('#learning-intro-modal').length) {
            if($('#learning-email').length) {
                $('#learning-email').blur();
                var email = $('#learning-email').val().trim();
                if(validateEmail_learning(email)) {
                    if(window.learning_restore_session==1) {
                        save_learning_log(1);
                    } else {
                        $('#learning-intro-modal').animate({
                            opacity: 0
                        }, { duration: 500, queue: false });
                        $('#learning-intro-modal').css('pointer-events','none');
                        setTimeout(function() {
                            $('#learning-intro-modal').hide();
                        },500);
                        initialize_learning();
                    }
                } else {
                    $('#learning-email').focus();
                }
            } else {
                if(window.learning_restore_session==1) {
                    save_learning_log(1);
                } else {
                    $('#learning-intro-modal').animate({
                        opacity: 0
                    }, { duration: 500, queue: false });
                    $('#learning-intro-modal').css('pointer-events','none');
                    setTimeout(function() {
                        $('#learning-intro-modal').hide();
                    },500);
                    initialize_learning();
                }
            }
        } else {
            if(window.learning_restore_session==1) {
                save_learning_log(1);
            } else {
                initialize_learning();
            }
        }
    }

    function initialize_learning() {
        setTimeout(function() {
            if(audio_prompt!=null) {
                if(controls_status['song']) {
                    audio_prompt_open = true;
                    audio_prompt.open();
                }
            }
        },250);
        $('#learning_score').fadeIn();
        learning_score_global_ring = new Donutty("#ring_score_global", {
            value: 0,
            thickness: 10,
            padding: 2,
            color: window.learning_summary_global_color,
            bg: window.learning_summary_global_color_bg,
            round: true,
            title: function() { return ""; },
        });
        learning_score_partial_ring = new Donutty("#ring_score_partial", {
            value: 0,
            thickness: 12,
            padding: 2,
            color: window.learning_summary_partial_color,
            bg: window.learning_summary_partial_color_bg,
            round: true,
            title: function() { return ""; },
        });
        calculate_learning_score(0);
        calculate_learning_score(panoramas[index_initial].id);
    }

    function validateEmail_learning(emailValue) {
        var mandatory = parseInt($('#learning-email').attr('data-mandatory'));
        const emailInput = document.getElementById('learning-email');
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        emailInput.classList.remove("invalid");
        if(mandatory==0 && emailValue === "") {
            return true;
        } else if (emailValue === "" && mandatory==1) {
            return false;
        } else if (!emailPattern.test(emailValue)) {
            emailInput.classList.add("invalid");
            return false;
        } else {
            return true;
        }
    }

    function calculate_learning_score(id_room = 0) {
        let totalCount = 0;
        let countOne = 0;
        const roomsToCount = id_room === 0 ? Object.keys(learning_poi_room) : ["r"+id_room];
        for (const roomId of roomsToCount) {
            if (learning_poi_room.hasOwnProperty(roomId)) {
                for (const markerId in learning_poi_room[roomId]) {
                    if (learning_poi_room[roomId].hasOwnProperty(markerId)) {
                        const value = learning_poi_room[roomId][markerId];
                        totalCount++;
                        if (value === 1) {
                            countOne++;
                        }
                    }
                }
            }
        }
        const percentageOnes = totalCount > 0 ? (countOne / totalCount) * 100 : 0;
        if(id_room==0) {
            $('#score_global .num').html(countOne);
            $('#score_global .tot').html(totalCount);
            if(learning_score_global_ring!=null) learning_score_global_ring.set("value",percentageOnes);
        } else {
            $('#score_partial .num').html(countOne);
            $('#score_partial .tot').html(totalCount);
            if(learning_score_partial_ring!=null) learning_score_partial_ring.set("value",percentageOnes);
        }
    }

    function count_learning_poi_in_room(id_room) {
        let totalCount = 0;
        const roomsToCount = id_room === 0 ? Object.keys(learning_poi_room) : ["r"+id_room];
        for (const roomId of roomsToCount) {
            if (learning_poi_room.hasOwnProperty(roomId)) {
                for (const markerId in learning_poi_room[roomId]) {
                    if (learning_poi_room[roomId].hasOwnProperty(markerId)) {
                        const value = learning_poi_room[roomId][markerId];
                        totalCount++;
                    }
                }
            }
        }
        return totalCount;
    }

    function check_learning_poi_progressive_disabled(id,id_room) {
        let first_poi_id = 0;
        let prev_poi_id = 0;
        if (learning_poi_room["r"+id_room] && typeof learning_poi_room["r"+id_room] === "object") {
            const keys = Object.keys(learning_poi_room["r"+id_room]);
            first_poi_id = keys.length > 0 ? keys[0] : 0;
            let currentIndex = keys.indexOf("p"+id);
            if (currentIndex >=0 && currentIndex < keys.length) {
                prev_poi_id = keys[currentIndex - 1];
            }
        }
        if(first_poi_id) first_poi_id = first_poi_id.replace("p",'');
        if(prev_poi_id) prev_poi_id = prev_poi_id.replace("p",'');
        if(learning_poi_visited.includes(prev_poi_id)) {
            return false;
        } else if(parseInt(first_poi_id)!=parseInt(id) && !learning_poi_visited.includes(id)) {
            return true;
        } else {
            return false;
        }
    }

    function unlock_poi_learning(id,id_room) {
        if (learning_poi_room["r"+id_room]?.["p"+id] !== undefined) {
            var learning_check = document.getElementById('learning_check_'+id);
            if(learning_check!==null && learning_check!==undefined) {
                learning_check.classList.add('visited');
            }
            learning_poi_visited.push(id);
            learning_poi_room["r"+id_room]["p"+id]=1;
            if(window.learning_poi_progressive) {
                let keys = Object.keys(learning_poi_room["r"+id_room]);
                let currentIndex = keys.indexOf("p"+id);
                if (currentIndex >= 0 && currentIndex < keys.length) {
                    let nextKey = keys[currentIndex + 1];
                    if(nextKey) {
                        nextKey = nextKey.replace("p","");
                        $('.hotspot_'+nextKey).removeClass('disabled_l');
                    }
                }
            }
            if(window.learning_unlock_marker) {
                if(!learning_check_room_locked(id_room)) {
                    $.each(learning_marker_room[id_room],function(id_marker_room,id_room_target) {
                        id_room_target = parseInt(id_room_target);
                        if(!learning_room_enabled.includes(id_room_target)) learning_room_enabled.push(id_room_target);
                        $('.marker_'+id_marker_room).removeClass('disabled_l');
                        $('#pointer_f_'+id_room_target).removeClass('disabled_l');
                        $('.pointer_list_'+id_room_target).removeClass('disabled_l');
                        $('.list_alt_'+id_room_target).removeClass('disabled_l');
                        $('#pointer_m_'+id_room_target).removeClass('disabled_l');
                    })
                }
            }
        }
    }

    function save_learning_log(first) {
        if(window.export_mode==0) {
            if(!$('#learning-intro-modal').length && first==1) {
                $('#learning-session-modal').animate({
                    opacity: 1
                }, { duration: 500, queue: false });
            }
            if(first==1) {
                var score_global = 0;
                var learning_poi_room_json = "";
            } else {
                var score_global = parseInt($('#score_global .num').html());
                var learning_poi_room_json = JSON.stringify(learning_poi_room);
            }
            var btn_html = $('.learning-intro-start').html();
            $('.learning-intro-start').html('<i class="fas fa-spin fa-circle-notch"></i>');
            if($('#learning-email').length) {
                var email = $('#learning-email').val();
            } else {
                var email = '';
            }
            Pace.ignore(function(){
                $.ajax({
                    url: "ajax/save_learning_log.php",
                    type: "POST",
                    data: {
                        id_learning: id_learning,
                        id_virtualtour: window.id_virtualtour,
                        ip_visitor: (window.learning_restore_session==1) ? window.ip_visitor : window.id_session_l,
                        email: email,
                        score_global: score_global,
                        learning_poi_room: learning_poi_room_json
                    },
                    async: true,
                    success: function (json) {
                        var rsp = JSON.parse(json);
                        if(rsp.status=='ok') {
                            if(first==1) {
                                if($('#learning-intro-modal').length) {
                                    $('#learning-intro-modal').animate({
                                        opacity: 0
                                    }, { duration: 500, queue: false });
                                    $('#learning-intro-modal').css('pointer-events','none');
                                    setTimeout(function() {
                                        $('#learning-intro-modal').hide();
                                    },500);
                                }
                                if(rsp.learning!='') {
                                    var learning_poi_room_s = rsp.learning_poi_room;
                                    for(const id_room in learning_poi_room_s) {
                                        for (const id_poi in learning_poi_room_s[id_room]) {
                                            if(learning_poi_room[id_room]?.[id_poi] !== undefined) {
                                                var visited = parseInt(learning_poi_room_s[id_room][id_poi]);
                                                learning_poi_room[id_room][id_poi] = visited;
                                                if(visited==1) unlock_poi_learning(id_poi.replace("p",""),id_room.replace("r",""));
                                            }
                                        }
                                    }
                                }
                                id_learning = parseInt(rsp.id);
                                initialize_learning();
                                if(!$('#learning-intro-modal').length && first==1) {
                                    $('#learning-session-modal').animate({
                                        opacity: 0
                                    }, { duration: 500, queue: false });
                                    $('#learning-session-modal').css('pointer-events','none');
                                    setTimeout(function() {
                                        $('#learning-session-modal').hide();
                                    },500);
                                }
                            }
                        } else {
                            $('.learning-intro-start').html(btn_html);
                        }
                    },
                    error: function () {
                        $('.learning-intro-start').html(btn_html);
                    }
                });
            });
        } else {
            $('#learning-intro-modal').animate({
                opacity: 0
            }, { duration: 500, queue: false });
            $('#learning-intro-modal').css('pointer-events','none');
            setTimeout(function() {
                $('#learning-intro-modal').hide();
            },500);
            initialize_learning();
        }
    }

    function setupSafariFullscreenXHandler() {
        const fullscreenClass = 'ipad-x-fullscreen';
        const standaloneClass = 'ipad-standalone';
        const bottomLineClass = 'ipad-bottom-line';
        const target = document.body;
        function isIpadIOS() {
            const ua = navigator.userAgent || navigator.vendor || window.opera;
            const isTouch = navigator.maxTouchPoints > 1;
            return (
                /iPad|iPhone|iPod/.test(ua) ||
                (ua.includes('Macintosh') && isTouch)
            );
        }
        function isStandaloneMode() {
            return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
        }
        function isSafariWithXInFullscreen() {
            const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
            const isFullscreen = controls_status['fullscreen'];
            return !isStandaloneMode() && isSafari && isFullscreen;
        }
        function updateClasses() {
            setTimeout(function() {
                if (isIpadIOS() && isSafariWithXInFullscreen()) {
                    target.classList.add(fullscreenClass);
                } else {
                    target.classList.remove(fullscreenClass);
                }
                if (isIpadIOS() && isStandaloneMode()) {
                    target.classList.add(standaloneClass);
                } else {
                    target.classList.remove(standaloneClass);
                }
                if (isIpadIOS() && !isStandaloneMode() && !controls_status['fullscreen']) {
                    target.classList.add(bottomLineClass);
                } else {
                    target.classList.remove(bottomLineClass);
                }
            },250);
        }
        window.addEventListener('resize', updateClasses);
        window.addEventListener('orientationchange', updateClasses);
        if (window.visualViewport) {
            window.visualViewport.addEventListener('resize', updateClasses);
        }
        document.addEventListener('DOMContentLoaded', updateClasses);
        updateClasses();
    }
})(jQuery);