// ---------------------------------------------------------------------------------------------]
// ---------------------------------------------------------------------------------------[ ALL ]
// ---------------------------------------------------------------------------------------------]

/*
*  ALL ::: Notificação ( Sweet Alert 2 )
*/

function sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult) {
	if(swalCancelButtonText != "") {
		swalShowCancelButton = true;
	}
	else {
		swalShowCancelButton = false;
	}

	Swal.fire({ 
		title: 							'',
		html: 							swalHtml,
		confirmButtonText:  swalConfirmButtonText,
		cancelButtonText:   swalCancelButtonText,
		allowOutsideClick:  false,
		allowEscapeKey:     false,
		showCancelButton: 	swalShowCancelButton,
		customClass: {
			popup: 		'w-100',
			actions: 	'p-2 pt-3 m-0',
		},
		showClass: {
			popup: 'animated bounceInUp faster'
		},
		hideClass: {
			popup: 'animated bounceOutDown faster'
		},
		position: 'bottom'
	})
	.then((result) => { 
		if(swalIsConfirmed == 1) {
			if(swalResult != "") {
				if (result.isConfirmed) { 
					eval(swalResult);
				} 
				else {
					console.log("Condição ainda não criada, código: #SWAL-0001");
				}
			}
			else {
				console.log("Condição ainda não criada, código: #SWAL-0002");
			} 
		}
		else {			
			if(swalResult != "") {
				eval(swalResult);
			}
			else {
				console.log("Condição ainda não criada, código: #SWAL-0003");
			}
		}
	});
}

/*
* ALL ::: isEmpty
*/

function isEmpty( el ) {
	return !$.trim( el.html() );
}

/*
* ALL ::: Menu Cookies
*/

$(document).ready(function() {
	if ($.cookie) {
		var cookieContainer = $(".container-cookie");

		$('.btn-cookie').on('click', function(event) {
			event.preventDefault();
			$.cookie("cookie-declaracao-de-privacidade", 1, { expires: 10 });
			cookieContainer.addClass('d-none');
		});

		var cookieValue = $.cookie("cookie-declaracao-de-privacidade");

		if (cookieValue) {
			cookieContainer.addClass('d-none');
		} 
		else {
			cookieContainer.removeClass('d-none');
		}
	} 
	else {
		console.error("O plugin jquery.cookie não está carregado.");
	}
});

/*
* ALL ::: Toastr Notification
*/

function toastShow(icon, title, message, type, delay, hide) {
	var toastKey 				= Math.floor((Math.random() * 10000) + 1);
	var toastIcon  	  	= icon;
	var toastTitle 	  	= title;
	var toastMessage  	= message;
	var toastType 			= type;
	var toastDelay 			= delay;
	var toastAutohide 	= hide;

	var html = "";

	html += '<div class="toast ' + toastType + ' toast-key-' + toastKey + ' shadow" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="' + toastDelay + '" data-bs-autohide="' + toastAutohide + '" data-key="' + toastKey + '">';
	html += '	<div class="toast-header">';
	html += 		toastIcon;
	html += '		<strong class="me-auto">';
	html += 			toastTitle;
	html += '		</strong>';
	html += '		<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close">';
	html += '			<i class="fa-light fa-xmark"></i>';
	html += '		</button>';
	html += '	</div>';
	html += '	<div class="toast-body">';
	html += 		toastMessage;
	html += '	</div>';
	html += '</div>';

	$( '.toast-container' ).append( html );

	var toastCollection = $(".toast");

	toastCollection.each(function() {
		var toastItem = new bootstrap.Toast( $(this) ).show();

		$(this).on('hidden.bs.toast', function(event) {
			event.preventDefault();

			$('.toast-key-' + $(this).data('key')).remove();
		});
	});
}

const Toast = Swal.mixin({
	toast: true,
	position: 'top-end',
	showConfirmButton: false,
	timer: 3000,
	timerProgressBar: true,
	didOpen: (toast) => {
		toast.addEventListener('mouseenter', Swal.stopTimer)
		toast.addEventListener('mouseleave', Swal.resumeTimer)
	}
});

/*
* ALL ::: Menu Mobile
*/

var overlayNav 	= $('.cd-overlay-nav'),
overlayContent 	= $('.cd-overlay-content'),
navigation 			= $('.cd-primary-nav'),
toggleNav 			= $('.cd-nav-trigger');

$(window).on('resize', function() {
	window.requestAnimationFrame(layerInit);
});

