

function mt_scroll_to_error(element)
{
	var header_element = $(".navbar:first");
	var header_height = header_element.length > 0 ? $(header_element).height() : 100;

	if(!element){
		return;
	}
	setTimeout(function(){
		var offset = $(element).offset();
		
		if(!offset){
			return;
		}

		if($(window).scrollTop() > offset.top-header_height){
			window.scrollTo({
				top: Math.max(0,offset.top-header_height),
				behavior: "smooth"
			});
		}else if($(window).scrollTop()+$(window).height() < offset.top){
			window.scrollTo({
				top: Math.max(0,offset.top-$(window).height()+$(element).outerHeight(true)),
				behavior: "smooth"
			});
		}
	},100); // show topmost error
}

function mt_scroll_to_top(selector)
{
	var header_element = $(".navbar:first");
	var header_height = header_element.length > 0 ? $(header_element).height() : 100;

	if(!selector){
		return;
	}
	setTimeout(function(){
		var element = $(selector);
		if(element.length == 0){
			return;
		}
		var offset = $(element).offset();
		window.scrollTo({
			top: Math.max(0,offset.top-header_height),
			behavior: "smooth"
		});
	},10); // scroll window to put element on the top edge of the screen
}

function mt_report_error(e, subject)
{
$.ajax({type:'post',data:{'responseText':subject,
	page:window.location.href,
	exception_message:e.message,
	exception_toString:e.toString(),
	exception_stack:e.stack
	}, url:'/ajax.php?action=report_error'});
}

function mt_save_event(params)
{
$.ajax({type:'post',data:JSON.parse(JSON.stringify(params)), url:'/ajax.php?action=save_event'});
}

function data_layer_event(type, field, content, label)
{
	var obj = {'timestamp': Date.now() };
	content = $('<span>'+content+'</span>').text();
	obj['event'] = type+' '+field+' '+content; 
	if(label){
		obj['custom_label'] = label;
	}
	window.dataLayer = window.dataLayer || [];
	window.dataLayer.push(obj);
}

function data_layer_event_with_variables(event, variables = {})
{
	let obj = {'timestamp': Date.now()};
	obj['event'] = event;

	for (let key in variables) {
		obj[key] = variables[key];
	}

	window.dataLayer = window.dataLayer || [];
	window.dataLayer.push(obj);
}

window.addEventListener('DOMContentLoaded', function(){
	localStorage.removeItem("alert_banner_dismiss");

	$('body').on('click','[data-popup-url]',function(){
		$('#popup_modal_iframe').attr('src', $(this).attr('data-popup-url'));
		mt_modal.show('#popup_modal_holder', function(){
			$('#popup_modal_iframe').attr('src', null);
		});
		
	}).on('click',"[data-href]",function(e){
		e.preventDefault();
		window.location=$(this).attr("data-href");
		
	}).on('mt.lazyload', function(event){ // Lazy loading when event 'mt.lazyload' arrive
		
		$("[data-ll-src],[data-ll-back]", event.target).each(function(){
			
			if($(this).attr('data-ll-src')){
				$(this).attr('data-lll-src', $(this).attr('data-ll-src')).attr('data-ll-src', null);
			}
			
			if($(this).attr('data-ll-back')){
				$(this).attr('data-lll-back', $(this).attr('data-ll-back')).attr('data-ll-back', null);
			}
			
			lazy_load_element(this);
		});
	});
	
	
	$(window).scroll(function(){
		handle_scroll_lazy_loading();
	}).resize(function(){
		handle_scroll_lazy_loading();
	});
	
	window.addEventListener('load', function(){
		handle_scroll_lazy_loading();
	});
	
	// Lazy load of CSS files
	$("[data-ll-href]").each(function(){
		$(this).attr('href', $(this).attr('data-ll-href')).attr('data-ll-href', null);
	});

	// Decode Ads blocks
	$(".mt-page-ads").each(function(){
		/*var c = atob($(this).text());
		console.log(c);
		$(this).html(c).css('opacity',1);*/
		$(this).css('opacity',1);
	});
});

function handle_scroll_lazy_loading()
{
	$("[data-lll-src],[data-lll-back]", event.target).each(function(){
		lazy_load_element(this);
	});
}

function lazy_load_element(element)
{
	var limit = $(window).height() + $(window).scrollTop(),
		offset = $(element).offset();
	if((offset.top > 0 || offset.left > 0) // make sure element visible
		&& offset.top < limit+300 // make sure element soon appear on the screen
		){
		// Images
		if($(element).attr('data-lll-src')){
			$(element).attr('src', $(element).attr('data-lll-src')).attr('data-lll-src', null);
		}
		// Load lazy background images after "load" event
		if($(element).attr('data-lll-back')){
			$(element).css('background-image', 'url('+$(element).attr('data-lll-back')+')')
				.attr('data-lll-back', null);
		}
	}
}

function setup_popup_onclick(element_selector, on_close_callback)
{
	var width = Math.ceil(100-(((screen.width-1024)/screen.width)*100));
	var height = Math.ceil(100-(((screen.height-768)/screen.height)*100));
	var params = {
		width: (width > 100 ? 100 : width)+'%',
		height: '100%',
		autoScale: false,
		transitionIn: 'none',
		transitionOut: 'none',
		type: 'iframe',
		centerOnScroll: true,
		margin: (window.screen.availWidth < 375 ? 0 : 14),
		padding: 0,
		titleShow: false,
		onStart: function() { $('#fancybox-outer').addClass('fancybox_loading_big'); },
		onClosed: function() { $('#fancybox-outer').removeClass('fancybox_loading_big');
			if(on_close_callback){
				on_close_callback();
			}
		}
	};
	//params['height'] = (height > 100 ? 100 : height)+'%';
	$(element_selector).fancybox(params);
}




/**
 * String.padStart()
 * version 1.0.1
 * Feature	        Chrome  Firefox Internet Explorer   Opera	Safari	Edge
 * Basic support	57   	51      (No)	            44   	10      15
 * -------------------------------------------------------------------------------
 */
if (!String.prototype.padStart) {
  Object.defineProperty(String.prototype, 'padStart', {
    configurable: true,
    writable: true,
    value: function (targetLength, padString) {
      targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
      padString = String(typeof padString !== 'undefined' ? padString : ' ');
      if (this.length > targetLength) {
        return String(this);
      } else {
        targetLength = targetLength - this.length;
        if (targetLength > padString.length) {
          padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
        }
        return padString.slice(0, targetLength) + String(this);
      }
    },
  });
}

String.prototype.allReplace = function(obj) {
	var retStr = this;
	for (var x in obj) {
	  retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
	}
	return retStr;
};

function mt_round(value, digits)
{
	digits = digits ? digits : 0;
	let base = Math.pow(10, digits);
	return Math.round(value*base)/base;
}

function mt_dtz_autodetect()
{
	var tz_offset = (new Date).getTimezoneOffset();
	return 'UTC'+(Math.sign(tz_offset)>0?'-':'+')
			+(''+Math.abs(Math.round(tz_offset/60))).padStart(2,'0')
			+':'
			+(''+Math.abs(tz_offset%60)).padStart(2,'0');
}

function mt_wait_and_run(wait_callback, run_callback)
{
	if(wait_callback()){
		run_callback();
		return;
	}
	
	setTimeout(function(){
		mt_wait_and_run(wait_callback, run_callback);
	}, 20);
}
