/* Minification failed. Returning unminified contents.
(60,26-27): run-time error JS1195: Expected expression: >
(63,6-7): run-time error JS1195: Expected expression: )
(63,19-20): run-time error JS1195: Expected expression: >
(91,6-7): run-time error JS1195: Expected expression: )
(94,3-4): run-time error JS1002: Syntax error: }
(187,34-35): run-time error JS1195: Expected expression: >
(190,6-7): run-time error JS1195: Expected expression: )
(190,19-20): run-time error JS1195: Expected expression: >
(205,6-7): run-time error JS1195: Expected expression: )
(208,3-4): run-time error JS1002: Syntax error: }
(338,34-35): run-time error JS1195: Expected expression: >
(341,6-7): run-time error JS1195: Expected expression: )
(341,19-20): run-time error JS1195: Expected expression: >
(356,5-6): run-time error JS1002: Syntax error: }
(451,33-34): run-time error JS1195: Expected expression: >
(454,5-6): run-time error JS1195: Expected expression: )
(454,18-19): run-time error JS1195: Expected expression: >
(469,4-5): run-time error JS1002: Syntax error: }
(505,33-34): run-time error JS1195: Expected expression: >
(508,5-6): run-time error JS1195: Expected expression: )
(508,18-19): run-time error JS1195: Expected expression: >
(523,4-5): run-time error JS1002: Syntax error: }
(525,4-5): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
 */



function initPhoneValidator() {
	$.validator.addMethod("phone", function (value, element) {
		if (this.optional(element)) {
			return true;
		}
		var reverseValue = $.trim(value).split("").reverse().join("");
		var reverseRegEx = new RegExp("^(\\d+\\s?(x|\\.txe?)\\s?)?((\\)(\\d+[\\s\\-\\.]?)?\\d+\\(|\\d+)[\\s\\-\\.]?)*(\\)([\\s\\-\\.]?\\d+)?\\d+\\+?\\((?!\\+.*)|\\d+)(\\s?\\+)?$", "i");
		var match = reverseRegEx.exec(reverseValue);
		return (match && (match.index === 0) && (match[0].length === value.length));
	});
	$.validator.unobtrusive.adapters.addBool("phone");
}


initPhoneValidator();

;



function InitializeAccountMigration() {
	
	var btnDefaultAddress = document.querySelectorAll(".btnAccountMigration");
	Array.prototype.forEach.call(btnDefaultAddress, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			$.validator.unobtrusive.parse("AccountMigrationForm");

			//console.log("This is a test");
			var isValid = $("#AccountMigrationForm").valid();
			//console.log("isValid: " + isValid);
			if (isValid) {


				$(".btnAccountMigration .save").addClass("hidden");
				$(".btnAccountMigration .saving").removeClass("hidden");
				$(".btnAccountMigration").attr("disabled", "disabled");

				var txtEmailAddress = document.getElementById("txtEmailAddress");
				var ServiceRequest = new Object();
				ServiceRequest.EmailAddress = txtEmailAddress.value;


				var fetchUrl = "/api/accounts/securityapi/beginaccountprovision";
				//console.log(fetchUrl);
				var apiPromise = fetch(fetchUrl,
					{
						method: "POST",
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify(ServiceRequest)
					});

				apiPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divErrorMessage");
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");
						//$.modalNoConflict.close();

						$(".btnAccountMigration .save").removeClass("hidden");
						$(".btnAccountMigration .saving").addClass("hidden");
						$(".btnAccountMigration").removeAttr("disabled");

					}
					if (data.IsSuccess) {

						var redirectUrl = data.Result.ReturnUrl;
						//console.log(redirectUrl);
						if (redirectUrl === null || redirectUrl === undefined) {
							redirectUrl = $("#divBeginAccountProvision").attr("data-return-url");
						}
						if (redirectUrl !== null && redirectUrl !== undefined) {
							window.location.href = redirectUrl;
						}
						else {
							window.location.reload();
						}
					}

				});
			}

		};
	});
}


InitializeAccountMigration();


;

var newAddressContactDataServices = null;



function InitializeEditAddressForm() {
	var btnSaveChanges = document.querySelectorAll(".btnEditAddressSaveChanges");
	Array.prototype.forEach.call(btnSaveChanges, function (el, i) {
		var aid = el.getAttribute("aid");
		var divAddressList = document.getElementById("divAddressList");
		var qasenabled = divAddressList.getAttribute("data-qas-enabled");
		var token = divAddressList.getAttribute("data-qas-token");


		el.onclick = function (evt) {
			evt.preventDefault();

			//console.log("aid: " + aid);

			var ddlCountriesJqObj = $("#ddlCountries_" + aid);
			var selectedCountryVal = ddlCountriesJqObj.val();
			//console.log(selectedCountryVal);
			var selectedCountryObj = ddlCountriesJqObj.find("option[value='" + selectedCountryVal + "']");
			//console.log(selectedCountryObj);
			var requirePostalCode = selectedCountryObj.data("require-postalcode");

			//console.log(requirePostalCode);
			if (requirePostalCode != "True") {
				$("#txtPostalCode_" + aid).rules("remove", "required");
			}


			//var ddlCountriesJqObjSelected =  ddlCountriesJqObj.data("val-required");
			//console.log(ddlCountriesJqObjSelected);

			$.validator.unobtrusive.parse("EditAddressForm_" + aid);
			var isValid = $("#EditAddressForm_" + aid).valid();

			if (isValid) {

				var divErrorClear = document.getElementById("divEditAddressErrorMessage_" + aid);
				//console.log(divErrorClear);
				divErrorClear.innerHTML = "";
				divErrorClear.classList.add("hidden");

				$(".btnEditAddressSaveChanges .save").addClass("hidden");
				$(".btnEditAddressSaveChanges .saving").removeClass("hidden");
				$(".btnEditAddressSaveChanges").attr("disabled", "disabled");

				var txtFirstName = document.getElementById("txtFirstName_" + aid);
				var txtLastName = document.getElementById("txtLastName_" + aid);
				var txtAddressLine1 = document.getElementById("txtAddressLine1_" + aid);
				var txtAddressLine2 = document.getElementById("txtAddressLine2_" + aid);
				var txtAddressLine3 = document.getElementById("txtAddressLine3_" + aid);
				var txtCity = document.getElementById("txtCity_" + aid);
				var txtState = document.getElementById("txtState_" + aid);
				var txtPostalCode = document.getElementById("txtPostalCode_" + aid);
				var ddlCountries = document.getElementById("ddlCountries_" + aid);


				var ServiceRequest = new Object();
				ServiceRequest.AddressId = aid;
				ServiceRequest.FirstName = txtFirstName.value;
				ServiceRequest.LastName = txtLastName.value;
				ServiceRequest.AddressLine1 = txtAddressLine1.value;
				ServiceRequest.AddressLine2 = txtAddressLine2.value;
				ServiceRequest.AddressLine3 = txtAddressLine3.value;
				ServiceRequest.City = txtCity.value;
				ServiceRequest.State = txtState.value;
				ServiceRequest.PostalCode = txtPostalCode.value;
				ServiceRequest.Country = ddlCountries.options[ddlCountries.selectedIndex].text;
				ServiceRequest.CountryCode = ddlCountries.value;


				var fetchUrl = "/api/accounts/addressapi/saveaddress";
				//console.log(fetchUrl);
				var editAccountPromise = fetch(fetchUrl, {
					method: "POST",
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify(ServiceRequest)
				});

				editAccountPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					//console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divEditAddressErrorMessage_" + aid);
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");

						$(".btnEditAddressSaveChanges .save").removeClass("hidden");
						$(".btnEditAddressSaveChanges .saving").addClass("hidden");
						$(".btnEditAddressSaveChanges").removeAttr("disabled");
					}
					if (data.IsSuccess) {
						window.location.reload();
					}

				});
			}

		};
	});


	var btnEditOpenChanges = document.querySelectorAll(".btnEditOpen");
	Array.prototype.forEach.call(btnEditOpenChanges, function (el, i) {
		var aid = el.getAttribute("aid");
		var divAddressList = document.getElementById("divAddressList");
		var qasenabled = divAddressList.getAttribute("data-qas-enabled");
		var token = divAddressList.getAttribute("data-qas-token");

		el.onclick = function (evt) {
			evt.preventDefault();
			//console.log("This is test");

			var countryCode = $("select[id='ddlCountries_" + aid + "']").val();
			//InitializeQaSForEdit(token, qasenabled, aid);
			var statesCollection = new Array();
			var promise = GetStates(countryCode, aid).done(function (data) {

				console.log(data);
				var states = data.States;
				for (var key in states) {

					if (states.hasOwnProperty(key)) {
						//console.log(key);
						//console.log(states[key]);
						var StateRequest = new Object();
						StateRequest.StateCode = key;
						StateRequest.State = states[key];
						statesCollection.push(StateRequest);
					}
				}

				var selector = "#ddlStates_" + aid;
				var selectorText = "#txtState_" + aid;

				//console.log(states.length);

				if (statesCollection.length > 0) {
					PopluateStates(statesCollection, selector);
					$(selector).removeClass("hidden");
					$(selectorText).addClass("hidden");
					$(selector).val($(selectorText).val());
					//$(selectorText).val("");
					//InitializeQaSForEdit(token, qasenabled, aid);
					InitializeQaSForEdit(aid);

				} else {
					//console.log("Show 2" + selectorText);
					$(selectorText).removeClass("hidden");
					$(selector).addClass("hidden");
					$(selector).empty();

					InitializeQaSForEditState(aid);
				}
			});

		};
	});

	var btnNewAddress = document.querySelectorAll(".btnNewAddress");
	Array.prototype.forEach.call(btnNewAddress, function (el, i) {
		var divAddressList = document.getElementById("divAddressList");
		var qasenabled = divAddressList.getAttribute("data-qas-enabled");
		var token = divAddressList.getAttribute("data-qas-token");
		InitializeQaSForNew(token, qasenabled);

		el.onclick = function (evt) {
			evt.preventDefault();
			var divErrorClear = document.getElementById("divNewAddressErrorMessage");
			console.log(divErrorClear);
			divErrorClear.innerHTML = "";
			divErrorClear.classList.add("hidden");




			var txtFirstName = document.getElementById("txtFirstName");
			var txtLastName = document.getElementById("txtLastName");
			var txtAddressLine1 = document.getElementById("txtAddressLine1");
			var txtAddressLine2 = document.getElementById("txtAddressLine2");
			var txtAddressLine3 = document.getElementById("txtAddressLine3");
			var txtCity = document.getElementById("txtCity");
			var txtState = document.getElementById("txtState");
			var txtPostalCode = document.getElementById("txtPostalCode");
			var ddlCountries = document.getElementById("ddlCountries");


			var ddlCountriesJqObj = $("#ddlCountries");
			var selectedCountryVal = ddlCountriesJqObj.val();
			var selectedCountryObj = ddlCountriesJqObj.find("option[value='" + selectedCountryVal + "']");
			var requirePostalCode = selectedCountryObj.data("require-postalcode");
			if (requirePostalCode != "True") {
				$("#txtPostalCode").rules("remove", "required");
			}


			$.validator.unobtrusive.parse("NewAddressForm");
			var isValid = $("#NewAddressForm").valid();

			if (isValid) {

				$(".btnNewAddress .save").addClass("hidden");
				$(".btnNewAddress .saving").removeClass("hidden");
				$(".btnNewAddress").attr("disabled", "disabled");

				var ServiceRequest = new Object();
				ServiceRequest.FirstName = txtFirstName.value;
				ServiceRequest.LastName = txtLastName.value;
				ServiceRequest.AddressLine1 = txtAddressLine1.value;
				ServiceRequest.AddressLine2 = txtAddressLine2.value;
				ServiceRequest.AddressLine3 = txtAddressLine3.value;
				ServiceRequest.City = txtCity.value;
				ServiceRequest.State = txtState.value;
				ServiceRequest.PostalCode = txtPostalCode.value;
				ServiceRequest.Country = ddlCountries.options[ddlCountries.selectedIndex].text;
				ServiceRequest.CountryCode = ddlCountries.value;
				ServiceRequest.AddressType = "Mailing";

				var fetchUrl = "/api/accounts/addressapi/saveaddress";
				console.log(fetchUrl);
				var editAddressPromise = fetch(fetchUrl, {
					method: "POST",
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify(ServiceRequest)
				});

				editAddressPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divNewAddressErrorMessage");
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");

						$(".btnNewAddress .save").removeClass("hidden");
						$(".btnNewAddress .saving").addClass("hidden");
						$(".btnNewAddress").removeAttr("disabled");
					}
					if (data.IsSuccess) {
						window.location.reload();
					}

				});
			}

		};
	});

	var btnNewOpenChanges = document.querySelectorAll(".btnNewOpen");
	Array.prototype.forEach.call(btnNewOpenChanges, function (el, i) {
		var divAddressList = document.getElementById("divAddressList");
		var qasenabled = divAddressList.getAttribute("data-qas-enabled");
		var token = divAddressList.getAttribute("data-qas-token");

		el.onclick = function (evt) {
			evt.preventDefault();


			var countryCode = $("#ddlCountries").val();
			//InitializeQaSForEdit(token, qasenabled, aid);
			var statesCollection = new Array();
			var promise = GetStates(countryCode, null).done(function (data) {

				console.log(data);
				var states = data.States;
				for (var key in states) {

					if (states.hasOwnProperty(key)) {
						//console.log(key);
						//console.log(states[key]);
						var StateRequest = new Object();
						StateRequest.StateCode = key;
						StateRequest.State = states[key];
						statesCollection.push(StateRequest);
					}
				}

				var selector = "#ddlStates";
				var selectorText = "#txtState";

				console.log(statesCollection.length);

				if (statesCollection.length > 0) {
					PopluateStates(statesCollection, selector);
					$(selector).removeClass("hidden");
					$(selectorText).addClass("hidden");
					$(selector).val($(selectorText).val());
					//$(selectorText).val("");
					//InitializeQaSForEdit(token, qasenabled, aid);
					//InitializeQaSForNew(token, qasenabled);

				} else {
					//console.log("Show 2" + selectorText);
					$(selectorText).removeClass("hidden");
					$(selector).addClass("hidden");
					$(selector).empty();

					//InitializeQaSForNewState(token, qasenabled);
				}
			});

		};
	});



	var btnRemoveAddress = document.querySelectorAll(".btnRemoveAddress");
	Array.prototype.forEach.call(btnRemoveAddress, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			var aid = el.getAttribute("aid");
			console.log("aid: " + aid);
			var divErrorClear = document.getElementById("divRemoveAddressErrorMessage_" + aid);
			console.log(divErrorClear);
			divErrorClear.innerHTML = "";
			divErrorClear.classList.add("hidden");

			$(".btnRemoveAddress .save").addClass("hidden");
			$(".btnRemoveAddress .saving").removeClass("hidden");
			$(".btnRemoveAddress").attr("disabled", "disabled");

			var ServiceRequest = new Object();
			ServiceRequest.AddressId = aid;


			var fetchUrl = "/api/accounts/addressapi/removeaddress";
			console.log(fetchUrl);
			var editAccountPromise = fetch(fetchUrl, {
				method: "POST",
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(ServiceRequest)
			});

			editAccountPromise.then(rep => {
				//				console.log(rep);
				return rep.json();
			}).then(data => {
				console.log(data);
				if (data.HasErrors) {
					var divError = document.getElementById("divRemoveAddressErrorMessage_" + aid);
					divError.innerHTML = data.Errors[0];
					divError.classList.remove("hidden");

					$(".btnRemoveAddress .save").removeClass("hidden");
					$(".btnRemoveAddress .saving").addClass("hidden");
					$(".btnRemoveAddress").removeAttr("disabled");
				}
				if (data.IsSuccess) {
					window.location.reload();
				}

			});

		};
	});

	var btnDefaultAddress = document.querySelectorAll(".btnDefaultAddress");
	Array.prototype.forEach.call(btnDefaultAddress, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			var aid = el.getAttribute("aid");
			console.log("aid: " + aid);
			var divErrorClear = document.getElementById("divDefaultAddressErrorMessage_" + aid);
			console.log(divErrorClear);
			divErrorClear.innerHTML = "";
			divErrorClear.classList.add("hidden");

			$(".btnDefaultAddress .save").addClass("hidden");
			$(".btnDefaultAddress .saving").removeClass("hidden");
			$(".btnDefaultAddress").attr("disabled", "disabled");

			var ServiceRequest = new Object();
			ServiceRequest.AddressId = aid;


			var fetchUrl = "/api/accounts/addressapi/defaultaddress";
			console.log(fetchUrl);
			var editAccountPromise = fetch(fetchUrl, {
				method: "POST",
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(ServiceRequest)
			});

			editAccountPromise.then(rep => {
				//				console.log(rep);
				return rep.json();
			}).then(data => {
				console.log(data);
				if (data.HasErrors) {
					var divError = document.getElementById("divDefaultAddressErrorMessage_" + aid);
					divError.innerHTML = data.Errors[0];
					divError.classList.remove("hidden");

					$(".btnDefaultAddress .save").removeClass("hidden");
					$(".btnDefaultAddress .saving").addClass("hidden");
					$(".btnDefaultAddress").removeAttr("disabled");
				}
				if (data.IsSuccess) {
					window.location.reload();
				}

			});

		};
	});

	$(".ddlCountries").each(function () {

		$(this).change(function () {
			//console.log("Test 2");
			var aid = $(this).attr("aid");
			var countryCode = $(this).val();
			var divAddressList = document.getElementById("divAddressList");
			var qasenabled = divAddressList.getAttribute("data-qas-enabled");
			var token = divAddressList.getAttribute("data-qas-token");
			//console.log("countryCode: " + countryCode);
			var statesCollection = new Array();
			var promise = GetStates(countryCode, aid).done(function (data) {

				//console.log("Results From Promise");
				//console.log(data);
				var states = data.States;
				for (var key in states) {
					if (states.hasOwnProperty(key)) {
						var StateRequest = new Object();
						StateRequest.StateCode = key;
						StateRequest.State = states[key];
						statesCollection.push(StateRequest);
					}
				}

				var selector = "#ddlStates_" + aid;
				var selectorText = "#txtState_" + aid;

				console.log(statesCollection.length);

				if (statesCollection.length > 0) {
					PopluateStates(statesCollection, selector);
					$(selector).removeClass("hidden");
					$(selectorText).addClass("hidden");
					//$(selectorText).val("");
					InitializeQaSForEdit(aid);
				} else {
					//console.log("Show 2" + selectorText);
					$(selectorText).removeClass("hidden");
					$(selector).addClass("hidden");
					$(selector).empty();
					InitializeQaSForEditState(aid);
				}
			});

		});

	});

	$("#ddlCountries").change(function () {

		var countryCode = $(this).val();
		var divAddressList = document.getElementById("divAddressList");
		var qasenabled = divAddressList.getAttribute("data-qas-enabled");
		var token = divAddressList.getAttribute("data-qas-token");
		//console.log("countryCode: " + countryCode);
		var statesCollection = new Array();
		var promise = GetStates(countryCode, null).done(function (data) {

			var states = data.States;
			for (var key in states) {
				if (states.hasOwnProperty(key)) {
					var StateRequest = new Object();
					StateRequest.StateCode = key;
					StateRequest.State = states[key];
					statesCollection.push(StateRequest);
				}
			}

			var selector = "#ddlStates";
			var selectorText = "#txtState";

			console.log(statesCollection.length);

			if (statesCollection.length > 0) {
				PopluateStates(statesCollection, selector);
				$(selector).removeClass("hidden");
				$(selectorText).addClass("hidden");
				//$(selectorText).val("");


				//newAddressContactDataServices.elements.province = document.querySelector("select[id='ddlStates']");
				//newAddressContactDataServices.reset();
				newAddressContactDataServices.unbind();
				InitializeQaSForNew(token, qasenabled);

			} else {
				//console.log("Show 2" + selectorText);
				$(selectorText).removeClass("hidden");
				$(selector).addClass("hidden");
				$(selector).empty();

				//console.log(newAddressContactDataServices.elements.province);
				//newAddressContactDataServices.elements.province = document.querySelector("input[id='txtState']");
				//console.log(newAddressContactDataServices.elements.province);
				//newAddressContactDataServices.reset();
				newAddressContactDataServices.unbind();
				InitializeQaSForNewState(token, qasenabled);
			}
		});

	});

	$(".ddlStates").change(function () {
		//console.log("Edit State Drop Down Changed");
		var aid = $(this).attr("aid");
		var stateVal = $(this).val();
		//console.log("State Changes");
		//console.log(stateVal);
		var selector = "#ddlStates_" + aid;
		var selectorText = "#txtState_" + aid;
		$(selectorText).val(stateVal);
	});

	$("#ddlStates").change(function () {
		var stateVal = $(this).val();
		//console.log(stateVal);
		var selector = "#ddlStates";
		var selectorText = "#txtState";
		$(selectorText).val(stateVal);
	});
}

