console.log('roomvo-script.js is loaded');


jQuery(document).ready(function($) {
    console.log(`Log: 'roomvo-script.js' is started`);

    // ---------------------------------------------------------------------------- ready ------------------------------------------------------------------------------------

    if (typeof click_touch == 'undefined') debugger

    // -----------
    // Sfeerfoto
    // -----------

    // ------------------------------
    // opening Sfeerfoto float panel
    // ------------------------------

    invoke_listener.floating_open_sfeerfoto = function(action) {
        if (action == "off") {
            $(".m_sfeerfoto").off(click_touch);
            console.log("event handler is removed");

            // event.preventDefault();
            // event.stopPropagation();

            return;
        }

        console.log('originally was $(".m_sfeerfoto").on(click_touch, {');

        $(".m_sfeerfoto").off(click_touch);
        $(".m_sfeerfoto").on(click_touch, {
            object_passed: "sfeerfoto menu is clicked",
        }, public_function.open_sfeer);
       
    }
    ;

    public_function.open_sfeer = function(e) {
        console.log(`Log: [open_sfeer] function is called`);
        // debugger

        if (typeof e == "object" && !e.originalEvent) {
            console.log("Dynamic triggering");
        }

        console.log("Log: group closing");
        public_function.floating_close_qr_favourite();
        public_function.floating_close_showsaved();
        public_function.floating_close_search_panel();

        public_function.close_roomselect();
        // public_function.close_sfeer();

        (async function asyncCall(e) {
            var result = await window.slider_upper({
                state: "close",
                direction: "wall",
            });


            $(".floating_wrapper.ft_sfeerfoto").removeClass("hide_feature_panel").removeClass("initial_ft_sfeerfoto");
            // m2_ajax_get_all_styles();   roomvo


            m2_ajax_get_style_colors();
        }
        )(e);

    }
    ;

    invoke_listener.floating_open_sfeerfoto();
    // invoke_listener.floating_open_qr_favourite();

    // ------------------------------
    // closing Sfeerfoto float panel
    // ------------------------------

    invoke_listener.floating_close_sfeerfoto = function(action) {
        if (action == "off") {
            $(".ft_sfeerfoto .floating_close_main").off(click_touch);
            console.log("event handler is removed");

            // event.preventDefault();
            // event.stopPropagation();

            return;
        }

        $(".ft_sfeerfoto .floating_close_main").off(click_touch);
        $(".ft_sfeerfoto .floating_close_main").on(click_touch, {
            object_passed: "sfeerfoto close is clicked",
        }, public_function.close_sfeer);
    };

    // invoke_listener.floating_close_sfeerfoto();

    public_function.close_sfeer = function(e) {
        console.log(`Log: [close_sfeer] function is called`);

        if (typeof e == "object" && !e.originalEvent) {
            console.log("Dynamic triggering");
        }

        $(".floating_wrapper.ft_sfeerfoto").addClass("hide_feature_panel");
    };


    invoke_listener.floating_close_sfeerfoto();

    // ----------------------------------------------------
    // Clicking on TAB (Multiple TAB Float Panel if exist)
    // ----------------------------------------------------
    invoke_listener.floating_tab_sfeerfoto = function(action) {
        if (action == "off") {
            $(".ft_sfeerfoto .floating_tab").off(click_touch);
            console.log("event handler is removed");
            // event.preventDefault();
            // event.stopPropagation();
            return;
        }

        $(".ft_sfeerfoto .floating_tab").off(click_touch);
        $(".ft_sfeerfoto .floating_tab").on(click_touch, function(e) {
            console.log(`Log: ft_sfeerfoto Tab is clicked, showing corresponding content if exist`);

            var is_Physical = e.hasOwnProperty("originalEvent") && e.originalEvent.hasOwnProperty("isTrusted") && e.originalEvent.isTrusted;
            if (is_Physical)
                registered_key("ft_sfeerfoto");

            var this_index = $(this).index();

            $(this).siblings().removeClass("floating_tab_active");
            $(this).addClass("floating_tab_active");

            $(this).closest(".floating_wrapper").find(".floating_content").removeClass("higher_z");
            $(this).closest(".floating_wrapper").find(".floating_content").eq(this_index).addClass("higher_z");
        });
    }
    ;

    // invoke_listener.floating_tab_sfeerfoto();
    invoke_listener.floating_tab_sfeerfoto();

    // ------------------------------------------------------------------
    // Sfeerfoto Radio select , should be invoked after ant dom creation, button clicked inspiratie_zoek
    // ------------------------------------------------------------------

    invoke_listener.sfeer_style_select = function(action) {
        if (action == "off") {
            // $(".get_all_styles_container  input").off(click_touch);
            $(".inspiratie_zoek  input").off(click_touch);
            console.log("event handler is removed");
            // event.preventDefault();
            // event.stopPropagation();
            return;
        }



        // $(".get_all_styles_container input").off("change");
        // $(".get_all_styles_container input").on("change", {
            // change_event: ".get_all_styles_container input",
        // }, public_function.fn_sfeer_style_select);
        //will send event, event.data, this

        // $(".get_style_colors_container select#styles-colors").off("change");
        // $(".get_style_colors_container select#styles-colors").on("change", {


        $(".inspiratie_zoek").off(click_touch);
        $(".inspiratie_zoek").on(click_touch, {
            // change_event: ".get_style_colors_container select#styles-colors ",
            change_event: ".inspiratie_zoek",
        }, public_function.fn_sfeer_style_select);
    
    }
    ;

    // invoke_listener.sfeer_style_select();

    public_function.fn_sfeer_style_select = function(e) {
        console.log(`Log: [fn_sfeer_style_select] function is called`);


        var is_Physical = e && e.hasOwnProperty("originalEvent") && e.originalEvent.hasOwnProperty("isTrusted") && e.originalEvent.isTrusted;
        if (is_Physical){
            registered_key("fn_sfeer_style_select");
        }


        console.log(`Log: Change sfeerfoto event = ${e.data.change_event}`);



        console.log('trigger is_Physical =  ', is_Physical);
        console.log(click_touch);
        console.log(e.target);
        // alert(click_touch);
 

        if (!is_Physical){

            console.log("returned => not physical");
            return;

                                // var selected_style = $(".get_all_styles_container > .sfeer_style_wraper input:checked").val();
                                // var selected_color = $(".get_style_colors_container select#styles-colors").val();
        }
        var selected_color = $("ul.inspiratie_div_color_ul input:checked").val();

         
        // id_query = 'ProductCategoryId=V&AtmosphereId='
        // id_query = 'ProductCategoryId=V&AtmosphereId=' + selected_style;

        // id_query = "ProductCategoryId=W&AtmosphereId=" + selected_style;

        if (!selected_color){
            // id_query += "&ColorId=" + selected_color;
            selected_color = 'Grijs';

            $('input[name=atmosphere_radio_input][value=Grijs]').prop('checked', true);



             
        }

        // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // roomvo sfeer
        // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


        // console.log('sfeer style search roomvo id_query change');
        console.log('sfeer style search roomvo zoek button clicked');
        console.log(selected_color);

        id_query = "ProductCategoryId=W&AtmosphereId=CLASSIC&AtmosphereId=MINIMALISTISCH&AtmosphereId=MODERN&AtmosphereId=RURAL&ColorId=" + selected_color;


        // if (styleColor != '') {
        //     var id_query = 'ProductCategoryId=V&AtmosphereId=' + style + '&ColorId=' + styleColor;
        //     $(".search-choices-wall .color").text(style);
        //     $(".search-choices-wall .size").text(styleColor);
        // } else {
        //     var id_query = 'ProductCategoryId=V&AtmosphereId=' + style + '&LookId=' + styleLook;
        //     $(".search-choices-wall .color").text(style);
        //     $(".search-choices-wall .size").text(styleLook);
        // }

        console.log(id_query);
        m2_GetInspirationbyQuery(id_query);
    }
    ;

    invoke_listener.sfeer_style_select();



    // --------------------------------------------------------------------------------------------------- moved -------------------------------------------------------------------------------------------


    function m2_ajax_get_all_styles() {

        console.log(`Log: [m2_ajax_get_all_styles()] is called`);

        $("#loading").css({
            "visibility": "visible",
            "display": "block"
        });


        // var selected_style  = $(".get_all_styles_container > .sfeer_style_wraper input:checked"); 
        var current_styles_container_html = $('.get_all_styles_container').html().trim();
        // var selected_style  = $(".get_all_styles_container > .sfeer_style_wraper input:checked").val();


        if (current_styles_container_html) {
            console.log(`Log:  already sfeer styles html exists , then will return`);
            return;
        }


        // if (current_styles_container_html && selected_style) {
        //     console.log(`Log:  already sfeer styles html exists and os checked, then will return`);
        //     return; 
        // }


        var query = "";
        // type_selected = 'W';
        // type_selected = settings.tileType;
        // if (type_selected == 'qrcode') {
        //     type_selected = 'V';
        // }

        // query = "?ProductCategoryId=" + type_selected;


        // var tileType = $(".filter-block-item.type.active").data('value');
        // if (tileType == "W" || tileType == "wall") {
        //     var customTileType = settings.customTileType;
        //     query = "?ProductCategoryId=" + customTileType;
        // }

        // var currentTileType = settings.tileType;

        // abort_all_ajax();

        jQuery.support.cors = true;
        $.ajax({
            url: service_url + 'Master/Atmospheres' + query,
            type: 'GET',
            dataType: 'json',
            passObject: { 'query': service_url + 'Master/Atmospheres' + query },

            beforeSend: function(xhr) {
                
                abort_all_ajax('Master__Atmospheres');  // (2) Cancel only Master/Atmospheres  requests if requestType is defined
                xhr.requestType = 'Master__Atmospheres';

                xhr.setRequestHeader('Authorization', apikey);
                global_xhrPool.push(xhr);
                loading('on');

            },


            success: function(data) {

                console.log(`Log: Received sfeer styles for Query = "${this.passObject.query}" =`);
                console.dir(data);
                loading('off');



                response_get_all_styles(data, this.passObject);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                if (jqXHR.readyState < 4) {
                    return true;
                }

                $("#busy").remove();
                loading('off');

                // $().toastmessage('showErrorToast', "Stijl niet gevonden");

            }
        });
    }

    function response_get_all_styles(data, passObject) {
        $("#loading").css({
            "visibility": "hidden",
            "display": "none"
        });

        for (var i = 0; i < data.length; i++) {
            data[i]['AtmosphereId'] = data[i]['AtmosphereId'].trim();
            data[i]['AtmosphereName'] = data[i]['AtmosphereName'].trim();

        }


        populate_get_all_styles(data, passObject);
        // pagination($(".style-container"));
    }

    function populate_get_all_styles(data, passObject) {
        var styles_array = sortByKey(data, 'AtmosphereId');

        // if (!$('.style-container').is(':visible')) {
        //     return;
        // }
        $('.get_all_styles_container').html('');

        $.each(styles_array, function(i) {

            var div = $('<div/>')
                .addClass("sfeer_style_wraper")
                .data('value', styles_array[i]['AtmosphereId'])
                .appendTo('.get_all_styles_container');
            var span1 = $('<input type="radio" name="sfeerfoto_style" />')
                .addClass("sfeerfoto_style")
                .val(styles_array[i]['AtmosphereName'])
                .appendTo(div);
            var span1 = $('<span/>')
                .addClass("sfeerfoto_name")
                .text(styles_array[i]['AtmosphereName'])
                .appendTo(div);

        });
        // $(".style-container .style input").first().trigger('click');

        console.log(`Log: initialising invoke_listener.sfeer_style_select event After dynamic dom creation`);
        invoke_listener.sfeer_style_select();
        // debugger;

        var selected_style = $(".get_all_styles_container > .sfeer_style_wraper input:checked");

        if (!selected_style.length) {
            console.log(`Log: Default sfeer style is triggered`);
            // $(".get_all_styles_container > .sfeer_style_wraper input").first().prop('checked', true).trigger('change');
            $(".get_all_styles_container > .sfeer_style_wraper input").eq(0).prop('checked', true);

        }


        m2_ajax_get_style_colors();
    }


    // ----------------------------
    //  Sfeerforo: get_style_colors
    // ----------------------------


    function m2_ajax_get_style_colors() {
        // $(".styles-colors-container").html('');

        console.log('m2_ajax_get_style_colors() is called');


                        // var selected_style_object = $(".get_all_styles_container > .sfeer_style_wraper input:checked");
                        // var current_style_colores_html = $(".get_style_colors_container").html();

                        // debugger
                        // current_style_colores_html = current_style_colores_html.trim();

                        // if (!selected_style_object.length && current_style_colores_html) {
                        //  console.log(`Log: No sfeerstyle selected and already style html exists, then will return`);
                        //  // return;
                        // }


        $("#loading").css({
            "visibility": "visible",
            "display": "block"
        });

                    // var query = "";
        // type_selected = "W";


        // // styleLabel = $(".style-container .style input:checked").val();
        // selected_style = $(".get_all_styles_container  > .sfeer_style_wraper > input:checked").val(); 




        // if (query == "") bindmark = "?AtmosphereId=";
        // else bindmark = "&AtmosphereId=";
        // query = query + bindmark + styleLabel;

                            // var selected_style = selected_style_object.val();
                                // if (selected_style) query = "?AtmosphereId=" + selected_style;

        // "ProductCategoryId=W&AtmosphereId=CLASSIC&AtmosphereId=MINIMALISTISCH&AtmosphereId=MODERN&AtmosphereId=RURAL&ColorId=" + selected_color;
         query = "?AtmosphereId=CLASSIC&AtmosphereId=MINIMALISTISCH&AtmosphereId=MODERN&AtmosphereId=RURAL";
         // query = "?AtmosphereId=CLASSIC";



        // abort_all_ajax();
        // https://showroomtgnonline.azurewebsites.net/api/Master/Colors?AtmosphereId=CLASSIC

        var counter = 0;

        jQuery.support.cors = true;
        $.ajax({
            url: service_url + 'Master/Colors' + query,
            type: 'GET',
            dataType: 'json',
            passObject: { 'query': service_url + 'Master/Colors' + query },


            beforeSend: function(xhr) {

                abort_all_ajax('Master__Colors_m2_ajax_get_style_colors');  // (2) Cancel only Master/Colors  requests if requestType is defined
                xhr.requestType = 'Master__Colors_m2_ajax_get_style_colors';


                xhr.setRequestHeader('Authorization', apikey);
                global_xhrPool.push(xhr);
                loading('on');

            },

            success: function(data) {

                console.log(`Log: Received style colors for Query = "${this.passObject.query}" =`);
                console.dir(data);
                loading('off');


                // console.dir(this.passObject);

                // debugger


                // if (data.length === 0) $(".js_style_label_filter").removeClass("style_active_filter");
                response_get_style_colors(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                loading('off');

                ++counter;

                if (counter <=3) {

                    console.log("INSPIRATION , repeat loading colore , counter = " + counter);
                    m2_ajax_get_style_colors();
                    return;

                } else {
                    console.log("INSPIRATION Failed to load colores");
                }
                if (jqXHR.readyState < 4) {
                    return true;
                }

            }
        });
    }



    function response_get_style_colors(data) {
        $("#loading").css({
            "visibility": "hidden",
            "display": "none"
        });

        if (!data.length) {
            console.log(`Log: No sfeerstyle selected and already style html exists, then will return`);
            return;
        }
// debugger

        for (var i = 0; i < data.length; i++) {
            data[i]['ColorId'] = data[i]['ColorId'].trim();
            data[i]['ColorName'] = data[i]['ColorName'].trim();
            data[i]['NumberOfArticles'] = data[i]['NumberOfArticles'];
        }

        // -------------------
        // Removing old colors
        // -------------------
        // $(".get_style_colors_container select#styles-colors").remove();

        // $(".get_style_colors_container").append('<select id="styles-colors" />');
        // $(".get_style_colors_container select#styles-colors").append('<option value="">Kies een kleur</option>');


        // ---------------

        // <div class="inspiratie_option_container" >
            // <!-- <ul class="inspiratie_div_color_ul inspiratie_show_more_colors_flag"> -->
            // <ul class="inspiratie_div_color_ul">



        $(".inspiratie_option_container .inspiratie_div_color_ul").remove();
        $(".inspiratie_option_container").append('<ul class="inspiratie_div_color_ul"></ul>');


        populate_get_style_colors(data);
    }

    function populate_get_style_colors(data) {
        stylecolor = sortByKey(data, 'NumberOfArticles', -1, 'ColorId', 1);

        var colors = [];
        colors['Grijs'] = '#a8a8a8';
        colors['Beige'] = '#CFBDA5';
        colors['Bruin'] = '#8E583C';
        colors['Zwart'] = '#000000';
        colors['Wit'] = '#FFFFFF';
        colors['Antraciet'] = '#4B4E57';
        colors['Rood'] = '#910818';
        colors['Groen'] = '#8cc63f';
        colors['Geel'] = '#f2e200';
        colors['Blauw'] = '#0f83c6';
        colors['Oranje'] = '#f48200';
        colors['Paars'] = '#8c01b2';
        colors['Roze'] = '#E8CAC2';
        colors['Creme'] = '#FBF7EE';


        // old

        // <div class="get_style_colors_container">
        //  <select id="styles-colors">
        //      <option value="">Kies een kleur</option>
        //      <option value="Grijs">Grijs</option>
        //      ....
        //  </select>
        // </div>


        // $.each(stylecolor, function(i) {
            // if (stylecolor[i]['NumberOfArticles']) {
                // $(".get_style_colors_container select#styles-colors").append('<option value="' + stylecolor[i]['ColorName'] + '">' + stylecolor[i]['ColorName'] + '</option>');
            // }
        // });
     

        // new

        // <div class="inspiratie_option_container">
            //  <ul class="inspiratie_div_color_ul inspiratie_show_more_colors_flag">
            //      <li class="color total_color active" >
            //          <div class="color_icon all_colors_icn"></div><span class="color_name_list">Alle kleuren</span>
            //          <div class="div_radio"></div>
            //      </li>
            //      <li class="color grijs" >
            //          <div class="color_icon"></div><span class="color_name_list">Grijs</span>
            //          <div class="div_radio"></div>
            //      </li>
            //      ...sortedGroupedNewresult
            //  </ul>
        // </div>

        // invoke_listener.sfeer_style_select = function(action) {  <<--- listener
        // $(".get_style_colors_container select#styles-colors").on("change", {

 

            // Grijs
            // Beige
            // Wit
            // Bruin
            // Zwart
            // Antraciet
            // GREIGE/TAUPE
            // Groen
            // Blauw
            // MULTICOLOR
            // CREME/IVOOR
            // RVS/ALU/ZILVER
            // Rood
            // Roze
            // Oranje
            // Geel
            // BRONS/KOPER/GOUD



        $.each(stylecolor, function(i, el) {

            

            if (el.ColorName == "GREIGE/TAUPE" ) return;
            if (el.ColorName == "CREME/IVOOR" ) return;
            if (el.ColorName == "RVS/ALU/ZILVER" ) return;
            if (el.ColorName == "BRONS/KOPER/GOUD" ) return;


            if (stylecolor[i]['NumberOfArticles']) {
                $(".inspiratie_option_container .inspiratie_div_color_ul").append('<li class="color ' + stylecolor[i]['ColorName'] + '">' +  '<label class="atmosphere_color_label">' +      '<span class="color_name_list">'+ stylecolor[i]['ColorName'] +'</span>' + '<input type="radio" name="atmosphere_radio_input"   class="atmosphere_radio_input" value="' + stylecolor[i]['ColorName']  + '">' +  '</label>' + '</li>');


                // $(".inspiratie_option_container .inspiratie_div_color_ul").append('<li class="color ' + stylecolor[i]['ColorName'] + '">' +       '<span class="color_name_list">'+ stylecolor[i]['ColorName'] +'</span>' + '<input type="radio" name="atmosphere_radio_input"   class="atmosphere_radio_input" value="' + stylecolor[i]['ColorName']  + '">' +   '</li>');

            }
        });







        console.log(`Log: initialising invoke_listener.sfeer_style_select event After dynamic dom creation`);
        invoke_listener.sfeer_style_select();

    }


    // --------------------------------------------------------------------------------------------------- eof moved -------------------------------------------------------------------------------------------
















































    // ---------------------------------------------------------------------------------------------------  moved -------------------------------------------------------------------------------------------




    // ------------------------------- Inspirationby Gallery ----------------------------------

    function m2_GetInspirationbyQuery(Query) {
        // debugger
        console.log(`Log: [m2_GetInspirationbyQuery(${Query})] `);

        if (debug) {
            console.log('m2_GetInspirationbyQuery(Query) = ');
            console.log(Query);
        }

        $("#loading").css({
            "visibility": "visible",
            "display": "block"
        });

        // var patienceToast = $().toastmessage('showToast', {
        //     text: 'Een ogenblik geduld, de foto\'s worden geladen.',
        //     sticky: true,
        //     type: 'notice',
        //     stayTime: 6000
        // });

        ajax_url = service_url + 'Master/AtmospherePhotos?' + Query;
        jQuery.support.cors = true;

        // abort_all_ajax();

        $.ajax({
            url: ajax_url,
            type: 'GET',
            dataType: 'json',
            beforeSend: function(xhr) {

                abort_all_ajax('Master__AtmospherePhotos_m2_GetInspirationbyQuery');  // (2) Cancel only Master/AtmospherePhotos  requests if requestType is defined
                xhr.requestType = 'Master__AtmospherePhotos_m2_GetInspirationbyQuery';




                xhr.setRequestHeader('Authorization', apikey);
                global_xhrPool.push(xhr);
                loading('on');

            },
            success: function(data) {
                loading('off');

                console.log(`Log: Success reponse of m2_GetInspirationbyQuery(${Query})`);
                console.log(data);

                $("#rotating-sfeer-item-wrapper, .gsfeer-icon-container").remove();

                if (data.length > 0) {

                    m2_WriteInspirationResponseQuery(data);
                } else {
                    $().toastmessage('showToast', {
                        text: 'Deze categorie bevat geen foto\'s.',
                        sticky: false,
                        type: 'notice',
                        stayTime: 3000
                    });

                    $('.sfeerfoto_thumb_container').html('');


                    // $(".controls").removeClass('isatmosphere');
                    // 17-5-2019
                    // removeSfeer(); 
                    // $('html').removeClass('sfeer_clicked');
                }
                // setTimeout(function() {
                //     if (patienceToast != '') {
                //         $().toastmessage('removeToast', patienceToast);
                //     }
                // }, 1000);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                loading('off');

                if (jqXHR.readyState < 4) {
                    return true;
                }
            }
        });

    }

    function m2_WriteInspirationResponseQuery(response) {

        console.log(`Log: [m2_WriteInspirationResponseQuery(response)] `);


        $("#loading").css({
            "visibility": "hidden",
            "display": "none"
        });


        console.log('add html class shaz_show_modal_inispiratie');
        // close_shaz_modal();
        $("html").addClass("shaz_show_modal_inispiratie");





        if (!(response instanceof Array) && response != null) {
            response = [response];
        }
        if (!response || response.length == 0) {
            console.log(`Log: no response data`);
            return;
        }

        // inspiration_results = response;
        inspiration_results = arr_clone(response);




        // m2_getAllInspiration();
        m2_generate_sfeergallery(inspiration_results);
    }




    function m2_generate_sfeergallery(response) {

        var inspiration_results = response;
        var inspirationsArray;
        var idArray;
        var currentItem = -1;

        // -------------------------------
        // Fill thumbnail in float panel 
        // -------------------------------


        public_function.gallery_fill_float = function(inspiration_results) {

            inspirationsArray = [];
            inspirationsArray.length = 0;

            idArray = [];
            idArray.length = 0;

            img_array = [];
            img_array.length = 0;

            var counter = 0;
            for (var i = 0; i < inspiration_results.length; i++) {

                maxIns_perItem = 1;
                for (var j = 0; j < maxIns_perItem; j++) {
                    // inspirationsArray[counter] = "/files/" + inspiration_results[i].FileName; // nuc_online
                    inspirationsArray[counter] = inspiration_results[i].FileName;
                    idArray[counter++] = inspiration_results[i].ArticleId;
                }
            }

            img_array = inspirationsArray;




            $('.sfeerfoto_thumb_container').html('');

            console.log(`Log: making thumbnail for sfeerfoto`);
            // multi_remove_scroll();
            // multi_add_scroll();

            // debugger
            for (var i = 0; i < inspirationsArray.length; i++) {
                var fileId = inspirationsArray[i].split('.');


                // fileId = fileId[0].replace('/files/', '').replace('/FILES/', ''); // nuc_online
                fileId = fileId[0];

                // ------------------------
                // nuc_online
                // ------------------------

                // if (is_online) {
                //     sfeer_thumbUrl = base_url + inspirationsArray[i].replace('/files/', '');
                // } else {
                //     // sfeer_thumbUrl = base_url + inspirationsArray[i] + sfeer_thumb;
                //     sfeer_thumbUrl = base_url.replace('?thumb&img=', '') + inspirationsArray[i].replace(/\/FILES/ig, 'resized') + '?custome_resize&request_action=width_400&img=' + inspirationsArray[i];
                // }


                // // if (debug) {
                // //     console.log('online + sfeer_thumbUrl = ' + online + " :: " + sfeer_thumbUrl);
                // //     console.log('base_url :: inspirationsArray[i] :: sfeer_thumb= ' + base_url + " :: " + inspirationsArray[i] + " :: " + sfeer_thumb);
                // //     console.log('sfeer_thumbUrl = ' + sfeer_thumbUrl );
                // //     console.log(' ----- ------ ----- ----- ------ -----');
                // // }


                sfeer_thumbUrl = base_url_400 + '/' + inspirationsArray[i];

                if (!idArray[i]) {
                    console.trace(`%c Log: [public_function.gallery_fill_float], NO tile_id found for sfeer thumb index = ${i}`, "color: red; font-size: x-large");
                }

                // http://localhost/FILES/000c9a6d-6c99-4d31-959d-ae6130e3e7ab.jpg

                // debugger
                if (local_linux) {
                    sfeer_thumbUrl = "http://33.0.0.100/" + inspirationsArray[i].replace(/\/FILES/ig, 'resized');
                }

                sfeer_thumb_div = '<li tile_id="' + idArray[i] + '" file_id="' + fileId + '"' + ' class="sfeerThumb"><img src="' + sfeer_thumbUrl + '" /></li>';

                // 17-5-2019
                // $('.results-wall:visible').append(sfeer_thumb_div);
                // $('.results-wall').append(sfeer_thumb_div);

                // console.log('inspirationsArray[i] = '+inspirationsArray[i]);
                // console.log('file_id = '+fileId);

                $('.sfeerfoto_thumb_container').append(sfeer_thumb_div);
            }

            // multi_add_scroll();




            invoke_all();
        };

        public_function.gallery_fill_float(response);

        // ---------------------------------------------------
        // add listener to thumbnails in float panel
        // ---------------------------------------------------


        invoke_listener.sfeerfoto_panel_thumb_click = function(action) {

            if (action == 'off') {
                $(".sfeerfoto_thumb_container li").off("click");
                event.preventDefault();
                event.stopPropagation();
                return;
            }

            $(".sfeerfoto_thumb_container li").off("click");
            $(".sfeerfoto_thumb_container li").on("click", { "object_passed": "sfeerfoto_panel_thumb_click" }, public_function.sfeerfoto_panel_thumb_click);

        };

        public_function.sfeerfoto_panel_thumb_click = function(e) {

            var message = e.originalEvent ? e.data.object_passed : "";
            message = message || e.message;
            console.log(`Log: [${message}] function is called`);

            if (typeof e == 'object' && !e.originalEvent) {
                console.log('Dynamic triggering');
            }

            console.log('removing html.shaz_show_modal_inispiratie');
            $("html").removeClass('shaz_show_modal_inispiratie');


            // $('.floating_wrapper.ft_sfeerfoto').addClass('hide_feature_panel');

            // $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
            currentItem = $(this).index();
            console.log(`Log: Clicked thumbnail = ${currentItem}`);
            gsfeerCurrentId = idArray[currentItem];
            console.log(gsfeerCurrentId);


            public_function.close_sfeer();
            public_function.gallery_build_dom({ "message": "gallery_build_dom" });
            public_function.move_images_to_slider({ "message": "move_images_to_slider" });

            public_function.sfeerfoto_slider_thumb_click({ "currentItem": currentItem }); // triggering the clicked thumbnail on slidebar

            // public_function.move_images_back_to_sfeerpanel({ "message": "move_images_back_to_sfeerpanel" });
            // public_function.gallery_remove_dom ({"message":"gallery_remove_dom"});

        };

        invoke_listener.sfeerfoto_panel_thumb_click();


        // ---------------------------------------------------
        // Build Full page Gallery Dom
        // ---------------------------------------------------

        public_function.gallery_build_dom = function(e) {

            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);

            // <div class="gallery_fullpage">
            //     <div class="gallery_info"><div class="g_style"></div><div class="g_color"></div></div>
            //     <div class="gallery_thumb_left_arrow"><i class="fa fa-chevron-left"></i></div>
            //     <div class="gallery_thumb_right_arrow"><i class="fa fa-chevron-right"></i></div>
            //     <div class="gallery_thumb_wrapper"><ul class="gallery_thumb_container"></ul></div>
            //         <ul class="gallery_thumb_container">
            //             <li tile_id="1251406" file_id="0525D026-EB58-4658-8791-4DA94CFF2810" class="gallery_thumb_item">
            //                 <img src="http://localhost/vlakkenmaker/resized/0525D026-EB58-4658-8791-4DA94CFF2810.jpg?custome_resize&amp;request_action=width_400&amp;img=/files/0525D026-EB58-4658-8791-4DA94CFF2810.jpg">
            //                         </li>
            //         </ul>
            //     </div>
            //     <div class="gallery_image_wrapper"><div class="gallery_image_container"></div></div>
            // </div>

            var gallery_container = $('<div class="fullpage_gallery_container"></div>');
            $(gallery_container).appendTo('body');

            var thumb_slider = $('<div class="fullpage_gallery_thumb_slider"></div>');
            $(thumb_slider).append($('<div class="fullpage_gallery_info"><div class="g_style"></div><div class="g_color"></div><div class="g_zoek">Zoek opnieuw</div>'));
            $(thumb_slider).append($('<div class="fullpage_gallery_thumb_left_arrow"><i class="fa fa-chevron-left"></i></div>'));
            $(thumb_slider).append($('<div class="fullpage_gallery_thumb_right_arrow"><i class="fa fa-chevron-right"></i></div>'));
            $(thumb_slider).append($('<div class="fullpage_gallery_thumb_wrapper"><ul class="gallery_thumb_container"></ul></div>'));
            $(thumb_slider).appendTo(gallery_container);

            var fullpage_gallery_close = $('<div class="fullpage_gallery_close"><i class="fa fa-close "></i></div>');
            $(fullpage_gallery_close).appendTo(gallery_container);

            $(gallery_container).append($('<div id="rotating-sfeer-item-wrapper" style="display: none;"></div>'));

            // -------------------
            // Add Full images
            // -------------------
            // create_sfeer_bg = function() {
            // gsfeer_div_container = $('<div id="rotating-sfeer-item-wrapper"></div>').prependTo("body").hide();
            // gsfeer_div_container = $('<div id="rotating-sfeer-item-wrapper" style="display: none;"></div>').prependTo(gallery_container);

            // $('<div class="gsfeer-icon-container"><span class="fa fa-tag icon"></span><span class="icon-text">Bekijk in ruimte</span></div>').prependTo("body");

            // for (var i = 0; i < img_array.length; i++) {
            //     if (!online) {
            //         $("<div></div>")
            //             .addClass('rotating-sfeer-item')
            //             .css('background-image', 'url("' + base_url + img_array[i] + '")')
            //             .appendTo(gsfeer_div_container);
            //     } else {
            //         $("<div></div>")
            //             .addClass('rotating-sfeer-item')
            //             .css('background-image', 'url("' + base_url.replace('600', 'images') + img_array[i].replace('/files', '') + '")')
            //             .appendTo(gsfeer_div_container);
            //     }

            // }
            // };

            // create_sfeer_bg();

            // gsfeer_div_container.fadeIn();


            private_function.fill_sfeer_big_images({ "message": "sfill_feer_big_images" });

            var selected_style = $(".get_all_styles_container > .sfeer_style_wraper input:checked").val();
            var selected_color = $(".get_style_colors_container select#styles-colors").val();

            $('.g_style').html(selected_style);
            $('.g_color').html(selected_color);






        };





        private_function.fill_sfeer_big_images = function(e) {

            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);

            // var gallery_container = $('div.fullpage_gallery_container');
            var gsfeer_div_container = $('#rotating-sfeer-item-wrapper');
            $(gsfeer_div_container).empty();

            for (var i = 0; i < img_array.length; i++) {

                var related_tileid = (idArray[i] != null) ? idArray[i] : "not_found";

                // NUC_ONLINE
                // if (!is_online) {
                //     var full_sfeer_image_url = base_url + img_array[i];
                // } else {
                //     var full_sfeer_image_url = base_url.replace('600', 'images') + img_array[i].replace('/files', '');
                // }

                // 

                var full_sfeer_image_url = base_url_1240 + '/' + img_array[i]

                if (local_linux) {
                    // sfeer_thumbUrl = "http://33.0.0.100/"+inspirationsArray[i].replace(/\/FILES/ig, 'resized');
                    full_sfeer_image_url = local_linux + inspirationsArray[i]; // .replace(/\/FILES/ig, 'resized');
                }

                $("<div></div>")
                    .addClass('rotating-sfeer-item')
                    .css('background-image', 'url("' + full_sfeer_image_url + '")')
                    .attr('related_tileid', related_tileid)
                    .appendTo(gsfeer_div_container);




                // if (!online) {
                //     $("<div></div>")
                //         .addClass('rotating-sfeer-item')
                //         .css('background-image', 'url("' + full_sfeer_image_url + '")')
                //         .attr('related_tileid', related_tileid)
                //         .appendTo(gsfeer_div_container);
                // } else {
                //     $("<div></div>")
                //         .addClass('rotating-sfeer-item')
                //         .css('background-image', 'url("' + base_url.replace('600', 'images') + img_array[i].replace('/files', '') + '")')
                //         .attr('related_tileid', related_tileid)
                //         .appendTo(gsfeer_div_container);
                // }

            }

            var gallery_container = $('div.fullpage_gallery_container');
            // -------------------
            // Adding etiket
            // -------------------
            $('<div class="gsfeer-icon-container"><span class="fa fa-tag icon"></span><span class="fullpage_gallery_icon-text">BEKIJK IN TEGELVIEWER</span></div>').prependTo(gallery_container);

            $('#rotating-sfeer-item-wrapper').show();

            // invoke_all();

        };





        public_function.move_images_to_slider = function(e) {

            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);

            var html_sfeerfoto_thumb_container = $('div.sfeerfoto_thumb_container').html();
            $('ul.gallery_thumb_container').html(html_sfeerfoto_thumb_container);

            invoke_all();

        };

        public_function.move_images_back_to_sfeerpanel = function(e) {

            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);

            var html_gallery_thumb_container = "";
            html_gallery_thumb_container = $('ul.gallery_thumb_container').html();

            if (!html_gallery_thumb_container) {
                console.log(`Log: [move_images_back_to_sfeerpanel] delay invoked`);
                if (typeof read_delay !== 'undefined' && read_delay) clearTimeout(read_delay);

                read_delay = setTimeout(function(that) {
                    html_gallery_thumb_container = $('ul.gallery_thumb_container').html();

                    $('div.sfeerfoto_thumb_container').html(html_gallery_thumb_container);
                }, 1000, this);
            } else {
                console.log(`Log: [move_images_back_to_sfeerpanel] direct call`);
                $('div.sfeerfoto_thumb_container').html(html_gallery_thumb_container);
            }
            // invoke_all();
        };














        // -----------------------------
        // gallery_control
        // -----------------------------


        invoke_listener.sfeerfoto_slider_thumb_click = function(action) {

            if (action == 'off') {
                $("ul.gallery_thumb_container > li").off(click_touch);
                event.preventDefault();
                event.stopPropagation();
                return;
            }

            $("ul.gallery_thumb_container > li").off(click_touch);
            $("ul.gallery_thumb_container > li").on(click_touch, { "object_passed": "sfeerfoto_slider_thumb_click" }, public_function.sfeerfoto_slider_thumb_click);

        };

        public_function.sfeerfoto_slider_thumb_click = function(e) {




            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);

            if (typeof e == 'object' && !e.originalEvent) {
                console.log(`Log: ${message} - Dynamic triggered`);
            }


            // if (Number.isInteger(val))
            // if (isNaN(val))
            // if (typeof(val) === 'number')

            // if (e.currentItem) currentItem; // if the function is called directly with public_function.sfeerfoto_slider_thumb_click({"currentItem":5});


            // infiniteLoop.pause();

            // $(".gsfeer_play").text('PLAY');
            $('.sfeerThumb').removeClass('activesfeerThumb');

            $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime); // previous active


            if (Number.isInteger(e.currentItem) && e.currentItem >= 0) { // overridden, if the function is called directly with public_function.sfeerfoto_slider_thumb_click({"currentItem":5});
                currentItem = e.currentItem;
            } else {
                currentItem = $(this).index();
            }

            console.log(`Log: currentItem sfeerfoto clicked/passed = ${currentItem}`);



            $('div.sfeerfoto_thumb_container > .sfeerThumb').eq(currentItem).addClass('activesfeerThumb'); // float panel
            $('ul.gallery_thumb_container > .sfeerThumb').eq(currentItem).addClass('activesfeerThumb'); // Thumb bottom slider

            gsfeerCurrentId = idArray[currentItem];
            $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);

            var fileId = $(this).attr('file_id');

            // .attr('related_tileid', related_tileid)

            if (!gsfeerCurrentId) {
                $('.gsfeer-icon-container').hide();
                console.log('Log: Hiding Label because Tile id is null');
            } else {
                $('.gsfeer-icon-container').show();

                // $('.gsfeer-icon-container').show();
            }

            setLabelPosition(fileId);

            fullpage_gallery_sfeer_pagination();


        };

        invoke_listener.sfeerfoto_slider_thumb_click();
        // invoke_all();




        // --------------
        // Close Gallery
        // --------------


        // public_function.gallery_remove_dom ({"message":"gallery_remove_dom"});


        invoke_listener.gallery_remove_dom = function(action) {

            if (action == 'off') {
                $(".fullpage_gallery_close, .g_zoek").off(click_touch);
                event.preventDefault();
                event.stopPropagation();
                return;
            }

            $(".fullpage_gallery_close, .g_zoek").off(click_touch);
            $(".fullpage_gallery_close, .g_zoek").on(click_touch, { "object_passed": "gallery_remove_dom" }, public_function.gallery_remove_dom);

        };



        public_function.gallery_remove_dom = function(e) {

            // new message format

            var message = ((e && e.originalEvent) ? e.data.object_passed : "") || e ? e.object_passed : "";
            console.log(`Log: [${message}] function is called`);
            $('div.fullpage_gallery_container').empty().remove();

            // if( gvars.registered_key[0] != "bekijk_in_tegelviewer" ) {

            // }
            console.log("Log: Don't reopen sfeer panel");

            console.log('triggering inspiratie_zoek_opnieuw');

            $('.inspiratie_zoek_opnieuw').trigger(click_touch);


            // public_function.open_sfeer();


            // invoke_all();
        };

        invoke_listener.gallery_remove_dom();


        // ----------------------------
        //   Slider Left Arrow 
        // ----------------------------


        invoke_listener.sfeerfoto_slider_left = function(action) {
            if (action == 'off') {
                $(".fullpage_gallery_thumb_left_arrow").off(click_touch);
                event.preventDefault();
                event.stopPropagation();
                return;
            }
            $(".fullpage_gallery_thumb_left_arrow").off(click_touch);
            $(".fullpage_gallery_thumb_left_arrow").on(click_touch, { "object_passed": "sfeerfoto_slider_left" }, public_function.sfeerfoto_slider_left);
        };

        public_function.sfeerfoto_slider_left = function(e) {
            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);
            if (typeof e == 'object' && !e.originalEvent) {
                console.log(`Log: ${message} - Dynamic triggered`);
            }
            fullpage_gallery_sfeer_pagination("left");
        };

        invoke_listener.sfeerfoto_slider_left();


        // ----------------------------
        //   Slider Right  Arrow 
        // ----------------------------


        invoke_listener.sfeerfoto_slider_right = function(action) {
            if (action == 'off') {
                $(".fullpage_gallery_thumb_right_arrow").off(click_touch);
                event.preventDefault();
                event.stopPropagation();
                return;
            }
            $(".fullpage_gallery_thumb_right_arrow").off(click_touch);
            $(".fullpage_gallery_thumb_right_arrow").on(click_touch, { "object_passed": "sfeerfoto_slider_right" }, public_function.sfeerfoto_slider_right);
        };

        public_function.sfeerfoto_slider_right = function(e) {
            var message = (e.originalEvent ? e.data.object_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);
            if (typeof e == 'object' && !e.originalEvent) {
                console.log(`Log: ${message} - Dynamic triggered`);
            }
            fullpage_gallery_sfeer_pagination("right");
        };

        invoke_listener.sfeerfoto_slider_right();



        function fullpage_gallery_sfeer_pagination(direction) {

            // portViewWidth = $(".portView").width();
            var containerWidth = $("ul.gallery_thumb_container").width();
            var portViewWidth = $(".fullpage_gallery_thumb_wrapper").width();
            var thumbWidth = $("ul.gallery_thumb_container .sfeerThumb").outerWidth(true);

            var totalThumb = img_array.length;
            var total_thumbs_per_page = Math.ceil(portViewWidth / thumbWidth);

            var left_position = $("ul.gallery_thumb_container").position().left;
            var current_view_segment = Math.floor(Math.trunc(Math.abs(left_position)) / Math.trunc(portViewWidth)); // Math.trunc = integer with same sign
            var total_segment = Math.ceil(Math.abs(containerWidth) / portViewWidth);




            if (direction == "left") {
                var new_view_segment = current_view_segment - 1;
            } else if (direction == "right") {
                var new_view_segment = current_view_segment + 1;
            } else {
                var currThumb = currentItem + 1;
                var totalPages = Math.ceil(containerWidth / portViewWidth);
                var reachedPosition = currThumb * (thumbWidth - 1);
                var new_view_segment = Math.floor(reachedPosition / portViewWidth);
            }

            if (new_view_segment >= total_segment) {
                new_view_segment = total_segment - 1;
                return;
            }

            if (new_view_segment < 0) {
                new_view_segment = 0;
                return;
            }

            console.log('portViewWidth = ' + portViewWidth);
            console.log('thumbWidth = ' + thumbWidth);
            console.log('total_thumbs_per_page = ' + total_thumbs_per_page);
            console.log('containerWidth = ' + containerWidth);
            console.log('totalThumb = ' + totalThumb);
            console.log('currThumb = ' + currThumb);
            console.log('totalPages = ' + totalPages);
            console.log('current_view_segment = ' + current_view_segment);
            console.log('new_view_segment = ' + new_view_segment);


            if (new_view_segment > current_view_segment || new_view_segment < current_view_segment) {
                // $(".sfeer_ThumbContainer").animate({
                $("ul.gallery_thumb_container").animate({
                    left: -new_view_segment * portViewWidth
                }, 500);


            }


        }



        // $(document).on('zzzclick', '.gsfeer-icon-container', function() {
        //             var articleId = $(".activesfeerThumb").attr('tile_id');
        //             var id_query = '?ArticleIds=' + $(".activesfeerThumb").attr('tile_id');
        //             GetItemsbyQuery(id_query, true, 'qrcode');
        //             return;


        // ------------------------------
        //   Click Bekijk in tegelviewer
        // ------------------------------


        invoke_listener.bekijk_in_tegelviewer = function(action) {
            if (action == 'off') {
                $(".gsfeer-icon-container").off(click_touch);
                event.preventDefault();
                event.stopPropagation();
                return;
            }

            console.log('.gsfeer-icon-container');

            $(".gsfeer-icon-container").off(click_touch);
            $(".gsfeer-icon-container").on(click_touch, { "message_passed": "bekijk_in_tegelviewer", "x":"y" }, public_function.bekijk_in_tegelviewer);
        };

        public_function.bekijk_in_tegelviewer = function(e) {
            // debugger;
            var message = (e.originalEvent ? e.data.message_passed : "") || e.message;
            console.log(`Log: [${message}] function is called`);

            if (typeof e == 'object' && !e.originalEvent) {
                console.log(`Log: ${message} - Dynamically triggered`);
            }

            registered_key('bekijk_in_tegelviewer');

            var articleId = $("li.sfeerThumb.activesfeerThumb").attr('tile_id');
            var id_query = '?ArticleIds=' + $("li.sfeerThumb.activesfeerThumb").attr('tile_id');

            console.log(`Log: sfeerfoto tile_id = ${articleId}`);

            // debugger;
            




            public_function.floating_close_qr_favourite();
            public_function.gallery_remove_dom();
            public_function.close_sfeer();
            // public_function.close_roomselect();
            // window.slider_upper();

            var target_pen = 'pen_icon_1';

            initialize_qrpen(e, target_pen);

            _global.active_icon = target_pen;
            _global.active_class = _global.current_walls_arr[_global.active_icon].class;
            _global.active_type = _global.renderLayers[_global.active_class].type; // tile or color

            console.log(`Log: <bekijk_in_tegelviewer>, setting _global.used_layers[${_global.active_icon}] = true`);

            _global.used_layers[_global.active_icon] = true;

            _global.vars[_global.active_icon].bekijk_in_tegelviewer = articleId;

            multi_GetItemsbyQuery(id_query, true, 'sfeer'); //  multi_GetItemsbyQuery(Query, updateBreadcrumbs, tileType, isQrScanner) qrpen


            console.log('show_frame(html_class) is calling');

            show_frame('tegelviewer');


        };

        invoke_listener.bekijk_in_tegelviewer();


































        // $(document.body).on(click_touch, ".gsfeer_prev", function() {
        //     infiniteLoop.pause();
        //     $(".gsfeer_play").text('PLAY');
        //     $('.sfeerThumb').removeClass('activesfeerThumb');
        //     $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
        //     --currentItem;
        //     if (currentItem < 0) currentItem = img_array.length - 1;
        //     $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
        //     gsfeerCurrentId = idArray[currentItem];
        //     $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);
        //     sfeer_pagination();

        //     var fileId = $('.sfeerThumb').eq(currentItem).attr('file_id');
        //     setLabelPosition(fileId);
        // });
        // $(document.body).on(click_touch, ".gsfeer_next", function() {
        //     infiniteLoop.pause();
        //     $(".gsfeer_play").text('PLAY');
        //     $('.sfeerThumb').removeClass('activesfeerThumb');
        //     $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
        //     ++currentItem;
        //     if (currentItem > img_array.length - 1) currentItem = 0;
        //     $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
        //     gsfeerCurrentId = idArray[currentItem];
        //     $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);
        //     sfeer_pagination();

        //     var fileId = $('.sfeerThumb').eq(currentItem).attr('file_id');
        //     setLabelPosition(fileId);
        // });


        //     public_function.sfeerfoto_slider_thumb_click({"currentItem":currentItem}); // triggering the clicked thumbnail on slidebar














        //     infiniteLoop.pause();
        // $(".gsfeer_play").text('PLAY');
        // $('.sfeerThumb').removeClass('activesfeerThumb');
        //  $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
        // currentItem = $(this).index();
        // // $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
        // gsfeerCurrentId = idArray[currentItem];
        // console.log(gsfeerCurrentId);
        // public_function.close_sfeer();
        // // $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);
        // // var fileId = $(this).attr('file_id');








    };








































    function m2_getAllInspiration(clicked_index) {

        console.log(`Log: [m2_getAllInspiration()] `);


        // 17-5-2019
        inspirationsArray = [];
        inspirationsArray.length = 0;

        idArray = [];
        idArray.length = 0;

        $("#rotating-sfeer-item-wrapper, .gsfeer-icon-container").remove();

        var counter = 0;
        for (var i = 0; i < inspiration_results.length; i++) {

            maxIns_perItem = 1;
            for (var j = 0; j < maxIns_perItem; j++) {
                inspirationsArray[counter] = "/files/" + inspiration_results[i].FileName;
                idArray[counter++] = inspiration_results[i].ArticleId;
            }
        }

        // debugger

        // $(".wall-results").addClass('atmosphere');
        // $("ul.results-wall").html('').addClass('atmosphere');
        // $(".floor-results").hide();

        $('.sfeerfoto_thumb_container').html('');



        //  -------------------- Gallery Control ----------------------


        $(document.body).on(click_touch, ".gsfeer_play", function() {
            if ($(this).text().trim() == "PAUZE") {
                infiniteLoop.pause();
                $(this).text('PLAY');
            } else {
                $(this).text('PAUZE');
                infiniteLoop.play();
            }
        });
        $(document.body).on(click_touch, ".gsfeer_prev", function() {
            infiniteLoop.pause();
            $(".gsfeer_play").text('PLAY');
            $('.sfeerThumb').removeClass('activesfeerThumb');
            $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
            --currentItem;
            if (currentItem < 0) currentItem = img_array.length - 1;
            $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
            gsfeerCurrentId = idArray[currentItem];
            $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);
            sfeer_pagination();

            var fileId = $('.sfeerThumb').eq(currentItem).attr('file_id');
            setLabelPosition(fileId);
        });
        $(document.body).on(click_touch, ".gsfeer_next", function() {
            infiniteLoop.pause();
            $(".gsfeer_play").text('PLAY');
            $('.sfeerThumb').removeClass('activesfeerThumb');
            $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
            ++currentItem;
            if (currentItem > img_array.length - 1) currentItem = 0;
            $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
            gsfeerCurrentId = idArray[currentItem];
            $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);
            sfeer_pagination();

            var fileId = $('.sfeerThumb').eq(currentItem).attr('file_id');
            setLabelPosition(fileId);
        });


        // --------------------------------------
        // clicking on thumbnail on float panel
        // --------------------------------------

        // $(document.body).on(click_touch, ".results-wall.atmosphere li", function() {









        // $(document.body).on(click_touch, ".sfeerfoto_thumb_container li", function() {

        //     // infiniteLoop.pause();
        //     // $(".gsfeer_play").text('PLAY');
        //     // $('.sfeerThumb').removeClass('activesfeerThumb');
        //     // $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
        //     currentItem = $(this).index();
        //     console.log(`Log: Clicked thumbnail = ${currentItem}`);


        //     // $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
        //     gsfeerCurrentId = idArray[currentItem];
        //     console.log(gsfeerCurrentId);


        //     public_function.close_sfeer();


        //     // $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);

        //     // var fileId = $(this).attr('file_id');
        //     // setLabelPosition(fileId);
        // });
















        // $(document.body).on(click_touch, ".results-wall.atmosphere li", function() {
        // $(document.body).on(click_touch, ".sfeerfoto_thumb_container li", function() {

        //     infiniteLoop.pause();
        //     $(".gsfeer_play").text('PLAY');
        //     $('.sfeerThumb').removeClass('activesfeerThumb');
        //     $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
        //     currentItem = $(this).index();
        //     if (debug) {
        //         console.log(currentItem);
        //     }

        //     $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
        //     gsfeerCurrentId = idArray[currentItem];
        //     $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);

        //     var fileId = $(this).attr('file_id');
        //     setLabelPosition(fileId);
        // });


        //  -------------------- eof Gallery Control ----------------------



        img_array = inspirationsArray;
        if (debug) {
            console.log(' ------------------- Atmosfeer -----------------');
            console.log('img_array = ');
            console.log(img_array);
        }
        makeThumbnail();

        function makeThumbnail() {

            console.log(`Log: making thumbnail for sfeerfoto`);
            // console.log("$('.results-wall:visible')");
            // console.log($('.results-wall:visible'));
            for (var i = 0; i < inspirationsArray.length; i++) {
                var fileId = inspirationsArray[i].split('.');
                fileId = fileId[0].replace('/files/', '').replace('/FILES/', '');
                if (is_online) {
                    sfeer_thumbUrl = base_url + inspirationsArray[i].replace('/files/', '');
                } else {
                    // sfeer_thumbUrl = base_url + inspirationsArray[i] + sfeer_thumb;
                    sfeer_thumbUrl = base_url.replace('?thumb&img=', '') + inspirationsArray[i].replace(/\/FILES/ig, 'resized') + '?custome_resize&request_action=width_400&img=' + inspirationsArray[i];
                }


                // if (debug) {
                //     console.log('online + sfeer_thumbUrl = ' + online + " :: " + sfeer_thumbUrl);
                //     console.log('base_url :: inspirationsArray[i] :: sfeer_thumb= ' + base_url + " :: " + inspirationsArray[i] + " :: " + sfeer_thumb);
                //     console.log('sfeer_thumbUrl = ' + sfeer_thumbUrl );
                //     console.log(' ----- ------ ----- ----- ------ -----');
                // }
                sfeer_thumb_div = '<li tile_id="' + idArray[i] + '" file_id="' + fileId + '"' + ' class="sfeerThumb"><img src="' + sfeer_thumbUrl + '" /></li>';

                // 17-5-2019
                // $('.results-wall:visible').append(sfeer_thumb_div);
                // $('.results-wall').append(sfeer_thumb_div);

                // console.log('inspirationsArray[i] = '+inspirationsArray[i]);
                // console.log('file_id = '+fileId);

                $('.sfeerfoto_thumb_container').append(sfeer_thumb_div);
            }


            // 17-5-2019
            setTimeout(function() {
                sfeer_gallery();
            }, 1000);

        }




        function sfeer_gallery() {
                    console.log('sfeer_gallery()');
            create_sfeer_bg = function() {
                gsfeer_div_container = $('<div id="rotating-sfeer-item-wrapper"></div>').prependTo("body").hide();
                $('<div class="gsfeer-icon-container"><span class="fa fa-tag icon"></span><span class="icon-text">Bekijk in ruimte</span></div>').prependTo("body");
                for (var i = 0; i < img_array.length; i++) {
                    if (!is_online) {
                        $("<div></div>")
                            .addClass('rotating-sfeer-item')
                            .css('background-image', 'url("' + base_url + img_array[i] + '")')
                            .appendTo(gsfeer_div_container);
                    } else {
                        $("<div></div>")
                            .addClass('rotating-sfeer-item')
                            .css('background-image', 'url("' + base_url.replace('600', 'images') + img_array[i].replace('/files', '') + '")')
                            .appendTo(gsfeer_div_container);
                    }

                }
            };

            create_sfeer_bg();

            gsfeer_div_container.fadeIn();


            var InfiniteRotator = {
                init: function() {
                    console.log('init InfiniteRotator');

                    var initialFadeIn = 1000;

                    var itemInterval = 5000;

                    var numberOfItems = img_array.length;

                    $('.rotating-sfeer-item').eq(currentItem).fadeIn(initialFadeIn);
                    $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
                    gsfeerCurrentId = idArray[currentItem];

                    var fileId = $('.sfeerThumb').eq(currentItem).attr('file_id');
                    setLabelPosition(fileId);



                    if (img_array.length < 2) return;

                    infiniteLoop = $.timer(function() {
                        console.log(currentItem);
                        $('.rotating-sfeer-item').eq(currentItem).fadeOut(fadeTime);
                        if (currentItem == numberOfItems - 1) {
                            currentItem = 0;
                        } else {
                            currentItem++;
                        }

                        $('.rotating-sfeer-item').eq(currentItem).fadeIn(fadeTime);
                        $('.sfeerThumb').eq(currentItem).siblings().removeClass('activesfeerThumb');
                        $('.sfeerThumb').eq(currentItem).addClass('activesfeerThumb');
                        gsfeerCurrentId = idArray[currentItem];
                        sfeer_pagination();
                    });
                    infiniteLoop.set({
                        time: itemInterval,
                        autostart: false
                    });
                }
            };
            InfiniteRotator.init();


            // 17-5-2019
            calculate_li_vieoport_widths();
        }

        function sfeer_pagination() {
            portViewWidth = $(".portView").width();
            thumbWidth = $(".sfeerThumb").outerWidth(true);
            containerWidth = $(".sfeer_ThumbContainer").width();
            totalThumb = img_array.length;
            currThumb = currentItem + 1;
            totalPages = Math.ceil(containerWidth / portViewWidth);
            reachedPosition = currThumb * thumbWidth;
            reachedSfeerpage = Math.floor(reachedPosition / portViewWidth);
            if (reachedSfeerpage > currSfeerpage) {
                $(".sfeer_ThumbContainer").animate({
                    left: -portViewWidth * reachedSfeerpage
                }, 500);
                currSfeerpage = reachedSfeerpage;
            } else if (reachedSfeerpage < currSfeerpage) {
                $(".sfeer_ThumbContainer").animate({
                    left: -portViewWidth * reachedSfeerpage
                }, 500);
                currSfeerpage = reachedSfeerpage;

            }
        }

    }

    // ----------------------- eof [m2_getAllInspiration] -----------------------

    // --------------------------------------------------------------------------------------------------- eof moved -------------------------------------------------------------------------------------------







    // -----------------
    // EOF Sfeerfoto
    // -----------------






    // ----------------------------------------------------------------------------------
    // -------------------------------- CMS Search Control ------------------------------
    // ----------------------------------------------------------------------------------

    // roomdesigner_mobile_background_image
    // roomdesigner_mobile_background_image.mobile_image

    // roomvo_calculator
    // roomvo_calculator.berekening_inschakelen
    // global_data.roomvo_calculator

    // {
    //     "berekening_inschakelen": true,
    //     "is_er_snijverlies": "Ja",
    //     "percentage_van_snijverlies": "12",
    //     "percentage_meer_of_minder_van_het_totaal": "10",
    //     "is_er_korting": "Ja",
    //     "korting_in_stapels": [
    //         {
    //             "van_hoveelheid": "0",
    //             "tot_hoveelheid": "100",
    //             "korting": "5"
    //         },
    //         {
    //             "van_hoveelheid": "100",
    //             "tot_hoveelheid": "200",
    //             "korting": "10"
    //         },
    //         {
    //             "van_hoveelheid": "200",
    //             "tot_hoveelheid": "",
    //             "korting": ""
    //         }
    //     ]
    // }






    // zoek_optie.alleen_buitentegels
    // zoek_optie.eigen_merken
    // zoek_optie.zo_ja_kies_het_merk


    // {
    //     "eigen_merken": "Ja",
    //     "zo_ja_kies_het_merk": {
    //         "merken": [
    //             {
    //                 "value": "vtwonen",
    //                 "label": "VTwonen"
    //             },
    //             {
    //                 "value": "piet_boon",
    //                 "label": "Piet Boon"
    //             },
    //             {
    //                 "value": "porcelanosa",
    //                 "label": "Porcelanosa"
    //             },
    //             {
    //                 "value": "douglas_jones",
    //                 "label": "Douglas & Jones"
    //             },
    //             {
    //                 "value": "motto_by_mosa",
    //                 "label": "Motto by Mosa"
    //             },
    //             {
    //                 "value": "beste_koop",
    //                 "label": "Beste Koop"
    //             },
    //             {
    //                 "value": "jos_tegels",
    //                 "label": "Jos Tegels"
    //             }
    //         ]
    //     },
    //     "alleen_buitentegels": "Nee"
    // }



    // ---------------------
    // Roomvo calculator
    // ---------------------

    //     "berekening_inschakelen": true,
    //     "is_er_snijverlies": "Ja",
    //     "percentage_van_snijverlies": "12",
    //     "percentage_meer_of_minder_van_het_totaal": "10",
    //     "is_er_korting": "Ja",
    //     "korting_in_stapels": [
    //         {
    //             "van_hoveelheid": "0",
    //             "tot_hoveelheid": "100",
    //             "korting": "5"
    //         },



    var berekening_inschakelen     = (global_data['roomvo_calculator'] || {}).berekening_inschakelen;
    var is_er_snijverlies          = (global_data['roomvo_calculator'] || {}).is_er_snijverlies;
    var percentage_van_snijverlies = (global_data['roomvo_calculator'] || {}).percentage_van_snijverlies;
    var is_er_korting              = (global_data['roomvo_calculator'] || {}).is_er_korting;
    var korting_in_stapels              = (global_data['roomvo_calculator'] || {}).korting_in_stapels;

    if (is_er_snijverlies == "Nee") percentage_van_snijverlies = 0;


    gvars.roomdesigner.berekening_inschakelen     = berekening_inschakelen;
    gvars.roomdesigner.is_er_snijverlies          = is_er_snijverlies;
    gvars.roomdesigner.percentage_van_snijverlies = percentage_van_snijverlies;
    gvars.roomdesigner.is_er_korting              = is_er_korting;
    gvars.roomdesigner.korting_in_stapels         = korting_in_stapels;



    if (!berekening_inschakelen){

        $('.action_button.button_b1').remove();
        $('.action_button.button_b3').next().remove('hr');
        $('.action_button.button_b3').remove();

    } else {

        var van_array = [], tot_array = [], korting_array = [];
        
        if (korting_in_stapels && korting_in_stapels.length > 0 ){
            korting_in_stapels.forEach(function(el, index) {
                
                var van_hoveelheid = el.van_hoveelheid;
                van_hoveelheid = parseFloat(van_hoveelheid);

                var tot_hoveelheid = el.tot_hoveelheid;
                if (!tot_hoveelheid) tot_hoveelheid = 0;
                tot_hoveelheid = parseFloat(tot_hoveelheid);

                var korting = el.korting;
                korting = parseFloat(korting);

                van_array.push(van_hoveelheid);
                tot_array.push(tot_hoveelheid);
                korting_array.push(korting);
            });


            gvars.roomdesigner.calculations = [van_array,tot_array,korting_array];
        }



    }









    // ------------------------------------------
    // Adding collectie
    console.log('adding_collectie()');
    adding_collection();
    // ------------------------------------------




















    // ------------------------------
    // Buitentegels enabled/disabled
    // ------------------------------
    var buitentegels_enabled             = (global_data['zoek_optie'] || {}).dealer_buitentegels;
    var buitentegels_alleen_buitentegels = (global_data['zoek_optie'] || {}).alleen_buitentegels;

    gvars.roomdesigner.buitentegels_enabled             = buitentegels_enabled;
    gvars.roomdesigner.buitentegels_alleen_buitentegels = buitentegels_alleen_buitentegels;


    if (buitentegels_enabled == "Ja"){
        $('html').addClass('buitentegels_enabled');

        if (buitentegels_alleen_buitentegels == "Ja"){
            $('html').addClass('buitentegels_alleen_buitentegels');

            $('.sh_title.filter_op div').html('Zoek buitentegel');
            $('.merken_labels_header1').remove();
        }

    }


















 
 
 



    // $(document.body).on(click_touch, ".back_to_home , .show_hide_sidebars_wrapper , .search_tabs_wrapper > div:not(.m_roomselect) ,  .button_containers > div , .action_buttons_wrapper > div", function() {
    $(document).on(click_touch, ".back_to_home , .show_hide_sidebars_wrapper , .search_tabs_wrapper > div:not(.m_roomselect) ,  .button_containers > div , .action_buttons_wrapper > div", function() {

        // debugger
        if ($('html.show_video').length > 0){

            console.log('/# Remove html.show_video #/');
            $('html.show_video').removeClass('show_video');
        }

    });



    $(document).on(click_touch, ".toggle_fscreen", function() {

        console.log('toggle full screen');
       
        toggleFullScreen(); 
    });










    // -------------------------------------------------------------------------- eof ready ----------------------------------------------------------------------------------


  });


