function log_to_backend(msg) {
	var ga = new GlideAjax("global.LogService");
	ga.addParam('message', msg);
	ga.addParam('sysparm_name', 'writeLog');
	ga.getXML(function(resp) {
		// no handle for the response
	});
}

var hasRun = false;
jQuery(document).ready(function () {
	if (!hasRun) {
		hasRun = true;
	
		var a = document.createElement('script');
		a.src = "/sys_attachment.do?sysparm_referring_url=tear_off&view=true&sys_id=87f25039db7204d0529d368d7c9619ca";
		a.type = "module";
		document.body.appendChild(a);

		setTimeout(function () {

			// check for an active okta session for this user
			if (typeof OktaAuth != 'undefined') { // if we have a valid client
				var authClient = new OktaAuth({
					url: 'https://deccs.auth.pmddtc.state.gov'
				});

				authClient.session.get().then(function (session) {
					if (session && session.status && session.status != 'INACTIVE') {
						// we have an active okta session
						console.log("valid okta session detected.");

						// check for an active servicenow session
						// portal has window.NOW.user_id in console its window.NOW.user.userID
						
						var userID = '';
						if (window && window.NOW && window.NOW.user_id && window.NOW.user_id != '' && window.NOW.user_id != 'guest') {
							userID = window.NOW.user_id; // portal
						}
						
						if (window && window.NOW && window.NOW.user && window.NOW.user.userID && window.NOW.user.userID != '' && window.NOW.user.userID != 'guest') {
							userID = window.NOW.user.userID;
						}
						
						if (userID != '') { // portal

							// active servicenow session, refresh the okta session
							console.log('detected an active servicenow session, sending a refresh to okta every 5 minutes.');
							try {
								authClient.session.refresh().then(function (session) {
									console.log('-- okta session refresh sent');
									var mivMM = setInterval(function() {
										try {
											authClient.session.refresh().then(function (ses) {
												var nd = new Date();
												console.log('--' + nd + ' okta session refresh sent');
											});
										} catch (ex) {
											log_to_backend("Okta Client Error: " + JSON.stringify(ex));
											clearInterval(mivMM);
										}
									}, (5 * 60 * 1000)); // refresh every 5 minutes
								});
							} catch (e) {
								log_to_backend("Okta Client Error: " + JSON.stringify(e));
							}
							

						}

					}
				}).catch(function (err) {
					console.log('no active okta session detected: ', err);
				});
			}

		}, 1000); // wait for the lib to load up
	}
});