function InitializeQaSForEdit(aid) {

	var elements = {
		input: document.querySelector("input[id='txtAddressLine1_" + aid + "']"),
		countryList: document.querySelector("select[id='ddlCountries_" + aid + "']"),
		addressLine1: document.querySelector("input[id='txtAddressLine1_" + aid + "']"),
		addressLine2: document.querySelector("input[id='txtAddressLine2_" + aid + "']"),
		addressLine3: document.querySelector("input[id='txtAddressLine3_" + aid + "']"),
		locality: document.querySelector("input[id='txtCity_" + aid + "']"),
		province: document.querySelector("select[id='ddlStates_" + aid + "']"),
		postalCode: document.querySelector("input[id='txtPostalCode_" + aid + "']")
	};
	var country = $("#ddlCountries_" + aid).val();
	var addressService = new QasServices.InitializeQAS(elements, country);
	if (addressService !== null &&
		addressService !== undefined &&
		addressService.events !== null &&
		addressService.events !== undefined) {

		addressService.events.on("post-picklist-selection", function (data) {

			setTimeout(function () {
				$("select[id='ddlStates_" + aid + "']").change();

			}, 400);

		});
	}

}

function InitializeQaSForEditState(aid) {

	//var qasEnabled = $(RegistrationForm.RootElement).data("qas-enabled");
	var elements = {
		input: document.querySelector("input[id='txtAddressLine1_" + aid + "']"),
		countryList: document.querySelector("select[id='ddlCountries_" + aid + "']"),
		addressLine1: document.querySelector("input[id='txtAddressLine1_" + aid + "']"),
		addressLine2: document.querySelector("input[id='txtAddressLine2_" + aid + "']"),
		addressLine3: document.querySelector("input[id='txtAddressLine3_" + aid + "']"),
		locality: document.querySelector("input[id='txtCity_" + aid + "']"),
		province: document.querySelector("select[id='txtState_" + aid + "']"),
		postalCode: document.querySelector("input[id='txtPostalCode_" + aid + "']")
	};

	var country = $("#ddlCountries_" + aid).val();
	var addressService = new QasServices.InitializeQAS(elements, country);
	if (addressService !== null &&
		addressService !== undefined &&
		addressService.events !== null &&
		addressService.events !== undefined) {
	}

}

function InitializeQaSForNew(token, qasEnabled) {
	var elements = {
		input: document.querySelector("input[id='txtAddressLine1']"),
		countryList: document.querySelector("select[id='ddlCountries']"),
		addressLine1: document.querySelector("input[id='txtAddressLine1']"),
		addressLine2: document.querySelector("input[id='txtAddressLine2']"),
		addressLine3: document.querySelector("input[id='txtAddressLine3']"),
		locality: document.querySelector("input[id='txtCity']"),
		province: document.querySelector("select[id='ddlStates']"),
		postalCode: document.querySelector("input[id='txtPostalCode']")
	};
	var country = $("#ddlCountries").val();
	var addressService = new QasServices.InitializeQAS(elements, country);
	if (addressService !== null && addressService !== undefined && addressService.events !== null && addressService.events !== undefined) {

		addressService.events.on("post-picklist-selection", function (data) {

		});
		addressService.events.on("post-formatting-search", function (data) {
			console.log("post-formatting-search");
			data.components.forEach(function (component) {

				if (component.provinceCode1 !== undefined) {
					document.querySelector("input[id='txtState']").value = component.provinceCode1;
				}

			});
		});
	}
	newAddressContactDataServices = addressService;

}

function InitializeQaSForNewState() {

	var elements = {
		input: document.querySelector("input[id='txtAddressLine1']"),
		countryList: document.querySelector("select[id='ddlCountries']"),
		addressLine1: document.querySelector("input[id='txtAddressLine1']"),
		addressLine2: document.querySelector("input[id='txtAddressLine2']"),
		addressLine3: document.querySelector("input[id='txtAddressLine3']"),
		locality: document.querySelector("input[id='txtCity']"),
		province: document.querySelector("select[id='txtState']"),
		postalCode: document.querySelector("input[id='txtPostalCode']")
	};

	var country = $("#ddlCountries").val();
	var addressService = new QasServices.InitializeQAS(elements, country);
	if (addressService !== null &&
		addressService !== undefined &&
		addressService.events !== null &&
		addressService.events !== undefined) {

	}
	newAddressContactDataServices = addressService;

}

function GetStates(countryCode, aid) {

	var ServiceRequest = new Object();
	ServiceRequest.countryCode = countryCode;

	var url = "/api/cxa/JmmSxaAccount/GetStates";
	var requestData = JSON.stringify(ServiceRequest);
	var ajaxRequest = $.ajax({
		type: 'POST',
		contentType: "application/json;charset=utf-8",
		url: url,
		data: requestData,
		success: function (data) {

		},
		error: function (x, y, z) {
			//alert(x + '\n' + y + '\n' + z);
		}
	});
	return ajaxRequest;
}

function PopluateStates(states, selector) {

	//console.log("ddl: ");
	//console.log(selector);
	//console.log(states);

	$(selector).empty();
	//console.log(states);
	for (var i = 0; i < states.length; i++) {
		//console.log(states[i]);
		//$(selector).hide();

		$(selector).append("<option value=" + states[i].StateCode + ">" + states[i].State + "</option>");
	}

}


function openDefaultModal(id) {
	document.querySelector(".main-layout").classList.add("modal-open");
	document.getElementById(id).style.display = "block";
	document.getElementById(id).style.background = "rgba(0,0,0, .5)";
	document.getElementById(id).classList.add("in");
}

function closeDefaultModal(modalId, inputId) {
	document.getElementById(inputId).checked = false;
	document.querySelector(".main-layout").classList.remove("modal-open");
	document.getElementById(modalId).style.display = "";
	document.getElementById(modalId).style.background = "";
	document.getElementById(modalId).classList.remove("in");
}

function GetCountryMap() {

	var countryMap = {
		"AF": "AFG",
		"AX": "ALA",
		"AL": "ALB",
		"DZ": "DZA",
		"AS": "ASM",
		"AD": "AND",
		"AO": "AGO",
		"AI": "AIA",
		"AQ": "ATA",
		"AG": "ATG",
		"AR": "ARG",
		"AM": "ARM",
		"AW": "ABW",
		"AU": "AUS",
		"AT": "AUT",
		"AZ": "AZE",
		"BS": "BHS",
		"BH": "BHR",
		"BD": "BGD",
		"BB": "BRB",
		"BY": "BLR",
		"BE": "BEL",
		"BZ": "BLZ",
		"BJ": "BEN",
		"BM": "BMU",
		"BT": "BTN",
		"BO": "BOL",
		"BA": "BIH",
		"BW": "BWA",
		"BV": "BVT",
		"BR": "BRA",
		"VG": "VGB",
		"IO": "IOT",
		"BN": "BRN",
		"BG": "BGR",
		"BF": "BFA",
		"BI": "BDI",
		"KH": "KHM",
		"CM": "CMR",
		"CA": "CAN",
		"CV": "CPV",
		"KY": "CYM",
		"CF": "CAF",
		"TD": "TCD",
		"CL": "CHL",
		"CN": "CHN",
		"HK": "HKG",
		"MO": "MAC",
		"CX": "CXR",
		"CC": "CCK",
		"CO": "COL",
		"KM": "COM",
		"CG": "COG",
		"CD": "COD",
		"CK": "COK",
		"CR": "CRI",
		"CI": "CIV",
		"HR": "HRV",
		"CU": "CUB",
		"CY": "CYP",
		"CZ": "CZE",
		"DK": "DNK",
		"DJ": "DJI",
		"DM": "DMA",
		"DO": "DOM",
		"EC": "ECU",
		"EG": "EGY",
		"SV": "SLV",
		"GQ": "GNQ",
		"ER": "ERI",
		"EE": "EST",
		"ET": "ETH",
		"FK": "FLK",
		"FO": "FRO",
		"FJ": "FJI",
		"FI": "FIN",
		"FR": "FRA",
		"GF": "GUF",
		"PF": "PYF",
		"TF": "ATF",
		"GA": "GAB",
		"GM": "GMB",
		"GE": "GEO",
		"DE": "DEU",
		"GH": "GHA",
		"GI": "GIB",
		"GR": "GRC",
		"GL": "GRL",
		"GD": "GRD",
		"GP": "GLP",
		"GU": "GUM",
		"GT": "GTM",
		"GG": "GGY",
		"GN": "GIN",
		"GW": "GNB",
		"GY": "GUY",
		"HT": "HTI",
		"HM": "HMD",
		"VA": "VAT",
		"HN": "HND",
		"HU": "HUN",
		"IS": "ISL",
		"IN": "IND",
		"ID": "IDN",
		"IR": "IRN",
		"IQ": "IRQ",
		"IE": "IRL",
		"IM": "IMN",
		"IL": "ISR",
		"IT": "ITA",
		"JM": "JAM",
		"JP": "JPN",
		"JE": "JEY",
		"JO": "JOR",
		"KZ": "KAZ",
		"KE": "KEN",
		"KI": "KIR",
		"KP": "PRK",
		"KR": "KOR",
		"KW": "KWT",
		"KG": "KGZ",
		"LA": "LAO",
		"LV": "LVA",
		"LB": "LBN",
		"LS": "LSO",
		"LR": "LBR",
		"LY": "LBY",
		"LI": "LIE",
		"LT": "LTU",
		"LU": "LUX",
		"MK": "MKD",
		"MG": "MDG",
		"MW": "MWI",
		"MY": "MYS",
		"MV": "MDV",
		"ML": "MLI",
		"MT": "MLT",
		"MH": "MHL",
		"MQ": "MTQ",
		"MR": "MRT",
		"MU": "MUS",
		"YT": "MYT",
		"MX": "MEX",
		"FM": "FSM",
		"MD": "MDA",
		"MC": "MCO",
		"MN": "MNG",
		"ME": "MNE",
		"MS": "MSR",
		"MA": "MAR",
		"MZ": "MOZ",
		"MM": "MMR",
		"NA": "NAM",
		"NR": "NRU",
		"NP": "NPL",
		"NL": "NLD",
		"AN": "ANT",
		"NC": "NCL",
		"NZ": "NZL",
		"NI": "NIC",
		"NE": "NER",
		"NG": "NGA",
		"NU": "NIU",
		"NF": "NFK",
		"MP": "MNP",
		"NO": "NOR",
		"OM": "OMN",
		"PK": "PAK",
		"PW": "PLW",
		"PS": "PSE",
		"PA": "PAN",
		"PG": "PNG",
		"PY": "PRY",
		"PE": "PER",
		"PH": "PHL",
		"PN": "PCN",
		"PL": "POL",
		"PT": "PRT",
		"PR": "PRI",
		"QA": "QAT",
		"RE": "REU",
		"RO": "ROU",
		"RU": "RUS",
		"RW": "RWA",
		"BL": "BLM",
		"SH": "SHN",
		"KN": "KNA",
		"LC": "LCA",
		"MF": "MAF",
		"PM": "SPM",
		"VC": "VCT",
		"WS": "WSM",
		"SM": "SMR",
		"ST": "STP",
		"SA": "SAU",
		"SN": "SEN",
		"RS": "SRB",
		"SC": "SYC",
		"SL": "SLE",
		"SG": "SGP",
		"SK": "SVK",
		"SI": "SVN",
		"SB": "SLB",
		"SO": "SOM",
		"ZA": "ZAF",
		"GS": "SGS",
		"SS": "SSD",
		"ES": "ESP",
		"LK": "LKA",
		"SD": "SDN",
		"SR": "SUR",
		"SJ": "SJM",
		"SZ": "SWZ",
		"SE": "SWE",
		"CH": "CHE",
		"SY": "SYR",
		"TW": "TWN",
		"TJ": "TJK",
		"TZ": "TZA",
		"TH": "THA",
		"TL": "TLS",
		"TG": "TGO",
		"TK": "TKL",
		"TO": "TON",
		"TT": "TTO",
		"TN": "TUN",
		"TR": "TUR",
		"TM": "TKM",
		"TC": "TCA",
		"TV": "TUV",
		"UG": "UGA",
		"UA": "UKR",
		"AE": "ARE",
		"GB": "GBR",
		"US": "USA",
		"UM": "UMI",
		"UY": "URY",
		"UZ": "UZB",
		"VU": "VUT",
		"VE": "VEN",
		"VN": "VNM",
		"VI": "VIR",
		"WF": "WLF",
		"EH": "ESH",
		"YE": "YEM",
		"ZM": "ZMB",
		"ZW": "ZWE",
		"XK": "XKX"
	};

	return countryMap;

}