function show_frame(html_class){

    console.log('show_frame is called, = ' + html_class);


    if (html_class == 'roomvo') {
        console.log("api: Clicking on mijn kamer from home page, activate upload picture");

        // roomvo_global.bridge.request = 1;

   
        activate_roomvolayer();
        html_class="tegelviewer";


        // if(roomvo_global.api_started && !roomvo_global.image_uploaded){
        if(global_roomvo.var.api_initialized   &&  global_roomvo.var.is_active && (! _roomvo || ! _roomvo.image_uploaded ) ){

                        console.log("api: go directly to upload button");
                        $("html").addClass("roomvolayer-upload");
                        // roomvo_global.api_is_called = 1;
        }

        // $("html").addClass("roomvolayer-active"); // needed from home page otherwise the background custom image will not appear.


        
    } else  if (html_class == 'tegelviewer') {
         deactivate_roomvolayer();
    }


    // $('html').removeClass('tegelviewer');
    // $('html').removeClass('roomvo');
    // $('html').removeClass('vrdemo');
    // $('html').removeClass('inspiratie_home');

    ['tegelviewer','roomvo','vrdemo','inspiratie_home'].forEach(function(el, index) {
            if (html_class == el) return;
            $('html').removeClass(el); 
    });

    $('html').addClass(html_class); 
}

