var Marzipano = window.Marzipano;
var bowser = window.bowser;
var screenfull = window.screenfull;
var APP_DATA = window.APP_DATA;
var curscene;

var transTiming = 1000;

var currentURL = document.URL;
var params = currentURL.extract();

// Grab elements from DOM.
var panoElement = document.querySelector('#pano');
var sceneNameElement = document.querySelector('#titleBar .sceneName');
var sceneListElement = document.querySelector('#sceneList');
var sceneElements = document.querySelectorAll('#sceneList .scene');
var sceneListToggleElement = document.querySelector('#sceneListToggle');
var autorotateToggleElement = document.querySelector('#autorotateToggle');
var fullscreenToggleElement = document.querySelector('#fullscreenToggle');
var deviceOrientationControlMethod = new DeviceOrientationControlMethod();
/* stopTouchAndScrollEventPropagation(document.querySelector('#video')); */

// Detect desktop or mobile mode.
if (window.matchMedia) {
    var setMode = function() {
        if (mql.matches) {
            document.body.classList.remove('desktop');
            document.body.classList.add('mobile');

        } else {
            document.body.classList.remove('mobile');
            document.body.classList.add('desktop');
        }
    };
    var mql = matchMedia("(max-width: 500px), (max-height: 500px)");
    setMode();
    // var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    var isMobile = navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i);


    if (isMobile) {

        document.body.classList.remove('desktop');
        document.body.classList.add('mobile');
        mobile = true;
    }

    mql.addListener(setMode);
} else {
    document.body.classList.add('desktop');
}

// Detect whether we are on a touch device.
document.body.classList.add('no-touch');
window.addEventListener('touchstart', function() {
    document.body.classList.remove('no-touch');
    document.body.classList.add('touch');
});

// Use tooltip fallback mode on IE < 11.
if (bowser.msie && parseFloat(bowser.version) < 11) {
    document.body.classList.add('tooltip-fallback');
}

var currentURL = document.URL;

// Viewer options.
var viewerOpts = {
    controls: {
        mouseViewMode: APP_DATA.settings.mouseViewMode
    }
};

// Initialize viewer.
var viewer = new Marzipano.Viewer(panoElement, viewerOpts);

// Setup autorotate.
var autorotate = Marzipano.autorotate({ yawSpeed: 0.01, targetPitch: 0, targetFov: Math.PI / 2 });
if (APP_DATA.settings.autorotateEnabled) {
    autorotateToggleElement.classList.add('enabled');
}

// Create scenes.
var scenes = APP_DATA.scenes.map(function(sceneData) {
    var source = Marzipano.ImageUrlSource.fromString(
        "tiles/" + sceneData.id + "/{z}/{f}/{y}/{x}.jpg", { cubeMapPreviewUrl: "tiles/" + sceneData.id + "/preview.jpg" });
    var geometry = new Marzipano.CubeGeometry(sceneData.levels);


    var limiter = Marzipano.RectilinearView.limit.traditional(
        sceneData.faceSize * window.devicePixelRatio, 100 * Math.PI / 180, 120 * Math.PI / 180);
    if (sceneData.id == "0-buiten") {
        var limiter = Marzipano.util.compose(
            Marzipano.RectilinearView.limit.traditional(sceneData.faceSize * window.devicePixelRatio, 100 * Math.PI / 180, 120 * Math.PI / 180),
            Marzipano.RectilinearView.limit.yaw(-Math.PI / 3, Math.PI / 3),
            Marzipano.RectilinearView.limit.pitch(-Math.PI / 7, Math.PI / 7)
        );

    } else {
        if (sceneData.id == "3-keuken") {
            var limiter = Marzipano.util.compose(
                Marzipano.RectilinearView.limit.traditional(sceneData.faceSize * window.devicePixelRatio, 100 * Math.PI / 180, 120 * Math.PI / 180),
                Marzipano.RectilinearView.limit.yaw(-Math.PI / 4, Math.PI / 3),
                Marzipano.RectilinearView.limit.pitch(-Math.PI / 5, Math.PI / 5)
            );

        }
    }


    var view = new Marzipano.RectilinearView(sceneData.initialViewParameters, limiter);

    var marzipanoScene = viewer.createScene({
        source: source,
        geometry: geometry,
        view: view,
        pinFirstLevel: true
    });



    if (typeof sceneData.infoIdHotspots != 'undefined') {
        sceneData.infoIdHotspots.forEach(function(hotspot) {
            marzipanoScene.hotspotContainer().createHotspot(document.querySelector(hotspot.id), { yaw: hotspot.yaw, pitch: hotspot.pitch });


        });
    }

    if (typeof sceneData.video != 'undefined') {
        sceneData.video.forEach(function(hotspot) {
            var element = createVideoElement(hotspot);
            marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch }, { perspective: { radius: hotspot.radius, extraRotations: hotspot.extraRotations } });
        });
    }

    if (typeof sceneData.pulseHotspots != 'undefined') {
        sceneData.pulseHotspots.forEach(function(hotspot) {
            var element = createPulseHotspotElement(hotspot);

            marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch });
        });
    }


    if (typeof sceneData.image != 'undefined') {
        sceneData.image.forEach(function(hotspot) {
            var element = createImageElement(hotspot);
            marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch }, { perspective: { radius: hotspot.radius, extraRotations: hotspot.extraRotations } });
        });
    }



    if (typeof sceneData.hotspotModal != 'undefined') {
        sceneData.hotspotModal.forEach(function(hotspot) {
            var element = createInfoHotspotElement(hotspot);
            createInfoHotspotModal(hotspot);
            marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch }, { perspective: { radius: hotspot.radius, extraRotations: hotspot.extraRotations } });
        });
    }



    // Create link hotspots.
    sceneData.linkHotspots.forEach(function(hotspot) {
        var element = createLinkHotspotElement(hotspot);
        marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch });
    });

    // Create info hotspots.
    if (typeof sceneData.infoHotspots != 'undefined') {
        sceneData.infoHotspots.forEach(function(hotspot) {
            var element = createInfoHotspotElement(hotspot);
            marzipanoScene.hotspotContainer().createHotspot(element, { yaw: hotspot.yaw, pitch: hotspot.pitch });
        });
    }


    return {
        data: sceneData,
        marzipanoObject: marzipanoScene
    };
});