InitializeEditAddressForm();
;



function InitializeChangePassword() {

	var btnDefaultAddress = document.querySelectorAll(".btnChangePassword");
	Array.prototype.forEach.call(btnDefaultAddress, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			$.validator.unobtrusive.parse("ChangePasswordForm");

			
			var isValid = $("#ChangePasswordForm").valid();
			//console.log("isValid: " + isValid);
			if (isValid) {


				$(".btnChangePassword .save").addClass("hidden");
				$(".btnChangePassword .saving").removeClass("hidden");
				$(".btnChangePassword").attr("disabled", "disabled");

				var txtEmailAddress = document.getElementById("txtPassword");
				var txtConfirmPassword = document.getElementById("txtConfirmPassword");

				var ServiceRequest = new Object();
				ServiceRequest.NewPassword = txtEmailAddress.value;
				ServiceRequest.ConfirmNewPassword = txtConfirmPassword.value;

				var fetchUrl = "/api/accounts/accountsapi/ChangePassword";
				//console.log(fetchUrl);
				var apiPromise = fetch(fetchUrl,
					{
						method: "POST",
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify(ServiceRequest)
					});

				apiPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					//console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divChangePasswordErrorMessage");
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");
						$.modalNoConflict.close();


						$(".btnChangePassword .save").removeClass("hidden");
						$(".btnChangePassword .saving").addClass("hidden");
						$(".btnChangePassword").removeAttr("disabled");
					}
					if (data.IsSuccess) {

						var redirectUrl = data.Result.ReturnUrl;
						//console.log(redirectUrl);
						if (redirectUrl === null || redirectUrl === undefined) {
							//redirectUrl = $("#divPasswordRecovery").attr("data-return-url");

						}
						if (redirectUrl !== null && redirectUrl !== undefined) {
							window.location.href = redirectUrl;
						}
						else {
							window.location.reload();
						}
					}

				});
			}

		};
	});
}


InitializeChangePassword();
;



function InitializeEditAccountForm() {
	var btnSaveChanges = document.querySelectorAll(".btnEditProfileSaveChanges");
	Array.prototype.forEach.call(btnSaveChanges, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			$.validator.unobtrusive.parse("PersonalInfoForm");
			var isValid = $("#PersonalInfoForm").valid();
			var isorganizationStr = $("#profileEditModal").attr("data-is-organization");
			var isorganization = isorganizationStr == "True" ? true : false;
			//console.log("isValid: " + isValid);
			//console.log("isorganization: " + isorganization);

			if (isValid) {


				var divErrorClear = document.getElementById("divEditAccountErrorMessage");
				divErrorClear.innerHTML = "";
				divErrorClear.classList.add("hidden");

				$(".btnEditProfileSaveChanges .save").addClass("hidden");
				$(".btnEditProfileSaveChanges .saving").removeClass("hidden");
				$(".btnEditProfileSaveChanges").attr("disabled", "disabled");


				var txtFirstName = document.getElementById("txtFirstName");
				var txtLastName = document.getElementById("txtLastName");
				var txtEmailAddress = document.getElementById("txtEmailAddress");
				var txtPhone = document.getElementById("txtPhone");
				var txtMobilePhone = document.getElementById("txtMobilePhone");
				var txtBirthDate = document.getElementById("txtBirthDate");
				var ddlWhereIWatchJoyce = document.getElementById("ddlWhereIWatchJoyce");
				var ddlGiftAid = document.getElementById("ddlGiftAid");

				var txtOrganization = document.getElementById("txtOrganization");
				var txtContactFirstName = document.getElementById("txtContactFirstName");
				var txtContactLastName = document.getElementById("txtContactLastName");
				var ddlOrganizationType = document.getElementById("ddlOrganizationType");

				var ServiceRequest = new Object();
				if (!isorganization) {
					ServiceRequest.FirstName = txtFirstName.value;
					ServiceRequest.LastName = txtLastName.value;
				}
				else {

					ServiceRequest.Organization = txtOrganization.value;
					ServiceRequest.ContactFirstName = txtContactFirstName.value;
					ServiceRequest.ContactLastName = txtContactLastName.value;
					ServiceRequest.OrganizationType = ddlOrganizationType.value;


					ServiceRequest.FirstName = txtContactFirstName.value;
					ServiceRequest.LastName = txtContactLastName.value;
				}

				ServiceRequest.EmailAddress = txtEmailAddress.value;
				ServiceRequest.Phone = txtPhone.value;
				//ServiceRequest.MobilePhone = txtMobilePhone.value;
				if (txtBirthDate != null)
					ServiceRequest.BirthDate = txtBirthDate.value;
				if (ddlWhereIWatchJoyce !== null) {
					ServiceRequest.WhereIWatchJoyce = ddlWhereIWatchJoyce.value;
				}

				if (ddlGiftAid !== null)
					ServiceRequest.GivingAid = ddlGiftAid.value;
				else
					ServiceRequest.GivingAid = "";

				var fetchUrl = "/api/accounts/accountsapi/updateaccount";
				console.log(fetchUrl);
				const editAccountPromise = fetch(fetchUrl,
					{
						method: "POST",
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify(ServiceRequest)
					});

				editAccountPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divEditAccountErrorMessage");
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");

						$(".btnEditProfileSaveChanges .save").removeClass("hidden");
						$(".btnEditProfileSaveChanges .saving").addClass("hidden");
						$(".btnEditProfileSaveChanges").removeAttr("disabled");
					}
					if (data.IsSuccess) {
						window.location.reload();
					}

				});
			}

		};
	});
}


InitializeEditAccountForm();
;



function InitializeForgotPassword() {

	var btnDefaultAddress = document.querySelectorAll(".btnForgotPassword");
	Array.prototype.forEach.call(btnDefaultAddress, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			$.validator.unobtrusive.parse("ForgotPasswordForm");

			//console.log("This is a test");
			var isValid = $("#ForgotPasswordForm").valid();
			//console.log("isValid: " + isValid);
			if (isValid) {

				$(".btnForgotPassword .save").addClass("hidden");
				$(".btnForgotPassword .saving").removeClass("hidden");
				$(".btnForgotPassword").attr("disabled", "disabled");


				var txtEmailAddress = document.getElementById("txtEmailAddress");
				var ServiceRequest = new Object();
				ServiceRequest.EmailAddress = txtEmailAddress.value;


				var fetchUrl = "/api/accounts/securityapi/forgotpassword";
				//console.log(fetchUrl);
				var apiPromise = fetch(fetchUrl,
					{
						method: "POST",
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify(ServiceRequest)
					});

				apiPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					//console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divErrorMessage");
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");
						//$.modalNoConflict.close();


						$(".btnForgotPassword .save").removeClass("hidden");
						$(".btnForgotPassword .saving").addClass("hidden");
						$(".btnForgotPassword").removeAttr("disabled");

					}
					if (data.IsSuccess) {

						var redirectUrl = data.Result.ReturnUrl;
						//console.log(redirectUrl);
						if (redirectUrl === null || redirectUrl === undefined) {
							redirectUrl = $("#divForgotPassword").attr("data-return-url");
						}
						if (redirectUrl !== null && redirectUrl !== undefined) {
							window.location.href = redirectUrl;
						}
						else {
							window.location.reload();
						}
					}

				});
			}

		};
	});
}


InitializeForgotPassword();
;



function InitializeGivingSummary() {

	var ddlGivingSummary = document.getElementById("ddlGivingSummary");

	if (ddlGivingSummary === null)
		return;

	ddlGivingSummary.addEventListener("change",
		function() {

			var hrefGivingSummaryView = document.getElementById("hrefGivingSummaryView");
			var year = ddlGivingSummary.value;
			var givingSummaryUrl = hrefGivingSummaryView.getAttribute("data-url");
			givingSummaryUrl = givingSummaryUrl + year;
			console.log(givingSummaryUrl);
			hrefGivingSummaryView.setAttribute("href", givingSummaryUrl);

		});


	

}


InitializeGivingSummary();
;
/*--- MFA ---*/
var loginData, verifyGuid, loginFromSpc, verificationCodeInputs, loginLabels, resetInterval, extendSession, isSubmitting;
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