toggleNav.on('click', function() {
	if(!toggleNav.hasClass('close-nav')) {
		toggleNav.addClass('close-nav');
		$('html').css('overflow', 'hidden');  

		overlayNav.children('span').velocity({
			translateZ: 0,
			scaleX: 		1,
			scaleY: 		1,
		}, 500, 'easeInCubic', function() {
			navigation.addClass('fade-in');
		});
	} 
	else {
		toggleNav.removeClass('close-nav');
		$('html').css('overflow', 'unset');

		overlayContent.children('span').velocity({
			translateZ: 0,
			scaleX: 		1,
			scaleY: 		1,
		}, 500, 'easeInCubic', function() {
			navigation.removeClass('fade-in');

			overlayNav.children('span').velocity({
				translateZ: 0,
				scaleX: 		0,
				scaleY: 		0,
			}, 0);

			overlayContent.addClass('is-hidden').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
				overlayContent.children('span').velocity({
					translateZ: 0,
					scaleX: 		0,
					scaleY: 		0,
				}, 0, function() {
					overlayContent.removeClass('is-hidden');
				});
			});

			if($('html').hasClass('no-csstransitions')) {
				overlayContent.children('span').velocity({
					translateZ: 0,
					scaleX: 		0,
					scaleY: 		0,
				}, 0, function() {
					overlayContent.removeClass('is-hidden')
				});
			}
		});
	}
});

function layerInit() {
	var diameterValue = (Math.sqrt( Math.pow($(window).height(), 2) + Math.pow($(window).width(), 2))*2);

	overlayNav.children('span').velocity({
		scaleX: 		0,
		scaleY: 		0,
		translateZ: 0,
	}, 50).velocity({
		height : 	diameterValue + 'px',
		width : 	diameterValue + 'px',
		top : 		-(diameterValue/2) + 'px',
		left : 		-(diameterValue/2) + 'px',
	}, 0);

	overlayContent.children('span').velocity({
		scaleX: 		0,
		scaleY: 		0,
		translateZ: 0,
	}, 50).velocity({
		height: 	diameterValue + 'px',
		width: 		diameterValue + 'px',
		top: 			-(diameterValue/2) + 'px',
		left: 		-(diameterValue/2) + 'px',
	}, 0);
}

layerInit();

/*
* ALL ::: Anchor
*/

$('.page-scroll').bind('click', function(event) {
	var id = $(this).data('anchor');

	$('html.mobile .side-panel-close').click();

	$('html, body').animate({
		scrollTop: $('.anchor-' + id).offset().top - 50
	}, 500);
});

/*
* ALL - Set #fff or #000 by the brightness of colour
*/

function setContrast(color) {
	var c 	= color.substring(1);   
	var rgb = parseInt(c, 16);   
	var r 	= (rgb >> 16) & 0xff;  
	var g 	= (rgb >>  8) & 0xff;  
	var b 	= (rgb >>  0) & 0xff;  

	const brightness = Math.round(((parseInt(r) * 299) + (parseInt(g) * 587) + (parseInt(b) * 114)) / 1000);
	const textColour = (brightness > 125) ? '#000' : '#fff';

	return textColour;
}

/*
* ALL :: Magnific Popup
*/

$('.popup-with-zoom-anim').magnificPopup({
	type: 'inline',
	midClick: true,
	mainClass: 'mfp-fade'
});

// ---------------------------------------------------------------------------------------------]
// -----------------------------------------------------------------------------------[ BUTTONS ]
// ---------------------------------------------------------------------------------------------]

var btnCopy = $('.btn-copy');

if(btnCopy.length > 0) {
	btnCopy.click(function() {
		var dataCopyValue = $(this).data("copy");
		var $tempTextArea = $("<textarea>");
		$("body").append($tempTextArea);

		$tempTextArea.val(dataCopyValue);
		$tempTextArea.select();
		document.execCommand("copy");
		$tempTextArea.remove();

		var swalHtml = "";
		swalHtml += '<i class="fa-light fa-check text-success text-12 mb-3"></i><br/>';
		swalHtml += '<h1>Tudo certo!</h1>';
		swalHtml += '<p class="mb-0 text-lowercase">Código copiado para a área de transferência: <b class="text-color-secondary">' + dataCopyValue + '</b></p>';

		var swalConfirmButtonText = 'Obrigado <i class="fa-light fa-arrow-right ms-1"></i>';
		var swalCancelButtonText 	= ''
		var swalIsConfirmed 			= 0;
		var swalResult 						= '';

		sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult);
	});
}

// ---------------------------------------------------------------------------------------------]
// -------------------------------------------------------------------------------------[ INPUT ]
// ---------------------------------------------------------------------------------------------]

/*
* INPUT ::: Mask
*/

function inputMask() {
	$('.mask-dinheiro').mask('000.000.000.000.000,00', {reverse: true});
	$('.mask-cnpj').mask('00.000.000/0000-00');
	$('.mask-cpf').mask('000.000.000-00');
	$('.mask-cep').mask('00000-000');
	$('.mask-data').mask('00/00/0000');
	$('.mask-phone').mask('(00) 0000-00009');

	$('.mask-phone').blur(function(event) {
		if($(this).val().length == 15) { 
			$(this).mask('(00) 00000-0009');
		} 
		else {
			$(this).mask('(00) 0000-00009');
		}
	});
}

