// source --> https://makasete-kyuutou.jp/wp-content/plugins/search-filter-elementor/assets/v2/js/search-filter-elementor.js?ver=1.3.4 
(function ($) {
	"use strict";
	$(function () {
		// re init layout after ajax request
		$(document).on("sf:ajaxfinish", ".searchandfilter", function (e, data) {
			if (window.elementorFrontend && window.elementorFrontend.elementsHandler && window.elementorFrontend.elementsHandler.runReadyTrigger) {
				setTimeout(function () {
					var runReadyTrigger = window.elementorFrontend.elementsHandler.runReadyTrigger;
					runReadyTrigger($(data.targetSelector));
					var ajaxTarget = $(data.targetSelector);
					if (ajaxTarget.length > 0) {
						ajaxTarget.find('.elementor-widget').each(function () {
							runReadyTrigger($(this));
						});
					}
				}, 100);
			}
		});
	});

	// Detects the end of an ajax request being made.
	var forms = [];
	$(document).on("sf:ajaxfinish", ".searchandfilter", function (e, form) {
		var $form = $('.searchandfilter[data-sf-form-id=' + form.sfid + ']')
		forms[form.sfid] = $form[0].innerHTML;
	});

	// load search forms in popups
	$(window).on('elementor/frontend/init', function () {
		// Search forms in popups reset to their page load state every time they are shown.
		// So we need to keep track of the latest one, and reload it into the popup when it is shown.
		if (window.elementorFrontend) {
			window.elementorFrontend.elements.$window.on('elementor/popup/show', (e, id, document) => {
				if ($().searchAndFilter) {
					var $sliders = $('.elementor-popup-modal .searchandfilter .meta-slider');
					if ($sliders.length > 0) {
						$sliders.empty();
					}

					// Get the forms ID:
					$('.elementor-popup-modal .searchandfilter').each(function () {
						var $form = $(this);
						$form.off();
						var formId = $form.data('sf-form-id');
						if (forms[formId]) {
							// Replace the form with the latest version:
							$form.html(forms[formId])
						}
						$form.searchAndFilter();

					});
				}
			});
		}
	});

}(jQuery));
// source --> https://makasete-kyuutou.jp/wp-content/plugins/addon-elements-for-elementor-page-builder/assets/js/iconHelper.js?ver=1.0 
window.eae = {};
window.renderIconHtml = function(view,elementor,sett,control_name, wClass = '', index=''){
    // console.log("View => ", view);
    // data.addRenderAttribute('key', 'context', 'value');
    // console.log(data.getRenderAttributeString('key'));

    var icon_class = '';
    let imageHtml = '';
    let lottie_data = [];
    let iconHtml = '';
    if(sett[control_name+'_graphic_type'] != 'none' && sett[control_name+'_graphic_type'] != ''){
        icon_class += ' eae-gbl-icon eae-graphic-type-'+ sett[control_name+'_graphic_type'] + ' elementor-animation-' + sett[control_name+'_hover_animation'];
        if(wClass != ''){
            icon_class += ' '+wClass;     
        }

        icon_class += ' eae-graphic-view-'+sett[control_name+'_view']; 
        if(sett[control_name+'_view'] != 'default'){
            icon_class += ' eae-graphic-shape-'+sett[control_name+'_shape'];
        }

        if(sett[control_name+'_graphic_type'] == 'lottie'){
            if( (sett[control_name+'_lottie_animation_url'] != '' ) ||  (sett[control_name+'_source_json']['url'] != '') ) {
                icon_class += ' eae-lottie-animation eae-lottie';
                lottie_data = {
                    'loop' : ( sett[control_name+'_lottie_animation_loop'] === 'yes' ) ? true : false,
                    'reverse' : ( sett[control_name+'_lottie_animation_reverse'] === 'yes' ) ? true : false,
                } 
                if(sett[control_name+'_source'] == 'media_file' && (sett[control_name+'_source_json']['url'] != '')){
                    lottie_data.url = sett[control_name+'_source_json']['url'];
                }else{
                    lottie_data.url = sett[control_name+'_lottie_animation_url'];
                }
                view.addRenderAttribute('panel-icon-'+ index, 'data-lottie-settings', JSON.stringify(lottie_data));
            }         
        }
        view.addRenderAttribute('panel-icon-'+ index, 'class', icon_class);
        if(sett[control_name+'_graphic_type'] == 'lottie' ){
            if(lottie_data.url != undefined){
                iconHtml = `<span ${view.getRenderAttributeString( 'panel-icon-'+ index )}></span>`;    
            }
        }else{
            if(sett[control_name+'_graphic_type'] === 'icon'){
                if(sett[control_name+'_graphic_icon']['value'] != ''){
                    var icon = elementor.helpers.renderIcon( view, sett[control_name+'_graphic_icon'], { 'aria-hidden': true }, 'i' , 'object' );
                    imageHtml = icon.value;
                    iconHtml = `<span ${ view.getRenderAttributeString( 'panel-icon-'+ index ) }>
                                ${imageHtml}
                                </span>`;
                }            
            }else{
                if(sett[control_name+'_graphic_image']['url'] != ''){
                    var image = {
                        id: sett[control_name+'_graphic_image']['id'],
                        url: sett[control_name+'_graphic_image']['url'],
                        size: sett[control_name+'_graphic_image_size'],
                        dimension: sett[control_name+'_graphic_image_custom_dimension'],
                        model: view.getEditModel()
                    };
                    var image_url = elementor.imagesManager.getImageUrl( image );
                    imageHtml = '<img src="' + image_url + '" />';
                    
                    iconHtml = `<span ${ view.getRenderAttributeString( 'panel-icon-'+ index ) }>
                                    ${imageHtml}
                                </span>`;
                }
            }
        }       
    }
    return iconHtml;
}