if (document.getElementById("utilityLoginPanel")) {
	verificationCodeInputs = [...document.querySelectorAll("input.code-input")];
	loginLabels= {
		"login": document.getElementById("btnAccountLogin").innerText,
		"verify": document.getElementById("btnCompleteLogin").innerText
	}

	async function loginRequest (serviceRequest, action) {
		const response = await fetch(`/api/accounts/securityapi/${action}`,
			{
				method: "POST",
				headers: {
					"Content-Type": "application/json"
				},
				body: JSON.stringify(serviceRequest)
			}
		);

		if (!response.ok || response.status !== 200) {
			throw new Error(`An error has occured: ${response.status}`);
		}

		const data = await response.json();
		return data;
	};

	function openLoginPanel(isSpc) {
		handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
		window.openUtilityPanel(null, "utilityLoginPanel");
		loginFromSpc = isSpc;
	}

	function loginUser () {
	   handleLoginLoading(true);
	   extendSession = document.getElementById("extendSession").checked;

		const serviceRequest = {
			"UserName": document.getElementById("userNameLoginCommerce").value,
			"Password": document.getElementById("passwordLoginCommerce").value
		};
		loginRequest(serviceRequest, "InitiateLogin")
			.then((data) => {
				if (data.IsSuccess) {
					loginData = data;
					if (!data.Profile.HasMultipleOptions) {
						populateCard(false, data.Profile.MfaOptions, "email");
						setMfaSelection(data.Profile.MfaOptions[0], "login-mfa3", "login-form", true);
						document.getElementById("mfaPhoneButton").style.display = "none";
					} else {
						const emails = loginData.Profile.MfaOptions.filter(obj => obj.Type.toLowerCase() === "email");
						const phones = loginData.Profile.MfaOptions.filter(obj => obj.Type.toLowerCase() === "phone");

						if (emails.length > 1) {
							populateCard(true, emails, "email");
							generateAddressList(emails, "email");
						} else if (emails.length !== 0) {
							populateCard(false, emails, "email");
						}

						if (phones.length > 1) {
							populateCard(true, phones, "phone");
							generateAddressList(phones, "phone");
							document.querySelector("#login-mfa2 [data-mfa-sms-disclaimer]").style.display = "";
							document.querySelector("#login-mfa1 [data-mfa-sms-disclaimer]").style.display = "none";
						} else if (phones.length !== 0) {
							populateCard(false, phones, "phone");
							document.querySelector("#login-mfa2 [data-mfa-sms-disclaimer]").style.display = "none";
							document.querySelector("#login-mfa1 [data-mfa-sms-disclaimer]").style.display = "";
						}

						mfaNext("login-mfa1", "login-form", true);
					}
					document.getElementById("LoginForm").reset();
					document.getElementById("divLoginErrorMessage").setAttribute("class", "alert alert-danger hidden");
				} else {
					document.getElementById("divLoginErrorMessage").innerText = data.ErrorMessage;
					document.getElementById("divLoginErrorMessage").setAttribute("class", "alert alert-danger");
					handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
				}

				handleLoginLoading(false);
			}).catch((err) => {
				document.getElementById("divLoginErrorMessage").innerText = err.message;
				document.getElementById("divLoginErrorMessage").setAttribute("class", "alert alert-danger");
				handleLoginLoading(false);
				handleLoginPanelSizeChange(document.getElementById("login-mfa1"), document.getElementById("login-tabs"));
			});
	}

	function completeLogin(verificationGuid) {
		if (isSubmitting) {
			return;
		}
		isSubmitting = true;
		const verificationCode = verificationCodeInputs.map(({ value }) => value).join("");

		handleLoginLoading(true);

		const today = new Date();
		today.setTime(today.getTime() + (30 * 60 * 1000));
		const cookieExpires = today.toUTCString();

		if (extendSession) {
			document.cookie = `extendSession=true; expires=${cookieExpires};`;
		} else {
			document.cookie = `extendSession=false; expires=${cookieExpires};`;
		}

		const serviceRequest = {
			"ProfileId": loginData.Profile.Id,
			"VerificationCode": verificationCode,
			"VerificationGuid": verificationGuid,
			"RememberMe": extendSession
		};
		loginRequest(serviceRequest, "CompleteLogin")
			.then((data) => {
				if (data.IsSuccess) {
					if (loginFromSpc) {
						window.sessionStorage.setItem("justLoggedIn", true);
						document.cookie = `JustLoggedIn=true;expires=${window.setTimeForCookies(120)};path=/`;
					}
					window.location.reload();
				} else {
					document.getElementById("divCompleteLoginErrorMessage").innerText = data.ErrorMessage;
					document.getElementById("divCompleteLoginErrorMessage").setAttribute("class", "alert alert-danger");
		            handleLoginLoading(false);
		            document.getElementById("verificationCodeForm").reset();
					handleLoginPanelSizeChange(document.getElementById("login-mfa3"), document.getElementById("login-tabs"));
					isSubmitting = false;
				}
			}).catch((err) => {
				document.getElementById("divCompleteLoginErrorMessage").innerText = err.message;
				document.getElementById("divCompleteLoginErrorMessage").setAttribute("class", "alert alert-danger");
				handleLoginLoading(false);
				document.getElementById("verificationCodeForm").reset();
				handleLoginPanelSizeChange(document.getElementById("login-mfa3"), document.getElementById("login-tabs"));
				isSubmitting = false;
			});
	}

	function resendVerificationCode(verificationId) {
		document.getElementById("divCompleteLoginErrorMessage").setAttribute("class", "alert alert-danger hidden");
		document.getElementById("divResendCodeSuccess").setAttribute("class", "alert alert-success hidden");

	   handleLoginLoading(true);
	   const serviceRequest = {
			"ProfileId": loginData.Profile.Id,
			"VerificationType": loginData.Profile.MfaOptions.filter(obj => obj.Id === verificationId)[0].Type,
			"VerificationId": verificationId
		};
		loginRequest(serviceRequest, "VerifyLogin")
			.then((data) => {
				if (data.IsSuccess) {
					handleLoginLoading(false);
					resendCodeTimeout();
					verifyGuid = data.VerificationGuid;
					document.getElementById("divResendCodeSuccess").innerText = "Code resent!";
					document.getElementById("divResendCodeSuccess").setAttribute("class", "alert alert-success");
					setTimeout(() => {
						document.getElementById("divResendCodeSuccess").setAttribute("class", "alert alert-success hidden");
						document.querySelectorAll("[data-mfa-assistance]").forEach(button => {
							button.disabled = false;
							button.style.opacity = "";
							button.style.cursor = "";
						});
						handleLoginPanelSizeChange(document.getElementById("login-mfa3"), document.getElementById("login-tabs"));
					}, 5000);
				} else {
					document.getElementById("divCompleteLoginErrorMessage").innerText = data.ErrorMessage;
					document.getElementById("divCompleteLoginErrorMessage").setAttribute("class", "alert alert-danger");
				}
	         document.getElementById("verificationCodeForm").reset();
	         handleLoginPanelSizeChange(document.getElementById("login-mfa3"), document.getElementById("login-tabs"));
			}).catch((err) => {
				document.getElementById("divCompleteLoginErrorMessage").innerText = err.message;
				document.getElementById("divCompleteLoginErrorMessage").setAttribute("class", "alert alert-danger");
	         handleLoginLoading(false);
	         handleLoginPanelSizeChange(document.getElementById("login-mfa3"), document.getElementById("login-tabs"));
			});
	}

	function setMfaSelection(obj, to, from, next) {
		document.querySelectorAll("[data-selected-address]").forEach(element => {
			element.innerText = obj.Value;
		});

	   if (!loginData.Profile.VerificationGuid ||
		   loginData.Profile.VerificationGuid === "00000000-0000-0000-0000-000000000000") {
		   handleLoginLoading(true);

		   const serviceRequest = {
			   "ProfileId": loginData.Profile.Id,
			   "VerificationType": obj.Type,
			   "VerificationId": obj.Id
		   };

		   loginRequest(serviceRequest, "VerifyLogin")
			   .then((data) => {
				   if (data.IsSuccess) {
					   verifyGuid = data.VerificationGuid;
					   document.querySelectorAll(".mfa-type").forEach(element => {
						   element.style.display = "none";
					   });
					   document.getElementById(`mfa_${obj.Type.toLowerCase()}VerificationDescription`).style.display = "";
					   mfaNext(to, from, next);
					   document.getElementById("btnCompleteLogin").onclick = () => {
						   completeLogin(data.VerificationGuid);
					   };
					   document.getElementById("resendCodeButton").onclick = () => {
						   resendVerificationCode(obj.Id);
					   };
					   document.querySelectorAll("[data-verify-login-error]").forEach((element) => {
						   element.innerText = "";
						   element.setAttribute("class", "alert alert-danger hidden");
					   });
				   } else {
					   document.querySelectorAll("[data-verify-login-error]").forEach((element) => {
						   element.innerText = data.ErrorMessage;
						   element.setAttribute("class", "alert alert-danger margin-block-start-2");
					   });
					   handleLoginPanelSizeChange(document.getElementById(from), document.getElementById("login-tabs"));
				   }
				   handleLoginLoading(false);
			   }).catch((err) => {
				   document.querySelectorAll("[data-verify-login-error]").forEach((element) => {
					   element.innerText = data.ErrorMessage;
					   element.setAttribute("class", "alert alert-danger margin-block-start-2");
				   });
				   handleLoginLoading(false);
				   handleLoginPanelSizeChange(document.getElementById(from), document.getElementById("login-tabs"));
			   });
	   } else {
		   verifyGuid = loginData.Profile.VerificationGuid;
		   document.querySelectorAll(".mfa-type").forEach(element => {
			   element.style.display = "none";
		   });
		   document.getElementById(`mfa_${obj.Type.toLowerCase()}VerificationDescription`).style.display = "";
		   mfaNext(to, from, next);
		   document.getElementById("btnCompleteLogin").onclick = () => {
			   completeLogin(verifyGuid);
		   };
		   document.getElementById("resendCodeButton").onclick = () => {
			   resendVerificationCode(obj.Id);
		   };
		   document.getElementById("divLoginErrorMessage").setAttribute("class", "alert alert-danger hidden");
	   }
	}

	function resetMfaSelection() {
		const descElements = document.querySelectorAll(".mfa-type");
		descElements.forEach(element => {
			element.style.display = "none";
			element.querySelector("[data-selected-address]").innerText = "";
		});
		document.getElementById("mfa_emailButtonContent").innerText = "";
		document.getElementById("mfa_phoneButtonContent").innerText = "";
		document.getElementById("mfa_phoneVerificationDescription").style.display = "none";
		document.getElementById("resendCodeButton").style.display = "";
		document.getElementById("resendCodeButton").disabled = false;
		document.getElementById("resendCodeTimeout").style.display = "none";
		document.getElementById("resendCodeTimeout2").style.display = "none";
			
		document.querySelectorAll("[data-mfa-change-method]").forEach(button => {
			button.disabled = false;
			button.style.opacity = "";
			button.style.cursor = "";
		});
		
		clearInterval(resetInterval);

		while (document.getElementById("mfa_phoneOptions").firstChild) {
			document.getElementById("mfa_phoneOptions").removeChild(document.getElementById("mfa_phoneOptions").firstChild);
		}
	}

	function populateCard(hasMultiple, data, type) {
		const primary = data[0];
		const cardText = {
			"email": {
				"single": "Send a code to my email",
				"multiple": "Email a code to"
			},
			"phone": {
				"single": "Text a code to",
				"multiple": "Text a code to my phone"
			}
		};

	   const fragment = document.createDocumentFragment();
		const text = document.createElement("span");
		text.setAttribute("class", "font-weight-2 color-font-dark");
		const address = document.createElement("span");
		address.setAttribute("class", "color-font-light");

		if (type.toLowerCase() === "email") {
			if (hasMultiple) {
				text.innerText = cardText.email.multiple;
				document.getElementById("mfaEmailButton").onclick = () => {
					handleMfaSelect(false, "mfa_emailOptions");
				};
			} else {
				text.innerText = cardText.email.single;
				address.innerText = primary.Value;
				address.id = primary.Id;
				document.getElementById("mfaEmailButton").onclick = () => {
					handleMfaSelect(true, primary.Id, "login-mfa1");
				};
			}
		}

		if (type.toLowerCase() === "phone") {
			if (hasMultiple) {
				text.innerText = cardText.phone.multiple;
				document.getElementById("mfaPhoneButton").onclick = () => {
					handleMfaSelect(false, "mfa_phoneOptions");
				};
			} else {
				text.innerText = cardText.phone.single;
				address.innerText = primary.Value;
				address.id = primary.Id;
				document.getElementById("mfaPhoneButton").onclick = () => {
					handleMfaSelect(true, primary.Id, "login-mfa1");
				};
			}
			document.getElementById("mfaPhoneButton").style.display = "";
		}
		fragment.append(text, address);
		document.getElementById(`mfa_${type}ButtonContent`).append(fragment);
	}

	function generateAddressList(data, type) {
		const fragment = document.createDocumentFragment();

		const fieldset = document.createElement("fieldset");
		fieldset.setAttribute("class", "margin-block-end-0");
		fieldset.setAttribute("style", "display: grid; grid-row-gap: 16px");

		data.forEach((obj) => {
			const container = document.createElement("div");
			container.setAttribute("class", "margin-block-end-0");
			container.setAttribute("style", "display: flex; -ms-align-items: center; -o-align-items: center; -webkit-align-items: center; align-items: center; padding: 0 10px; background: #fff; border: solid 1px #4e544d; border: solid 1px rgba(78, 84, 77, 0.34); -ms-border-radius: 3px; border-radius: 3px;");

			const input = document.createElement("input");
			input.setAttribute("type", "radio");
			input.setAttribute("id", obj.Id);
			input.setAttribute("name", `mfa_${type}Radio`);
			input.setAttribute("class", "mfa-radio");
			input.setAttribute("data-type", type);
			input.value = obj.Id;
			input.onclick = () => {
				handleMfaSelect(true, obj.Id, "login-mfa2");
				setTimeout(() => {
					document.querySelectorAll("input.mfa-radio").forEach(element => {
						element.checked = false;
					});
				}, 4000);
			};
			const label = document.createElement("label");
			label.setAttribute("for", obj.Id);
			label.setAttribute("class", "margin-block-end-0");
			label.setAttribute("style", "width: 100%; padding: 10px 0 10px 10px; text-align: left; font-weight: 600;");
			label.innerText = obj.Value;
			container.append(input, label);
			fieldset.append(container);
		});

		fragment.append(fieldset);
		document.getElementById(`mfa_${type}Options`).append(fragment);
	}

	function handleLoginLoading(isLoading) {
		document.getElementById("userNameLoginCommerce").disabled = isLoading;
		document.getElementById("passwordLoginCommerce").disabled = isLoading;
		document.getElementById("btnAccountLogin").disabled = isLoading;
		document.getElementById("btnCompleteLogin").disabled = isLoading;
		document.getElementById("loginClose").disabled = isLoading;
		document.getElementById("mfaEmailButton").disabled = isLoading;
		document.getElementById("mfaPhoneButton").disabled = isLoading;
		document.getElementById("resendCodeButton").disabled = isLoading;

		document.querySelectorAll("[data-mfa-change-method]").forEach(button => {
			button.disabled = isLoading;
		});
		document.querySelectorAll(".code-input").forEach(input => {
			input.disabled = isLoading;
		});
		document.querySelectorAll(".mfa-radio").forEach(input => {
			input.disabled = isLoading;
		});

		document.getElementById("btnAccountLogin").innerText = isLoading ? "...Processing" : loginLabels.login;
		document.getElementById("btnCompleteLogin").innerText = isLoading ? "...Processing" : loginLabels.verify;
		document.getElementById("loginClose").style.display = isLoading ? "none" : "";
	}

	function mfaNext(to, from, next) {
		const nextTab = document.getElementById(to);
		const currentTab = document.getElementById(from);
		const container = document.getElementById("login-tabs");
		const currentTabCss = next ? "is-complete" : "";

		if (from !== undefined) {
			handleLoginTabSlide(currentTab, `login-tab ${currentTabCss}`, "display: none;", 250);
		} else {
			document.querySelectorAll(".login-tab").forEach(element => {
				element.setAttribute("class", "login-tab");
				element.style.display = "none";
			});
		}

		document.querySelectorAll(".alert").forEach(element => {
			if(!element.classList.contains("hidden")) {
				element.classList.add("hidden");
			}
		});

		handleLoginTabSlide(nextTab, "login-tab is-current", "display: block;", 50);
		handleLoginPanelSizeChange(nextTab, container);
	}

	function handleLoginTabSlide(element, cssClass, style, timeout) {
		element.setAttribute("style", style);
		setTimeout(() => {
			element.setAttribute("class", cssClass);
		}, timeout);
	}

	function handleLoginPanelSizeChange(element, container) {
		setTimeout(() => {
			var newHeight = element.scrollHeight;
			container.style.height = `${newHeight + 5}px`;
		}, 10);
	}

	function handleMfaSelect(finalSelection, id, panel) {
	   if(finalSelection){
	      const selected = loginData.Profile.MfaOptions.filter(obj => obj.Id === id)[0];
	      setMfaSelection(selected, "login-mfa3", panel, true);
	   } else {
	      document.querySelectorAll(".mfa-list").forEach(element => {
	         element.style.display = "none";
	      });
	      document.getElementById(id).style.display = "";
	      mfaNext("login-mfa2", "login-mfa1", true);
	   }
	}

	function resendCodeTimeout() {
		document.getElementById("resendCodeButton").style.display = "none";
		document.getElementById("resendCodeButton").disabled = true;
		document.getElementById("resendCodeTimeout").style.display = "";
		document.getElementById("resendCodeTimeout2").style.display = "";
		document.querySelectorAll("[data-mfa-change-method]").forEach(button => {
			button.disabled = true;
			button.style.opacity = ".7";
			button.style.cursor = "not-allowed";
		});
		document.querySelectorAll("[data-mfa-assistance]").forEach(button => {
			button.disabled = true;
			button.style.opacity = ".7";
			button.style.cursor = "not-allowed";
		});

		startCountdown(59);
		
		setTimeout(() => {
			document.getElementById("resendCodeButton").style.display = "";
			document.getElementById("resendCodeButton").disabled = false;
			document.getElementById("resendCodeTimeout").style.display = "none";
			document.getElementById("resendCodeTimeout2").style.display = "none";
			document.querySelectorAll("[data-mfa-change-method]").forEach(button => {
				button.disabled = false;
				button.style.opacity = "";
				button.style.cursor = "";
			});
		}, 60000);
	}

	function startCountdown(seconds) {
		let counter = seconds;
		const counterElement = document.querySelector("#resendCodeTimeout strong");
		const counterElement2 = document.querySelector("#resendCodeTimeout2 strong");
		counterElement.innerText = seconds + 1;
		resetInterval = setInterval(() => {
			counterElement.innerText = counter;
			counterElement2.innerText = counter;
			counter--;
			if (counter < 0 ) {
				clearInterval(resetInterval);
			}
		}, 1000);
	}

	function validateLoginFields() {
		var hasError = false;
		const userName = document.getElementById("userNameLoginCommerce");
		const userNameError = document.getElementById("userNameLoginCommerce_error");
		const password = document.getElementById("passwordLoginCommerce");
		const passwordError = document.getElementById("passwordLoginCommerce_error");

		if (!userName.value.length > 0 || !userName.value.match(emailRegex)) {
			hasError = true;
			userNameError.setAttribute("class", "field-validation-error");
			userName.closest(".form-group").setAttribute("class", "required-field form-group has-error");
			handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
			if (!userName.value.length > 0) {
				userNameError.querySelector("span").innerText = "The Email Address field is required.";
			} else  if (!userName.value.match(emailRegex)) {
				userNameError.querySelector("span").innerText = "Please enter a valid email address.";
			}
		} else {
			userNameError.setAttribute("class", "field-validation-error hidden");
			userNameError.querySelector("span").innerText = "";
			userName.closest(".form-group").setAttribute("class", "required-field form-group");
			handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
		}

		if (!password.value.length > 0) {
			hasError = true;
			passwordError.setAttribute("class", "field-validation-error");
			passwordError.querySelector("span").innerText = "The Password field is required.";
			password.closest(".form-group").setAttribute("class", "required-field form-group has-error");
			handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
		} else {
			passwordError.setAttribute("class", "field-validation-error hidden");
			passwordError.querySelector("span").innerText = "";
			password.closest(".form-group").setAttribute("class", "required-field form-group");
			handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
		}
		return hasError;
	}

	//Event Listeners
	verificationCodeInputs.forEach((ele, index) => {
		ele.addEventListener("keydown", (e) => {
			if (e.keyCode === 8 && e.target.value === "")
				verificationCodeInputs[Math.max(0, index - 1)].focus();
		});

		ele.addEventListener("input", (e) => {
			const [first, ...rest] = e.target.value;
			e.target.value = first ? first : ""; 
			const lastInputBox = index === verificationCodeInputs.length - 1;
			const didInsertContent = first !== undefined;
			if (didInsertContent && !lastInputBox) {
				verificationCodeInputs[index + 1].focus();
				verificationCodeInputs[index + 1].value = rest.join("");
				verificationCodeInputs[index + 1].dispatchEvent(new Event("input"));
			}
			if (didInsertContent && lastInputBox) {
				if (verificationCodeInputs[5].value.length > 0) {
					completeLogin(verifyGuid);
				}
			}
		});

		ele.addEventListener("paste", (e) => {
			e.preventDefault();
				
			const firstInput = document.getElementById("otc-1");
			const clipboardData = e.clipboardData || window.clipboardData;
			const pastedData = clipboardData.getData("Text").split(" ").join("");
			firstInput.value = pastedData.trim();
			firstInput.dispatchEvent(new Event("change"));
		});
	});

	document.getElementById("otc-1").addEventListener("change", (event) => {
		const value = event.target.value;
		if (value.length === 1 || value.length === 0) return;
		verificationCodeInputs.forEach((element, index) => {
			element.value = value[index];

			if (index === verificationCodeInputs.length - 1) {
				element.focus();
				element.dispatchEvent(new Event("change"));
			}
		});
	});

	document.getElementById("otc-6").addEventListener("change", (event) => {
		const value = event.target.value;
		if (value.length > 0) {
			completeLogin(verifyGuid);
		}
	});

	document.getElementById("resendCodeButton").addEventListener("click", () => {
		resendVerificationCode(window.verificationGuid);
	});

	document.getElementById("loginClose").addEventListener("click", () => {
		window.closeUtilityPanel(false, "utilityLoginPanel");
		mfaNext("login-form", undefined, false);
		document.getElementById("LoginForm").reset();
		resetMfaSelection();
	});

	document.querySelectorAll("[data-mfa-assistance]").forEach(element => {
		element.addEventListener("click", (event) => {
			const target = event.target;
			const parent = target.closest(".login-tab");
			mfaNext("login-mfa4", parent.id, true);
		});
	});

	document.querySelectorAll("[data-mfa-change-method]").forEach(element => {
		element.addEventListener("click", (event) => {
			const target = event.target;
			const parent = target.closest(".login-tab");
			mfaNext("login-mfa1", parent.id, false);
		});
	});

	document.querySelectorAll("[data-mfa-change-login]").forEach(element => {
		element.addEventListener("click", (event) => {
			const target = event.target;
			const parent = target.closest(".login-tab");
			mfaNext("login-form", parent.id, false);
		});
	});

	document.querySelectorAll(".login-user").forEach(element => {
		element.addEventListener("click", () => {
			openLoginPanel();
		});
	});

	document.getElementById("LoginForm").addEventListener("submit", (event) => {
		event.preventDefault();
		const hasErrors = validateLoginFields();
		if (!hasErrors) {
			loginUser();
		}
	});

	document.getElementById("passwordLoginCommerce").addEventListener("input", (event) => {
		const target = event.target;
		if (target.closest(".form-group").classList.contains("has-error")) {
			if (target.value.length > 0) {
				document.getElementById("passwordLoginCommerce_error").setAttribute("class", "field-validation-error hidden");
				document.getElementById("passwordLoginCommerce_error").querySelector("span").innerText = "";
				target.closest(".form-group").setAttribute("class", "required-field form-group");
				handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
			}
		}
	});

	document.getElementById("userNameLoginCommerce").addEventListener("input", (event) => {
		const target = event.target;
		if (target.closest(".form-group").classList.contains("has-error")) {
			if (target.value.length > 0 && target.value.match(emailRegex)) {
				document.getElementById("userNameLoginCommerce_error").setAttribute("class", "field-validation-error hidden");
				document.getElementById("userNameLoginCommerce_error").querySelector("span").innerText = "";
				target.closest(".form-group").setAttribute("class", "required-field form-group");
				handleLoginPanelSizeChange(document.getElementById("login-form"), document.getElementById("login-tabs"));
			}
		}
	});
}
;
function InitializeMyAccountValidator() {
	addEventListener("load", (event) => {
		if (document.URL.indexOf("accountmanagement/profile") > 0) {
			var element = document.getElementById("txtFirstName");
			if (!element) {
				element = document.getElementById("txtOrganization");
				if (!element) {
					$.ajax({
						url: "/api/cxa/JmmSxaAccount/JmmLogoff",
						type: "POST",
						data: {},
						contentType: "application/json",
						dataType: "json",
						crossDomain: false,
						success: function (data) {
							window.location.href = '/';
						}, error: function () {
							window.location.href = '/';
						}
					});
				}
			}
		}
	});
}