// ---------------- offerte ------------------

function fill_offerte_modal(){

    console.log('fill_offerte_modal is called');

    var tiles = Object.keys(gvars.caculator.tile_ids);

    if (!tiles.length) {
        return;
    }


    $("table.offerte_aanvragen tbody").empty();


    tiles.forEach(function(tile_id, index){

        var tile = gvars.caculator.tile_ids[tile_id];
        console.log(tile);

        if (!tile.bruto_area){
            console.log('tile id is deleted ' + tile_id);
            delete gvars.caculator.tile_ids[tile_id];
            return;
        }


        // var tr = $("</tr>");
        var tr = $("<tr>").appendTo($("table.offerte_aanvragen tbody"));

        var td = $("<td>").append('<img src="' + tile.thumb + '"  class="c_td_thumb" />').appendTo(tr);
        var td = $("<td>").append('<div class="c_td_dealer_id" >' + tile.dealer_id + '</div>').appendTo(tr);
        var td = $("<td>").append('<div class="c_td_bruto_area" >' + tile.bruto_area + '</div>').appendTo(tr);
        var td = $("<td>").append('<div class="c_td_onze_prijs" >' + tile.onze_prijs.replace(".", ",") + '</div>').appendTo(tr);
        var td = $("<td>").append('<div class="c_td_calculated_price" >' + tile.calculated_price + '</div>').appendTo(tr);

        // console.log(tr);
        // $(tr).appendTo("table.offerte_aanvragen tbody");

    });









}