var currentURL = document.URL;
var params = currentURL.extract();


if (params && params.id) {
    $("#intro").hide();
    $("#info360").hide();
    $(document.body).addClass('hidehotspots');

    var scene = scenes[params.id];
    switchScene(scene);



} else {
    switchScene(scenes[0]);
}


// Display the initial scene.


// Set handler for autorotate toggle.
autorotateToggleElement.addEventListener('click', toggleAutorotate);

// Check if fullscreen is supported and enable it if so
if (screenfull.enabled && APP_DATA.settings.fullscreenButton) {
    document.body.classList.add('fullscreen-enabled');
    fullscreenToggleElement.addEventListener('click', toggleFullscreen);
} else {
    document.body.classList.add('fullscreen-disabled');
}

// Set handler for scene list toggle.
sceneListToggleElement.addEventListener('click', toggleSceneList);

// Start with the scene list open on desktop.
if (!document.body.classList.contains('mobile')) {
    showSceneList();
}

// Set handler for scene switch.
scenes.forEach(function(scene) {

    var el = document.querySelector('#sceneList .scene[data-id="' + scene.data.id + '"]');

    if (el != null) {
        el.addEventListener('click', function() {
            switchScene(scene);
            // On mobile, hide scene list after selecting a scene.
            if (document.body.classList.contains('mobile')) {
                hideSceneList();
            }
        });
    }

});

/* DOM elements for view controls.
var viewUpElement = document.querySelector('#viewUp');
var viewDownElement = document.querySelector('#viewDown');
var viewLeftElement = document.querySelector('#viewLeft');
var viewRightElement = document.querySelector('#viewRight');
var viewInElement = document.querySelector('#viewIn');
var viewOutElement = document.querySelector('#viewOut');

// Dynamic parameters for controls.
var velocity = 0.7;
var friction = 3;
*/
// Associate view controls with elements.
var controls = viewer.controls();
controls.enableMethodGroup('arrowKeys');
/*
controls.registerMethod('upElement', new Marzipano.ElementPressControlMethod(viewUpElement, 'y', -velocity, friction), true);
controls.registerMethod('downElement', new Marzipano.ElementPressControlMethod(viewDownElement, 'y', velocity, friction), true);
controls.registerMethod('leftElement', new Marzipano.ElementPressControlMethod(viewLeftElement, 'x', -velocity, friction), true);
controls.registerMethod('rightElement', new Marzipano.ElementPressControlMethod(viewRightElement, 'x', velocity, friction), true);
controls.registerMethod('inElement', new Marzipano.ElementPressControlMethod(viewInElement, 'zoom', -velocity, friction), true);
controls.registerMethod('outElement', new Marzipano.ElementPressControlMethod(viewOutElement, 'zoom', velocity, friction), true);
*/
controls.registerMethod('deviceOrientation', deviceOrientationControlMethod);
//controls.enableMethod('deviceOrientation');