InitializeMyAccountValidator();
;
var OrderHistoryViewModelController;

var OrderHistoryViewModel = function () {
	var self = this;
	self.ErrorMessage = ko.observable("");
	//self.Orders = ko.observableArray([]);
	self.Orders = ko.observable("");
	self.LoadingOrders = ko.observable(true);

	self.InitializeViewModel = function () {
		//console.log("init");
		self.LoadOrdersPageLoad();
	};

	self.LoadOrdersPageLoad = function () {
		var ServiceRequest = new Object();
		//ServiceRequest.CurrentItemId = $("#divMiniCart").attr("data-attr-cid");
		self.ShowLoadingOrders();
		var promise = GetOrders(ServiceRequest).done(function (data) {
			//console.log(data);
			if (data.Errors !== null & data.Errors !== "undefined") {
				self.ErrorMessage(data.Error);
				self.HideLoadingOrders();
			} else {
				//console.log("success");
				self.Orders(data.Result);
				self.HideLoadingOrders();
				//self.ConfigureCartUIModels();


				//

				//self.UpdateListrakSCA();
				//self.UpdateListrakRecommender();

				//initializeCarousels(document, true);
			}
		});
		return promise;
	};


	self.ShowLoadingOrders = function () {
		self.LoadingOrders(true);
	};
	self.HideLoadingOrders = function () {
		self.LoadingOrders(false);
	};

	self.SearchByProductType = function (productType, event) {

		var ServiceRequest = new Object();
		ServiceRequest.ProductType = productType;
		self.ShowLoadingOrders();
		var promise = GetOrders(ServiceRequest).done(function (data) {
			//console.log(data);
			if (data.Errors !== null & data.Errors !== "undefined") {
				self.ErrorMessage(data.Error);
				self.HideLoadingOrders();
			} else {
				//console.log("success");
				self.Orders(data.Result);
				self.HideLoadingOrders();
			}
		});

	};

	self.SearchByLast6Months = function (event) {

		var ServiceRequest = new Object();
		ServiceRequest.NumberOfMonths = 6;
		self.ShowLoadingOrders();
		var promise = GetOrders(ServiceRequest).done(function (data) {
			//console.log(data);
			if (data.Errors !== null & data.Errors !== "undefined") {
				self.ErrorMessage(data.Error);
				self.HideLoadingOrders();
			} else {
				//console.log("success");
				self.Orders(data.Result);
				self.HideLoadingOrders();
			}
		});

	};

	self.SearchByLast12Months = function (event) {

		var ServiceRequest = new Object();
		ServiceRequest.NumberOfMonths = 12;
		self.ShowLoadingOrders();
		var promise = GetOrders(ServiceRequest).done(function (data) {
			//console.log(data);
			if (data.Errors !== null & data.Errors !== "undefined") {
				self.ErrorMessage(data.Error);
				self.HideLoadingOrders();
			} else {
				//console.log("success");
				self.Orders(data.Result);
				self.HideLoadingOrders();
			}
		});

	};

	self.Search = function (event) {

		self.LoadOrdersPageLoad();

	};

};


function GetOrders(ServiceRequest) {


	//ServiceRequest.countryCode = countryCode;

	var url = "/api/accounts/orderhistoryapi/Search";
	var requestData = JSON.stringify(ServiceRequest);
	var ajaxRequest = $.ajax({
		type: 'POST',
		contentType: "application/json;charset=utf-8",
		url: url,
		data: requestData,
		success: function (data) {

		},
		error: function (x, y, z) {
			//alert(x + '\n' + y + '\n' + z);
		}
	});
	return ajaxRequest;
}


function InitializeOrderHistory() {

	var initializeViewModel = false;
	OrderHistoryViewModelController = new OrderHistoryViewModel();
	if ($("#divOrderHistoryContainer").length > 0) {
		ko.applyBindings(OrderHistoryViewModelController, document.getElementById("divOrderHistoryContainer"));
		ko.applyBindings(OrderHistoryViewModelController, document.getElementById("divOrderHistoryControls"));
		initializeViewModel = true;
	}

	if (initializeViewModel) {
		OrderHistoryViewModelController.InitializeViewModel();
	}


	//var ordersPromise = GetOrders();
	//ordersPromise.done(function (data) {

	//	console.log(data);

	//});
}




$(document).ready(function () {
	InitializeOrderHistory();
});

;



function InitializePasswordRecovery() {

	var btnDefaultAddress = document.querySelectorAll(".btnPasswordRecovery");
	Array.prototype.forEach.call(btnDefaultAddress, function (el, i) {

		el.onclick = function (evt) {
			evt.preventDefault();

			$.validator.unobtrusive.parse("PasswordRecoveryForm");

			
			var isValid = $("#PasswordRecoveryForm").valid();
			//console.log("isValid: " + isValid);
			if (isValid) {


				$(".btnPasswordRecovery .save").addClass("hidden");
				$(".btnPasswordRecovery .saving").removeClass("hidden");
				$(".btnPasswordRecovery").attr("disabled", "disabled");


				var txtEmailAddress = document.getElementById("txtPassword");
				var txtConfirmPassword = document.getElementById("txtConfirmPassword");
				var hfToken = document.getElementById("hfToken");

				var ServiceRequest = new Object();
				ServiceRequest.Password = txtEmailAddress.value;
				ServiceRequest.ConfirmPassword = txtConfirmPassword.value;
				ServiceRequest.Token = hfToken.value;


				var fetchUrl = "/api/accounts/securityapi/PasswordRecovery";
				//console.log(fetchUrl);
				var apiPromise = fetch(fetchUrl,
					{
						method: "POST",
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify(ServiceRequest)
					});

				apiPromise.then(rep => {
					//				console.log(rep);
					return rep.json();
				}).then(data => {
					//console.log(data);
					if (data.HasErrors) {
						var divError = document.getElementById("divErrorMessage");
						divError.innerHTML = data.Errors[0];
						divError.classList.remove("hidden");
						$.modalNoConflict.close();

						$(".btnPasswordRecovery .save").removeClass("hidden");
						$(".btnPasswordRecovery .saving").addClass("hidden");
						$(".btnPasswordRecovery").removeAttr("disabled");

					}
					if (data.IsSuccess) {

						var redirectUrl = data.Result.ReturnUrl;
						//console.log(redirectUrl);
						if (redirectUrl === null || redirectUrl === undefined) {
							redirectUrl = $("#divPasswordRecovery").attr("data-return-url");
						}
						if (redirectUrl !== null && redirectUrl !== undefined) {
							window.location.href = redirectUrl;
						}
						else {
							window.location.reload();
						}
					}

				});
			}

		};
	});
}


InitializePasswordRecovery();
;
var currentPanel;

const bluefinStyleOptions = {
	layout: "2",
	inputFontFamily: "11",
	labelFontFamily: "11",
	height: "155px"
}

const bluefinSpcStyleOptsAch = {
	layout: "2",
	inputFontFamily: "11",
	labelFontFamily: "11",
	height: "75px"
}

function openPaymentUpdate(event, updateType) {
	updateType = updateType.toLowerCase();
	currentPanel = updateType;

	var paymentData = JSON.parse(event.target.dataset.paymentInfo);
	var element = document.getElementById("utilityAccountPanel");

	handlePaymentPanelUpdates(element, updateType, paymentData);	
	openUtilityPanel(element);
}

function handlePaymentPanelUpdates(panel, updateType, paymentObj) {
	var paymentContainers = document.querySelectorAll(".payment-container");

	switch (updateType) {
		case "replace":
			document.getElementById("btnReplaceCard").dataset.paymentId = paymentObj.paymentId;
			document.getElementById("btnReplaceCard").dataset.scheduleId = paymentObj.scheduleId;
			document.getElementById("btnReplaceCard").dataset.email = paymentObj.email;
			document.getElementById("btnReplaceCard").dataset.firstName = paymentObj.firstName;
			document.getElementById("btnReplaceCard").dataset.lastName = paymentObj.lastName;
			document.getElementById("btnReplaceBankAccount").dataset.paymentId = paymentObj.paymentId;
			document.getElementById("btnReplaceBankAccount").dataset.scheduleId = paymentObj.scheduleId;
			document.getElementById("btnReplaceBankAccount").dataset.firstName = paymentObj.firstName;
			document.getElementById("btnReplaceBankAccount").dataset.lastName = paymentObj.lastName;
			document.getElementById("btnReplaceBankAccount").dataset.email = paymentObj.email;
			document.getElementById("updatePaymentHeader").style.display = "";
			document.getElementById("updatePartnershipHeader").style.display = "none";
			document.getElementById("currentPartnership").style.display = "none";
			updatePaymentContainer(paymentContainers, "replacePaymentContainer", true);
			break;
		case "edit":
			document.getElementById("btnEditCard").dataset.paymentId = paymentObj.paymentId;
			document.getElementById("btnEditCard").dataset.scheduleId = paymentObj.scheduleId;
			document.getElementById("updatePaymentHeader").style.display = "";
			document.getElementById("updatePartnershipHeader").style.display = "none";
			document.getElementById("currentPartnership").style.display = "none";
			updatePaymentContainer(paymentContainers, "editPaymentContainer", true);
			break;
		case "editpartnership":
			document.getElementById("btnEditPartnership").dataset.paymentId = paymentObj.paymentId;
			document.getElementById("btnEditPartnership").dataset.scheduleId = paymentObj.scheduleId;
			document.getElementById("newPartnershipAmountInput").value = paymentObj.amountValue;
			document.getElementById("newPartnershipAmountInput").dataset.currentAmount = paymentObj.amountValue;
			document.getElementById("currentDate").innerText = paymentObj.date;
			document.getElementById("currentAmount").innerText = paymentObj.amount;
			document.getElementById("updatePartnershipHeader").style.display = "";
			document.getElementById("currentPartnership").style.display = "";
			document.getElementById("updatePaymentHeader").style.display = "none";
			document.getElementById("updatePaymentHeader").style.display = "none";
			updatePaymentContainer(paymentContainers, "editPartnershipContainer", true);
			break;
	}

	document.getElementById("currentPaymentMethodIcon").setAttribute("class", getIconType(panel, paymentObj.paymentType));
	document.getElementById("currentPaymentMethodType").innerText = paymentObj.paymentProvider;
	document.getElementById("currentPaymentLastFour").innerText = paymentObj.lastFour;
	if (paymentObj.expiration) {
		document.querySelector("#currentPaymentExpiration strong").innerText = paymentObj.expiration;
		document.getElementById("currentPaymentExpiration").style.display = "block";
	} else {
		document.getElementById("currentPaymentExpiration").style.display = "none";
	}
}

function getIconType(panel, paymentType) {
	if (paymentType === "card") {
		return "fas fa-credit-card";
	}
	else if (paymentType === "bank") {
		return "fas fa-landmark";
	}
}

function updatePaymentContainer(elements, id, reset) {
	elements.forEach(element => {
		element.style.display = "none";
	});
	document.getElementById(id).style.display = "";
	if (reset) {
		document.getElementById("updateDisclaimer").style.display = "";
		document.getElementById("currentPaymentMethod").style.display = "";
	}
}

function handleErrors(message, container, clearErrors) {
	if (clearErrors) clearUtilityPanel(container);

	var listElement = document.createElement("li");
	listElement.innerText = message;
	container.append(listElement);
}

function handlePaymentProviderToggle(event) {
	var target = event.target || event.srcElement;
	var type = target.dataset.provider;
	if (!target.matches("active")) {
		if (type.toLowerCase() === "card") {
			document.getElementById("cardForm").style.display = "";
			document.getElementById("achForm").style.display = "none";
			document.getElementById("achToggle").classList.remove("active");
		} else if (type.toLowerCase() === "ach") {
			document.getElementById("achForm").style.display = "";
			document.getElementById("cardForm").style.display = "none";
			document.getElementById("cardToggle").classList.remove("active");
		}
		target.classList.add("active");
	}
}

function SavePartnership(ServiceRequest) {
	var url = "/api/accounts/scheduledpaymentapi/ChangePreferences";
	var requestData = JSON.stringify(ServiceRequest);
	var ajaxRequest = $.ajax({
		type: 'POST',
		contentType: "application/json;charset=utf-8",
		url: url,
		data: requestData,
		success: function (data) {

		},
		error: function (x, y, z) {
			//alert(x + '\n' + y + '\n' + z);
		}
	});
	return ajaxRequest;
}

function SavePartnershipExpDate(ServiceRequest) {
	var url = "/api/accounts/scheduledpaymentapi/ChangeExpDate";
	var requestData = JSON.stringify(ServiceRequest);
	var ajaxRequest = $.ajax({
		type: 'POST',
		contentType: "application/json;charset=utf-8",
		url: url,
		data: requestData,
		success: function (data) {
		},
		error: function (x, y, z) {
			//alert(x + '\n' + y + '\n' + z);
		}
	});
	return ajaxRequest;
}

function PerformDonationValiation(event) {
	const numericRegex = /^[0-9]+$/;
	const target = event.target || event.srcElement;
	const minValue = target.dataset.minimum;
	const newValue = target.value.replace(".", "");
	const errorSpan = document.getElementById("newPartnershipAmountError");
	const parent = target.closest(".required-field");
	if (!numericRegex.test(newValue) && newValue.length > 0) {
		target.value = "";
		errorSpan.style.display = "";
		errorSpan.innerText = "Amount must be whole number. No special characters allowed.";
	}
	else if (Number(newValue) < Number(minValue)) {
		if (Number(newValue) === 0) {
			target.value = "";
		}
		errorSpan.style.display = "";
		errorSpan.innerText = `Amount must be greater than $${target.dataset.minimum}`;
	}
	else {
		errorSpan.style.display = "none";
		if(parent.classList.contains("has-error")){
			parent.classList.remove("has-error");
		}
		target.value = newValue;
	}
}

function handleSelectError(element, hasError, id, error) {
	if (hasError) {
		element.classList.add("has-error");
		document.getElementById(id).innerText = error;
	} else {
		element.classList.contains("has-error") ? element.classList.remove("has-error") : null;
		document.getElementById(id).innerText = "";
	}
}