// --------------------------------------------------------


function send_offerte(validate = 1) {
    if (!validate) {
        console.log("Log: send_offerte form not valid");
        return;
    }
     
    console.log(`Log: send_offerte`);
    // console.log(m_capture.tiles_arr);

    // gvars.toast = $(".toast-container").attr("class") || "toast-container toast-position-middle-center";
    // $(".toast-container").attr("class", "toast-container toast-position-top-right");

    // $().toastmessage("showToast", {
    //     text: "Tegels informatie is verzonden",
    //     sticky: false,
    //     position: "top-right",
    //     // position: 'middle-center',
    //     type: "notice",
    //     //  'notice' 'success' 'warning' 'error'
    //     close: function() {
    //         $(".toast-container").delay(500).queue(function() {
    //             $(this).attr("class", gvars.toast).dequeue();
    //         });
    //     },
    // });

    // var name = $('input[name="email_sender_name"]#email_sender_name').val().trim();
    // var email = $('input[name="email_sender_email"]#email_sender_email').val().trim();
    // var telefoonnummer = $('input[name="email_sender_telefoonnummer"]#email_sender_telefoonnummer').val().trim();
    // var uwvraag = $('.ft_showsaved form textarea[name = "email_sender_uwvraag"]').val().trim();

    // var code = $('input[name="Code"]').val();



    var voornaam       = $('input[name = "offerte_modal_form_voornaam"]#offerte_modal_form_voornaam').val().trim();
    var achternaam     = $('input[name = "offerte_modal_form_achternaam"]#offerte_modal_form_achternaam').val().trim();
    var straatnaam     = $('input[name = "offerte_modal_form_straatnaam"]#offerte_modal_form_straatnaam').val().trim();
    var huisnummer     = $('input[name = "offerte_modal_form_huisnummer"]#offerte_modal_form_huisnummer').val().trim();
    var postcode       = $('input[name = "offerte_modal_form_postcode"]#offerte_modal_form_postcode').val().trim();
    var woonplaats     = $('input[name = "offerte_modal_form_woonplaats"]#offerte_modal_form_woonplaats').val().trim();
    var email          = $('input[name = "offerte_modal_form_email"]#offerte_modal_form_email').val().trim();
    var telefoonnummer = $('input[name = "offerte_modal_form_telefoonnummer"]#offerte_modal_form_telefoonnummer').val().trim();
    var opmerking      = $('textarea[name = "offerte_modal_form_textarea_22"]#offerte_modal_form_textarea_22').val().trim();
    var tiles          = gvars.caculator.tile_ids


    var jform               = {};
    jform["voornaam"]       = voornaam;
    jform["achternaam"]     = achternaam;
    jform["straatnaam"]     = straatnaam;
    jform["huisnummer"]     = huisnummer;
    jform["woonplaats"]     = woonplaats;
    jform["postcode"]       = postcode;
    jform["email"]          = email;
    jform["telefoonnummer"] = telefoonnummer;
    jform["opmerking"] = opmerking;
    jform["tiles"]          = tiles;
    jform["action"]         = "tegelcollectie_offerte";








                                            // // var pdf   = doc.output();
                                            // // var blob = doc.output('blob');
                                            // // doc.save("test.pdf");
                                            // // return;

                                            // // var jform = new FormData();
                                            // // jform.append('VisitorName', name);
                                            // // jform.append('telefoonnummer', "000");
                                            // // jform.append('VisitorEmail', email);
                                            // // jform.append('uwvraag', 'uwvraag...');
                                            // // jform.append('Code', code);
                                            // // jform.append('ArticleIds', [m_capture.tiles_arr]);

                                            // // jform.append('generated_pdf' ,blob);

                                            // // form_data.ArticleIds
                                            // // jform.append('ArticleIds',"vlakkenmaker_make_screenshot");
                                            // // jform.append('action',"tegelcollectie_email_code");

                                            // var jform = {};
                                            // jform["VisitorName"] = name;
                                            // jform["telefoonnummer"] = telefoonnummer;
                                            // jform["VisitorEmail"] = email;
                                            // jform["uwvraag"] = uwvraag;
                                            // jform["Code"] = code;
                                            // jform["ArticleIds"] = m_capture.tiles_arr;
                                            // jform["action"] = "tegelcollectie_email_code";

                                            // // data = JSON.stringify(Object.fromEntries(jform));

                                            // // console.log(data);
                                            // // console.log(jform);

                                                // var data = JSON.stringify(jform);
                                            // //var ajaxurl = global_data.ajaxurl;

    if (global_data.home_url.indexOf(".") !== -1) {
        var ajaxurl = global_data.home_url + "/wp-admin/admin-ajax.php";
    }

                                                // // if subdomain is true use it.

                                                // // var ajaxurl = 'https://tgnshowroom2018.tegelcollectie.nl/wp-admin/admin-ajax.php';
                                                // var msg = global_data.txt_thanks;
                                                // msg = msg.replace("[code]", jform.Code);





    // data = {
    //     action: "tegelcollectie_offerte",
    //     data: jform
    // };

    // data = JSON.stringify(data);

    // $.ajax({
    //     url: ajaxurl,
    //     data: data,
    //     type: "POST",
    //     dataType: "json",
    //     contentType: "text/json",
    //     // beforeSend: function(xhr) {
    //     //     xhr.setRequestHeader("Authorization", apikey);
    //     // },
    //     complete: function(response) {
    //         // $('.favorites form').get(0).reset();
    //         // $('.favorites button[type=submit]').show();

    //         console.log('complete');
    //         console.log(response);
    //     },
    //     success: function(response) {
    //         console.log('success');
    //         console.log(response);
    //     },
    // });


    // return;


























    data = {
        action: "tegelcollectie_offerte",
        data: jform
    };

    console.clear();
    console.log(console.clear());

    console.log("Log: jform =");
    console.log(jform);
    // debugger
    $.post(ajaxurl, data, function(response) {

        console.log(response);

        if (response == 1) {
            $().toastmessage("showToast", {
                text: "Offerte is verzonden, we nemen contact met u op",
                position: "middle-center",
                type: "success",
                stayTime: 5000,
            });
        } else {
            $().toastmessage("showToast", {
                text: "Offerte verzonden is mislukt",
                position: "middle-center",
                type: "error",
                stayTime: 2000,
            });
        }

        $('.shaz-modal-top-header-close').trigger('click');


        // var json = JSON.parse(response);
        // console.log(json);




        // $(".submit_success_message").html(msg);
        // $(".submit_success_message").fadeIn().delay(7000).fadeOut();

        // console.log("log: reset form");
        // $(".floating_content.sv2_online form")[0].reset();
        // $(".favorite-counter").html("0");

        // $(".favorite-counter").prev().addClass("inactive_grey");
        // $(".favorite-counter").parent().parent().addClass("inactive_grey_li");
        // $(".favorite-counter").parent().parent().find("span.control-tooltip").html("Sla eerst uw keuze op");

        // $(".favorite-counter").removeAttr("style");
        // $(".floating_content.sv1_online .saved_left_content").html('<div class="nog_geen">U heeft nog geen tegels opgeslagen</div>');

        // m_capture = {
        //     room: {},
        //     tiles_arr: [],
        //     tiles: {},
        //     room_tegels: {},
        // };

        // gvars.total_fav = 0;
        // $(".floating_content.sv2_online input[name=Code]").val(Math.floor(Date.now() / 1000));

  
    });
 

    // data = JSON.stringify(jform);

    // $.ajax({
    //     url: api_url + "/TileSelection",
    //     data: data,
    //     type: "POST",
    //     dataType: "json",
    //     contentType: "text/json",
    //     beforeSend: function(xhr) {
    //         xhr.setRequestHeader("Authorization", apikey);
    //     },
    //     complete: function() {
    //         // $('.favorites form').get(0).reset();
    //         // $('.favorites button[type=submit]').show();

    //         console.log("Log: ajax completed to: " + api_url + "/TileSelection");
    //     },
    //     success: function(data) {
    //         console.log("Log: ajax successed to: " + api_url + "/TileSelection");
    //     },
    // });
 
}






