function DateBook_Paystack_Fee() {

	"use strict";

	this.DEFAULT_PERCENTAGE = 0.015;
	this.DEFAULT_ADDITIONAL_CHARGE = 10000;
	this.DEFAULT_THRESHOLD = 250000;
	this.DEFAULT_CAP = 200000;

	this.percentage = this.DEFAULT_PERCENTAGE;
	this.additional_charge = this.DEFAULT_ADDITIONAL_CHARGE;
	this.threshold = this.DEFAULT_THRESHOLD;
	this.cap = this.DEFAULT_CAP;

	this.chargeDivider = 0;
	this.crossover = 0;
	this.flatlinePlusCharge = 0;
	this.flatline = 0;

	this.withPercentage = function(percentage) {
		this.percentage = percentage;
		this.__setup();
	};

	this.withAdditionalCharge = function(additional_charge) {
		this.additional_charge = additional_charge;
		this.__setup();
	};

	this.withThreshold = function(threshold) {
		this.threshold = threshold;
		this.__setup();
	};

	this.withCap = function(cap) {
		this.cap = cap;
		this.__setup();
	};

	this.__setup = function() {
		this.chargeDivider = this.__chargeDivider();
		this.crossover = this.__crossover();
		this.flatlinePlusCharge = this.__flatlinePlusCharge();
		this.flatline = this.__flatline();
	};

	this.__chargeDivider = function() {
		return 1 - this.percentage;
	};

	this.__crossover = function() {
		return this.threshold * this.chargeDivider - this.additional_charge;
	};

	this.__flatlinePlusCharge = function() {
		return (this.cap - this.additional_charge) / this.percentage;
	};

	this.__flatline = function() {
		return this.flatlinePlusCharge - this.cap;
	};

	this.addFor = function(amountinkobo) {
		if (amountinkobo > this.flatline) {
			return parseInt(Math.round(amountinkobo + this.cap));
		} else if (amountinkobo > this.crossover) {
			return parseInt(
				Math.round((amountinkobo + this.additional_charge) / this.chargeDivider)
			);
		} else {
			return parseInt(Math.round(amountinkobo / this.chargeDivider));
		}
	};

	this.__setup = function() {
		this.chargeDivider = this.__chargeDivider();
		this.crossover = this.__crossover();
		this.flatlinePlusCharge = this.__flatlinePlusCharge();
		this.flatline = this.__flatline();
	};

	this.__setup();
}