if (document.getElementById("newPartnershipDate")) {
	document.getElementById("newPartnershipDate").addEventListener("change", (event) => {
		if (event.target.value.length > 0) {
			var parent = event.target.parentNode;
			handleSelectError(parent, false, "newPartnershipDateError");
		}
	});
}

if (document.getElementById("partnershipExpYear")) {
	document.getElementById("partnershipExpYear").addEventListener("change", (event) => {
		if (event.target.value.length > 0) {
			var parent = event.target.parentNode;
			handleSelectError(parent, false, "expYearError");
		}
	});
}

if (document.getElementById("partnershipExpMonth")) {
	document.getElementById("partnershipExpMonth").addEventListener("change", (event) => {
		if (event.target.value.length > 0) {
			var parent = event.target.parentNode;
			handleSelectError(parent, false, "expMonthError");
		}
	});
}

var ScheduledPaymentViewModelController;

var ScheduledPaymentViewModel = function () {
	var self = this;

	self.ErrorMessage = ko.observable("");
	self.Orders = ko.observable("");
	self.LoadingOrders = ko.observable(false);
	self.bluefinEnabled = false;
	self.bluefinAccountId = '';
	self.bluefinErrorList = {};
	self.bluefinAuthorizeUrl = '';
	self.bluefinProcessUrl = '';
	self.paymentiFrame = null;
	self.achPaymentIframe = null;
	self.errorList = document.getElementById("errorList");
	self.paymentContainers = document.querySelectorAll(".payment-container");
	self.accountType = undefined;
	self.addToWallet = ko.observable(false);

	self.errorMessages = {
		account: "Account Type is required",
		expMonth: "Month is required",
		expYear: "Year is required",
		recurringDate: "Please choose a date to continue"
	};


	self.InitializeViewModel = function () {
		if (sessionStorage.getItem('bluefin.enabled') &&
			typeof sessionStorage.getItem('bluefin.enabled') !== 'undefined') {

			self.bluefinEnabled = sessionStorage.getItem('bluefin.enabled');
			self.bluefinAccountId = sessionStorage.getItem('bluefin.accountid');
			self.bluefinErrorList = sessionStorage.getItem('bluefin.errorlist');
			self.bluefinAuthorizeUrl = sessionStorage.getItem('bluefin.authorizeurl');
			self.bluefinProcessUrl = sessionStorage.getItem('bluefin.processurl');

			self.paymentiFrame = new PaymentiFrame({
				create: true,
				iframeId: "payment_iframe",
				settings: {
					account: self.bluefinAccountId,
					parentId: "iframe_container",
					lang: "en",
					cvv: "required",
					expy: "double_dropdown",
					showFrame: false,
					devServer: self.bluefinAuthorizeUrl,
					css: {
						class_row: "margin-bottom: 16px;",
						id_number_input: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width:100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 8px 12px; height: 40px;",
						id_cvv_input: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 8px 12px; height: 40px;",
						id_expy_dd_month: "-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 40px;width: 55%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 8px 12px;margin-right: 8px;",
						id_expy_dd_year: "-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 40px;width: 38%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 8px 12px;margin-right: 8px",
						class_label: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;font-weight: 500;font-family: sans-serif;margin-bottom:3px;",
						id_expy_row: "display:inline-block; width: 75%;",
						id_cvv_row: "display:inline-block; width: 25%;"
					},
					text: {
						number: {
							label: "Card #",
							placeholder: "Enter Card Number"
						},
						expy: {
							label: "Expiration",
						},
						cvv: {
							label: "Security #",
							placeholder: "000"
						},
					},
					...bluefinStyleOptions
				}
			});

			self.achPaymentIframe = new PaymentiFrame({
				create: true,
				iframeId: "ach_payment_iframe",
				settings: {
					account: self.bluefinAccountId,
					parentId: "ach_iframe_container",
					lang: "en",
					cvv: "required",
					showFrame: false,
					devServer: self.bluefinAuthorizeUrl,
					payment_method: "ach",
					css: {
						class_row: "display: inline-block; width: 49%;",
						id_account_row: "margin-right: 2%",
						class_input_box: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width:100%;font-size: 16px;padding: 8px 12px;background: #fff;border-radius: 5px;color:#333;border:solid 1px #c3c3c3;margin-bottom:16px; height: 40px;",
						class_label: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width:100%;font-size: 16px;font-weight: 500;font-family: sans-serif;margin-bottom:3px;"
					},
					text: {
						bank_account: {
							label: "Account #",
							placeholder: "Enter Account #"
						},
						routing_number: {
							label: "Routing #",
							placeholder: "Enter Routing #"
						}
					},
					...bluefinSpcStyleOptsAch
				}
			});

			var accountTypeDropdown = document.querySelector("#accountType");

			if (accountTypeDropdown) {
				accountTypeDropdown.addEventListener("change", (event) => {
					if (event.target.value.length > 0) {
						var parent = event.target.parentNode;
						self.accountType = event.target.value;
						handleSelectError(parent, false, "accountTypeError");
					}
				});
			}
		} else {
			$.ajax({
				url: "/api/cxa/JmmContent/GetBluefinSettings",
				type: "POST",
				data: {},
				async: false,
				contentType: "application/json",
				dataType: "json",
				crossDomain: false,
				success: function (data) {
					if (data) {
						self.bluefinEnabled = data.BluefinEnabled;
						self.bluefinAccountId = data.BluefinAccountId;
						self.bluefinErrorList = data.ErrorList;
						self.bluefinAuthorizeUrl = data.AuthorizeUrl;
						self.bluefinProcessUrl = data.ProcessUrl;

						sessionStorage.setItem('bluefin.enabled', self.bluefinEnabled);
						sessionStorage.setItem('bluefin.accountid', self.bluefinAccountId);
						sessionStorage.setItem('bluefin.errorlist', self.bluefinErrorList);
						sessionStorage.setItem('bluefin.authorizeurl', self.bluefinAuthorizeUrl);
						sessionStorage.setItem('bluefin.processurl', self.bluefinProcessUrl);

						self.paymentiFrame = new PaymentiFrame({
							create: true,
							iframeId: "payment_iframe",
							settings: {
								account: self.bluefinAccountId,
								parentId: "iframe_container",
								lang: "en",
								cvv: "required",
								expy: "double_dropdown",
								showFrame: false,
								devServer: self.bluefinAuthorizeUrl,
								css: {
									class_row: "margin-bottom: 16px;",
									id_number_input: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width:100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 16px;",
									id_cvv_input: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 16px;",
									id_expy_dd_month: "-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 53px;width: 55%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 16px;margin-right: 8px;",
									id_expy_dd_year: "-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 53px;width: 38%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 16px;margin-right: 8px",
									class_label: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;font-weight: 500;font-family: sans-serif;margin-bottom:3px;",
									id_expy_row: "display:inline-block; width: 75%;",
									id_cvv_row: "display:inline-block; width: 25%;"
								},
								text: {
									number: {
										label: "Card #",
										placeholder: "Enter Card Number"
									},
									expy: {
										label: "Expiration",
									},
									cvv: {
										label: "Security #",
										placeholder: "000"
									},
								},
								...bluefinStyleOptions
							}
						});

						self.achPaymentIframe = new PaymentiFrame({
							create: true,
							iframeId: "ach_payment_iframe",
							settings: {
								account: self.bluefinAccountId,
								parentId: "ach_iframe_container",
								lang: "en",
								cvv: "required",
								showFrame: false,
								devServer: self.bluefinAuthorizeUrl,
								payment_method: "ach",
								css: {
									class_row: "display: inline-block; width: 49%;",
									id_account_row: "margin-right: 2%",
									class_input_box: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width:100%;font-size: 16px;padding: 16px;background: #fff;border-radius: 5px;color:#333;border:solid 1px #c3c3c3;margin-bottom:16px;",
									class_label: "display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width:100%;font-size: 16px;font-weight: 500;font-family: sans-serif;margin-bottom:3px;"
								},
								text: {
									bank_account: {
										label: "Account #",
										placeholder: "Enter Account #"
									},
									routing_number: {
										label: "Routing #",
										placeholder: "Enter Routing #"
									}
								},
								...bluefinSpcStyleOptsAch
							}
						});

						var accountTypeDropdown = document.querySelector("#accountType");

						if (accountTypeDropdown) {
							accountTypeDropdown.addEventListener("change", (event) => {
								if (event.target.value.length > 0) {
									var parent = event.target.parentNode;
									self.accountType = event.target.value;
									handleSelectError(parent, false, "accountTypeError");
								}
							});
						}
					}
				}
			});
		};

	}

	self.SaveChanges = function (data, event) {
		var target = event.target || event.srcElement;
		var scheduleID = target.getAttribute("data-schedule-id");
		var recurringDate = document.getElementById("newPartnershipDate");
		var ServiceRequest = new Object();
		var recurringDateParent = recurringDate.closest(".required-field");
		const amountInput = document.getElementById("newPartnershipAmountInput");

		if (recurringDate.value.length === 0) {
			self.expMonth = event.target.value;
			handleSelectError(recurringDateParent, true, "newPartnershipDateError", self.errorMessages.recurringDate);
		}
		if (Number(amountInput.value) < Number(amountInput.dataset.minimum)) {
			var parent = amountInput.closest(".required-field");
			parent.classList.add("has-error");
			document.getElementById("newPartnershipAmountError").style.display = "";
			document.getElementById("newPartnershipAmountError").innerText = `Amount must be greater than $${amountInput.dataset.minimum}`;
		} else {
			ServiceRequest.ScheduledPaymentId = scheduleID;
			ServiceRequest.Amount = $("#newPartnershipAmountInput").val();
			ServiceRequest.DayOfMonth = $("#newPartnershipDate").val();
			handleSelectError(recurringDateParent, false, "newPartnershipDateError");

			if (ServiceRequest.Amount.length > 0 && ServiceRequest.Amount !== "0") {
				var updateButton = document.getElementById("btnEditPartnership");
				var buttonText = updateButton.innerText;

				updateButton.disabled = true;
				updateButton.innerText = "Processing...";

				var promise = SavePartnership(ServiceRequest).done(function (data) {
					if (data.HasErrors === false) {
						document.getElementById("paymentConfirmation").style.display = "none";
						document.getElementById("partnershipConfirmation").style.display = "block";

						updatePaymentContainer(self.paymentContainers, "updateConfirmation");
						document.querySelector("#utilityAccountPanel .utility-panel__close").style.display = "none";
					} else {
						handleErrors(`We were unable to save your changes due to a  system error.`, self.errorList, true);
						updatePaymentContainer(self.paymentContainers, "updateError");
						document.getElementById("btnEditPartnership").disabled = false;
						document.getElementById("btnEditPartnership").innerText = buttonText;
					}
				});
				return promise;
			} else {
				event.preventDefault();
				document.getElementById("newPartnershipAmountError").style.display = "";
				document.getElementById("newPartnershipAmountError").innerText = "Amount must be greater than $0";
			}
		}
	};

	self.SaveChangesExpDate = function (data, event) {
		var target = event.target || event.srcElement;
		var scheduleID = target.getAttribute("data-schedule-id");
		var ServiceRequest = new Object();
		var buttonText = document.getElementById("btnEditCard").innerText;
		var expMonth = document.getElementById("partnershipExpMonth");
		var expMonthParent = expMonth.closest(".required-field");
		var expYear = document.getElementById("partnershipExpYear");
		var expYearParent = expYear.closest(".required-field");

		if (expMonth.value.length > 0 && expYear.value.length > 0) {
			ServiceRequest.ScheduledPaymentId = scheduleID;
			ServiceRequest.ExpMonth = $("#partnershipExpMonth").val();
			ServiceRequest.ExpYear = $("#partnershipExpYear").val();

			handleSelectError(expMonthParent, false, "expMonthError");
			handleSelectError(expYearParent, false, "expYearError");

			document.getElementById("btnEditCard").disabled = true;
			document.getElementById("btnEditCard").innerText = "Processing...";

			var promise = SavePartnershipExpDate(ServiceRequest).done(function (data) {
				console.log(data);
				if (data.HasErrors === false) {
					document.querySelector("#utilityAccountPanel .utility-panel__close").style.display = "none";
					document.getElementById("paymentConfirmation").style.display = "block";
					document.getElementById("partnershipConfirmation").style.display = "none";
					updatePaymentContainer(self.paymentContainers, "updateConfirmation");
				} else {
					handleErrors(`We were unable to save your changes due to a  system error.`, self.errorList, true);
					updatePaymentContainer(self.paymentContainers, "updateError");
					document.getElementById("btnEditCard").disabled = false;
					document.getElementById("btnEditCard").innerText = buttonText;
				}
			});
			return promise;
		} else {
			if (expMonth.value.length === 0) {
				handleSelectError(expMonthParent, true, "expMonthError", self.errorMessages.expMonth);
			} else {
				handleSelectError(expMonthParent, false, "expMonthError");
			}

			if (expYear.value.length === 0) {
				self.expMonth = event.target.value;
				handleSelectError(expYearParent, true, "expYearError", self.errorMessages.expYear);
			} else {
				handleSelectError(expYearParent, false, "expYearError");
			}
		}
	};

	self.ClosePanel = function (id) {
		closeUtilityPanel(false, 'utilityAccountPanel');

		var panel = document.getElementById(id);
		var errorElements = panel.querySelectorAll(".form-error");
		errorElements.forEach(element => {
			element.innerText = "";
		});
	};

	self.ReplaceCard = function (data, event) {
		var target = event.target || event.srcElement;
		var scheduleID = target.getAttribute("data-schedule-id");
		var replaceButton = document.getElementById("btnReplaceCard");
		var buttonText = document.getElementById("btnReplaceCard").innerText;
		var email = target.getAttribute("data-email");
		var firstName = target.getAttribute("data-first-name");
		var lastName = target.getAttribute("data-last-name");

		replaceButton.disabled = true;
		replaceButton.innerText = "Processing...";

		self.paymentiFrame.encrypt({
			failure: function (err) {
				var message = err.message;
				if (self.bluefinErrorList[err.id] !== undefined) {
					message = self.bluefinErrorList[err.id];
				}
				handleErrors(`Payment Error: ${message}`, self.errorList);
				updatePaymentContainer(self.paymentContainers, "updateError");
				replaceButton.disabled = false;
				replaceButton.innerText = buttonText;
			},
			invalidInput: function (data) {
				for (var i = 0; i < data.invalidInputs.length; i++) {
					var code = data.invalidInputs[i].code;
					var message = data.invalidInputs[i].message;
					var field = data.invalidInputs[i].field;
					if (self.bluefinErrorList[code] !== undefined) {
						message = self.bluefinErrorList[code];
					}
					handleErrors(`${message} - please review the ${field} field.`, self.errorList, i === 0 ? true : false);
				}
				updatePaymentContainer(self.paymentContainers, "updateError");
				replaceButton.disabled = false;
				replaceButton.innerText = buttonText;
			},
			success: function (res) {
				var paymenttoken = res.eToken;
				var expiration = res.masked.expy;


				AjaxService.Post("/api/cxa/JmmCheckout/ProcessBluefinPayment",
					{
						Url: self.bluefinProcessUrl,
						TenderType: "CARD",
						TransactionType: "AUTHORIZATION",
						TransactionAmount: 0,
						PaymentToken: paymenttoken,
						CardExpiration: expiration,
						Email: email,
						FirstName: firstName,
						LastName: lastName
					},
					function (data, success) {
						if (data && success) {
							var url = "/api/accounts/scheduledpaymentapi/ReplaceScheduledPaymentMethod";
							var cardData = data.Transaction;
							var ServiceRequest = new Object();
							ServiceRequest.PaymentType = 'Payconnex';
							ServiceRequest.Token = cardData.TransactionId;
							ServiceRequest.ExpiryMonth = cardData.CardExpiration.substring(0, 2);
							ServiceRequest.ExpiryYear = cardData.CardExpiration.substring(2, 4);
							ServiceRequest.CardType = cardData.CardBrand;
							ServiceRequest.Last4 = cardData.Last4;
							ServiceRequest.IsPrimary = true;
							ServiceRequest.ScheduledPaymentId = scheduleID;

							var requestData = JSON.stringify(ServiceRequest);
							$.ajax({
								type: 'POST',
								contentType: "application/json;charset=utf-8",
								url: url,
								data: requestData,
								success: function (data) {
									if (data.HasErrors) {
										var message = data.Errors[0];
										handleErrors(`Payment Error: ${message}`, self.errorList);
										updatePaymentContainer(self.paymentContainers, "updateError");
										replaceButton.disabled = false;
										replaceButton.innerText = buttonText;
									}
									if (data.IsSuccess) {
										if (self.addToWallet() === true) {
											var url = "/api/accounts/walletpaymentapi/AddNewWalletPayment";
											var ServiceRequest = new Object();
											ServiceRequest.PaymentType = 'Payconnex';
											ServiceRequest.Token = cardData.TransactionId;
											ServiceRequest.ExpiryMonth = cardData.CardExpiration.substring(0, 2);
											ServiceRequest.ExpiryYear = cardData.CardExpiration.substring(2, 4);
											ServiceRequest.CardType = cardData.CardBrand;
											ServiceRequest.Last4 = cardData.Last4;


											var requestData = JSON.stringify(ServiceRequest);
											$.ajax({
												type: 'POST',
												contentType: "application/json;charset=utf-8",
												url: url,
												data: requestData,
												success: function (data) {
												},
												error: function (xhr, status, message) {
	
												},
												complete: function () {
												}
											});
										}
										document.getElementById("paymentConfirmation").style.display = "block";
										document.getElementById("partnershipConfirmation").style.display = "none";
										updatePaymentContainer(self.paymentContainers, "updateConfirmation");
										replaceButton.disabled = false;
										replaceButton.innerText = buttonText;
									}
								},
								error: function (xhr, status, message) {
									handleErrors(`Payment Error: ${message}`, self.errorList);
									updatePaymentContainer(self.paymentContainers, "updateError");
									replaceButton.disabled = false;
									replaceButton.innerText = buttonText;
								},
								complete: function () {
									document.querySelector("#utilityAccountPanel .utility-panel__close").style.display = "none";
									replaceButton.disabled = false;
									replaceButton.innerText = buttonText;
								}
							});
						} else {
							var msg = data.Errors[0];
							console.log(msg);
							var message = msg;
							if (self.bluefinErrorList[msg] !== undefined) {
								message = self.bluefinErrorList[msg];
							}
							handleErrors(`Payment Error: ${message}`, self.errorList);
							updatePaymentContainer(self.paymentContainers, "updateError");
							replaceButton.disabled = false;
							replaceButton.innerText = buttonText;
						}
					});

			}
		});
	}

	self.ReplaceBankAccount = function (data, event) {
		var target = event.target || event.srcElement;
		var scheduleID = target.getAttribute("data-schedule-id");
		var firstName = target.getAttribute("data-first-name");
		var lastName = target.getAttribute("data-last-name");
		var email = target.getAttribute("data-email");
		var replaceButton = document.getElementById("btnReplaceBankAccount");
		var buttonText = document.getElementById("btnReplaceBankAccount").innerText;
		var accountTypeParent = document.getElementById("accountTypeError").closest(".required-field");

		if (self.accountType !== undefined && self.accountType !== null) {
			handleSelectError(accountTypeParent, false, "accountTypeError");

			replaceButton.disabled = true;
			replaceButton.innerText = "Processing...";

			self.achPaymentIframe.encrypt({
				failure: function (err) {
					var message = err.message;
					if (self.bluefinErrorList[err.id] !== undefined) {
						message = self.bluefinErrorList[err.id];
					}
					handleErrors(`Payment Error: ${message}`, self.errorList);
					updatePaymentContainer(self.paymentContainers, "updateError");
					replaceButton.disabled = false;
					replaceButton.innerText = buttonText;
				},
				invalidInput: function (data) {
					for (var i = 0; i < data.invalidInputs.length; i++) {
						var code = data.invalidInputs[i].code;
						var message = data.invalidInputs[i].message;
						var field = data.invalidInputs[i].field;
						if (self.bluefinErrorList[code] !== undefined) {
							message = self.bluefinErrorList[code];
						}
						handleErrors(`${message} - please review the ${field} field.`, self.errorList, i === 0 ? true : false);
					}
					updatePaymentContainer(self.paymentContainers, "updateError");
					replaceButton.disabled = false;
					replaceButton.innerText = buttonText;
				},
				success: function (res) {
					var paymenttoken = res.eToken;
					var expiration = res.masked.expy;


					AjaxService.Post("/api/cxa/JmmCheckout/ProcessBluefinPayment",
						{
							Url: self.bluefinProcessUrl,
							TenderType: "ACH",
							TransactionType: "AUTHORIZATION",
							TransactionAmount: 0,
							PaymentToken: paymenttoken,
							CardExpiration: expiration,
							FirstName: firstName,
							LastName: lastName,
							AccountType: self.accountType,
							Email: email
						},
						function (data, success) {
							if (data && success) {
								var url = "/api/accounts/scheduledpaymentapi/ReplaceScheduledPaymentMethod";
								var bankData = data.Transaction;
								var ServiceRequest = new Object();
								ServiceRequest.PaymentType = 'ACH';
								ServiceRequest.Token = bankData.TransactionId;
								ServiceRequest.CardType = bankData.CardBrand;
								ServiceRequest.Last4 = bankData.Last4;
								ServiceRequest.IsPrimary = true;
								ServiceRequest.ScheduledPaymentId = scheduleID;
								ServiceRequest.AccountType = self.accountType;

								var requestData = JSON.stringify(ServiceRequest);
								$.ajax({
									type: 'POST',
									contentType: "application/json;charset=utf-8",
									url: url,
									data: requestData,
									success: function (data) {
										if (data.HasErrors) {
											var message = data.Errors[0];
											handleErrors(`Payment Error: ${message}`, self.errorList);
											updatePaymentContainer(self.paymentContainers, "updateError");
											replaceButton.disabled = false;
											replaceButton.innerText = buttonText;
										}
										if (data.IsSuccess) {
											document.getElementById("paymentConfirmation").style.display = "block";
											document.getElementById("partnershipConfirmation").style.display = "none";
											updatePaymentContainer(self.paymentContainers, "updateConfirmation");
											replaceButton.disabled = false;
											replaceButton.innerText = buttonText;
										}
									},
									error: function (xhr, status, message) {
										handleErrors(`Payment Error: ${message}`, self.errorList);
										updatePaymentContainer(self.paymentContainers, "updateError");
										replaceButton.disabled = false;
										replaceButton.innerText = buttonText;
									},
									complete: function () {
										document.querySelector("#utilityAccountPanel .utility-panel__close").style.display = "none";
										replaceButton.disabled = false;
										replaceButton.innerText = buttonText;
									}
								});
							} else {
								var msg = data.Errors[0];
								console.log(msg);
								var message = msg;
								if (self.bluefinErrorList[msg] !== undefined) {
									message = self.bluefinErrorList[msg];
								}
								handleErrors(`Payment Error: ${message}`, self.errorList);
								updatePaymentContainer(self.paymentContainers, "updateError");
								replaceButton.disabled = false;
								replaceButton.innerText = buttonText;
							}
						});
				}
			});
		} else {
			handleSelectError(accountTypeParent, true, "accountTypeError", self.errorMessages.account);
		}
	}

	self.RetryReplaceCard = function (data, event) {
		var target = event.target || event.srcElement;

		if (currentPanel === "replace") {
			updatePaymentContainer(self.paymentContainers, "replacePaymentContainer", true);
		}
		if (currentPanel === "edit") {
			updatePaymentContainer(self.paymentContainers, "editPaymentContainer", true);
		}
	}

	self.RefreshPage = function () {
		window.location.reload();
	}
}