viewer.controls().methods().mouseViewQtvr.instance._opts.speed = 5;





var enabled = true;
var toggleElement = document.getElementById('gyroscope');



function enablegyro() {

    controls.enableMethod('deviceOrientation');
    enabled = true;

}

function disablegyro() {
    controls.disableMethod('deviceOrientation');
    enabled = false;

}

function togglegyro() {

    if (enabled) {
        disablegyro();
        $(".iconbutton#gyroscope i").removeClass('icon-gyro1');
        $(".iconbutton#gyroscope i").addClass('icon-gyro0');
        $(".iconbutton#gyroscope").set
    } else {
        $(".iconbutton#gyroscope i").addClass('icon-gyro1');
        $(".iconbutton#gyroscope i").removeClass('icon-gyro0');
        enablegyro();
    }

}


setDefContextItems();
var enabledrag = true;

function setDefContextItems() {
    if (params && params.debug) {

        items = { "qvr": { name: "Drag/Qtvr", icon: "fa-edit" } };

        if (params.returnurl) {

            items["return"] = { name: "Terug naar CMS", icon: "fa-beer" };
        }

    } else {
        items = {
            "qvr": { name: "Drag", icon: "fa-edit" }
        };
    }


}

function toggledrag() {

    if (enabledrag) {
        enableqvt();
    } else {
        enabledrg();
    }

}

function enabledrg() {

    enabledrag = true;

    $("#invertmouse").removeClass('qtvr');
    $("#invertmouse").addClass('drag');

    controls.disableMethod('mouseViewQtvr');
    controls.enableMethod('mouseViewDrag');
    items = {
        "qvr": { name: "Drag", icon: "fa-edit" }
    };

}

function enableqvt() {

    enabledrag = false;
    $("#invertmouse").removeClass('drag');
    $("#invertmouse").addClass('qtvr');

    controls.disableMethod('mouseViewDrag');
    controls.enableMethod('mouseViewQtvr');
    items = {
        "qvr": { name: "Qtvr", icon: "fa-edit" }
    };
}