// // Begin setup

// const mainNode = document.getElementById('html')
// // const toggleNode = document.getElementById('toggle')

// // toggleNode.addEventListener(click_touch, function() {
// //   mainNode.classList.toggle('--blue')
// // })

// // End setup

// function callback(mutationsList, observer) {
//     console.log('Mutations:', mutationsList)
//     console.log('Observer:', observer)
//     mutationsList.forEach(mutation => {
//         if (mutation.attributeName === 'class') {
//             // alert('Ch-ch-ch-changes!')

//                 console.log("///////////////////// html Class Change ///////////////////////");

//         }
//     })
// }

// const mutationObserver = new MutationObserver(callback)

// mutationObserver.observe(mainNode, { attributes: true })





jQuery(document).ready(function($) {
        var element = $('html');

        var observer = new MutationObserver(function(mutations) {


            

          console.log("Change detected");
          if ($('html').hasClass('shaz_show_modal_location') == true) {
            // console.log("Tegelinfo show detected");

            $('div.mainscreen #roomvo_api').appendTo('.showroom_location_left');
             
          } else {
            // console.log("No Tegelinfo show detected");

            $('.showroom_location_left  #roomvo_api').appendTo('div.mainscreen');
          }



            if ( $('html').hasClass('hide_sidebars')) {
                close_sub_vid_menu();
            }

            var htmlElement = $('html');
            var classes = htmlElement.attr('class').split(/\s+/);

            // var is_inispiratie = 0;

            // var hasShape = classes.filter(function(className) {
            //     return className.startsWith('demo_');
            // }).length > 0;

            // if (hasShape) debugger;



            var hasMatchingClass = classes.filter(function(className) {

                // if (className == 'shaz_show_modal_inispiratie') {
                //     is_inispiratie = 1;
                // }
                return className.startsWith('shaz_show_modal_');
            }).length > 0;

            // if (hasMatchingClass && !is_inispiratie) {
            if (hasMatchingClass) {
                // close_sub_vid_menu();
                public_function.close_roomselect();
            }



        });

        observer.observe(element[0], {
          attributes: true,
          attributeFilter: ['class']
        });



        // ------------- monitir pdf 2d container -------------


        if (global_detect_floating_content_sv3_class_change){

            let element = $('.is_showroom.floating_wrapper.ft_showsaved  .floating_content.sv3');
            let observer = new MutationObserver(function(mutations) {

                console.log('.floating_content.sv3 class is changed')
                debugger

            });

            observer.observe(element[0], {
              attributes: true,
              attributeFilter: ['class']
            });


        }




});


 // ------------------------------- Inspirationby idle Gallery ----------------------------------



 