inputMask();

/*
* INPUT ::: Switchery
*/

var countSwitchery = $('.js-switch').length;

if(countSwitchery == 1) {
	singleSwitchery();		
}
else if(countSwitchery > 1) {
	multiSwitchery();		
} 

function singleSwitchery() {
	var elem = document.querySelector('.js-switch');
	var btn  = $('.btn-submit');

	var init = new Switchery(elem, { 
		size: 'small', 
		color: '#64bd63', 
		secondaryColor: '#f44336', 
		jackColor: null, 
		jackSecondaryColor: null
	});

	$(elem).on('change', function(event) {
		event.preventDefault();

		if(elem.checked == true) {
			$('.btn-submit').removeAttr("type").attr("type", "submit");
		}
		else {
			$('.btn-submit').removeAttr("type").attr("type", "button");
		}
	});

	btn.on('click', function() {
		if (!$(elem).is(':checked')) {
			Swal.fire({ 
				title: 							'',
				html: 							'<i class="fal fa-info-circle"></i><br/> É preciso aceitar o Termo de Uso e as Políticas de Privacidade.',
				confirmButtonText:  'Ok <i class="fas fa-angle-right"></i>',
				allowOutsideClick:  false,
				allowEscapeKey:     false,
				showCancelButton: 	false,
				showClass: {
					popup: 'animated fadeInUp faster'
				},
				hideClass: {
					popup: 'animated fadeOutDown faster'
				},
				position: 'bottom'
			});
		}
	});
}

function multiSwitchery() {
	var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));

	elems.forEach(function(elem) {
		if(typeof $(elem).data('switchery') === 'undefined') {
			var switchery = new Switchery(elem, { size: 'small', color: '#64bd63', secondaryColor: '#f44336', jackColor: null, jackSecondaryColor: null });

			$(elem).on('change', function(event) {
				event.preventDefault();

				var key = $(this).data('key');

				if(elem.checked == true) {
					$('.btn-submit-' + key).removeAttr("type").attr("type", "submit");
					$('.btn-submit-' + key).attr("disabled", false);
				}
				else {
					$('.btn-submit-' + key).removeAttr("type").attr("type", "button");
					$('.btn-submit-' + key).attr("disabled", true);
				}
			});
		}
	});
}

/*
* INPUT ::: iChecks
*/

function iChecks() {
	$('.i-checks').iCheck({
		checkboxClass:  'icheckbox_square-green',
		radioClass:     'iradio_square-green',
	});
}

if($('.i-checks').length > 0) {
	iChecks();
}

$('.i-checks.green').iCheck({
	checkboxClass:  'icheckbox_square-green',
	radioClass:     'iradio_square-green',
});

$('.i-checks.red').iCheck({
	checkboxClass:  'icheckbox_square-red',
	radioClass:     'iradio_square-red',
});

// ---------------------------------------------------------------------------------------------]
// --------------------------------------------------------------------------------------[ MAPS ]
// ---------------------------------------------------------------------------------------------]

/*
* MAPS ::: Inicializa o mapa
*/

let map;

function initMapWithMultiPoints(func) {
	map = new google.maps.Map(document.getElementById("mapWithMultiPoints"), {
		center: new google.maps.LatLng(-10.3333333, -53.2),
		zoom: 4
	});

	$.getJSON(BASEURL + '/' + func, function(cadastros) {
		$.each(cadastros, function(index, cadastro) {
			const contentString = 
			'<div id="content">' +
			'	<div id="siteNotice"></div>' +
			'	<h1 id="firstHeading" class="firstHeading text-4 mb-2 lh-1 font-weight-bold">' + cadastro.titulo + '</h1>' +
			'	<div id="bodyContent">' +
			'		<p class="text-color-black lh-1 mb-2">' + cadastro.endereco + '</p>' +
			'		<p class="text-color-black lh-1 mb-2">' + cadastro.local + '</p>' +
			'		<p class="text-color-black lh-1">' + cadastro.contato + '</p>' +
			'	</div>' +
			'</div>';

			const infowindow = new google.maps.InfoWindow({
				content: contentString,
			});

			const marker = new google.maps.Marker({
				position: new google.maps.LatLng(cadastro.latitude, cadastro.longitude),
				icon: ANCHOR_ICON,
				map: map,
				draggable: false,
				animation: google.maps.Animation.DROP,
				title: cadastro.titulo,
			});

			marker.addListener("click", () => {
				infowindow.open(map, marker);
			});
		});
	});
}

function mapsSetLocation(lat, lon, zoom) {
	map.setCenter(new google.maps.LatLng(lat, lon));
	map.setZoom(zoom);
}

/*
* MAPS ::: Inicializa o mapa
*/