function InitiialScheduledPaymentServices() {

	var initializeViewModel = false;
	ScheduledPaymentViewModelController = new ScheduledPaymentViewModel();
	if ($("#divScheduledPaymentContainer").length > 0) {
		ko.applyBindings(ScheduledPaymentViewModelController,
			document.getElementById("divScheduledPaymentContainer"));
		initializeViewModel = true;
	}

	if (initializeViewModel) {
		ScheduledPaymentViewModelController.InitializeViewModel();
	}

}

$(document).ready(function () {
	InitiialScheduledPaymentServices();
});
;
var currentPanel;

function openWalletPaymentUpdate(event, updateType) {
	updateType = updateType.toLowerCase();
	currentPanel = updateType;

	var paymentData = JSON.parse(event.target.dataset.paymentInfo);
	var element = document.getElementById("utilityAccountWalletPaymentPanel");

	handleWalletPaymentPanelUpdates(element, updateType, paymentData);
	openUtilityPanel(element);
}

function handleWalletPaymentPanelUpdates(panel, updateType, paymentObj) {
	var paymentContainers = document.querySelectorAll(".payment-container");

	switch (updateType) {
		case "add":
			document.getElementById("btnAddNewCard").dataset.email = paymentObj.email;
			document.getElementById("addPaymentHeader").style.display = "";
			document.getElementById("replacePaymentHeader").style.display = "none";
			document.getElementById("editPaymentHeader").style.display = "none";
			document.getElementById("deletePaymentHeader").style.display = "none";
			document.getElementById("setAsDefaultContainer_add") ? document.getElementById("setAsDefaultContainer_add").style.display = "" : null;
			updateWalletPaymentContainer(paymentContainers, "addNewPaymentContainer", true);
			updateCurrentPayment(paymentObj);
			break;
		case "replace":
			document.getElementById("btnAddNewCard").dataset.email = paymentObj.email;
			document.getElementById("btnAddNewCard").dataset.walletPaymentId = paymentObj.walletPaymentId;
			document.getElementById("addPaymentHeader").style.display = "none";
			document.getElementById("replacePaymentHeader").style.display = "";
			document.getElementById("editPaymentHeader").style.display = "none";
			document.getElementById("deletePaymentHeader").style.display = "none";
			document.getElementById("setAsDefaultContainer_add").style.display = "none";
			updateWalletPaymentContainer(paymentContainers, "addNewPaymentContainer", true);
			updateCurrentPayment(paymentObj);
			document.getElementById("currentPayment").style.display = "";
			break;
		case "edit":
			document.querySelectorAll(".required-field").forEach((element) => {
				element.classList.contains("has-error") ? element.classList.remove("has-error") : null;
			});
			document.getElementById("btnEditCard").dataset.walletPaymentId = paymentObj.walletId;
			document.getElementById("btnEditCard").dataset.paymentId = paymentObj.paymentId;
			document.getElementById("btnEditCard").dataset.isDefault = paymentObj.isDefault.toLowerCase();
			document.getElementById("addPaymentHeader").style.display = "none";
			document.getElementById("replacePaymentHeader").style.display = "none";
			document.getElementById("editPaymentHeader").style.display = "";
			document.getElementById("deletePaymentHeader").style.display = "none";
			if (paymentObj.status !== "expired") {
				document.getElementById("savedExpMonth").value = paymentObj.expiryMonth;
				document.getElementById("savedExpYear").value = paymentObj.expiryYear;
			}
			if (paymentObj.status === "expired") {
				document.getElementById("savedExpMonth").selectedIndex = 0;
				document.getElementById("savedExpYear").selectedIndex = 0;
			}
			(paymentObj.isDefault.toLowerCase() === "false" && paymentObj.status !== "expired") ? document.getElementById("setAsDefaultContainer_edit").style.display = "" : document.getElementById("setAsDefaultContainer_edit").style.display = "none";
			updateWalletPaymentContainer(paymentContainers, "editPaymentContainer", true);
			updateCurrentPayment(paymentObj);
			document.getElementById("currentPayment").style.display = "";
			break;
		case "delete":
			document.getElementById("btnDeleteCard").dataset.walletPaymentId = paymentObj.walletPaymentId;
			document.getElementById("addPaymentHeader").style.display = "none";
			document.getElementById("replacePaymentHeader").style.display = "none";
			document.getElementById("editPaymentHeader").style.display = "none";
			document.getElementById("deletePaymentHeader").style.display = "";
			updateWalletPaymentContainer(paymentContainers, "deletePaymentContainer", true);
			updateCurrentPayment(paymentObj);
			document.getElementById("currentPayment").style.display = "";
			break;
		case "loading":
			document.getElementById("addPaymentHeader").style.display = "none";
			document.getElementById("replacePaymentHeader").style.display = "none";
			document.getElementById("editPaymentHeader").style.display = "none";
			document.getElementById("deletePaymentHeader").style.display = "none";
			updateWalletPaymentContainer(paymentContainers, "loadingPaymentContainer", true);
			break;

	}
}

function handleWalletPaymentErrors(message, container, clearErrors) {
	if (clearErrors) clearUtilityPanel(container);

	var listElement = document.createElement("li");
	listElement.innerText = message;
	container.append(listElement);
}

function updateWalletPaymentContainer(elements, id, reset) {
	elements.forEach(element => {
		element.style.display = "none";
	});
	document.getElementById(id).style.display = "";
}

function updateCurrentPayment(obj) {
	document.getElementById("currentPaymentMethodIcon").src = obj.icon;
	document.getElementById("currentPaymentMethodType").innerText = obj.paymentProvider;
	document.getElementById("currentPaymentLastFour").innerText = obj.lastFour;
	document.getElementById("currentPaymentExpiration").innerText = obj.expiration;

	if (obj.status === "expired") {
		document.querySelector("#currentPaymentExpiration_container span").innerText = "expired ";
		document.getElementById("currentPaymentExpiration_container").setAttribute("class", "color-danger font-weight-2");
	}
	else if (obj.status === "expiring_soon") {
		document.querySelector("#currentPaymentExpiration_container span").innerText = "expires ";
		document.getElementById("currentPaymentExpiration_container").setAttribute("class", "color-caution font-weight-2");
	} else {
		document.querySelector("#currentPaymentExpiration_container span").innerText = "expires ";
		document.getElementById("currentPaymentExpiration_container").setAttribute("class", "");
	}
}

function handleSelectError(element, hasError, id, error) {
	if (hasError) {
		element.classList.add("has-error");
		document.getElementById(id).innerText = error;
	} else {
		element.classList.contains("has-error") ? element.classList.remove("has-error") : null;
		document.getElementById(id).innerText = "";
	}
}

if (document.getElementById("savedExpYear")) {
	document.getElementById("savedExpYear").addEventListener("change", (event) => {
		if (event.target.value.length > 0) {
			var parent = event.target.parentNode;
			handleSelectError(parent, false, "expYearError");
		}
	});
}

if (document.getElementById("savedExpMonth")) {
	document.getElementById("savedExpMonth").addEventListener("change", (event) => {
		if (event.target.value.length > 0) {
			var parent = event.target.parentNode;
			handleSelectError(parent, false, "expMonthError");
		}
	});
}

function SaveWalletPaymentExpDate(ServiceRequest) {
	const url = "/api/accounts/walletpaymentapi/ChangeWalletPaymentExpDate";
	const requestData = JSON.stringify(ServiceRequest);
	const ajaxRequest = $.ajax({
		type: 'POST',
		contentType: "application/json;charset=utf-8",
		url: url,
		data: requestData,
		success: function(data) {
		},
		error: function(x, y, z) {
		}
	});
	return ajaxRequest;
}

var WalletPaymentViewModelController;