// -----------------
// For Nuc only
// -----------------

jQuery(document).ready(function($) {

    if (global_data.forceShowroom) {
        fetch_nuc_idle_photos();

        // Reset the timer on user activity
        document.addEventListener('mousemove', resetIdleTimer);
        document.addEventListener('keypress', resetIdleTimer);
        
        // Initial setup
        resetIdleTimer();


    }

});


// ---------------------------------------------------------------------------
// Detect idle time nuc (add nuc_idle to html if detected otherwise remove it)
// ---------------------------------------------------------------------------


if (global_data.forceShowroom){



    let idleTimer;
    let idleDuration = global_data.nuc_settings.nuc_inactivity_time * 1000; // Set the idle duration in milliseconds (e.g., 5000ms or 5 seconds)
    var nuc_idle_show_period = global_data.nuc_settings.nuc_time_to_show * 1000;   // image to stay shown
    let  initialize_first = 0; 

    // --nuc-transition-idle = global_data.nuc_settings.nuc_transition_time; // in ms in /wp-content/themes/tegelcollectie-dealer/assets/sfeertool/css/php_style.php

    // idleDuration = 5000;

    console.log('idle Duration = '+ idleDuration );
    console.log('nuc_idle_show_period = '+ nuc_idle_show_period );

    function resetIdleTimer() {

        $('html').removeClass('nuc_idle');
      clearTimeout(idleTimer);
      idleTimer = setTimeout(() => {
        console.log('nuc_idle is detected');
        $('html').addClass('nuc_idle');

        if (!initialize_first){
            initialize_first = 1;
            start_nuc_idle();
        }

      }, idleDuration);
    }


    // -------------------
    // Fetch photos urls
    // -------------------

    var arr_nuc_idle_inspirations_url = [];

    function fetch_nuc_idle_photos() {

    var Query = 'ProductCategoryId=W&AtmosphereId=CLASSIC&AtmosphereId=MINIMALISTISCH&AtmosphereId=MODERN&AtmosphereId=RURAL';
    ajax_url = service_url + 'Master/AtmospherePhotos?' + Query;
    jQuery.support.cors = true;

    // abort_all_ajax();

    $.ajax({
        url: ajax_url,
        type: 'GET',
        dataType: 'json',
        beforeSend: function(xhr) {

            abort_all_ajax('AtmospherePhotos');  // (1) Cancel only AtmospherePhotos requests if requestType is defined
            xhr.requestType = 'AtmospherePhotos';
            xhr.setRequestHeader('Authorization', apikey);

            global_xhrPool.push(xhr);
            loading('on');

        },
        success: function(response) {
            loading('off');

            if (!(response instanceof Array) && response != null) {
                response = [response];
            }

            if (!response || response.length == 0) {
                console.log('NO SFEER FOTO NUC');
                return;
            }

            // shuffleArray(response);
            sortByFileIdDescending(response);
            console.log(response);
            // debugger


            for (var i = 0; i < response.length; i++) {
                arr_nuc_idle_inspirations_url[i] = base_url + '/' + response[i].FileName;     
            }


            add_nuc_photo_container();
            downloadImagesInChunks(arr_nuc_idle_inspirations_url);
            // start_nuc_idle();

        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
            loading('off');

            if (jqXHR.readyState < 4) {
                return true;
            }
        }
    });

    }


    // -----------------------------------------------------------
    // -------------------- Setup Divs nuc idle ------------------
    // -----------------------------------------------------------

    function add_nuc_photo_container(){
        if(! $('#nuc_idle_inspiration_container').length){
            var nuc_idle_inspiration_container = $('<div id="nuc_idle_inspiration_container"></div>').prependTo("body");
        }

    }

} 


// ---------------------
//  randomize an array
// ---------------------

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    // Swap array[i] and array[j]
    [array[i], array[j]] = [array[j], array[i]];
  }
}


function sortByFileIdDescending(arr) {
    return arr.sort((a, b) => b.FileId - a.FileId);
}


// --------------------------------
// Download images in chunks
// --------------------------------

function downloadImagesInChunks(imageUrls, chunkSize = 5, delayBetweenChunks = 1000) {
  let currentIndex = 0;

  function downloadChunk() {
    const currentChunk = imageUrls.slice(currentIndex, currentIndex + chunkSize);
    currentIndex += chunkSize;

    currentChunk.forEach(url => {
      const img = new Image();
      img.onload = () => {
            // console.log(`${url} downloaded`);

            $("<div></div>").addClass("nuc_idle_inspiration_photo").css("background-image", 'url("' + url + '")').appendTo('#nuc_idle_inspiration_container');
      }


      img.onerror = () => console.error(`Failed to download ${url}`);
      img.src = url;
    });
  }

  function downloadNextChunkWithDelay() {
    if (currentIndex < imageUrls.length) {
      downloadChunk();
      setTimeout(downloadNextChunkWithDelay, delayBetweenChunks);
    } else {
      console.log('All images downloaded!');
    }
  }

  downloadNextChunkWithDelay();
}

// ------------------------------------
 

function start_nuc_idle(){

    var images = $('#nuc_idle_inspiration_container .nuc_idle_inspiration_photo');
    let currentIndex = 0;

    console.log('start_nuc_idle() is started');

    // Add fadeIn class to the first image
    images.eq(0).addClass('fadeIn');

    // console.clear();
    // console.log(' **************************************************************** images.eq(0) ***********************************************************************');

    // console.log(images.length);
    // console.log(images.eq(0));

    function showNextImage() {

        if (!$("html").hasClass("nuc_idle")) { 
            return;
        }

      var images = $('#nuc_idle_inspiration_container .nuc_idle_inspiration_photo');

      const nextIndex = (currentIndex + 1) % images.length;

      images.eq(currentIndex).removeClass('fadeIn');
      images.eq(nextIndex).addClass('fadeIn');

      currentIndex = nextIndex;
    }

    // Set the interval to switch images (e.g., every 5 seconds)
    setInterval(showNextImage, nuc_idle_show_period);
}




// -------------------------------------- new API --------------------------------------



jQuery(document).ready(function($) {


    // function get_merken() {
    //     // if (debug) {
    //     //     console.log("GetInspirationbyQuery(Query) = ");
    //     //     console.log(Query);
    //     // }
    //     // $("#loading").css({
    //     //     visibility: "visible",
    //     //     display: "block",
    //     // });
    //     // var patienceToast = $().toastmessage("showToast", {
    //     //     text: "Een ogenblik geduld, de foto's worden geladen.",
    //     //     sticky: true,
    //     //     type: "notice",
    //     //     stayTime: 6000,
    //     // });

    //     var Query = 'BrandId=MOTTO';
    //     ajax_url = service_url + "Master/BrandLookSeries?" + Query;

    //     console.log('new api');
    //     console.log(ajax_url);
    //     // debugger

    //     jQuery.support.cors = true;
    //     $.ajax({
    //         url: ajax_url,
    //         type: "GET",
    //         dataType: "json",
    //         beforeSend: function(xhr) {
    //             xhr.setRequestHeader("Authorization", apikey);
    //         },
    //         success: function(data) {
    //             // $("#rotating-sfeer-item-wrapper, .gsfeer-icon-container").remove();
    //             // if (data.length > 0) {
    //             //     WriteInspirationResponseQuery(data);
    //             // } else {
    //             //     $().toastmessage("showToast", {
    //             //         text: "Deze categorie bevat geen foto's.",
    //             //         sticky: false,
    //             //         type: "notice",
    //             //         stayTime: 3000,
    //             //     });
    //             //     $(".controls").removeClass("isatmosphere");
    //             //     // 17-5-2019
    //             //     removeSfeer();
    //             //     // $('html').removeClass('sfeer_clicked');
    //             // }
    //             // setTimeout(function() {
    //             //     if (patienceToast != "") {
    //             //         $().toastmessage("removeToast", patienceToast);
    //             //     }
    //             // }, 1000);

    //             console.log(data);
    //         },
    //         error: function(jqXHR, textStatus, errorThrown) {
    //             console.log(errorThrown);
    //             if (jqXHR.readyState < 4) {
    //                 return true;
    //             }
    //         },
    //     });
    // }


    // get_merken();
























    // ---------------- Video -------------------



     


$(document.body).on(click_touch, '.search_tabs_wrapper .search_tabs', function(event) {


    if ($(this).hasClass('m_roomselect') && event.target === this) {

        if ($(this).hasClass('active_m_roomselect')){
            $(this).removeClass('active_m_roomselect');
        } else {
            $(this).addClass('active_m_roomselect');
        }
    } else if (! $(this).hasClass('m_roomselect')) {
        $('.active_m_roomselect').removeClass('active_m_roomselect');
    }

    
    // hide_shaz_sidebar(); 



})



    // --- video -----------

// show_video();







    // ------------------- eof ready ------------------
});

function close_sub_vid_menu(){

    console.log('close_sub_vid_menu()');
    $('.active_m_roomselect').removeClass('active_m_roomselect');
}





// -------------------- Video -------------------
// video.js



// var currentVideoContainer = null;
// var currentPlayer = null;

// function show_video(videoName = 'badkamer') {
//     if (played_video[videoName]) {
//         return;
//     } else {
//         played_video[videoName] = played_video[videoName] || 0;
//         played_video[videoName] += 1;
//     }

//     var videoURL = videoLinks[videoName];

//     // Close the current video if there is one
//     if (currentPlayer) {
//         currentPlayer.pause();
//         currentVideoContainer.remove();
//     }

//     if (videoURL) {
//         // Dynamically create the video container
//         var videoContainer = $('<div class="video-container">');
//         var videoPlayer = $('<video class="video-player" loop muted playsinline>');

//         // Set the video source
//         videoPlayer.attr('src', videoURL);

//         // Append elements to the container
//         videoContainer.append(videoPlayer);

//         // Append the container to the body
//         $('body').append(videoContainer);

//         // Show the video container
//         videoContainer.show();

//         // Initialize the video player
//         currentPlayer = videoPlayer[0];

//         // Close video on 'video-container' click
//         videoContainer.on(click_touch, function() {
//             currentPlayer.play().catch((error) => {
//                 console.error('Failed to play the video:', error);
//             });
//         });

//         // Update the current video container
//         currentVideoContainer = videoContainer;
//     }
// }


var videoLinks = {
    "badkamer"   : "https://tgnshowroom2021.tegelcollectie.nl/wp-content/themes/tegelcollectie-dealer/assets/sfeertool/images/videos/badkamer.mp4",
    "keuken"     : "https://tgnshowroom2021.tegelcollectie.nl/wp-content/themes/tegelcollectie-dealer/assets/sfeertool/images/videos/keuken.mp4",
    "slaapkamer" : "https://tgnshowroom2021.tegelcollectie.nl/wp-content/themes/tegelcollectie-dealer/assets/sfeertool/images/videos/slaapkamer.mp4",
    "tuin"       : "https://tgnshowroom2021.tegelcollectie.nl/wp-content/themes/tegelcollectie-dealer/assets/sfeertool/images/videos/tuin.mp4",
    "woonkamer"  : "https://tgnshowroom2021.tegelcollectie.nl/wp-content/themes/tegelcollectie-dealer/assets/sfeertool/images/videos/woonkamer.mp4",
};

var currentVideoContainer = null;
var currentPlayer = null;

var played_video = {};


// function show_video(videoName = '') {


 

//     if (videoName != 'keuken' && played_video[videoName] ) {
//         return;
//     }

//     if (videoName == 'keuken' && !played_video[videoName]) {

//         played_video[videoName] = played_video[videoName] || 0;
//         played_video[videoName] += 1;
//         return;
//     }

//     if ((videoName != 'keuken' && played_video[videoName]) ||  (videoName == 'keuken' && played_video[videoName]) > 1  ) {
//         return;
//     }
    
//     // played_video[videoName] = played_video[videoName] || 0;
//     // played_video[videoName] += 1;
  


//     // Pause and remove the current video if there is one
//     if (currentPlayer && currentVideoContainer) {
//         currentPlayer.pause();
//         currentVideoContainer.remove();
//     }

//     var videoURL = videoLinks[videoName];

//     if (videoURL) {
//         // Dynamically create the video container
//         var videoContainer = $('<div class="video-container">');
//         var videoPlayer = $('<video class="video-player" loop muted playsinline>');

//         // Set the video source
//         videoPlayer.attr('src', videoURL);

//         // Dynamically create the close button
//         var closeButton = $('<div class="video_close-button"><i class="fa-sharp fa-thin fa-xmark-large"></i></div>');


//         // closeButton.on(click_touch, function() {
//         //     // Remove the container
//         //     videoContainer.remove();
//         // });

//         // Append elements to the container
//         videoContainer.append(closeButton, videoPlayer);

//         // Append the container to the body
//         $('body').append(videoContainer);

//         // Show the video container
//         videoContainer.show();

//         // Initialize the video player
//         currentPlayer = videoPlayer[0];

//         // Play the video when the container is clicked
//         videoContainer.one(click_touch, function() {
//             currentPlayer.play();
//         });

//         // Close video on 'video-container' click
//         videoContainer.on(click_touch, function() {
//             currentPlayer.pause();
//             videoContainer.remove();

//             played_video[videoName] = played_video[videoName] || 0;
//             played_video[videoName] += 1;
//         });

//         // Listen for the 'canplay' event to start the video
//         currentPlayer.addEventListener('canplay', function() {
//             currentPlayer.play().catch((error) => {
//                 console.error('Failed to play the video:', error);
//             });
//         }, { once: true });

//         // Update the current video container
//         currentVideoContainer = videoContainer;
//     }
// }

