$(function(){
	$(document).on("submit", "form.form-ajax", function(event){
		event.preventDefault();

		let form = $(this);
		let formData = new FormData(this);

		let options = {};
		
		options.data        = (form.attr("enctype") == "multipart/form-data") ? formData : form.serialize();
		options.method      = (form.data("method") != undefined) ? form.data("method") : ((form.attr("method") != undefined) ? form.attr("method") : "GET");
		options.url         = (form.data("url") != undefined) ? form.data("url") : ((form.attr("action") != undefined) ? form.attr("action") : window.location.href);
		options.async       = (form.data("async") != undefined) ? ((form.data("async") == true) ? true : false) : true;
		options.processData = (form.data("process-data") != undefined) ? ((form.data("process-data") == true) ? true : false) : ((form.attr("enctype") == "multipart/form-data") ? false : true);
		options.contentType = (form.data("content-type") != undefined) ? ((form.data("content-type") == true) ? true : false) : ((form.attr("enctype") == "multipart/form-data") ? false : "application/x-www-form-urlencoded; charset=UTF-8");
		options.dataType    = "json";
		options.timeout     = 30000;

		let redirect     = (form.data("redirect") != undefined) ? form.data("redirect") : false;
		let target       = (form.data("target") != undefined) ? form.data("target") : (form.attr("target") != undefined) ? form.attr("target") : false;
		let reload       = (form.data("reload") != undefined) ? ((form.data("reload") == true) ? true : false) : false;
		let reset        = (form.data("reset") != undefined) ? ((form.data("reset") == false) ? false : true) : true;
		let confirmation = (form.data("confirmation") != undefined) ? ((form.data("confirmation") != "") ? form.data("confirmation") : "Tem certeza que deseja enviar esse formulário?") : false;
		let fnSuccess    = (form.data("success") != undefined) ? "var __fnSuccess = "+form.data("success") : false;
		let fnError      = (form.data("error") != undefined) ? "var __fnError = "+form.data("error") : false;

		let btns = $("input[type='submit'], button[type='submit']");

		btns.blur();
		btns.mouseout();
		btns.attr("disabled", true);

		var __ajax_command = function(){
			let status = true;

			form.find("input, select, textarea").removeClass("is-warning");
			$.each(form.find("input[data-required='true'], select[data-required='true'], textarea[data-required='true']"), function(i, elemet){
				if (empty($(this).val())) {
					status = false;
					
					$(this).addClass("is-warning");
					if ($(this).parent().html().indexOf("select") == -1) {
						$(this).keyup(function(){
							$(this).removeClass("is-warning");
						});
					}
					else{
						$(this).change(function(){
							$(this).removeClass("is-warning");
						});
					}
				}
			});

			if (status == false) {
				$.toast({
					heading: "Aviso",
					text: "Preencha Todos os Campos Obrigatórios!",
					icon: "warning",
					hideAfter: 5000,
					loader: true,
					html: true
				});

				btns.attr("disabled", false);
			}
			else{
				$.ajax(options).then(function(response){
					if (response.status == "success") {
						if (!empty(response.token)) {
							$("#csrf-token").val(response.token);
						}

						if (reload == true || response.reload == true) {
							if (empty(response.message)) {
								window.location.reload(true);
							}
							else{
								window.location.href = (window.location.href.indexOf("?") == -1) ? window.location.href+"?status=success&message="+encodeURI(response.message) : window.location.href+"&status=success&message="+encodeURI(response.message);
							}
						}
						else if (response.redirect != undefined) {
							let url_redirect;

							if (empty(response.message)) {
								url_redirect = response.redirect;
							}
							else{
								url_redirect = (response.redirect.indexOf("?") == -1) ? response.redirect+"?status=success&message="+encodeURI(response.message) : response.redirect+"&status=success&message="+encodeURI(response.message);
							}

							if (target != false || response.target != undefined) {
								window.open(url_redirect, "_blank");

								if (reset == true) {
									form.each(function(){
										this.reset();
									});
								}

								if (fnSuccess != false) {
									eval(fnSuccess);
									__fnSuccess(response);
								}
							}
							else{
								window.location.href = url_redirect;
							}
						}
						else if (redirect == false) {
							if (response.message != undefined) {
								$.toast({
									heading: "Aviso",
									text: response.message,
									icon: "success",
									hideAfter: 5000,
									loader: true,
									html: true
								});
							}

							if (reset == true) {
								form.each(function(){
									this.reset();
								});
							}

							if (fnSuccess != false) {
								eval(fnSuccess);
								__fnSuccess(response);
							}
						}
						else {
							window.location.href = redirect;
						}
					}
					else if (response.status == "warning" || response.status == "info") {
						$.toast({
							heading: "Aviso",
							text: response.message,
							icon: response.status,
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}
					else if (response.status == "error") {
						if (reload == true || response.reload == true) {
							if (empty(response.message)) {
								window.location.reload(true);
							}
							else{
								window.location.href = (window.location.href.indexOf("?") == -1) ? window.location.href+"?status=error&message="+encodeURI(response.message) : window.location.href+"&status=error&message="+encodeURI(response.message);
							}
						}
						else if (response.redirect != undefined) {
							let url_redirect;

							if (empty(response.message)) {
								url_redirect = response.redirect;
							}
							else{
								url_redirect = (response.redirect.indexOf("?") == -1) ? response.redirect+"?status=success&message="+encodeURI(response.message) : response.redirect+"&status=success&message="+encodeURI(response.message);
							}

							if (target != false || response.target != undefined) {
								window.open(url_redirect, "_blank");

								if (fnError != false) {
									eval(fnError);
									__fnError(response);
								}
							}
							else{
								window.location.href = url_redirect;
							}
						}
						else if (redirect == false) {
							if (response.message != undefined) {
								$.toast({
									heading: "Aviso",
									text: response.message,
									icon: "error",
									hideAfter: 5000,
									loader: true,
									html: true
								});
							}

							if (fnError != false) {
								eval(fnError);
								__fnError(response);
							}
						}
						else {
							window.location.href = redirect;
						}
					}
					else{
						$.toast({
							heading: "Aviso",
							text: "Nenhuma resposta válida recebida!",
							icon: "error",
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}

					btns.attr("disabled", false);
				}, function(error){
					if (error.responseJSON != undefined) {
						let response = error.responseJSON;

						$.toast({
							heading: "Aviso",
							text: response.message,
							icon: response.status,
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}
					else{
						$.toast({
							heading: "Aviso",
							text: "Ocorreu um erro inesperado. Tente novamente mais tarde!",
							icon: "error",
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}

					btns.attr("disabled", false);
				});
			}
		};

		if (confirmation == false) {
			__ajax_command();
		}
		else{
			Swal.fire({
				title: "Aviso",
				html: confirmation,
				icon: "warning",
				allowOutsideClick: false,
				allowEscapeKey: false,
				allowEnterKey: false,
				showCancelButton: true,
				focusCancel: true,
				keydownListenerCapture: true,
				confirmButtonText: "<i class='fa-regular fa-check'></i> Sim",
				cancelButtonText: "<i class='fa-regular fa-xmark'></i> Não",
				customClass: {
					confirmButton: "swal2-btn-default",
					cancelButton: "swal2-btn-default"
				}
			}).then(function(response){
				if (response.isConfirmed == true) {
					__ajax_command();
				}
				else{
					$("input[type='submit'], button[type='submit']").attr("disabled", false);
				}
			});
		}
	});

	$(document).on("click", ".btn-delete", function(){
		let btn  = $(this);
		let data = {};

		let value  = (btn.data("value")  != undefined) ? btn.data("value")  : null;
		let name   = (btn.data("name")   != undefined) ? btn.data("name")   : "id";
		let url    = (btn.data("url")    != undefined) ? btn.data("url")    : window.location.href;
		let method = (btn.data("method") != undefined) ? btn.data("method") : "DELETE";

		let redirect     = (btn.data("redirect") != undefined) ? btn.data("redirect") : false;
		let reload       = (btn.data("reload") != undefined) ? ((btn.data("reload") == true) ? true : false) : false;
		let confirmation = (btn.data("confirmation") != undefined && btn.data("confirmation") != "") ? btn.data("confirmation") : "Tem certeza que deseja EXCLUIR esse item?";
		let fnSuccess    = (btn.data("success") != undefined) ? "var __fnSuccess = "+btn.data("success") : false;
		let fnError      = (btn.data("error") != undefined) ? "var __fnError = "+btn.data("error") : false;

		btn.blur();
		btn.mouseout();
		btn.attr("disabled", true);

		Swal.fire({
			title: "Aviso",
			html: confirmation,
			icon: "warning",
			allowOutsideClick: false,
			allowEscapeKey: false,
			allowEnterKey: false,
			showCancelButton: true,
			focusCancel: true,
			keydownListenerCapture: true,
			confirmButtonText: "<i class='fa-regular fa-check'></i> Sim",
			cancelButtonText: "<i class='fa-regular fa-xmark'></i> Não",
			customClass: {
				confirmButton: "swal2-btn-default",
				cancelButton: "swal2-btn-default"
			}
		}).then(function(response){
			if (response.isConfirmed == true) {
				data[name] = value;

				$.ajax({
					method: method,
					dataType: "json",
					data: data,
					url: url,
					async: true
				}).then(function(response){
					if (response.status == "success") {
						if (reload == true || response.reload == true) {
							window.location.reload(true);
						}
						else if (response.redirect != undefined) {
							window.location.href = response.redirect;
						}
						else if (redirect == false) {
							$.toast({
								heading: "Aviso",
								text: response.message,
								icon: "success",
								hideAfter: 5000,
								loader: true,
								html: true
							});

							if (fnSuccess != false) {
								eval(fnSuccess);
								__fnSuccess(response);
							}
						}
						else {
							window.location.href = redirect;
						}
					}
					else if (response.status == "warning" || response.status == "info") {
						$.toast({
							heading: "Aviso",
							text: response.message,
							icon: response.status,
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}
					else if (response.status == "error") {
						if (reload == true || response.reload == true) {
							window.location.reload(true);
						}
						else if (response.redirect != undefined) {
							window.location.href = response.redirect;
						}
						else if (redirect == false) {
							$.toast({
								heading: "Aviso",
								text: response.message,
								icon: "error",
								hideAfter: 5000,
								loader: true,
								html: true
							});

							if (fnError != false) {
								eval(fnError);
								__fnError(response);
							}
						}
						else {
							window.location.href = redirect;
						}
					}
					else{
						$.toast({
							heading: "Aviso",
							text: "Nenhuma resposta válida recebida!",
							icon: "error",
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}

					if (screen.width > 765) {
						$("[data-bs-toggle='tooltip']").tooltip("hide");
						$("[data-bs-toggle='popover']").popover("hide");
					}

					btn.attr("disabled", false);
				}, function(error){
					if (error.responseJSON != undefined) {
						let response = error.responseJSON;

						$.toast({
							heading: "Aviso",
							text: response.message,
							icon: response.status,
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}
					else{
						$.toast({
							heading: "Aviso",
							text: "Ocorreu um erro inesperado. Tente novamente mais tarde!",
							icon: "error",
							hideAfter: 5000,
							loader: true,
							html: true
						});
					}

					btn.attr("disabled", false);
				});
			}
			else{
				btn.attr("disabled", false);
			}
		});
	});

	$(document).on("click", ".btn-send", function(){
		let btn = $(this);

		let value  = (btn.data("value")  != undefined) ? btn.data("value")  : null;
		let url    = (btn.data("url")    != undefined) ? btn.data("url")    : window.location.href;
		let method = (btn.data("method") != undefined) ? btn.data("method") : "POST";
		let name   = (btn.data("name")   != undefined) ? btn.data("name")   : "id";

		btn.attr("disabled", true);

		$("body").append(`
			<form id="form-btn-send" method="${method}" action="${url}">
				<input type="hidden" name="${name}" value="${value}">
			</form>
		`);

		$("#form-btn-send").submit();
	});

	$("input[data-value], select[data-value], textarea[data-value]").each(function(){
		let value = $(this).data("value");
		$(this).val(value);
	});

	if (getURLParams("status") != undefined && getURLParams("message") != undefined) {
		$.toast({
			heading: "Aviso",
			text: getURLParams("message"),
			icon: getURLParams("status"),
			hideAfter: 5000,
			loader: true,
			html: true
		});

		removeURLParams("status");
		removeURLParams("message");
	}
});

function modal(args = {}){
	let rand = Math.ceil(Math.random() * 100000);

	let backdrop = (args.backdrop != undefined && args.backdrop != "static") ? ((args.backdrop == true) ? "true" : "false") : "static";
	let vCentered = (args.vCentered != undefined && args.vCentered != false) ? "modal-dialog-centered" : "";
	let size = "";

	switch (args.size) {
		case "xxl":
			size = "modal-xxl";
			break;
		case "xl":
			size = "modal-xl";
			break;
		case "lg":
			size = "modal-lg";
			break;
		case "sm":
			size = "modal-sm";
			break;
	}

	let title = (args.header != undefined && typeof args.header == "object") ? ((args.header.title != undefined) ? args.header.title : ((args.title != undefined) ? args.title : "")) : ((args.title != undefined) ? args.title : ""); 
	let titleClass = (args.header != undefined && typeof args.header == "object") ? ((args.header.class != undefined) ? args.header.class : "") : ""; 
	let headerButtonClose = (args.header != undefined && typeof args.header == "object") ? ((args.header.buttonClose == true) ? `<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" style="color: #212529; opacity: 0.75;"><span aria-hidden="true">&times;</span></button>` : "") : ""; 

	let content = (args.body != undefined && typeof args.body == "object") ? ((args.body.content != undefined) ? args.body.content : ((args.content != undefined) ? args.content : "")) : ((args.content != undefined) ? args.content : ""); 

	let footerButtonClose = (args.footer != undefined && typeof args.footer == "object") ? ((args.footer.buttonClose == true) ? `<button type="button" class="btn btn-white" data-bs-dismiss="modal">Fechar</button>` : "") : "";
	let footerButtons = "";

	if (args.footer != undefined && typeof args.footer == "object") {
		if (args.footer.buttons != undefined && typeof args.footer.buttons == "object") {
			$.each(args.footer.buttons, function(i, data){
				let idButton = (data.id != undefined) ? data.id : "button-"+Math.ceil(Math.random() * 100000);

				footerButtons += `
					<button 
						type="button" 
						id="${idButton}" 
						class="${(data.class != undefined) ? data.class : "btn btn-white"}" 
						${(data.close == true) ? "data-bs-dismiss='modal'" : ""}
					>
						${(data.text != undefined) ? data.text : "Button"}
					</button>
				`;

				if (data.onclick != undefined) {
					$(document).on("click", "#"+idButton, new Function(`(${data.onclick})()`));
				}
			});
		}
	}

	let header = (!empty(title) || !empty(headerButtonClose)) ? `
		<div class="modal-header">
			<h5 class="modal-title ${titleClass}" style="color: #212529; font-weight: 600; width: 100%;">${title}</h5>
			${headerButtonClose}
		</div>
	` : "";

	let footer = (!empty(footerButtonClose) || !empty(footerButtons)) ? `
		<div class="modal-footer">
			${!empty(footerButtons) ? "<div>"+footerButtons+"</div>" : ""} 
			${!empty(footerButtonClose) ? "<div>"+footerButtonClose+"</div>" : ""} 
		</div>
	` : "";

	if ($(".modal-js-custom[aria-hidden='true']").length > 0) {
		$(".modal-js-custom[aria-hidden='true']").remove();
	}

	$("body").append(`
		<div class="modal fade modal-js-custom" id="modal-${rand}" data-bs-backdrop="${backdrop}" data-bs-keyboard="false" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-dialog-scrollable ${vCentered} ${size}">
				<div class="modal-content" style="border: none; border-radius: 5px; box-shadow: 0 0 8px rgb(0 0 0 / 40%);">
					${header}
					<div class="modal-body py-4" style="color: rgba(33, 37, 41, 0.85); font-size: 16px;">
						${content}
					</div>
					${footer}
				</div>
			</div>
		</div>
	`); //title: style="color: #212529; font-weight: 600; width: 100%;"

	$(".modal-js-custom input[data-value], .modal-js-custom select[data-value], .modal-js-custom textarea[data-value]").each(function(){
		let value = $(this).data("value");
		$(this).val(value);
	});

	if (screen.width > 765) {
		$("[data-bs-toggle='tooltip']").tooltip();
		$("[data-bs-toggle='popover']").popover();
	}

	$("#modal-"+rand).modal("show");
}

window.app = {
	location: "pt-BR",
	currency: "BRL"
};

function time(datetime = null, options=""){
	let result = new Date().getTime();

	if (datetime != null && datetime.toLowerCase().trim() != "now") {
		if (datetime.search(/\d{2}:\d{2}:\d{2}/g) != -1) {
			result = new Date(datetime.trim().replaceAll(/\-\:/gi, " ")).getTime();
		}
		else{
			result = new Date((datetime.trim()+" 00:00:00").replaceAll(/\-\:/gi, " ")).getTime();
		}
	}

	let aux = options.trim().split(" ");

	if (aux.length == 2) {
		let number = Number(aux[0].replaceAll(/\s/gi, ""));

		switch (aux[1].trim().toLowerCase()) {
			case "year":
			case "years":
				result = new Date(result).setFullYear(new Date(result).getFullYear() + number);
				break;
			case "month":
			case "months":
				result = new Date(result).setMonth(new Date(result).getMonth() + number);
				break;
			case "week":
			case "weeks":
				result = new Date(result).setDate(new Date(result).getDate() + (number * 7));
				break;
			case "day":
			case "days":
				result = new Date(result).setDate(new Date(result).getDate() + number);
				break;
			case "hour":
			case "hours":
				result = new Date(result).setHours(new Date(result).getHours() + number);
				break;
			case "minute":
			case "minutes":
				result = new Date(result).setMinutes(new Date(result).getMinutes() + number);
				break;
			case "second":
			case "seconds":
				result = new Date(result).setSeconds(new Date(result).getSeconds() + number);
				break;
		}
	}

	return result;
}

function date(format, timestamp = new Date().getTime()){
	let date = new Date(timestamp);

	format = format.replaceAll("%d", (date.getDate() > 9) ? date.getDate() : "0"+date.getDate());
	format = format.replaceAll("%j", date.getDate());
	format = format.replaceAll("%m", (date.getMonth()+1 > 9) ? Number(date.getMonth())+1 : "0"+(Number(date.getMonth())+1));
	format = format.replaceAll("%n", Number(date.getMonth())+1);
	format = format.replaceAll("%Y", date.getFullYear());
	format = format.replaceAll("%y", String(date.getFullYear()).substr(2));
	format = format.replaceAll("%g", (date.getHours() > 12) ? date.getHours()-12 : date.getHours());
	format = format.replaceAll("%G", date.getHours());
	format = format.replaceAll("%h", (date.getHours() > 12) ? ((date.getHours()-12 > 9) ? date.getHours()-12 : "0"+(date.getHours()-12)) : ((date.getHours() > 9) ? date.getHours() : "0"+date.getHours()));
	format = format.replaceAll("%H", (date.getHours() > 9) ? date.getHours() : "0"+date.getHours());
	format = format.replaceAll("%i", (date.getMinutes() > 9) ? date.getMinutes() : "0"+date.getMinutes());
	format = format.replaceAll("%s", (date.getSeconds() > 9) ? date.getSeconds() : "0"+date.getSeconds());
	format = format.replaceAll("%u", date.getMilliseconds());
	format = format.replaceAll("%L", (date.getFullYear() % 4 == 0) ? 1 : 0);
	format = format.replaceAll("%w", date.getDay());
	format = format.replaceAll("%W", date.toLocaleString(window.app.location, {weekday: "long"}));
	format = format.replaceAll("%F", date.toLocaleString(window.app.location, {month: "long"}));
	format = format.replaceAll("%R", date.toLocaleString(window.app.location, {weekday: "long", year: "numeric", month: "long", day: "numeric"}));
	format = format.replaceAll("%N", (date.getDay() == 0) ? 7 : date.getDay());
	format = format.replaceAll("%z", Math.round((date.getTime() - new Date(`${date.getFullYear()} 01 01 ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`).getTime()) / (24 * 60 * 60 * 1000)));
	format = format.replaceAll("%a", (date.getHours() > 12) ? "pm" : "am");
	format = format.replaceAll("%A", (date.getHours() > 12) ? "PM" : "AM");

	if (
		date.getMonth() == 0 || 
		date.getMonth() == 2 || 
		date.getMonth() == 4 || 
		date.getMonth() == 6 || 
		date.getMonth() == 7 || 
		date.getMonth() == 9 || 
		date.getMonth() == 11  
	) {
		format = format.replaceAll("%t", 31);
	}
	else if (
		date.getMonth() == 3 || 
		date.getMonth() == 5 || 
		date.getMonth() == 8 || 
		date.getMonth() == 10 
	) {
		format = format.replaceAll("%t", 30);
	}
	else{
		format = format.replaceAll("%t", (date.getFullYear() % 4 == 0) ? 29 : 28);
	}

	return format;
}

function dateDiff(datetime1, datetime2, resultIn = "days"){
	let d1 = new Date((datetime1.search(/\d{2}:\d{2}:\d{2}/g) != -1) ? datetime1.trim().replaceAll(/\-\:/gi, " ") : (datetime1.trim()+" 00:00:00").replaceAll(/\-\:/gi, " "));
	let d2 = new Date((datetime2.search(/\d{2}:\d{2}:\d{2}/g) != -1) ? datetime2.trim().replaceAll(/\-\:/gi, " ") : (datetime2.trim()+" 00:00:00").replaceAll(/\-\:/gi, " "));

	let result;

	switch (resultIn.trim().toLowerCase()) {
		case "year":
		case "years":
			result = d1.getFullYear() - d2.getFullYear();
			break;
		case "month":
		case "months":
			result = (d1.getMonth()+12 * d1.getFullYear())-(d2.getMonth()+12 * d2.getFullYear());
			break;
		case "week":
		case "weeks":
			result = (d1.getTime() - d2.getTime()) / (7 * 24 * 60 * 60 * 1000);
			break;
		case "day":
		case "days":
			result = (d1.getTime() - d2.getTime()) / (24 * 60 * 60 * 1000);
			break;
		case "hour":
		case "hours":
			result = (d1.getTime() - d2.getTime()) / (60 * 60 * 1000);
			break;
		case "minute":
		case "minutes":
			result = (d1.getTime() - d2.getTime()) / (60 * 1000);
			break;
		case "second":
		case "seconds":
			result = (d1.getTime() - d2.getTime()) / 1000;
			break;
	}

	return Math.abs(Math.round(result));
}

function dateFormat(datetime, location = window.app.location, options = {}){
	let result;

	if (datetime.search(/\d{2}:\d{2}:\d{2}/g) != -1) {
		result = new Date(datetime.trim().replaceAll(/\-\:/gi, " "));
	}
	else{
		result = new Date((datetime.trim()+" 00:00:00").replaceAll(/\-\:/gi, " "));
		options = (Object.keys(options).length == 0) ? {year: "numeric", month: "numeric", day: "numeric"} : options;
	}

	return result.toLocaleString(location, options);
}

function numberFormat(number, location = window.app.location, options = {minimumFractionDigits: 2}) {
	return Number(number).toLocaleString(location, options);
}

function moneyFormat(number, location = window.app.location, currency = "BRL") {
	return Number(number).toLocaleString(location, {style: "currency", currency: currency});
}

function getURLParams(key = null){
	let url = new URL(window.location);
	let result = {};

	if (key != null) {
		result = url.searchParams.getAll(key);
	}
	else{
		url.searchParams.forEach(function(v, k){
			if (result[k] == undefined) {
				result[k] = v;
			}
			else if (typeof result[k] == "object") {
				result[k].push(v);
			}
			else{
				result[k] = [result[k], v];
			}
		});
	}

	return (key != null) ? ((result.length > 0) ? ((result.length == 1) ? result[0] : result) : undefined) : result;
}

function setURLParams(key, value){
	let url = new URL(window.location);
	
	if (typeof value == "object") {
		url.searchParams.delete(key);

		value.forEach(function(v){
			if (typeof v != "object") {
				url.searchParams.append(key, v);
			}
		});
	}
	else{
		url.searchParams.set(key, value);
	}

	window.history.pushState("", "", url);
}

function removeURLParams(key){
	let url = new URL(window.location);

	url.searchParams.delete(key);

	window.history.pushState("", "", url);
}

function removeAllURLParams(){
	window.history.pushState("", "", window.location.href.replace(window.location.search, ""));
}

function hasURLParams(key){
	let url = new URL(window.location);

	return url.searchParams.has(key);
}

function empty(variable){
	switch (typeof variable) {
		case "string":
			if (variable == 0) {
				return true;
				break;
			}

			return (variable.length > 0) ? false : true;
			break;
		case "number":
			return (variable == 0) ? true : false;
			break;
		case "object":
			if (variable === null) {
				return true;
				break;
			}
			else{
				return (Object.keys(variable).length > 0) ? false : true;
				break;
			}
		case "undefined":
			return true;
			break;
		case "boolean":
			return (variable == false) ? true : false;
			break;
		default:
			return true;
	}
}

function mask(string, mask){
	let string_maskared = "";
	let count = 0;

	for (let i = 0; i < mask.length; i++) {
		if (string[count] != undefined) {
			if (mask[i] == "#") {
				string_maskared += string[count];
				count++;
			} 
			else {
				string_maskared += mask[i];
			}
		}
	}

	return string_maskared;
}

function compressString(string, length, breaking = false){
	let newString;
	let lastSpace;

	if (string.length <= length) {
		newString = string;
	}
	else{
		if (breaking == true) { 
			newString = string.trim().substr(0, length)+"...";
		}
		else{
			lastSpace = string.trim().substr(0, length).indexOf(" ");
			newString = string.trim().substr(0, lastSpace)+"...";
		}
	}

	return (newString == "...") ? string : newString;
}

function copyText(text, success = null){
	let input = document.createElement("input");
	input.value = text;

	document.body.appendChild(input);

	input.select();
	document.execCommand("copy");

	document.body.removeChild(input);

	if (typeof(success) == "function") {
		success.call();
	}
}

function imagePreview(input, img){
	if (input.prop("files") && input.prop("files")[0]){
		let r = new FileReader();
		r.onload = function(e){
			img.attr("src", e.target.result);
		}

		r.readAsDataURL(input.prop("files")[0]);
	}
}

function resizeImage(object, dir_img){
	let image = new Image();
	image.addEventListener("load", function(){
		let divs = document.querySelectorAll(object), 
		oWidth = this.width,
		oHeight = this.height;

		for (let i = 0; i < divs.length; i++) {
			let canvas = document.createElement("canvas"),
			ctx = canvas.getContext("2d"),

			sx = 0,
			sy = 0,
			sWidth = oWidth,
			sHeight = oHeight,
	
			dWidth = divs[i].offsetWidth,
			dHeight = divs[i].offsetHeight,

			iWidth = Math.round(sHeight / dHeight * dWidth),
			iHeight = Math.round(sWidth / dWidth * dHeight);

			if (sWidth > iWidth) { // cortar na largura
				sx = parseInt((sWidth - iWidth) / 2);
				sWidth = iWidth;
			} else if (sHeight > iHeight) { // cortar na altura
				sy = parseInt((sHeight - iHeight) / 2);
				sHeight = iHeight;
			}
			
			canvas.width = dWidth;
			canvas.height = dHeight;
			ctx.drawImage(this, sx, sy, sWidth, sHeight, 0, 0, dWidth, dHeight);
			divs[i].appendChild(canvas);
		}
	}, false);
	image.src = dir_img;
}