$(function() {

    $.contextMenu({
        selector: '.multiple-scenes2',
        build: function($triggerElement, e) {
            return {
                callback: function(key, options) {
                    var m = "clicked: " + key;
                    if (key == 'qvr') { toggledrag(); } else {

                        $('#infohotspot').hide();
                        $('#hyperhotspot').hide();
                        $('#imagevideohotspot').hide();

                        if (key == 'addinfohotspot') {
                            $('#infohotspot').show();

                            $('#hotspotinput').show();
                        } else {
                            if (key == 'addvideohotspot') {
                                document.getElementById("video").setAttribute('value', true);
                                $('#imagevideohotspot').show();
                                $('#hotspotinput').show();
                            } else {
                                if (key == 'addhyperhotspot') {
                                    $('#hyperhotspot').show();
                                    $('#hotspotinput').show();
                                } else {
                                    if (key == 'addimagehotspot') {
                                        document.getElementById("video").setAttribute('value', false);
                                        $('#imagevideohotspot').show();
                                        $('#hotspotinput').show();
                                    } else {
                                        if (key == "return") {
                                            window.location.href = params.returnurl;
                                            $('#hotspotinput').show();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    window.console && console.log(m);
                },
                items: items
            };
        }
    });




});



function sanitize(s) {
    return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
}

$("#pano").click(function(event) {
    var params = currentURL.extract();


    if (params && params.debug) {
        var view = curscene.marzipanoObject.view(); // get the scene's
        // view
        // Get the view values

        var yaw = view.yaw();
        var pitch = view.pitch();
        $("#debugcenter").show();
        var index = scenes.indexOf(curscene);

        $("#pano").attr('title', 'yaw:' + view.yaw() + ' pitch:' + view.pitch() + 'fov: ' + view.fov());
        console.log('yaw:' + view.yaw() + ' pitch:' + view.pitch() + 'fov: ' + view.fov());
        var link = window.location.protocol + "//" + window.location.host + location.pathname + "?id=" + index + "&yaw=" + view.yaw() + "&pitch=" + view.pitch() + "&fov=" + view.fov();
        $("#debug").show();
        $("#debug-link").show();
        $("#debug-link").attr('href', link).text(link)
        $("#debug").text('yaw:' + view.yaw() + ' pitch:' + view.pitch() + 'fov: ' + view.fov());
    }
});

$('.modal ').on('hide.bs.modal', function(e) {

    if ($(this).find('video').length > 0) {
        $(this).find('video')[0].pause();
        $(this).find('.videomodal').addClass('init');
    }



});


function switchSceneHotspot(scene, hotspot) {
    $(".info").hide();
    $(".info p").hide();
    $("#hideinfo").hide();
    $("#sceneList").removeClass('show');
    $("a#showScene").removeClass('hidden');
    $("a#hideScene").addClass('hidden');


    var previndex = scenes.indexOf(curscene)
    var elements = document.getElementsByClassName('video-' + previndex);

    var n = elements.length;
    for (var i = 0; i < n; i++) {
        var video = elements[i];
        if (video != null) {
            // video.pause();
        }
    }

    elements = document.getElementsByClassName('video-99');

    var n = elements.length;
    for (var i = 0; i < n; i++) {
        var video = elements[i];
        if (video != null) {
            //    video.pause();
        }
    }
    var first = false;
    if (curscene == null) {
        first = true;
    }
    stopAutorotate();
    var index = scenes.indexOf(scene);

    console.log('index' + index);


    elements = document.getElementsByClassName('video-' + index);

    n = elements.length;
    for (var i = 0; i < n; i++) {
        var video = elements[i];
        if (video != null) {
            //    video.pause();
        }
        if (video != null) {
            video.currentTime = 0;
            setTimeout(function() {


                if (index == scenes.indexOf(curscene)) {
                    //  video.play();
                    //   video.muted = "muted";
                }

            }, 1000);

        }
    }

    var destinationViewParameters = null;
    var parameters = {
        yaw: scene.data.initialViewParameters.yaw,
        pitch: scene.data.initialViewParameters.pitch
    };

    var options = {
        transitionDuration: 20
    }


    //
    //    if (curscene != null) {
    //        var name = 'hotspotViewParameters_' + curscene.data.id;
    //
    //
    //
    //
    //        if (hotspot == true) {
    //            registerclick('Hotspot', sanitize(scene.data.name));
    //        }
    //
    //
    //        if (hotspot == true && scene.data[name] != 'undefined' && scene.data[name] != null) {
    //
    //            parameters = scene.data[name];
    //        } else {
    //            if (hotspot) {
    //
    //                var view = curscene.marzipanoObject.view();
    //                var parameters = {
    //                    yaw: view.yaw(),
    //                    pitch: view.pitch(),
    //                    fov: view.fov()
    //                };
    //            } else {
    //                parameters = scene.data.initialViewParameters;
    //            }
    //
    //        }
    //
    //
    //
    //
    //
    //    }

    var options = {
        transitionDuration: 0
    }



    scene.marzipanoObject.lookTo(parameters, options);
    scene.marzipanoObject.switchTo();


    scene.marzipanoObject.addEventListener('viewChange', function(a, b) {


        var hotspots = scene.marzipanoObject._hotspotContainer._hotspots;

        for (var key in hotspots) {

            try {


                var difyaw = hotspots[key]._params.yaw - scene.marzipanoObject._view._yaw;

                if (difyaw < 0) {
                    difyaw = difyaw * -1;
                }

                if (difyaw < 1 || difyaw > 6.1) {

                    hotspots[key]._domElement.classList.add('showtip');
                } else {
                    hotspots[key]._domElement.classList.remove('showtip');
                }


            } catch (err) {
                console.log(err);
            }


        }



    });

    startAutorotate();
    updateSceneName(scene);
    updateSceneList(scene);
    curscene = scene;
    $('#form-div h1').text(scene.data.name);
    var index = scenes.indexOf(scene);
    if (typeof $carousel != 'undefined') {
        $carousel.flickity('select', index);

    }

    console.log(curscene.data.id);

    var index = scenes.indexOf(scene);

    console.log('index' + index);
    if (index > 0) {
        setTimeout(function() {
            $('#info-' + curscene.data.id).modal('show');
        }, 1000)
    }



}

function switchScene(scene) {
    switchSceneHotspot(scene, false);

}


function registerclick(categorie, type) {
    try {


        gtag('event', categorie, {
            'event_category': type,
            'event_label': type
        });

    } catch (err) {
        console.error(err);
    }
}


function updateSceneName(scene) {
    sceneNameElement.innerHTML = sanitize(scene.data.name);

    try {

        gtag('config', analytics, {
            'page_title': sanitize(scene.data.name)
        });


    } catch (err) {
        console.error(err);
    }
}

function updateSceneList(scene) {
    for (var i = 0; i < sceneElements.length; i++) {
        var el = sceneElements[i];
        if (el.getAttribute('data-id') === scene.data.id) {
            el.classList.add('current');
        } else {
            el.classList.remove('current');
        }
    }
}

function showSceneList() {
    sceneListElement.classList.add('enabled');
    sceneListToggleElement.classList.add('enabled');
}

function hideSceneList() {
    sceneListElement.classList.remove('enabled');
    sceneListToggleElement.classList.remove('enabled');
}

function toggleSceneList() {
    sceneListElement.classList.toggle('enabled');
    sceneListToggleElement.classList.toggle('enabled');
}

function startAutorotate() {
    if (!autorotateToggleElement.classList.contains('enabled')) {
        return;
    }

    setTimeout(function() {
        viewer.startMovement(autorotate);
        viewer.setIdleMovement(12000, autorotate);
    }, 3000);

}

function stopAutorotate() {
    autorotateToggleElement.classList.remove('enabled');
    viewer.stopMovement();
    viewer.setIdleMovement(Infinity);
}

function toggleAutorotate() {
    if (autorotateToggleElement.classList.contains('enabled')) {
        autorotateToggleElement.classList.remove('enabled');
        stopAutorotate();
    } else {
        autorotateToggleElement.classList.add('enabled');
        startAutorotate();
    }
}

function toggleFullscreen() {
    screenfull.toggle();

    if (screenfull.isFullscreen) {
        fullscreenToggleElement.classList.add('enabled');
    } else {
        fullscreenToggleElement.classList.remove('enabled');
    }
}

function createPulseHotspotElement(hotspot) {

    // Create wrapper element to hold icon and tooltip.
    var wrapper = document.createElement('div');
    wrapper.setAttribute("id", hotspot.id);
    wrapper.classList.add('hotspot');
    wrapper.classList.add('pulse-hotspot');

    // Create image element.
    //	var dot = document.createElement('div');
    //	dot.classList.add('dot');
    var pulse = document.createElement('pulse');
    pulse.classList.add('pulse');

    var icon = document.createElement('img');
    icon.src = 'img/link.png';
    icon.classList.add('link-hotspot-icon');

    // Set rotation transform.

    var transformProperties = ['-ms-transform', '-webkit-transform',
        'transform'
    ];
    for (var i = 0; i < transformProperties.length; i++) {
        var property = transformProperties[i];
        icon.style[property] = 'rotate(' + hotspot.rotation + 'rad)';
    }





    stopTouchAndScrollEventPropagation(pulse);
    //	wrapper.appendChild(dot);
    wrapper.appendChild(pulse);
    // wrapper.appendChild(tooltip);

    // Prevent touch and scroll events from reaching the parent element.
    // This prevents the view control logic from interfering with the
    // hotspot.
    stopTouchAndScrollEventPropagation(wrapper);
    return wrapper;
}


function createLinkHotspotElement(hotspot) {

    var targetname = findSceneDataById(hotspot.target).name;

    var targetid = targetname.replace(/ /g, '_');
    // Create wrapper element to hold icon and tooltip.
    var wrapper = document.createElement('div');
    wrapper.classList.add('hotspot');
    wrapper.classList.add('link-hotspot');
    wrapper.setAttribute("id", targetid);
    // Create image element.
    var dot = document.createElement('div');
    dot.classList.add('dot');
    var pulse = document.createElement('pulse');
    pulse.classList.add('pulse');

    var icon = document.createElement('img');
    icon.src = 'img/link.png';
    icon.classList.add('link-hotspot-icon');

    // Set rotation transform.

    var transformProperties = ['-ms-transform', '-webkit-transform',
        'transform'
    ];
    for (var i = 0; i < transformProperties.length; i++) {
        var property = transformProperties[i];
        icon.style[property] = 'rotate(' + hotspot.rotation + 'rad)';
    }

    // Add click event handler.
    wrapper.addEventListener('click', function() {
        switchSceneHotspot(findSceneById(hotspot.target), true);

    });
    //	wrapper.setAttribute('title',findSceneDataById(hotspot.target).name);
    //	wrapper.setAttribute('data-placement','bottom');




    // Create tooltip element.
    var tooltip = document.createElement('div');
    tooltip.classList.add('hotspot-tooltip');
    tooltip.classList.add('link-hotspot-tooltip');
    tooltip.setAttribute("id", 'tooltip' + targetid);
    tooltip.classList.add('tooltip' + targetid);


    tooltip.innerHTML = targetname;

    stopTouchAndScrollEventPropagation(pulse);
    wrapper.appendChild(dot);
    wrapper.appendChild(pulse);
    wrapper.appendChild(tooltip);

    // Prevent touch and scroll events from reaching the parent element.
    // This prevents the view control logic from interfering with the
    // hotspot.
    stopTouchAndScrollEventPropagation(wrapper);


    return wrapper;
}

function createzoomFancyHotspotElement(hotspot) {
    // Create wrapper element to hold icon and tooltip.
    var wrapper = document.createElement('div');
    wrapper.classList.add('hotspot');
    wrapper.classList.add('zoom-hotspot');

    // Create hotspot/tooltip header.
    var header = document.createElement('div');
    header.classList.add('zoom-hotspot-header');

    // Create image element.
    var iconWrapper = document.createElement('div');
    iconWrapper.classList.add('zoom-hotspot-icon-wrapper');
    var icon = document.createElement('i');

    icon.classList.add('fa');
    icon.classList.add('fa-search-plus');

    icon.classList.add('fa-2x');
    iconWrapper.appendChild(icon);

    // Create title element.

    var images = new Array;
    images[0] = 'img/kantinewand/kantine_01.png';


    // Construct header element.
    header.appendChild(iconWrapper);



    // Place header and text into wrapper element.
    wrapper.appendChild(header);


    // Create a modal for the hotspot content to appear on mobile mode.
    var modal = document.createElement('div');
    modal.innerHTML = wrapper.innerHTML;
    modal.classList.add('info-hotspot-modal');
    document.body.appendChild(modal);

    var toggle = function() {
        $.fancybox.open([

            'img/kantinewand/kantine_01.png'


        ], {
            padding: 0,
            index: hotspot.index

        })

    };

    // Show content when hotspot is clicked.
    wrapper.querySelector('.zoom-hotspot-header').addEventListener('click',
        toggle);



    // Prevent touch and scroll events from reaching the parent element.
    // This prevents the view control logic from interfering with the
    // hotspot.
    stopTouchAndScrollEventPropagation(wrapper);

    return wrapper;
}

function createZoomHotspotElement(hotspot) {

    // Create wrapper element to hold icon and tooltip.
    var wrapper = document.createElement('div');
    wrapper.classList.add('hotspot');
    wrapper.classList.add('zoom-hotspot');

    // Create hotspot/tooltip header.
    var header = document.createElement('div');
    header.classList.add('zoom-hotspot-header');

    // Create image element.
    var iconWrapper = document.createElement('div');
    iconWrapper.classList.add('zoom-hotspot-icon-wrapper');
    var icon = document.createElement('i');

    icon.classList.add('fa');
    icon.classList.add('fa-search-plus');

    icon.classList.add('fa-2x');
    iconWrapper.appendChild(icon);

    // Create title element.





    // Construct header element.
    header.appendChild(iconWrapper);



    // Place header and text into wrapper element.
    wrapper.appendChild(header);


    // Create a modal for the hotspot content to appear on mobile mode.
    var modal = document.createElement('div');
    modal.innerHTML = wrapper.innerHTML;
    modal.classList.add('info-hotspot-modal');
    document.body.appendChild(modal);

    var toggle = function() {
        $.fancybox.open([{
            href: 'img/' + hotspot.img
        }], {
            padding: 0
        })

    };

    // Show content when hotspot is clicked.
    wrapper.querySelector('.zoom-hotspot-header').addEventListener('click',
        toggle);



    // Prevent touch and scroll events from reaching the parent element.
    // This prevents the view control logic from interfering with the
    // hotspot.
    stopTouchAndScrollEventPropagation(wrapper);

    return wrapper;
}




function createImageElement(hotspot) {

    // Create wrapper element to hold icon and tooltip.
    var container = document.createElement('div');
    container.classList.add('hotspot');
    container.classList.add('image-hotspot');
    var image = $('<img />', {

        src: hotspot.url,
        id: hotspot.id,
        width: hotspot.width + "px",
        height: hotspot.height + "px",

    });



    image.appendTo(container);


    // HTML sources.


    return container;
}

function createVideoElement(hotspot) {

    // Create wrapper element to hold icon and tooltip.
    var container = document.createElement('div');
    container.classList.add('hotspot');
    container.classList.add('video-hotspot');
    container.classList.add('init');
    /*var video = $('<video />', {
        'class': 'video-' + hotspot.id,
        src: hotspot.url,
        'controls': hotspot.controls,
        'webkit-playsinline': 'webkit-playsinline',
        'playsinline': 'playsinline',
        type: 'video/mp4',
        width: hotspot.width + "px",
        poster: hotspot.poster,
        height: hotspot.height + "px",
        preload: "none",
        autoplay: false,
        loop: hotspot.loop
    });*/

    var video = $('<img />', {

        src: hotspot.poster,
        id: hotspot.id,
        width: hotspot.width + "px",
        height: hotspot.height + "px",

    });



    video.appendTo(container);

    var button = $('<div />', {

        'class': 'playpause'

    });


    button.appendTo(container);



    var popup = function() {

        var videoElement = document.getElementById('smallscreenvideo');


        var source = document.createElement('source');





        source.setAttribute('src', hotspot.url);



        videoElement.appendChild(source);

        videoElement.currentTime = 0;
        videoElement.play();




        $("#settingspull").hide();

        hideActions();


        $("#settingspull").fadeOut(1000);

        $("#sceneList").fadeOut(1000);

        // $("#scenelistbar").fadeOut(1000);



        $("#media-popupwrapper").show();


        $("#smallscreenvideo").bind("ended", function() {
            stoppopupvideo();




        });


        $("#smallscreenvideo").on("ended", function() {

            stoppopupvideo();



        });

        $("#media-popupwrapper").bind("click", function() {
            stoppopupvideo();
            videoElement.stop();
        });

        $("#smallscreenvideo").bind("click", function() {
            stoppopupvideo();


        });


    };

    // Show content when hotspot is clicked.
    container.addEventListener('click',
        popup);


    return container;
}


function stoppopupvideo() {
    $('#media-popupwrapper').hide();

    var videoElement = document.getElementById('smallscreenvideo');
    videoElement.pause();

    $("#settingspull").fadeIn(1000);

    $("#sceneList").fadeIn(1000);

    // $("#scenelistbar").fadeIn(1000);

    movecontrols();



}



function registervideoclick(id) {

    try {

        gtag('event', 'Video Afspelen', {
            'event_category': id,
            'event_label': id
        });

    } catch (err) {
        console.error(err);
    }
}


$("a#mode").click(function() {

    var scene;
    var index = scenes.indexOf(curscene);
    if (curscene.data.id.indexOf('a', curscene.data.id.length - 1) !== -1) {
        index = index + 1;
        $('body').removeClass('bday');
        $('body').addClass('bnight');
        $(".day").hide();
        $(".night").show();
        //	  $("#mode.iconbutton").removeClass('fa-moon-o');
        //	  $("#mode.iconbutton").addClass('fa-sun-o');



    } else {
        index = index - 1;


        $('body').removeClass('bnight');
        $('body').addClass('bday');
        $(".night").hide();
        $(".day").show();
        //	  $("#mode.iconbutton").addClass('fa-moon-o');
        //	  $("#mode.iconbutton").removeClass('fa-sun-o');




    }




    scene = scenes[index];
    var view = curscene.marzipanoObject.view();

    switchScene(scene);
    var destinationViewParameters = {
        yaw: view.yaw(),
        pitch: view.pitch(),
        fov: view.fov()

    };
    var options = {
        transitionDuration: 1
    }

    scene.marzipanoObject.lookTo(destinationViewParameters, options);



});



function createInfoHotspotModal(hotspot) {

    var modalwrapper = document.createElement('div');
    modalwrapper.classList.add('modal');
    modalwrapper.classList.add('fade');
    if (hotspot.id != null) {
        modalwrapper.setAttribute("id", hotspot.id);
    } else {
        modalwrapper.setAttribute("id", 'modal' + '_' + hotspot.title.replace(/ /g, '_'));
    }

    modalwrapper.setAttribute('role', 'dialog');

    var modaldialog = document.createElement('div');
    modaldialog.classList.add('modal-dialog');
    /* modaldialog.classList.add('fullscreen'); */
    var modalcontent = document.createElement('div');
    modalcontent.classList.add('modal-content');
    var modalheader = document.createElement('div');

    modalheader.classList.add('modal-header');
    var modaltitle = document.createElement('h4');
    modaltitle.innerHTML = hotspot.title;


    modaltitle.innerHTML = '<span class="nl">' + hotspot.title.trim() + '</span>';




    var closebutton = document.createElement('button');
    closebutton.classList.add('close');
    closebutton.classList.add('modernclose');
    closebutton.setAttribute("data-dismiss", "modal");
    closebutton.innerHTML = "x";

    var closeclassicbutton = document.createElement('button');
    closeclassicbutton.classList.add('close');
    closeclassicbutton.classList.add('classicclose');
    closeclassicbutton.setAttribute("data-dismiss", "modal");
    closeclassicbutton.innerHTML = "x";
    var modalbody = document.createElement('div');
    modalbody.classList.add('modal-body');

    modalheader.appendChild(closeclassicbutton);

    var modalbodytext = document.createElement('div');
    modalbodytext.classList.add('modal-body-text');

    var modaltext = document.createElement('p');

    modaltext.innerHTML = '<div class="nl">' + hotspot.text +
        '</div>';




    modalbody.appendChild(closebutton);
    modalbody.appendChild(modalbodytext);

    // modalbodytext.appendChild(modaltitle);
    modalbodytext.appendChild(modaltext);
    var modalfooter = document.createElement('div');



    modalheader.appendChild(modaltitle);
    //modalheader.appendChild(closebutton);
    modalcontent.appendChild(modalheader);

    modalcontent.appendChild(modalbody);

    modalcontent.appendChild(modalfooter);
    modaldialog.appendChild(modalcontent);
    modalwrapper.appendChild(modaldialog);

    var body = document.querySelector('#modal');
    body.appendChild(modalwrapper);

}



function createInfoHotspotElement(hotspot) {

    // Create wrapper element to hold icon and tooltip.
    var wrapper = document.createElement('div');
    wrapper.classList.add('hotspot');
    wrapper.classList.add('info-hotspot');
    if (typeof hotspot.class != 'undefined') {
        wrapper.classList.add(hotspot.class);
    }

    // Create hotspot/tooltip header.
    var header = document.createElement('div');
    header.classList.add('info-hotspot-header');
    // header.setAttribute('title',hotspot.title);
    // header.setAttribute('data-placement','left');
    // Create image element.

    var iconWrapper = document.createElement('div');
    iconWrapper.classList.add('zoom-hotspot-icon-wrapper');
    var icon = document.createElement('i');
    // header.setAttribute('id', hotspot.id);
    icon.classList.add('fa');
    if (typeof hotspot.class != 'undefined') {
        if (hotspot.class == 'videohotspot') {
            icon.classList.add('fa-video-camera');
        } else if (hotspot.class == 'weetjehotspot') {
            icon.classList.add('fa-question')
        } else {
            icon.classList.add('fa-info');
        }
    } else {
        icon.classList.add('fa-info');
    }


    icon.classList.add('fa-25x');
    iconWrapper.appendChild(icon);



    // Create title element.
    var titleWrapper = document.createElement('div');
    titleWrapper.classList.add('info-hotspot-title-wrapper');
    var title = document.createElement('div');
    title.classList.add('info-hotspot-title');
    title.innerHTML = "<span class='nl'>" + hotspot.title + "</span>";

    titleWrapper.appendChild(title);



    // Construct header element.
    header.appendChild(iconWrapper);
    header.appendChild(titleWrapper);

    // Create text element.
    var text = document.createElement('div');
    text.classList.add('info-hotspot-text');
    // text.innerHTML = hotspot.text;

    // Place header and text into wrapper element.
    wrapper.appendChild(header);
    wrapper.appendChild(text);

    // Create a modal for the hotspot content to appear on mobile mode.



    var modal = document.createElement('div');
    modal.innerHTML = wrapper.innerHTML;
    modal.classList.add('info-hotspot-modal');
    document.body.appendChild(modal);


    var toggle = function() {

        if (hotspot.refmodal != null) {
            $('#' + hotspot.refmodal).modal('show');

            setTimeout(function() {
                $('#grid_' + hotspot.refmodal).grid('reload');

            }, 1000);



            setTimeout(function() {
                $('#grid_' + hotspot.refmodal).grid('reload');

            }, 1500);


        } else {
            if (hotspot.id != null) {
                $('#' + hotspot.id).modal('show');
            } else {
                var title = hotspot.title.replace(/ /g, '_');
                $('#modal' + '_' + title).modal('show');
            }



        }

        gtag('config', analytics, {
            'page_title': 'Hotspot ' + hotspot.title
        });



    };

    // Show content when hotspot is clicked.
    wrapper.querySelector('.info-hotspot-header').addEventListener('click', toggle);

    // Hide content when close icon is clicked.
    // modal.querySelector('.info-hotspot-close-wrapper').addEventListener('click',
    // toggle);

    // Prevent touch and scroll events from reaching the parent element.
    // This prevents the view control logic from interfering with the hotspot.
    stopTouchAndScrollEventPropagation(wrapper);

    return wrapper;
}

// Prevent touch and scroll events from reaching the parent element.
function stopTouchAndScrollEventPropagation(element, eventList) {
    var eventList = ['touchstart', 'touchmove', 'touchend', 'touchcancel',
        'wheel', 'mousewheel'
    ];
    for (var i = 0; i < eventList.length; i++) {
        element.addEventListener(eventList[i], function(event) {
            event.stopPropagation();
        });
    }
}

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

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