var WalletPaymentViewModel = function () {
	var self = this;

	self.bluefinEnabled = false;
	self.bluefinAccountId = '';
	self.bluefinErrorList = {};
	self.bluefinAuthorizeUrl = '';
	self.bluefinProcessUrl = '';
	self.paymentiFrame = null;
	self.errorList = document.getElementById("errorList");
	self.paymentContainers = document.querySelectorAll(".payment-container");

	const bluefinStyleOptions = {
		layout: "2",
		inputFontFamily: "11",
		inputStyle: "2",
		labelFontSize: "13",
		labelFontColor: "#333333",
		labelFontFamily: "11",
		width: "300px",
		height: "185px",
	}

	self.InitializeViewModel = function () {
		if (sessionStorage.getItem('bluefin.enabled') &&
			typeof sessionStorage.getItem('bluefin.enabled') !== 'undefined') {

			self.bluefinEnabled = sessionStorage.getItem('bluefin.enabled');
			self.bluefinAccountId = sessionStorage.getItem('bluefin.accountid');
			self.bluefinErrorList = sessionStorage.getItem('bluefin.errorlist');
			self.bluefinAuthorizeUrl = sessionStorage.getItem('bluefin.authorizeurl');
			self.bluefinProcessUrl = sessionStorage.getItem('bluefin.processurl');

			self.paymentiFrame = new PaymentiFrame({
				create: true,
				iframeId: "payment_iframe",
				settings: {
					account: self.bluefinAccountId,
					parentId: "iframe_container",
					lang: "en",
					cvv: "required",
					expy: "double_dropdown",
					showFrame: false,
					devServer: self.bluefinAuthorizeUrl,
					css: {
						class_row: "margin-bottom: 16px;",
						id_number_input:
							"display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;min-width: 100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 8px 12px; height: 52px;",
						id_cvv_input:
							"display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 8px 12px; height: 52px;",
						id_expy_dd_month:
							"-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 52px;width: 55%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 8px 12px;margin-right: 8px;",
						id_expy_dd_year:
							"-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 52px;width: 38%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 8px 12px;margin-right: 8px",
						class_label:
							"display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;font-weight: 500;font-family: sans-serif;margin-bottom:3px;",
						id_expy_row: "display:inline-block; width: 75%;",
						id_cvv_row: "display:inline-block; width: 25%;"
					},
					text: {
						number: {
							label: "Card #",
							placeholder: "Enter Card Number"
						},
						expy: {
							label: "Expiration",
						},
						cvv: {
							label: "Security #",
							placeholder: "000"
						},
					},
					...bluefinStyleOptions
				}
			});

		} else {
			$.ajax({
				url: "/api/cxa/JmmContent/GetBluefinSettings",
				type: "POST",
				data: {},
				async: false,
				contentType: "application/json",
				dataType: "json",
				crossDomain: false,
				success: function (data) {
					if (data) {
						self.bluefinEnabled = data.BluefinEnabled;
						self.bluefinAccountId = data.BluefinAccountId;
						self.bluefinErrorList = data.ErrorList;
						self.bluefinAuthorizeUrl = data.AuthorizeUrl;
						self.bluefinProcessUrl = data.ProcessUrl;

						sessionStorage.setItem('bluefin.enabled', self.bluefinEnabled);
						sessionStorage.setItem('bluefin.accountid', self.bluefinAccountId);
						sessionStorage.setItem('bluefin.errorlist', self.bluefinErrorList);
						sessionStorage.setItem('bluefin.authorizeurl', self.bluefinAuthorizeUrl);
						sessionStorage.setItem('bluefin.processurl', self.bluefinProcessUrl);

						self.paymentiFrame = new PaymentiFrame({
							create: true,
							iframeId: "payment_iframe",
							settings: {
								account: self.bluefinAccountId,
								parentId: "iframe_container",
								lang: "en",
								cvv: "required",
								expy: "double_dropdown",
								showFrame: false,
								devServer: self.bluefinAuthorizeUrl,
								css: {
									class_row: "margin-bottom: 16px;",
									id_number_input:
										"display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;min-width: 100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 8px 12px; height: 52px;",
									id_cvv_input:
										"display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;color: #333;background: #fff;border-radius: 5px;border:solid 1px #c3c3c3;padding: 8px 12px; height: 52px;",
									id_expy_dd_month:
										"-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 52px;width: 55%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 8px 12px;margin-right: 8px;",
									id_expy_dd_year:
										"-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;height: 52px;width: 38%;font-size: 16px;color: #333;border-radius: 5px;border: 1px solid #c3c3c3;padding: 8px 12px;margin-right: 8px",
									class_label:
										"display: block;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;width: 100%;font-size: 16px;font-weight: 500;font-family: sans-serif;margin-bottom:3px;",
									id_expy_row: "display:inline-block; width: 75%;",
									id_cvv_row: "display:inline-block; width: 25%;"
								},
								text: {
									number: {
										label: "Card #",
										placeholder: "Enter Card Number"
									},
									expy: {
										label: "Expiration",
									},
									cvv: {
										label: "Security #",
										placeholder: "000"
									},
								},
								...bluefinStyleOptions
							}
						});
					}
				}
			});
		};

	};

	self.AddNewCard = function (data, event) {
		var target = event.target || event.srcElement;
		var addNewCardButton = document.getElementById("btnAddNewCard");
		var buttonText = document.getElementById("btnAddNewCard").innerText;
		var email = target.getAttribute("data-email");
		const setAsDefault = document.getElementById("setAsDefault_add");

		addNewCardButton.disabled = true;
		addNewCardButton.innerText = "Processing...";

		self.paymentiFrame.encrypt({
			failure: function (err) {
				var message = err.message;
				if (self.bluefinErrorList[err.id] !== undefined) {
					message = self.bluefinErrorList[err.id];
				}
				handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
				updateWalletPaymentContainer(self.paymentContainers, "updateError");
				addNewCardButton.disabled = false;
				addNewCardButton.innerText = buttonText;
			},
			invalidInput: function (data) {
				for (var i = 0; i < data.invalidInputs.length; i++) {
					var code = data.invalidInputs[i].code;
					var message = data.invalidInputs[i].message;
					var field = data.invalidInputs[i].field;
					if (self.bluefinErrorList[code] !== undefined) {
						message = self.bluefinErrorList[code];
					}
					handleWalletPaymentErrors(`${message} - please review the ${field} field.`, self.errorList, i === 0 ? true : false);
				}
				updateWalletPaymentContainer(self.paymentContainers, "updateError");
				addNewCardButton.disabled = false;
				addNewCardButton.innerText = buttonText;
			},
			success: function (res) {
				var paymentToken = res.eToken;
				var expiration = res.masked.expy;


				AjaxService.Post("/api/cxa/JmmCheckout/ProcessBluefinPayment",
					{
						Url: self.bluefinProcessUrl,
						TenderType: "CARD",
						TransactionType: "AUTHORIZATION",
						TransactionAmount: 0,
						PaymentToken: paymentToken,
						CardExpiration: expiration,
						Email: email
					},
					function (data, success) {
						if (data && success) {
							var isReplace = false;
							var walletPaymentId = target.getAttribute("data-wallet-payment-id");
							if (walletPaymentId !== undefined &&
								walletPaymentId !== null &&
								walletPaymentId.length > 0) {
								isReplace = true;
							}

							var url = "/api/accounts/walletpaymentapi/AddNewWalletPayment";
							var cardData = data.Transaction;
							var ServiceRequest = new Object();
							ServiceRequest.PaymentType = 'Payconnex';
							ServiceRequest.Token = cardData.TransactionId;
							ServiceRequest.ExpiryMonth = cardData.CardExpiration.substring(0, 2);
							ServiceRequest.ExpiryYear = cardData.CardExpiration.substring(2, 4);
							ServiceRequest.CardType = cardData.CardBrand;
							ServiceRequest.Last4 = cardData.Last4;
							ServiceRequest.IsPrimary = true;
							if (isReplace) {
								ServiceRequest.IsDefault = true;
							} else {
								ServiceRequest.IsDefault = setAsDefault ? setAsDefault.checked : true;
							}

							var requestData = JSON.stringify(ServiceRequest);
							$.ajax({
								type: 'POST',
								contentType: "application/json;charset=utf-8",
								url: url,
								data: requestData,
								success: function (data) {
									if (data.HasErrors) {
										var message = data.Errors[0];
										handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
										updateWalletPaymentContainer(self.paymentContainers, "updateError");
										addNewCardButton.disabled = false;
										addNewCardButton.innerText = buttonText;
									}
									if (data.IsSuccess) {
										document.getElementById("paymentConfirmation").style.display = "block";
										if (isReplace === true) {

											var url = "/api/accounts/walletpaymentapi/DeleteWalletPayment";
											var ServiceRequest = new Object();
											ServiceRequest.WalletPaymentId = walletPaymentId;

											var requestData = JSON.stringify(ServiceRequest);

											$.ajax({
												type: 'POST',
												contentType: "application/json;charset=utf-8",
												url: url,
												data: requestData,
												success: function (data) {

												},
												error: function (xhr, status, message) {

												},
												complete: function () {

												}
											});
										}
										updateWalletPaymentContainer(self.paymentContainers, "updateConfirmation");
										document.getElementById("addPaymentHeader").style.display = "none";
										document.getElementById("addConfirmation").style.display = "block";
										addNewCardButton.disabled = false;
										addNewCardButton.innerText = buttonText;
									}
								},
								error: function (xhr, status, message) {
									handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
									updateWalletPaymentContainer(self.paymentContainers, "updateError");
									addNewCardButton.disabled = false;
									addNewCardButton.innerText = buttonText;
								},
								complete: function () {
									document.querySelector("#utilityAccountWalletPaymentPanel .utility-panel__close").style.display = "none";
									addNewCardButton.disabled = false;
									addNewCardButton.innerText = buttonText;
								}
							});
						} else {
							var msg = data.Errors[0];
							console.log(msg);
							var message = msg;
							if (self.bluefinErrorList[msg] !== undefined) {
								message = self.bluefinErrorList[msg];
							}
							handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
							updateWalletPaymentContainer(self.paymentContainers, "updateError");
							addNewCardButton.disabled = false;
							addNewCardButton.innerText = buttonText;
						}
					});

			}
		});
	}

	self.DeleteCard = function(data, event) {
		var target = event.target || event.srcElement;
		var deleteCardButton = document.getElementById("btnDeleteCard");
		var buttonText = document.getElementById("btnDeleteCard").innerText;
		var walletPaymentId = target.getAttribute("data-wallet-payment-id");

		deleteCardButton.disabled = true;
		deleteCardButton.innerText = "Processing...";

		var url = "/api/accounts/walletpaymentapi/DeleteWalletPayment";
		var ServiceRequest = new Object();
		ServiceRequest.WalletPaymentId = walletPaymentId;

		var requestData = JSON.stringify(ServiceRequest);
		$.ajax({
			type: 'POST',
			contentType: "application/json;charset=utf-8",
			url: url,
			data: requestData,
			success: function (data) {
				if (data.HasErrors) {
					var message = data.Errors[0];
					handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
					updateWalletPaymentContainer(self.paymentContainers, "updateError");
					deleteCardButton.disabled = false;
					deleteCardButton.innerText = buttonText;
				}
				if (data.IsSuccess) {
					document.getElementById("paymentConfirmation").style.display = "block";
					document.getElementById("deleteConfirmation").style.display = "block";
					updateWalletPaymentContainer(self.paymentContainers, "updateConfirmation");
					deleteCardButton.disabled = false;
					deleteCardButton.innerText = buttonText;
				}
			},
			error: function (xhr, status, message) {
				handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
				updateWalletPaymentContainer(self.paymentContainers, "updateError");
				deleteCardButton.disabled = false;
				deleteCardButton.innerText = buttonText;
			},
			complete: function () {
				document.querySelector("#utilityAccountWalletPaymentPanel .utility-panel__close").style.display = "none";
				deleteCardButton.disabled = false;
				deleteCardButton.innerText = buttonText;
			}
		});
	}

	self.UpdateDefaultCard = function (data, event) {
		var element = document.getElementById("utilityAccountWalletPaymentPanel");
		handleWalletPaymentPanelUpdates(element, "loading");
		openUtilityPanel(element);
		var target = event.target || event.srcElement;
		var walletPaymentId = target.getAttribute("data-wallet-payment-id");

		var url = "/api/accounts/walletpaymentapi/UpdateWalletPayment";
		var ServiceRequest = new Object();
		ServiceRequest.WalletPaymentId = walletPaymentId;

		var requestData = JSON.stringify(ServiceRequest);
		$.ajax({
			type: 'POST',
			contentType: "application/json;charset=utf-8",
			url: url,
			data: requestData,
			success: function (data) {
				if (data.HasErrors) {
					var message = data.Errors[0];
					handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
					updateWalletPaymentContainer(self.paymentContainers, "updateError");
				}
				if (data.IsSuccess) {
					self.RefreshPage();
				}
			},
			error: function (xhr, status, message) {
				handleWalletPaymentErrors(`Payment Error: ${message}`, self.errorList);
				updateWalletPaymentContainer(self.paymentContainers, "updateError");
			}
		});
	}


	self.RetryAddNewCard = function (data, event) {
		if (currentPanel === "add") {
			updateWalletPaymentContainer(self.paymentContainers, "addNewPaymentContainer", true);
		}
		if (currentPanel === "replace") {
			updateWalletPaymentContainer(self.paymentContainers, "addNewPaymentContainer", true);
			document.getElementById("currentPayment").style.display = '';
		}
		if (currentPanel === "edit") {
			updateWalletPaymentContainer(self.paymentContainers, "editPaymentContainer", true);
		}
	}

	self.ClosePanel = function (id) {
		closeUtilityPanel(false, 'utilityAccountWalletPaymentPanel');

		var panel = document.getElementById(id);
		var errorElements = panel.querySelectorAll(".form-error");
		errorElements.forEach(element => {
			element.innerText = "";
		});
	};

	self.RefreshPage = function() {
		window.location.reload();
	};


	self.SaveChangesExpDate = function (data, event) {
		const target = event.target || event.srcElement;
		const walletPaymentId = target.getAttribute("data-wallet-payment-id");
		const isDefault = target.getAttribute("data-is-default");
		const paymentId = target.getAttribute("data-payment-id");
		const ServiceRequest = new Object();
		const buttonText = document.getElementById("btnEditCard").innerText;
		const expMonth = document.getElementById("savedExpMonth");
		const expMonthParent = expMonth.closest(".required-field");
		const expYear = document.getElementById("savedExpYear");
		const expYearParent = expYear.closest(".required-field");

		if (expMonth.value.length > 0 && expYear.value.length > 0) {
			const exp = new Date(parseInt(expYear.value), parseInt(expMonth.value));
			const today = new Date();

			if(today > exp){
				handleSelectError(expMonthParent, true, "expMonthError", "Expiration date cannot be in the past or current month.");
				handleSelectError(expYearParent, true, "expYearError", "");
			} else {
				ServiceRequest.WalletPaymentId = walletPaymentId;
				ServiceRequest.PaymentMethodPaymentId = paymentId;
				ServiceRequest.ExpMonth = $("#savedExpMonth").val();
				ServiceRequest.ExpYear = $("#savedExpYear").val();
				ServiceRequest.IsDefault = (isDefault === "false") ? document.getElementById("setAsDefault_edit").checked : true;

				handleSelectError(expMonthParent, false, "expMonthError");
				handleSelectError(expYearParent, false, "expYearError");

				document.getElementById("btnEditCard").disabled = true;
				document.getElementById("btnEditCard").innerText = "Processing...";

				const promise = SaveWalletPaymentExpDate(ServiceRequest).done(function (data) {
					console.log(data);
					if (data.HasErrors === false) {
						document.querySelector("#utilityAccountWalletPaymentPanel .utility-panel__close").style.display = "none";
						document.getElementById("paymentConfirmation").style.display = "block";
						document.getElementById("editConfirmation").style.display = "block";
						document.getElementById("editPaymentHeader").style.display = "none";
						updateWalletPaymentContainer(self.paymentContainers, "updateConfirmation");
					} else {
						handleWalletPaymentErrors(`We were unable to save your changes due to a system error.`, self.errorList, true);
						updateWalletPaymentContainer(self.paymentContainers, "updateError");
						document.getElementById("btnEditCard").disabled = false;
						document.getElementById("btnEditCard").innerText = buttonText;
					}
				});
				return promise;
			}
		} else {
			if (expMonth.value.length === 0) {
				handleSelectError(expMonthParent, true, "expMonthError", "Exp Month is required");
			} else {
				handleSelectError(expMonthParent, false, "expMonthError");
			}

			if (expYear.value.length === 0) {
				self.expMonth = event.target.value;
				handleSelectError(expYearParent, true, "expYearError", "Exp Year is required");
			} else {
				handleSelectError(expYearParent, false, "expYearError");
			}
		}
	};
};

function InitialWalletPaymentServices() {

	var initializeViewModel = false;
	WalletPaymentViewModelController = new WalletPaymentViewModel();
	if ($("#divWalletPaymentContainer").length > 0) {
		ko.applyBindings(WalletPaymentViewModelController,
			document.getElementById("divWalletPaymentContainer"));
		initializeViewModel = true;
	}

	if (initializeViewModel) {
		WalletPaymentViewModelController.InitializeViewModel();
	}
}

$(document).ready(function () {
	InitialWalletPaymentServices();
});
;