function initMapWithSinglePoint() {
	if(INSTITUCIONAL.latitude != "" && INSTITUCIONAL.longitude != "") {
		console.log("Log: A função initMapWithSinglePoint() foi executada.");

		map = new google.maps.Map(document.getElementById("mapWithSinglePoint"), {
			center: new google.maps.LatLng(INSTITUCIONAL.latitude, INSTITUCIONAL.longitude),
			zoom: 15
		});

		const marker = new google.maps.Marker({
			position: 	new google.maps.LatLng(INSTITUCIONAL.latitude, INSTITUCIONAL.longitude),
			icon: 			ANCHOR_ICON,
			map: 				map,
			draggable: 	false,
			animation: 	google.maps.Animation.DROP,
			title: 			INSTITUCIONAL.titulo
		});

		/*
		* TRUE 	= Mostra os dados do contentString ao clicar no ícone.
		* FALSE = Não faz nada ao clicar.
		*/

		var infoMark = true;

		if(infoMark) {
			const contentString = '' +
			'<div id="content">' + 
			'	<div id="siteNotice"></div>' + 
			'	<h1 id="firstHeading" class="firstHeading mb-0">' + INSTITUCIONAL.titulo + '</h1>' + 
			'	<h3 id="secondHeading" class="secondHeading mb-0">' + INSTITUCIONAL.subtitulo + '</h3>' + 
			'	<div id="bodyContent">' + 
			'		<p class="mb-0">' + INSTITUCIONAL.endereco + '</p>' + 
			'		<p class="mb-0">' + INSTITUCIONAL.cidade + '/' + INSTITUCIONAL.estado + '</p>' + 
			'		<p class="mb-0">' + INSTITUCIONAL.email + '</p>' + 
			'	</div>' + 
			'</div>';

			const infowindow = new google.maps.InfoWindow({
				content: contentString
			});

			marker.addListener("click", () => {
				infowindow.open(map, marker);
			});
		}
	}
	else {
		console.log("Log: A função initMapWithSinglePoint() não foi executada.");
	}
}

if($('#mapWithSinglePoint').length > 0) {
	initMapWithSinglePoint();
}

// ---------------------------------------------------------------------------------------------]
// --------------------------------------------------------------------------------------[ FORM ]
// ---------------------------------------------------------------------------------------------]

/*
* FORM ::: Validator
*/

$.validator.addMethod("noSpace", function(value, element) {
	if ($(element).hasClass('form-control-password')) {
		if ($(element).attr('required')) {
			return value.search(/^[^a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669]|^[a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669]/i) !== -1;
		}
	}
	else {
		if( $(element).attr('required') ) {
			return value.search(/[a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669 ]/i) == 0;
		}
	}
	return true;
}, 'Esta campo não pode ser vazio.');

$.validator.addMethod("customEmail", function(value, element) {
	return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(value);
}, 'Por favor, insira um endereço de e-mail válido.');

$.validator.addMethod("requiredFile", function(value, element) {
	return element.files.length > 0;
}, "Por favor, selecione um arquivo.");

$.validator.addClassRules({
	'form-control': {
		noSpace: true
	},
	'mask-cnpj': {
		noSpace: true
	},
	'mask-cep': {
		noSpace: true
	},
	'mask-phone': {
		noSpace: false
	},
	'file-required': { 
		requiredFile: true 
	}
});

/*
* FORM ::: Contact - Submit
*/

