/* Minification failed. Returning unminified contents.
(99,23-24): run-time error JS1014: Invalid character: `
(100,7-8): run-time error JS1195: Expected expression: <
(100,7-8): run-time error JS1195: Expected expression: <
(101,28-29): run-time error JS1195: Expected expression: <
(105,9-10): run-time error JS1195: Expected expression: <
(108,6-7): run-time error JS1014: Invalid character: `
(111,6-7): run-time error JS1195: Expected expression: )
(112,3-4): run-time error JS1197: Too many errors. The file might not be a JavaScript file: }
 */
$(function () {
	buildRssWidget("smartbrief-rss", "9761eec7");
});

function buildRssWidget(widgetClassName, campaign) {
	const widget = $("." + widgetClassName);
	if (widget.length === 0) {
		console.log("Failed to get widget by class: " + widgetClassName);
		return;
	}
	const container = widget.find(".rss-articles-container");
	if (container.length === 0) {
		console.log("Div with 'rss-articles-container' class is missing");
		return;
	}

	// bind input
	const subscribeButton = widget.find("button.rss-subscribe-button");
	const subscribeInput = widget.find("input.rss-subscribe-input");
	if (subscribeInput.length > 0) {
		subscribeInput.on("focusin", function () {
			widget.find(".rss-subscribe-message").html("");
		});
		subscribeInput.on("focusout", function () {
			widget.find(".rss-subscribe-message").html("");
		});
		subscribeInput.keypress(function (e) {
			let key = e.which;
			if (key == 13) {
				subscribeButton.click();
				return false;
			}
		});
	}

	// bind subscribe button
	if (subscribeButton.length > 0) {
		subscribeButton.on("click", function () {
			const email = widget.find(".rss-subscribe-input").val();
			const message = widget.find(".rss-subscribe-message");
			if (email === null || email === "") {
				message.html("Email is required");
				return;
			}
			else if (email.indexOf("@") === -1) {
				message.html("Email is invalid");
				return;
			}

			$.ajax("/restAPI/NemaServices/smartbrief/subscribe?format=json&email=" + email + "&campaign=" + campaign, {
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				async: false,
				cache: false,
				success: function (data) {
					if (data !== null && data.Message !== null) {
						message.html(data.Message);
					}
					else {
						message.html("Unknown Error");
					}
				},
				error: function (xhr, status, thrownError) {
					let errorMessage = "";

					if (errorMessage === null || errorMessage === "") {
						if (thrownError !== null && thrownError !== "") {
							errorMessage = thrownError;
						}
						else {
							errorMessage = "Undefined Error!";
						}
					}
					message.html(thrownError);
				}
			})
		});
	}

	// fetch rss
	$.ajax("/restAPI/NemaServices/smartbrief/rss", {
		accepts: {
			xml: "application/rss+xml"
		},
		dataType: "xml",
		async: true,
		cache: true,
		success: function (data) {
			$(data)
				.find("item")
				.each(function () {
					const article = $(this);
					const date = new Date(article.find("pubDate").text());
					const displayDate = isValidDate(date)
						? date.toLocaleDateString("en-US", { month: 'short' }) + " " +
						date.toLocaleDateString("en-US", { day: 'numeric' }) + ", " +
						date.toLocaleDateString("en-US", { year: 'numeric' })
						: article.find("pubDate").text();
					const template = `
						<article>
							<time>${displayDate}</time>
							<h3>
								<a href="${article.find("link").text()}" target="_blank" rel="noopener">
									${article.find("title").text()}
								</a>
							</h3>
						</article>
					`;

					container.append(template);
				});
		},
		error: function () {
			console.log("Error!");
		}
	});
}

function isValidDate(d) {
	return d instanceof Date && !isNaN(d);
}
;