(function($) {

	"use strict";

	$(document).ready(function($) {

		$(function() {
			$(".date-picker").datepicker({
				dateFormat: "mm/dd/yy",
				prevText: '<<',
				nextText: '>>'
			});
		});
		if ($("#datebook-paystack-vamount").length) {
			var amountField = $("#datebook-paystack-vamount");
			calculateTotal();
		} else {
			var amountField = $("#datebook-paystack-amount");
		}
		var max = 10;
		amountField.keydown(function(e) {
			format_validate(max, e);
		});

		amountField.keyup(function(e) {
			checkMinimumVal();
		});

		function checkMinimumVal() {
			if ($("#datebook-paystack-minimum-hidden").length) {
				var min_amount = Number($("#datebook-paystack-minimum-hidden").val());
				var amt = Number($("#datebook-paystack-amount").val());
				if (min_amount > 0 && amt < min_amount) {
					$("#datebook-paystack-min-val-warn").text("Amount cannot be less than the minimum amount");
					return false;
				} else {
					$("#datebook-paystack-min-val-warn").text("");
					$("#datebook-paystack-amount").removeClass("rerror");
				}
			}
		}

		function format_validate(max, e) {
			var value = amountField.text();
			if (e.which !== 8 && value.length > max) {
				e.preventDefault();
			}
			// Allow: backspace, delete, tab, escape, enter and .
			if (
				$.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
				// Allow: Ctrl+A
				(e.keyCode === 65 && e.ctrlKey === true) ||
				// Allow: Ctrl+C
				(e.keyCode === 67 && e.ctrlKey === true) ||
				// Allow: Ctrl+X
				(e.keyCode === 88 && e.ctrlKey === true) ||
				// Allow: home, end, left, right
				(e.keyCode >= 35 && e.keyCode <= 39)
			) {
				// let it happen, don't do anything
				calculateFees();
				return;
			}
			// Ensure that it is a number and stop the keypress
			if (
				(e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
				(e.keyCode < 96 || e.keyCode > 105)
			) {
				e.preventDefault();
			} else {
				calculateFees();
			}
		}

		$.fn.digits = function() {
			return this.each(function() {
				$(this).text(
					$(this)
					.text()
					.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
				);
			});
		};

		function calculateTotal() {
			var unit;
			if ($("#datebook-paystack-vamount").length) {
				unit = $("#datebook-paystack-form").find("#datebook-paystack-vamount").val();
			} else {
				unit = $("#datebook-paystack-amount").val();
			}
			var quant = $("#datebook-paystack-quantity").val();
			var newvalue = unit * quant;

			if (quant === "" || quant === null) {
				quant = 1;
			} else {
				$("#datebook-paystack-total").val(newvalue);
			}
		}

		function calculateFees(transaction_amount) {
			setTimeout(function() {
				transaction_amount = transaction_amount || parseInt(amountField.val());
				if ($("#datebook-paystack-vamount").length) {
					var name = $("#datebook-paystack-vamount option:selected").attr("data-name");
					$("#datebook-paystack-vname").val(name);
				}
				if (
					transaction_amount === "" ||
					transaction_amount === 0 ||
					transaction_amount.length === 0 ||
					transaction_amount === null ||
					isNaN(transaction_amount)
				) {
					var total = 0;
					var fees = 0;
				} else {
					var obj = new DateBook_Paystack_Fee();

					obj.withAdditionalCharge(datebookpaystacksettings.fee.adc);
					obj.withThreshold(datebookpaystacksettings.fee.ths);
					obj.withCap(datebookpaystacksettings.fee.cap);
					obj.withPercentage(datebookpaystacksettings.fee.prc);

					var total = obj.addFor(transaction_amount * 100) / 100;
					var fees = total - transaction_amount;
				}
				$(".datebook-paystack-txncharge")
					.hide()
					.html("NGN" + fees.toFixed(2))
					.show()
					.digits();
				$(".datebook-paystack-txntotal")
					.hide()
					.html("NGN" + total.toFixed(2))
					.show()
					.digits();
			}, 100);
		}

		calculateFees();

		$(".datebook-paystack-number").keydown(function(event) {
			if (
				event.keyCode === 46 ||
				event.keyCode === 8 ||
				event.keyCode === 9 ||
				event.keyCode === 27 ||
				event.keyCode === 13 ||
				(event.keyCode == 65 && event.ctrlKey === true) ||
				(event.keyCode >= 35 && event.keyCode <= 39)
			) {
				return;
			} else {
				if (
					event.shiftKey ||
					((event.keyCode < 48 || event.keyCode > 57) &&
						(event.keyCode < 96 || event.keyCode > 105))
				) {
					event.preventDefault();
				}
			}
		});
		$("#datebook-paystack-quantity, #datebook-paystack-vamount, #datebook-paystack-amount").on("change", function() {
			calculateTotal();
			calculateFees();
		});
		
		var clickedbutton;
		
		$(".datebook-paystack-form button[type=submit]").on("click", function() {
			clickedbutton = $(this).attr('name');
		});


		$(".datebook-paystack-form").on("submit", function(e) {

			if(clickedbutton === 'submit'){

				e.preventDefault();

				var requiredFieldIsInvalid = false;

				$("#datebook-paystack-agreementicon").removeClass("rerror");

				$(this).find("input, select, textarea").each(function() {
					$(this).removeClass("rerror"); //.css({ "border-color":"#d1d1d1" });
				});

				$(this).find("input, select, text, textarea").filter("[required]").filter(function() {
					return this.value === "";
				}).each(function() {
					$(this).addClass("rerror");
					requiredFieldIsInvalid = true;
				});

				if ($("#datebook-paystack-agreement").length && !$("#datebook-paystack-agreement").is(":checked")) {
					$("#datebook-paystack-agreementicon").addClass("rerror");
					requiredFieldIsInvalid = true;
				}

				if (requiredFieldIsInvalid) {
					$("html,body").animate({
							scrollTop: $(".rerror").offset().top - 110
						},
						500
					);
					return false;
				}

				var self = $(this);

				$.blockUI({
					message: "Please wait...",
						css: {
							border: 'none',
							padding: '15px',
							backgroundColor: '#fff',
							'-webkit-border-radius': '3px',
							'-moz-border-radius': '3px',
						}
				});

				var formdata = new FormData(this);

				formdata.append('whatisit', 'payment_paystack');

				$.ajax({
					url: datebookpaystacksettings.ajax_paystack_url,
					type: "POST",
					data: formdata,
					mimeTypes: "multipart/form-data",
					contentType: false,
					cache: false,
					processData: false,
					dataType: "JSON",
					success: function(data) {
						
						$.unblockUI();

						if (data.result === "success") {

							var names = data.name.split(" ");
							var firstName = names[0] || "";
							var lastName = names[1] || "";
							var quantity = data.quantity;
							// console.log(firstName+ " - "+lastName);
							if (data.plan === "none" || data.plan === "" || data.plan === "no") {
								
								var handler = PaystackPop.setup({
									key: datebookpaystacksettings.key,
									email: data.email,
									amount: data.total,
									firstname: firstName,
									lastname: lastName,
									currency: data.currency,
									subaccount: data.subaccount,
									bearer: data.txnbearer,
									transaction_charge: data.transaction_charge,
									ref: data.code,
									metadata: {
										custom_fields: data.custom_fields
									},
									callback: function(response) {
										$.blockUI({
											message: "Please wait...",
												css: {
													border: 'none',
													padding: '15px',
													backgroundColor: '#fff',
													'-webkit-border-radius': '3px',
													'-moz-border-radius': '3px',
												}
										});

										$.post(datebookpaystacksettings.ajax_paystack_url,	{
												whatisit: "paystack_confirm_payment",
												action: "datebook_paystack_confirm_payment",
												paystack_id: data.paystack_id,
												code: response.trxref,
												quantity: quantity
											},
											function(newdata) {

												if (newdata.result === "success2") {
													window.location.href = newdata.link;
												}
												if (newdata.result === "success") {
													$(".datebook-paystack-form")[0].reset();
													$(".datebook-paystack-form").hide();
													$(".datebook-payment-gateway-panel").remove();
													self.before('<div class="alert alert-success">' + newdata.message + '</div>');
													$(this).find("input, select, textarea").each(function() {
														$(this).css({
																"border-color": "#d1d1d1",
																"background-color": "#fff"
															});
														}
													);
													$(".datebook-paystack-txncharge")
														.hide()
														.html("NGN0")
														.show()
														.digits();
													$(".datebook-paystack-txntotal")
														.hide()
														.html("NGN0")
														.show()
														.digits();

													$.unblockUI();
												} else {
													self.before('<div class="alert alert-danger">' + newdata.message + '</div>');
													$.unblockUI();
												}
											}
										);
									},
									onClose: function() {}
								});

							} else {
								
								var handler = PaystackPop.setup({
									key: datebookpaystacksettings.key,
									email: data.email,
									plan: data.plan,
									firstname: firstName,
									lastname: lastName,
									ref: data.code,
									currency: data.currency,
									subaccount: data.subaccount,
									bearer: data.txnbearer,
									transaction_charge: data.transaction_charge,
									metadata: {
										custom_fields: data.custom_fields
									},
									callback: function(response) {
										$.blockUI({
											message: "Please wait...",
												css: {
													border: 'none',
													padding: '15px',
													backgroundColor: '#fff',
													'-webkit-border-radius': '3px',
													'-moz-border-radius': '3px',
												}
										});
										$.post(datebookpaystacksettings.ajax_paystack_url, {
												whatisit: "paystack_confirm_payment",
												action: "datebook_paystack_confirm_payment",
												paystack_id: data.paystack_id,
												code: response.trxref,
												quantity: quantity
											},
											function(newdata) {
												if (newdata.result === "success2") {
													window.location.href = newdata.link;
												}
												if (newdata.result === "success") {
													$(".datebook-paystack-form")[0].reset();
													$(".datebook-paystack-form").hide();
													$(".datebook-payment-gateway-panel").remove();
													self.before('<div class="alert alert-success">' + newdata.message + '</div>');
													$(this).find("input, select, textarea").each(function() {
														$(this).css({
															"border-color": "#d1d1d1",
															"background-color": "#fff"
														});
														}
													);
													$(".datebook-paystack-txncharge")
														.hide()
														.html("NGN0")
														.show()
														.digits();
													$(".datebook-paystack-txntotal")
														.hide()
														.html("NGN0")
														.show()
														.digits();

													$.unblockUI();
												} else {
													self.before('<div class="alert alert-danger">' + newdata.message + '</div>');
													$.unblockUI();
												}
											}
										);
									},
									onClose: function() {}
								});
							}

							handler.openIframe();

						} else {

							alert(newdata.message);

						}
					}
				});
			}
		});

	});
})(jQuery);