$('.contact-form-recaptcha-v3').each(function() {
	$(this).validate({
		submitHandler: function(form) {
			var $form 				= $(form),
			$submitButton 		= $form.find('.btn-submit'),
			submitButtonText 	= $submitButton.html();

			$submitButton.html("<i class='fad fa-spinner-third fa-spin'></i> Enviando...").prop('disabled', true);

			var site_key = $('#google-recaptcha-v3').attr('src').split("render=")[1];

			grecaptcha.execute(site_key, {action: 'contact_us'}).then(function(token) {
				var formData 	= $form.serializeArray(),
				data 					= {};

				$(formData).each(function(index, obj){
					data[obj.name] = obj.value;
				});

				data["g-recaptcha-response"] = token;

				$.ajax({
					type: 'POST',
					dataType: "JSON",
					url: $form.attr('action'),
					data: data
				})
				.always(function(data, textStatus, jqXHR) {
					if (data.response == 'success') {
						$form.find('.form-control').val('').blur().parent().removeClass('has-success').removeClass('has-danger').find('label.error').remove();

						$form.find('.form-control').removeClass('error');
						$form.find('.form-control').removeClass('is-valid');
						$form.find('.form-control').removeClass('is-invalid');

						$submitButton.html(submitButtonText).prop('disabled', false);

						var swalHtml = "";
						swalHtml += '<i class="fa-light fa-check text-success text-12 mb-3"></i><br/>';
						swalHtml += '<h1>Tudo certo!</h1>';
						swalHtml += '<p class="mb-0 text-lowercase">' + data.successMessage + '</p>';

						var swalConfirmButtonText = 'Obrigado <i class="fa-light fa-arrow-right ms-1"></i>';
						var swalCancelButtonText 	= ''
						var swalIsConfirmed 			= 0;
						var swalResult 						= '';

						sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult);
						return;
					} 
					else if (data.response == 'error') {
						var swalHtml = "";
						swalHtml += '<i class="fa-light fa-xmark text-danger text-12 mb-3"></i><br/>';
						swalHtml += '<h1>Ops!</h1>';
						swalHtml += '<p class="mb-0 text-lowercase">' + data.errorMessage + '</p>';

						var swalConfirmButtonText = 'Obrigado <i class="fa-light fa-arrow-right ms-1"></i>';
						var swalCancelButtonText 	= ''
						var swalIsConfirmed 			= 0;
						var swalResult 						= '';

						sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult);
					} 
					else {
						var swalHtml = "";
						swalHtml += '<i class="fa-light fa-xmark text-danger text-12 mb-3"></i><br/>';
						swalHtml += '<h1>Ops!</h1>';
						swalHtml += '<p class="mb-0 text-lowercase">' + data.errorMessage + '</p>';

						var swalConfirmButtonText = 'Obrigado <i class="fa-light fa-arrow-right ms-1"></i>';
						var swalCancelButtonText 	= ''
						var swalIsConfirmed 			= 0;
						var swalResult 						= '';

						sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult);
					}

					$form.find('.has-success').removeClass('has-success');
					$submitButton.html(submitButtonText).prop('disabled', false);
				});
			});
		}
	});
});

/*
* FORM ::: Estado / Cidade
*/

$('.select-estado').on('change', function(event) {
	event.preventDefault();

	var idEstado 	= $(this).val();

	$.ajax({
		method: "POST",
		url: 		BASEURL + "/DAH_appGetCidades",
		data: { 
			csrf_token: CSRF_TOKEN,
			idEstado:		idEstado
		},
		beforeSend: function( xhr ) {
			$('.select-cidade').html('').append('<option>Carregando cidades...</option>');
		}
	})
	.done(function( result ) {
		var data = $.parseJSON(result);

		$('.select-cidade').html('');

		if(data != "") {
			$('.select-cidade').append('<option value="" selected>Selecione a cidade</option>');

			$.each(data, function(index, val) {
				$('.select-cidade').append('<option value="'+val.id+'">'+val.titulo+'</option>')
			});
		}
		else {
			$('.select-cidade').append('<option value="">Sem cidades encontradas</option>');
		}
	});
});

/*
* FORM ::: Submit
*/

var countSwitcheryForm 	= $('.js-switch-form').length;
var elemFormChecked 		= false;

if(countSwitcheryForm == 1) {
	singleSwitcheryForm();		
}
else if(countSwitcheryForm > 1) {
	multiSwitcheryForm();		
}

function singleSwitcheryForm() {
	var elemForm = document.querySelector('.js-switch-form');

	if(elemForm) {
		var init = new Switchery(elemForm, { 
			size: 'small', 
			color: '#64bd63', 
			secondaryColor: '#f44336', 
			jackColor: null, 
			jackSecondaryColor: null
		});

		$(elemForm).on('change', function(event) {
			event.preventDefault();

			if(elemForm.checked == true) {
				$('.btn-submit').removeAttr("type").attr("type", "submit");
				elemFormChecked = true;
			}
			else {
				$('.btn-submit').removeAttr("type").attr("type", "button");
				elemFormChecked = false;
			}
		});
	}
}

function multiSwitcheryForm() {
	var elemsForm = Array.prototype.slice.call(document.querySelectorAll('.js-switch-form'));

	elemsForm.forEach(function(elemForm) {
		if(typeof $(elemForm).data('switchery') === 'undefined') {
			var switchery = new Switchery(elemForm, { 
				size: 'small', 
				color: '#64bd63', 
				secondaryColor: '#f44336', 
				jackColor: null, 
				jackSecondaryColor: null 
			});

			$(elemForm).on('change', function(event) {
				event.preventDefault();

				var key = $(this).data('key');

				if(elemForm.checked == true) {
					$('.btn-submit-' + key).removeAttr("type").attr("type", "submit");
					elemFormChecked = true;
				}
				else {
					$('.btn-submit-' + key).removeAttr("type").attr("type", "button");
					elemFormChecked = false;
				}
			});
		}
	});
}