// Call the function on document ready
// jQuery(document).ready(function($) {
//     show_video();
// });




                                                                                // jQuery(document).ready(function($) {
                                                                                // // $(document).on(click_touch, "li.filter_merk_item", function(event) {
                                                                                //           $(document).on(click_touch, "div.collectie_look_item_wrapper", function(event) {
                                                                                //               console.log(`Log: collectie filter_merk_item `);

                                                                                //               // $(".multi_size_panel").empty().remove();
                                                                                //               // _hook.call(this, 'colorlistlicolor');

                                                                                //               // --------------- total 9-2022---------------

                                                                                //               // if ($(this).hasClass("active")) {

                                                                                //               //   if ($(this).parent().find("li.active").length > 1) {
                                                                                //               //     $(this).toggleClass("active");
                                                                                //               //   }
                                                                                //               // } else {
                                                                                //               //   $(this).addClass("active");
                                                                                //               // }

                                                                                //               $(this).toggleClass("active");

                                                                                //               collect_active_merken_collection();
                                                                                           

                                                                                //               // --------------- eof total ---------------

                                                                                //               // commented 9-2022
                                                                                //               // if ($(this).hasClass('active')) { // TODO: to be checked ,   color must not empty

                                                                                //               //  var total_selected_colors =  $(this).parent().find('li.active');

                                                                                //               //  if (total_selected_colors && total_selected_colors.length > 1){
                                                                                //               //    $(this).removeClass('active')
                                                                                //               //  }

                                                                                //               //  console.log(`Log: calling reset_Look_Sizes() & GetAllLook(${_global.active_tiletype}), with color selected = none`);
                                                                                //               //  reset_Look_Sizes();
                                                                                //               //  GetAllLook(_global.active_tiletype);

                                                                                //               //  return;
                                                                                //               // }

                                                                                //               // reset_Look_Sizes();
                                                                                //               // GetAllLook(_global.active_tiletype);

                                                                                //               // return;

                                                                                //               // $(this).parent().find('li').removeClass('active'); 9-22
                                                                                //               // $(this).addClass('active'); // 9-2022

                                                                                //               // var selected_color = activeColor(this);

                                                                                //               // console.log(`Log: selected color = ${selected_color}`);
                                                                                //               // reset_Look_Sizes();
                                                                                //               // GetAllLook(_global.active_tiletype);
                                                                                //           });

                                                                                // });







// ----------------------------------------------------------------------------------------------------------
//  Adding Eigen merken
// ----------------------------------------------------------------------------------------------------------


function adding_collection() {



    // ------------------------------
    // Eigen merken enabled/disabled
    // ------------------------------
    var eigen_merken_enabled = (global_data['zoek_optie'] || {}).eigen_merken;

    gvars.roomdesigner.eigen_merken_enabled = eigen_merken_enabled;

    if (eigen_merken_enabled == "Ja"){
        $('html').addClass('eigen_merken_enabled');

        var eigen_merken = ((global_data['zoek_optie'] || {}).zo_ja_kies_het_merk || {} ).merken;






        // eigen_merken  = [
        //     {
        //         "value": "vtwonen",
        //         "label": "VTwonen"
        //     },
        //     {
        //         "value": "piet_boon",
        //         "label": "Piet Boon"
        //     },
        //     {
        //         "value": "porcelanosa",
        //         "label": "Porcelanosa"
        //     },
        //     {
        //         "value": "douglas_jones",
        //         "label": "Douglas & Jones"
        //     },
        //     {
        //         "value": "motto_by_mosa",
        //         "label": "Motto by Mosa"
        //     },
        //     {
        //         "value": "jos_tegels",
        //         "label": "Jos Tegels"
        //     }
        // ]

        // ACF =
        // vtwonen : VTwonen
        // piet_boon : Piet Boon
        // porcelanosa : Porcelanosa
        // douglas_jones : Douglas & Jones
        // motto_by_mosa : Motto by Mosa
        // beste_koop : Beste Koop
        // jos_tegels : Jos Tegels

        var brands = {
            "vtwonen" : "VT WONEN",
            "piet_boon" : "PIET BOON",
            "porcelanosa" : "PORCWVT",
            "douglas_jones" : "DOUGLASJNS",
            "motto_by_mosa" : "MOTTO",
            "beste_koop" : "BESTE KOOP",
            "jos_tegels" : "JOS.",
        }

                                // var brands_order = ['douglas_jones' , 'vtwonen' , 'piet_boon' , 'motto_by_mosa' , 'jos_tegels' , 'porcelanosa' , 'beste_koop'];
                                
                                // var ordered_eigen_merken = {}, labels = [];


                                //  // Map "value" key to keys in brands, get corresponding values, and display in the order of brands_order

                                //  for (var i = 0; i < brands_order.length; i++) {
                                //      var brandKey = brands_order[i];
                                //      var eigenMerkenItem = eigen_merken.find(item => item.value === brandKey);

                                //      if (eigenMerkenItem) {
                                //          var brandLabel = eigenMerkenItem.label;
                                //          var ajax_brandKey = brands[brandKey];

                                //          console.log(`Key: ${ajax_brandKey} , Label: ${brandLabel}`);

                                //          labels.push(brandLabel);
                                //          ordered_eigen_merken[ajax_brandKey] = brandLabel;

                                //      }
                                //  }

                                //  var labels_txt = labels.slice(0, -1).join(', ') +' & ' + labels.slice(-1);


        // Create ordered_eigen_merken object
        var  ordered_eigen_merken = {};
        eigen_merken.forEach(item => {
            ordered_eigen_merken[brands[item.value]] = item.label;
        });

        // Sort ordered_eigen_merken alphabetically based on keys (B)
        var  sorted_ordered_eigen_merken = Object.fromEntries(
            Object.entries(ordered_eigen_merken).sort((a, b) => a[1].localeCompare(b[1]))
        );

        // console.log(eigen_merken);
        console.log('----------------------------------');
        console.log('** sorted_ordered_eigen_merken  **');
        console.log('----------------------------------');
        console.log(sorted_ordered_eigen_merken);
        // debugger

        var collectie_labels = Object.values(sorted_ordered_eigen_merken);
        var labels_txt = collectie_labels.slice(0, -1).join(', ') +' & ' + collectie_labels.slice(-1);

        // console.log(labels_txt);
        // debugger


         console.log('set label Collectie');
         // $('.merken_labels_header_1_sub label').html(labels_txt);
         // $('.merken_labels_header_1_sub label').html("Collecties");

         // $('.merken_labels_header1 label').html("Collecties: " + labels_txt);



         console.log('ignore adding Collecties label');
         // $('.merken_labels_header1 label').addClass("complete_collectie_label").html("Collecties: " + labels_txt);
         $('.merken_labels_header1 label').addClass("complete_collectie_label").html("Collecties ");

         $('<label for="brand_id" class="empty_collectie_label">Collecties </label>').appendTo('.merken_labels_header1');

       

         fetch_collection_merken(sorted_ordered_eigen_merken);


    } else {
            $('.merken_labels_header1').remove();
    }





}
// ----------------------------------------------------------------------------------------------------------


function fetch_collection_merken(ordered_eigen_merken){

    // ordered_eigen_merken = {
    //     "DOUGLASJNS": "Douglas & Jones",
    //     "VT WONEN": "VTwonen",
    //     "PIET BOON": "Piet Boon",
    //     "MOTTO": "Motto by Mosa",
    //     "JOS": "Jos Tegels",
    //     "PORCWVT": "Porcelanosa"
    // }

    // ?BrandId=DOUGLASJNS&BrandId=DOUGLASJNS&VT WONEN&BrandId=PIET BOON....

    var urlParameters = [];

    // Iterate through the keys in the ordered_eigen_merken object
    for (var key in ordered_eigen_merken) {
        if (ordered_eigen_merken.hasOwnProperty(key)) {
            // Encode the key and push it to the array
            urlParameters.push("BrandId=" + encodeURIComponent(key));
        }
    }

    // Join the array into a string using "&" as a separator
    var urlString = "?" + urlParameters.join("&");



    var ajax_url = "https://showroomtgnonline.azurewebsites.net/api/Master/BrandLookSeries" + urlString;

    console.log('eigen merk query');
    console.log(ajax_url);
    // debugger
    // var apikey =  "ApiKey TGN Showroom 2018_J5iW;Lb1O6x=7A(0GGM&pw}!FARVr:e1G-;t!-{IgT?LANn{wGCg-;):*W[7q{f$)G(G}&Cj";
     
    jQuery.support.cors = true;
            $.ajax({
                url: ajax_url,
                type: "GET",
                dataType: "json",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", apikey);
                },
                success: function(data) {
                    console.log('success fetch_collection_merken response');
                    console.log(data);

                    // debugger

                    show_collection_merken(data , ordered_eigen_merken);



                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(errorThrown);
                    debugger;
                    if (jqXHR.readyState < 4) {
                        return true;
                    }
                     
                },
            });

}


                      

function show_collection_merken(data , ordered_eigen_merken) {
  if (data) {
    // console.log(data);

    var  sortedData = {};

    // Sort based on the second-level keys ("key2")
    var  sortedKeys1 = Object.keys(data).sort((a, b) => a.localeCompare(b));

    sortedKeys1.forEach(key1 => {
        const innerObject = data[key1];
        sortedData[key1] = {};

        // Sort the arrays associated with "key2" in alphabetical order
        const sortedKeys2 = Object.keys(innerObject).sort((a, b) => a.localeCompare(b));

        sortedKeys2.forEach(key2 => {
            sortedData[key1][key2] = innerObject[key2].sort((a, b) => a.localeCompare(b));
        });
    });

    data = sortedData;

    // console.log(sortedData);





    // debugger
    var outerCounter = 0;

 

    let  look_name_mapping = {
        "Beton"       : "Betonlook",
        "Design"      : "Design",
        "Hardsteen"   : "Hardsteenlook",
        "Hout"        : "Houtlook",
        "Marmer"      : "Marmerlook",
        "Metaal"      : "Metaallook",
        "Natuursteen" : "Natuursteenlook",
        "Patchwork"   : "Patchwork",
        "Stone"       : "Steenlook",
        "Terracotta"  : "Terracotta",
        "Travertin"   : "Travertin",
        "Uni"         : "Uni",
        "Graniet"     : "Granietlook"
    };

    let lowerKeys = Object.keys(look_name_mapping).map(key => key.toLowerCase());



    for (var key1 in data) {
      outerCounter++;
      if (data.hasOwnProperty(key1)) {
        console.log("Level 1 Key:", key1);

        // ------------------- Merk ------------------------
        var merk = key1;
        // debugger

        var li_new = $("<li/>").addClass('filter_merk_item').attr('data-datafilter', '');
        li_new.appendTo('ul.listed.merken-list');

        // if (outerCounter > 1) {
        if (outerCounter > 0) {
          $(li_new).addClass('do_merk_collaps');
        }

        var collectie_merken_wrapper = $("<div/>").addClass('collectie_merken_wrapper');
        var collectie_merken_wrapper_header_wrapper = $("<div/>").addClass('collectie_merken_wrapper_header_wrapper').appendTo(collectie_merken_wrapper);
        var collectie_merken_wrapper_header_title = $("<div/>").addClass('collectie_merken_wrapper_header_title').attr("collectie_merk", merk).html(ordered_eigen_merken[merk]).appendTo(collectie_merken_wrapper_header_wrapper);

        $('<div class="collectie_collaps"><i class="fa fa-chevron-down"></i><i class="fa fa-chevron-up"></i></div>').appendTo(collectie_merken_wrapper_header_wrapper);

        collectie_merken_wrapper.appendTo(li_new);

        // -------------------- Look -------------------------

        var collectie_look_wrapper = $("<div/>").addClass('collectie_look_wrapper').appendTo(collectie_merken_wrapper);

        // Loop through the second level (keys within the nested object)
        for (var key2 in data[key1]) {
          var innerCounter = 0;

          var look = key2;


          let lowerLook = look.toLowerCase();

          let newlook = look;

          for (let key in look_name_mapping) {
            if (key.toLowerCase() === lowerLook) {
              newlook = look_name_mapping[key];
              break;
            }
          }






          if (data[key1].hasOwnProperty(key2)) {
            console.log("  Level 2 Key:", key2);

            var collectie_look_wrapper_item = $("<div/>").addClass('collectie_look_wrapper_item').appendTo(collectie_look_wrapper);

            var collectie_look = $("<div/>").addClass('collectie_look').attr("collectie_look", look).html(newlook).appendTo(collectie_look_wrapper_item);

            // -------------------- Serie -------------------------

            // Loop through the third level (array elements within the nested object)
            var level3Array = data[key1][key2];
            for (var i = 0; i < level3Array.length; i++) {
              innerCounter++;
              console.log("    Level 3 Element:", level3Array[i]);

              var serie = level3Array[i];

              var serie_item = $('<div class="collectie_look_item_wrapper"><div class="collectie_look_item collectie_serie">' + serie + '</div><div class="collectie_radio"></div></div>');
              serie_item.attr("collectie_serie", serie);
              serie_item.appendTo(collectie_look_wrapper_item);
            }
          }
        }
      }
    }
  }


  f_hookend(14); //  after show_collection_merken",
}

 

                                        // jQuery(document).ready(function ($) {

                                        //   var activeItems = []; // To store information about active items

                                        //   $(document).on(click_touch, "div.collectie_look_item_wrapper", function (event) {
                                        //     var collectie_merk = $(this).closest('.filter_merk_item').find('.collectie_merken_wrapper_header_title').attr('collectie_merk');
                                        //     var collectie_look = $(this).closest('.collectie_look_wrapper_item').find('.collectie_look').attr('collectie_look');
                                        //     var collectie_serie = $(this).attr('collectie_serie');

                                        //     $(this).toggleClass("active");

                                        //     // Store information about the clicked item
                                        //     var itemData = {
                                        //       collectie_merk: collectie_merk,
                                        //       collectie_look: collectie_look,
                                        //       collectie_serie: collectie_serie
                                        //     };

                                        //     // Check if the item is already in activeItems array
                                        //     var index = -1;
                                        //     for (var i = 0; i < activeItems.length; i++) {
                                        //       if (activeItems[i].collectie_merk === collectie_merk && activeItems[i].collectie_look === collectie_look && activeItems[i].collectie_serie === collectie_serie) {
                                        //         index = i;
                                        //         break;
                                        //       }
                                        //     }

                                        //     if ($(this).hasClass("active")) {
                                        //       // Add the item to activeItems if it's not present
                                        //       if (index === -1) {
                                        //         activeItems.push(itemData);
                                        //       }
                                        //     } else {
                                        //       // Remove the item from activeItems if it's present
                                        //       if (index !== -1) {
                                        //         activeItems.splice(index, 1);
                                        //       }
                                        //     }

                                        //     // Output information about all active items
                                        //     collect_active_merken_collection(activeItems);
                                        //   });

                                        // });




// --------------------------------------------------------------------------------------------------------------------------------------

jQuery(document).ready(function ($) {

  var activeItems = []; // To store information about active items

  $(document).on(click_touch, "div.collectie_look_item_wrapper", function (event) {
    $(this).toggleClass("active");

    console.log("-- brand-look-serie is clicked --");

    // disable other brands clicked series
    control_active_collection(this);

    // Output information about all active items and update activeItems array
    activeItems = fetch_active_collection();
    collect_active_merken_collection(activeItems);
  });



  function control_active_collection(elem){

    console.log('disable other brands clicked series');
    var li_brand = $(elem).closest('li.filter_merk_item');
    // li_brand.css({"background-color":"red"});

    var parentElement = $(elem).closest('li.filter_merk_item');

    // Select all siblings of the clicked element's parent and exclude the parent itself
    var otherSiblings = parentElement.siblings().not(parentElement);


     

     $(otherSiblings).each(function( index, value ) {
       $(this).find('.collectie_look_item_wrapper.active').removeClass('active');
    });




    // $(li_brand).remove();
    // var this_brand = (filter_merk_item
  }

  function fetch_active_collection() {

    console.log(' ** fetch_active_collection() **');

    var activeItemsArray = [];

    // Find all active items within the scope of ul.listed.merken-list
    $('ul.listed.merken-list .collectie_look_item_wrapper.active').each(function () {
      var collectieSerie = $(this).attr('collectie_serie');
      var collectieLook = $(this).closest('.collectie_look_wrapper_item').find('.collectie_look').attr('collectie_look');
      var collectieMerk = $(this).closest('.collectie_merken_wrapper').find('.collectie_merken_wrapper_header_title').attr('collectie_merk');

      console.log("collectie_serie:", collectieSerie);
      console.log("collectie_look:", collectieLook);
      console.log("collectie_merk:", collectieMerk);

      // Store information about the active item
      activeItemsArray.push({
        collectie_merk: collectieMerk,
        collectie_look: collectieLook,
        collectie_serie: collectieSerie
      });
    });

    return activeItemsArray;
  }

});