window.eae.validateHTMLTag = function( $tag, $collection = null, $fallback = null){
   if($collection == null){
        $collection = ['h1','h2','h3','h4','h5','h6','p','span','div'];
   }
   if($fallback == null){
    $fallback = 'h3';
   }    
   if($collection.includes($tag)){
        return $tag;
   }else{
        return $fallback;
   }
};
// source --> https://makasete-kyuutou.jp/wp-content/plugins/duracelltomi-google-tag-manager/js/analytics-talk-content-tracking.js?ver=1.22.3 
/*
 * Source: http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-analytics-part-1/
 * Original authors:
 *  - Nick Mihailovski
 *  - Thomas Baekdal
 *  - Avinash Kaushik
 *  - Joost de Valk
 *  - Eivind Savio
 *  - Justin Cutroni
 *
 * Google Tag Manager dataLayer events added by:
 *   Thomas Geiger
 *   gtm4wp.com
 */

if ( "undefined" == typeof console ) {
	window.console = {
		log: function () {}
	};
}

(function(  ) {
	// Debug flag
	const debugMode      = gtm4wp_scrollerscript_debugmode;

	// Default time delay before checking location
	const callBackTime   = gtm4wp_scrollerscript_callbacktime;

	// # px before tracking a reader
	const readerLocation = gtm4wp_scrollerscript_readerlocation;

	// Set some flags for tracking & execution
	let timer       = 0;
	let scroller    = false;
	let endContent  = false;
	let didComplete = false;

	// Set some time variables to calculate reading time
	const startTime = new Date();
	const beginning = startTime.getTime();
	let totalTime = 0;

	// Track the aticle load
	if ( !debugMode ) {
		window[ gtm4wp_datalayer_name ].push({
			'event': 'gtm4wp.reading.articleLoaded'
		});
	} else {
		console.log( 'Article loaded' );
	}

	// Check the location and track user
	function trackLocation() {
		//const bottom = $( window ).height() + $( window ).scrollTop();
		const bottom = window.innerHeight + window.scrollY;
		//const height = $( document ).height();
		const height = document.body.offsetHeight
		let scrollStart = 0;

		// If user starts to scroll send an event
		if ( bottom > readerLocation && !scroller ) {
			const currentTime = new Date();
			scrollStart = currentTime.getTime();
			const timeToScroll = Math.round( ( scrollStart - beginning ) / 1000 );

			if ( !debugMode ) {
				window[ gtm4wp_datalayer_name ].push({
					'event': 'gtm4wp.reading.startReading',
					'timeToScroll': timeToScroll
				});
			} else {
				console.log( 'Started reading ' + timeToScroll );
			}
			scroller = true;
		}

		// If user has hit the bottom of the content send an event
		//if ( bottom >= $( '#' + gtm4wp_scrollerscript_contentelementid ).scrollTop() + $( '#' + gtm4wp_scrollerscript_contentelementid ).innerHeight() && !endContent ) {
		const scroll_top = document.querySelector('#' + gtm4wp_scrollerscript_contentelementid)?.scrollTop || 0;
		const client_height = document.querySelector('#' + gtm4wp_scrollerscript_contentelementid )?.clientHeight || 0;
		if ( bottom >= scroll_top + client_height && !endContent ) {
			
			const currentTime = new Date();
			const contentScrollEnd = currentTime.getTime();
			const timeToContentEnd = Math.round( ( contentScrollEnd - scrollStart ) / 1000 );

			if ( !debugMode ) {
				window[ gtm4wp_datalayer_name ].push({
					'event': 'gtm4wp.reading.contentBottom',
					'timeToScroll': timeToContentEnd
				});
			} else {
				console.log( 'End content section ' + timeToContentEnd );
			}

			endContent = true;
		}

		// If user has hit the bottom of page send an event
		if ( bottom >= height && !didComplete ) {
			const currentTime = new Date();
			const end = currentTime.getTime();
			totalTime = Math.round( ( end - scrollStart ) / 1000 );

			if ( !debugMode ) {
				if ( totalTime < gtm4wp_scrollerscript_scannertime ) {
					window[ gtm4wp_datalayer_name ].push({
						'event': 'gtm4wp.reading.readerType',
						'readerType': 'scanner'
					});
				} else {
					window[ gtm4wp_datalayer_name ].push({
						'event': 'gtm4wp.reading.readerType',
						'readerType': 'reader'
					});
				}

				window[ gtm4wp_datalayer_name ].push({
					'event': 'gtm4wp.reading.pagebottom',
					'timeToScroll': totalTime
				});
			} else {
				if ( totalTime < gtm4wp_scrollerscript_scannertime ) {
					console.log( 'The visitor seems to be a "scanner"' );
				} else {
					console.log( 'The visitor seems to be a "reader"' );
				}

				console.log( 'Bottom of page ' + totalTime );
			}

			didComplete = true;
		}
	}
	
	// Track the scrolling and track location
	//$( window ).scroll(function() {
	document.addEventListener("scroll", function(event){
		if ( timer ) {
			clearTimeout( timer );
		}

		// Use a buffer so we don't call trackLocation too often.
		timer = setTimeout( trackLocation, callBackTime );
	});
})(window, document);