$('.btn-submit').on('click', function(event) {
	event.preventDefault();

	if(elemFormChecked === true) {
		var page = $(this).data('page');
		var form = $(this).data('form');
		var url  = $(this).data('url');

		submitForm(form, url);
	}
	else {
		Swal.fire({ 
			title: 							'',
			html: 							'É preciso aceitar o Termo de Uso e as Políticas de Privacidade.',
			confirmButtonText:  'Vou verificar <i class="fa-light fa-arrow-right"></i>',
			allowOutsideClick:  false,
			allowEscapeKey:     false,
			showCancelButton: 	false,
			showClass: {
				popup: 'animated fadeInUp faster'
			},
			hideClass: {
				popup: 'animated fadeOutDown faster'
			},
			position: 'bottom'
		});
	}
});

function submitForm(form, url) {
	grecaptcha.ready(function () {
		grecaptcha.execute('6Ldf58UZAAAAALwADZ_qh30S5Oipx-Ic0BqBv-yI', { action: 'submit' }).then(function (token) {
			$('#recaptchaToken').val(token);

			var CSRF_TOKEN 			= $('input[name="csrf_token"]').val();
			var formData 				= {};
			var fileData 				= {};
			var hasError 				= false;
			var firstErrorField = null;

			$('#' + form).find('input, select, textarea').each(function() {
				var input 				= $(this);
				var inputName 		= input.attr('name');
				var isRequired 		= input.prop('required');
				var errorMessage 	= input.data('msg-required');
				var parentGroup 	= input.closest('.form-group');
				var value 				= input.val() || "";

				if (input.attr('type') === 'file') {
					var files = input[0].files;

					var allowedTypes = [
						'image/png', 
						'image/jpeg', 
						'image/jpg', 
						'application/pdf', 
						'application/msword', 
						'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 
						'application/vnd.ms-excel', 
						'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
					];

					var errorMsgElement = parentGroup.find('.file-required-msg');

					if (isRequired && files.length === 0) {
						parentGroup.addClass('hasError');
						parentGroup.removeClass('isValid');
						errorMsgElement.text(errorMessage);
						hasError = true;

						if (!firstErrorField) {
							firstErrorField = input;
						}
					} 
					else {
						var invalidFileType = false;

						$.each(files, function(index, file) {
							if (!allowedTypes.includes(file.type)) {
								invalidFileType = true;
								return false;
							}
						});

						if (invalidFileType) {
							parentGroup.addClass('hasError');
							parentGroup.removeClass('isValid');
							errorMsgElement.text("Arquivo inválido");
							hasError = true;

							if (!firstErrorField) {
								firstErrorField = input;
							}
						} 
						else {
							parentGroup.removeClass('hasError');
							parentGroup.addClass('isValid');
							errorMsgElement.text("");
							fileData[inputName] = files;
						}
					}
				} 
				else {
					var errorMsgElement = parentGroup.find('.input-required-msg');

					if (isRequired && value.trim() === "") {
						parentGroup.addClass('hasError');
						parentGroup.removeClass('isValid');
						errorMsgElement.text(errorMessage);
						hasError = true;

						if (!firstErrorField) {
							firstErrorField = input;
						}
					} 
					else {
						parentGroup.removeClass('hasError');
						parentGroup.addClass('isValid');
						errorMsgElement.text("");
						formData[inputName] = value;
					}
				}
			});

			if (hasError) {
				$('html, body').animate({
					scrollTop: firstErrorField.closest('.form-group').offset().top - 100
				}, 500);

				firstErrorField.focus();
				return;
			}

			var ajaxData = new FormData();

			$.each(formData, function(key, value) {
				ajaxData.append(key, value);
			});

			$.each(fileData, function(key, files) {
				for (var i = 0; i < files.length; i++) {
					ajaxData.append(key, files[i]);
				}
			});

			ajaxData.append('csrf_token', CSRF_TOKEN);

			var jqXHR = $.ajax({
				url: BASEURL + url + "/cadastrar",
				type: 'POST',
				data: ajaxData,
				processData: false,
				contentType: false,
				success: function (response) {
					if (!response.status) {
						var swalHtml = "";
						swalHtml += '<i class="fa-light fa-xmark text-danger text-12 mb-3"></i><br/>';
						swalHtml += '<h1>Ops!</h1>';
						swalHtml += '<p class="mb-0 text-lowercase">' + response.message + '</p>';

						var swalConfirmButtonText = 'Vou verificar <i class="fa-light fa-arrow-right ms-1"></i>';
						var swalCancelButtonText 	= ''
						var swalIsConfirmed 			= 0;
						var swalResult 						= '';

						sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult);
					} 
					else {
						var swalHtml = "";
						swalHtml += '<i class="fa-light fa-check text-success text-12 mb-3"></i><br/>';
						swalHtml += '<h1>Tudo certo!</h1>';
						swalHtml += '<p class="mb-0 text-lowercase">' + response.message + '</b></p>';

						var swalConfirmButtonText = 'Obrigado, por enquanto <i class="fa-light fa-arrow-right ms-1"></i>';
						var swalCancelButtonText 	= ''
						var swalIsConfirmed 			= 0;
						var swalResult 						= '';

						sweetAlert2(swalHtml, swalConfirmButtonText, swalCancelButtonText, swalIsConfirmed, swalResult);

						$('#simulationForm').find('input, select, textarea').val('');
						$('#simulationForm').find('input[type="checkbox"], input[type="radio"]').prop('checked', false);
						$('#simulationForm').find('.form-group').removeClass('hasError isValid'); 
						$('#simulationForm').find('.file-required-msg, .input-required-msg').text(''); 
					}
				},
				error: function () {
					alert('Erro ao processar o formulário. Tente novamente.');
				}
			});

			jqXHR.done(function(result) {
			});

			jqXHR.fail(function(error) {
				console.error('Erro:', error);
			});

			jqXHR.always(function() {
			});
		});
});
}

