window.alert = function(message)
{
	nerivon_alert("", message, "info")
}

var nvModalAnswer = false;

function nerivon_confirm(title, message, type, close_after, callback)
{
	closeModals();

	if(callback == null)
	{
		callback = function() {};
	}

 	if(type == "warning")
	{
		icon = '<em class="fas fa-exclamation-circle text-warning"></em>';
	}
	else if(type == "error")
	{
		icon = '<em class="fas fa-exclamation-circle text-danger"></em>';
	}
	else if(type == "success")
	{
		icon = '<em class="fas fa-check-circle text-success"></em>';
	}
	else if(type == "info")
	{
		icon = '<em class="fas fa-info-circle"></em>';
	}

	nvModalAnswer = false;

	jQuery("body").prepend('<div class="modal fade" tabindex="-1" role="dialog" id="nvModal"> \
		<div class="modal-dialog modal-dialog-centered" role="document"> \
			<div class="modal-content"> \
				<div class="modal-header"> \
					<h3 class="modal-title">' + icon + ' ' + title + '</h3> \
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
					<span aria-hidden="true">&times;</span> \
					</button> \
				</div> \
				<div class="modal-body text-center">' + message + '</div> \
				<div class="modal-footer text-center"> \
					<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="nvModalAnswer = false">No</button> \
					<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="nvModalAnswer = true">Yes</button> \
				</div> \
			</div> \
		</div> \
	</div>');

	jQuery('#nvModal').on('shown.bs.modal', function (e)
	{
		jQuery('#nvModal input[autofocus]').focus();
	});

	jQuery('#nvModal').on('hidden.bs.modal', function (e)
	{
		jQuery('#nvModal').detach();
		callback(nvModalAnswer);
	});

	jQuery("#nvModal").modal("show");
}

function nerivon_alert(title, message, type, close_after, callback)
{
	closeModals();

	if(callback == null)
	{
		callback = function(isConfirm)
		{
			return;
		};
	}

	if(type == "warning")
	{
		icon = '<em class="fas fa-exclamation-circle text-warning"></em>';
	}
	else if(type == "error")
	{
		icon = '<em class="fas fa-exclamation-circle text-danger"></em>';
	}
	else if(type == "success")
	{
		icon = '<em class="fas fa-check-circle text-success"></em>';
	}
	else if(type == "info")
	{
		icon = '<em class="fas fa-info-circle"></em>';
	}

	nvModalAnswer = false;

	jQuery("body").prepend('<div class="modal fade" tabindex="-1" role="dialog" id="nvModal"> \
		<div class="modal-dialog modal-dialog-centered" role="document"> \
			<div class="modal-content"> \
				<div class="modal-header"> \
					<h3 class="modal-title">' + icon + ' ' + title + '</h3> \
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
					<span aria-hidden="true">&times;</span> \
					</button> \
				</div> \
				<div class="modal-body text-center">' + message + '</div> \
				<div class="modal-footer text-center"> \
					<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="nvModalAnswer = true">Ok</button> \
				</div> \
			</div> \
		</div> \
	</div>');

	jQuery('#nvModal').on('shown.bs.modal', function (e)
	{
		jQuery('#nvModal input[autofocus]').focus();
	});

	jQuery('#nvModal').on('hidden.bs.modal', function (e)
	{
		jQuery('#nvModal').detach();
		callback(nvModalAnswer);
	});

	jQuery("#nvModal").modal("show");
}

function nerivon_input(title, message, close_after, callback)
{
	closeModals();

	if(callback == null)
	{
		callback = function() {};
	}

	nvModalAnswer = false;

	jQuery("body").prepend('<div class="modal fade" tabindex="-1" role="dialog" id="nvModal"> \
		<div class="modal-dialog modal-dialog-centered" role="document"> \
			<div class="modal-content"> \
				<div class="modal-header"> \
					<h3 class="modal-title"><em class="fas fa-keyboard"></em> ' + title + '</h3> \
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
					<span aria-hidden="true">&times;</span> \
					</button> \
				</div> \
				<div class="modal-body text-center">' + message + '<br><br><input id="nvModalInput" class="form-control" autofocus /></div> \
				<div class="modal-footer text-center"> \
					<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="nvModalAnswer = false">Cancel</button> \
					<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="nvModalAnswer = jQuery(\'#nvModalInput\').val()">Ok</button> \
				</div> \
			</div> \
		</div> \
	</div>');

	jQuery('#nvModal').on('shown.bs.modal', function (e)
	{
		jQuery('#nvModal input[autofocus]').focus();
	});

	jQuery('#nvModal').on('hidden.bs.modal', function (e)
	{
		jQuery('#nvModal').detach();
		callback(nvModalAnswer);
	});

	jQuery("#nvModal").modal("show");
}

function warning(message, text, close_after, callback)
{
	nerivon_confirm(message, text, "warning", close_after, callback);
}

function error(message, text, close_after, callback)
{
	nerivon_alert(message, text, "error", close_after, callback);
}

function success(message, text, close_after, callback)
{
	nerivon_alert(message, text, "success", close_after, callback);
}

function info(message, text, close_after, callback)
{
	nerivon_alert(message, text, "info", close_after, callback);
}

function confirm_delete(message, text, url, obj, datatable)
{
	nerivon_confirm(message, text, "warning", false, function(confirmed)
	{
		if(confirmed)
		{
			wait("Deleting...", "The " + obj.toLowerCase() + " is being deleted. This dialog will close when it is complete.");

			jQuery.post
		    (
		        url,
		        null,
		        function(data)
		        {
		        	closeModals();

		        	if(data == "SUCCESS")
		        	{
		        		success(obj + " Deleted", "The selected " + obj.toLowerCase() + " was deleted.", true, null);

	    		        jQuery('#' + datatable).dataTable().fnFilter(jQuery("#" + datatable + "_filter input").val());
		        	}
		        	else
		        	{
		        		error("Error Deleting Item", data, true, null);
		        	}
		        }
		    );
		}
	});
}

function wait(message, text)
{
	closeModals();

	info(message, text, true, null);
}

function closeModals()
{
	jQuery(".modal").each(function()
	{
		var me = jQuery(this);

		if(me.hasClass("fade"))
		{
			me.removeClass("fade");
			me.modal("hide");
			me.addClass("fade");
		}
		else
		{
			me.modal("hide");
		}
	});
}

function setCookie(cname,cvalue,exdays)
{
	var d = new Date();
	d.setTime(d.getTime()+(exdays*24*60*60*1000));
	var expires = "expires="+d.toGMTString();
	document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/;";
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++)
	{
		var c = ca[i].trim();
		if (c.indexOf(name)==0)
			return c.substring(name.length,c.length);
	}
	return "";
}

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function is_numeric (mixed_var) {
	// http://kevin.vanzonneveld.net
	// Original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function number_format (number, decimals, dec_point, thousands_sep) {
	// http://kevin.vanzonneveld.net
	// Original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// Strip all characters but numerical ones.
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
	var n = !isFinite(+number) ? 0 : +number,
	prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
	sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
	dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
	s = '',
	toFixedFix = function (n, prec) {
		var k = Math.pow(10, prec);
		return '' + Math.round(n * k) / k;
	};
	// Fix for IE parseFloat(0.55).toFixed(0) = 0;
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}

/**
 * Request a token from Google.
 * @param  {string}   action   An identifier for the action being tested.
 * @param  {Function} callback A callback function to make use of the token received
 * @return {string}            A token which can later be verified.
 */
function botToken(action, callback)
{
	if(typeof callback != "function")
	{
		console.error("botToken() callback must be a function.");
		return;
	}

	grecaptcha.ready(function()
	{
		grecaptcha.execute(RECAPTCHA_PUBLIC_KEY, {action: action}).then(function(token)
		{
			callback(token);
		});
	});
}

/**
 * Request a token from Google and perform verification of the token.
 * @param  {string}   action   An identifier for the action being tested.
 * @param  {Function} callback A callback function to make use of the token received
 * @return object         	   An object containing all of Google's response fields,
 *                        	   plus a boolean "passed" flag of our own and a status message of our own.
 *                        	   The "passed" flag is true if the user's score is equal to or
 *                        	   above our site's reCAPTCHA threshold value.
 */
function botCheck(action, callback)
{
	if(typeof callback != "function")
	{
		console.error("botCheck() callback must be a function.");
		return;
	}

	grecaptcha.ready(function()
	{
		grecaptcha.execute(RECAPTCHA_PUBLIC_KEY, {action: action}).then(function(token)
		{
			// We are using raw XMLHttpRequest to avoid requiring jQuery.
			var botReq = new XMLHttpRequest();
			botReq.addEventListener("load", function()
			{
				callback(JSON.parse(this.responseText));
			});
			botReq.addEventListener("error", function()
			{
				callback(JSON.parse(this.responseText));
			});
			botReq.addEventListener("abort", function()
			{
				callback(JSON.parse(this.responseText));
			});

			botReq.open("POST", "/functions/recaptcha");
			botReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			botReq.send("action=" + action + "&g-recaptcha-response=" + token);
		});
	});
}