// --------------------------------------------------------------------------------------------------------------------------------------












function collect_active_merken_collection(activeItems) {
  // console.log('collect_active_merken_collection()');
  // console.log(activeItems);

  let urlString = generateQueryString(activeItems);
  // console.log(urlString);

  fetch_collection_tiles(urlString); 
  return;


// -----------------------------------------------

 
  // service_url = 'https://showroomtgnonline.azurewebsites.net/api/';
    var ajax_url = service_url + 'Items/BrandLookSeries?' + urlString;
   

    console.log (ajax_url);

    // var ajax_url = "https://showroomtgnonline.azurewebsites.net/api/Master/BrandLookSeries" + urlString;
    // var apikey =  "ApiKey TGN Showroom 2018_J5iW;Lb1O6x=7A(0GGM&pw}!FARVr:e1G-;t!-{IgT?LANn{wGCg-;):*W[7q{f$)G(G}&Cj";
     
    jQuery.support.cors = true;
            $.ajax({
                url: ajax_url,
                type: "GET",
                dataType: "json",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", apikey);
                },
                success: function(data) {
                    console.log('fetch_collection_merken response');
                    console.log(data);




                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(errorThrown);
                    debugger;
                    if (jqXHR.readyState < 4) {
                        return true;
                    }
                     
                },
            });
     

// -----------------------------------------------

}



 
function generateQueryString(selectedItems) {
  const groupedItems = {};

  // Group items by BrandId, LookId, and SeriesId
  for (const item of selectedItems) {
    const brandId = item.collectie_merk;
    const lookId = item.collectie_look;
    const seriesId = item.collectie_serie;

    if (!groupedItems[brandId]) {
      groupedItems[brandId] = {};
    }

    if (!groupedItems[brandId][lookId]) {
      groupedItems[brandId][lookId] = [];
    }

    if (seriesId) {
      groupedItems[brandId][lookId] = groupedItems[brandId][lookId].concat(seriesId);
    }
  }

  // Generate the query string
  let queryString = '';
  for (const brandId in groupedItems) {
    queryString += `&BrandId=${brandId}`;

    for (const lookId in groupedItems[brandId]) {
      queryString += `&LookId=${lookId}`;

      const seriesIds = groupedItems[brandId][lookId];
      for (const seriesId of seriesIds) {
        queryString += `&SeriesId=${seriesId}`;
      }
    }
  }

  // Remove the leading '&' character
  queryString = queryString.slice(1);

  return queryString;
}






function makeAjaxCall(ajax_url, passObject) {
    var activeAjaxRequest = null; // Variable to store the active Ajax request

    function cancelPreviousRequest() {
        // If there is an active request, abort it before sending a new one
        if (activeAjaxRequest) {
            activeAjaxRequest.abort();
            console.log('abort activeAjaxRequest');
        }
    }
// debugger
    // Create a new Promise for the Ajax call
    return new Promise(function(resolve, reject) {
        // Call the function to cancel the previous request, if any
        cancelPreviousRequest();
        on_ajax_start();

        var xhr = $.ajax({
            url: ajax_url,
            type: "GET",
            dataType: "json",
            data: passObject,
            beforeSend: function(xhr) {


                abort_all_ajax('Items__BrandLookSeries');  // (2) Cancel only Items/BrandLookSeries  requests if requestType is defined
                xhr.requestType = 'Items__BrandLookSeries';



                xhr.setRequestHeader("Authorization", apikey);
                global_xhrPool.push(xhr);
            },
            success: function(data) {
                console.log('fetch_collection_merken response');
                console.log(data);
                resolve({ data, passObject });
                on_ajax_end();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                console.log('ERROR: debugger');


                // debugger;
                on_ajax_end();
                if (jqXHR.readyState < 4) {
                    resolve({ passObject }); // Resolve with passObject for partial success
                } else {
                    reject({ errorThrown, passObject });
                }
            },
            complete: function() {
                // Clear the active request once it's completed
                activeAjaxRequest = null;
                on_ajax_end();

            },
        });

        // Store the current XMLHttpRequest object as the active request
        activeAjaxRequest = xhr;
    });
}


function fetch_collection_tiles(urlString) {

    var ajax_url = service_url + 'Items/BrandLookSeries?' + urlString;

    var select_filter;

    if ($('html').hasClass('eigenschappen_filter')) select_filter = "eigenschappen_filter";
    if ($('html').hasClass('merk_filter')) select_filter = "merk_filter";
    




    var passObject = {
        url: urlString,
        select_filter: select_filter,
    };

    makeAjaxCall(ajax_url, passObject)
        .then(function(response) {
            console.log('Ajax call succeeded:', response.data);
            console.log('passObject:', response.passObject);
            // Your success logic here

 
             loading("off");
             data = clone_extraimageurlsister(response.data);
             store_tiles(data);

             console.log('saving select_filter');
             _global.vars[_global.active_icon].select_filter = response.passObject.select_filter;

             gvars.qrcode.type = 'collection';
             
             multi_WriteItemResponseQuery(data, true, "W");
               // toonResultaten();
        })
        .catch(function(error) {
            console.log('Ajax call failed:', error.errorThrown);
            console.log('passObject:', error.passObject);
             loading("off");

            // Your error handling logic here
        });






    // // Example usage in a loop
    // for (var i = 0; i < yourArray.length; i++) {
    //     var ajax_url = service_url + 'Items/BrandLookSeries?' + yourArray[i];
    //     var passObject = {
    //         xroom: "AAA",
    //         xlayer: "BBB",
    //     };

    //     makeAjaxCall(ajax_url, passObject)
    //         .then(function(response) {
    //             console.log('Ajax call succeeded:', response.data);
    //             console.log('passObject:', response.passObject);
    //             // Your success logic here
    //         })
    //         .catch(function(error) {
    //             console.log('Ajax call failed:', error.errorThrown);
    //             console.log('passObject:', error.passObject);
    //             // Your error handling logic here
    //         });
    // }
}


function reset_collection_radio(){
    console.log('reset_collection_radio');
    $('.collectie_look_item_wrapper.active').removeClass('active');
}

function after_multi_WriteItemResponseQuery(response) {

    

    // multi-clickevents.js
    // $(document).on(click_touch, ".size-chart-wall .listed li", function(e) {
    // if (e.hasOwnProperty("originalEvent") && e.originalEvent.hasOwnProperty("isTrusted") && e.originalEvent.isTrusted) {
        $(".toon_results_wrapper .toon_results").removeClass("initial_toon_results");
    // }


    console.log(`Log: remove busy from 'toon_results' `);
    $(".toon_results").removeClass("disableToon");
    // if (response.length == 1) resultaat_text = ' resultaat'; else resultaat_text = ' resultaten';
    if (response.length == 1) resultaat_text = ' tegel'; else resultaat_text = ' tegels';
    $(".toon_results").html("Toon " + response.length + resultaat_text);
    $(".results_header_resultaten_digit").html(response.length);
}


function on_ajax_start(message){

    console.log('--- on_ajax_start ---')
    
    // abort_all_ajax();


    $("div.toon_results").addClass("disableToon");
    global_xbusy(1);
    loading("on");
}
             
function on_ajax_end(message){

    console.log('--- on_ajax_end ---')
    loading("off");
    global_xbusy(0);

    console.log(`Log: remove busy from 'toon_results' `);
    $(".toon_results").removeClass("disableToon");
}


function reset_all_filters(){


    console.log('reset_all_filters()');
    
    // 12-08-2024
    // $('.color.total_color').click();

    // 12-08-2024 added
    $("ul.color-list li.color").removeClass("active");
    $('.color.grijs').click();
    $('.color.grijs.active').removeClass('active');
    $(".results-wall").html("");
    reset_tile_results();

    // eof 12-08-2024

    show_more_selector('all');
    reset_collection_radio();
    $('.ul-color-look-wrapper.is-open').removeClass('is-open');
    $('.filter_merk_item').addClass('do_merk_collaps');


    console.log('Triggering kleur look formaat radio button' );
    $("input#properties_id").trigger("click");

    // --------------------- bugs fixing --------------
    $('.results_header_resultaten_digit').html('0');
    $('.pen_icon.svg_active .pen_icon_total_wrapper').remove();
    $('.shaz_container_border_bg_footer .toon_results').addClass('toon_merkenresults_wrapper').html('');



}



document.addEventListener('DOMContentLoaded', function () {
    // $('body').append('<div id="kenBurnsContainer" class="ken-burns-container"></div>');
    
    var kenBurnsContainer = document.createElement('div');
    kenBurnsContainer.id = 'kenBurnsContainer';
    kenBurnsContainer.className = 'ken-burns-container';
    document.body.appendChild(kenBurnsContainer);


});



function show_video(index){

    console.log('function ---- show_video = ', index);
 
    f_hookend(11);
    console.log('f_hookend(11)');

    if (typeof index =='undefined') {

        console.log('---- rooms_object[global_roomId].group_type ', rooms_object[global_roomId].group_type);

        index = rooms_object[global_roomId].group_type;
    }

    // if (index=='keuken') debugger;


    const kenBurn_imageArray = {
      'badkamer'   : global_data.ken_imgs['badkamer'],
      'keuken'     : global_data.ken_imgs['keuken'],
      'slaapkamer' : global_data.ken_imgs['slaapkamer'],
      'woonkamer'  : global_data.ken_imgs['woonkamer']
      // 'tuin'       : global_data.ken_imgs['outdoor-1'],
    };
 
    changeImage(index);




    function changeImage(imageKey) {
      const container = $('#kenBurnsContainer');
      const imageUrl = kenBurn_imageArray[imageKey];

      if (container.length === 0) {
        // If container doesn't exist, create it
        $('body').append('<div id="kenBurnsContainer" class="ken-burns-container"></div>');
      }

      const newImage = $('<img>', {
        class: 'ken-burns-image',
        src: imageUrl,
        alt: 'Ken Burns Effect Image',
      });

      // Check if there are visible children
      const visibleChildren = container.children().filter(":visible");

      if (visibleChildren.length > 0) {
        // Append the new image behind the existing image
        container.append(newImage);

        // Fade out the existing image
        visibleChildren.animate({ opacity: 0 }, 300, function () {
          // Remove the older image after the transition
          $(this).remove();
        });

        // visibleChildren.remove();

        // Fade in the new image
        newImage.css('opacity', 1);
      } else {
        // If there are no visible children, simply append the new image
        container.append(newImage.css('opacity', 1));
      }
    }




    // function changeImage(imageKey) {
    //   const container = $('#kenBurnsContainer');
    //   const imageUrl = kenBurn_imageArray[imageKey];

    //   // Callback to be executed after ensuring the container is in the DOM
    //   const appendImageCallback = function () {
    //     const visibleChildren = container.children().filter(":visible");
    //     const newImage = $('<img>', {
    //       class: 'ken-burns-image',
    //       src: imageUrl,
    //       alt: 'Ken Burns Effect Image',
    //     });

    //     if (visibleChildren.length > 0) {
    //       container.append(newImage);

    //       visibleChildren.fadeOut(1000, function () {
    //         $(this).remove();
    //       });

    //       newImage.hide().fadeIn(1000);
    //     } else {
    //       container.append(newImage.fadeIn(1000));
    //     }
    //   };

    //   // Disconnect existing observer if it exists
    //   if (window.myObserver) {
    //     window.myObserver.disconnect();
    //   }

    //   // Use MutationObserver to watch for changes to the DOM
    //   window.myObserver = new MutationObserver(function (mutations) {
    //     mutations.forEach(function (mutation) {
    //       // Check if the container was added
    //       if ($(mutation.target).is(container)) {
    //         // Disconnect the observer once the container is added
    //         window.myObserver.disconnect();
    //         // Execute the callback after ensuring the container exists
    //         appendImageCallback();
    //       }
    //     });
    //   });

    //   // Start observing the DOM for changes
    //   window.myObserver.observe(document.body, { childList: true, subtree: true });

    //   // If container doesn't exist, create it
    //   if (container.length === 0) {
    //     $('body').append('<div id="kenBurnsContainer" class="ken-burns-container"></div>');
    //   } else {
    //     // If container already exists, execute the callback directly
    //     appendImageCallback();
    //   }
    // }

     









}


// remove initial active ruimte group from vertical menu

var remove_initial_active_ruimte;


jQuery(document).ready(function($) {
      remove_initial_active_ruimte = (function() {
      // Use a static variable to track whether the action has been performed
      let actionPerformed = false;

      // Return a function that performs the action only once
      return function() {
        if (!actionPerformed) {
          // Perform the action
          console.log("/# perform action: remove initial active ruimte group from vertical menu #/");
          $('.floating_wrapper.ft_roomselect.vid_menu .floating_tab_active').removeClass('floating_tab_active');
          // Update the static variable to indicate that the action has been performed
          actionPerformed = true;
        } else {
          console.log("Action already performed.");
        }
      };
    })();

});



function toggleFullScreen() {
  if ((document.fullScreenElement && document.fullScreenElement !== null) ||    
   (!document.mozFullScreen && !document.webkitIsFullScreen)) {
    if (document.documentElement.requestFullScreen) {  
      document.documentElement.requestFullScreen();  
    } else if (document.documentElement.mozRequestFullScreen) {  
      document.documentElement.mozRequestFullScreen();  
    } else if (document.documentElement.webkitRequestFullScreen) {  
      document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);  
    }  
  } else {  
    if (document.cancelFullScreen) {  
      document.cancelFullScreen();  
    } else if (document.mozCancelFullScreen) {  
      document.mozCancelFullScreen();  
    } else if (document.webkitCancelFullScreen) {  
      document.webkitCancelFullScreen();  
    }  
  }  
}



function isFullScreen() {
    return !!(
        document.fullscreenElement || 
        document.webkitFullscreenElement || 
        document.mozFullScreenElement || 
        document.msFullscreenElement
    );
}

function handleFullScreenChange() {
    if (isFullScreen()) {
         $('.toggle_fscreen').removeClass('normal_screen');
        console.log("Entered full screen mode.");
    } else {
        console.log("Exited full screen mode.");
         $('.toggle_fscreen').addClass('normal_screen');
    }
}

document.addEventListener('fullscreenchange', handleFullScreenChange);
document.addEventListener('webkitfullscreenchange', handleFullScreenChange);
document.addEventListener('mozfullscreenchange', handleFullScreenChange);
document.addEventListener('MSFullscreenChange', handleFullScreenChange);