$('.customForm').on('input change', 'input, select, textarea', function() {
	var input 			= $(this);
	var parentGroup = input.closest('.form-group');
	var value 			= input.val() || "";
	var errorMsgElement;

	if (input.attr('type') === 'file') {
		errorMsgElement = parentGroup.find('.file-required-msg');
	} 
	else {
		errorMsgElement = parentGroup.find('.input-required-msg');
	}

	if (parentGroup.hasClass('hasError') && value.trim() !== "") {
		parentGroup.removeClass('hasError');
		parentGroup.addClass('isValid');
		errorMsgElement.text("");
	}
});

document.addEventListener('click', function (event) {
	if (event.target.closest('.custom-file-input')) {
		const parentDiv = event.target.closest('.form-group');
		parentDiv.querySelector('.file-input').click();
	}
});

document.addEventListener('change', function (event) {
	if (event.target.classList.contains('file-input')) {
		const parentDiv = event.target.closest('.form-group');
		const fileName = event.target.files[0]?.name || "Anexe seu arquivo:";
		parentDiv.querySelector('.file-placeholder').textContent = fileName;
	}
});

// ---------------------------------------------------------------------------------------------]
// --------------------------------------------------------------------------------[ PAGINATION ]
// ---------------------------------------------------------------------------------------------]

function scrollToElement(selector, time, verticalOffset) {
	time 						= typeof(time) != 'undefined' ? time : 1000;
	verticalOffset 	= typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
	element 				= $(selector);
	offset 					= element.offset();
	offsetTop 			= offset.top + verticalOffset;

	$('#main').animate({
		scrollTop: offsetTop
	}, time);
}

var paginationButton 	= $('.btn-pagination');
var paginationFilter 	= $('.btn-pagination-filter');
var paginationContent = $('.pagination-content');
var paginationLoader 	= $('.pagination-loader');
var paginationPages 	= $('.pagination-pages');

if(paginationButton.length > 0 || paginationFilter.length > 0) {
	function buttonPagination( btn ) {
		var page 									= btn.data('page');
		var limit 								= btn.data('limit');
		var offset 								= btn.data('offset');
		var pagination						= btn.data('pagination');

		var mod 									= btn.data('module');
		var cla 									= btn.data('class');
		var fun 									= btn.data('function');
		var index									= btn.data('index');
		var variable							= btn.data('variable');
		var application						= btn.data('application');
		var api										= btn.data('api');
		var filterStatus					= btn.data('filter-status');
		var filterClass 					= btn.data('filter-class');
		var filterClassType				= btn.data('filter-class-type');
		var filterClassURL  			= btn.data('filter-class-url');

		var urlAddress  					= btn.data('url-address');
		var urlClass  						= btn.data('url-class');
		var urlTitleClass  				= btn.data('url-title-class');
		var urlTitle  						= btn.data('url-title');
		var urlDescriptionClass  	= btn.data('url-description-class');
		var urlDescription  			= btn.data('url-description');
		var urlRemoveClasse  			= btn.data('url-remove-class');

		var viewContent 	 				= btn.data('view-content');
		var viewPagination 				= btn.data('view-pagination');

		paginationContent.html('');
		paginationLoader.show();

		if(filterStatus == 1 && filterClass == "form-filter") {
			var filterInputs = new Array();
			var obj 				 = {};

			$( '.' + filterClass ).each(function(index, e) {
				obj[$(this).attr("name")] = $(this).val();
			});

			filterInputs = obj;
		}
		else if(filterStatus == 1 && filterClass == "form-filter-url") {
			var filterInputs 				= new Array();
			var obj 								= {};
			
			obj['filter_categoria'] = filterClassURL;
			filterInputs 						= obj;
		}
		else {
			filterInputs = null;
		}

		var jqXHR = $.ajax({
			dataType: 'json',
			type: 		"POST",
			url: 			BASEURL + "DH_pagination",
			data: {
				csrf_token: 			CSRF_TOKEN,
				page: 						page,
				limit: 						limit,
				offset: 					offset,
				pagination:				pagination,
				mod: 							mod,
				cla: 							cla,
				fun: 							fun,
				index: 						index,
				application:			application,
				variable:					variable,
				api:							api,
				filterStatus:			filterStatus,
				filterInputs:			filterInputs,
				filterType:				filterClassType,
				urlAddress: 			urlAddress,
				urlClass: 				urlClass,
				urlTitle: 				urlTitle,
				urlDescription: 	urlDescription,
				viewContent: 			viewContent,
				viewPagination: 	viewPagination
			},
			beforeSend: function( xhr ) {
				$("html, body").animate({
					scrollTop: $(".pagination-top").offset().top - 250
				}, 1000);
			}
		});

		jqXHR.done(function( result ) {
			paginationLoader.hide();
			paginationContent.html('').append(result.content);
			paginationPages.html('').append(result.pagination);

			console.log("Log: A função DH_pagination() foi realizada.");

			if (urlAddress.length > 0) {
				var currentURL 	= window.location.href;
				var newURL 			= currentURL.split(urlAddress)[0] + urlAddress;
				history.pushState({}, '', newURL);

				if(result.content.length > 0) {
					if(urlTitle.length > 0) {
						$('.' + urlTitleClass).html('').html(urlTitle);
					}

					if(urlDescription.length > 0) {
						$('.' + urlDescriptionClass).html('').html(urlDescription);
					}
				}
				else {
					$('.' + urlTitleClass).html('').html("Nenhum resultado encontrado");
					$('.' + urlDescriptionClass).html('');
				}

				if(urlRemoveClasse.length > 0) {
					var stringRecebida 		= urlRemoveClasse;
					var objetosSeparados 	= stringRecebida.split(',');
					var arrayDeObjetos 		= [];

					for (var i = 0; i < objetosSeparados.length; i++) {
						var objetoAtual = objetosSeparados[i].replace(/[{}]/g, '').split(';');
						$('.' + objetoAtual[0] + ' .' + objetoAtual[1] ).remove();
					}
				}
			} 
		});

		jqXHR.fail(function() {
			console.log("Log: A função DH_pagination() gerou um ou mais erros.");
		});

		jqXHR.always(function() {
			console.log("Log: A função DH_pagination() foi finalizada.");
		});
	}
}

// ---------------------------------------------------------------------------------------------]
// ---------------------------------------------------------------------------------------[ OWL ]
// ---------------------------------------------------------------------------------------------]

var owlGallery = $('.owl-gallery');

owlGallery.owlCarousel({
	loop: 							true,
	nav: 								false,
	dots: 							false,
	margin: 						0,
	autoplay: 					true,
	autoplayTimeout: 		2500,
	autoplaySpeed: 			1000,
	autoplayHoverPause: true,
	responsive : {
		0 : {
			items: 1
		},
		480 : {
			items: 3
		},
		768 : {
			items: 3
		},
		1366 : {
			items: 3
		}
	}
});

$('.owl-gallery-custom-prev').click(function () {
	owlGallery.trigger('prev.owl.carousel');
});

$('.owl-gallery-custom-next').click(function () {
	owlGallery.trigger('next.owl.carousel');
});

// ---------------------------------------------------------------------------------------------]

var owlBlog = $('.owl-blog');

owlBlog.owlCarousel({
	loop: 							true,
	nav: 								false,
	dots: 							false,
	margin: 						15,
	autoplay: 					true,
	autoplayTimeout: 		2500,
	autoplaySpeed: 			1000,
	autoplayHoverPause: true,
	responsive : {
		0 : {
			items: 1
		},
		480 : {
			items: 3
		},
		768 : {
			items: 3
		},
		1366 : {
			items: 3
		}
	}
});

$('.owl-blog-custom-prev').click(function () {
	owlBlog.trigger('prev.owl.carousel');
});

$('.owl-blog-custom-next').click(function () {
	owlBlog.trigger('next.owl.carousel');
});

// ---------------------------------------------------------------------------------------------]

var owlMarcas = $('.owl-marcas');

owlMarcas.owlCarousel({
	loop: 							true,
	nav: 								false,
	dots: 							false,
	margin: 						15,
	autoplay: 					true,
	autoplayTimeout: 		2500,
	autoplaySpeed: 			1000,
	autoplayHoverPause: true,
	responsive : {
		0 : {
			items: 1
		},
		480 : {
			items: 3
		},
		768 : {
			items: 3
		},
		1366 : {
			items: 3
		}
	}
});

$('.owl-marcas-custom-prev').click(function () {
	owlBlog.trigger('prev.owl.carousel');
});

$('.owl-marcas-custom-next').click(function () {
	owlBlog.trigger('next.owl.carousel');
});

// ---------------------------------------------------------------------------------------------]
// ---------------------------------------------------------------------------------------[ END ]
// ---------------------------------------------------------------------------------------------]